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
|
update docs about releasing providersk
|
dd410fd3c9de14e94034dcb4ccae52bbf5216199
|
<ide><path>dev/README_RELEASE_PROVIDER_PACKAGES.md
<ide> - [Publish release](#publish-release)
<ide> - [Summarize the voting for the Apache Airflow release](#summarize-the-voting-for-the-apache-airflow-release)
<ide> - [Publish release to SVN](#publish-release-to-svn)
<del> - [Publish the Regular convenience package to PyPI](#publish-the-regular-convenience-package-to-pypi-1)
<add> - [Publish the packages to PyPI](#publish-the-packages-to-pypi)
<ide> - [Publish documentation prepared before](#publish-documentation-prepared-before)
<ide> - [Add tags in git](#add-tags-in-git-1)
<ide> - [Notify developers of release](#notify-developers-of-release)
<ide> Verify that the packages appear in
<ide> [providers](https://dist.apache.org/repos/dist/release/airflow/providers)
<ide>
<ide>
<del>## Publish the Regular convenience package to PyPI
<add>## Publish the packages to PyPI
<ide>
<del>By that time the packages with proper name (renamed from rc* to final version should be in your dist
<del>folder.
<add>By that time the packages should be in your dist folder.
<ide>
<ide> ```shell script
<ide> cd ${AIRFLOW_REPO_ROOT}
<add>git checkout <ONE_OF_THE_RC_TAGS_FOR_ONE_OF_THE_RELEASED_PROVIDERS>
<ide> ```
<ide>
<ide> * Verify the artifacts that would be uploaded:
<ide> twine upload -r pypitest ${AIRFLOW_REPO_ROOT}/dist/*.whl ${AIRFLOW_REPO_ROOT}/di
<ide> twine upload -r pypi ${AIRFLOW_REPO_ROOT}/dist/*.whl ${AIRFLOW_REPO_ROOT}/dist/*.tar.gz
<ide> ```
<ide>
<add>Copy links to updated packages.
<add>
<ide> * Again, confirm that the packages are available under the links printed.
<ide>
<ide> ## Publish documentation prepared before
<ide> Dear Airflow community,
<ide>
<ide> I'm happy to announce that new versions of Airflow Providers packages were just released.
<ide>
<add>TODO: If there is just a few packages to release - paste the links to PyPI packages. Otherwise delete this TODO (too many links make the message unclear).
<add>
<ide> The source release, as well as the binary releases, are available here:
<ide>
<ide> https://airflow.apache.org/docs/apache-airflow-providers/installing-from-sources
<ide>
<del>You can install the providers via PyPI https://airflow.apache.org/apache-airflow-providers/installing-from-pypi
<add>You can install the providers via PyPI https://airflow.apache.org/docs/apache-airflow-providers/installing-from-pypi
<ide>
<ide> The documentation is available at https://airflow.apache.org/docs/ and linked from the PyPI packages.
<ide>
| 1
|
Ruby
|
Ruby
|
match #{prefix}/libexec and prefix+'libexec'
|
be9d91b2b80fdfe82720b2e2d3ceec378e33b371
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_formula_text name, text
<ide> end
<ide>
<ide> # Prefer formula path shortcuts in Pathname+
<del> if text =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|lib|libexec|sbin|share))}
<add> if text =~ %r{\(\s*(prefix\s*\+\s*(['"])(bin|include|libexec|lib|sbin|share))}
<ide> problems << " * \"(#{$1}...#{$2})\" should be \"(#{$3}+...)\""
<ide> end
<ide>
<ide> def audit_formula_text name, text
<ide> end
<ide>
<ide> # Prefer formula path shortcuts in strings
<del> if text =~ %r[(\#\{prefix\}/(bin|include|lib|libexec|sbin|share))]
<add> if text =~ %r[(\#\{prefix\}/(bin|include|libexec|lib|sbin|share))]
<ide> problems << " * \"#{$1}\" should be \"\#{#{$2}}\""
<ide> end
<ide>
| 1
|
Ruby
|
Ruby
|
fix unbottled dependency handling
|
eb74717a9e24eb94de9a60508a208b224dff8172
|
<ide><path>Library/Homebrew/exceptions.rb
<ide> def dump(verbose: false)
<ide> end
<ide> end
<ide>
<del># Raised by {FormulaInstaller#check_dependencies_bottled} and
<del># {FormulaInstaller#install} if the formula or its dependencies are not bottled
<del># and are being installed on a system without necessary build tools.
<del>class BuildToolsError < RuntimeError
<add># Raised if the formula or its dependencies are not bottled and are being
<add># installed in a situation where a bottle is required.
<add>class UnbottledError < RuntimeError
<ide> def initialize(formulae)
<del> super <<~EOS
<del> The following #{"formula".pluralize(formulae.count)}
<add> msg = +<<~EOS
<add> The following #{"formula".pluralize(formulae.count)} cannot be installed from #{"bottle".pluralize(formulae.count)} and must be
<add> built from source.
<ide> #{formulae.to_sentence}
<del> cannot be installed as #{"binary package".pluralize(formulae.count)} and must be built from source.
<del> #{DevelopmentTools.installation_instructions}
<ide> EOS
<add> msg += "#{DevelopmentTools.installation_instructions}\n" unless DevelopmentTools.installed?
<add> msg.freeze
<add> super(msg)
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def install
<ide>
<ide> check_conflicts
<ide>
<del> raise BuildToolsError, [formula] if !pour_bottle? && !formula.bottle_unneeded? && !DevelopmentTools.installed?
<add> raise UnbottledError, [formula] if !pour_bottle? && !formula.bottle_unneeded? && !DevelopmentTools.installed?
<ide>
<ide> unless ignore_deps?
<ide> deps = compute_dependencies
<del> check_dependencies_bottled(deps) if pour_bottle? && !DevelopmentTools.installed?
<add> if ((pour_bottle? && !DevelopmentTools.installed?) || build_bottle?) &&
<add> (unbottled = unbottled_dependencies(deps)).presence
<add> # Check that each dependency in deps has a bottle available, terminating
<add> # abnormally with a UnbottledError if one or more don't.
<add> raise UnbottledError, unbottled
<add> end
<add>
<ide> install_dependencies(deps)
<ide> end
<ide>
<ide> def install
<ide> @pour_failed = true
<ide> onoe e.message
<ide> opoo "Bottle installation failed: building from source."
<del> raise BuildToolsError, [formula] unless DevelopmentTools.installed?
<add> raise UnbottledError, [formula] unless DevelopmentTools.installed?
<ide>
<ide> compute_and_install_dependencies unless ignore_deps?
<ide> else
<ide> def compute_dependencies
<ide> expand_dependencies(req_deps + formula.deps)
<ide> end
<ide>
<del> # Check that each dependency in deps has a bottle available, terminating
<del> # abnormally with a BuildToolsError if one or more don't.
<del> # Only invoked when the user has no developer tools.
<del> def check_dependencies_bottled(deps)
<del> unbottled = deps.reject do |dep, _|
<del> dep_f = dep.to_formula
<del> dep_f.pour_bottle? || dep_f.bottle_unneeded?
<del> end
<add> def unbottled_dependencies(deps)
<add> deps.map(&:first).map(&:to_formula).reject do |dep_f|
<add> next false unless dep_f.pour_bottle?
<ide>
<del> raise BuildToolsError, unbottled unless unbottled.empty?
<add> dep_f.bottle_unneeded? || dep_f.bottled?
<add> end
<ide> end
<ide>
<ide> def compute_and_install_dependencies
<ide><path>Library/Homebrew/test/formula_installer_bottle_spec.rb
<ide> def temporarily_install_bottle(formula)
<ide>
<ide> expect {
<ide> described_class.new(formula).install
<del> }.to raise_error(BuildToolsError)
<add> }.to raise_error(UnbottledError)
<ide>
<ide> expect(formula).not_to be_latest_version_installed
<ide> end
| 3
|
Python
|
Python
|
implement different approach to fix bug
|
8fbd472e562237dd56ce251e266e2090d6c5003b
|
<ide><path>numpy/lib/arraysetops.py
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False):
<ide> ar1 = np.asarray(ar1).ravel()
<ide> ar2 = np.asarray(ar2).ravel()
<ide>
<add> # Ensure that iteration through object arrays yields size-1 arrays
<add> if ar2.dtype == object:
<add> ar2 = ar2.reshape(-1, 1)
<add>
<ide> # Check if one of the arrays may contain arbitrary objects
<ide> contains_object = ar1.dtype.hasobject or ar2.dtype.hasobject
<ide>
<ide> def in1d(ar1, ar2, assume_unique=False, invert=False):
<ide> if len(ar2) < 10 * len(ar1) ** 0.145 or contains_object:
<ide> if invert:
<ide> mask = np.ones(len(ar1), dtype=bool)
<del> # If ar2.dtype is object, store is used to wrap the a value
<del> # in an array to prevent tuples from being unpacked before the comparison
<del> if ar2.dtype == object:
<del> store = np.empty(shape=1, dtype=object)
<del> for a in ar2:
<del> store[0] = a
<del> mask &= (ar1 != store)
<del> else:
<del> for a in ar2:
<del> mask &= (ar1 != a)
<add> for a in ar2:
<add> mask &= (ar1 != a)
<ide> else:
<ide> mask = np.zeros(len(ar1), dtype=bool)
<del> # If ar2.dtype is object, store is used to wrap the a value
<del> # in an array to prevent tuples from being unpacked before the comparison
<del> if ar2.dtype == object:
<del> store = np.empty(shape=1, dtype=object)
<del> for a in ar2:
<del> store[0] = a
<del> mask |= (ar1 == store)
<del> else:
<del> for a in ar2:
<del> mask |= (ar1 == a)
<add> for a in ar2:
<add> mask |= (ar1 == a)
<ide> return mask
<ide>
<ide> # Otherwise use sorting
| 1
|
Javascript
|
Javascript
|
watch object refference or equality
|
d6e3e1baabc3acc930e4fda387b62cbd03e64577
|
<ide><path>src/directives.js
<ide> function classDirective(name, selector) {
<ide> if (isObject(newVal) && !isArray(newVal))
<ide> newVal = map(newVal, function(v, k) { if (v) return k });
<ide> if (newVal) element.addClass(isArray(newVal) ? newVal.join(' ') : newVal); }
<del> });
<add> }, true);
<ide> });
<ide> }
<ide>
<ide> var ngStyleDirective = valueFn(function(scope, element, attr) {
<ide> forEach(oldStyles, function(val, style) { element.css(style, '');});
<ide> }
<ide> if (newStyles) element.css(newStyles);
<del> });
<add> }, true);
<ide> });
<ide>
<ide>
<ide><path>src/service/scope.js
<ide> * event processing life-cycle. See {@link guide/dev_guide.scopes developer guide on scopes}.
<ide> */
<ide> function $RootScopeProvider(){
<add> var TTL = 10;
<add>
<add> this.ttl = function(value) {
<add> if (arguments.length) {
<add> TTL = value;
<add> }
<add> return TTL;
<add> }
<add>
<ide> this.$get = ['$injector', '$exceptionHandler', '$parse',
<ide> function( $injector, $exceptionHandler, $parse) {
<ide>
<ide> function $RootScopeProvider(){
<ide> *
<ide> * - `string`: Evaluated as {@link guide/dev_guide.expressions expression}
<ide> * - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
<add> *
<add> * @param {boolean=} objectEquality Compare object for equality rather then for refference.
<ide> * @returns {function()} Returns a deregistration function for this listener.
<ide> */
<del> $watch: function(watchExp, listener) {
<add> $watch: function(watchExp, listener, objectEquality) {
<ide> var scope = this,
<ide> get = compileToFn(watchExp, 'watch'),
<ide> array = scope.$$watchers,
<ide> watcher = {
<ide> fn: listener,
<ide> last: initWatchVal,
<ide> get: get,
<del> exp: watchExp
<add> exp: watchExp,
<add> eq: !!objectEquality
<ide> };
<ide>
<ide> // in the case user pass string, we need to compile it, do we really need this ?
<ide> function $RootScopeProvider(){
<ide> watchers,
<ide> asyncQueue,
<ide> length,
<del> dirty, ttl = 100,
<add> dirty, ttl = TTL,
<ide> next, current, target = this,
<ide> watchLog = [],
<ide> logIdx, logMsg;
<ide> function $RootScopeProvider(){
<ide> watch = watchers[length];
<ide> // Most common watches are on primitives, in which case we can short
<ide> // circuit it with === operator, only when === fails do we use .equals
<del> if ((value = watch.get(current)) !== (last = watch.last) && !equals(value, last)) {
<add> if ((value = watch.get(current)) !== (last = watch.last) &&
<add> !(watch.eq
<add> ? equals(value, last)
<add> : (typeof value == 'number' && typeof last == 'number'
<add> && isNaN(value) && isNaN(last)))) {
<ide> dirty = true;
<del> watch.last = copy(value);
<add> watch.last = watch.eq ? copy(value) : value;
<ide> watch.fn(value, ((last === initWatchVal) ? value : last), current);
<ide> if (ttl < 5) {
<ide> logIdx = 4 - ttl;
<ide> function $RootScopeProvider(){
<ide> } while ((current = next));
<ide>
<ide> if(dirty && !(ttl--)) {
<del> throw Error('100 $digest() iterations reached. Aborting!\n' +
<add> throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
<ide> 'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
<ide> }
<ide> } while (dirty || asyncQueue.length);
<ide><path>test/service/scopeSpec.js
<ide> describe('Scope', function() {
<ide> }));
<ide>
<ide>
<del> it('should prevent infinite recursion and print watcher expression',inject(
<del> function($rootScope) {
<del> $rootScope.$watch('a', function() {$rootScope.b++;});
<del> $rootScope.$watch('b', function() {$rootScope.a++;});
<del> $rootScope.a = $rootScope.b = 0;
<add> it('should prevent infinite recursion and print watcher expression',function() {
<add> module(function($rootScopeProvider) {
<add> $rootScopeProvider.ttl(100);
<add> });
<add> inject(function($rootScope) {
<add> $rootScope.$watch('a', function() {$rootScope.b++;});
<add> $rootScope.$watch('b', function() {$rootScope.a++;});
<add> $rootScope.a = $rootScope.b = 0;
<ide>
<del> expect(function() {
<del> $rootScope.$digest();
<del> }).toThrow('100 $digest() iterations reached. Aborting!\n'+
<del> 'Watchers fired in the last 5 iterations: ' +
<del> '[["a; newVal: 96; oldVal: 95","b; newVal: 97; oldVal: 96"],' +
<del> '["a; newVal: 97; oldVal: 96","b; newVal: 98; oldVal: 97"],' +
<del> '["a; newVal: 98; oldVal: 97","b; newVal: 99; oldVal: 98"],' +
<del> '["a; newVal: 99; oldVal: 98","b; newVal: 100; oldVal: 99"],' +
<del> '["a; newVal: 100; oldVal: 99","b; newVal: 101; oldVal: 100"]]');
<del> }));
<add> expect(function() {
<add> $rootScope.$digest();
<add> }).toThrow('100 $digest() iterations reached. Aborting!\n'+
<add> 'Watchers fired in the last 5 iterations: ' +
<add> '[["a; newVal: 96; oldVal: 95","b; newVal: 97; oldVal: 96"],' +
<add> '["a; newVal: 97; oldVal: 96","b; newVal: 98; oldVal: 97"],' +
<add> '["a; newVal: 98; oldVal: 97","b; newVal: 99; oldVal: 98"],' +
<add> '["a; newVal: 99; oldVal: 98","b; newVal: 100; oldVal: 99"],' +
<add> '["a; newVal: 100; oldVal: 99","b; newVal: 101; oldVal: 100"]]');
<add> });
<add> });
<ide>
<ide>
<ide> it('should prevent infinite recursion and print print watcher function name or body',
<ide> describe('Scope', function() {
<ide> $rootScope.$watch('a', function(value) {
<ide> log +='.';
<ide> expect(value).toBe($rootScope.a);
<del> });
<add> }, true);
<ide> $rootScope.$watch('b', function(value) {
<ide> log +='!';
<ide> expect(value).toBe($rootScope.b);
<del> });
<add> }, true);
<ide> $rootScope.$digest();
<ide> log = '';
<ide>
<ide> describe('Scope', function() {
<ide> $rootScope.$watch(function() { return undefined;}, logger);
<ide> $rootScope.$watch(function() { return '';}, logger);
<ide> $rootScope.$watch(function() { return false;}, logger);
<del> $rootScope.$watch(function() { return {};}, logger);
<add> $rootScope.$watch(function() { return {};}, logger, true);
<ide> $rootScope.$watch(function() { return 23;}, logger);
<ide>
<ide> $rootScope.$digest();
| 3
|
Text
|
Text
|
fix broken links in english challenges
|
cb35d49a210950f672b602412e86346e5f940de5
|
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/assignment-with-a-returned-value.english.md
<ide> videoUrl: 'https://scrimba.com/c/ce2pEtB'
<ide>
<ide> ## Description
<ide> <section id='description'>
<del>If you'll recall from our discussion of <a href="javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Storing Values with the Assignment Operator</a>, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
<add>If you'll recall from our discussion of <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator" target="_blank">Storing Values with the Assignment Operator</a>, everything to the right of the equal sign is resolved before the value is assigned. This means we can take the return value of a function and assign it to a variable.
<ide> Assume we have pre-defined a function <code>sum</code> which adds two numbers together, then:
<ide> <code>ourSum = sum(5, 12);</code>
<ide> will call <code>sum</code> function, which returns a value of <code>17</code> and assigns it to <code>ourSum</code> variable.
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/generate-random-fractions-with-javascript.english.md
<ide> videoUrl: 'https://scrimba.com/c/cyWJJs3'
<ide> <section id='description'>
<ide> Random numbers are useful for creating random behavior.
<ide> JavaScript has a <code>Math.random()</code> function that generates a random decimal number between <code>0</code> (inclusive) and not quite up to <code>1</code> (exclusive). Thus <code>Math.random()</code> can return a <code>0</code> but never quite return a <code>1</code>
<del><strong>Note</strong><br>Like <a href='storing-values-with-the-assignment-operator' target='_blank'>Storing Values with the Equal Operator</a>, all function calls will be resolved before the <code>return</code> executes, so we can <code>return</code> the value of the <code>Math.random()</code> function.
<add><strong>Note</strong><br>Like <a href='learn/javascript-algorithms-and-data-structures/basic-javascript/storing-values-with-the-assignment-operator' target='_blank'>Storing Values with the Equal Operator</a>, all function calls will be resolved before the <code>return</code> executes, so we can <code>return</code> the value of the <code>Math.random()</code> function.
<ide> </section>
<ide>
<ide> ## Instructions
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/basic-javascript/record-collection.english.md
<ide> There are several rules for handling incomplete data:
<ide> If <code>prop</code> is <code>"tracks"</code> but the album doesn't have a <code>"tracks"</code> property, create an empty array before adding the new value to the album's corresponding property.
<ide> If <code>prop</code> is <code>"tracks"</code> and <code>value</code> isn't empty (<code>""</code>), push the <code>value</code> onto the end of the album's existing <code>tracks</code> array.
<ide> If <code>value</code> is empty (<code>""</code>), delete the given <code>prop</code> property from the album.
<del><strong>Hints</strong><br>Use <code>bracket notation</code> when <a href="javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">accessing object properties with variables</a>.
<add><strong>Hints</strong><br>Use <code>bracket notation</code> when <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables" target="_blank">accessing object properties with variables</a>.
<ide> Push is an array method you can read about on <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank">Mozilla Developer Network</a>.
<del>You may refer back to <a href="javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">Manipulating Complex Objects</a> Introducing JavaScript Object Notation (JSON) for a refresher.
<add>You may refer back to <a href="learn/javascript-algorithms-and-data-structures/basic-javascript/manipulating-complex-objects" target="_blank">Manipulating Complex Objects</a> Introducing JavaScript Object Notation (JSON) for a refresher.
<ide> </section>
<ide>
<ide> ## Instructions
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/introducing-inline-styles.english.md
<ide> isRequired: false
<ide>
<ide> ## Description
<ide> <section id='description'>
<del>There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of <a target="_blank" href="front-end-libraries/react/define-an-html-class-in-jsx"> the way you apply classes to JSX elements</a>.
<add>There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of <a target="_blank" href="learn/front-end-libraries/react/define-an-html-class-in-jsx"> the way you apply classes to JSX elements</a>.
<ide> If you import styles from a stylesheet, it isn't much different at all. You apply a class to your JSX element using the <code>className</code> attribute, and apply styles to the class in your stylesheet. Another option is to apply <strong><em>inline</em></strong> styles, which are very common in ReactJS development.
<ide> You apply inline styles to JSX elements similar to how you do it in HTML, but with a few JSX differences. Here's an example of an inline style in HTML:
<ide> <code><div style="color: yellow; font-size: 16px">Mellow Yellow</div></code>
| 4
|
Javascript
|
Javascript
|
move error creation helpers to errors.js
|
c0762c2f54f80b92f2f5e0f9af51f4c048c53e4f
|
<ide><path>lib/dgram.js
<ide> const SEND_BUFFER = false;
<ide> // Lazily loaded
<ide> var cluster = null;
<ide>
<del>const errnoException = util._errnoException;
<del>const exceptionWithHostPort = util._exceptionWithHostPort;
<add>const errnoException = errors.errnoException;
<add>const exceptionWithHostPort = errors.exceptionWithHostPort;
<ide>
<ide>
<ide> function lookup4(lookup, address, callback) {
<ide><path>lib/dns.js
<ide>
<ide> 'use strict';
<ide>
<del>const util = require('util');
<del>
<ide> const cares = process.binding('cares_wrap');
<ide> const { isIP, isIPv4, isLegalPort } = require('internal/net');
<ide> const { customPromisifyArgs } = require('internal/util');
<ide> const errors = require('internal/errors');
<del>const {
<del> UV_EAI_MEMORY,
<del> UV_EAI_NODATA,
<del> UV_EAI_NONAME
<del>} = process.binding('uv');
<ide>
<ide> const {
<ide> GetAddrInfoReqWrap,
<ide> const {
<ide> ChannelWrap,
<ide> } = cares;
<ide>
<del>function errnoException(err, syscall, hostname) {
<del> // FIXME(bnoordhuis) Remove this backwards compatibility nonsense and pass
<del> // the true error to the user. ENOTFOUND is not even a proper POSIX error!
<del> if (err === UV_EAI_MEMORY ||
<del> err === UV_EAI_NODATA ||
<del> err === UV_EAI_NONAME) {
<del> err = 'ENOTFOUND';
<del> }
<del> var ex = null;
<del> if (typeof err === 'string') { // c-ares error code.
<del> const errHost = hostname ? ` ${hostname}` : '';
<del> ex = new Error(`${syscall} ${err}${errHost}`);
<del> ex.code = err;
<del> ex.errno = err;
<del> ex.syscall = syscall;
<del> } else {
<del> ex = util._errnoException(err, syscall);
<del> }
<del> if (hostname) {
<del> ex.hostname = hostname;
<del> }
<del> return ex;
<del>}
<del>
<ide> const IANA_DNS_PORT = 53;
<del>
<add>const dnsException = errors.dnsException;
<ide>
<ide> function onlookup(err, addresses) {
<ide> if (err) {
<del> return this.callback(errnoException(err, 'getaddrinfo', this.hostname));
<add> return this.callback(dnsException(err, 'getaddrinfo', this.hostname));
<ide> }
<ide> if (this.family) {
<ide> this.callback(null, addresses[0], this.family);
<ide> function onlookup(err, addresses) {
<ide>
<ide> function onlookupall(err, addresses) {
<ide> if (err) {
<del> return this.callback(errnoException(err, 'getaddrinfo', this.hostname));
<add> return this.callback(dnsException(err, 'getaddrinfo', this.hostname));
<ide> }
<ide>
<ide> var family = this.family;
<ide> function lookup(hostname, options, callback) {
<ide>
<ide> var err = cares.getaddrinfo(req, hostname, family, hints, verbatim);
<ide> if (err) {
<del> process.nextTick(callback, errnoException(err, 'getaddrinfo', hostname));
<add> process.nextTick(callback, dnsException(err, 'getaddrinfo', hostname));
<ide> return {};
<ide> }
<ide> return req;
<ide> Object.defineProperty(lookup, customPromisifyArgs,
<ide>
<ide> function onlookupservice(err, host, service) {
<ide> if (err)
<del> return this.callback(errnoException(err, 'getnameinfo', this.host));
<add> return this.callback(dnsException(err, 'getnameinfo', this.host));
<ide>
<ide> this.callback(null, host, service);
<ide> }
<ide> function lookupService(host, port, callback) {
<ide> req.oncomplete = onlookupservice;
<ide>
<ide> var err = cares.getnameinfo(req, host, port);
<del> if (err) throw errnoException(err, 'getnameinfo', host);
<add> if (err) throw dnsException(err, 'getnameinfo', host);
<ide> return req;
<ide> }
<ide>
<ide> function onresolve(err, result, ttls) {
<ide> result = result.map((address, index) => ({ address, ttl: ttls[index] }));
<ide>
<ide> if (err)
<del> this.callback(errnoException(err, this.bindingName, this.hostname));
<add> this.callback(dnsException(err, this.bindingName, this.hostname));
<ide> else
<ide> this.callback(null, result);
<ide> }
<ide> function resolver(bindingName) {
<ide> req.oncomplete = onresolve;
<ide> req.ttl = !!(options && options.ttl);
<ide> var err = this._handle[bindingName](req, name);
<del> if (err) throw errnoException(err, bindingName);
<add> if (err) throw dnsException(err, bindingName);
<ide> return req;
<ide> }
<ide> Object.defineProperty(query, 'name', { value: bindingName });
<ide><path>lib/fs.js
<ide> const { kMaxLength } = require('buffer');
<ide> const isWindows = process.platform === 'win32';
<ide>
<ide> const DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
<del>const errnoException = util._errnoException;
<add>const errnoException = errors.errnoException;
<ide>
<ide> let truncateWarn = true;
<ide>
<ide><path>lib/internal/child_process.js
<ide> const {
<ide> UV_ESRCH
<ide> } = process.binding('uv');
<ide>
<del>const errnoException = util._errnoException;
<add>const errnoException = errors.errnoException;
<ide> const { SocketListSend, SocketListReceive } = SocketList;
<ide>
<ide> const MAX_HANDLE_RETRANSMISSIONS = 3;
<ide><path>lib/internal/errors.js
<ide> var green = '';
<ide> var red = '';
<ide> var white = '';
<ide>
<del>const { errmap } = process.binding('uv');
<add>const {
<add> errmap,
<add> UV_EAI_MEMORY,
<add> UV_EAI_NODATA,
<add> UV_EAI_NONAME
<add>} = process.binding('uv');
<ide> const { kMaxLength } = process.binding('buffer');
<ide> const { defineProperty } = Object;
<ide>
<ide> function lazyUtil() {
<ide> return util_;
<ide> }
<ide>
<add>var internalUtil = null;
<add>function lazyInternalUtil() {
<add> if (!internalUtil) {
<add> internalUtil = require('internal/util');
<add> }
<add> return internalUtil;
<add>}
<add>
<ide> function makeNodeError(Base) {
<ide> return class NodeError extends Base {
<ide> constructor(key, ...args) {
<ide> function E(sym, val) {
<ide> messages.set(sym, typeof val === 'function' ? val : String(val));
<ide> }
<ide>
<del>// This creates an error compatible with errors produced in UVException
<del>// using the context collected in CollectUVExceptionInfo
<del>// The goal is to migrate them to ERR_* errors later when
<del>// compatibility is not a concern
<add>/**
<add> * This creates an error compatible with errors produced in the C++
<add> * function UVException using a context object with data assembled in C++.
<add> * The goal is to migrate them to ERR_* errors later when compatibility is
<add> * not a concern.
<add> *
<add> * @param {Object} ctx
<add> * @returns {Error}
<add> */
<ide> function uvException(ctx) {
<ide> const err = new Error();
<ide>
<ide> function uvException(ctx) {
<ide> return err;
<ide> }
<ide>
<add>/**
<add> * This used to be util._errnoException().
<add> *
<add> * @param {number} err - A libuv error number
<add> * @param {string} syscall
<add> * @param {string} [original]
<add> * @returns {Error}
<add> */
<add>function errnoException(err, syscall, original) {
<add> // TODO(joyeecheung): We have to use the type-checked
<add> // getSystemErrorName(err) to guard against invalid arguments from users.
<add> // This can be replaced with [ code ] = errmap.get(err) when this method
<add> // is no longer exposed to user land.
<add> const code = lazyUtil().getSystemErrorName(err);
<add> const message = original ?
<add> `${syscall} ${code} ${original}` : `${syscall} ${code}`;
<add>
<add> const ex = new Error(message);
<add> // TODO(joyeecheung): errno is supposed to err, like in uvException
<add> ex.code = ex.errno = code;
<add> ex.syscall = syscall;
<add>
<add> Error.captureStackTrace(ex, errnoException);
<add> return ex;
<add>}
<add>
<add>/**
<add> * This used to be util._exceptionWithHostPort().
<add> *
<add> * @param {number} err - A libuv error number
<add> * @param {string} syscall
<add> * @param {string} address
<add> * @param {number} [port]
<add> * @param {string} [additional]
<add> * @returns {Error}
<add> */
<add>function exceptionWithHostPort(err, syscall, address, port, additional) {
<add> // TODO(joyeecheung): We have to use the type-checked
<add> // getSystemErrorName(err) to guard against invalid arguments from users.
<add> // This can be replaced with [ code ] = errmap.get(err) when this method
<add> // is no longer exposed to user land.
<add> const code = lazyUtil().getSystemErrorName(err);
<add> let details = '';
<add> if (port && port > 0) {
<add> details = ` ${address}:${port}`;
<add> } else if (address) {
<add> details = ` ${address}`;
<add> }
<add> if (additional) {
<add> details += ` - Local (${additional})`;
<add> }
<add>
<add> const ex = new Error(`${syscall} ${code}${details}`);
<add> // TODO(joyeecheung): errno is supposed to err, like in uvException
<add> ex.code = ex.errno = code;
<add> ex.syscall = syscall;
<add> ex.address = address;
<add> if (port) {
<add> ex.port = port;
<add> }
<add>
<add> Error.captureStackTrace(ex, exceptionWithHostPort);
<add> return ex;
<add>}
<add>
<add>/**
<add> * @param {number|string} err - A libuv error number or a c-ares error code
<add> * @param {string} syscall
<add> * @param {string} [hostname]
<add> * @returns {Error}
<add> */
<add>function dnsException(err, syscall, hostname) {
<add> const ex = new Error();
<add> // FIXME(bnoordhuis) Remove this backwards compatibility nonsense and pass
<add> // the true error to the user. ENOTFOUND is not even a proper POSIX error!
<add> if (err === UV_EAI_MEMORY ||
<add> err === UV_EAI_NODATA ||
<add> err === UV_EAI_NONAME) {
<add> err = 'ENOTFOUND'; // Fabricated error name.
<add> }
<add> if (typeof err === 'string') { // c-ares error code.
<add> const errHost = hostname ? ` ${hostname}` : '';
<add> ex.message = `${syscall} ${err}${errHost}`;
<add> // TODO(joyeecheung): errno is supposed to be a number, like in uvException
<add> ex.code = ex.errno = err;
<add> ex.syscall = syscall;
<add> } else { // libuv error number
<add> const code = lazyInternalUtil().getSystemErrorName(err);
<add> ex.message = `${syscall} ${code}`;
<add> // TODO(joyeecheung): errno is supposed to be err, like in uvException
<add> ex.code = ex.errno = code;
<add> ex.syscall = syscall;
<add> }
<add> if (hostname) {
<add> ex.hostname = hostname;
<add> }
<add> Error.captureStackTrace(ex, dnsException);
<add> return ex;
<add>}
<add>
<ide> module.exports = exports = {
<add> dnsException,
<add> errnoException,
<add> exceptionWithHostPort,
<ide> uvException,
<ide> message,
<ide> Error: makeNodeError(Error),
<ide><path>lib/internal/http2/core.js
<ide> class Http2Stream extends Duplex {
<ide> req.async = false;
<ide> const err = createWriteReq(req, handle, data, encoding);
<ide> if (err)
<del> throw util._errnoException(err, 'write', req.error);
<add> throw errors.errnoException(err, 'write', req.error);
<ide> trackWriteState(this, req.bytes);
<ide> }
<ide>
<ide> class Http2Stream extends Duplex {
<ide> }
<ide> const err = handle.writev(req, chunks);
<ide> if (err)
<del> throw util._errnoException(err, 'write', req.error);
<add> throw errors.errnoException(err, 'write', req.error);
<ide> trackWriteState(this, req.bytes);
<ide> }
<ide>
<ide><path>lib/internal/process.js
<ide> function setupKillAndExit() {
<ide> }
<ide>
<ide> if (err)
<del> throw util._errnoException(err, 'kill');
<add> throw errors.errnoException(err, 'kill');
<ide>
<ide> return true;
<ide> };
<ide> function setupSignalHandlers() {
<ide> const err = wrap.start(signum);
<ide> if (err) {
<ide> wrap.close();
<del> throw util._errnoException(err, 'uv_signal_start');
<add> throw errors.errnoException(err, 'uv_signal_start');
<ide> }
<ide>
<ide> signalWraps[type] = wrap;
<ide><path>lib/net.js
<ide> const kLastWriteQueueSize = Symbol('lastWriteQueueSize');
<ide> // reasons it's lazy loaded.
<ide> var cluster = null;
<ide>
<del>const errnoException = util._errnoException;
<del>const exceptionWithHostPort = util._exceptionWithHostPort;
<add>const errnoException = errors.errnoException;
<add>const exceptionWithHostPort = errors.exceptionWithHostPort;
<ide>
<ide> const {
<ide> kTimeout,
<ide><path>lib/tty.js
<ide>
<ide> 'use strict';
<ide>
<del>const { inherits, _errnoException, _extend } = require('util');
<add>const { inherits, _extend } = require('util');
<ide> const net = require('net');
<ide> const { TTY, isTTY } = process.binding('tty_wrap');
<ide> const errors = require('internal/errors');
<ide> WriteStream.prototype._refreshSize = function() {
<ide> const winSize = new Array(2);
<ide> const err = this._handle.getWindowSize(winSize);
<ide> if (err) {
<del> this.emit('error', _errnoException(err, 'getWindowSize'));
<add> this.emit('error', errors.errnoException(err, 'getWindowSize'));
<ide> return;
<ide> }
<ide> const [newCols, newRows] = winSize;
<ide><path>lib/util.js
<ide> function error(...args) {
<ide> }
<ide> }
<ide>
<del>function _errnoException(err, syscall, original) {
<del> const name = getSystemErrorName(err);
<del> var message = `${syscall} ${name}`;
<del> if (original)
<del> message += ` ${original}`;
<del> const e = new Error(message);
<del> e.code = e.errno = name;
<del> e.syscall = syscall;
<del> return e;
<del>}
<del>
<del>function _exceptionWithHostPort(err,
<del> syscall,
<del> address,
<del> port,
<del> additional) {
<del> var details;
<del> if (port && port > 0) {
<del> details = `${address}:${port}`;
<del> } else {
<del> details = address;
<del> }
<del>
<del> if (additional) {
<del> details += ` - Local (${additional})`;
<del> }
<del> var ex = exports._errnoException(err, syscall, details);
<del> ex.address = address;
<del> if (port) {
<del> ex.port = port;
<del> }
<del> return ex;
<del>}
<del>
<ide> function callbackifyOnRejected(reason, cb) {
<ide> // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
<ide> // Because `null` is a special error value in callbacks which means "no error
<ide> function getSystemErrorName(err) {
<ide>
<ide> // Keep the `exports =` so that various functions can still be monkeypatched
<ide> module.exports = exports = {
<del> _errnoException,
<del> _exceptionWithHostPort,
<add> _errnoException: errors.errnoException,
<add> _exceptionWithHostPort: errors.exceptionWithHostPort,
<ide> _extend,
<ide> callbackify,
<ide> debuglog,
| 10
|
Go
|
Go
|
add init_windows.go for compilation
|
40b6ebfe754d6efe839f89ecfd4727ccdbbea359
|
<ide><path>libnetwork/ns/init_windows.go
<add>package ns
<add>
<add>// File is present so that go build ./... is closer to working on Windows from repo root.
| 1
|
Javascript
|
Javascript
|
add table parsing capability to the doctool
|
0584aeb30a97d8ca81f242f4ddc05a0c6f9b7684
|
<ide><path>tools/doc/html.js
<ide> function analyticsScript(analytics) {
<ide> `;
<ide> }
<ide>
<add>// replace placeholders in text tokens
<add>function replaceInText(text) {
<add> return linkJsTypeDocs(linkManPages(text));
<add>}
<add>
<ide> // handle general body-text replacements
<ide> // for example, link man page references to the actual page
<ide> function parseText(lexed) {
<ide> lexed.forEach(function(tok) {
<del> if (tok.text && tok.type !== 'code') {
<del> tok.text = linkManPages(tok.text);
<del> tok.text = linkJsTypeDocs(tok.text);
<add> if (tok.type === 'table') {
<add> if (tok.cells) {
<add> tok.cells.forEach((row, x) => {
<add> row.forEach((_, y) => {
<add> if (tok.cells[x] && tok.cells[x][y]) {
<add> tok.cells[x][y] = replaceInText(tok.cells[x][y]);
<add> }
<add> });
<add> });
<add> }
<add>
<add> if (tok.header) {
<add> tok.header.forEach((_, i) => {
<add> if (tok.header[i]) {
<add> tok.header[i] = replaceInText(tok.header[i]);
<add> }
<add> });
<add> }
<add> } else if (tok.text && tok.type !== 'code') {
<add> tok.text = replaceInText(tok.text);
<ide> }
<ide> });
<ide> }
| 1
|
Go
|
Go
|
fix error message when invalid directory
|
74a2b13687787a33b0963f020f704d3cdde4b06d
|
<ide><path>commands.go
<ide> func (cli *DockerCli) CmdBuild(args ...string) error {
<ide> } else if utils.IsURL(cmd.Arg(0)) || utils.IsGIT(cmd.Arg(0)) {
<ide> isRemote = true
<ide> } else {
<add> if _, err := os.Stat(cmd.Arg(0)); err != nil {
<add> return err
<add> }
<ide> context, err = Tar(cmd.Arg(0), Uncompressed)
<ide> }
<ide> var body io.Reader
| 1
|
Java
|
Java
|
take unsubscribes before onnext
|
d21720938426e6612ec026c2bd2d80395fbd3f07
|
<ide><path>src/main/java/rx/internal/operators/OperatorTake.java
<ide> public void onError(Throwable e) {
<ide> @Override
<ide> public void onNext(T i) {
<ide> if (!isUnsubscribed()) {
<del> child.onNext(i);
<ide> if (++count >= limit) {
<ide> completed = true;
<del> child.onCompleted();
<add> // unsubscribe before emitting onNext so shutdown happens before possible effects
<add> // of onNext such as product.request(n) calls be sent upstream.
<ide> unsubscribe();
<ide> }
<add> child.onNext(i);
<add> if (completed) {
<add> child.onCompleted();
<add> }
<ide> }
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
add test case
|
30856a67501a5a7f1f4f88b7c40ef106be02d07d
|
<ide><path>test/ConfigTestCases.template.js
<ide> const describeCases = config => {
<ide> return;
<ide> }
<ide>
<del> const globalContext = {
<del> console: console,
<del> expect: expect,
<del> setTimeout: setTimeout,
<del> clearTimeout: clearTimeout,
<del> document: new FakeDocument(),
<del> location: {
<del> href: "https://test.cases/path/index.html",
<del> origin: "https://test.cases",
<del> toString() {
<del> return "https://test.cases/path/index.html";
<del> }
<del> }
<del> };
<del>
<del> const requireCache = Object.create(null);
<del> function _require(currentDirectory, options, module) {
<del> if (Array.isArray(module) || /^\.\.?\//.test(module)) {
<del> let content;
<del> let p;
<del> if (Array.isArray(module)) {
<del> p = path.join(currentDirectory, ".array-require.js");
<del> content = `module.exports = (${module
<del> .map(arg => {
<del> return `require(${JSON.stringify(`./${arg}`)})`;
<del> })
<del> .join(", ")});`;
<del> } else {
<del> p = path.join(currentDirectory, module);
<del> content = fs.readFileSync(p, "utf-8");
<del> }
<del> if (p in requireCache) {
<del> return requireCache[p].exports;
<del> }
<del> const m = {
<del> exports: {}
<del> };
<del> requireCache[p] = m;
<del> let runInNewContext = false;
<del> const moduleScope = {
<del> require: _require.bind(null, path.dirname(p), options),
<del> importScripts: _require.bind(
<del> null,
<del> path.dirname(p),
<del> options
<del> ),
<del> module: m,
<del> exports: m.exports,
<del> __dirname: path.dirname(p),
<del> __filename: p,
<del> it: _it,
<del> beforeEach: _beforeEach,
<del> afterEach: _afterEach,
<del> expect,
<del> jest,
<del> _globalAssign: { expect },
<del> __STATS__: jsonStats,
<del> nsObj: m => {
<del> Object.defineProperty(m, Symbol.toStringTag, {
<del> value: "Module"
<del> });
<del> return m;
<del> }
<del> };
<del> if (
<del> options.target === "web" ||
<del> options.target === "webworker"
<del> ) {
<del> moduleScope.window = globalContext;
<del> moduleScope.self = globalContext;
<del> runInNewContext = true;
<del> }
<del> if (testConfig.moduleScope) {
<del> testConfig.moduleScope(moduleScope);
<del> }
<del> const args = Object.keys(moduleScope).join(", ");
<del> if (!runInNewContext)
<del> content = `Object.assign(global, _globalAssign); ${content}`;
<del> const code = `(function({${args}}) {${content}\n})`;
<del> const fn = runInNewContext
<del> ? vm.runInNewContext(code, globalContext, p)
<del> : vm.runInThisContext(code, p);
<del> fn.call(m.exports, moduleScope);
<del> return m.exports;
<del> } else if (
<del> testConfig.modules &&
<del> module in testConfig.modules
<del> ) {
<del> return testConfig.modules[module];
<del> } else return require(module);
<del> }
<ide> let filesCount = 0;
<ide>
<ide> if (testConfig.noTests) return process.nextTick(done);
<ide> const describeCases = config => {
<ide> const bundlePath = testConfig.findBundle(i, optionsArr[i]);
<ide> if (bundlePath) {
<ide> filesCount++;
<add> const globalContext = {
<add> console: console,
<add> expect: expect,
<add> setTimeout: setTimeout,
<add> clearTimeout: clearTimeout,
<add> document: new FakeDocument(),
<add> location: {
<add> href: "https://test.cases/path/index.html",
<add> origin: "https://test.cases",
<add> toString() {
<add> return "https://test.cases/path/index.html";
<add> }
<add> }
<add> };
<add>
<add> const requireCache = Object.create(null);
<add> // eslint-disable-next-line no-loop-func
<add> const _require = (currentDirectory, options, module) => {
<add> if (Array.isArray(module) || /^\.\.?\//.test(module)) {
<add> let content;
<add> let p;
<add> if (Array.isArray(module)) {
<add> p = path.join(currentDirectory, ".array-require.js");
<add> content = `module.exports = (${module
<add> .map(arg => {
<add> return `require(${JSON.stringify(`./${arg}`)})`;
<add> })
<add> .join(", ")});`;
<add> } else {
<add> p = path.join(currentDirectory, module);
<add> content = fs.readFileSync(p, "utf-8");
<add> }
<add> if (p in requireCache) {
<add> return requireCache[p].exports;
<add> }
<add> const m = {
<add> exports: {}
<add> };
<add> requireCache[p] = m;
<add> let runInNewContext = false;
<add> const moduleScope = {
<add> require: _require.bind(
<add> null,
<add> path.dirname(p),
<add> options
<add> ),
<add> importScripts: url => {
<add> _require(path.dirname(p), options, `./${url}`);
<add> },
<add> module: m,
<add> exports: m.exports,
<add> __dirname: path.dirname(p),
<add> __filename: p,
<add> it: _it,
<add> beforeEach: _beforeEach,
<add> afterEach: _afterEach,
<add> expect,
<add> jest,
<add> _globalAssign: { expect },
<add> __STATS__: jsonStats,
<add> nsObj: m => {
<add> Object.defineProperty(m, Symbol.toStringTag, {
<add> value: "Module"
<add> });
<add> return m;
<add> }
<add> };
<add> if (
<add> options.target === "web" ||
<add> options.target === "webworker"
<add> ) {
<add> moduleScope.window = globalContext;
<add> moduleScope.self = globalContext;
<add> runInNewContext = true;
<add> }
<add> if (testConfig.moduleScope) {
<add> testConfig.moduleScope(moduleScope);
<add> }
<add> const args = Object.keys(moduleScope).join(", ");
<add> if (!runInNewContext)
<add> content = `Object.assign(global, _globalAssign); ${content}`;
<add> const code = `(function({${args}}) {${content}\n})`;
<add> const fn = runInNewContext
<add> ? vm.runInNewContext(code, globalContext, p)
<add> : vm.runInThisContext(code, p);
<add> fn.call(m.exports, moduleScope);
<add> return m.exports;
<add> } else if (
<add> testConfig.modules &&
<add> module in testConfig.modules
<add> ) {
<add> return testConfig.modules[module];
<add> } else return require(module);
<add> };
<add>
<ide> results.push(
<ide> _require(outputDirectory, optionsArr[i], bundlePath)
<ide> );
<ide><path>test/configCases/target/chunk-loading-per-entry/chunk.js
<add>export default 42;
<ide><path>test/configCases/target/chunk-loading-per-entry/test.config.js
<add>module.exports = {
<add> findBundle: function (i, options) {
<add> return i === 0 ? "./web-0.js" : "./webworker-1.js";
<add> }
<add>};
<ide><path>test/configCases/target/chunk-loading-per-entry/web.js
<add>it("should allow to load a shared chunk in web", async () => {
<add> const promise = import(/* webpackChunkName: "chunk" */ "./chunk");
<add> expect(document.head._children).toHaveLength(1);
<add> const script = document.head._children[0];
<add> __non_webpack_require__("./chunk-0.js");
<add> script.onload();
<add>
<add> expect(await promise).toEqual(
<add> nsObj({
<add> default: 42
<add> })
<add> );
<add>});
<ide><path>test/configCases/target/chunk-loading-per-entry/webpack.config.js
<add>const base = {
<add> entry: {
<add> web: "./web",
<add> webworker: {
<add> import: "./webworker",
<add> chunkLoading: "import-scripts"
<add> }
<add> },
<add> output: {
<add> globalObject: "(typeof self === 'undefined' ? window : self)"
<add> },
<add> target: "web"
<add>};
<add>
<add>/** @type {import("../../../../").Configuration[]} */
<add>module.exports = [
<add> { ...base, output: { ...base.output, filename: "[name]-0.js" } },
<add> { ...base, output: { ...base.output, filename: "[name]-1.js" } }
<add>];
<ide><path>test/configCases/target/chunk-loading-per-entry/webworker.js
<add>it("should allow to load a shared chunk in a WebWorker", async () => {
<add> expect(await import(/* webpackChunkName: "chunk" */ "./chunk")).toEqual(
<add> nsObj({
<add> default: 42
<add> })
<add> );
<add>});
| 6
|
Ruby
|
Ruby
|
handle tap aliases
|
002f8f2eb79af9db832133ca785abf6097582e3a
|
<ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_class
<ide> end
<ide> end
<ide>
<del> @@aliases ||= Formula.aliases
<add> # core aliases + tap alias names + tap alias full name
<add> @@aliases ||= Formula.aliases + Formula.tap_aliases
<ide>
<ide> def audit_formula_name
<ide> return unless @strict
<ide> def audit_formula_name
<ide> name = formula.name
<ide> full_name = formula.full_name
<ide>
<del> if @@aliases.include? name
<add> if Formula.aliases.include? name
<ide> problem "Formula name conflicts with existing aliases."
<ide> return
<ide> end
| 1
|
Text
|
Text
|
add devenvironment link to contributing.md
|
9a4b0b982393e0612fef70c37a04654ea46b4c1d
|
<ide><path>CONTRIBUTING.md
<ide> Want to hack on Docker? Awesome! Here are instructions to get you started. They are probably not perfect, please let us know if anything feels
<ide> wrong or incomplete.
<ide>
<add>## Build Environment
<add>
<add>For instructions on setting up your development environment, please see our dedicated [dev environment setup docs](http://docs.docker.io/en/latest/contributing/devenvironment/).
<add>
<ide> ## Contribution guidelines
<ide>
<ide> ### Pull requests are always welcome
| 1
|
Python
|
Python
|
fix f401 flake8 warning (x88 / 116)
|
783a61699962f4b058688db21d417e1932423417
|
<ide><path>examples/distillation/distiller.py
<ide> import os
<ide> import time
<ide>
<del>import numpy as np
<ide> import torch
<ide> import torch.nn as nn
<ide> import torch.nn.functional as F
<ide> from torch.optim import AdamW
<ide> from torch.utils.data import BatchSampler, DataLoader, RandomSampler
<ide> from torch.utils.data.distributed import DistributedSampler
<del>from tqdm import tqdm, trange
<add>from tqdm import tqdm
<ide>
<ide> import psutil
<ide> from grouped_batch_sampler import GroupedBatchSampler, create_lengths_groups
<ide><path>examples/distillation/scripts/extract.py
<ide>
<ide> import torch
<ide>
<del>from transformers import BertForMaskedLM, GPT2LMHeadModel, RobertaForMaskedLM
<add>from transformers import GPT2LMHeadModel, RobertaForMaskedLM
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>examples/distillation/scripts/extract_distilbert.py
<ide>
<ide> import torch
<ide>
<del>from transformers import BertForMaskedLM, RobertaForMaskedLM
<add>from transformers import BertForMaskedLM
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>examples/run_bertology.py
<ide>
<ide> import numpy as np
<ide> import torch
<del>from torch.nn import CrossEntropyLoss, MSELoss
<del>from torch.utils.data import DataLoader, SequentialSampler, Subset, TensorDataset
<add>from torch.utils.data import DataLoader, SequentialSampler, Subset
<ide> from torch.utils.data.distributed import DistributedSampler
<ide> from tqdm import tqdm
<ide>
<ide><path>examples/run_squad.py
<ide>
<ide> import numpy as np
<ide> import torch
<del>from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
<add>from torch.utils.data import DataLoader, RandomSampler, SequentialSampler
<ide> from torch.utils.data.distributed import DistributedSampler
<ide> from tqdm import tqdm, trange
<ide>
<ide><path>examples/run_tf_ner.py
<ide> # coding=utf-8
<del>import _pickle as pickle
<ide> import collections
<ide> import datetime
<ide> import glob
<ide><path>templates/adding_a_new_model/configuration_xxx.py
<ide>
<ide> import logging
<ide>
<del>import six
<del>
<ide> from .configuration_utils import PretrainedConfig
<ide>
<ide>
<ide><path>templates/adding_a_new_model/modeling_tf_xxx.py
<ide>
<ide> from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<del>import itertools
<ide> import logging
<ide>
<del>import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> from .configuration_xxx import XxxConfig
<ide><path>templates/adding_a_new_model/modeling_xxx.py
<ide>
<ide> from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<del>import itertools
<ide> import logging
<ide> import os
<ide>
<ide>
<ide> from .configuration_xxx import XxxConfig
<ide> from .file_utils import add_start_docstrings
<del>from .modeling_utils import PreTrainedModel, prune_linear_layer
<add>from .modeling_utils import PreTrainedModel
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>templates/adding_a_new_model/tests/modeling_tf_xxx_test.py
<ide>
<ide>
<ide> if is_tf_available():
<del> import tensorflow as tf
<ide> from transformers.modeling_tf_xxx import (
<ide> TFXxxModel,
<ide> TFXxxForMaskedLM,
<ide><path>templates/adding_a_new_model/tokenization_xxx.py
<ide> import collections
<ide> import logging
<ide> import os
<del>import unicodedata
<ide> from io import open
<ide>
<ide> from .tokenization_utils import PreTrainedTokenizer
<ide><path>transformers/commands/convert.py
<ide> from argparse import ArgumentParser, Namespace
<ide> from logging import getLogger
<ide>
<del>from transformers import AutoModel, AutoTokenizer
<ide> from transformers.commands import BaseTransformersCLICommand
<ide>
<ide>
<ide><path>transformers/configuration_t5.py
<ide>
<ide> import logging
<ide>
<del>import six
<del>
<ide> from .configuration_utils import PretrainedConfig
<ide>
<ide>
<ide><path>transformers/convert_pytorch_checkpoint_to_tf2.py
<ide> import logging
<ide> import os
<ide>
<del>import tensorflow as tf
<del>
<ide> from transformers import (
<ide> ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
<ide> BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
<ide><path>transformers/convert_roberta_original_pytorch_checkpoint_to_pytorch.py
<ide> import logging
<ide> import pathlib
<ide>
<del>import numpy as np
<ide> import torch
<ide> from packaging import version
<ide>
<ide><path>transformers/data/metrics/squad_metrics.py
<ide> import string
<ide> from io import open
<ide>
<del>from tqdm import tqdm
<del>
<del>from transformers.tokenization_bert import BasicTokenizer, whitespace_tokenize
<add>from transformers.tokenization_bert import BasicTokenizer
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>transformers/data/processors/squad.py
<ide> from tqdm import tqdm
<ide>
<ide> from ...file_utils import is_tf_available, is_torch_available
<del>from ...tokenization_bert import BasicTokenizer, whitespace_tokenize
<del>from .utils import DataProcessor, InputExample, InputFeatures
<add>from ...tokenization_bert import whitespace_tokenize
<add>from .utils import DataProcessor
<ide>
<ide>
<ide> if is_torch_available():
<ide><path>transformers/hf_api.py
<ide>
<ide> import requests
<ide> import six
<del>from requests.exceptions import HTTPError
<ide> from tqdm import tqdm
<ide>
<ide>
<ide><path>transformers/modeling_auto.py
<ide> XLMRobertaConfig,
<ide> XLNetConfig,
<ide> )
<del>from .file_utils import add_start_docstrings
<ide> from .modeling_albert import (
<ide> ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP,
<ide> AlbertForMaskedLM,
<ide> )
<ide> from .modeling_t5 import T5_PRETRAINED_MODEL_ARCHIVE_MAP, T5Model, T5WithLMHeadModel
<ide> from .modeling_transfo_xl import TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP, TransfoXLLMHeadModel, TransfoXLModel
<del>from .modeling_utils import PreTrainedModel, SequenceSummary
<ide> from .modeling_xlm import (
<ide> XLM_PRETRAINED_MODEL_ARCHIVE_MAP,
<ide> XLMForQuestionAnswering,
<ide><path>transformers/modeling_ctrl.py
<ide> import torch
<ide> import torch.nn as nn
<ide> from torch.nn import CrossEntropyLoss
<del>from torch.nn.parameter import Parameter
<ide>
<ide> from .configuration_ctrl import CTRLConfig
<ide> from .file_utils import add_start_docstrings
<del>from .modeling_utils import Conv1D, PreTrainedModel, SequenceSummary, prune_conv1d_layer
<add>from .modeling_utils import Conv1D, PreTrainedModel
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>transformers/modeling_distilbert.py
<ide> from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<ide> import copy
<del>import itertools
<ide> import logging
<ide> import math
<ide>
<ide><path>transformers/modeling_encoder_decoder.py
<ide>
<ide> import torch
<ide> from torch import nn
<del>from tqdm import trange
<ide>
<ide> from .modeling_auto import AutoModel, AutoModelWithLMHead
<ide>
<ide><path>transformers/modeling_gpt2.py
<ide> import torch
<ide> import torch.nn as nn
<ide> from torch.nn import CrossEntropyLoss
<del>from torch.nn.parameter import Parameter
<ide>
<ide> from .configuration_gpt2 import GPT2Config
<ide> from .file_utils import add_start_docstrings
<ide> def load_tf_weights_in_gpt2(model, config, gpt2_checkpoint_path):
<ide> """
<ide> try:
<ide> import re
<del> import numpy as np
<ide> import tensorflow as tf
<ide> except ImportError:
<ide> logger.error(
<ide><path>transformers/modeling_openai.py
<ide> import torch
<ide> import torch.nn as nn
<ide> from torch.nn import CrossEntropyLoss
<del>from torch.nn.parameter import Parameter
<ide>
<ide> from .configuration_openai import OpenAIGPTConfig
<ide> from .file_utils import add_start_docstrings
<ide><path>transformers/modeling_t5.py
<ide> import torch
<ide> import torch.nn.functional as F
<ide> from torch import nn
<del>from torch.nn import CrossEntropyLoss, MSELoss
<add>from torch.nn import CrossEntropyLoss
<ide>
<ide> from .configuration_t5 import T5Config
<ide> from .file_utils import DUMMY_INPUTS, DUMMY_MASK, add_start_docstrings
<ide><path>transformers/modeling_tf_auto.py
<ide> XLMConfig,
<ide> XLNetConfig,
<ide> )
<del>from .file_utils import add_start_docstrings
<ide> from .modeling_tf_albert import (
<ide> TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP,
<ide> TFAlbertForMaskedLM,
<ide><path>transformers/modeling_tf_ctrl.py
<ide>
<ide> from .configuration_ctrl import CTRLConfig
<ide> from .file_utils import add_start_docstrings
<del>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, get_initializer, shape_list
<add>from .modeling_tf_utils import TFPreTrainedModel, TFSharedEmbeddings, shape_list
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>transformers/modeling_tf_distilbert.py
<ide> """
<ide> from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<del>import itertools
<ide> import logging
<ide> import math
<ide>
<ide><path>transformers/modeling_tf_pytorch_utils.py
<ide> def load_pytorch_checkpoint_in_tf2_model(tf_model, pytorch_checkpoint_path, tf_i
<ide> """ Load pytorch checkpoints in a TF 2.0 model
<ide> """
<ide> try:
<del> import tensorflow as tf
<del> import torch
<add> import tensorflow as tf # noqa: F401
<add> import torch # noqa: F401
<ide> except ImportError as e:
<ide> logger.error(
<ide> "Loading a PyTorch model in TensorFlow, requires both PyTorch and TensorFlow to be installed. Please see "
<ide> def load_pytorch_weights_in_tf2_model(tf_model, pt_state_dict, tf_inputs=None, a
<ide> """ Load pytorch state_dict in a TF 2.0 model.
<ide> """
<ide> try:
<del> import torch
<del> import tensorflow as tf
<add> import torch # noqa: F401
<add> import tensorflow as tf # noqa: F401
<ide> from tensorflow.python.keras import backend as K
<ide> except ImportError as e:
<ide> logger.error(
<ide> def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs
<ide> (see https://github.com/tensorflow/tensorflow/blob/ee16fcac960ae660e0e4496658a366e2f745e1f0/tensorflow/python/keras/engine/network.py#L1352-L1357).
<ide> """
<ide> try:
<del> import tensorflow as tf
<del> import torch
<add> import tensorflow as tf # noqa: F401
<add> import torch # noqa: F401
<ide> except ImportError as e:
<ide> logger.error(
<ide> "Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see "
<ide> def load_tf2_weights_in_pytorch_model(pt_model, tf_weights, allow_missing_keys=F
<ide> """ Load TF2.0 symbolic weights in a PyTorch model
<ide> """
<ide> try:
<del> import tensorflow as tf
<del> import torch
<add> import tensorflow as tf # noqa: F401
<add> import torch # noqa: F401
<ide> except ImportError as e:
<ide> logger.error(
<ide> "Loading a TensorFlow model in PyTorch, requires both PyTorch and TensorFlow to be installed. Please see "
<ide><path>transformers/modeling_tf_roberta.py
<ide>
<ide> from .configuration_roberta import RobertaConfig
<ide> from .file_utils import add_start_docstrings
<del>from .modeling_tf_bert import TFBertEmbeddings, TFBertMainLayer, gelu, gelu_new
<add>from .modeling_tf_bert import TFBertEmbeddings, TFBertMainLayer, gelu
<ide> from .modeling_tf_utils import TFPreTrainedModel, get_initializer, shape_list
<ide>
<ide>
<ide><path>transformers/modeling_tf_transfo_xl.py
<ide>
<ide> import logging
<ide>
<del>import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> from .configuration_transfo_xl import TransfoXLConfig
<ide> from .file_utils import add_start_docstrings
<ide> from .modeling_tf_transfo_xl_utilities import TFAdaptiveSoftmaxMask
<del>from .modeling_tf_utils import TFConv1D, TFPreTrainedModel, TFSequenceSummary, get_initializer, shape_list
<add>from .modeling_tf_utils import TFPreTrainedModel, get_initializer, shape_list
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>transformers/modeling_tf_transfo_xl_utilities.py
<ide> """
<ide>
<ide>
<del>import numpy as np
<ide> import tensorflow as tf
<ide>
<ide> from .modeling_tf_utils import shape_list
<ide><path>transformers/modeling_transfo_xl.py
<ide> import torch
<ide> import torch.nn as nn
<ide> import torch.nn.functional as F
<del>from torch.nn import CrossEntropyLoss
<del>from torch.nn.parameter import Parameter
<ide>
<ide> from .configuration_transfo_xl import TransfoXLConfig
<ide> from .file_utils import add_start_docstrings
<ide> from .modeling_transfo_xl_utilities import LogUniformSampler, ProjectedAdaptiveLogSoftmax, sample_logits
<del>from .modeling_utils import Conv1D, PreTrainedModel, SequenceSummary, prune_conv1d_layer
<add>from .modeling_utils import PreTrainedModel
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>transformers/modeling_transfo_xl_utilities.py
<ide> """
<ide>
<ide>
<del>import numpy as np
<ide> import torch
<ide> import torch.nn as nn
<ide> import torch.nn.functional as F
<ide><path>transformers/modeling_utils.py
<ide> import logging
<ide> import os
<ide>
<del>import six
<ide> import torch
<ide> from torch import nn
<ide> from torch.nn import CrossEntropyLoss
<ide><path>transformers/pipelines.py
<ide> import sys
<ide> from abc import ABC, abstractmethod
<ide> from contextlib import contextmanager
<del>from itertools import groupby
<ide> from os.path import abspath, exists
<ide> from typing import Dict, List, Optional, Tuple, Union
<ide>
<ide><path>transformers/tests/modeling_auto_test.py
<ide> )
<ide> from transformers.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP
<ide>
<del> from .modeling_common_test import CommonTestCases, ids_tensor
<del> from .configuration_common_test import ConfigTester
<del>
<ide>
<ide> @require_torch
<ide> class AutoModelTest(unittest.TestCase):
<ide><path>transformers/tests/modeling_distilbert_test.py
<ide>
<ide> from .configuration_common_test import ConfigTester
<ide> from .modeling_common_test import CommonTestCases, ids_tensor
<del>from .utils import CACHE_DIR, require_torch, slow, torch_device
<add>from .utils import require_torch, torch_device
<ide>
<ide>
<ide> if is_torch_available():
<ide><path>transformers/tests/modeling_t5_test.py
<ide> from transformers import is_torch_available
<ide>
<ide> from .configuration_common_test import ConfigTester
<del>from .modeling_common_test import CommonTestCases, floats_tensor, ids_tensor
<del>from .utils import CACHE_DIR, require_torch, slow, torch_device
<add>from .modeling_common_test import CommonTestCases, ids_tensor
<add>from .utils import CACHE_DIR, require_torch, slow
<ide>
<ide>
<ide> if is_torch_available():
<ide><path>transformers/tests/modeling_tf_albert_test.py
<ide>
<ide>
<ide> if is_tf_available():
<del> import tensorflow as tf
<ide> from transformers.modeling_tf_albert import (
<ide> TFAlbertModel,
<ide> TFAlbertForMaskedLM,
<ide><path>transformers/tests/modeling_tf_auto_test.py
<ide> TFAutoModelForQuestionAnswering,
<ide> TFBertForQuestionAnswering,
<ide> )
<del> from transformers.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP
<del>
<del> from .modeling_common_test import CommonTestCases, ids_tensor
<del> from .configuration_common_test import ConfigTester
<ide>
<ide>
<ide> @require_tf
<ide><path>transformers/tests/modeling_tf_common_test.py
<ide>
<ide> from transformers import is_tf_available, is_torch_available
<ide>
<del>from .utils import require_tf, slow
<add>from .utils import require_tf
<ide>
<ide>
<ide> if is_tf_available():
<ide> import tensorflow as tf
<ide> import numpy as np
<del> from transformers import TFPreTrainedModel
<ide>
<ide> # from transformers.modeling_bert import BertModel, BertConfig, BERT_PRETRAINED_MODEL_ARCHIVE_MAP
<ide>
<ide><path>transformers/tests/modeling_tf_ctrl_test.py
<ide>
<ide>
<ide> if is_tf_available():
<del> import tensorflow as tf
<ide> from transformers.modeling_tf_ctrl import TFCTRLModel, TFCTRLLMHeadModel, TF_CTRL_PRETRAINED_MODEL_ARCHIVE_MAP
<ide>
<ide>
<ide><path>transformers/tests/modeling_tf_distilbert_test.py
<ide>
<ide> from .configuration_common_test import ConfigTester
<ide> from .modeling_tf_common_test import TFCommonTestCases, ids_tensor
<del>from .utils import CACHE_DIR, require_tf, slow
<add>from .utils import require_tf
<ide>
<ide>
<ide> if is_tf_available():
<del> import tensorflow as tf
<ide> from transformers.modeling_tf_distilbert import (
<ide> TFDistilBertModel,
<ide> TFDistilBertForMaskedLM,
<ide><path>transformers/tests/modeling_tf_t5_test.py
<ide>
<ide>
<ide> if is_tf_available():
<del> import tensorflow as tf
<del> from transformers.modeling_tf_t5 import TFT5Model, TFT5WithLMHeadModel, TF_T5_PRETRAINED_MODEL_ARCHIVE_MAP
<add> from transformers.modeling_tf_t5 import TFT5Model, TFT5WithLMHeadModel
<ide>
<ide>
<ide> @require_tf
<ide><path>transformers/tests/tokenization_albert_test.py
<ide> import os
<ide> import unittest
<ide>
<del>from transformers.tokenization_albert import SPIECE_UNDERLINE, AlbertTokenizer
<add>from transformers.tokenization_albert import AlbertTokenizer
<ide>
<ide> from .tokenization_tests_commons import CommonTestCases
<ide>
<ide><path>transformers/tests/tokenization_distilbert_test.py
<ide> from transformers.tokenization_distilbert import DistilBertTokenizer
<ide>
<ide> from .tokenization_bert_test import BertTokenizationTest
<del>from .tokenization_tests_commons import CommonTestCases
<ide> from .utils import slow
<ide>
<ide>
<ide><path>transformers/tests/tokenization_transfo_xl_test.py
<ide>
<ide>
<ide> if is_torch_available():
<del> import torch
<ide> from transformers.tokenization_transfo_xl import TransfoXLTokenizer, VOCAB_FILES_NAMES
<ide>
<ide>
<ide><path>transformers/tokenization_bert_japanese.py
<ide> import six
<ide>
<ide> from .tokenization_bert import BasicTokenizer, BertTokenizer, WordpieceTokenizer, load_vocab
<del>from .tokenization_utils import PreTrainedTokenizer
<ide>
<ide>
<ide> logger = logging.getLogger(__name__)
<ide><path>transformers/tokenization_distilbert.py
<ide> from __future__ import absolute_import, division, print_function, unicode_literals
<ide>
<ide> import logging
<del>import unicodedata
<ide>
<ide> from .tokenization_bert import BertTokenizer
<ide>
<ide><path>transformers/tokenization_roberta.py
<ide>
<ide> import logging
<ide>
<del>import regex as re
<del>
<ide> from .tokenization_gpt2 import GPT2Tokenizer
<ide>
<ide>
<ide><path>transformers/tokenization_xlm.py
<ide>
<ide> import sacremoses as sm
<ide>
<del>from .tokenization_bert import BasicTokenizer
<ide> from .tokenization_utils import PreTrainedTokenizer
<ide>
<ide>
| 52
|
Python
|
Python
|
fix formatting and consistency
|
1436b9f15a5cd9ba1576281636ef528e1de763c3
|
<ide><path>spacy/es/language_data.py
<ide> def get_time_exc(hours):
<ide>
<ide>
<ide> TOKENIZER_EXCEPTIONS = dict(TOKENIZER_EXCEPTIONS)
<del>update_exc(TOKENIZER_EXCEPTIONS, get_time_exc(range(1, 12 + 1)))
<ide> STOP_WORDS = set(STOP_WORDS)
<ide>
<del>
<ide> update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(ORTH_ONLY))
<add>update_exc(TOKENIZER_EXCEPTIONS, get_time_exc(range(1, 12 + 1)))
<ide> update_exc(TOKENIZER_EXCEPTIONS, strings_to_exc(base.EMOTICONS))
<ide>
<del>
<ide> __all__ = ["TOKENIZER_EXCEPTIONS", "STOP_WORDS"]
| 1
|
Python
|
Python
|
update trove classifiers
|
66ee1969751e1bf1d5fada15e6a1e7212cab58d9
|
<ide><path>setup.py
<ide> def run(self, *args, **kwargs):
<ide> test_suite="nose.collector",
<ide> classifiers=[
<ide> "Development Status :: 5 - Production/Stable",
<del> "Operating System :: OS Independent",
<del> "Environment :: No Input/Output (Daemon)",
<del> "Intended Audience :: Developers",
<ide> "License :: OSI Approved :: BSD License",
<del> "Operating System :: POSIX",
<del> "Topic :: Communications",
<ide> "Topic :: System :: Distributed Computing",
<del> "Topic :: Software Development :: Libraries :: Python Modules",
<add> "Topic :: Software Development :: Object Brokering",
<add> "Intended Audience :: Developers",
<add> "Intended Audience :: Information Technology",
<add> "Intended Audience :: Science/Research",
<add> "Intended Audience :: Financial and Insurance Industry",
<add> "Intended Audience :: Healthcare Industry",
<add> "Environment :: No Input/Output (Daemon)",
<add> "Environment :: Console",
<ide> "Programming Language :: Python",
<ide> "Programming Language :: Python :: 2",
<ide> "Programming Language :: Python :: 2.5",
<ide> "Programming Language :: Python :: 2.6",
<ide> "Programming Language :: Python :: 2.7",
<ide> "Programming Language :: Python :: 3",
<add> "Programming Language :: Python :: 3.2",
<ide> "Programming Language :: Python :: Implementation :: CPython",
<ide> "Programming Language :: Python :: Implementation :: PyPy",
<ide> "Programming Language :: Python :: Implementation :: Jython",
<add> "Operating System :: OS Independent",
<add> "Operating System :: POSIX",
<add> "Operating System :: Microsoft :: Windows",
<add> "Operating System :: MacOS :: MacOS X",
<ide> ],
<ide> entry_points={
<ide> 'console_scripts': console_scripts,
| 1
|
Text
|
Text
|
fix script link
|
43b860a8728facf8efe16bb145060a152c929bf7
|
<ide><path>threejs/lessons/ru/threejs-optimize-lots-of-objects.md
<ide> scene.add(mesh);
<ide> [другой статье](threejs-optimize-lots-of-objects-animated.html).
<ide>
<ide> <canvas id="c"></canvas>
<del><script type="module" src="resources/threejs-lots-of-objects.js"></script>
<add><script type="module" src="../resources/threejs-lots-of-objects.js"></script>
| 1
|
Javascript
|
Javascript
|
remove unneeded classnamebinding tests
|
60dddda0f54b1849988c9823ca11d869cf8180fe
|
<ide><path>packages/ember-views/tests/views/view/actions_test.js
<del>import run from 'ember-metal/run_loop';
<del>import { Mixin } from 'ember-metal/mixin';
<del>import Controller from 'ember-runtime/controllers/controller';
<del>import EmberObject from 'ember-runtime/system/object';
<del>import View from 'ember-views/views/view';
<del>
<del>let view;
<del>
<del>QUnit.module('View action handling', {
<del> teardown() {
<del> run(() => {
<del> if (view) { view.destroy(); }
<del> });
<del> }
<del>});
<del>
<del>QUnit.test('Action can be handled by a function on actions object', function() {
<del> expect(1);
<del> view = View.extend({
<del> actions: {
<del> poke() {
<del> ok(true, 'poked');
<del> }
<del> }
<del> }).create();
<del> view.send('poke');
<del>});
<del>
<del>QUnit.test('A handled action can be bubbled to the target for continued processing', function() {
<del> expect(2);
<del> view = View.extend({
<del> actions: {
<del> poke() {
<del> ok(true, 'poked 1');
<del> return true;
<del> }
<del> },
<del> target: Controller.extend({
<del> actions: {
<del> poke() {
<del> ok(true, 'poked 2');
<del> }
<del> }
<del> }).create()
<del> }).create();
<del> view.send('poke');
<del>});
<del>
<del>QUnit.test('Action can be handled by a superclass\' actions object', function() {
<del> expect(4);
<del>
<del> let SuperView = View.extend({
<del> actions: {
<del> foo() {
<del> ok(true, 'foo');
<del> },
<del> bar(msg) {
<del> equal(msg, 'HELLO');
<del> }
<del> }
<del> });
<del>
<del> let BarViewMixin = Mixin.create({
<del> actions: {
<del> bar(msg) {
<del> equal(msg, 'HELLO');
<del> this._super(msg);
<del> }
<del> }
<del> });
<del>
<del> let IndexView = SuperView.extend(BarViewMixin, {
<del> actions: {
<del> baz() {
<del> ok(true, 'baz');
<del> }
<del> }
<del> });
<del>
<del> view = IndexView.create();
<del> view.send('foo');
<del> view.send('bar', 'HELLO');
<del> view.send('baz');
<del>});
<del>
<del>QUnit.test('Actions cannot be provided at create time', function() {
<del> expectAssertion(() => {
<del> view = View.create({
<del> actions: {
<del> foo() {
<del> ok(true, 'foo');
<del> }
<del> }
<del> });
<del> });
<del> // but should be OK on an object that doesn't mix in Ember.ActionHandler
<del> EmberObject.create({
<del> actions: ['foo']
<del> });
<del>});
<ide><path>packages/ember-views/tests/views/view/class_name_bindings_test.js
<del>import run from 'ember-metal/run_loop';
<del>import { isWatching } from 'ember-metal/watching';
<del>import EmberView from 'ember-views/views/view';
<del>
<del>let view;
<del>
<del>QUnit.module('EmberView - Class Name Bindings', {
<del> teardown() {
<del> run(() => view.destroy());
<del> }
<del>});
<del>
<del>QUnit.skip('classNameBindings lifecycle test', function() {
<del> run(() => {
<del> view = EmberView.create({
<del> classNameBindings: ['priority'],
<del> priority: 'high'
<del> });
<del> });
<del>
<del> equal(isWatching(view, 'priority'), false);
<del>
<del> run(() => view.createElement());
<del>
<del> equal(view.$().attr('class'), 'ember-view high');
<del> equal(isWatching(view, 'priority'), true);
<del>
<del> run(() => {
<del> view.destroyElement();
<del> view.set('priority', 'low');
<del> });
<del>
<del> equal(isWatching(view, 'priority'), false);
<del>});
<del>
<del>
| 2
|
Javascript
|
Javascript
|
use updated monaco api
|
457dbe13be6a9afddd23945c381499cc9aeb1152
|
<ide><path>client/src/templates/Challenges/classic/Editor.js
<ide> class Editor extends Component {
<ide> this.props.setEditorFocusability(true)
<ide> );
<ide> // This is to persist changes caused by the accessibility tooltip.
<del> // Unfortunately it relies on Monaco's implementation details
<del> this._editor.onDidChangeConfiguration(() => {
<add> this._editor.onDidChangeConfiguration(event => {
<ide> if (
<del> this._editor.getConfiguration().accessibilitySupport === 2 &&
<add> event.hasChanged(monaco.editor.EditorOption.accessibilitySupport) &&
<add> editor.getRawOptions().accessibilitySupport === 'on' &&
<ide> !this.props.inAccessibilityMode
<ide> ) {
<ide> this.props.setAccessibilityMode(true);
| 1
|
Go
|
Go
|
avoid testexecwindowsopenhandles timing out
|
f8821202c649a19cbec063399174f03c3f66527c
|
<ide><path>integration-cli/docker_cli_exec_test.go
<ide> func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) {
<ide> exec <- true
<ide> }()
<ide>
<add> count := 0
<ide> for {
<ide> top := make(chan string)
<ide> var out string
<ide> func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) {
<ide>
<ide> select {
<ide> case <-time.After(time.Second * 5):
<del> c.Error("timed out waiting for top while exec is exiting")
<add> c.Fatal("timed out waiting for top while exec is exiting")
<ide> case out = <-top:
<ide> break
<ide> }
<ide> func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) {
<ide> // The initial exec process (cmd.exe) has exited, and both sleeps are currently running
<ide> break
<ide> }
<add> count++
<add> if count >= 30 {
<add> c.Fatal("too many retries")
<add> }
<ide> time.Sleep(1 * time.Second)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) {
<ide>
<ide> select {
<ide> case <-time.After(time.Second * 5):
<del> c.Error("timed out waiting for inspect while exec is exiting")
<add> c.Fatal("timed out waiting for inspect while exec is exiting")
<ide> case <-inspect:
<ide> break
<ide> }
<ide> func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) {
<ide> // The exec should exit when the background sleep exits
<ide> select {
<ide> case <-time.After(time.Second * 15):
<del> c.Error("timed out waiting for async exec to exit")
<add> c.Fatal("timed out waiting for async exec to exit")
<ide> case <-exec:
<ide> // Ensure the background sleep has actually exited
<ide> out, _ := dockerCmd(c, "top", "test")
| 1
|
Javascript
|
Javascript
|
add buffer slice utf-8 test
|
0abcf44d6b1a31250272eb4a4e24192eeba53db1
|
<ide><path>test/parallel/test-buffer.js
<ide> writeTest.write('e', 3, 'ascii');
<ide> writeTest.write('j', 'ascii', 4);
<ide> assert.equal(writeTest.toString(), 'nodejs');
<ide>
<add>// ASCII slice test
<add>
<ide> var asciiString = 'hello world';
<ide> var offset = 100;
<ide>
<ide> for (var i = 0; i < asciiString.length; i++) {
<ide> assert.equal(sliceA[i], sliceB[i]);
<ide> }
<ide>
<del>// TODO utf8 slice tests
<add>// UTF-8 slice test
<add>
<add>var utf8String = '¡hέlló wôrld!';
<add>var offset = 100;
<add>
<add>b.write(utf8String, 0, Buffer.byteLength(utf8String), 'utf8');
<add>var utf8Slice = b.toString('utf8', 0, Buffer.byteLength(utf8String));
<add>assert.equal(utf8String, utf8Slice);
<ide>
<add>var written = b.write(utf8String, offset, 'utf8');
<add>assert.equal(Buffer.byteLength(utf8String), written);
<add>utf8Slice = b.toString('utf8', offset, offset + Buffer.byteLength(utf8String));
<add>assert.equal(utf8String, utf8Slice);
<add>
<add>var sliceA = b.slice(offset, offset + Buffer.byteLength(utf8String));
<add>var sliceB = b.slice(offset, offset + Buffer.byteLength(utf8String));
<add>for (var i = 0; i < Buffer.byteLength(utf8String); i++) {
<add> assert.equal(sliceA[i], sliceB[i]);
<add>}
<ide>
<ide> var slice = b.slice(100, 150);
<ide> assert.equal(50, slice.length);
| 1
|
PHP
|
PHP
|
improve error messages when replies run out
|
969d40df5076c6adda32a7f032b80732d6b59d67
|
<ide><path>src/TestSuite/ConsoleIntegrationTestTrait.php
<ide> use Cake\TestSuite\Constraint\Console\ExitCode;
<ide> use Cake\TestSuite\Stub\ConsoleInput;
<ide> use Cake\TestSuite\Stub\ConsoleOutput;
<add>use Cake\TestSuite\Stub\MissingConsoleInputException;
<ide>
<ide> /**
<ide> * A test case class intended to make integration tests of cake console commands
<ide> public function exec($command, array $input = [])
<ide>
<ide> try {
<ide> $this->_exitCode = $runner->run($args, $io);
<add> } catch (MissingConsoleInputException $e) {
<add> $messages = $this->_out->messages();
<add> if (count($messages)) {
<add> $e->setQuestion($messages[count($messages) - 1]);
<add> }
<add> throw $e;
<ide> } catch (StopException $exception) {
<ide> $this->_exitCode = $exception->getCode();
<ide> }
<ide><path>src/TestSuite/Stub/ConsoleInput.php
<ide> namespace Cake\TestSuite\Stub;
<ide>
<ide> use Cake\Console\ConsoleInput as ConsoleInputBase;
<del>use Cake\Console\Exception\ConsoleException;
<add>use Cake\TestSuite\Stub\MissingConsoleInputException;
<ide> use NumberFormatter;
<ide>
<ide> /**
<ide> public function read()
<ide>
<ide> $replies = implode(', ', $this->replies);
<ide> $message = "There are no more input replies available. This is the {$nth} read operation, " .
<del> "only {$total} replies were set. The provided replies are: {$replies}";
<del> throw new ConsoleException($message);
<add> "only {$total} replies were set.\nThe provided replies are: {$replies}";
<add> throw new MissingConsoleInputException($message);
<ide> }
<ide>
<ide> return $this->replies[$this->currentIndex];
<ide><path>src/TestSuite/Stub/MissingConsoleInputException.php
<add><?php
<add>/**
<add> * CakePHP : Rapid Development Framework (https://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<add> * @link https://cakephp.org CakePHP Project
<add> * @license https://opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\TestSuite\Stub;
<add>
<add>use RuntimeException;
<add>
<add>/**
<add> * Exception class used to indicate missing console input.
<add> */
<add>class MissingConsoleInputException extends RuntimeException
<add>{
<add> /**
<add> * Update the exception message with the question text
<add> *
<add> * @param string $question The question text.
<add> * @return void
<add> */
<add> public function setQuestion($question)
<add> {
<add> $this->message .= "\nThe question asked was: " . $question;
<add> }
<add>}
<ide><path>tests/TestCase/TestSuite/ConsoleIntegrationTestTraitTest.php
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\Configure;
<ide> use Cake\TestSuite\ConsoleIntegrationTestCase;
<add>use Cake\TestSuite\Stub\MissingConsoleInputException;
<ide> use PHPUnit\Framework\AssertionFailedError;
<ide>
<ide> class ConsoleIntegrationTestTraitTest extends ConsoleIntegrationTestCase
<ide> public function testExecWithInput()
<ide> */
<ide> public function testExecWithMissingInput()
<ide> {
<del> $this->expectException(ConsoleException::class);
<add> $this->expectException(MissingConsoleInputException::class);
<ide> $this->expectExceptionMessage('no more input');
<ide> $this->exec('integration bridge', ['cake']);
<ide> }
| 4
|
Ruby
|
Ruby
|
remove final reference to formula_exist
|
ba63619f8efacd04ca6e75b593fec3fc95f56edb
|
<ide><path>Library/Homebrew/test/spec_helper.rb
<ide>
<ide> require "test/support/helper/spec/shared_context/homebrew_cask" if OS.mac?
<ide> require "test/support/helper/spec/shared_context/integration_test"
<del>require "test/support/helper/spec/shared_examples/formulae_exist"
<ide>
<ide> TEST_DIRECTORIES = [
<ide> CoreTap.instance.path/"Formula",
| 1
|
Go
|
Go
|
avoid jsonlog allocation in loop
|
473bb5274ce7a520bc73ccb3529f99729a799062
|
<ide><path>pkg/jsonlog/jsonlog.go
<ide> func (jl *JSONLog) Format(format string) (string, error) {
<ide> return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
<ide> }
<ide>
<add>func (jl *JSONLog) Reset() {
<add> jl.Log = ""
<add> jl.Stream = ""
<add> jl.Created = time.Time{}
<add>}
<add>
<ide> func WriteLog(src io.Reader, dst io.Writer, format string) error {
<ide> dec := json.NewDecoder(src)
<add> l := &JSONLog{}
<ide> for {
<del> l := &JSONLog{}
<del>
<ide> if err := dec.Decode(l); err == io.EOF {
<ide> return nil
<ide> } else if err != nil {
<ide> func WriteLog(src io.Reader, dst io.Writer, format string) error {
<ide> if _, err := io.WriteString(dst, line); err != nil {
<ide> return err
<ide> }
<add> l.Reset()
<ide> }
<ide> }
| 1
|
Text
|
Text
|
follow docs convention for notes
|
ee325eb5d5fbb91de7e6bbd7cfab4e7d30287821
|
<ide><path>docs/docs/09.5-clone-with-props.md
<ide> In rare situations a component may want to change the props of a component that
<ide>
<ide> Do a shallow copy of `component` and merge any props provided by `extraProps`. Props are merged in the same manner as [`transferPropsTo()`](/react/docs/component-api.html#transferpropsto), so props like `className` will be merged intelligently.
<ide>
<del>**NOTE:** `cloneWithProps` does not transfer the `key` prop to the cloned component. If you wish to preserve the key, add it to the `extraProps` object:
<del>
<del>```js
<del>var clonedComponent = cloneWithProps(originalComponent, { key : originalComponent.props.key });
<del>```
<add>> Note:
<add>>
<add>> `cloneWithProps` does not transfer the `key` prop to the cloned component. If you wish to preserve the key, add it to the `extraProps` object:
<add>> ```js
<add>> var clonedComponent = cloneWithProps(originalComponent, { key : originalComponent.props.key });
<add>> ```
| 1
|
Javascript
|
Javascript
|
extract appcontainer into its own module
|
f26c908638cbf7a7708fc092e531447d4f26c4e5
|
<ide><path>Libraries/ReactIOS/AppContainer.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> *
<add> * @providesModule AppContainer
<add> * @noflow
<add> */
<add>
<add>'use strict';
<add>
<add>var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<add>var React = require('React');
<add>var ReactNative = require('ReactNative');
<add>var Subscribable = require('Subscribable');
<add>var StyleSheet = require('StyleSheet');
<add>var View = require('View');
<add>
<add>var Inspector = __DEV__ ? require('Inspector') : null;
<add>var YellowBox = __DEV__ ? require('YellowBox') : null;
<add>
<add>var AppContainer = React.createClass({
<add> mixins: [Subscribable.Mixin],
<add>
<add> getInitialState: function() {
<add> return { inspector: null, mainKey: 1 };
<add> },
<add>
<add> toggleElementInspector: function() {
<add> var inspector = !__DEV__ || this.state.inspector
<add> ? null
<add> : <Inspector
<add> rootTag={this.props.rootTag}
<add> inspectedViewTag={ReactNative.findNodeHandle(this.refs.main)}
<add> onRequestRerenderApp={(updateInspectedViewTag) => {
<add> this.setState(
<add> (s) => ({mainKey: s.mainKey + 1}),
<add> () => updateInspectedViewTag(ReactNative.findNodeHandle(this.refs.main))
<add> );
<add> }}
<add> />;
<add> this.setState({inspector});
<add> },
<add>
<add> componentDidMount: function() {
<add> this.addListenerOn(
<add> RCTDeviceEventEmitter,
<add> 'toggleElementInspector',
<add> this.toggleElementInspector
<add> );
<add> },
<add>
<add> render: function() {
<add> let yellowBox = null;
<add> if (__DEV__) {
<add> yellowBox = <YellowBox />;
<add> }
<add> return (
<add> <View style={styles.appContainer}>
<add> <View
<add> collapsable={false}
<add> key={this.state.mainKey}
<add> style={styles.appContainer} ref="main">
<add> {this.props.children}
<add> </View>
<add> {yellowBox}
<add> {this.state.inspector}
<add> </View>
<add> );
<add> }
<add>});
<add>
<add>var styles = StyleSheet.create({
<add> appContainer: {
<add> flex: 1,
<add> },
<add>});
<add>
<add>module.exports = AppContainer;
<ide><path>Libraries/ReactIOS/renderApplication.ios.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule renderApplication
<del> * @noflow
<add> * @flow
<ide> */
<ide>
<ide> 'use strict';
<ide>
<del>var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
<add>var AppContainer = require('AppContainer');
<ide> var React = require('React');
<ide> var ReactNative = require('ReactNative');
<del>var StyleSheet = require('StyleSheet');
<del>var Subscribable = require('Subscribable');
<del>var View = require('View');
<ide>
<ide> var invariant = require('fbjs/lib/invariant');
<ide>
<del>var Inspector = __DEV__ ? require('Inspector') : null;
<del>var YellowBox = __DEV__ ? require('YellowBox') : null;
<del>
<del>var AppContainer = React.createClass({
<del> mixins: [Subscribable.Mixin],
<del>
<del> getInitialState: function() {
<del> return { inspector: null, mainKey: 1 };
<del> },
<del>
<del> toggleElementInspector: function() {
<del> var inspector = !__DEV__ || this.state.inspector
<del> ? null
<del> : <Inspector
<del> rootTag={this.props.rootTag}
<del> inspectedViewTag={ReactNative.findNodeHandle(this.refs.main)}
<del> onRequestRerenderApp={(updateInspectedViewTag) => {
<del> this.setState(
<del> (s) => ({mainKey: s.mainKey + 1}),
<del> () => updateInspectedViewTag(ReactNative.findNodeHandle(this.refs.main))
<del> );
<del> }}
<del> />;
<del> this.setState({inspector});
<del> },
<del>
<del> componentDidMount: function() {
<del> this.addListenerOn(
<del> RCTDeviceEventEmitter,
<del> 'toggleElementInspector',
<del> this.toggleElementInspector
<del> );
<del> },
<del>
<del> render: function() {
<del> let yellowBox = null;
<del> if (__DEV__) {
<del> yellowBox = <YellowBox />;
<del> }
<del> return (
<del> <View style={styles.appContainer}>
<del> <View
<del> collapsible={false}
<del> key={this.state.mainKey}
<del> style={styles.appContainer} ref="main">
<del> {this.props.children}
<del> </View>
<del> {yellowBox}
<del> {this.state.inspector}
<del> </View>
<del> );
<del> }
<del>});
<del>
<del>function renderApplication<D, P, S>(
<add>function renderApplication<P>(
<ide> RootComponent: ReactClass<P>,
<ide> initialProps: P,
<ide> rootTag: any
<ide> function renderApplication<D, P, S>(
<ide> rootTag,
<ide> 'Expect to have a valid rootTag, instead got ', rootTag
<ide> );
<del> /* eslint-disable jsx-no-undef-with-namespace */
<ide> ReactNative.render(
<ide> <AppContainer rootTag={rootTag}>
<ide> <RootComponent
<ide> function renderApplication<D, P, S>(
<ide> </AppContainer>,
<ide> rootTag
<ide> );
<del> /* eslint-enable jsx-no-undef-with-namespace */
<ide> }
<ide>
<del>var styles = StyleSheet.create({
<del> appContainer: {
<del> flex: 1,
<del> },
<del>});
<ide>
<ide> module.exports = renderApplication;
| 2
|
Text
|
Text
|
add docker wg
|
679596c8483340bf6df65cd4a647a2c4196af6fb
|
<ide><path>WORKING_GROUPS.md
<ide> back in to the TC.
<ide> * [i18n](#i18n)
<ide> * [Evangelism](#evangelism)
<ide> * [Roadmap](#roadmap)
<add>* [Docker](#docker)
<ide> * [Starting a Working Group](#starting-a-wg)
<ide> * [Bootstrap Governance](#bootstrap-governance)
<ide>
<ide> Its responsibilities are:
<ide> * Produce Packages for all target platforms.
<ide> * Run tests.
<ide> * Run performance testing and comparisons.
<del>* Creates and manages official docker images.
<ide> * Creates and manages build-containers.
<ide>
<ide>
<ide> Their responsibilities are:
<ide> * Create Pull Requests for relevant changes to [Roadmap.md](./ROADMAP.md)
<ide>
<ide>
<add>### [Docker](https://github.com/iojs/docker-iojs)
<add>
<add>The Docker working group's purpose is to build, maintain, and improve official
<add>Docker images for the `io.js` project.
<add>
<add>Their responsibilities are:
<add>* Keep the official Docker images updated in line with new `io.js` releases.
<add>* Decide and implement image improvements and/or fixes.
<add>* Maintain and improve the images' documentation.
<add>
<add>
<ide> ## Starting a WG
<ide>
<ide> A Working Group is established by first defining a charter that can be
| 1
|
Python
|
Python
|
fix bug in `preprocess_weights_for_loading`
|
1ddf23528e38d6ef47ad42d10010da90d8c21018
|
<ide><path>keras/engine/topology.py
<ide> def preprocess_weights_for_loading(layer, weights,
<ide> (2, 3, 1, 0))
<ide> weights = [kernel, recurrent_kernel, bias]
<ide>
<add> if layer.__class__.__name__ in ['Model', 'Sequential']:
<add> new_weights = []
<add> # trainable weights
<add> for sublayer in layer.layers:
<add> num_weights = len(sublayer.trainable_weights)
<add> if num_weights > 0:
<add> new_weights.extend(preprocess_weights_for_loading(
<add> layer=sublayer,
<add> weights=weights[:num_weights],
<add> original_keras_version=original_keras_version,
<add> original_backend=original_backend))
<add> weights = weights[num_weights:]
<add>
<add> # non-trainable weights
<add> for sublayer in layer.layers:
<add> num_weights = len([l for l in sublayer.weights if l not in sublayer.trainable_weights])
<add> if num_weights > 0:
<add> new_weights.extend(preprocess_weights_for_loading(
<add> layer=sublayer,
<add> weights=weights[:num_weights],
<add> original_keras_version=original_keras_version,
<add> original_backend=original_backend))
<add> weights = weights[num_weights:]
<add> weights = new_weights
<add>
<ide> conv_layers = ['Conv1D',
<ide> 'Conv2D',
<ide> 'Conv3D',
| 1
|
Java
|
Java
|
fix trailing slash in nested path
|
7582adc0bc4d9456465338f92198fbcbdc84151a
|
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java
<ide> public ServerRequest nestRequest(ServerRequest request) {
<ide> if (!subPath.startsWith("/")) {
<ide> subPath = "/" + subPath;
<ide> }
<add> if (requestPath.endsWith("/") && !subPath.endsWith("/")) {
<add> subPath += "/";
<add> }
<ide> return new SubPathServerRequestWrapper(request, subPath);
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
provide info about actual error
|
2bee7996a57a44aec1f7ee3a07cd49a5b235ad78
|
<ide><path>lib/assert.js
<ide> function expectsNoError(stackStartFn, actual, error, message) {
<ide> actual,
<ide> expected: error,
<ide> operator: stackStartFn.name,
<del> message: `Got unwanted ${fnType}${details}\n${actual && actual.message}`,
<add> message: `Got unwanted ${fnType}${details}\n` +
<add> `Actual message: "${actual && actual.message}"`,
<ide> stackStartFn
<ide> });
<ide> }
<ide><path>test/parallel/test-assert-async.js
<ide> common.crashOnUnhandledRejection();
<ide> assert(err instanceof assert.AssertionError,
<ide> `${err.name} is not instance of AssertionError`);
<ide> assert.strictEqual(err.code, 'ERR_ASSERTION');
<del> assert(/^Got unwanted rejection\.\n$/.test(err.message));
<add> assert.strictEqual(err.message,
<add> 'Got unwanted rejection.\nActual message: ""');
<ide> assert.strictEqual(err.operator, 'doesNotReject');
<ide> assert.ok(!err.stack.includes('at Function.doesNotReject'));
<ide> return true;
<ide><path>test/parallel/test-assert.js
<ide> assert.throws(() => thrower(TypeError));
<ide> assert.ok(threw, 'a.doesNotThrow is not catching type matching errors');
<ide> }
<ide>
<del>common.expectsError(
<add>assert.throws(
<ide> () => a.doesNotThrow(() => thrower(Error), 'user message'),
<ide> {
<del> type: a.AssertionError,
<add> name: 'AssertionError [ERR_ASSERTION]',
<ide> code: 'ERR_ASSERTION',
<ide> operator: 'doesNotThrow',
<del> message: 'Got unwanted exception: user message\n[object Object]'
<add> message: 'Got unwanted exception: user message\n' +
<add> 'Actual message: "[object Object]"'
<ide> }
<ide> );
<ide>
<del>common.expectsError(
<del> () => a.doesNotThrow(() => thrower(Error), 'user message'),
<del> {
<del> code: 'ERR_ASSERTION',
<del> message: /Got unwanted exception: user message\n\[object Object\]/
<del> }
<del>);
<del>
<del>common.expectsError(
<add>assert.throws(
<ide> () => a.doesNotThrow(() => thrower(Error)),
<ide> {
<ide> code: 'ERR_ASSERTION',
<del> message: /Got unwanted exception\.\n\[object Object\]/
<add> message: 'Got unwanted exception.\nActual message: "[object Object]"'
<ide> }
<ide> );
<ide>
<ide> common.expectsError(
<ide>
<ide> // eslint-disable-next-line no-throw-literal
<ide> assert.throws(() => { throw undefined; }, /undefined/);
<del> common.expectsError(
<add> assert.throws(
<ide> // eslint-disable-next-line no-throw-literal
<ide> () => a.doesNotThrow(() => { throw undefined; }),
<ide> {
<del> type: assert.AssertionError,
<add> name: 'AssertionError [ERR_ASSERTION]',
<ide> code: 'ERR_ASSERTION',
<del> message: 'Got unwanted exception.\nundefined'
<add> message: 'Got unwanted exception.\nActual message: "undefined"'
<ide> }
<ide> );
<ide> }
| 3
|
Ruby
|
Ruby
|
fix my own typo now, ops! [ci skip]
|
10a37f33b795519c63cc4eced2329326bd7c6852
|
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def not(opts, *rest)
<ide> # # WHERE "authors"."id" IS NULL
<ide> #
<ide> # Additionally, multiple relations can be combined. This will return posts
<del> # that are missing both an author and any` comments:
<add> # that are missing both an author and any comments:
<ide> #
<ide> # Post.where.missing(:author, :comments)
<ide> # # SELECT "posts".* FROM "posts"
| 1
|
Text
|
Text
|
fix typo in caching with rails guide [skip ci]
|
17545b4d889149d8185c0a3a78030703d7e70c0e
|
<ide><path>guides/source/caching_with_rails.md
<ide> Caching in Development
<ide> ----------------------
<ide>
<ide> It's common to want to test the caching strategy of your application
<del>in developement mode. Rails provides the rake task `dev:cache` to
<add>in development mode. Rails provides the rake task `dev:cache` to
<ide> easily toggle caching on/off.
<ide>
<ide> ```bash
| 1
|
PHP
|
PHP
|
fix migration path
|
c4a5b3b0967820eacdcc1d351d48f1e1afa07ec9
|
<ide><path>src/Illuminate/Database/Console/Migrations/BaseCommand.php
<ide> protected function getMigrationPath()
<ide> return $this->laravel['path.base'].$path;
<ide> }
<ide>
<del> return $this->laravel['path'].'/database/migrations';
<add> return $this->laravel['path.database'].'/migrations';
<ide> }
<ide>
<ide> }
<ide><path>tests/Database/DatabaseMigrationMigrateCommandTest.php
<ide> public function tearDown()
<ide> public function testBasicMigrationsCallMigratorWithProperArguments()
<ide> {
<ide> $command = new MigrateCommand($migrator = m::mock('Illuminate\Database\Migrations\Migrator'), __DIR__.'/vendor');
<del> $app = new ApplicationDatabaseMigrationStub(array('path' => __DIR__));
<add> $app = new ApplicationDatabaseMigrationStub(array('path.database' => __DIR__));
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', false);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false);
<ide> $migrator->shouldReceive('getNotes')->andReturn(array());
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<ide>
<ide> public function testMigrationRepositoryCreatedWhenNecessary()
<ide> {
<ide> $params = array($migrator = m::mock('Illuminate\Database\Migrations\Migrator'), __DIR__.'/vendor');
<ide> $command = $this->getMock('Illuminate\Database\Console\Migrations\MigrateCommand', array('call'), $params);
<del> $app = new ApplicationDatabaseMigrationStub(array('path' => __DIR__));
<add> $app = new ApplicationDatabaseMigrationStub(array('path.database' => __DIR__));
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', false);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false);
<ide> $migrator->shouldReceive('getNotes')->andReturn(array());
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(false);
<ide> $command->expects($this->once())->method('call')->with($this->equalTo('migrate:install'), $this->equalTo(array('--database' => null)));
<ide> public function testVendorPackageIsRespectedWhenMigrating()
<ide> public function testTheCommandMayBePretended()
<ide> {
<ide> $command = new MigrateCommand($migrator = m::mock('Illuminate\Database\Migrations\Migrator'), __DIR__.'/vendor');
<del> $app = new ApplicationDatabaseMigrationStub(array('path' => __DIR__));
<add> $app = new ApplicationDatabaseMigrationStub(array('path.database' => __DIR__));
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with(null);
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', true);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', true);
<ide> $migrator->shouldReceive('getNotes')->andReturn(array());
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<ide>
<ide> public function testTheCommandMayBePretended()
<ide> public function testTheDatabaseMayBeSet()
<ide> {
<ide> $command = new MigrateCommand($migrator = m::mock('Illuminate\Database\Migrations\Migrator'), __DIR__.'/vendor');
<del> $app = new ApplicationDatabaseMigrationStub(array('path' => __DIR__));
<add> $app = new ApplicationDatabaseMigrationStub(array('path.database' => __DIR__));
<ide> $command->setLaravel($app);
<ide> $migrator->shouldReceive('setConnection')->once()->with('foo');
<del> $migrator->shouldReceive('run')->once()->with(__DIR__.'/database/migrations', false);
<add> $migrator->shouldReceive('run')->once()->with(__DIR__.'/migrations', false);
<ide> $migrator->shouldReceive('getNotes')->andReturn(array());
<ide> $migrator->shouldReceive('repositoryExists')->once()->andReturn(true);
<ide>
| 2
|
Ruby
|
Ruby
|
skip broken formulae
|
7ff5de2ad816e54eef5baa839365fd465088ae44
|
<ide><path>Library/Homebrew/formula.rb
<ide> def self.names
<ide>
<ide> # an array of all Formula, instantiated
<ide> def self.all
<del> names.map{ |fn| Formula.factory(fn) }
<add> all = []
<add> names.each do |n|
<add> begin
<add> all << Formula.factory(n)
<add> rescue
<add> # Don't let one broken formula break commands.
<add> end
<add> end
<add> return all
<ide> end
<ide>
<ide> def self.aliases
| 1
|
Text
|
Text
|
fix indentation for proper markdown syntax
|
c7010bef6ea96fb6035a746ad0f5c2a24c46ae21
|
<ide><path>CONTRIBUTING.md
<ide> Before you submit your pull request consider the following guidelines:
<ide>
<ide> If the PR gets too outdated we may ask you to rebase and force push to update the PR:
<ide>
<del> ```shell
<del> git rebase master -i
<del> git push origin my-fix-branch -f
<del> ```
<add>```shell
<add>git rebase master -i
<add>git push origin my-fix-branch -f
<add>```
<ide>
<ide> *WARNING. Squashing or reverting commits and forced push thereafter may remove GitHub comments
<ide> on code that were previously made by you and others in your commits.*
| 1
|
Ruby
|
Ruby
|
default the reaping frequency to 10 seconds
|
7cc588b684f6d1af3e7fab1edfa6715e269e41a2
|
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> def initialize(spec)
<ide>
<ide> @checkout_timeout = spec.config[:checkout_timeout] || 5
<ide> @dead_connection_timeout = spec.config[:dead_connection_timeout] || 5
<del> @reaper = Reaper.new self, spec.config[:reaping_frequency]
<add> @reaper = Reaper.new(self, spec.config[:reaping_frequency] || 10)
<ide> @reaper.run
<ide>
<ide> # default max pool size to 5
| 1
|
Javascript
|
Javascript
|
implement textarea keyword
|
5d95e7b739dd40a91925625adf449ed1b785db98
|
<ide><path>packages/ember-htmlbars/lib/env.js
<ide> import view from "ember-htmlbars/keywords/view";
<ide> import componentKeyword from "ember-htmlbars/keywords/component";
<ide> import partial from "ember-htmlbars/keywords/partial";
<ide> import input from "ember-htmlbars/keywords/input";
<add>import textarea from "ember-htmlbars/keywords/textarea";
<ide> import collection from "ember-htmlbars/keywords/collection";
<ide> import templateKeyword from "ember-htmlbars/keywords/template";
<ide>
<ide> registerKeyword('component', componentKeyword);
<ide> registerKeyword('partial', partial);
<ide> registerKeyword('template', templateKeyword);
<ide> registerKeyword('input', input);
<add>registerKeyword('textarea', textarea);
<ide> registerKeyword('collection', collection);
<ide>
<ide> export default {
<ide><path>packages/ember-htmlbars/lib/keywords/textarea.js
<add>export default {
<add>
<add> render(morph, env, scope, params, hash, template, inverse, visitor) {
<add> env.hooks.component(morph, env, scope, '-text-area', hash, template, visitor);
<add> }
<add>};
<ide><path>packages/ember-htmlbars/tests/helpers/text_area_test.js
<ide> import View from "ember-views/views/view";
<ide> import compile from "ember-template-compiler/system/compile";
<ide> import { set as o_set } from "ember-metal/property_set";
<ide> import { runAppend, runDestroy } from "ember-runtime/tests/utils";
<add>import TextArea from "ember-views/views/text_area";
<add>import Registry from "container/registry";
<add>import ComponentLookup from "ember-views/component_lookup";
<ide>
<ide> var textArea, controller;
<ide>
<ide> QUnit.module("{{textarea}}", {
<ide> val: 'Lorem ipsum dolor'
<ide> };
<ide>
<add> var registry = new Registry();
<add> registry.register('component:-text-area', TextArea);
<add> registry.register('component-lookup:main', ComponentLookup);
<add>
<ide> textArea = View.extend({
<add> container: registry.container(),
<ide> controller: controller,
<ide> template: compile('{{textarea disabled=disabled value=val}}')
<ide> }).create();
<ide> QUnit.module("{{textarea}}", {
<ide> }
<ide> });
<ide>
<del>QUnit.skip("Should insert a textarea", function() {
<add>QUnit.test("Should insert a textarea", function() {
<ide> equal(textArea.$('textarea').length, 1, "There is a single textarea");
<ide> });
<ide>
<del>QUnit.skip("Should become disabled when the controller changes", function() {
<add>QUnit.test("Should become disabled when the controller changes", function() {
<ide> ok(textArea.$('textarea').is(':not(:disabled)'), "Nothing is disabled yet");
<ide> set(controller, 'disabled', true);
<ide> ok(textArea.$('textarea').is(':disabled'), "The disabled attribute is updated");
<ide><path>packages/ember-testing/tests/helpers_test.js
<ide> QUnit.test("`wait` helper can be passed a resolution value", function() {
<ide>
<ide> });
<ide>
<del>QUnit.skip("`click` triggers appropriate events in order", function() {
<add>QUnit.test("`click` triggers appropriate events in order", function() {
<ide> expect(5);
<ide>
<ide> var click, wait, events;
<ide><path>packages/ember-views/lib/initializers/components.js
<ide> import { onLoad } from "ember-runtime/system/lazy_load";
<ide> import TextField from "ember-views/views/text_field";
<add>import TextArea from "ember-views/views/text_area";
<ide> import Checkbox from "ember-views/views/checkbox";
<ide>
<ide> onLoad('Ember.Application', function(Application) {
<ide> Application.initializer({
<ide> name: 'ember-views-components',
<ide> initialize(registry) {
<ide> registry.register('component:-text-field', TextField);
<add> registry.register('component:-text-area', TextArea);
<ide> registry.register('component:-checkbox', Checkbox);
<ide> }
<ide> });
<ide> });
<del>
| 5
|
Text
|
Text
|
update korean transltaion to 4c778e2
|
e67c0943b887dc9e4f9853d904f92367d5cef091
|
<ide><path>docs/docs/02.1-jsx-in-depth.ko-KR.md
<ide> var person = React.createElement(
<ide> );
<ide> ```
<ide>
<add>### 불린 어트리뷰트
<add>
<add>어트리뷰트의 값을 생략하면 JSX는 값을 `true`로 취급합니다. 어트리뷰트 표현식에 `false`를 넘기려면 사용해야만 합니다. HTML 폼 엘리먼트에 `disabled`, `required`, `checked`, `readOnly`같은 어트리뷰트를 사용할 일이 자주 있습니다.
<add>
<add>```javascript
<add>// JSX에서 이 두 줄은 똑같이 버튼을 비활성화합니다.
<add><input type="button" disabled />;
<add><input type="button" disabled={true} />;
<add>
<add>// 그리고 JSX에서 이 두 줄은 똑같이 버튼을 비활성화하지 않습니다.
<add><input type="button" />;
<add><input type="button" disabled={false} />;
<add>```
<add>
<ide> ### 자식 표현식
<ide>
<ide> 비슷하게, JavaScript 표현식을 자식을 표현하는 데 사용할 수 있습니다.
<ide><path>docs/docs/05-reusable-components.ko-KR.md
<ide> React.render(
<ide>
<ide> 믹스인의 괜찮은 점은 컴포넌트가 여러 믹스인을 사용하고 여러 믹스인에서 같은 생명주기 메소드를 사용할 때(예를 들어, 여러 믹스인에서 컴포넌트가 사라질 때 뭔가 정리하려 한다면) 모든 생명주기 메소드들의 실행은 보장됩니다. 믹스인에 정의된 메소드은 컴포넌트의 메소드가 호출됨에 따라 믹스인이 나열된 순서대로 실행됩니다.
<ide>
<add><a name="es6-classes"></a>
<ide> ## ES6 클래스
<ide>
<ide> React 클래스를 일반적인 JavaScript 클래스로 선언할 수도 있습니다. 다음의 예제는 ES6 클래스 문법을 사용합니다:
<ide><path>docs/docs/07-forms.ko-KR.md
<ide> HTML에서는 `<textarea>` 태그의 값을 설정할 때 `<textarea>` 태그의
<ide>
<ide> 모든 DOM 이벤트처럼 `onChange` prop은 모든 네이티브 컴포넌트에서 지원되며 일어난(bubbled) 변경 이벤트를 감시하는데 사용할 수 있습니다.
<ide>
<add>> 주의:
<add>>
<add>> `<input>`, `<textarea>`에서는 `onChange`가 DOM의 [`oninput`](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput) 이벤트 핸들러와 같은 기능을 제공하므로 일반적인 경우에는 `onChange`를 사용하세요.
<ide>
<ide> ## 제어되는(controlled) 컴포넌트
<ide>
<ide><path>docs/docs/ref-01-top-level-api.ko-KR.md
<ide> DOMElement findDOMNode(ReactComponent component)
<ide> #### React.Children.map
<ide>
<ide> ```javascript
<del>object React.Children.map(object children, function fn [, object context])
<add>object React.Children.map(object children, function fn [, object thisArg])
<ide> ```
<ide>
<del>`children`의 바로 밑에 있는 모든 자식에 `fn`을 호출합니다. 이 때 `this`는 `context`로 설정됩니다. `children`이 중첩된 객체나 배열일 경우 그 안의 값을 순회합니다. 따라서 `fn`에 컨테이너 객체가 넘어가는 일은 일어나지 않습니다. `children`이 `null`이거나 `undefined`면 빈 객체 대신 `null` 또는 `undefined`를 리턴합니다.
<add>`children`의 바로 밑에 있는 모든 자식에 `fn`을 호출합니다. 이 때 `this`는 `thisArg`로 설정됩니다. `children`이 중첩된 객체나 배열일 경우 그 안의 값을 순회합니다. 따라서 `fn`에 컨테이너 객체가 넘어가는 일은 일어나지 않습니다. `children`이 `null`이거나 `undefined`면 빈 객체 대신 `null` 또는 `undefined`를 리턴합니다.
<ide>
<ide> #### React.Children.forEach
<ide>
<ide> ```javascript
<del>React.Children.forEach(object children, function fn [, object context])
<add>React.Children.forEach(object children, function fn [, object thisArg])
<ide> ```
<ide>
<ide> `React.Children.map()`과 비슷하지만 객체를 리턴하지 않습니다.
<ide><path>docs/docs/ref-03-component-specs.ko-KR.md
<ide> next: tags-and-attributes-ko-KR.html
<ide>
<ide> `React.createClass()`를 호출하여 컴포넌트 클래스를 생성할 때, `render` 메소드를 포함한 명세 객체를 제공해야 합니다. 또한 필요한 경우 여기에서 설명하는 다른 생명주기 메소드를 명세 객체에 추가로 제공할 수 있습니다.
<ide>
<add>> 주의:
<add>>
<add>> 그냥 JavaScript 클래스를 컴포넌트 클래스로 사용할 수도 있습니다. 이 클래스는 구현할 수 있는 메소드가 거의 같지만 약간의 차이가 있습니다. 차이에 관한 더 자세한 정보는 [ES6 클래스](/react/docs/reusable-components-ko-KR.html#es6-classes)를 읽어보세요.
<ide>
<ide> ### render
<ide>
<ide><path>docs/tips/13-false-in-jsx.ko-KR.md
<ide> prev: initial-ajax-ko-KR.html
<ide> next: communicate-between-components-ko-KR.html
<ide> ---
<ide>
<del>`false` 렌더링이 여러 문맥에서 어떻게 다뤄지는지 봅시다.
<add>`false` 렌더링이 여러 상황에서 어떻게 다뤄지는지 봅시다.
<ide>
<ide> `id="false"`로 렌더링
<ide>
| 6
|
Python
|
Python
|
fix flax_multiple_choice_sample typo
|
eec9c8bbd784059275527897aad75df59442a370
|
<ide><path>src/transformers/file_utils.py
<ide> def _prepare_output_docstrings(output_type, config_class, min_indent=None):
<ide> >>> encoding = tokenizer([prompt, prompt], [choice0, choice1], return_tensors='jax', padding=True)
<ide> >>> outputs = model(**{{k: v[None, :] for k,v in encoding.items()}})
<ide>
<del> >>> logits = outputs.logits ```
<add> >>> logits = outputs.logits
<add> ```
<ide> """
<ide>
<ide> FLAX_CAUSAL_LM_SAMPLE = r"""
| 1
|
PHP
|
PHP
|
apply suggestions from code review
|
036e1220cd7a8d022031a56290d9310b39edb0a9
|
<ide><path>src/ORM/Table.php
<ide> public function get($primaryKey, array $options = []): EntityInterface
<ide> if ($cacheConfig) {
<ide> if (!$cacheKey) {
<ide> $cacheKey = sprintf(
<del> 'get-%s.%s%s',
<add> 'get-%s-%s-%s',
<ide> $this->getConnection()->configName(),
<ide> $this->getTable(),
<ide> json_encode($primaryKey)
| 1
|
Ruby
|
Ruby
|
use actiondispatch mimes in asset_tag_helper_test
|
5579871687c95797039bcd978063e0a0a4782d78
|
<ide><path>actionview/test/template/asset_tag_helper_test.rb
<ide> require "abstract_unit"
<ide> require "active_support/ordered_options"
<ide>
<add>require "action_dispatch"
<add>ActionView::Template::Types.delegate_to Mime
<add>
<ide> class AssetTagHelperTest < ActionView::TestCase
<ide> tests ActionView::Helpers::AssetTagHelper
<ide>
| 1
|
PHP
|
PHP
|
pass path to route loader
|
bf30ca7238203f224e32b1c88037b5ec774b0f85
|
<ide><path>public/index.php
<ide> * @link http://laravel.com
<ide> */
<ide>
<add>$t = microtime(true);
<add>
<ide> // --------------------------------------------------------------
<ide> // The path to the application directory.
<ide> // --------------------------------------------------------------
<ide> // ----------------------------------------------------------
<ide> if (is_null($response))
<ide> {
<del> $route = System\Routing\Router::make(System\Request::method(), System\Request::uri(), new System\Routing\Loader)->route();
<add> $route = System\Routing\Router::make(System\Request::method(), System\Request::uri(), new System\Routing\Loader(APP_PATH))->route();
<ide>
<ide> $response = (is_null($route)) ? System\Response::error('404') : $route->call();
<ide> }
| 1
|
Python
|
Python
|
add english lex_attrs overrides
|
88adeee5485aaa021de3aa7632e8687d1fc9459c
|
<ide><path>spacy/lang/en/__init__.py
<ide> from .tokenizer_exceptions import TOKENIZER_EXCEPTIONS
<ide> from .tag_map import TAG_MAP
<ide> from .stop_words import STOP_WORDS
<add>from .lex_attrs import LEX_ATTRS
<ide> from .morph_rules import MORPH_RULES
<ide> from .lemmatizer import LEMMA_RULES, LEMMA_INDEX, LEMMA_EXC
<ide>
<ide> class English(Language):
<ide> class Defaults(Language.Defaults):
<ide> lex_attr_getters = dict(Language.Defaults.lex_attr_getters)
<ide> lex_attr_getters[LANG] = lambda text: 'en'
<add> lex_attr_getters.update(LEX_ATTRS)
<ide>
<ide> tokenizer_exceptions = update_exc(BASE_EXCEPTIONS, TOKENIZER_EXCEPTIONS)
<ide> tag_map = dict(TAG_MAP)
<ide><path>spacy/lang/en/lex_attrs.py
<ide> from __future__ import unicode_literals
<ide>
<ide>
<del># Number words
<add>from ...attrs import LIKE_NUM
<ide>
<del>NUM_WORDS = set("""
<del>zero one two three four five six seven eight nine ten eleven twelve thirteen
<del>fourteen fifteen sixteen seventeen eighteen nineteen twenty thirty forty fifty
<del>sixty seventy eighty ninety hundred thousand million billion trillion
<del>quadrillion gajillion bazillion
<del>""".split())
<ide>
<add>_num_words = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
<add> 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
<add> 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen', 'twenty',
<add> 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety',
<add> 'hundred', 'thousand', 'million', 'billion', 'trillion', 'quadrillion',
<add> 'gajillion', 'bazillion']
<ide>
<del># Ordinal words
<ide>
<del>ORDINAL_WORDS = set("""
<del>first second third fourth fifth sixth seventh eigth ninth tenth eleventh twelveth
<del>thirteenth fourteenth fifteenth sixteenth sventeenth eighteenth nineteenth
<del>twentieth thirtieth fortieth fiftieth sixtieth seventieth eightieth ninetieth
<del>hundreth thousandth millionth billionth trillionth quadrillionth gajillionth
<del>bazillionth
<del>""".split())
<add>def like_num(text):
<add> text = text.replace(',', '')
<add> text = text.replace('.', '')
<add> if text.isdigit():
<add> return True
<add> if text.count('/') == 1:
<add> num, denom = text.split('/')
<add> if num.isdigit() and denom.isdigit():
<add> return True
<add> if text in _num_words:
<add> return True
<add> return False
<add>
<add>
<add>LEX_ATTRS = {
<add> LIKE_NUM: like_num
<add>}
| 2
|
Text
|
Text
|
remove tmp file
|
b3f2a208322c84886a19dcf2faa8c6ecc5e7f1bb
|
<ide><path>changelog.tmp.md
<del><a name="v1.0.0rc3"></a>
<del># v1.0.0rc3 (2012-03-27)
<del>
<del>
<del>## Bug Fixes
<del>
<del>- **$compile:**
<del> - create new (isolate) scopes for directives on root elements ([5390fb37](https://github.com/angular/angular.js/commit/5390fb37d2c01937922613fc57df4986af521787), closes [#817](https://github.com/angular/angular.js/issues/817))
<del> - don't touch static element attributes ([9cb2195e](https://github.com/angular/angular.js/commit/9cb2195e61a78e99020ec19d687a221ca88b5900))
<del> - Merge interpolated css class when replacing an element ([f49eaf8b](https://github.com/angular/angular.js/commit/f49eaf8bf2df5f4e0e82d6c89e849a4f82c8d414))
<del>- **$http:**
<del> - don't send Content-Type header when no data ([1a5bebd9](https://github.com/angular/angular.js/commit/1a5bebd927ecd22f9c34617642fdf58fe3f62efb), closes [#749](https://github.com/angular/angular.js/issues/749))
<del>- **$log:**
<del> - avoid console.log.apply calls in IE ([15213ec2](https://github.com/angular/angular.js/commit/15213ec212769837cb2b7e781ffc5bfd598d27ca), closes [#805](https://github.com/angular/angular.js/issues/805))
<del>- **$resource:**
<del> - support escaping of ':' in resource url ([6d6f8753](https://github.com/angular/angular.js/commit/6d6f875345e01f2c6c63ef95164f6f39e923da15))
<del>- **compiler:**
<del> - allow transclusion of root elements ([9918b748](https://github.com/angular/angular.js/commit/9918b748be01266eb10db39d51b4d3098d54ab66))
<del>- **e2e runner:**
<del> - fix typo that caused errors on IE8 ([ee5a5352](https://github.com/angular/angular.js/commit/ee5a5352fd4b94cedee6ef20d4bf2d43ce77e00b), closes [#806](https://github.com/angular/angular.js/issues/806))
<del>- **forEach:**
<del> - should ignore prototypically inherited properties ([8d7e6948](https://github.com/angular/angular.js/commit/8d7e6948496ff26ef1da8854ba02fcb8eebfed61), closes [#813](https://github.com/angular/angular.js/issues/813))
<del>- **forms:**
<del> - Remove double registering of form ([1faafa31](https://github.com/angular/angular.js/commit/1faafa31582c4e9413f48dc7d12f5b681f9fe9fd))
<del> - Set ng-valid/ng-invalid correctly ([08bfea18](https://github.com/angular/angular.js/commit/08bfea183a850b29da270eac47f80b598cbe600f))
<del>- **init:**
<del> - use jQuery#ready for init if available ([cb2ad9ab](https://github.com/angular/angular.js/commit/cb2ad9abf24e6f855cc749efe3155bd7987ece9d), closes [#818](https://github.com/angular/angular.js/issues/818))
<del>- **json:**
<del> - added support for iso8061 timezone ([5ac14f63](https://github.com/angular/angular.js/commit/5ac14f633a69f49973b5512780c6ec7752405967))
<del>- **matchers.toHaveClass:**
<del> - Correct reference to angular.mock.dump ([f701ce08](https://github.com/angular/angular.js/commit/f701ce08f9d63be05fc3b92f57ad473e1e749b2d))
<del>- **ng-switch:**
<del> - properly destroy child scopes ([2315d9b3](https://github.com/angular/angular.js/commit/2315d9b3610994b36c44e4a97fb1427d59471ce8))
<del>- **ngDocSpec:**
<del> - fix broken tests ([53b6f522](https://github.com/angular/angular.js/commit/53b6f522a56eea314cbd084816e08f24b2c7879f))
<del>- **ngForm:**
<del> - alias name||ngForm ([823adb23](https://github.com/angular/angular.js/commit/823adb231995e917bc060bfa49453e2a96bac2b6))
<del>- **ngRepeat:**
<del> - correct variable reference in error message ([935c1018](https://github.com/angular/angular.js/commit/935c1018da05dbf3124b2dd33619c4a3c82d7a2a))
<del>- **ngView:**
<del> - controller not published ([21e74c2d](https://github.com/angular/angular.js/commit/21e74c2d2e8e985b23711785287feb59965cbd90))
<del>- **q:**
<del> - resolve all of nothing to nothing ([ac75079e](https://github.com/angular/angular.js/commit/ac75079e2113949d5d64adbcf23d56f3cf295d41))
<del>- **select:**
<del> - multiselect failes to update view on selection insert ([6ecac8e7](https://github.com/angular/angular.js/commit/6ecac8e71a84792a434d21db2c245b3648c55f18))
<del>
<del>
<del>## Features
<del>
<del>- **$compile:**
<del> - do not interpolate boolean attributes, rather evaluate them ([a08cbc02](https://github.com/angular/angular.js/commit/a08cbc02e78e789a66e9af771c410e8ad1646e25))
<del>- **$controller:**
<del> - support controller registration via $controllerProvider ([d54dfecb](https://github.com/angular/angular.js/commit/d54dfecb00fba41455536c5ddd55310592fdaf84))
<del>- **$route:**
<del> - when matching consider trailing slash as optional ([a4fe51da](https://github.com/angular/angular.js/commit/a4fe51da3ba0dc297ecd389e230d6664f250c9a6), closes [#784](https://github.com/angular/angular.js/issues/784))
<del>- **assertArgFn:**
<del> - should support array annotated fns ([4b8d9260](https://github.com/angular/angular.js/commit/4b8d926062eb4d4483555bdbdec4656f585ab40b))
<del>- **http:**
<del> - added params parameter ([73c85930](https://github.com/angular/angular.js/commit/73c8593077155a9f2e8ef42efd4c497eba0bef4f))
<del>- **injector:**
<del> - infer _foo_ as foo ([f13dd339](https://github.com/angular/angular.js/commit/f13dd3393dfb7a33565c9360342c193bc0bddcb6))
<del>- **input.radio:**
<del> - Allow value attribute to be interpolated ([ade6c452](https://github.com/angular/angular.js/commit/ade6c452753145c84884d17027a7865bf4b34b0c))
<del>- **jqLite:**
<del> - make injector() and scope() work with the document object ([5fdab52d](https://github.com/angular/angular.js/commit/5fdab52dd7c269f99839f4fa6b5854d9548269fa))
<del> - add .controller() method ([6c5a05ad](https://github.com/angular/angular.js/commit/6c5a05ad49a1e083570c3dfe331403398f899dbe))
<del>- **ngValue:**
<del> - allow radio inputs to have non string values ([09e175f0](https://github.com/angular/angular.js/commit/09e175f02cca0f4a295fd0c9b980cd8f432e722b), closes [#816](https://github.com/angular/angular.js/issues/816))
<del>- **scope:**
<del> - broadcast $destroy event on scope destruction ([9b1aff90](https://github.com/angular/angular.js/commit/9b1aff905b638aa274a5fc8f88662df446d374bd))
<del>- **scope.$eval:**
<del> - Allow passing locals to the expression ([192ff61f](https://github.com/angular/angular.js/commit/192ff61f5d61899e667c6dbce4d3e6e399429d8b))
<del>
<del>
<del>## Breaking Changes
<del>
<del>- boolean attrs are evaluated rather than interpolated ([a08cbc02](https://github.com/angular/angular.js/commit/a08cbc02e78e789a66e9af771c410e8ad1646e25))
<del>- ng-bind-attr directive removed ([55027132](https://github.com/angular/angular.js/commit/55027132f3d57e5dcf94683e6e6bd7b0aae0087d))
<del>- any app that depends on this service and its fallback to Modernizr, please ([aaedefb9](https://github.com/angular/angular.js/commit/aaedefb92e6bec6626e173e5155072c91471596a))
<del>
| 1
|
Javascript
|
Javascript
|
remove unused code block
|
73343d5ceef7cb4ddee1ed0ddd2c51d1958e3bb1
|
<ide><path>lib/_http_server.js
<ide> ServerResponse.prototype.writeHead = function(statusCode) {
<ide>
<ide> var obj = arguments[headerIndex];
<ide>
<del> if (obj && this._headers) {
<del> if (util.isArray(obj)) {
<del> // handle array case
<del> // TODO: remove when array is no longer accepted
<del> var field;
<del> for (var i = 0, len = obj.length; i < len; ++i) {
<del> field = obj[i][0];
<del> if (!util.isUndefined(headers[field])) {
<del> obj.push([field, headers[field]]);
<del> }
<del> }
<del> headers = obj;
<del>
<del> } else {
<del> // handle object case
<add> if (this._headers) {
<add> // Slow-case: when progressive API and header fields are passed.
<add> if (obj) {
<ide> var keys = Object.keys(obj);
<ide> for (var i = 0; i < keys.length; i++) {
<ide> var k = keys[i];
<ide> if (k) this.setHeader(k, obj[k]);
<ide> }
<del> // Slow-case: when progressive API and header fields are passed.
<del> headers = this._renderHeaders();
<ide> }
<del> } else if (this._headers) {
<ide> // only progressive api is used
<ide> headers = this._renderHeaders();
<ide> } else {
| 1
|
Javascript
|
Javascript
|
fix url interception in hash-bang mode
|
58ef32308f45141c8f7f7cc32a6156cd328ba692
|
<ide><path>src/ng/http.js
<ide> function isSameDomain(requestUrl, locationUrl) {
<ide> relativeProtocol: match[2] === undefined || match[2] === ''
<ide> };
<ide>
<del> match = URL_MATCH.exec(locationUrl);
<add> match = SERVER_MATCH.exec(locationUrl);
<ide> var domain2 = {
<ide> protocol: match[1],
<ide> host: match[3],
<ide><path>src/ng/httpBackend.js
<ide> function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument,
<ide>
<ide> function completeRequest(callback, status, response, headersString) {
<ide> // URL_MATCH is defined in src/service/location.js
<del> var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
<add> var protocol = (url.match(SERVER_MATCH) || ['', locationProtocol])[1];
<ide>
<ide> // fix status code for file protocol (it's always 0)
<ide> status = (protocol == 'file') ? (response ? 200 : 404) : status;
<ide><path>src/ng/location.js
<ide> 'use strict';
<ide>
<del>var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
<del> PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
<del> HASH_MATCH = PATH_MATCH,
<add>var SERVER_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
<add> PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
<ide> DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
<ide>
<ide>
<ide> function encodePath(path) {
<ide> return segments.join('/');
<ide> }
<ide>
<del>function stripHash(url) {
<del> return url.split('#')[0];
<add>function matchUrl(url, obj) {
<add> var match = SERVER_MATCH.exec(url);
<add>
<add> obj.$$protocol = match[1];
<add> obj.$$host = match[3];
<add> obj.$$port = int(match[5]) || DEFAULT_PORTS[match[1]] || null;
<ide> }
<ide>
<add>function matchAppUrl(url, obj) {
<add> var match = PATH_MATCH.exec(url);
<ide>
<del>function matchUrl(url, obj) {
<del> var match = URL_MATCH.exec(url);
<del>
<del> match = {
<del> protocol: match[1],
<del> host: match[3],
<del> port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
<del> path: match[6] || '/',
<del> search: match[8],
<del> hash: match[10]
<del> };
<del>
<del> if (obj) {
<del> obj.$$protocol = match.protocol;
<del> obj.$$host = match.host;
<del> obj.$$port = match.port;
<del> }
<add> obj.$$path = decodeURIComponent(match[1]);
<add> obj.$$search = parseKeyValue(match[3]);
<add> obj.$$hash = decodeURIComponent(match[5] || '');
<ide>
<del> return match;
<add> // make sure path starts with '/';
<add> if (obj.$$path && obj.$$path.charAt(0) != '/') obj.$$path = '/' + obj.$$path;
<ide> }
<ide>
<ide>
<ide> function composeProtocolHostPort(protocol, host, port) {
<ide> return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
<ide> }
<ide>
<del>
<del>function pathPrefixFromBase(basePath) {
<del> return basePath.substr(0, basePath.lastIndexOf('/'));
<add>/**
<add> *
<add> * @param {string} begin
<add> * @param {string} whole
<add> * @param {string} otherwise
<add> * @returns {string} returns text from whole after begin or otherwise if it does not begin with expected string.
<add> */
<add>function beginsWith(begin, whole, otherwise) {
<add> return whole.indexOf(begin) == 0 ? whole.substr(begin.length) : otherwise;
<ide> }
<ide>
<ide>
<del>function convertToHtml5Url(url, basePath, hashPrefix) {
<del> var match = matchUrl(url);
<del>
<del> // already html5 url
<del> if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
<del> match.hash.indexOf(hashPrefix) !== 0) {
<del> return url;
<del> // convert hashbang url -> html5 url
<del> } else {
<del> return composeProtocolHostPort(match.protocol, match.host, match.port) +
<del> pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
<del> }
<add>function stripHash(url) {
<add> var index = url.indexOf('#');
<add> return index == -1 ? url : url.substr(0, index);
<ide> }
<ide>
<ide>
<del>function convertToHashbangUrl(url, basePath, hashPrefix) {
<del> var match = matchUrl(url);
<del>
<del> // already hashbang url
<del> if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) &&
<del> match.hash.indexOf(hashPrefix) === 0) {
<del> return url;
<del> // convert html5 url -> hashbang url
<del> } else {
<del> var search = match.search && '?' + match.search || '',
<del> hash = match.hash && '#' + match.hash || '',
<del> pathPrefix = pathPrefixFromBase(basePath),
<del> path = match.path.substr(pathPrefix.length);
<del>
<del> if (match.path.indexOf(pathPrefix) !== 0) {
<del> throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
<del> }
<add>function stripFile(url) {
<add> return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
<add>}
<ide>
<del> return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
<del> '#' + hashPrefix + path + search + hash;
<del> }
<add>/* return the server only */
<add>function serverBase(url) {
<add> return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
<ide> }
<ide>
<ide>
<ide> /**
<del> * LocationUrl represents an url
<add> * LocationHtml5Url represents an url
<ide> * This object is exposed as $location service when HTML5 mode is enabled and supported
<ide> *
<ide> * @constructor
<del> * @param {string} url HTML5 url
<del> * @param {string} pathPrefix
<add> * @param {string} appBase application base URL
<add> * @param {string} basePrefix url path prefix
<ide> */
<del>function LocationUrl(url, pathPrefix, appBaseUrl) {
<del> pathPrefix = pathPrefix || '';
<del>
<add>function LocationHtml5Url(appBase, basePrefix) {
<add> basePrefix = basePrefix || '';
<add> var appBaseNoFile = stripFile(appBase);
<ide> /**
<ide> * Parse given html5 (regular) url string into properties
<ide> * @param {string} newAbsoluteUrl HTML5 url
<ide> * @private
<ide> */
<del> this.$$parse = function(newAbsoluteUrl) {
<del> var match = matchUrl(newAbsoluteUrl, this);
<del>
<del> if (match.path.indexOf(pathPrefix) !== 0) {
<del> throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
<add> this.$$parse = function(url) {
<add> var parsed = {}
<add> matchUrl(url, parsed);
<add> var pathUrl = beginsWith(appBaseNoFile, url);
<add> if (!isString(pathUrl)) {
<add> throw Error('Invalid url "' + url + '", missing path prefix "' + appBaseNoFile + '".');
<add> }
<add> matchAppUrl(pathUrl, parsed);
<add> extend(this, parsed);
<add> if (!this.$$path) {
<add> this.$$path = '/';
<ide> }
<del>
<del> this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
<del> this.$$search = parseKeyValue(match.search);
<del> this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
<ide>
<ide> this.$$compose();
<ide> };
<ide> function LocationUrl(url, pathPrefix, appBaseUrl) {
<ide> hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
<ide>
<ide> this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
<del> this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
<del> pathPrefix + this.$$url;
<add> this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
<ide> };
<ide>
<add> this.$$rewrite = function(url) {
<add> var appUrl;
<ide>
<del> this.$$rewriteAppUrl = function(absoluteLinkUrl) {
<del> if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
<del> return absoluteLinkUrl;
<add> if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
<add> if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
<add> return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
<add> } else {
<add> return appBase;
<add> }
<add> } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
<add> return appBaseNoFile + appUrl;
<add> } else if (appBaseNoFile == url + '/') {
<add> return appBaseNoFile;
<ide> }
<ide> }
<del>
<del>
<del> this.$$parse(url);
<ide> }
<ide>
<ide>
<ide> function LocationUrl(url, pathPrefix, appBaseUrl) {
<ide> * This object is exposed as $location service when html5 history api is disabled or not supported
<ide> *
<ide> * @constructor
<del> * @param {string} url Legacy url
<del> * @param {string} hashPrefix Prefix for hash part (containing path and search)
<add> * @param {string} appBase application base URL
<add> * @param {string} hashPrefix hashbang prefix
<ide> */
<del>function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
<del> var basePath;
<add>function LocationHashbangUrl(appBase, hashPrefix) {
<add> var appBaseNoFile = stripFile(appBase);
<ide>
<ide> /**
<ide> * Parse given hashbang url into properties
<ide> * @param {string} url Hashbang url
<ide> * @private
<ide> */
<ide> this.$$parse = function(url) {
<del> var match = matchUrl(url, this);
<del>
<del>
<del> if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
<del> throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
<add> matchUrl(url, this);
<add> var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
<add> if (!isString(withoutBaseUrl)) {
<add> throw new Error('Invalid url "' + url + '", does not start with "' + appBase + '".');
<ide> }
<del>
<del> basePath = match.path + (match.search ? '?' + match.search : '');
<del> match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
<del> if (match[1]) {
<del> this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
<del> } else {
<del> this.$$path = '';
<add> var withoutHashUrl = withoutBaseUrl.charAt(0) == '#' ? beginsWith(hashPrefix, withoutBaseUrl) : withoutBaseUrl;
<add> if (!isString(withoutHashUrl)) {
<add> throw new Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '".');
<ide> }
<del>
<del> this.$$search = parseKeyValue(match[3]);
<del> this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
<del>
<add> matchAppUrl(withoutHashUrl, this);
<ide> this.$$compose();
<ide> };
<ide>
<ide> function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
<ide> hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
<ide>
<ide> this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
<del> this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
<del> basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
<add> this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
<ide> };
<ide>
<del> this.$$rewriteAppUrl = function(absoluteLinkUrl) {
<del> if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
<del> return absoluteLinkUrl;
<add> this.$$rewrite = function(url) {
<add> if(stripHash(appBase) == stripHash(url)) {
<add> return url;
<ide> }
<ide> }
<add>}
<add>
<add>
<add>/**
<add> * LocationHashbangUrl represents url
<add> * This object is exposed as $location service when html5 history api is enabled but the browser
<add> * does not support it.
<add> *
<add> * @constructor
<add> * @param {string} appBase application base URL
<add> * @param {string} hashPrefix hashbang prefix
<add> */
<add>function LocationHashbangInHtml5Url(appBase, hashPrefix) {
<add> LocationHashbangUrl.apply(this, arguments);
<add>
<add> var appBaseNoFile = stripFile(appBase);
<ide>
<add> this.$$rewrite = function(url) {
<add> var appUrl;
<ide>
<del> this.$$parse(url);
<add> if ( appBase == stripHash(url) ) {
<add> return url;
<add> } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
<add> return appBase + hashPrefix + appUrl;
<add> } else if ( appBaseNoFile === url + '/') {
<add> return appBaseNoFile;
<add> }
<add> }
<ide> }
<ide>
<ide>
<del>LocationUrl.prototype = {
<add>LocationHashbangInHtml5Url.prototype =
<add> LocationHashbangUrl.prototype =
<add> LocationHtml5Url.prototype = {
<ide>
<ide> /**
<ide> * Has any change been replacing ?
<ide> LocationUrl.prototype = {
<ide> }
<ide> };
<ide>
<del>LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
<del>
<del>function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
<del> LocationHashbangUrl.apply(this, arguments);
<del>
<del>
<del> this.$$rewriteAppUrl = function(absoluteLinkUrl) {
<del> if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
<del> return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
<del> }
<del> }
<del>}
<del>
<del>LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
<del>
<ide> function locationGetter(property) {
<ide> return function() {
<ide> return this[property];
<ide> function $LocationProvider(){
<ide> this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
<ide> function( $rootScope, $browser, $sniffer, $rootElement) {
<ide> var $location,
<del> basePath,
<del> pathPrefix,
<del> initUrl = $browser.url(),
<del> initUrlParts = matchUrl(initUrl),
<del> appBaseUrl;
<add> LocationMode,
<add> baseHref = $browser.baseHref(),
<add> initialUrl = $browser.url(),
<add> appBase;
<ide>
<ide> if (html5Mode) {
<del> basePath = $browser.baseHref() || '/';
<del> pathPrefix = pathPrefixFromBase(basePath);
<del> appBaseUrl =
<del> composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
<del> pathPrefix + '/';
<del>
<del> if ($sniffer.history) {
<del> $location = new LocationUrl(
<del> convertToHtml5Url(initUrl, basePath, hashPrefix),
<del> pathPrefix, appBaseUrl);
<del> } else {
<del> $location = new LocationHashbangInHtml5Url(
<del> convertToHashbangUrl(initUrl, basePath, hashPrefix),
<del> hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
<del> }
<add> appBase = baseHref ? serverBase(initialUrl) + baseHref : initialUrl;
<add> LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
<ide> } else {
<del> appBaseUrl =
<del> composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
<del> (initUrlParts.path || '') +
<del> (initUrlParts.search ? ('?' + initUrlParts.search) : '') +
<del> '#' + hashPrefix + '/';
<del>
<del> $location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
<add> appBase = stripHash(initialUrl);
<add> LocationMode = LocationHashbangUrl;
<ide> }
<add> $location = new LocationMode(appBase, '#' + hashPrefix);
<add> $location.$$parse($location.$$rewrite(initialUrl));
<ide>
<ide> $rootElement.bind('click', function(event) {
<ide> // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
<ide> function $LocationProvider(){
<ide> }
<ide>
<ide> var absHref = elm.prop('href'),
<del> rewrittenUrl = $location.$$rewriteAppUrl(absHref);
<add> rewrittenUrl = $location.$$rewrite(absHref);
<ide>
<ide> if (absHref && !elm.attr('target') && rewrittenUrl) {
<ide> // update location manually
<ide> function $LocationProvider(){
<ide>
<ide>
<ide> // rewrite hashbang url <> html5 url
<del> if ($location.absUrl() != initUrl) {
<add> if ($location.absUrl() != initialUrl) {
<ide> $browser.url($location.absUrl(), true);
<ide> }
<ide>
<ide><path>test/ng/locationSpec.js
<ide> describe('$location', function() {
<ide>
<ide> describe('NewUrl', function() {
<ide> beforeEach(function() {
<del> url = new LocationUrl('http://www.domain.com:9877/path/b?search=a&b=c&d#hash');
<add> url = new LocationHtml5Url('http://www.domain.com:9877/');
<add> url.$$parse('http://www.domain.com:9877/path/b?search=a&b=c&d#hash');
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should parse new url', function() {
<del> url = new LocationUrl('http://host.com/base');
<add> url = new LocationHtml5Url('http://host.com/');
<add> url.$$parse('http://host.com/base');
<ide> expect(url.path()).toBe('/base');
<ide>
<del> url = new LocationUrl('http://host.com/base#');
<add> url = new LocationHtml5Url('http://host.com/');
<add> url.$$parse('http://host.com/base#');
<ide> expect(url.path()).toBe('/base');
<ide> });
<ide>
<ide>
<ide> it('should prefix path with forward-slash', function() {
<del> url = new LocationUrl('http://server/a');
<add> url = new LocationHtml5Url('http://server/');
<ide> url.path('b');
<ide>
<ide> expect(url.path()).toBe('/b');
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should set path to forward-slash when empty', function() {
<del> url = new LocationUrl('http://server');
<add> url = new LocationHtml5Url('http://server/');
<add> url.$$parse('http://server/')
<ide> expect(url.path()).toBe('/');
<ide> expect(url.absUrl()).toBe('http://server/');
<ide> });
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should prepend path with basePath', function() {
<del> url = new LocationUrl('http://server/base/abc?a', '/base');
<add> url = new LocationHtml5Url('http://server/base/');
<add> url.$$parse('http://server/base/abc?a');
<ide> expect(url.path()).toBe('/abc');
<ide> expect(url.search()).toEqual({a: true});
<ide>
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> it('should throw error when invalid url given', function() {
<del> url = new LocationUrl('http://server.org/base/abc', '/base');
<add> it('should throw error when invalid server url given', function() {
<add> url = new LocationHtml5Url('http://server.org/base/abc', '/base');
<add>
<add> expect(function() {
<add> url.$$parse('http://other.server.org/path#/path');
<add> }).toThrow('Invalid url "http://other.server.org/path#/path", missing path prefix "http://server.org/base/".');
<add> });
<add>
<add>
<add> it('should throw error when invalid base url given', function() {
<add> url = new LocationHtml5Url('http://server.org/base/abc', '/base');
<ide>
<ide> expect(function() {
<ide> url.$$parse('http://server.org/path#/path');
<del> }).toThrow('Invalid url "http://server.org/path#/path", missing path prefix "/base" !');
<add> }).toThrow('Invalid url "http://server.org/path#/path", missing path prefix "http://server.org/base/".');
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should decode special characters', function() {
<del> url = new LocationUrl('http://host.com/a%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23');
<add> url = new LocationHtml5Url('http://host.com/');
<add> url.$$parse('http://host.com/a%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23');
<ide> expect(url.path()).toBe('/a <>#');
<ide> expect(url.search()).toEqual({'i j': '<>#'});
<ide> expect(url.hash()).toBe('x <>#');
<ide> describe('$location', function() {
<ide> describe('HashbangUrl', function() {
<ide>
<ide> beforeEach(function() {
<del> url = new LocationHashbangUrl('http://www.server.org:1234/base#!/path?a=b&c#hash', '!');
<add> url = new LocationHashbangUrl('http://www.server.org:1234/base', '#!');
<add> url.$$parse('http://www.server.org:1234/base#!/path?a=b&c#hash');
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should preserve query params in base', function() {
<del> url = new LocationHashbangUrl('http://www.server.org:1234/base?base=param#/path?a=b&c#hash', '');
<add> url = new LocationHashbangUrl('http://www.server.org:1234/base?base=param', '#');
<add> url.$$parse('http://www.server.org:1234/base?base=param#/path?a=b&c#hash');
<ide> expect(url.absUrl()).toBe('http://www.server.org:1234/base?base=param#/path?a=b&c#hash');
<ide>
<ide> url.path('/new/path');
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should prefix path with forward-slash', function() {
<del> url = new LocationHashbangUrl('http://host.com/base#path', '');
<add> url = new LocationHashbangUrl('http://host.com/base', '#');
<add> url.$$parse('http://host.com/base#path');
<ide> expect(url.path()).toBe('/path');
<ide> expect(url.absUrl()).toBe('http://host.com/base#/path');
<ide>
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should set path to forward-slash when empty', function() {
<del> url = new LocationHashbangUrl('http://server/base#!', '!');
<add> url = new LocationHashbangUrl('http://server/base', '#!');
<add> url.$$parse('http://server/base');
<ide> url.path('aaa');
<ide>
<ide> expect(url.path()).toBe('/aaa');
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> it('should throw error when invalid url given', function() {
<add> it('should throw error when invalid server url given', function() {
<ide> expect(function() {
<ide> url.$$parse('http://server.org/path#/path');
<del> }).toThrow('Invalid url "http://server.org/path#/path", missing hash prefix "!" !');
<add> }).toThrow('Invalid url "http://server.org/path#/path", does not start with "http://www.server.org:1234/base".');
<add> });
<add>
<add>
<add> it('should throw error when invalid hashbang prefix given', function() {
<add> expect(function() {
<add> url.$$parse('http://www.server.org:1234/base#/path');
<add> }).toThrow('Invalid url "http://www.server.org:1234/base#/path", missing hash prefix "#!".');
<ide> });
<ide>
<ide>
<ide> describe('$location', function() {
<ide>
<ide>
<ide> it('should decode special characters', function() {
<del> url = new LocationHashbangUrl('http://host.com/a#/%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23', '');
<add> url = new LocationHashbangUrl('http://host.com/a', '#');
<add> url.$$parse('http://host.com/a#/%20%3C%3E%23?i%20j=%3C%3E%23#x%20%3C%3E%23');
<ide> expect(url.path()).toBe('/ <>#');
<ide> expect(url.search()).toEqual({'i j': '<>#'});
<ide> expect(url.hash()).toBe('x <>#');
<ide> });
<ide>
<ide>
<ide> it('should return decoded characters for search specified in URL', function() {
<del> var locationUrl = new LocationUrl('http://host.com/?q=1%2F2%203');
<add> var locationUrl = new LocationHtml5Url('http://host.com/');
<add> locationUrl.$$parse('http://host.com/?q=1%2F2%203');
<ide> expect(locationUrl.search()).toEqual({'q': '1/2 3'});
<ide> });
<ide>
<ide>
<ide> it('should return decoded characters for search specified with setter', function() {
<del> var locationUrl = new LocationUrl('http://host.com/');
<add> var locationUrl = new LocationHtml5Url('http://host.com/');
<add> locationUrl.$$parse('http://host.com/')
<ide> locationUrl.search('q', '1/2 3');
<ide> expect(locationUrl.search()).toEqual({'q': '1/2 3'});
<ide> });
<ide> describe('$location', function() {
<ide> describe('wiring', function() {
<ide>
<ide> beforeEach(initService(false, '!', true));
<del> beforeEach(inject(initBrowser('http://new.com/a/b#!', '/a/b')));
<add> beforeEach(inject(initBrowser('http://new.com/a/b#!', 'http://new.com/a/b')));
<ide>
<ide>
<ide> it('should update $location when browser url changes', inject(function($browser, $location) {
<ide> describe('$location', function() {
<ide> it('should not $apply when browser url changed inside $apply', inject(
<ide> function($rootScope, $browser, $location) {
<ide> var OLD_URL = $browser.url(),
<del> NEW_URL = 'http://updated.com/url';
<add> NEW_URL = 'http://new.com/a/b#!/new';
<ide>
<ide>
<ide> $rootScope.$apply(function() {
<ide> describe('$location', function() {
<ide> it('should not $apply when browser url changed inside $digest', inject(
<ide> function($rootScope, $browser, $location) {
<ide> var OLD_URL = $browser.url(),
<del> NEW_URL = 'http://updated.com/url',
<add> NEW_URL = 'http://new.com/a/b#!/new',
<ide> notRunYet = true;
<ide>
<ide> $rootScope.$watch(function() {
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> describe('URL_MATCH', function() {
<add> describe('SERVER_MATCH', function() {
<ide>
<ide> it('should parse basic url', function() {
<del> var match = URL_MATCH.exec('http://www.angularjs.org/path?search#hash?x=x');
<add> var match = SERVER_MATCH.exec('http://www.angularjs.org/path?search#hash?x=x');
<ide>
<ide> expect(match[1]).toBe('http');
<ide> expect(match[3]).toBe('www.angularjs.org');
<del> expect(match[6]).toBe('/path');
<del> expect(match[8]).toBe('search');
<del> expect(match[10]).toBe('hash?x=x');
<ide> });
<ide>
<ide>
<ide> it('should parse file://', function() {
<del> var match = URL_MATCH.exec('file:///Users/Shared/misko/work/angular.js/scenario/widgets.html');
<add> var match = SERVER_MATCH.exec('file:///Users/Shared/misko/work/angular.js/scenario/widgets.html');
<ide>
<ide> expect(match[1]).toBe('file');
<ide> expect(match[3]).toBe('');
<ide> expect(match[5]).toBeFalsy();
<del> expect(match[6]).toBe('/Users/Shared/misko/work/angular.js/scenario/widgets.html');
<del> expect(match[8]).toBeFalsy();
<ide> });
<ide>
<ide>
<ide> it('should parse url with "-" in host', function() {
<del> var match = URL_MATCH.exec('http://a-b1.c-d.09/path');
<add> var match = SERVER_MATCH.exec('http://a-b1.c-d.09/path');
<ide>
<ide> expect(match[1]).toBe('http');
<ide> expect(match[3]).toBe('a-b1.c-d.09');
<ide> expect(match[5]).toBeFalsy();
<del> expect(match[6]).toBe('/path');
<del> expect(match[8]).toBeFalsy();
<ide> });
<ide>
<ide>
<ide> it('should parse host without "/" at the end', function() {
<del> var match = URL_MATCH.exec('http://host.org');
<add> var match = SERVER_MATCH.exec('http://host.org');
<ide> expect(match[3]).toBe('host.org');
<ide>
<del> match = URL_MATCH.exec('http://host.org#');
<add> match = SERVER_MATCH.exec('http://host.org#');
<ide> expect(match[3]).toBe('host.org');
<ide>
<del> match = URL_MATCH.exec('http://host.org?');
<add> match = SERVER_MATCH.exec('http://host.org?');
<ide> expect(match[3]).toBe('host.org');
<ide> });
<ide>
<ide>
<del> it('should match with just "/" path', function() {
<del> var match = URL_MATCH.exec('http://server/#?book=moby');
<del>
<del> expect(match[10]).toBe('?book=moby');
<del> });
<del>
<del>
<ide> it('should parse chrome extension urls', function() {
<del> var match = URL_MATCH.exec('chrome-extension://jjcldkdmokihdaomalanmlohibnoplog/index.html?foo#bar');
<add> var match = SERVER_MATCH.exec('chrome-extension://jjcldkdmokihdaomalanmlohibnoplog/index.html?foo#bar');
<ide>
<ide> expect(match[1]).toBe('chrome-extension');
<ide> expect(match[3]).toBe('jjcldkdmokihdaomalanmlohibnoplog');
<del> expect(match[6]).toBe('/index.html');
<del> expect(match[8]).toBe('foo');
<del> expect(match[10]).toBe('bar');
<ide> });
<ide>
<ide> it('should parse FFOS app:// urls', function() {
<del> var match = URL_MATCH.exec('app://{d0419af1-8b42-41c5-96f4-ef4179e52315}/path');
<add> var match = SERVER_MATCH.exec('app://{d0419af1-8b42-41c5-96f4-ef4179e52315}/path');
<ide>
<ide> expect(match[1]).toBe('app');
<ide> expect(match[3]).toBe('{d0419af1-8b42-41c5-96f4-ef4179e52315}');
<ide> expect(match[5]).toBeFalsy();
<ide> expect(match[6]).toBe('/path');
<ide> expect(match[8]).toBeFalsy();
<ide>
<del> match = URL_MATCH.exec('app://}foo{')
<add> match = SERVER_MATCH.exec('app://}foo{')
<ide> expect(match).toBe(null);
<ide> });
<ide> });
<ide> describe('$location', function() {
<ide> });
<ide>
<ide>
<del> it('should not intercept link clicks outside the app base url space', function() {
<add> it('should not intercept clicks outside the current hash prefix', function() {
<ide> var base, clickHandler;
<ide> module(function($provide) {
<ide> $provide.value('$rootElement', {
<ide> bind: function(event, handler) {
<ide> expect(event).toEqual('click');
<ide> clickHandler = handler;
<ide> },
<del> unbind: angular.noop
<add> unbind: noop
<ide> });
<ide> return function($browser) {
<ide> $browser.url(base = 'http://server/');
<ide> }
<ide> });
<del> inject(function($rootScope, $compile, $browser, $rootElement, $document, $location) {
<add> inject(function($location) {
<ide> // make IE happy
<ide> jqLite(window.document.body).html('<a href="http://server/test.html">link</a>');
<ide>
| 4
|
Python
|
Python
|
add more tests for qr factorization
|
d0b6a7a48e4662b3c2788d541b06ad5d46a2f177
|
<ide><path>numpy/linalg/tests/test_deprecations.py
<add>"""Test deprecation and future warnings.
<add>
<add>"""
<add>import numpy as np
<add>from numpy.testing import assert_warns, run_module_suite
<add>
<add>
<add>def test_qr_mode_full_future_warning():
<add> """Check mode='full' FutureWarning.
<add>
<add> In numpy 1.8 the mode options 'full' and 'economic' in linalg.qr were
<add> deprecated. The release date will probably be sometime in the summer
<add> of 2013.
<add>
<add> """
<add> a = np.eye(2)
<add> assert_warns(DeprecationWarning, np.linalg.qr, a, mode='full')
<add> assert_warns(DeprecationWarning, np.linalg.qr, a, mode='f')
<add> assert_warns(DeprecationWarning, np.linalg.qr, a, mode='economic')
<add> assert_warns(DeprecationWarning, np.linalg.qr, a, mode='e')
<add>
<add>
<add>if __name__ == "__main__":
<add> run_module_suite()
<ide><path>numpy/linalg/tests/test_linalg.py
<ide> def test_reduced_rank():
<ide>
<ide>
<ide> class TestQR(TestCase):
<add>
<add>
<add> def check_qr(self, a):
<add> # This test expects the argument `a` to be an ndarray or
<add> # a subclass of an ndarray of inexact type.
<add> a_type = type(a)
<add> a_dtype = a.dtype
<add> m, n = a.shape
<add> k = min(m, n)
<add>
<add> # mode == 'complete'
<add> q, r = linalg.qr(a, mode='complete')
<add> assert_(q.dtype == a_dtype)
<add> assert_(r.dtype == a_dtype)
<add> assert_(isinstance(q, a_type))
<add> assert_(isinstance(r, a_type))
<add> assert_(q.shape == (m, m))
<add> assert_(r.shape == (m, n))
<add> assert_almost_equal(dot(q, r), a)
<add> assert_almost_equal(dot(q.T.conj(), q), np.eye(m))
<add> assert_almost_equal(np.triu(r), r)
<add>
<add>
<add> # mode == 'reduced'
<add> q1, r1 = linalg.qr(a, mode='reduced')
<add> assert_(q1.dtype == a_dtype)
<add> assert_(r1.dtype == a_dtype)
<add> assert_(isinstance(q1, a_type))
<add> assert_(isinstance(r1, a_type))
<add> assert_(q1.shape == (m, k))
<add> assert_(r1.shape == (k, n))
<add> assert_almost_equal(dot(q1, r1), a)
<add> assert_almost_equal(dot(q1.T.conj(), q1), np.eye(k))
<add> assert_almost_equal(np.triu(r1), r1)
<add>
<add> # mode == 'r'
<add> r2 = linalg.qr(a, mode='r')
<add> assert_(r2.dtype == a_dtype)
<add> assert_(isinstance(r2, a_type))
<add> assert_almost_equal(r2, r1)
<add>
<add>
<add>
<ide> def test_qr_empty(self):
<ide> a = np.zeros((0,2))
<ide> self.assertRaises(linalg.LinAlgError, linalg.qr, a)
<ide>
<ide>
<add> def test_mode_raw(self):
<add> a = array([[1, 2], [3, 4], [5, 6]], dtype=np.double)
<add> b = a.astype(np.single)
<add>
<add> # m > n
<add> h1, tau1 = (
<add> array([[-5.91607978, 0.43377175, 0.72295291],
<add> [-7.43735744, 0.82807867, 0.89262383]]),
<add> array([ 1.16903085, 1.113104 ])
<add> )
<add> # m > n
<add> h2, tau2 = (
<add> array([[-2.23606798, 0.61803399],
<add> [-4.91934955, -0.89442719],
<add> [-7.60263112, -1.78885438]]),
<add> array([ 1.4472136, 0. ])
<add> )
<add>
<add> # Test double
<add> h, tau = linalg.qr(a, mode='raw')
<add> assert_(h.dtype == np.double)
<add> assert_(tau.dtype == np.double)
<add> old_assert_almost_equal(h, h1, decimal=8)
<add> old_assert_almost_equal(tau, tau1, decimal=8)
<add>
<add> h, tau = linalg.qr(a.T, mode='raw')
<add> assert_(h.dtype == np.double)
<add> assert_(tau.dtype == np.double)
<add> old_assert_almost_equal(h, h2, decimal=8)
<add> old_assert_almost_equal(tau, tau2, decimal=8)
<add>
<add> # Test single
<add> h, tau = linalg.qr(b, mode='raw')
<add> assert_(h.dtype == np.double)
<add> assert_(tau.dtype == np.double)
<add> old_assert_almost_equal(h, h1, decimal=8)
<add> old_assert_almost_equal(tau, tau1, decimal=8)
<add>
<add>
<add> def test_mode_all_but_economic(self):
<add> a = array([[1, 2], [3, 4]])
<add> b = array([[1, 2], [3, 4], [5, 6]])
<add> for dt in "fd":
<add> m1 = a.astype(dt)
<add> m2 = b.astype(dt)
<add> self.check_qr(m1)
<add> self.check_qr(m2)
<add> self.check_qr(m2.T)
<add> self.check_qr(matrix(m1))
<add> for dt in "fd":
<add> m1 = 1 + 1j * a.astype(dt)
<add> m2 = 1 + 1j * b.astype(dt)
<add> self.check_qr(m1)
<add> self.check_qr(m2)
<add> self.check_qr(m2.T)
<add> self.check_qr(matrix(m1))
<add>
<add>
<add>
<add>
<add>
<ide> def test_byteorder_check():
<ide> # Byte order check should pass for native order
<ide> if sys.byteorder == 'little':
| 2
|
Javascript
|
Javascript
|
remove applyastemplateargument function
|
917200d46a9b390c9062c69019aafb9a87d7f92a
|
<ide><path>lib/dependencies/ModuleDependencyTemplateAsId.js
<ide> class ModuleDependencyTemplateAsId {
<ide> content = require("./WebpackMissingModule").module(dep.request);
<ide> source.replace(dep.range[0], dep.range[1] - 1, content);
<ide> }
<del>
<del> applyAsTemplateArgument(name, dep, source) {
<del> if(!dep.range) return;
<del> source.replace(dep.range[0], dep.range[1] - 1, name);
<del> }
<ide> }
<ide> module.exports = ModuleDependencyTemplateAsId;
| 1
|
Java
|
Java
|
add support for forwardedheaderfilter sendredirect
|
db2ebd30da027498273ed7a4ea6714d07adef6fd
|
<ide><path>spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java
<ide> import java.util.Locale;
<ide> import java.util.Map;
<ide> import java.util.Set;
<add>
<ide> import javax.servlet.FilterChain;
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.http.HttpServletRequest;
<ide> import javax.servlet.http.HttpServletRequestWrapper;
<ide> import javax.servlet.http.HttpServletResponse;
<add>import javax.servlet.http.HttpServletResponseWrapper;
<ide>
<ide> import org.springframework.http.HttpRequest;
<ide> import org.springframework.http.server.ServletServerHttpRequest;
<ide> import org.springframework.web.util.UrlPathHelper;
<ide>
<ide> /**
<del> * Filter that wraps the request in order to override its
<add> * Filter that wraps the request and response in order to override its
<ide> * {@link HttpServletRequest#getServerName() getServerName()},
<ide> * {@link HttpServletRequest#getServerPort() getServerPort()},
<del> * {@link HttpServletRequest#getScheme() getScheme()}, and
<del> * {@link HttpServletRequest#isSecure() isSecure()} methods with values derived
<del> * from "Forwarded" or "X-Forwarded-*" headers. In effect the wrapped request
<del> * reflects the client-originated protocol and address.
<add> * {@link HttpServletRequest#getScheme() getScheme()},
<add> * {@link HttpServletRequest#isSecure() isSecure()},
<add> * {@link HttpServletResponse#sendRedirect(String) sendRedirect(String)},
<add> * methods with values derived from "Forwarded" or "X-Forwarded-*"
<add> * headers. In effect the wrapped request and response reflects the
<add> * client-originated protocol and address.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Eddú Meléndez
<add> * @author Rob Winch
<ide> * @since 4.3
<ide> */
<ide> public class ForwardedHeaderFilter extends OncePerRequestFilter {
<ide> protected boolean shouldNotFilterErrorDispatch() {
<ide> protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
<ide> FilterChain filterChain) throws ServletException, IOException {
<ide>
<del> filterChain.doFilter(new ForwardedHeaderRequestWrapper(request, this.pathHelper), response);
<add> ForwardedHeaderRequestWrapper wrappedRequest = new ForwardedHeaderRequestWrapper(request, this.pathHelper);
<add> ForwardedHeaderResponseWrapper wrappedResponse = new ForwardedHeaderResponseWrapper(response, wrappedRequest);
<add> filterChain.doFilter(wrappedRequest, wrappedResponse);
<ide> }
<ide>
<ide>
<ide> public Enumeration<String> getHeaderNames() {
<ide> }
<ide> }
<ide>
<add> private static class ForwardedHeaderResponseWrapper extends HttpServletResponseWrapper {
<add> private static final String FOLDER_SEPARATOR = "/";
<add>
<add> private final HttpServletRequest request;
<add>
<add> public ForwardedHeaderResponseWrapper(HttpServletResponse response, HttpServletRequest request) {
<add> super(response);
<add> this.request = request;
<add> }
<add>
<add> @Override
<add> public void sendRedirect(String location) throws IOException {
<add> String forwardedLocation = forwardedLocation(location);
<add>
<add> super.sendRedirect(forwardedLocation);
<add> }
<add>
<add> private String forwardedLocation(String location) {
<add> if(hasScheme(location)) {
<add> return location;
<add> }
<add>
<add> return createForwardedLocation(location);
<add> }
<add>
<add> private String createForwardedLocation(String location) {
<add> boolean isNetworkPathReference = location.startsWith("//");
<add> if(isNetworkPathReference) {
<add> UriComponentsBuilder schemeForwardedLocation = UriComponentsBuilder.fromUriString(location).scheme(request.getScheme());
<add> return schemeForwardedLocation.toUriString();
<add> }
<add>
<add> HttpRequest httpRequest = new ServletServerHttpRequest(request);
<add> UriComponentsBuilder forwardedLocation = UriComponentsBuilder.fromHttpRequest(httpRequest);
<add> boolean isRelativeToContextPath = location.startsWith(FOLDER_SEPARATOR);
<add> if(isRelativeToContextPath) {
<add> forwardedLocation.replacePath(request.getContextPath());
<add> } else if(endsWithFileSpecificPart(forwardedLocation)) {
<add> // remove a file specific part from existing request
<add> forwardedLocation.path("/../");
<add> }
<add> forwardedLocation.path(location);
<add> return forwardedLocation.build().normalize().toUriString();
<add> }
<add>
<add> private boolean endsWithFileSpecificPart(UriComponentsBuilder forwardedLocation) {
<add> return !forwardedLocation.build().getPath().endsWith(FOLDER_SEPARATOR);
<add> }
<add>
<add> private boolean hasScheme(String location) {
<add> String locationScheme = UriComponentsBuilder.fromUriString(location).build().getScheme();
<add> return locationScheme != null;
<add> }
<add> }
<add>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/filter/ForwardedHeaderFilterTests.java
<ide>
<ide> import java.io.IOException;
<ide> import java.util.Enumeration;
<add>
<add>import javax.servlet.Filter;
<add>import javax.servlet.FilterChain;
<ide> import javax.servlet.ServletException;
<ide> import javax.servlet.http.HttpServlet;
<ide> import javax.servlet.http.HttpServletRequest;
<add>import javax.servlet.http.HttpServletResponse;
<ide>
<ide> import org.junit.Before;
<ide> import org.junit.Test;
<ide> * Unit tests for {@link ForwardedHeaderFilter}.
<ide> * @author Rossen Stoyanchev
<ide> * @author Eddú Meléndez
<add> * @author Rob Winch
<ide> */
<ide> public class ForwardedHeaderFilterTests {
<ide>
<ide> public void contextPathWithForwardedPrefixTrailingSlash() throws Exception {
<ide> assertEquals("/prefix", actual);
<ide> }
<ide>
<add> @Test
<add> public void sendRedirectWithAbsolutePath() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add>
<add> String redirectedUrl = sendRedirect("/foo/bar");
<add> assertEquals("https://example.com/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithContextPath() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add> this.request.setContextPath("/context");
<add>
<add> String redirectedUrl = sendRedirect("/foo/bar");
<add> assertEquals("https://example.com/context/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithXForwardedPrefix() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add> this.request.addHeader(X_FORWARDED_PREFIX, "/prefix");
<add>
<add> String redirectedUrl = sendRedirect("/foo/bar");
<add> assertEquals("https://example.com/prefix/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithXForwardedPrefixAndContextPath() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add> this.request.addHeader(X_FORWARDED_PREFIX, "/prefix");
<add> this.request.setContextPath("/context");
<add>
<add> String redirectedUrl = sendRedirect("/foo/bar");
<add> assertEquals("https://example.com/prefix/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithRelativePath() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add> this.request.setRequestURI("/parent/");
<add>
<add> String redirectedUrl = sendRedirect("foo/bar");
<add> assertEquals("https://example.com/parent/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithFileInPathAndRelativeRedirect() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add> this.request.setRequestURI("/context/a");
<add>
<add> String redirectedUrl = sendRedirect("foo/bar");
<add> assertEquals("https://example.com/context/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithRelativePathIgnoresFile() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add> this.request.setRequestURI("/parent");
<add>
<add> String redirectedUrl = sendRedirect("foo/bar");
<add> assertEquals("https://example.com/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithLocationDotDotPath() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add>
<add> String redirectedUrl = sendRedirect("parent/../foo/bar");
<add> assertEquals("https://example.com/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithLocationHasScheme() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add>
<add> String location = "http://other.info/foo/bar";
<add> String redirectedUrl = sendRedirect(location);
<add> assertEquals(location, redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithLocationSlashSlash() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add>
<add> String location = "//other.info/foo/bar";
<add> String redirectedUrl = sendRedirect(location);
<add> assertEquals("https:" + location, redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithLocationSlashSlashParentDotDot() throws Exception {
<add> this.request.addHeader(X_FORWARDED_PROTO, "https");
<add> this.request.addHeader(X_FORWARDED_HOST, "example.com");
<add> this.request.addHeader(X_FORWARDED_PORT, "443");
<add>
<add> String location = "//other.info/parent/../foo/bar";
<add> String redirectedUrl = sendRedirect(location);
<add> assertEquals("https:" + location, redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithNoXForwardedAndAbsolutePath() throws Exception {
<add> String redirectedUrl = sendRedirect("/foo/bar");
<add> assertEquals("/foo/bar", redirectedUrl);
<add> }
<add>
<add> @Test
<add> public void sendRedirectWithNoXForwardedAndDotDotPath() throws Exception {
<add> String redirectedUrl = sendRedirect("../foo/bar");
<add> assertEquals("../foo/bar", redirectedUrl);
<add> }
<add>
<add> private String sendRedirect(final String location) throws ServletException, IOException {
<add> MockHttpServletResponse response = doWithFiltersAndGetResponse(this.filter, new OncePerRequestFilter() {
<add> @Override
<add> protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
<add> throws ServletException, IOException {
<add> response.sendRedirect(location);
<add> }
<add> });
<add>
<add> return response.getRedirectedUrl();
<add> }
<add>
<add> private MockHttpServletResponse doWithFiltersAndGetResponse(Filter... filters) throws ServletException, IOException {
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add> FilterChain filterChain = new MockFilterChain(new HttpServlet() {}, filters);
<add> filterChain.doFilter(request, response);
<add> return response;
<add> }
<add>
<ide> private String filterAndGetContextPath() throws ServletException, IOException {
<ide> return filterAndGetWrappedRequest().getContextPath();
<ide> }
| 2
|
Ruby
|
Ruby
|
share common logic
|
443111896e71f394a19047caf6ac9e0e8e2e9b4d
|
<ide><path>Library/Homebrew/update_migrator/cache_entries_to_symlinks.rb
<ide> def migrate_cache_entries_to_symlinks(initial_version)
<ide>
<ide> ohai "Migrating cache entries..."
<ide>
<add> cache_entries = lambda do |path|
<add> if path.directory?
<add> path.children
<add> .reject(&:symlink?)
<add> .select(&:file?)
<add> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<add> .uniq
<add> else
<add> []
<add> end
<add> end
<add>
<ide> load_formula = lambda do |formula|
<ide> begin
<ide> Formula[formula]
<ide> def migrate_cache_entries_to_symlinks(initial_version)
<ide> end
<ide> end
<ide>
<del> formula_downloaders = if HOMEBREW_CACHE.directory?
<del> HOMEBREW_CACHE.children
<del> .reject(&:symlink?)
<del> .select(&:file?)
<del> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<del> .uniq
<del> .map(&load_formula)
<del> .compact
<del> .flat_map { |formula| formula_resources(formula) }
<del> .map { |resource| [resource.downloader, resource.download_name, resource.version] }
<del> else
<del> []
<del> end
<add> formula_downloaders =
<add> cache_entries.call(HOMEBREW_CACHE)
<add> .map(&load_formula)
<add> .compact
<add> .flat_map { |formula| formula_resources(formula) }
<add> .map { |resource| [resource.downloader, resource.download_name, resource.version] }
<ide>
<del> cask_downloaders = if (HOMEBREW_CACHE/"Cask").directory?
<del> (HOMEBREW_CACHE/"Cask").children
<del> .reject(&:symlink?)
<del> .select(&:file?)
<del> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") }
<del> .uniq
<del> .map(&load_cask)
<del> .compact
<del> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] }
<del> else
<del> []
<del> end
<add> cask_downloaders =
<add> cache_entries.call(HOMEBREW_CACHE/"Cask")
<add> .map(&load_cask)
<add> .compact
<add> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] }
<ide>
<ide> downloaders = formula_downloaders + cask_downloaders
<ide>
| 1
|
Go
|
Go
|
update version to not use string anymore
|
3ee37f547f4685ab88bfc39517cc18c1911451e5
|
<ide><path>api/common.go
<ide> package api
<ide> import (
<ide> "fmt"
<ide> "github.com/dotcloud/docker/engine"
<add> "github.com/dotcloud/docker/pkg/version"
<ide> "github.com/dotcloud/docker/utils"
<ide> "mime"
<ide> "strings"
<ide> )
<ide>
<ide> const (
<del> APIVERSION = "1.10"
<del> DEFAULTHTTPHOST = "127.0.0.1"
<del> DEFAULTUNIXSOCKET = "/var/run/docker.sock"
<add> APIVERSION version.Version = "1.10"
<add> DEFAULTHTTPHOST = "127.0.0.1"
<add> DEFAULTUNIXSOCKET = "/var/run/docker.sock"
<ide> )
<ide>
<ide> func ValidateHost(val string) (string, error) {
<ide><path>api/server/server.go
<ide> func makeHttpHandler(eng *engine.Engine, logging bool, localMethod string, local
<ide>
<ide> if strings.Contains(r.Header.Get("User-Agent"), "Docker-Client/") {
<ide> userAgent := strings.Split(r.Header.Get("User-Agent"), "/")
<del> if len(userAgent) == 2 && !dockerVersion.Equal(userAgent[1]) {
<add> if len(userAgent) == 2 && !dockerVersion.Equal(version.Version(userAgent[1])) {
<ide> utils.Debugf("Warning: client and server don't have the same version (client: %s, server: %s)", userAgent[1], dockerVersion)
<ide> }
<ide> }
<ide><path>pkg/version/version.go
<ide> import (
<ide>
<ide> type Version string
<ide>
<del>func (me Version) compareTo(other string) int {
<add>func (me Version) compareTo(other Version) int {
<ide> var (
<ide> meTab = strings.Split(string(me), ".")
<del> otherTab = strings.Split(other, ".")
<add> otherTab = strings.Split(string(other), ".")
<ide> )
<ide> for i, s := range meTab {
<ide> var meInt, otherInt int
<ide> func (me Version) compareTo(other string) int {
<ide> return 0
<ide> }
<ide>
<del>func (me Version) LessThan(other string) bool {
<add>func (me Version) LessThan(other Version) bool {
<ide> return me.compareTo(other) == -1
<ide> }
<ide>
<del>func (me Version) LessThanOrEqualTo(other string) bool {
<add>func (me Version) LessThanOrEqualTo(other Version) bool {
<ide> return me.compareTo(other) <= 0
<ide> }
<ide>
<del>func (me Version) GreaterThan(other string) bool {
<add>func (me Version) GreaterThan(other Version) bool {
<ide> return me.compareTo(other) == 1
<ide> }
<ide>
<del>func (me Version) GreaterThanOrEqualTo(other string) bool {
<add>func (me Version) GreaterThanOrEqualTo(other Version) bool {
<ide> return me.compareTo(other) >= 0
<ide> }
<ide>
<del>func (me Version) Equal(other string) bool {
<add>func (me Version) Equal(other Version) bool {
<ide> return me.compareTo(other) == 0
<ide> }
<ide><path>pkg/version/version_test.go
<ide> import (
<ide> )
<ide>
<ide> func assertVersion(t *testing.T, a, b string, result int) {
<del> if r := Version(a).compareTo(b); r != result {
<add> if r := Version(a).compareTo(Version(b)); r != result {
<ide> t.Fatalf("Unexpected version comparison result. Found %d, expected %d", r, result)
<ide> }
<ide> }
| 4
|
Javascript
|
Javascript
|
add localesorted argument to weekday listers
|
08b2661a9e8384ff0eeabbf4c4f339164e0bcc92
|
<ide><path>src/lib/locale/lists.js
<ide> function get (format, index, field, setter) {
<ide> return locale[field](utc, format);
<ide> }
<ide>
<del>function list (format, index, field, count, setter) {
<add>function listMonthsImpl (format, index, field) {
<ide> if (typeof format === 'number') {
<ide> index = format;
<ide> format = undefined;
<ide> function list (format, index, field, count, setter) {
<ide> format = format || '';
<ide>
<ide> if (index != null) {
<del> return get(format, index, field, setter);
<add> return get(format, index, field, 'month');
<ide> }
<ide>
<ide> var i;
<ide> var out = [];
<del> for (i = 0; i < count; i++) {
<del> out[i] = get(format, i, field, setter);
<add> for (i = 0; i < 12; i++) {
<add> out[i] = get(format, i, field, 'month');
<add> }
<add> return out;
<add>}
<add>
<add>// ()
<add>// (5)
<add>// (fmt, 5)
<add>// (fmt)
<add>// (true)
<add>// (true, 5)
<add>// (true, fmt, 5)
<add>// (true, fmt)
<add>function listWeekdaysImpl (localeSorted, format, index, field) {
<add> if (typeof localeSorted === 'boolean') {
<add> if (typeof format === 'number') {
<add> index = format;
<add> format = undefined;
<add> }
<add>
<add> format = format || '';
<add> } else {
<add> format = localeSorted;
<add> index = format;
<add> localeSorted = false;
<add>
<add> if (typeof format === 'number') {
<add> index = format;
<add> format = undefined;
<add> }
<add>
<add> format = format || '';
<add> }
<add>
<add> var locale = getLocale(),
<add> shift = localeSorted ? locale._week.dow : 0;
<add>
<add> if (index != null) {
<add> return get(format, (index + shift) % 7, field, 'day');
<add> }
<add>
<add> var i;
<add> var out = [];
<add> for (i = 0; i < 7; i++) {
<add> out[i] = get(format, (i + shift) % 7, field, 'day');
<ide> }
<ide> return out;
<ide> }
<ide>
<ide> export function listMonths (format, index) {
<del> return list(format, index, 'months', 12, 'month');
<add> return listMonthsImpl(format, index, 'months');
<ide> }
<ide>
<ide> export function listMonthsShort (format, index) {
<del> return list(format, index, 'monthsShort', 12, 'month');
<add> return listMonthsImpl(format, index, 'monthsShort');
<ide> }
<ide>
<del>export function listWeekdays (format, index) {
<del> return list(format, index, 'weekdays', 7, 'day');
<add>export function listWeekdays (localeSorted, format, index) {
<add> return listWeekdaysImpl(localeSorted, format, index, 'weekdays');
<ide> }
<ide>
<del>export function listWeekdaysShort (format, index) {
<del> return list(format, index, 'weekdaysShort', 7, 'day');
<add>export function listWeekdaysShort (localeSorted, format, index) {
<add> return listWeekdaysImpl(localeSorted, format, index, 'weekdaysShort');
<ide> }
<ide>
<del>export function listWeekdaysMin (format, index) {
<del> return list(format, index, 'weekdaysMin', 7, 'day');
<add>export function listWeekdaysMin (localeSorted, format, index) {
<add> return listWeekdaysImpl(localeSorted, format, index, 'weekdaysMin');
<ide> }
<ide><path>src/test/moment/listers.js
<ide> test('localized', function (assert) {
<ide> monthsShort = 'on_tw_th_fo_fi_si_se_ei_ni_te_el_tw'.split('_'),
<ide> weekdays = 'one_two_three_four_five_six_seven'.split('_'),
<ide> weekdaysShort = 'on_tw_th_fo_fi_si_se'.split('_'),
<del> weekdaysMin = '1_2_3_4_5_6_7'.split('_');
<add> weekdaysMin = '1_2_3_4_5_6_7'.split('_'),
<add> weekdaysLocale = 'four_five_six_seven_one_two_three'.split('_'),
<add> weekdaysShortLocale = 'fo_fi_si_se_on_tw_th'.split('_'),
<add> weekdaysMinLocale = '4_5_6_7_1_2_3'.split('_'),
<add> week = {
<add> dow : 3,
<add> doy : 6
<add> };
<ide>
<ide> moment.locale('numerologists', {
<ide> months : months,
<ide> monthsShort : monthsShort,
<ide> weekdays : weekdays,
<ide> weekdaysShort: weekdaysShort,
<del> weekdaysMin: weekdaysMin
<add> weekdaysMin: weekdaysMin,
<add> week : week
<ide> });
<ide>
<ide> assert.deepEqual(moment.months(), months);
<ide> test('localized', function (assert) {
<ide> assert.equal(moment.weekdays(2), 'three');
<ide> assert.equal(moment.weekdaysShort(2), 'th');
<ide> assert.equal(moment.weekdaysMin(2), '3');
<add>
<add> assert.deepEqual(moment.weekdays(true), weekdaysLocale);
<add> assert.deepEqual(moment.weekdaysShort(true), weekdaysShortLocale);
<add> assert.deepEqual(moment.weekdaysMin(true), weekdaysMinLocale);
<add>
<add> assert.equal(moment.weekdays(true, 0), 'four');
<add> assert.equal(moment.weekdaysShort(true, 0), 'fo');
<add> assert.equal(moment.weekdaysMin(true, 0), '4');
<add>
<add> assert.equal(moment.weekdays(false, 2), 'three');
<add> assert.equal(moment.weekdaysShort(false, 2), 'th');
<add> assert.equal(moment.weekdaysMin(false, 2), '3');
<ide> });
<ide>
<ide> test('with functions', function (assert) {
| 2
|
Javascript
|
Javascript
|
remove old eslint-ignores from unstable_ prefix
|
b2624012ea52438dee783425e0d6b87d14c0fc9e
|
<ide><path>packages/next/export/worker.js
<ide> export default async function({
<ide> let curRenderOpts = {}
<ide> let renderMethod = renderToHTML
<ide>
<del> // eslint-disable-next-line camelcase
<ide> const renderedDuringBuild = getStaticProps => {
<del> // eslint-disable-next-line camelcase
<ide> return !buildExport && getStaticProps && !isDynamicRoute(path)
<ide> }
<ide>
<ide><path>test/integration/client-navigation/pages/nav/url-prop-change.js
<ide> export default class UrlPropChange extends React.Component {
<ide> }
<ide> }
<ide>
<del> // eslint-disable-next-line camelcase
<ide> componentDidUpdate(prevProps) {
<ide> if (prevProps.url !== this.props.url) {
<ide> this.setState(() => {
<ide><path>test/integration/getserversideprops/pages/another/index.js
<ide> import Link from 'next/link'
<ide> import fs from 'fs'
<ide> import findUp from 'find-up'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps() {
<ide> const text = fs
<ide> .readFileSync(
<ide><path>test/integration/getserversideprops/pages/blog/[post]/[comment].js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps({ query }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/getserversideprops/pages/blog/[post]/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps({ params }) {
<ide> if (params.post === 'post-10') {
<ide> await new Promise(resolve => {
<ide><path>test/integration/getserversideprops/pages/blog/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps() {
<ide> return {
<ide> props: {
<ide><path>test/integration/getserversideprops/pages/catchall/[...path].js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps({ params }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/getserversideprops/pages/default-revalidate.js
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps() {
<ide> return {
<ide> props: {
<ide><path>test/integration/getserversideprops/pages/index.js
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps() {
<ide> return {
<ide> props: {
<ide><path>test/integration/getserversideprops/pages/invalid-keys.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps({ params, query }) {
<ide> return {
<ide> world: 'world',
<ide><path>test/integration/getserversideprops/pages/something.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps({ params, query }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/getserversideprops/pages/user/[user]/profile.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getServerSideProps({ query }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender-invalid-catchall-params/pages/[...slug].js
<ide> import React from 'react'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticPaths() {
<ide> return { paths: [{ params: { slug: 'hello' } }], fallback: true }
<ide> }
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender-invalid-paths/pages/[foo]/[post].js
<ide> import React from 'react'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticPaths() {
<ide> return { paths: [{ foo: 'bad', baz: 'herro' }], fallback: true }
<ide> }
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender-legacy/pages/blog/[post].js
<ide> import React from 'react'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function unstable_getStaticParams() {
<ide> return ['/blog/post-1']
<ide> }
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender/pages/another/index.js
<ide> import Link from 'next/link'
<ide> import fs from 'fs'
<ide> import findUp from 'find-up'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps() {
<ide> const text = fs
<ide> .readFileSync(
<ide><path>test/integration/prerender/pages/blog/[post]/[comment].js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticPaths() {
<ide> return {
<ide> paths: [
<ide> export async function getStaticPaths() {
<ide> }
<ide> }
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender/pages/blog/[post]/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticPaths() {
<ide> return {
<ide> paths: [
<ide> export async function getStaticPaths() {
<ide>
<ide> let counter = 0
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> if (params.post === 'post-10') {
<ide> await new Promise(resolve => {
<ide><path>test/integration/prerender/pages/blog/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps() {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender/pages/default-revalidate.js
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps() {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender/pages/index.js
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps() {
<ide> // throw new Error('oops from getStaticProps')
<ide> return {
<ide><path>test/integration/prerender/pages/something.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> return {
<ide> props: {
<ide><path>test/integration/prerender/pages/user/[user]/profile.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticPaths() {
<ide> return { paths: [], fallback: true }
<ide> }
<ide>
<del>// eslint-disable-next-line camelcase
<ide> export async function getStaticProps({ params }) {
<ide> return {
<ide> props: {
| 23
|
Python
|
Python
|
add sparse option to np.core.numeric.indices
|
504b287bdf4745256044f336f17c88ddcb0175dd
|
<ide><path>numpy/core/numeric.py
<ide> def roll(a, shift, axis=None):
<ide> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])
<ide> >>> np.roll(x, -2)
<ide> array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])
<del>
<add>
<ide> >>> x2 = np.reshape(x, (2,5))
<ide> >>> x2
<ide> array([[0, 1, 2, 3, 4],
<ide> def cross(a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
<ide>
<ide>
<ide> @set_module('numpy')
<del>def indices(dimensions, dtype=int):
<add>def indices(dimensions, dtype=int, sparse=False):
<ide> """
<ide> Return an array representing the indices of a grid.
<ide>
<del> Compute an array where the subarrays contain index values 0,1,...
<add> Compute an array where the subarrays contain index values 0, 1, ...
<ide> varying only along the corresponding axis.
<ide>
<ide> Parameters
<ide> def indices(dimensions, dtype=int):
<ide> The shape of the grid.
<ide> dtype : dtype, optional
<ide> Data type of the result.
<add> sparse : boolean, optional
<add> Return a sparse representation of the grid instead of a dense
<add> representation. Default is False.
<add>
<add> .. versionadded:: 1.17
<ide>
<ide> Returns
<ide> -------
<del> grid : ndarray
<del> The array of grid indices,
<del> ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
<add> grid : one ndarray or tuple of ndarrays
<add> If sparse is False:
<add> Returns one array of grid indices,
<add> ``grid.shape = (len(dimensions),) + tuple(dimensions)``.
<add> If sparse is True:
<add> Returns a tuple of arrays, with
<add> ``grid[i].shape = (1, ..., 1, dimensions[i], 1, ..., 1)`` with
<add> dimensions[i] in the ith place
<ide>
<ide> See Also
<ide> --------
<del> mgrid, meshgrid
<add> mgrid, ogrid, meshgrid
<ide>
<ide> Notes
<ide> -----
<del> The output shape is obtained by prepending the number of dimensions
<del> in front of the tuple of dimensions, i.e. if `dimensions` is a tuple
<del> ``(r0, ..., rN-1)`` of length ``N``, the output shape is
<del> ``(N,r0,...,rN-1)``.
<add> The output shape in the dense case is obtained by prepending the number
<add> of dimensions in front of the tuple of dimensions, i.e. if `dimensions`
<add> is a tuple ``(r0, ..., rN-1)`` of length ``N``, the output shape is
<add> ``(N, r0, ..., rN-1)``.
<ide>
<ide> The subarrays ``grid[k]`` contains the N-D array of indices along the
<ide> ``k-th`` axis. Explicitly::
<ide>
<del> grid[k,i0,i1,...,iN-1] = ik
<add> grid[k, i0, i1, ..., iN-1] = ik
<ide>
<ide> Examples
<ide> --------
<ide> def indices(dimensions, dtype=int):
<ide> Note that it would be more straightforward in the above example to
<ide> extract the required elements directly with ``x[:2, :3]``.
<ide>
<add> If sparse is set to true, the grid will be returned in a sparse
<add> representation.
<add>
<add> >>> i, j = np.indices((2, 3), sparse=True)
<add> >>> i.shape
<add> (2, 1)
<add> >>> j.shape
<add> (1, 3)
<add> >>> i # row indices
<add> array([[0],
<add> [1]])
<add> >>> j # column indices
<add> array([[0, 1, 2]])
<add>
<ide> """
<ide> dimensions = tuple(dimensions)
<ide> N = len(dimensions)
<ide> shape = (1,)*N
<del> res = empty((N,)+dimensions, dtype=dtype)
<add> if sparse:
<add> res = tuple()
<add> else:
<add> res = empty((N,)+dimensions, dtype=dtype)
<ide> for i, dim in enumerate(dimensions):
<del> res[i] = arange(dim, dtype=dtype).reshape(
<add> idx = arange(dim, dtype=dtype).reshape(
<ide> shape[:i] + (dim,) + shape[i+1:]
<ide> )
<add> if sparse:
<add> res = res + (idx,)
<add> else:
<add> res[i] = idx
<ide> return res
<ide>
<ide>
<ide><path>numpy/core/tests/test_numeric.py
<ide> def test_outer_out_param():
<ide> assert_equal(np.outer(arr2, arr3, out2), out2)
<ide>
<ide>
<add>class TestIndices(object):
<add>
<add> def test_simple(self):
<add> [x, y] = np.indices((4, 3))
<add> assert_array_equal(x, np.array([[0, 0, 0],
<add> [1, 1, 1],
<add> [2, 2, 2],
<add> [3, 3, 3]]))
<add> assert_array_equal(y, np.array([[0, 1, 2],
<add> [0, 1, 2],
<add> [0, 1, 2],
<add> [0, 1, 2]]))
<add>
<add> def test_single_input(self):
<add> [x] = np.indices((4,))
<add> assert_array_equal(x, np.array([0, 1, 2, 3]))
<add>
<add> [x] = np.indices((4,), sparse=True)
<add> assert_array_equal(x, np.array([0, 1, 2, 3]))
<add>
<add> def test_scalar_input(self):
<add> assert_array_equal([], np.indices(()))
<add> assert_array_equal([], np.indices((), sparse=True))
<add> assert_array_equal([[]], np.indices((0,)))
<add> assert_array_equal([[]], np.indices((0,), sparse=True))
<add>
<add> def test_sparse(self):
<add> [x, y] = np.indices((4,3), sparse=True)
<add> assert_array_equal(x, np.array([[0], [1], [2], [3]]))
<add> assert_array_equal(y, np.array([[0, 1, 2]]))
<add>
<add> @pytest.mark.parametrize("dtype", [np.int, np.float32, np.float64])
<add> @pytest.mark.parametrize("dims", [(), (0,), (4, 3)])
<add> def test_return_type(self, dtype, dims):
<add> inds = np.indices(dims, dtype=dtype)
<add> assert_(inds.dtype == dtype)
<add>
<add> for arr in np.indices(dims, dtype=dtype, sparse=True):
<add> assert_(arr.dtype == dtype)
<add>
<add>
<ide> class TestRequire(object):
<ide> flag_names = ['C', 'C_CONTIGUOUS', 'CONTIGUOUS',
<ide> 'F', 'F_CONTIGUOUS', 'FORTRAN',
<ide> def test_zero_dimension(self):
<ide> td = np.tensordot(a, b, (1, 0))
<ide> assert_array_equal(td, np.dot(a, b))
<ide> assert_array_equal(td, np.einsum('ij,jk', a, b))
<del>
<add>
<ide> def test_zero_dimensional(self):
<ide> # gh-12130
<ide> arr_0d = np.array(1)
| 2
|
Mixed
|
Ruby
|
add metadata to schema_migrations
|
0a5afa229d769bce9e221f34053bb93b60817a5a
|
<ide><path>activerecord/CHANGELOG.md
<ide> ## Rails 4.0.0 (unreleased) ##
<ide>
<add>* Add metadata columns to schema_migrations table.
<add> New columns are: migrated_at (timestamp),
<add> fingerprint (md5 hash of migration source), and
<add> name (filename minus version and extension)
<add>
<add> *Josh Susser*
<add>
<ide> * Add STI support to init and building associations.
<ide> Allows you to do BaseClass.new(:type => "SubClass") as well as
<ide> parent.children.build(:type => "SubClass") or parent.build_child
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def dump_schema_information #:nodoc:
<ide> sm_table = ActiveRecord::Migrator.schema_migrations_table_name
<ide>
<ide> ActiveRecord::SchemaMigration.order('version').map { |sm|
<del> "INSERT INTO #{sm_table} (version) VALUES ('#{sm.version}');"
<add> "INSERT INTO #{sm_table} (version, migrated_at, name) VALUES ('#{sm.version}',LOCALTIMESTAMP,'#{sm.name}');"
<ide> }.join "\n\n"
<ide> end
<ide>
<ide> def assume_migrated_upto_version(version, migrations_paths = ActiveRecord::Migra
<ide> end
<ide>
<ide> unless migrated.include?(version)
<del> execute "INSERT INTO #{sm_table} (version) VALUES ('#{version}')"
<add> ActiveRecord::SchemaMigration.create!(:version => version, :migrated_at => Time.now)
<ide> end
<ide>
<ide> inserted = Set.new
<ide> (versions - migrated).each do |v|
<ide> if inserted.include?(v)
<ide> raise "Duplicate migration #{v}. Please renumber your migrations to resolve the conflict."
<ide> elsif v < version
<del> execute "INSERT INTO #{sm_table} (version) VALUES ('#{v}')"
<add> ActiveRecord::SchemaMigration.create!(:version => v, :migrated_at => Time.now)
<ide> inserted << v
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/migration.rb
<ide> require "active_support/core_ext/class/attribute_accessors"
<ide> require 'set'
<add>require 'digest/md5'
<ide>
<ide> module ActiveRecord
<ide> # Exception that can be raised to stop migrations from going backwards.
<ide> def basename
<ide>
<ide> delegate :migrate, :announce, :write, :to => :migration
<ide>
<add> def fingerprint
<add> @fingerprint ||= Digest::MD5.hexdigest(File.read(filename))
<add> end
<add>
<ide> private
<ide>
<ide> def migration
<ide> def run
<ide> raise UnknownMigrationVersionError.new(@target_version) if target.nil?
<ide> unless (up? && migrated.include?(target.version.to_i)) || (down? && !migrated.include?(target.version.to_i))
<ide> target.migrate(@direction)
<del> record_version_state_after_migrating(target.version)
<add> record_version_state_after_migrating(target)
<ide> end
<ide> end
<ide>
<ide> def migrate
<ide> begin
<ide> ddl_transaction do
<ide> migration.migrate(@direction)
<del> record_version_state_after_migrating(migration.version)
<add> record_version_state_after_migrating(migration)
<ide> end
<ide> rescue => e
<ide> canceled_msg = Base.connection.supports_ddl_transactions? ? "this and " : ""
<ide> def validate(migrations)
<ide> raise DuplicateMigrationVersionError.new(version) if version
<ide> end
<ide>
<del> def record_version_state_after_migrating(version)
<add> def record_version_state_after_migrating(target)
<ide> if down?
<del> migrated.delete(version)
<del> ActiveRecord::SchemaMigration.where(:version => version.to_s).delete_all
<add> migrated.delete(target.version)
<add> ActiveRecord::SchemaMigration.where(:version => target.version.to_s).delete_all
<ide> else
<del> migrated << version
<del> ActiveRecord::SchemaMigration.create!(:version => version.to_s)
<add> migrated << target.version
<add> ActiveRecord::SchemaMigration.create!(
<add> :version => target.version.to_s,
<add> :migrated_at => Time.now,
<add> :fingerprint => target.fingerprint,
<add> :name => File.basename(target.filename,'.rb').gsub(/^\d+_/,'')
<add> )
<ide> end
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/schema_migration.rb
<ide> def self.index_name
<ide> end
<ide>
<ide> def self.create_table
<del> unless connection.table_exists?(table_name)
<add> if connection.table_exists?(table_name)
<add> cols = connection.columns(table_name).collect { |col| col.name }
<add> unless cols.include?("migrated_at")
<add> connection.add_column(table_name, "migrated_at", :datetime)
<add> q_table_name = connection.quote_table_name(table_name)
<add> q_timestamp = connection.quoted_date(Time.now)
<add> connection.update("UPDATE #{q_table_name} SET migrated_at = '#{q_timestamp}' WHERE migrated_at IS NULL")
<add> connection.change_column(table_name, "migrated_at", :datetime, :null => false)
<add> end
<add> unless cols.include?("fingerprint")
<add> connection.add_column(table_name, "fingerprint", :string, :limit => 32)
<add> end
<add> unless cols.include?("name")
<add> connection.add_column(table_name, "name", :string)
<add> end
<add> else
<ide> connection.create_table(table_name, :id => false) do |t|
<del> t.column :version, :string, :null => false
<add> t.column "version", :string, :null => false
<add> t.column "migrated_at", :datetime, :null => false
<add> t.column "fingerprint", :string, :limit => 32
<add> t.column "name", :string
<ide> end
<del> connection.add_index table_name, :version, :unique => true, :name => index_name
<add> connection.add_index(table_name, "version", :unique => true, :name => index_name)
<ide> end
<add> reset_column_information
<ide> end
<ide>
<ide> def self.drop_table
<add> if connection.index_exists?(table_name, "version", :unique => true, :name => index_name)
<add> connection.remove_index(table_name, :name => index_name)
<add> end
<ide> if connection.table_exists?(table_name)
<del> connection.remove_index table_name, :name => index_name
<ide> connection.drop_table(table_name)
<ide> end
<ide> end
<ide><path>activerecord/test/cases/migration/logger_test.rb
<ide> class LoggerTest < ActiveRecord::TestCase
<ide> # mysql can't roll back ddl changes
<ide> self.use_transactional_fixtures = false
<ide>
<del> Migration = Struct.new(:name, :version) do
<add> Migration = Struct.new(:name, :version, :filename, :fingerprint) do
<ide> def migrate direction
<ide> # do nothing
<ide> end
<add> def filename; "anon.rb"; end
<add> def fingerprint; "123456789012345678901234567890ab"; end
<ide> end
<ide>
<ide> def setup
<ide><path>activerecord/test/cases/migration/table_and_index_test.rb
<del>require "cases/helper"
<del>
<del>module ActiveRecord
<del> class Migration
<del> class TableAndIndexTest < ActiveRecord::TestCase
<del> def test_add_schema_info_respects_prefix_and_suffix
<del> conn = ActiveRecord::Base.connection
<del>
<del> conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
<del> # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters
<del> ActiveRecord::Base.table_name_prefix = 'p_'
<del> ActiveRecord::Base.table_name_suffix = '_s'
<del> conn.drop_table(ActiveRecord::Migrator.schema_migrations_table_name) if conn.table_exists?(ActiveRecord::Migrator.schema_migrations_table_name)
<del>
<del> conn.initialize_schema_migrations_table
<del>
<del> assert_equal "p_unique_schema_migrations_s", conn.indexes(ActiveRecord::Migrator.schema_migrations_table_name)[0][:name]
<del> ensure
<del> ActiveRecord::Base.table_name_prefix = ""
<del> ActiveRecord::Base.table_name_suffix = ""
<del> end
<del> end
<del> end
<del>end
<ide><path>activerecord/test/cases/migration_test.rb
<ide> def teardown
<ide> def test_migrator_versions
<ide> migrations_path = MIGRATIONS_ROOT + "/valid"
<ide> ActiveRecord::Migrator.migrations_paths = migrations_path
<add> m0_path = File.join(migrations_path, "1_valid_people_have_last_names.rb")
<add> m0_fingerprint = Digest::MD5.hexdigest(File.read(m0_path))
<ide>
<ide> ActiveRecord::Migrator.up(migrations_path)
<ide> assert_equal 3, ActiveRecord::Migrator.current_version
<ide> assert_equal 3, ActiveRecord::Migrator.last_version
<ide> assert_equal false, ActiveRecord::Migrator.needs_migration?
<ide>
<add> rows = connection.select_all("SELECT * FROM #{connection.quote_table_name(ActiveRecord::Migrator.schema_migrations_table_name)}")
<add> assert_equal m0_fingerprint, rows[0]["fingerprint"]
<add> assert_equal "valid_people_have_last_names", rows[0]["name"]
<add> rows.each do |row|
<add> assert_match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, row["migrated_at"], "missing migrated_at")
<add> end
<add>
<ide> ActiveRecord::Migrator.down(MIGRATIONS_ROOT + "/valid")
<ide> assert_equal 0, ActiveRecord::Migrator.current_version
<ide> assert_equal 3, ActiveRecord::Migrator.last_version
<ide><path>activerecord/test/cases/migrator_test.rb
<ide> def initialize name = self.class.name, version = nil
<ide>
<ide> def up; @went_up = true; end
<ide> def down; @went_down = true; end
<add> # also used in place of a MigrationProxy
<add> def filename; "anon.rb"; end
<add> def fingerprint; "123456789012345678901234567890ab"; end
<ide> end
<ide>
<ide> def setup
<ide> def test_relative_migrations
<ide> end
<ide>
<ide> def test_finds_pending_migrations
<del> ActiveRecord::SchemaMigration.create!(:version => '1')
<add> ActiveRecord::SchemaMigration.create!(:version => '1', :name => "anon", :migrated_at => Time.now)
<ide> migration_list = [ Migration.new('foo', 1), Migration.new('bar', 3) ]
<ide> migrations = ActiveRecord::Migrator.new(:up, migration_list).pending_migrations
<ide>
<ide> def test_down_calls_down
<ide> end
<ide>
<ide> def test_current_version
<del> ActiveRecord::SchemaMigration.create!(:version => '1000')
<add> ActiveRecord::SchemaMigration.create!(:version => '1000', :name => "anon", :migrated_at => Time.now)
<ide> assert_equal 1000, ActiveRecord::Migrator.current_version
<ide> end
<ide>
<ide> def test_migrator_forward
<ide>
<ide> def test_only_loads_pending_migrations
<ide> # migrate up to 1
<del> ActiveRecord::SchemaMigration.create!(:version => '1')
<add> ActiveRecord::SchemaMigration.create!(:version => '1', :name => "anon", :migrated_at => Time.now)
<ide>
<ide> calls, migrator = migrator_class(3)
<ide> migrator.migrate("valid", nil)
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> def standard_dump
<ide> def test_dump_schema_information_outputs_lexically_ordered_versions
<ide> versions = %w{ 20100101010101 20100201010101 20100301010101 }
<ide> versions.reverse.each do |v|
<del> ActiveRecord::SchemaMigration.create!(:version => v)
<add> ActiveRecord::SchemaMigration.create!(:version => v, :name => "anon", :migrated_at => Time.now)
<ide> end
<ide>
<ide> schema_info = ActiveRecord::Base.connection.dump_schema_information
<ide><path>activerecord/test/cases/schema_migration_test.rb
<add>require "cases/helper"
<add>
<add>class SchemaMigrationTest < ActiveRecord::TestCase
<add> def sm_table_name
<add> ActiveRecord::SchemaMigration.table_name
<add> end
<add>
<add> def connection
<add> ActiveRecord::Base.connection
<add> end
<add>
<add> def test_add_schema_info_respects_prefix_and_suffix
<add> connection.drop_table(sm_table_name) if connection.table_exists?(sm_table_name)
<add> # Use shorter prefix and suffix as in Oracle database identifier cannot be larger than 30 characters
<add> ActiveRecord::Base.table_name_prefix = 'p_'
<add> ActiveRecord::Base.table_name_suffix = '_s'
<add> connection.drop_table(sm_table_name) if connection.table_exists?(sm_table_name)
<add>
<add> ActiveRecord::SchemaMigration.create_table
<add>
<add> assert_equal "p_unique_schema_migrations_s", connection.indexes(sm_table_name)[0][:name]
<add> ensure
<add> ActiveRecord::Base.table_name_prefix = ""
<add> ActiveRecord::Base.table_name_suffix = ""
<add> end
<add>
<add> def test_add_metadata_columns_to_exisiting_schema_migrations
<add> # creates the old table schema from pre-Rails4.0, so we can test adding to it below
<add> if connection.table_exists?(sm_table_name)
<add> connection.drop_table(sm_table_name)
<add> end
<add> connection.create_table(sm_table_name, :id => false) do |schema_migrations_table|
<add> schema_migrations_table.column("version", :string, :null => false)
<add> end
<add>
<add> connection.insert "INSERT INTO #{connection.quote_table_name(sm_table_name)} (version) VALUES (100)"
<add> connection.insert "INSERT INTO #{connection.quote_table_name(sm_table_name)} (version) VALUES (200)"
<add>
<add> ActiveRecord::SchemaMigration.create_table
<add>
<add> rows = connection.select_all("SELECT * FROM #{connection.quote_table_name(sm_table_name)}")
<add> assert rows[0].has_key?("migrated_at"), "missing column `migrated_at`"
<add> assert_match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/, rows[0]["migrated_at"])
<add> assert rows[0].has_key?("fingerprint"), "missing column `fingerprint`"
<add> assert rows[0].has_key?("name"), "missing column `name`"
<add> end
<add>
<add> def test_schema_migrations_columns
<add> ActiveRecord::SchemaMigration.create_table
<add>
<add> columns = connection.columns(sm_table_name).collect(&:name)
<add> %w[version migrated_at fingerprint name].each { |col| assert columns.include?(col), "missing column `#{col}`" }
<add> end
<add>end
| 10
|
Javascript
|
Javascript
|
improve coverage of the buffer module
|
8699ecd3400259be3e2c1b373f5de34a7fb43128
|
<ide><path>test/parallel/test-buffer-alloc.js
<ide> assert.strictEqual(512, c.length);
<ide> const d = Buffer.from([]);
<ide> assert.strictEqual(0, d.length);
<ide>
<add>// Test offset properties
<add>{
<add> const b = Buffer.alloc(128);
<add> assert.strictEqual(128, b.length);
<add> assert.strictEqual(0, b.byteOffset);
<add> assert.strictEqual(0, b.offset);
<add>}
<add>
<ide> // Test creating a Buffer from a Uint32Array
<ide> {
<ide> const ui32 = new Uint32Array(4).fill(42);
<ide> assert.throws(() => b.toString('invalid'),
<ide> // invalid encoding for Buffer.write
<ide> assert.throws(() => b.write('test string', 0, 5, 'invalid'),
<ide> /Unknown encoding: invalid/);
<add>// unsupported arguments for Buffer.write
<add>assert.throws(() => b.write('test', 'utf8', 0),
<add> /is no longer supported/);
<ide>
<ide>
<ide> // try to create 0-length buffers
<ide> assert.strictEqual('<Buffer 81 a3 66 6f 6f a3 62 61 72>', x.inspect());
<ide> assert.strictEqual(buf[4], 0);
<ide> }
<ide>
<add>{
<add> // test alloc with fill option
<add> const buf = Buffer.alloc(5, '800A', 'hex');
<add> assert.strictEqual(buf[0], 128);
<add> assert.strictEqual(buf[1], 10);
<add> assert.strictEqual(buf[2], 128);
<add> assert.strictEqual(buf[3], 10);
<add> assert.strictEqual(buf[4], 128);
<add>}
<add>
<ide>
<ide> // Check for fractional length args, junk length args, etc.
<ide> // https://github.com/joyent/node/issues/1758
<ide><path>test/parallel/test-buffer-compare-offset.js
<ide> assert.strictEqual(-1, a.compare(b, '0'));
<ide> // Equivalent to a.compare(b).
<ide> assert.strictEqual(-1, a.compare(b, 0, undefined, 0));
<ide>
<del>// Zero-length targer, return 1
<add>// Zero-length target, return 1
<ide> assert.strictEqual(1, a.compare(b, 0, 0, 0));
<ide> assert.strictEqual(1, a.compare(b, '0', '0', '0'));
<ide>
<ide> assert.strictEqual(1, a.compare(b, 6, 10));
<ide> // Zero-length source, return -1
<ide> assert.strictEqual(-1, a.compare(b, 6, 10, 0, 0));
<ide>
<add>// Zero-length source and target, return 0
<add>assert.strictEqual(0, a.compare(b, 0, 0, 0, 0));
<add>assert.strictEqual(0, a.compare(b, 1, 1, 2, 2));
<add>
<ide> // Equivalent to Buffer.compare(a.slice(4), b.slice(0, 5))
<ide> assert.strictEqual(1, a.compare(b, 0, 5, 4));
<ide>
<ide><path>test/parallel/test-buffer-indexof.js
<ide> 'use strict';
<ide> require('../common');
<del>var assert = require('assert');
<add>const assert = require('assert');
<ide>
<del>var Buffer = require('buffer').Buffer;
<add>const Buffer = require('buffer').Buffer;
<ide>
<del>var b = Buffer.from('abcdef');
<del>var buf_a = Buffer.from('a');
<del>var buf_bc = Buffer.from('bc');
<del>var buf_f = Buffer.from('f');
<del>var buf_z = Buffer.from('z');
<del>var buf_empty = Buffer.from('');
<add>const b = Buffer.from('abcdef');
<add>const buf_a = Buffer.from('a');
<add>const buf_bc = Buffer.from('bc');
<add>const buf_f = Buffer.from('f');
<add>const buf_z = Buffer.from('z');
<add>const buf_empty = Buffer.from('');
<ide>
<ide> assert.equal(b.indexOf('a'), 0);
<ide> assert.equal(b.indexOf('a', 1), -1);
<ide> assert.equal(b.indexOf(Buffer.from('f'), 6), -1);
<ide>
<ide> assert.equal(Buffer.from('ff').indexOf(Buffer.from('f'), 1, 'ucs2'), -1);
<ide>
<add>// test invalid and uppercase encoding
<add>assert.strictEqual(b.indexOf('b', 'utf8'), 1);
<add>assert.strictEqual(b.indexOf('b', 'UTF8'), 1);
<add>assert.strictEqual(b.indexOf('62', 'HEX'), 1);
<add>assert.throws(() => b.indexOf('bad', 'enc'), /Unknown encoding: enc/);
<add>
<ide> // test hex encoding
<ide> assert.strictEqual(
<ide> Buffer.from(b.toString('hex'), 'hex')
<ide><path>test/parallel/test-buffer-new.js
<add>'use strict';
<add>
<add>require('../common');
<add>const assert = require('assert');
<add>const Buffer = require('buffer').Buffer;
<add>
<add>assert.throws(() => new Buffer(42, 'utf8'), /first argument must be a string/);
| 4
|
Text
|
Text
|
fix some recent nits in fs.md
|
039eb5624950ca5eba46fad8ab78924441d7acfc
|
<ide><path>doc/api/fs.md
<ide> added: v12.12.0
<ide>
<ide> A class representing a directory stream.
<ide>
<del>Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or [`fsPromises.opendir()`][].
<add>Created by [`fs.opendir()`][], [`fs.opendirSync()`][], or
<add>[`fsPromises.opendir()`][].
<ide>
<ide> ```js
<ide> const fs = require('fs');
<ide> async function print(path) {
<ide> print('./').catch(console.error);
<ide> ```
<ide>
<del>### dir.path
<del><!-- YAML
<del>added: v12.12.0
<del>-->
<del>
<del>* {string}
<del>
<del>The read-only path of this directory as was provided to [`fs.opendir()`][],
<del>[`fs.opendirSync()`][], or [`fsPromises.opendir()`][].
<del>
<ide> ### dir.close()
<ide> <!-- YAML
<ide> added: v12.12.0
<ide> added: v12.12.0
<ide> Synchronously close the directory's underlying resource handle.
<ide> Subsequent reads will result in errors.
<ide>
<add>### dir.path
<add><!-- YAML
<add>added: v12.12.0
<add>-->
<add>
<add>* {string}
<add>
<add>The read-only path of this directory as was provided to [`fs.opendir()`][],
<add>[`fs.opendirSync()`][], or [`fsPromises.opendir()`][].
<add>
<ide> ### dir.read()
<ide> <!-- YAML
<ide> added: v12.12.0
<ide> included in the iteration results.
<ide> added: v10.10.0
<ide> -->
<ide>
<del>A representation of a directory entry, as returned by reading from an [`fs.Dir`][].
<add>A representation of a directory entry, as returned by reading from an
<add>[`fs.Dir`][].
<ide>
<ide> Additionally, when [`fs.readdir()`][] or [`fs.readdirSync()`][] is called with
<ide> the `withFileTypes` option set to `true`, the resulting array is filled with
<ide> a colon, Node.js will open a file system stream, as described by
<ide> Functions based on `fs.open()` exhibit this behavior as well:
<ide> `fs.writeFile()`, `fs.readFile()`, etc.
<ide>
<del>## fs.openSync(path\[, flags, mode\])
<del><!-- YAML
<del>added: v0.1.21
<del>changes:
<del> - version: v11.1.0
<del> pr-url: https://github.com/nodejs/node/pull/23767
<del> description: The `flags` argument is now optional and defaults to `'r'`.
<del> - version: v9.9.0
<del> pr-url: https://github.com/nodejs/node/pull/18801
<del> description: The `as` and `as+` modes are supported now.
<del> - version: v7.6.0
<del> pr-url: https://github.com/nodejs/node/pull/10739
<del> description: The `path` parameter can be a WHATWG `URL` object using `file:`
<del> protocol. Support is currently still *experimental*.
<del>-->
<del>
<del>* `path` {string|Buffer|URL}
<del>* `flags` {string|number} **Default:** `'r'`.
<del> See [support of file system `flags`][].
<del>* `mode` {integer} **Default:** `0o666`
<del>* Returns: {number}
<del>
<del>Returns an integer representing the file descriptor.
<del>
<del>For detailed information, see the documentation of the asynchronous version of
<del>this API: [`fs.open()`][].
<del>
<ide> ## fs.opendir(path\[, options\], callback)
<ide> <!-- YAML
<ide> added: v12.12.0
<ide> and cleaning up the directory.
<ide> The `encoding` option sets the encoding for the `path` while opening the
<ide> directory and subsequent read operations.
<ide>
<add>## fs.openSync(path\[, flags, mode\])
<add><!-- YAML
<add>added: v0.1.21
<add>changes:
<add> - version: v11.1.0
<add> pr-url: https://github.com/nodejs/node/pull/23767
<add> description: The `flags` argument is now optional and defaults to `'r'`.
<add> - version: v9.9.0
<add> pr-url: https://github.com/nodejs/node/pull/18801
<add> description: The `as` and `as+` modes are supported now.
<add> - version: v7.6.0
<add> pr-url: https://github.com/nodejs/node/pull/10739
<add> description: The `path` parameter can be a WHATWG `URL` object using `file:`
<add> protocol. Support is currently still *experimental*.
<add>-->
<add>
<add>* `path` {string|Buffer|URL}
<add>* `flags` {string|number} **Default:** `'r'`.
<add> See [support of file system `flags`][].
<add>* `mode` {integer} **Default:** `0o666`
<add>* Returns: {number}
<add>
<add>Returns an integer representing the file descriptor.
<add>
<add>For detailed information, see the documentation of the asynchronous version of
<add>this API: [`fs.open()`][].
<add>
<ide> ## fs.read(fd, buffer, offset, length, position, callback)
<ide> <!-- YAML
<ide> added: v0.0.2
<ide> by [Naming Files, Paths, and Namespaces][]. Under NTFS, if the filename contains
<ide> a colon, Node.js will open a file system stream, as described by
<ide> [this MSDN page][MSDN-Using-Streams].
<ide>
<del>## fsPromises.opendir(path\[, options\])
<add>### fsPromises.opendir(path\[, options\])
<ide> <!-- YAML
<ide> added: v12.12.0
<ide> -->
<ide> the file contents.
<ide> [`Buffer.byteLength`]: buffer.html#buffer_class_method_buffer_bytelength_string_encoding
<ide> [`Buffer`]: buffer.html#buffer_buffer
<ide> [`FSEvents`]: https://developer.apple.com/documentation/coreservices/file_system_events
<add>[`Number.MAX_SAFE_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
<ide> [`ReadDirectoryChangesW`]: https://docs.microsoft.com/en-us/windows/desktop/api/winbase/nf-winbase-readdirectorychangesw
<ide> [`ReadStream`]: #fs_class_fs_readstream
<ide> [`URL`]: url.html#url_the_whatwg_url_api
<ide> the file contents.
<ide> [`net.Socket`]: net.html#net_class_net_socket
<ide> [`stat()`]: fs.html#fs_fs_stat_path_options_callback
<ide> [`util.promisify()`]: util.html#util_util_promisify_original
<del>[bigints]: https://tc39.github.io/proposal-bigint
<ide> [Caveats]: #fs_caveats
<ide> [Common System Errors]: errors.html#errors_common_system_errors
<ide> [FS Constants]: #fs_fs_constants_1
<ide> the file contents.
<ide> [MSDN-Rel-Path]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file#fully-qualified-vs-relative-paths
<ide> [MSDN-Using-Streams]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams
<ide> [Naming Files, Paths, and Namespaces]: https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file
<add>[bigints]: https://tc39.github.io/proposal-bigint
<ide> [chcp]: https://ss64.com/nt/chcp.html
<ide> [inode]: https://en.wikipedia.org/wiki/Inode
<ide> [support of file system `flags`]: #fs_file_system_flags
<del>[`Number.MAX_SAFE_INTEGER`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
| 1
|
PHP
|
PHP
|
add missing docblock for typehint
|
8a503c32999750e601d2d4e82a34bd4e8a290454
|
<ide><path>src/I18n/Number.php
<ide> public static function formatter(array $options = []): NumberFormatter
<ide> static::$_formatters[$locale][$type] = new NumberFormatter($locale, $type);
<ide> }
<ide>
<add> /** @var \NumberFormatter $formatter */
<ide> $formatter = static::$_formatters[$locale][$type];
<ide>
<ide> $options = array_intersect_key($options, [
| 1
|
Python
|
Python
|
fix typo in docstring for pipeline
|
3b583d02d6d63295e1756116cd611d651c7ffe96
|
<ide><path>src/transformers/pipelines/__init__.py
<ide> def pipeline(
<ide> - :obj:`"text2text-generation"`: will return a :class:`~transformers.Text2TextGenerationPipeline`.
<ide> - :obj:`"text-generation"`: will return a :class:`~transformers.TextGenerationPipeline`.
<ide> - :obj:`"zero-shot-classification:`: will return a :class:`~transformers.ZeroShotClassificationPipeline`.
<del> - :obj:`"conversation"`: will return a :class:`~transformers.ConversationalPipeline`.
<add> - :obj:`"conversational"`: will return a :class:`~transformers.ConversationalPipeline`.
<ide> model (:obj:`str` or :obj:`~transformers.PreTrainedModel` or :obj:`~transformers.TFPreTrainedModel`, `optional`):
<ide> The model that will be used by the pipeline to make predictions. This can be a model identifier or an
<ide> actual instance of a pretrained model inheriting from :class:`~transformers.PreTrainedModel` (for PyTorch)
| 1
|
Javascript
|
Javascript
|
create context for more stuff
|
f3213f2d00c0df8dfa137ac8150b819747a9e475
|
<ide><path>lib/ContextModule.js
<ide> ContextModule.prototype.source = function(dependencyTemplates, outputOptions, re
<ide> var str = [
<ide> "var map = ", JSON.stringify(map, null, "\t"), ";\n",
<ide> "function webpackContext(req) {\n",
<del> "\treturn require(map[req] || (function() { throw new Error(\"Cannot find module '\" + req + \"'.\") }()));\n",
<add> "\treturn require(webpackContextResolve(req));\n",
<add> "};\n",
<add> "function webpackContextResolve(req) {\n",
<add> "\treturn map[req] || (function() { throw new Error(\"Cannot find module '\" + req + \"'.\") }());\n",
<ide> "};\n",
<ide> "webpackContext.keys = function webpackContextKeys() {\n",
<ide> "\treturn Object.keys(map);\n",
<ide> "};\n",
<add> "webpackContext.resolve = webpackContextResolve;\n",
<ide> "module.exports = webpackContext;\n",
<ide> ];
<ide> return new RawSource(str.join(""));
<ide><path>lib/dependencies/AMDDefineDependencyParserPlugin.js
<ide> */
<ide> var AbstractPlugin = require("../AbstractPlugin");
<ide> var AMDRequireItemDependency = require("./AMDRequireItemDependency");
<add>var AMDRequireContextDependency = require("./AMDRequireContextDependency");
<ide> var ConstDependency = require("./ConstDependency");
<ide> var AMDDefineDependency = require("./AMDDefineDependency");
<add>var ContextDependencyHelpers = require("./ContextDependencyHelpers");
<ide>
<ide> module.exports = AbstractPlugin.create({
<ide> "call define": function(expr) {
<ide> module.exports = AbstractPlugin.create({
<ide> param.items.forEach(function(param) {
<ide> var result = this.applyPluginsBailResult("call define:amd:item", expr, param);
<ide> if(result === undefined) {
<del> // TODO: context
<add> this.applyPluginsBailResult("call define:amd:context", expr, param);
<ide> }
<ide> }, this);
<ide> }
<ide> module.exports = AbstractPlugin.create({
<ide> param.options.forEach(function(param) {
<ide> var result = this.applyPluginsBailResult("call define:amd:item", expr, param);
<ide> if(result === undefined) {
<del> // TODO: context
<add> this.applyPluginsBailResult("call define:amd:context", expr, param);
<ide> }
<ide> }, this);
<ide> return true;
<ide> module.exports = AbstractPlugin.create({
<ide> this.state.current.addDependency(dep);
<ide> return true;
<ide> }
<add> },
<add> "call define:amd:context": function(expr, param) {
<add> var dep = ContextDependencyHelpers.create(AMDRequireContextDependency, param.range, param, expr);
<add> if(!dep) return;
<add> dep.loc = expr.loc;
<add> dep.optional = !!this.scope.inTry;
<add> this.state.current.addDependency(dep);
<add> return true;
<ide> }
<ide> });
<ide>
<ide><path>lib/dependencies/AMDRequireDependenciesBlockParserPlugin.js
<ide> module.exports = AbstractPlugin.create({
<ide> param.options.forEach(function(param) {
<ide> var result = this.applyPluginsBailResult("call require:amd:item", expr, param);
<ide> if(result === undefined) {
<del> // TODO: context
<add> this.applyPluginsBailResult("call require:amd:context", expr, param);
<ide> }
<ide> }, this);
<ide> return true;
<ide><path>lib/dependencies/CommonJsPlugin.js
<ide> var CommonJsRequireDependency = require("./CommonJsRequireDependency");
<ide> var CommonJsRequireContextDependency = require("./CommonJsRequireContextDependency");
<ide> var RequireResolveDependency = require("./RequireResolveDependency");
<add>var RequireResolveContextDependency = require("./RequireResolveContextDependency");
<ide> var RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
<ide>
<ide> var NullFactory = require("../NullFactory");
<ide> CommonJsPlugin.prototype.apply = function(compiler) {
<ide> compilation.dependencyFactories.set(RequireResolveDependency, normalModuleFactory);
<ide> compilation.dependencyTemplates.set(RequireResolveDependency, new RequireResolveDependency.Template());
<ide>
<add> compilation.dependencyFactories.set(RequireResolveContextDependency, contextModuleFactory);
<add> compilation.dependencyTemplates.set(RequireResolveContextDependency, new RequireResolveContextDependency.Template());
<add>
<ide> compilation.dependencyFactories.set(RequireResolveHeaderDependency, new NullFactory());
<ide> compilation.dependencyTemplates.set(RequireResolveHeaderDependency, new RequireResolveHeaderDependency.Template());
<ide> });
<ide><path>lib/dependencies/ContextDependencyTemplateAsId.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>function ContextDependencyTemplateAsId() {}
<add>module.exports = ContextDependencyTemplateAsId;
<add>
<add>ContextDependencyTemplateAsId.prototype.apply = function(dep, source, outputOptions, requestShortener) {
<add> var comment = "";
<add> if(outputOptions.pathinfo) comment = "/*! " + requestShortener.shorten(dep.request) + " */ ";
<add> if(dep.module) {
<add> if(dep.valueRange) {
<add> source.replace(dep.valueRange[1], dep.range[1]-1, ")");
<add> source.replace(dep.range[0], dep.valueRange[0]-1, "require(" + comment + dep.module.id + ").resolve(" + (typeof dep.prepend == "string" ? JSON.stringify(dep.prepend) : "") + "");
<add> } else {
<add> source.replace(dep.range[0], dep.range[1]-1, "require(" + comment + dep.module.id + ").resolve");
<add> }
<add> } else {
<add> var content = "(function webpackMissingModule() { throw new Error(" + JSON.stringify("Cannot find module \"" + dep.request + "\"") + "); }())";
<add> source.replace(dep.range[0], dep.range[1]-1, content);
<add> }
<add>};
<ide><path>lib/dependencies/RequireResolveContextDependency.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add> Author Tobias Koppers @sokra
<add>*/
<add>var ContextDependency = require("./ContextDependency");
<add>
<add>function RequireResolveContextDependency(request, recursive, regExp, range, valueRange) {
<add> ContextDependency.call(this, request, recursive, regExp);
<add> this.range = range;
<add> this.valueRange = valueRange;
<add> this.Class = RequireResolveContextDependency;
<add>}
<add>module.exports = RequireResolveContextDependency;
<add>
<add>RequireResolveContextDependency.prototype = Object.create(ContextDependency.prototype);
<add>RequireResolveContextDependency.prototype.type = "amd require context";
<add>
<add>RequireResolveContextDependency.Template = require("./ContextDependencyTemplateAsId");
<ide><path>lib/dependencies/RequireResolveDependencyParserPlugin.js
<ide> */
<ide> var AbstractPlugin = require("../AbstractPlugin");
<ide> var RequireResolveDependency = require("./RequireResolveDependency");
<add>var RequireResolveContextDependency = require("./RequireResolveContextDependency");
<ide> var RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
<add>var ContextDependencyHelpers = require("./ContextDependencyHelpers");
<ide>
<ide> module.exports = AbstractPlugin.create({
<ide> "call require.resolve": function(expr) {
<ide> module.exports = AbstractPlugin.create({
<ide> param.options.forEach(function(option) {
<ide> var result = this.applyPluginsBailResult("call require.resolve:item", expr, option);
<ide> if(result === undefined) {
<del> // TODO: context
<add> this.applyPluginsBailResult("call require.resolve:context", expr, option);
<ide> }
<ide> }, this);
<ide> this.state.current.addDependency(new RequireResolveHeaderDependency(expr.callee.range));
<ide> return true;
<ide> } else {
<ide> var result = this.applyPluginsBailResult("call require.resolve:item", expr, param);
<ide> if(result === undefined) {
<del> // TODO: context
<add> this.applyPluginsBailResult("call require.resolve:context", expr, param);
<ide> }
<ide> this.state.current.addDependency(new RequireResolveHeaderDependency(expr.callee.range));
<ide> return true;
<ide> module.exports = AbstractPlugin.create({
<ide> this.state.current.addDependency(dep);
<ide> return true;
<ide> }
<add> },
<add> "call require.resolve:context": function(expr, param) {
<add> var dep = ContextDependencyHelpers.create(RequireResolveContextDependency, param.range, param, expr);
<add> if(!dep) return;
<add> dep.loc = expr.loc;
<add> dep.optional = !!this.scope.inTry;
<add> this.state.current.addDependency(dep);
<add> return true;
<ide> }
<ide> });
<ide>
<ide><path>test/browsertest/lib/index.web.js
<ide> describe("main", function() {
<ide> require("raw!../resources/" + abc + ".txt").should.be.eql("abc");
<ide> });
<ide>
<add> it("should be able to require.resolve with automatical context", function() {
<add> var template = "tmpl";
<add> require.resolve("../templates/" + template).should.be.eql(require.resolve("../templates/tmpl"));
<add> });
<add>
<ide> it("should resolve loaders relative to require", function() {
<ide> var index = "index", test = "test";
<ide> require("../loaders/queryloader?query!!!!../node_modules/subcontent/" + index + ".js").should.be.eql({
| 8
|
Javascript
|
Javascript
|
remove support for `process.platform`
|
46d98e1d688890b18445b9fe7e9d208f4ea6c758
|
<ide><path>Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js
<ide> function setUpProcess() {
<ide> if (!global.process.env.NODE_ENV) {
<ide> global.process.env.NODE_ENV = __DEV__ ? 'development' : 'production';
<ide> }
<del>
<del> polyfillLazyGlobal('platform', () => require('Platform').OS, global.process);
<ide> }
<ide>
<ide> function setUpDevTools() {
<ide><path>packager/react-packager/src/JSTransformer/worker/__tests__/inline-test.js
<ide> describe('inline constants', () => {
<ide> normalize(code.replace(/process\.env\.NODE_ENV/, '"development"')));
<ide> });
<ide>
<del> it('replaces process.platform in the code', () => {
<del> const code = `function a() {
<del> if (process.platform === 'android') {
<del> return require('./android');
<del> }
<del> return require('./ios');
<del> }`;
<del> const {ast} = inline('arbitrary.js', {code}, {platform: 'ios'});
<del> expect(toString(ast)).toEqual(
<del> normalize(code.replace(/process\.platform\b/, '"ios"')));
<del> });
<del>
<ide> it('accepts an AST as input', function() {
<ide> const code = 'function ifDev(a,b){return __DEV__?a:b;}';
<ide> const {ast} = inline('arbitrary.hs', {ast: toAst(code)}, {dev: false});
<ide><path>packager/react-packager/src/JSTransformer/worker/inline.js
<ide> const requirePattern = {name: 'require'};
<ide> const env = {name: 'env'};
<ide> const nodeEnv = {name: 'NODE_ENV'};
<ide> const processId = {name: 'process'};
<del>const platformId = {name: 'platform'};
<ide>
<ide> const dev = {name: '__DEV__'};
<ide>
<ide> const isProcessEnvNodeEnv = (node, scope) =>
<ide> t.isIdentifier(node.object.object, processId) &&
<ide> isGlobal(scope.getBinding(processId.name));
<ide>
<del>const isProcessPlatform = (node, scope) =>
<del> t.isIdentifier(node.property, platformId) &&
<del> t.isIdentifier(node.object, processId) &&
<del> isGlobal(scope.getBinding(processId.name));
<del>
<ide> const isDev = (node, parent, scope) =>
<ide> t.isIdentifier(node, dev) &&
<ide> isGlobal(scope.getBinding(dev.name)) &&
<ide> const inlinePlugin = {
<ide> } else if (isProcessEnvNodeEnv(node, scope)) {
<ide> path.replaceWith(
<ide> t.stringLiteral(state.opts.dev ? 'development' : 'production'));
<del> } else if (isProcessPlatform(node, scope)) {
<del> path.replaceWith(
<del> t.stringLiteral(state.opts.platform));
<ide> }
<ide> },
<ide> },
| 3
|
Ruby
|
Ruby
|
allow regex without capture groups
|
0deceac28cf190900ca861f7da27f05cf82f8b61
|
<ide><path>Library/Homebrew/livecheck/strategy/page_match.rb
<ide> def self.page_matches(url, regex, &block)
<ide> end
<ide> end
<ide>
<del> page.scan(regex).map(&:first).uniq
<add> page.scan(regex).map do |match|
<add> case match
<add> when String
<add> match
<add> else
<add> match.first
<add> end
<add> end.uniq
<ide> end
<ide>
<ide> # Checks the content at the URL for new versions, using the provided
| 1
|
Text
|
Text
|
clarify case for already placed valid number
|
728f44ab38a42df1cb763f828957ea3f2a4e131d
|
<ide><path>curriculum/challenges/english/06-quality-assurance/quality-assurance-projects/sudoku-solver.md
<ide> async (getUserInput) => {
<ide> };
<ide> ```
<ide>
<add>If `value` submitted to `/api/check` is already placed in `puzzle` on that `coordinate`, the returned value will be an object containing a `valid` property with `true` if `value` is not conflicting.
<add>
<add>```js
<add>async (getUserInput) => {
<add> const input =
<add> '..9..5.1.85.4....2432......1...69.83.9.....6.62.71...9......1945....4.37.4.3..6..';
<add> const coordinate = 'C3';
<add> const value = '2';
<add> const data = await fetch(getUserInput('url') + '/api/check', {
<add> method: 'POST',
<add> headers: { 'Content-Type': 'application/json' },
<add> body: JSON.stringify({ puzzle: input, coordinate, value })
<add> });
<add> const parsed = await data.json();
<add> assert.property(parsed, 'valid');
<add> assert.isTrue(parsed.valid);
<add>};
<add>```
<add>
<ide> If the puzzle submitted to `/api/check` contains values which are not numbers or periods, the returned value will be `{ error: 'Invalid characters in puzzle' }`
<ide>
<ide> ```js
| 1
|
Javascript
|
Javascript
|
fix jshint issue
|
8f6f8820686cc57ab0ee3139c4d7d7c2c13b7014
|
<ide><path>src/elements/element.point.js
<ide> module.exports = function(Chart) {
<ide> Chart.elements.Point = Chart.Element.extend({
<ide> inRange: function(mouseX, mouseY) {
<ide> var vm = this._view;
<del> return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false
<add> return vm ? ((Math.pow(mouseX - vm.x, 2) + Math.pow(mouseY - vm.y, 2)) < Math.pow(vm.hitRadius + vm.radius, 2)) : false;
<ide> },
<ide> inLabelRange: function(mouseX) {
<ide> var vm = this._view;
| 1
|
Java
|
Java
|
avoid creation of unnecessary environment objects
|
91f05c8b9d4e108e744484d808564a95b618e731
|
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotatedBeanDefinitionReader.java
<ide> public class AnnotatedBeanDefinitionReader {
<ide>
<ide> private final BeanDefinitionRegistry registry;
<ide>
<del> private Environment environment = new StandardEnvironment();
<add> private Environment environment;
<ide>
<ide> private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();
<ide>
<ide> private ScopeMetadataResolver scopeMetadataResolver = new AnnotationScopeMetadataResolver();
<ide>
<ide> /**
<del> * Create a new {@code AnnotatedBeanDefinitionReader} for the given bean factory.
<add> * Create a new {@code AnnotatedBeanDefinitionReader} for the given registry.
<add> * If the registry is {@link EnvironmentCapable}, e.g. is an {@code ApplicationContext},
<add> * the {@link Environment} will be inherited, otherwise a new
<add> * {@link StandardEnvironment} will be created and used.
<ide> * @param registry the {@code BeanFactory} to load bean definitions into,
<ide> * in the form of a {@code BeanDefinitionRegistry}
<add> * @see #AnnotatedBeanDefinitionReader(BeanDefinitionRegistry, Environment)
<add> * @see #setEnvironment(Environment)
<ide> */
<ide> public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
<add> this(registry, getOrCreateEnvironment(registry));
<add> }
<add>
<add> /**
<add> * Create a new {@code AnnotatedBeanDefinitionReader} for the given registry and using
<add> * the given {@link Environment}.
<add> * @param registry the {@code BeanFactory} to load bean definitions into,
<add> * in the form of a {@code BeanDefinitionRegistry}
<add> * @param environment the {@code Environment} to use when evaluating bean definition
<add> * profiles.
<add> * @since 3.1
<add> */
<add> public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
<ide> Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
<del> this.registry = registry;
<add> Assert.notNull(environment, "Environment must not be null");
<ide>
<del> // Inherit Environment if possible
<del> if (this.registry instanceof EnvironmentCapable) {
<del> this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
<del> }
<add> this.registry = registry;
<add> this.environment = environment;
<ide>
<ide> AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
<ide> }
<ide> public void registerBean(Class<?> annotatedClass, String name, Class<? extends A
<ide> definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
<ide> BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
<ide> }
<add>
<add>
<add> /**
<add> * Get the Environment from the given registry if possible, otherwise return a new
<add> * StandardEnvironment.
<add> */
<add> private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
<add> Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
<add> if (registry instanceof EnvironmentCapable) {
<add> return ((EnvironmentCapable) registry).getEnvironment();
<add> }
<add> return new StandardEnvironment();
<add> }
<add>
<ide> }
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/AnnotationConfigApplicationContext.java
<ide> */
<ide> public class AnnotationConfigApplicationContext extends GenericApplicationContext {
<ide>
<del> private final AnnotatedBeanDefinitionReader reader = new AnnotatedBeanDefinitionReader(this);
<add> private final AnnotatedBeanDefinitionReader reader;
<ide>
<del> private final ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this);
<add> private final ClassPathBeanDefinitionScanner scanner;
<ide>
<ide>
<ide> /**
<ide> * Create a new AnnotationConfigApplicationContext that needs to be populated
<ide> * through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
<ide> */
<ide> public AnnotationConfigApplicationContext() {
<del> this.delegateEnvironment(super.getEnvironment());
<add> this.reader = new AnnotatedBeanDefinitionReader(this);
<add> this.scanner = new ClassPathBeanDefinitionScanner(this);
<ide> }
<ide>
<ide> /**
<ide> public AnnotationConfigApplicationContext(String... basePackages) {
<ide> @Override
<ide> public void setEnvironment(ConfigurableEnvironment environment) {
<ide> super.setEnvironment(environment);
<del> delegateEnvironment(environment);
<del> }
<del>
<del> private void delegateEnvironment(ConfigurableEnvironment environment) {
<ide> this.reader.setEnvironment(environment);
<ide> this.scanner.setEnvironment(environment);
<ide> }
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java
<ide> import org.springframework.beans.factory.support.BeanDefinitionReaderUtils;
<ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry;
<ide> import org.springframework.beans.factory.support.BeanNameGenerator;
<add>import org.springframework.core.env.Environment;
<ide> import org.springframework.core.env.EnvironmentCapable;
<add>import org.springframework.core.env.StandardEnvironment;
<ide> import org.springframework.core.io.ResourceLoader;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.util.PatternMatchUtils;
<ide>
<ide> /**
<ide> * A bean definition scanner that detects bean candidates on the classpath,
<del> * registering corresponding bean definitions with a given registry (BeanFactory
<del> * or ApplicationContext).
<add> * registering corresponding bean definitions with a given registry ({@code BeanFactory}
<add> * or {@code ApplicationContext}).
<ide> *
<ide> * <p>Candidate classes are detected through configurable type filters. The
<ide> * default filters include classes that are annotated with Spring's
<ide> public class ClassPathBeanDefinitionScanner extends ClassPathScanningCandidateCo
<ide>
<ide>
<ide> /**
<del> * Create a new ClassPathBeanDefinitionScanner for the given bean factory.
<del> * @param registry the BeanFactory to load bean definitions into,
<del> * in the form of a BeanDefinitionRegistry
<add> * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.
<add> * @param registry the {@code BeanFactory} to load bean definitions into, in the form
<add> * of a {@code BeanDefinitionRegistry}
<ide> */
<ide> public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
<ide> this(registry, true);
<ide> }
<ide>
<ide> /**
<del> * Create a new ClassPathBeanDefinitionScanner for the given bean factory.
<del> * <p>If the passed-in bean factory does not only implement the BeanDefinitionRegistry
<del> * interface but also the ResourceLoader interface, it will be used as default
<del> * ResourceLoader as well. This will usually be the case for
<del> * {@link org.springframework.context.ApplicationContext} implementations.
<del> * <p>If given a plain BeanDefinitionRegistry, the default ResourceLoader will be a
<del> * {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
<add> * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory.
<add> * <p>If the passed-in bean factory does not only implement the
<add> * {@code BeanDefinitionRegistry} interface but also the {@code ResourceLoader}
<add> * interface, it will be used as default {@code ResourceLoader} as well. This will
<add> * usually be the case for {@link org.springframework.context.ApplicationContext}
<add> * implementations.
<add> * <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}
<add> * will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
<ide> * <p>If the the passed-in bean factory also implements {@link EnvironmentCapable} its
<ide> * environment will be used by this reader. Otherwise, the reader will initialize and
<ide> * use a {@link org.springframework.core.env.StandardEnvironment}. All
<del> * ApplicationContext implementations are EnvironmentCapable, while normal BeanFactory
<del> * implementations are not.
<del> * @param registry the BeanFactory to load bean definitions into,
<del> * in the form of a BeanDefinitionRegistry
<add> * {@code ApplicationContext} implementations are {@code EnvironmentCapable}, while
<add> * normal {@code BeanFactory} implementations are not.
<add> * @param registry the {@code BeanFactory} to load bean definitions into, in the form
<add> * of a {@code BeanDefinitionRegistry}
<ide> * @param useDefaultFilters whether to include the default filters for the
<ide> * {@link org.springframework.stereotype.Component @Component},
<ide> * {@link org.springframework.stereotype.Repository @Repository},
<ide> public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry) {
<ide> * @see #setEnvironment
<ide> */
<ide> public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
<del> super(useDefaultFilters);
<add> this(registry, useDefaultFilters, getOrCreateEnvironment(registry));
<add> }
<add>
<add> /**
<add> * Create a new {@code ClassPathBeanDefinitionScanner} for the given bean factory and
<add> * using the given {@link Environment} when evaluating bean definition profile metadata.
<add> * <p>If the passed-in bean factory does not only implement the {@code
<add> * BeanDefinitionRegistry} interface but also the {@link ResourceLoader} interface, it
<add> * will be used as default {@code ResourceLoader} as well. This will usually be the
<add> * case for {@link org.springframework.context.ApplicationContext} implementations.
<add> * <p>If given a plain {@code BeanDefinitionRegistry}, the default {@code ResourceLoader}
<add> * will be a {@link org.springframework.core.io.support.PathMatchingResourcePatternResolver}.
<add> * @param registry the {@code BeanFactory} to load bean definitions into, in the form
<add> * of a {@code BeanDefinitionRegistry}
<add> * @param useDefaultFilters whether to include the default filters for the
<add> * @param environment the Spring {@link Environment} to use when evaluating bean
<add> * definition profile metadata.
<add> * {@link org.springframework.stereotype.Component @Component},
<add> * {@link org.springframework.stereotype.Repository @Repository},
<add> * {@link org.springframework.stereotype.Service @Service}, and
<add> * {@link org.springframework.stereotype.Controller @Controller} stereotype
<add> * annotations.
<add> * @since 3.1
<add> * @see #setResourceLoader
<add> */
<add> public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment) {
<add> super(useDefaultFilters, environment);
<ide>
<ide> Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
<ide> this.registry = registry;
<ide> public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean u
<ide> if (this.registry instanceof ResourceLoader) {
<ide> setResourceLoader((ResourceLoader) this.registry);
<ide> }
<del>
<del> // Inherit Environment if possible
<del> if (this.registry instanceof EnvironmentCapable) {
<del> setEnvironment(((EnvironmentCapable) this.registry).getEnvironment());
<del> }
<ide> }
<ide>
<ide>
<ide> protected boolean isCompatible(BeanDefinition newDefinition, BeanDefinition exis
<ide> newDefinition.equals(existingDefinition)); // scanned equivalent class twice
<ide> }
<ide>
<add>
<add> /**
<add> * Get the Environment from the given registry if possible, otherwise return a new
<add> * StandardEnvironment.
<add> */
<add> private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {
<add> Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
<add> if (registry instanceof EnvironmentCapable) {
<add> return ((EnvironmentCapable) registry).getEnvironment();
<add> }
<add> return new StandardEnvironment();
<add> }
<add>
<ide> }
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ClassPathScanningCandidateComponentProvider.java
<ide> public class ClassPathScanningCandidateComponentProvider implements EnvironmentC
<ide>
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<del> private Environment environment = new StandardEnvironment();
<add> private Environment environment;
<ide>
<ide> private ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
<ide>
<ide> public class ClassPathScanningCandidateComponentProvider implements EnvironmentC
<ide> * @see #registerDefaultFilters()
<ide> */
<ide> public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters) {
<add> this(useDefaultFilters, new StandardEnvironment());
<add> }
<add>
<add> public ClassPathScanningCandidateComponentProvider(boolean useDefaultFilters, Environment environment) {
<ide> if (useDefaultFilters) {
<ide> registerDefaultFilters();
<ide> }
<add> this.environment = environment;
<ide> }
<ide>
<ide>
| 4
|
Text
|
Text
|
fix changelog.md formatting
|
e5f9ef62f6d94c908b9a0cde6e4dff2e5088964e
|
<ide><path>CHANGELOG.md
<ide> release.
<ide> </td>
<ide> <td valign="top">
<ide> <b><a href="doc/changelogs/CHANGELOG_V14.md#14.17.2">14.17.2</a></b><br/>
<del><a href="doc/changelogs/CHANGELOG_V14.md#14.17.1">14.17.1</a></b>
<add><a href="doc/changelogs/CHANGELOG_V14.md#14.17.1">14.17.1</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V14.md#14.17.0">14.17.0</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V14.md#14.16.1">14.16.1</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V14.md#14.16.0">14.16.0</a><br/>
<ide> release.
<ide> </td>
<ide> <td valign="top">
<ide> <b><a href="doc/changelogs/CHANGELOG_V12.md#12.22.2">12.22.2</a></b><br/>
<del><a href="doc/changelogs/CHANGELOG_V12.md#12.22.1">12.22.1</a></b>
<add><a href="doc/changelogs/CHANGELOG_V12.md#12.22.1">12.22.1</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V12.md#12.22.0">12.22.0</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V12.md#12.21.0">12.21.0</a><br/>
<ide> <a href="doc/changelogs/CHANGELOG_V12.md#12.20.2">12.20.2</a><br/>
| 1
|
Text
|
Text
|
add example to concisely return object
|
2e92a63a690fc35f82ad14cea9daae428a55cf90
|
<ide><path>guide/english/javascript/arrow-functions/index.md
<ide> const multiply = (x, y) => x * y;
<ide> // if you only have one argument/parameter
<ide> const multiplyBy2 = x => x * 2;
<ide>
<add>// if you need to concisely return an object, you can wrap the {} inside the () to avoid syntax conflicts
<add>const getSumProductObject = (x, y) => ({sum : x + y, product: x * y});
<add>
<ide> // combined with the ternary operator, but note it's not a looker!
<ide> const addOrMultiply = (x, y, mathOperator) => mathOperator.toLowerCase() === 'add' ? x + y : x * y;
<ide> ```
| 1
|
Ruby
|
Ruby
|
fix incorrect usage of 'or'
|
bb2e67f37e608f1987348c06c6c1435ea6850568
|
<ide><path>Library/Homebrew/cmd/doctor.rb
<ide> def check_xcode_select_path
<ide> # with the advent of CLT-only support, we don't need xcode-select
<ide> return if MacOS.clt_installed?
<ide> unless File.file? "#{MacOS.xcode_folder}/usr/bin/xcodebuild" and not MacOS.xctools_fucked?
<del> path = MacOS.app_with_bundle_id(MacOS::XCODE_4_BUNDLE_ID) or MacOS.app_with_bundle_id(MacOS::XCODE_3_BUNDLE_ID)
<add> path = MacOS.app_with_bundle_id(MacOS::XCODE_4_BUNDLE_ID) || MacOS.app_with_bundle_id(MacOS::XCODE_3_BUNDLE_ID)
<ide> path = '/Developer' if path.nil? or not path.directory?
<ide> <<-EOS.undent
<ide> Your Xcode is configured with an invalid path.
| 1
|
Python
|
Python
|
use bundle entry-points (and rearrange setup.py)
|
a8d02a2f4d528d1ac47fec67b33b4a838c1618f9
|
<ide><path>celery/contrib/bundles.py
<add>import os
<add>import sys
<add>
<add>from celery import VERSION
<add>from bundle import Bundle
<add>from bundle.extensions import Dist
<add>
<add>
<add>defaults = {"author": "Celery Project",
<add> "author_email": "bundles@celeryproject.org",
<add> "url": "http://celeryproject.org",
<add> "license": "BSD"}
<add>celery = Dist("celery", VERSION, **defaults)
<add>django_celery = Dist("django-celery", VERSION, **defaults)
<add>flask_celery = Dist("Flask-Celery", VERSION, **defaults)
<add>
<add>bundles = [
<add> celery.Bundle("celery-with-redis",
<add> "Bundle installing the dependencies for Celery and Redis",
<add> requires=["redis>=2.4.4"]),
<add> celery.Bundle("celery-with-mongodb",
<add> "Bundle installing the dependencies for Celery and MongoDB",
<add> requires=["pymongo"]),
<add> django_celery.Bundle("django-celery-with-redis",
<add> "Bundle that installs the dependencies for Django-Celery and Redis",
<add> requires=["redis>=2.4.4"]),
<add> django_celery.Bundle("django-celery-with-mongodb",
<add> "Bundle that installs the dependencies for Django-Celery and MongoDB",
<add> requires=["redis>=2.4.4"]),
<add> celery.Bundle("bundle-celery",
<add> "Bundle that installs Celery related modules",
<add> requires=[django_celery, flask_celery,
<add> "django", "setproctitle", "celerymon",
<add> "cyme", "kombu-sqlalchemy", "django-kombu"]),
<add>]
<ide><path>setup.py
<ide> import codecs
<ide> import platform
<ide>
<del>extra = {}
<del>tests_require = ["nose", "nose-cover3", "sqlalchemy", "mock"]
<del>is_py3k = sys.version_info >= (3, 0)
<del>if is_py3k:
<del> extra.update(use_2to3=True)
<del>elif sys.version_info < (2, 7):
<del> tests_require.append("unittest2")
<del>elif sys.version_info <= (2, 5):
<del> tests_require.append("simplejson")
<del>
<ide> if sys.version_info < (2, 5):
<ide> raise Exception("Celery requires Python 2.5 or higher.")
<ide>
<ide> from setuptools import setup, find_packages # noqa
<ide> from setuptools.command.test import test # noqa
<ide>
<add>NAME = "celery"
<add>entrypoints = {}
<add>extra = {}
<add>
<add># -*- Classifiers -*-
<add>
<add>classes = """
<add> Development Status :: 5 - Production/Stable
<add> License :: OSI Approved :: BSD License
<add> Topic :: System :: Distributed Computing
<add> Topic :: Software Development :: Object Brokering
<add> Intended Audience :: Developers
<add> Intended Audience :: Information Technology
<add> Intended Audience :: Science/Research
<add> Intended Audience :: Financial and Insurance Industry
<add> Intended Audience :: Healthcare Industry
<add> Environment :: No Input/Output (Daemon)
<add> Environment :: Console
<add> Programming Language :: Python
<add> Programming Language :: Python :: 2
<add> Programming Language :: Python :: 2.5
<add> Programming Language :: Python :: 2.6
<add> Programming Language :: Python :: 2.7
<add> Programming Language :: Python :: 3
<add> Programming Language :: Python :: 3.2
<add> Programming Language :: Python :: Implementation :: CPython
<add> Programming Language :: Python :: Implementation :: PyPy
<add> Programming Language :: Python :: Implementation :: Jython
<add> Operating System :: OS Independent
<add> Operating System :: POSIX
<add> Operating System :: Microsoft :: Windows
<add> Operating System :: MacOS :: MacOS X
<add>"""
<add>classifiers = [s.strip() for s in classes.split('\n') if s]
<add>
<add># -*- Python 3 -*-
<add>is_py3k = sys.version_info >= (3, 0)
<add>if is_py3k:
<add> extra.update(use_2to3=True)
<add>
<add># -*- Distribution Meta -*-
<add>
<ide> os.environ["CELERY_NO_EVAL"] = "yes"
<ide> import celery as distmeta
<ide> os.environ.pop("CELERY_NO_EVAL", None)
<ide> sys.modules.pop("celery", None)
<ide>
<add># -*- Custom Commands -*-
<ide>
<ide> class quicktest(test):
<ide> extra_env = dict(SKIP_RLIMITS=1, QUICKTEST=1)
<ide> def run(self, *args, **kwargs):
<ide> os.environ[env_name] = str(env_value)
<ide> test.run(self, *args, **kwargs)
<ide>
<add># -*- Installation Dependencies -*-
<add>
<ide> install_requires = []
<ide> try:
<ide> import importlib # noqa
<ide> def run(self, *args, **kwargs):
<ide> install_requires.append("threadpool")
<ide> install_requires.append("simplejson")
<ide>
<add># -*- Tests Requires -*-
<add>
<add>tests_require = ["nose", "nose-cover3", "sqlalchemy", "mock"]
<add>if sys.version_info < (2, 7):
<add> tests_require.append("unittest2")
<add>elif sys.version_info <= (2, 5):
<add> tests_require.append("simplejson")
<add>
<add># -*- Long Description -*-
<add>
<ide> if os.path.exists("README.rst"):
<ide> long_description = codecs.open("README.rst", "r", "utf-8").read()
<ide> else:
<ide> long_description = "See http://pypi.python.org/pypi/celery"
<ide>
<add># -*- Entry Points -*- #
<ide>
<del>console_scripts = [
<add>console_scripts = entrypoints["console_scripts"] = [
<ide> 'celerybeat = celery.bin.celerybeat:main',
<ide> 'camqadm = celery.bin.camqadm:main',
<ide> 'celeryev = celery.bin.celeryev:main',
<ide> def run(self, *args, **kwargs):
<ide> else:
<ide> console_scripts.append('celeryd = celery.bin.celeryd:main')
<ide>
<add># bundles: Only relevant for Celery developers.
<add>entrypoints["bundle.bundles"] = ["celery = celery.contrib.bundles:bundles"]
<add>
<add># -*- %%% -*-
<ide>
<ide> setup(
<ide> name="celery",
<ide> def run(self, *args, **kwargs):
<ide> zip_safe=False,
<ide> install_requires=install_requires,
<ide> tests_require=tests_require,
<del> cmdclass={"test": test,
<del> "quicktest": quicktest},
<ide> test_suite="nose.collector",
<del> classifiers=[
<del> "Development Status :: 5 - Production/Stable",
<del> "License :: OSI Approved :: BSD License",
<del> "Topic :: System :: Distributed Computing",
<del> "Topic :: Software Development :: Object Brokering",
<del> "Intended Audience :: Developers",
<del> "Intended Audience :: Information Technology",
<del> "Intended Audience :: Science/Research",
<del> "Intended Audience :: Financial and Insurance Industry",
<del> "Intended Audience :: Healthcare Industry",
<del> "Environment :: No Input/Output (Daemon)",
<del> "Environment :: Console",
<del> "Programming Language :: Python",
<del> "Programming Language :: Python :: 2",
<del> "Programming Language :: Python :: 2.5",
<del> "Programming Language :: Python :: 2.6",
<del> "Programming Language :: Python :: 2.7",
<del> "Programming Language :: Python :: 3",
<del> "Programming Language :: Python :: 3.2",
<del> "Programming Language :: Python :: Implementation :: CPython",
<del> "Programming Language :: Python :: Implementation :: PyPy",
<del> "Programming Language :: Python :: Implementation :: Jython",
<del> "Operating System :: OS Independent",
<del> "Operating System :: POSIX",
<del> "Operating System :: Microsoft :: Windows",
<del> "Operating System :: MacOS :: MacOS X",
<del> ],
<del> entry_points={
<del> 'console_scripts': console_scripts,
<del> },
<add> cmdclass={"quicktest": quicktest},
<add> classifiers=classifiers,
<add> entry_points=entrypoints,
<ide> long_description=long_description,
<ide> **extra)
| 2
|
PHP
|
PHP
|
return instance from foundation helpers
|
33f4a611095812ebb8a8a2fda2870caf22789e9b
|
<ide><path>src/Illuminate/Foundation/helpers.php
<ide> function bcrypt($value, $options = array())
<ide> * @param mixed $default
<ide> * @return mixed
<ide> */
<del> function config($key, $default = null)
<add> function config($key = null, $default = null)
<ide> {
<add> if (is_null($key)) return app('config');
<add>
<ide> if (is_array($key))
<ide> {
<ide> return app('config')->set($key);
<ide> function info($message, $context = array())
<ide> * @param array $context
<ide> * @return void
<ide> */
<del> function logger($message, array $context = array())
<add> function logger($message = null, array $context = array())
<ide> {
<add> if (is_null($message)) return app('log');
<add>
<ide> return app('log')->debug($message, $context);
<ide> }
<ide> }
<ide> function public_path($path = '')
<ide> */
<ide> function redirect($to = null, $status = 302, $headers = array(), $secure = null)
<ide> {
<del> if ( ! is_null($to))
<del> {
<del> return app('redirect')->to($to, $status, $headers, $secure);
<del> }
<del> else
<del> {
<del> return app('redirect');
<del> }
<add> if (is_null($to)) return app('redirect');
<add>
<add> return app('redirect')->to($to, $status, $headers, $secure);
<ide> }
<ide> }
<ide>
<ide> function storage_path($path = '')
<ide> * @param string $locale
<ide> * @return string
<ide> */
<del> function trans($id, $parameters = array(), $domain = 'messages', $locale = null)
<add> function trans($id = null, $parameters = array(), $domain = 'messages', $locale = null)
<ide> {
<add> if (is_null($id)) return app('translator');
<add>
<ide> return app('translator')->trans($id, $parameters, $domain, $locale);
<ide> }
<ide> }
| 1
|
Python
|
Python
|
assign ips upon machine creation
|
ca8e25b6a495a7ea883c82aadd289833dcf1cf29
|
<ide><path>libcloud/compute/drivers/packet.py
<ide>
<ide>
<ide> import datetime
<add>import json
<ide>
<ide> from libcloud.utils.py3 import httplib
<ide>
<ide> def list_sizes(self):
<ide> size.get('line') == 'baremetal']
<ide>
<ide> def create_node(self, name, size, image, location,
<del> ex_project_id=None, cloud_init=None, **kwargs):
<add> ex_project_id=None, ip_addresses=[], cloud_init=None, **kwargs):
<ide> """
<ide> Create a node.
<ide>
<ide> def create_node(self, name, size, image, location,
<ide> # if project has been specified on initialization of driver, then
<ide> # create on this project
<ide>
<add> import ipdb; ipdb.set_trace();
<ide> if self.project_id:
<ide> ex_project_id = self.project_id
<ide> else:
<ide> def create_node(self, name, size, image, location,
<ide> facility = location.extra['code']
<ide> params = {'hostname': name, 'plan': size.id,
<ide> 'operating_system': image.id, 'facility': facility,
<del> 'include': 'plan', 'billing_cycle': 'hourly'}
<add> 'include': 'plan', 'billing_cycle': 'hourly',
<add> 'ip_addresses': ip_addresses}
<ide> params.update(kwargs)
<ide> if cloud_init:
<ide> params["userdata"] = cloud_init
<ide> data = self.connection.request('/projects/%s/devices' %
<ide> (ex_project_id),
<del> params=params, method='POST')
<add> data=json.dumps(params), method='POST')
<ide>
<ide> status = data.object.get('status', 'OK')
<ide> if status == 'ERROR':
| 1
|
PHP
|
PHP
|
add support for appendable component attributes
|
09b887b85614d3e2539e74f40d7aa9c1c9f903d3
|
<ide><path>src/Illuminate/View/AppendableAttributeValue.php
<add><?php
<add>
<add>namespace Illuminate\View;
<add>
<add>class AppendableAttributeValue
<add>{
<add> public $value;
<add>
<add> public function __construct($value)
<add> {
<add> $this->value = $value;
<add> }
<add>}
<ide><path>src/Illuminate/View/ComponentAttributeBag.php
<ide> public function exceptProps($keys)
<ide> */
<ide> public function merge(array $attributeDefaults = [], $escape = true)
<ide> {
<del> $attributes = [];
<del>
<ide> $attributeDefaults = array_map(function ($value) use ($escape) {
<del> if (! $escape || is_object($value) || is_null($value) || is_bool($value)) {
<del> return $value;
<del> }
<del>
<del> return e($value);
<add> return $this->shouldEscapeAttributeValue($escape, $value)
<add> ? e($value)
<add> : $value;
<ide> }, $attributeDefaults);
<ide>
<del> foreach ($this->attributes as $key => $value) {
<del> if ($key !== 'class') {
<del> $attributes[$key] = $value;
<add> [$appendableAttributes, $nonAppendableAttributes] = collect($this->attributes)
<add> ->partition(function ($value, $key) use ($attributeDefaults) {
<add> return $key === 'class' ||
<add> (isset($attributeDefaults[$key]) &&
<add> $attributeDefaults[$key] instanceof AppendableAttributeValue);
<add> });
<ide>
<del> continue;
<del> }
<add> $attributes = $appendableAttributes->mapWithKeys(function ($value, $key) use ($attributeDefaults, $escape) {
<add> $defaultsValue = isset($attributeDefaults[$key]) && $attributeDefaults[$key] instanceof AppendableAttributeValue
<add> ? $this->resolveAppendableAttributeDefault($attributeDefaults, $key, $escape)
<add> : ($attributeDefaults[$key] ?? '');
<ide>
<del> $attributes[$key] = implode(' ', array_unique(
<del> array_filter([$attributeDefaults[$key] ?? '', $value])
<del> ));
<del> }
<add> return [$key => implode(' ', array_unique(array_filter([$defaultsValue, $value])))];
<add> })->merge($nonAppendableAttributes)->all();
<ide>
<ide> return new static(array_merge($attributeDefaults, $attributes));
<ide> }
<ide>
<add> /**
<add> * Determine if the specific attribute value should be escaped.
<add> *
<add> * @param bool $escape
<add> * @param mixed $value
<add> * @return bool
<add> */
<add> protected function shouldEscapeAttributeValue($escape, $value)
<add> {
<add> if (! $escape) {
<add> return false;
<add> }
<add>
<add> return ! is_object($value) &&
<add> ! is_null($value) &&
<add> ! is_bool($value);
<add> }
<add>
<add> /**
<add> * Create a new appendable attribute value.
<add> *
<add> * @param mixed $value
<add> * @return \Illuminate\View\AppendableAttributeValue
<add> */
<add> public function appends($value)
<add> {
<add> return new AppendableAttributeValue($value);
<add> }
<add>
<add> /**
<add> * Resolve an appendable attribute value default value.
<add> *
<add> * @param array $attributeDefaults
<add> * @param string $key
<add> * @param bool $escape
<add> * @return mixed
<add> */
<add> protected function resolveAppendableAttributeDefault($attributeDefaults, $key, $escape)
<add> {
<add> if ($this->shouldEscapeAttributeValue($escape, $value = $attributeDefaults[$key]->value)) {
<add> $value = e($value);
<add> }
<add>
<add> return $value;
<add> }
<add>
<ide> /**
<ide> * Get all of the raw attributes.
<ide> *
<ide><path>tests/Integration/View/BladeTest.php
<ide> public function test_rendering_the_same_dynamic_component_with_different_attribu
<ide> </span>', trim($view));
<ide> }
<ide>
<add> public function test_appendable_attributes()
<add> {
<add> $view = View::make('uses-appendable-panel', ['name' => 'Taylor'])->render();
<add>
<add> $this->assertEquals('<div class="mt-4 bg-gray-100" data-controller="inside-controller outside-controller" foo="bar">
<add> Hello Taylor
<add></div>', trim($view));
<add> }
<add>
<ide> protected function getEnvironmentSetUp($app)
<ide> {
<ide> $app['config']->set('view.paths', [__DIR__.'/templates']);
<ide><path>tests/Integration/View/templates/components/appendable-panel.blade.php
<add>@props(['name'])
<add>
<add><div {{ $attributes->merge(['class' => 'mt-4', 'data-controller' => $attributes->appends('inside-controller')]) }}>
<add> Hello {{ $name }}
<add></div>
<ide><path>tests/Integration/View/templates/uses-appendable-panel.blade.php
<add><x-appendable-panel class="bg-gray-100" :name="$name" data-controller="outside-controller" foo="bar">
<add> Panel contents
<add></x-appendable-panel>
| 5
|
Ruby
|
Ruby
|
integrate amo xml serializer into ar
|
e83a05af076637cc78f0408f5810d5f8f965e10c
|
<ide><path>activemodel/lib/active_model/serializers/xml.rb
<ide> def initialize(name, serializable)
<ide> @value = compute_value
<ide> end
<ide>
<add> # There is a significant speed improvement if the value
<add> # does not need to be escaped, as <tt>tag!</tt> escapes all values
<add> # to ensure that valid XML is generated. For known binary
<add> # values, it is at least an order of magnitude faster to
<add> # Base64 encode binary values and directly put them in the
<add> # output XML than to pass the original value or the Base64
<add> # encoded value to the <tt>tag!</tt> method. It definitely makes
<add> # no sense to Base64 encode the value and then give it to
<add> # <tt>tag!</tt>, since that just adds additional overhead.
<ide> def needs_encoding?
<ide> ![ :binary, :date, :datetime, :boolean, :float, :integer ].include?(type)
<ide> end
<ide> def serializable_method_attributes
<ide> end
<ide> end
<ide>
<del> def add_attributes
<del> (serializable_attributes + serializable_method_attributes).each do |attribute|
<del> add_tag(attribute)
<del> end
<del> end
<del>
<del> def add_procs
<del> if procs = options.delete(:procs)
<del> [ *procs ].each do |proc|
<del> proc.call(options)
<del> end
<del> end
<del> end
<del>
<del> def add_tag(attribute)
<del> builder.tag!(
<del> reformat_name(attribute.name),
<del> attribute.value.to_s,
<del> attribute.decorations(!options[:skip_types])
<del> )
<del> end
<del>
<ide> def serialize
<ide> args = [root]
<ide>
<ide> def reformat_name(name)
<ide> name = name.camelize if camelize?
<ide> dasherize? ? name.dasherize : name
<ide> end
<add>
<add> def add_attributes
<add> (serializable_attributes + serializable_method_attributes).each do |attribute|
<add> builder.tag!(
<add> reformat_name(attribute.name),
<add> attribute.value.to_s,
<add> attribute.decorations(!options[:skip_types])
<add> )
<add> end
<add> end
<add>
<add> def add_procs
<add> if procs = options.delete(:procs)
<add> [ *procs ].each do |proc|
<add> proc.call(options)
<add> end
<add> end
<add> end
<ide> end
<ide>
<ide> def to_xml(options = {}, &block)
<ide><path>activerecord/lib/active_record/serializers/xml_serializer.rb
<ide> def from_xml(xml)
<ide> end
<ide> end
<ide>
<del> class XmlSerializer < ActiveModel::Serializer #:nodoc:
<add> class XmlSerializer < ActiveModel::Serializers::Xml::Serializer #:nodoc:
<ide> include Serialization::RecordSerializer
<ide>
<del> def builder
<del> @builder ||= begin
<del> require 'builder' unless defined? ::Builder
<del> options[:indent] ||= 2
<del> builder = options[:builder] ||= ::Builder::XmlMarkup.new(:indent => options[:indent])
<del>
<del> unless options[:skip_instruct]
<del> builder.instruct!
<del> options[:skip_instruct] = true
<del> end
<del>
<del> builder
<del> end
<del> end
<del>
<del> def root
<del> root = (options[:root] || @serializable.class.to_s.underscore).to_s
<del> reformat_name(root)
<del> end
<del>
<del> def dasherize?
<del> !options.has_key?(:dasherize) || options[:dasherize]
<del> end
<del>
<del> def camelize?
<del> options.has_key?(:camelize) && options[:camelize]
<del> end
<del>
<del> def reformat_name(name)
<del> name = name.camelize if camelize?
<del> dasherize? ? name.dasherize : name
<del> end
<del>
<ide> def serializable_attributes
<ide> serializable_attribute_names.collect { |name| Attribute.new(name, @serializable) }
<ide> end
<ide> def serializable_method_attributes
<ide> end
<ide> end
<ide>
<del> def add_attributes
<del> (serializable_attributes + serializable_method_attributes).each do |attribute|
<del> add_tag(attribute)
<del> end
<del> end
<del>
<del> def add_procs
<del> if procs = options.delete(:procs)
<del> [ *procs ].each do |proc|
<del> proc.call(options)
<del> end
<del> end
<del> end
<del>
<del> def add_tag(attribute)
<del> builder.tag!(
<del> reformat_name(attribute.name),
<del> attribute.value.to_s,
<del> attribute.decorations(!options[:skip_types])
<del> )
<del> end
<del>
<ide> def add_associations(association, records, opts)
<ide> if records.is_a?(Enumerable)
<ide> tag = reformat_name(association.to_s)
<ide> def serialize
<ide> end
<ide> end
<ide>
<del> class Attribute #:nodoc:
<del> attr_reader :name, :value, :type
<del>
<del> def initialize(name, record)
<del> @name, @record = name, record
<del>
<del> @type = compute_type
<del> @value = compute_value
<del> end
<del>
<del> # There is a significant speed improvement if the value
<del> # does not need to be escaped, as <tt>tag!</tt> escapes all values
<del> # to ensure that valid XML is generated. For known binary
<del> # values, it is at least an order of magnitude faster to
<del> # Base64 encode binary values and directly put them in the
<del> # output XML than to pass the original value or the Base64
<del> # encoded value to the <tt>tag!</tt> method. It definitely makes
<del> # no sense to Base64 encode the value and then give it to
<del> # <tt>tag!</tt>, since that just adds additional overhead.
<del> def needs_encoding?
<del> ![ :binary, :date, :datetime, :boolean, :float, :integer ].include?(type)
<del> end
<del>
<del> def decorations(include_types = true)
<del> decorations = {}
<del>
<del> if type == :binary
<del> decorations[:encoding] = 'base64'
<del> end
<del>
<del> if include_types && type != :string
<del> decorations[:type] = type
<del> end
<del>
<del> if value.nil?
<del> decorations[:nil] = true
<del> end
<del>
<del> decorations
<del> end
<del>
<add> class Attribute < ActiveModel::Serializers::Xml::Serializer::Attribute #:nodoc:
<ide> protected
<ide> def compute_type
<del> type = @record.class.serialized_attributes.has_key?(name) ? :yaml : @record.class.columns_hash[name].type
<add> type = @serializable.class.serialized_attributes.has_key?(name) ? :yaml : @serializable.class.columns_hash[name].type
<ide>
<ide> case type
<ide> when :text
<ide> def compute_type
<ide> type
<ide> end
<ide> end
<del>
<del> def compute_value
<del> value = @record.send(name)
<del>
<del> if formatter = Hash::XML_FORMATTING[type.to_s]
<del> value ? formatter.call(value) : nil
<del> else
<del> value
<del> end
<del> end
<ide> end
<ide>
<ide> class MethodAttribute < Attribute #:nodoc:
<ide> protected
<ide> def compute_type
<del> Hash::XML_TYPE_NAMES[@record.send(name).class.name] || :string
<add> Hash::XML_TYPE_NAMES[@serializable.send(name).class.name] || :string
<ide> end
<ide> end
<ide> end
| 2
|
Ruby
|
Ruby
|
require minitest rather than test/unit
|
b15d2c0708b78ee1c8ad6958022214bda18bdbae
|
<ide><path>actionmailer/test/abstract_unit.rb
<ide> lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
<ide> $:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'action_mailer'
<ide> require 'action_mailer/test_case'
<ide>
<ide><path>actionpack/test/abstract_unit.rb
<ide> Encoding.default_external = "UTF-8"
<ide> end
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'abstract_controller'
<ide> require 'action_controller'
<ide> require 'action_view'
<ide><path>actionpack/test/ts_isolated.rb
<ide> $:.unshift(File.dirname(__FILE__))
<ide> $:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'rbconfig'
<ide> require 'active_support/core_ext/kernel/reporting'
<ide> require 'abstract_unit'
<ide><path>activemodel/test/cases/helper.rb
<ide> # Show backtraces for deprecated behavior for quicker cleanup.
<ide> ActiveSupport::Deprecation.debug = true
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide><path>activeresource/test/abstract_unit.rb
<ide> lib = File.expand_path("#{File.dirname(__FILE__)}/../lib")
<ide> $:.unshift(lib) unless $:.include?('lib') || $:.include?(lib)
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'active_resource'
<ide> require 'active_support'
<ide> require 'active_support/test_case'
<ide><path>activesupport/lib/active_support/test_case.rb
<del>require 'minitest/unit'
<add>require 'minitest/spec'
<ide> require 'active_support/testing/setup_and_teardown'
<ide> require 'active_support/testing/assertions'
<ide> require 'active_support/testing/deprecation'
<ide><path>activesupport/test/abstract_unit.rb
<ide> Encoding.default_external = "UTF-8"
<ide> end
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'empty_bool'
<ide>
<ide> silence_warnings { require 'mocha' }
<ide> def uses_memcached(test_name)
<ide> end
<ide>
<ide> # Show backtraces for deprecated behavior for quicker cleanup.
<del>ActiveSupport::Deprecation.debug = true
<ide>\ No newline at end of file
<add>ActiveSupport::Deprecation.debug = true
<ide><path>activesupport/test/ts_isolated.rb
<ide> $:.unshift(File.dirname(__FILE__) + '/../../activesupport/lib')
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'active_support/test_case'
<ide> require 'rbconfig'
<ide> require 'active_support/core_ext/kernel/reporting'
<ide><path>railties/lib/rails/generators/test_unit/plugin/templates/test_helper.rb
<ide> require 'rubygems'
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'active_support'
<ide><path>railties/lib/rails/test_help.rb
<ide> # so fixtures aren't loaded into that environment
<ide> abort("Abort testing: Your Rails environment is running in production mode!") if Rails.env.production?
<ide>
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'active_support/test_case'
<ide> require 'action_controller/test_case'
<ide> require 'action_dispatch/testing/integration'
<ide><path>railties/test/abstract_unit.rb
<ide> require File.expand_path("../../../load_paths", __FILE__)
<ide>
<ide> require 'stringio'
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'fileutils'
<ide>
<ide> require 'active_support'
<ide><path>railties/test/application/route_inspect_test.rb
<del>require 'test/unit'
<add>require 'minitest/autorun'
<ide> require 'rails/application/route_inspector'
<ide> require 'action_controller'
<ide> require 'rails/engine'
<ide><path>railties/test/isolation/abstract_unit.rb
<ide> # Rails booted up.
<ide> require 'fileutils'
<ide>
<del>require 'test/unit'
<ide> require 'rubygems'
<add>require 'minitest/autorun'
<ide> require 'active_support/test_case'
<ide>
<ide> # TODO: Remove setting this magic constant
| 13
|
Javascript
|
Javascript
|
replace simple quote by double quote
|
6158e4f522fa4b9293085a1e3cd7c6ff97fe5079
|
<ide><path>glances/outputs/static/js/components/plugin-alert/component.js
<ide> import angular from "angular";
<ide> import GlancesPluginAlertController from "./controller";
<ide> import template from "./view.html";
<ide>
<del>export default angular.module('glancesApp').component('glancesPluginAlert', {
<add>export default angular.module("glancesApp").component("glancesPluginAlert", {
<ide> controller: GlancesPluginAlertController,
<ide> controllerAs: 'vm',
<ide> templateUrl: template,
<ide><path>glances/outputs/static/js/services/plugin_helper.js
<ide> function GlancesPluginHelper () {
<ide> return plugin;
<ide> }
<ide>
<del>export default angular.module('glancesApp').service('GlancesPluginHelper', GlancesPluginHelper);
<add>export default angular.module("glancesApp").service("GlancesPluginHelper", GlancesPluginHelper);
<ide><path>glances/outputs/static/js/services/stats.js
<ide>
<del>import angular from 'angular';
<add>import angular from "angular";
<ide>
<ide> function GlancesStats ($http, $q, $rootScope, $timeout, GlancesPluginHelper, REFRESH_TIME, CONFIG, ARGUMENTS) {
<ide>
<ide> function GlancesStats ($http, $q, $rootScope, $timeout, GlancesPluginHelper, REF
<ide> };
<ide> }
<ide>
<del>export default angular.module('glancesApp').service('GlancesStats', GlancesStats);
<add>export default angular.module("glancesApp").service("GlancesStats", GlancesStats);
| 3
|
Java
|
Java
|
fix typo in error message.
|
c799bc08ade4fb981a2a5b2ad983a0adf1445c23
|
<ide><path>src/main/java/io/reactivex/observers/BaseTestConsumer.java
<ide> public final U assertValueSequence(Iterable<? extends T> sequence) {
<ide> throw fail("More values received than expected (" + i + ")");
<ide> }
<ide> if (expectedNext) {
<del> throw fail("Fever values received than expected (" + i + ")");
<add> throw fail("Fewer values received than expected (" + i + ")");
<ide> }
<ide> return (U)this;
<ide> }
| 1
|
Javascript
|
Javascript
|
return self from readable.wrap
|
14947b6c5e12ec65e6df75d4db5bcf47f7b29819
|
<ide><path>lib/_stream_readable.js
<ide> Readable.prototype.wrap = function(stream) {
<ide> // underlying stream.
<ide> self._read = function(n) {
<ide> if (paused) {
<del> stream.resume();
<ide> paused = false;
<add> stream.resume();
<ide> }
<ide> };
<add>
<add> return self;
<ide> };
<ide>
<ide>
<ide><path>test/simple/test-stream2-readable-wrap.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>
<add>var Readable = require('_stream_readable');
<add>var Writable = require('_stream_writable');
<add>var EE = require('events').EventEmitter;
<add>
<add>var old = new EE;
<add>var r = new Readable({ highWaterMark: 10 });
<add>assert.equal(r, r.wrap(old));
<add>
<add>var ended = false;
<add>r.on('end', function() {
<add> ended = true;
<add>});
<add>
<add>var pauses = 0;
<add>var resumes = 0;
<add>
<add>old.pause = function() {
<add> pauses++;
<add> old.emit('pause');
<add> flowing = false;
<add>};
<add>
<add>old.resume = function() {
<add> resumes++;
<add> old.emit('resume');
<add> flow();
<add>};
<add>
<add>var flowing;
<add>var chunks = 10;
<add>var oldEnded = false;
<add>function flow() {
<add> flowing = true;
<add> while (flowing && chunks-- > 0) {
<add> old.emit('data', new Buffer('xxxxxxxxxx'));
<add> }
<add> if (chunks <= 0) {
<add> oldEnded = true;
<add> old.emit('end');
<add> }
<add>}
<add>
<add>var w = new Writable({ highWaterMark: 20 });
<add>var written = [];
<add>w._write = function(chunk, encoding, cb) {
<add> written.push(chunk.toString());
<add> setTimeout(cb);
<add>};
<add>
<add>var finished = false;
<add>w.on('finish', function() {
<add> finished = true;
<add>});
<add>
<add>
<add>var expect = new Array(11).join('xxxxxxxxxx');
<add>
<add>r.pipe(w);
<add>
<add>flow();
<add>
<add>process.on('exit', function() {
<add> assert.equal(pauses, 10);
<add> assert.equal(resumes, 9);
<add> assert(ended);
<add> assert(finished);
<add> assert(oldEnded);
<add> assert.equal(written.join(''), expect);
<add> console.log('ok');
<add>});
| 2
|
Ruby
|
Ruby
|
add async and inline adapters
|
b17a7e4c4daa4ab54223b0c5e2d03b491c070e0e
|
<ide><path>actioncable/lib/action_cable/subscription_adapter/async.rb
<add>require 'action_cable/subscription_adapter/inline'
<add>
<add>module ActionCable
<add> module SubscriptionAdapter
<add> class Async < Inline # :nodoc:
<add> private
<add> def subscriber_map
<add> @subscriber_map ||= AsyncSubscriberMap.new
<add> end
<add>
<add> class AsyncSubscriberMap < SubscriberMap
<add> def add_subscriber(*)
<add> ::EM.next_tick { super }
<add> end
<add>
<add> def invoke_callback(*)
<add> ::EM.next_tick { super }
<add> end
<add> end
<add> end
<add> end
<add>end
<ide><path>actioncable/lib/action_cable/subscription_adapter/inline.rb
<add>module ActionCable
<add> module SubscriptionAdapter
<add> class Inline < Base # :nodoc:
<add> def broadcast(channel, payload)
<add> subscriber_map.broadcast(channel, payload)
<add> end
<add>
<add> def subscribe(channel, callback, success_callback = nil)
<add> subscriber_map.add_subscriber(channel, callback, success_callback)
<add> end
<add>
<add> def unsubscribe(channel, callback)
<add> subscriber_map.remove_subscriber(channel, callback)
<add> end
<add>
<add> private
<add> def subscriber_map
<add> @subscriber_map ||= SubscriberMap.new
<add> end
<add> end
<add> end
<add>end
| 2
|
Text
|
Text
|
improve russian translation
|
78e4ef96317b27b1e56769c27e3ce8f9844b3b76
|
<ide><path>curriculum/challenges/russian/05-apis-and-microservices/basic-node-and-express/use-the-.env-file.russian.md
<ide> localeTitle: Используйте файл .env
<ide> ## Description
<ide> <section id='description'>
<ide> Файл <code>.env</code> - это скрытый файл, который используется для передачи переменных среды вашему приложению. Этот файл является секретным, никто, кроме вас, не может получить к нему доступ, и его можно использовать для хранения данных, которые вы хотите сохранить в секрете или скрыть. Например, вы можете хранить ключи API от внешних служб или URI вашей базы данных. Вы также можете использовать его для хранения параметров конфигурации. Установив параметры конфигурации, вы можете изменить поведение вашего приложения без необходимости переписывать некоторый код.
<del>Переменные среды доступны из приложения как <code>process.env.VAR_NAME</code> . Объект <code>process.env</code> является глобальным объектом Node, а переменные передаются в виде строк. По соглашению имена переменных должны быть в верхнем регистре, а слова разделены подчеркиванием. <code>.env</code> - это файл оболочки, поэтому вам не нужно <code>.env</code> в кавычки имена или значения. Также важно отметить, что не должно быть пробела вокруг знака равенства, когда вы присваиваете значения своим переменным, например, <code>VAR_NAME=value</code> . Обычно вы помещаете каждое определение переменной в отдельную строку.
<del>Давайте добавим переменную окружения в качестве опции конфигурации. Сохраните переменную <code>MESSAGE_STYLE=uppercase</code> <code>.env</code> файле <code>.env</code> . Затем сообщите обработчику маршрута GET <code>/json</code> который вы создали в последнем вызове, чтобы преобразовать сообщение объекта ответа в верхний регистр, если <code>process.env.MESSAGE_STYLE</code> равен <code>process.env.MESSAGE_STYLE</code> <code>uppercase</code> . Объектом ответа должно стать <code>{"message": "HELLO JSON"}</code> .
<add>Переменные среды доступны из приложения как <code>process.env.VAR_NAME</code> . Объект <code>process.env</code> является глобальным объектом Node, а переменные передаются в виде строк. По соглашению имена переменных должны быть в верхнем регистре, а слова разделены подчеркиванием. <code>.env</code> - это файл оболочки, поэтому вам не нужно заключать <code>.env</code> в кавычки имена или значения. Также важно отметить, что не должно быть пробела вокруг знака равенства, когда вы присваиваете значения своим переменным, например, <code>VAR_NAME=value</code> . Обычно помещают каждое определение переменной в отдельную строку.
<ide> </section>
<ide>
<del>## Instructions
<add>## Задание
<ide> <section id='instructions'>
<del>Let's add an environment variable as a configuration option.
<del>Store the variable <code>MESSAGE_STYLE=uppercase</code> in the <code>.env</code> file. Then tell the GET <code>/json</code> route handler that you created in the last challenge to transform the response object’s message to uppercase if <code>process.env.MESSAGE_STYLE</code> equals <code>uppercase</code>. The response object should become <code>{"message": "HELLO JSON"}</code>.
<add>
<add>Добавьте переменную окружения в качестве опции конфигурации. Сохраните переменную <code>MESSAGE_STYLE=uppercase</code> <code>.env</code> файле <code>.env</code> . Затем сообщите обработчику маршрута GET <code>/json</code> который вы создали в последнем вызове, чтобы преобразовать сообщение объекта ответа в верхний регистр, если <code>process.env.MESSAGE_STYLE</code> равен <code>process.env.MESSAGE_STYLE</code> <code>uppercase</code> . Объектом ответа должно стать <code>{"message": "HELLO JSON"}</code> .
<ide> </section>
<ide>
<del>## Tests
<add>## Тесты
<ide> <section id='tests'>
<ide>
<ide> ```yml
| 1
|
Go
|
Go
|
check sysinfo for cpuset cpu.shares and blkio
|
b7599d58cb103e3b13b3a51553fd69f5f8b60893
|
<ide><path>daemon/daemon_unix.go
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostC
<ide> return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
<ide> }
<ide> }
<add> if hostConfig.CPUShares > 0 && !daemon.SystemConfig().CPUShares {
<add> warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
<add> logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
<add> hostConfig.CPUShares = 0
<add> }
<ide> if hostConfig.CPUPeriod > 0 && !daemon.SystemConfig().CPUCfsPeriod {
<ide> warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
<ide> logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostC
<ide> logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
<ide> hostConfig.CPUQuota = 0
<ide> }
<add> if (hostConfig.CpusetCpus != "" || hostConfig.CpusetMems != "") && !daemon.SystemConfig().Cpuset {
<add> warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
<add> logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
<add> hostConfig.CpusetCpus = ""
<add> hostConfig.CpusetMems = ""
<add> }
<add> if hostConfig.BlkioWeight > 0 && !daemon.SystemConfig().BlkioWeight {
<add> warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
<add> logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
<add> hostConfig.BlkioWeight = 0
<add> }
<ide> if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
<ide> return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
<ide> }
<ide><path>pkg/sysinfo/sysinfo.go
<ide> type SysInfo struct {
<ide>
<ide> *cgroupMemInfo
<ide> *cgroupCPUInfo
<add> *cgroupBlkioInfo
<add> *cgroupCpusetInfo
<ide>
<ide> // Whether IPv4 forwarding is supported or not, if this was disabled, networking will not work
<ide> IPv4ForwardingDisabled bool
<ide> type cgroupMemInfo struct {
<ide> }
<ide>
<ide> type cgroupCPUInfo struct {
<add> // Whether CPU shares is supported or not
<add> CPUShares bool
<add>
<ide> // Whether CPU CFS(Completely Fair Scheduler) period is supported or not
<ide> CPUCfsPeriod bool
<ide>
<ide> // Whether CPU CFS(Completely Fair Scheduler) quota is supported or not
<ide> CPUCfsQuota bool
<ide> }
<add>
<add>type cgroupBlkioInfo struct {
<add> // Whether Block IO weight is supported or not
<add> BlkioWeight bool
<add>}
<add>
<add>type cgroupCpusetInfo struct {
<add> // Whether Cpuset is supported or not
<add> Cpuset bool
<add>}
<ide><path>pkg/sysinfo/sysinfo_linux.go
<ide> func New(quiet bool) *SysInfo {
<ide> sysInfo := &SysInfo{}
<ide> sysInfo.cgroupMemInfo = checkCgroupMem(quiet)
<ide> sysInfo.cgroupCPUInfo = checkCgroupCPU(quiet)
<add> sysInfo.cgroupBlkioInfo = checkCgroupBlkioInfo(quiet)
<add> sysInfo.cgroupCpusetInfo = checkCgroupCpusetInfo(quiet)
<ide>
<ide> _, err := cgroups.FindCgroupMountpoint("devices")
<ide> sysInfo.CgroupDevicesEnabled = err == nil
<ide> func checkCgroupCPU(quiet bool) *cgroupCPUInfo {
<ide> return info
<ide> }
<ide>
<add> info.CPUShares = cgroupEnabled(mountPoint, "cpu.shares")
<add> if !quiet && !info.CPUShares {
<add> logrus.Warn("Your kernel does not support cgroup cpu shares")
<add> }
<add>
<ide> info.CPUCfsPeriod = cgroupEnabled(mountPoint, "cpu.cfs_period_us")
<ide> if !quiet && !info.CPUCfsPeriod {
<ide> logrus.Warn("Your kernel does not support cgroup cfs period")
<ide> func checkCgroupCPU(quiet bool) *cgroupCPUInfo {
<ide> return info
<ide> }
<ide>
<add>func checkCgroupBlkioInfo(quiet bool) *cgroupBlkioInfo {
<add> info := &cgroupBlkioInfo{}
<add> mountPoint, err := cgroups.FindCgroupMountpoint("blkio")
<add> if err != nil {
<add> if !quiet {
<add> logrus.Warn(err)
<add> }
<add> return info
<add> }
<add>
<add> info.BlkioWeight = cgroupEnabled(mountPoint, "blkio.weight")
<add> if !quiet && !info.BlkioWeight {
<add> logrus.Warn("Your kernel does not support cgroup blkio weight")
<add> }
<add> return info
<add>}
<add>
<add>func checkCgroupCpusetInfo(quiet bool) *cgroupCpusetInfo {
<add> info := &cgroupCpusetInfo{}
<add> _, err := cgroups.FindCgroupMountpoint("cpuset")
<add> if err != nil {
<add> if !quiet {
<add> logrus.Warn(err)
<add> }
<add> return info
<add> }
<add>
<add> info.Cpuset = true
<add> return info
<add>}
<add>
<ide> func cgroupEnabled(mountPoint, name string) bool {
<ide> _, err := os.Stat(path.Join(mountPoint, name))
<ide> return err == nil
| 3
|
Javascript
|
Javascript
|
implement synthetic modules for node 10
|
a53578be7e6dbbc3767440add2666ffb248c9985
|
<ide><path>test/ConfigTestCases.template.js
<ide> const describeCases = config => {
<ide> specifier,
<ide> "evaluated"
<ide> );
<del> return await asModule(result);
<add> return await asModule(result, module.context);
<ide> }
<ide> });
<ide> if (esmMode === "unlinked") return esm;
<ide> const describeCases = config => {
<ide> specifier,
<ide> "unlinked"
<ide> ),
<del> module.context
<add> module.context,
<add> true
<ide> );
<ide> }
<ide> );
<ide><path>test/TestCases.template.js
<ide> const describeCases = config => {
<ide> specifier,
<ide> "evaluated"
<ide> );
<del> return await asModule(result);
<add> return await asModule(result, module.context);
<ide> }
<ide> });
<ide> } catch (e) {
<ide> const describeCases = config => {
<ide> await esm.link(async (specifier, module) => {
<ide> return await asModule(
<ide> await _require(specifier, "unlinked"),
<del> module.context
<add> module.context,
<add> true
<ide> );
<ide> });
<ide> // node.js 10 needs instantiate
<ide><path>test/helpers/asModule.js
<ide> const vm = require("vm");
<ide>
<del>module.exports = async (something, unlinkedInContext) => {
<add>const SYNTHETIC_MODULES_STORE = "__SYNTHETIC_MODULES_STORE";
<add>
<add>module.exports = async (something, context, unlinked) => {
<ide> if (
<ide> something instanceof (vm.Module || /* node.js 10 */ vm.SourceTextModule)
<ide> ) {
<ide> return something;
<ide> }
<del> if (!vm.SyntheticModule) return something;
<del> const m = new vm.SyntheticModule(
<del> [...new Set(["default", ...Object.keys(something)])],
<del> function () {
<del> for (const key in something) {
<del> this.setExport(key, something[key]);
<del> }
<del> this.setExport("default", something);
<del> },
<del> {
<del> context: unlinkedInContext
<del> }
<del> );
<del> if (unlinkedInContext) return m;
<add> context[SYNTHETIC_MODULES_STORE] = context[SYNTHETIC_MODULES_STORE] || [];
<add> const i = context[SYNTHETIC_MODULES_STORE].length;
<add> context[SYNTHETIC_MODULES_STORE].push(something);
<add> const code = [...new Set(["default", ...Object.keys(something)])]
<add> .map(
<add> name =>
<add> `const _${name} = ${SYNTHETIC_MODULES_STORE}[${i}][${JSON.stringify(
<add> name
<add> )}]; export { _${name} as ${name}};`
<add> )
<add> .join("\n");
<add> const m = new vm.SourceTextModule(code, {
<add> context
<add> });
<add> if (unlinked) return m;
<ide> await m.link(() => {});
<ide> if (m.instantiate) m.instantiate();
<ide> await m.evaluate();
| 3
|
Text
|
Text
|
fix typo on oop challenge
|
abc6c3c2088e2ee7d7688ce8247aa5a9a7c6c96d
|
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/object-oriented-programming/remember-to-set-the-constructor-property-when-changing-the-prototype.english.md
<ide> function Dog(name) {
<ide> // Modify the code below this line
<ide> Dog.prototype = {
<ide>
<del> numLegs: 2,
<add> numLegs: 4,
<ide> eat: function() {
<ide> console.log("nom nom nom");
<ide> },
<ide> function Dog(name) {
<ide> }
<ide> Dog.prototype = {
<ide> constructor: Dog,
<del> numLegs: 2,
<add> numLegs: 4,
<ide> eat: function() {
<ide> console.log("nom nom nom");
<ide> },
| 1
|
Java
|
Java
|
fix directories i/o in resourcehttprequesthandler
|
4d5fca596dfe193556ad7148d16aae718805a84d
|
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
<ide>
<ide> package org.springframework.web.servlet.resource;
<ide>
<add>import java.io.FileNotFoundException;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<ide> import java.io.OutputStream;
<ide> protected void setHeaders(HttpServletResponse response, Resource resource, Media
<ide> * @throws IOException in case of errors while writing the content
<ide> */
<ide> protected void writeContent(HttpServletResponse response, Resource resource) throws IOException {
<del> InputStream in = resource.getInputStream();
<ide> try {
<del> StreamUtils.copy(in, response.getOutputStream());
<del> }
<del> finally {
<add> InputStream in = resource.getInputStream();
<ide> try {
<del> in.close();
<add> StreamUtils.copy(in, response.getOutputStream());
<ide> }
<del> catch (IOException ex) {
<del> // ignore
<add> finally {
<add> try {
<add> in.close();
<add> }
<add> catch (Throwable ex) {
<add> // ignore, see SPR-12999
<add> }
<ide> }
<ide> }
<add> catch (FileNotFoundException ex) {
<add> // ignore, see SPR-12999
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandlerTests.java
<ide> package org.springframework.web.servlet.resource;
<ide>
<ide> import static org.junit.Assert.*;
<add>import static org.mockito.BDDMockito.given;
<add>import static org.mockito.Mockito.*;
<ide>
<add>import java.io.FileNotFoundException;
<ide> import java.io.IOException;
<add>import java.io.InputStream;
<ide> import java.util.ArrayList;
<ide> import java.util.Arrays;
<ide> import java.util.List;
<ide> public void setUp() throws Exception {
<ide> List<Resource> paths = new ArrayList<>(2);
<ide> paths.add(new ClassPathResource("test/", getClass()));
<ide> paths.add(new ClassPathResource("testalternatepath/", getClass()));
<add> paths.add(new ClassPathResource("META-INF/resources/webjars/"));
<ide>
<ide> this.handler = new ResourceHttpRequestHandler();
<ide> this.handler.setLocations(paths);
<ide> public void initAllowedLocations() throws Exception {
<ide> PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0);
<ide> Resource[] locations = resolver.getAllowedLocations();
<ide>
<del> assertEquals(2, locations.length);
<add> assertEquals(3, locations.length);
<ide> assertEquals("test/", ((ClassPathResource) locations[0]).getPath());
<ide> assertEquals("testalternatepath/", ((ClassPathResource) locations[1]).getPath());
<add> assertEquals("META-INF/resources/webjars/", ((ClassPathResource) locations[2]).getPath());
<ide> }
<ide>
<ide> @Test
<ide> public void directory() throws Exception {
<ide> assertEquals(404, this.response.getStatus());
<ide> }
<ide>
<add> @Test
<add> public void directoryInJarFile() throws Exception {
<add> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "underscorejs/");
<add> this.handler.handleRequest(this.request, this.response);
<add> assertEquals(200, this.response.getStatus());
<add> assertEquals(0, this.response.getContentLength());
<add> }
<add>
<ide> @Test
<ide> public void missingResourcePath() throws Exception {
<ide> this.request.setAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE, "");
<ide> public void partialContentMultipleByteRanges() throws Exception {
<ide> assertEquals("t.", ranges[11]);
<ide> }
<ide>
<add> // SPR-12999
<add> @Test
<add> public void writeContentNotGettingInputStream() throws Exception {
<add> Resource resource = mock(Resource.class);
<add> given(resource.getInputStream()).willThrow(FileNotFoundException.class);
<add>
<add> this.handler.writeContent(this.response, resource);
<add>
<add> assertEquals(200, this.response.getStatus());
<add> assertEquals(0, this.response.getContentLength());
<add> }
<add>
<add> // SPR-12999
<add> @Test
<add> public void writeContentNotClosingInputStream() throws Exception {
<add> Resource resource = mock(Resource.class);
<add> InputStream inputStream = mock(InputStream.class);
<add> given(resource.getInputStream()).willReturn(inputStream);
<add> given(inputStream.read(any())).willReturn(-1);
<add> doThrow(new NullPointerException()).when(inputStream).close();
<add>
<add> this.handler.writeContent(this.response, resource);
<add>
<add> assertEquals(200, this.response.getStatus());
<add> assertEquals(0, this.response.getContentLength());
<add> }
<add>
<ide>
<ide> private long headerAsLong(String responseHeaderName) {
<ide> return Long.valueOf(this.response.getHeader(responseHeaderName));
| 2
|
Ruby
|
Ruby
|
use pg connection#escape over connection.escape
|
a2dc26e5add938058b99e2c6c4fe4640dfdae9dd
|
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb
<ide> def quote(value) # :nodoc:
<ide>
<ide> # Quotes strings for use in SQL input.
<ide> def quote_string(s) # :nodoc:
<del> PG::Connection.escape(s)
<add> @connection.escape(s)
<ide> end
<ide>
<ide> # Checks the following cases:
<ide><path>activerecord/test/cases/adapters/abstract_mysql_adapter_test.rb
<ide> require "cases/helper"
<ide>
<ide> class AbstractMysqlAdapterTest < ActiveRecord::Mysql2TestCase
<del> class ExampleMysqlAdapter < ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter; end
<add> if current_adapter?(:Mysql2Adapter)
<add> class ExampleMysqlAdapter < ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter; end
<ide>
<del> def setup
<del> @conn = ExampleMysqlAdapter.new(
<del> ActiveRecord::ConnectionAdapters::Mysql2Adapter.new_client({}),
<del> ActiveRecord::Base.logger,
<del> nil,
<del> { socket: File::NULL }
<del> )
<del> end
<add> def setup
<add> @conn = ExampleMysqlAdapter.new(
<add> ActiveRecord::ConnectionAdapters::Mysql2Adapter.new_client({}),
<add> ActiveRecord::Base.logger,
<add> nil,
<add> { socket: File::NULL }
<add> )
<add> end
<ide>
<del> def test_execute_not_raising_error
<del> assert_nothing_raised do
<del> @conn.execute("SELECT 1")
<add> def test_execute_not_raising_error
<add> assert_nothing_raised do
<add> @conn.execute("SELECT 1")
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def exec_params(*)
<ide> {}
<ide> end
<ide>
<add> def escape(query)
<add> PG::Connection.escape(query)
<add> end
<add>
<ide> def reset
<ide> raise PG::ConnectionBad, "I'll be rescued by the reconnect method"
<ide> end
| 3
|
Python
|
Python
|
add assert_docs_equal util to compare two docs
|
442237787c7b25b38fb441a444f7c780f847f686
|
<ide><path>spacy/tests/util.py
<ide> def apply_transition_sequence(parser, doc, sequence):
<ide> def get_cosine(vec1, vec2):
<ide> """Get cosine for two given vectors"""
<ide> return numpy.dot(vec1, vec2) / (numpy.linalg.norm(vec1) * numpy.linalg.norm(vec2))
<add>
<add>
<add>def assert_docs_equal(doc1, doc2):
<add> # tokens
<add> assert [ t.orth for t in doc1 ] == [ t.orth for t in doc2 ]
<add>
<add> # tags
<add> assert [ t.pos for t in doc1 ] == [ t.pos for t in doc2 ]
<add> assert [ t.tag for t in doc1 ] == [ t.tag for t in doc2 ]
<add>
<add> # parse
<add> assert [ t.head.i for t in doc1 ] == [ t.head.i for t in doc2 ]
<add> assert [ t.dep for t in doc1 ] == [ t.dep for t in doc2 ]
<add> if doc1.is_parsed and doc2.is_parsed:
<add> assert [ s for s in doc1.sents ] == [ s for s in doc2.sents ]
<add>
<add> # entities
<add> assert [ t.ent_type for t in doc1 ] == [ t.ent_type for t in doc2 ]
<add> assert [ t.ent_iob for t in doc1 ] == [ t.ent_iob for t in doc2 ]
<add> assert [ ent for ent in doc1.ents ] == [ ent for ent in doc2.ents ]
| 1
|
Javascript
|
Javascript
|
fix deprecation warning in test-doctool-html
|
0a77830342c699ff8b3e4e2602b57afd01311baa
|
<ide><path>test/doctool/test-doctool-html.js
<ide> function toHTML({ input, filename, nodeVersion, versions }) {
<ide> .use(html.preprocessText, { nodeVersion })
<ide> .use(html.preprocessElements, { filename })
<ide> .use(html.buildToc, { filename, apilinks: {} })
<del> .use(remark2rehype, { allowDangerousHTML: true })
<add> .use(remark2rehype, { allowDangerousHtml: true })
<ide> .use(raw)
<ide> .use(htmlStringify)
<ide> .processSync(input);
| 1
|
Ruby
|
Ruby
|
lock the whole boot step, get rid of unneeded hash
|
844af9fa7c18a0ee3316d6cf1289b144d48d84d7
|
<ide><path>activesupport/lib/active_support/evented_file_update_checker.rb
<ide> def initialize(files, dirs = {}, &block)
<ide> @block = block
<ide> @updated = Concurrent::AtomicBoolean.new(false)
<ide> @lcsp = @ph.longest_common_subpath(@dirs.keys)
<del> @pid_hash = Concurrent::Hash.new
<del> @parent_pid = Process.pid
<add> @pid = Process.pid
<add> @boot_mutex = Mutex.new
<ide>
<ide> if (@dtw = directories_to_watch).any?
<ide> # Loading listen triggers warnings. These are originated by a legit
<ide> def initialize(files, dirs = {}, &block)
<ide> end
<ide>
<ide> def updated?
<del> boot! unless @pid_hash[Process.pid]
<add> @boot_mutex.synchronize do
<add> if @pid != Process.pid
<add> boot!
<add> @pid = Process.pid
<add> @updated.make_true
<add> end
<add> end
<ide> @updated.true?
<ide> end
<ide>
<ide> def execute_if_updated
<ide> private
<ide> def boot!
<ide> Listen.to(*@dtw, &method(:changed)).start
<del> @pid_hash[Process.pid] = true
<del> @updated.make_true if @parent_pid != Process.pid
<ide> end
<ide>
<ide> def changed(modified, added, removed)
| 1
|
Ruby
|
Ruby
|
incorporate suggestions from code review
|
2a941ec6b17bcb0d9557cf3604d64a3954cc199e
|
<ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit
<ide> # Run tap audits first
<ide> if args.tap
<ide> tap = Tap.fetch(args.tap)
<del> ta = TapAuditor.new(tap, options)
<add> ta = TapAuditor.new(tap, strict: args.strict?)
<ide> ta.audit
<ide>
<ide> if ta.problems.any?
<ide> def problem(text)
<ide> class TapAuditor
<ide> attr_reader :name, :path, :tap_audit_exceptions, :problems
<ide>
<del> def initialize(tap, options = {})
<add> def initialize(tap, strict:)
<ide> @name = tap.name
<ide> @path = tap.path
<ide> @tap_audit_exceptions = tap.audit_exceptions
<del> @strict = options[:strict]
<add> @strict = strict
<ide> @problems = []
<ide> end
<ide>
<ide> def audit
<ide> audit_json_files
<ide> audit_tap_audit_exceptions
<del> self
<ide> end
<ide>
<ide> def audit_json_files
<del> Dir[@path/"**/*.json"].each do |file|
<del> JSON.parse Pathname.new(file).read
<add> Pathname.glob(@path/"**/*.json").each do |file|
<add> JSON.parse file.read
<ide> rescue JSON::ParserError
<del> problem "#{file.delete_prefix("#{@path}/")} contains invalid JSON"
<add> problem "#{file.to_s.delete_prefix("#{@path}/")} contains invalid JSON"
<ide> end
<ide> end
<ide>
<ide> def audit_tap_audit_exceptions
<ide>
<ide> invalid_formulae = []
<ide> formula_names.each do |name|
<del> invalid_formulae.push name if Formulary.factory(name).tap != @name
<add> invalid_formulae << name if Formula[name].tap != @name
<ide> rescue FormulaUnavailableError
<del> invalid_formulae.push name
<add> invalid_formulae << name
<ide> end
<ide>
<ide> next if invalid_formulae.empty?
<ide>
<ide> problem <<~EOS
<ide> audit_exceptions/#{list_name}.json references
<del> formulae that were are found in the #{@name} tap.
<add> formulae that are not found in the #{@name} tap.
<ide> Invalid formulae: #{invalid_formulae.join(", ")}
<ide> EOS
<ide> end
<ide><path>Library/Homebrew/tap.rb
<ide> def tap_migrations
<ide> def audit_exceptions
<ide> @audit_exceptions = {}
<ide>
<del> Dir[path/"audit_exceptions/*"].each do |exception_file|
<del> list_name = File.basename(exception_file).chomp(".json").to_sym
<add> Pathname.glob(path/"audit_exceptions/*").each do |exception_file|
<add> list_name = exception_file.basename.to_s.chomp(".json").to_sym
<ide> list_contents = begin
<del> JSON.parse Pathname.new(exception_file).read
<add> JSON.parse exception_file.read
<ide> rescue JSON::ParserError
<del> nil
<add> opoo "#{exception_file} contains invalid JSON"
<ide> end
<ide>
<ide> next if list_contents.nil?
| 2
|
Ruby
|
Ruby
|
make arel methods private api
|
cd93d7175e3f92c77744110204dc9194a3aa592c
|
<ide><path>activerecord/lib/active_record/core.rb
<ide> def ===(object)
<ide> # class Post < ActiveRecord::Base
<ide> # scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
<ide> # end
<del> def arel_table
<add> def arel_table # :nodoc:
<ide> @arel_table ||= Arel::Table.new(table_name, arel_engine)
<ide> end
<ide>
<ide> # Returns the Arel engine.
<del> def arel_engine
<add> def arel_engine # :nodoc:
<ide> @arel_engine ||=
<ide> if Base == self || connection_handler.retrieve_connection_pool(self)
<ide> self
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def reverse_order! # :nodoc:
<ide> end
<ide>
<ide> # Returns the Arel object associated with the relation.
<del> def arel
<add> def arel # :nodoc:
<ide> @arel ||= build_arel
<ide> end
<ide>
<del> # Like #arel, but ignores the default scope of the model.
<add> private
<add>
<ide> def build_arel
<ide> arel = Arel::SelectManager.new(table.engine, table)
<ide>
<ide> def build_arel
<ide> arel
<ide> end
<ide>
<del> private
<del>
<ide> def symbol_unscoping(scope)
<ide> if !VALID_UNSCOPING_VALUES.include?(scope)
<ide> raise ArgumentError, "Called unscope() with invalid unscoping argument ':#{scope}'. Valid arguments are :#{VALID_UNSCOPING_VALUES.to_a.join(", :")}."
| 2
|
Javascript
|
Javascript
|
add docs for ngpattern, ngminlength, ngmaxlength
|
8863836cd4b82c8f0f9d72de4323aace28402c38
|
<ide><path>src/ng/directive/validators.js
<ide> var requiredDirective = function() {
<ide> };
<ide> };
<ide>
<add>/**
<add> * @ngdoc directive
<add> * @name ngPattern
<add> *
<add> * @description
<add> *
<add> * ngPattern adds the pattern {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<add> * It is most often used for text-based [@link input `input`} controls, but can also be applied to custom text-based controls.
<add> *
<add> * The validator sets the `pattern` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<add> * does not match a RegExp which is obtained by evaluating the Angular expression given in the
<add> * `ngPattern` attribute value:
<add> * * If the expression evaluates to a RegExp object, then this is used directly.
<add> * * If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it
<add> * in `^` and `$` characters. For instance, `"abc"` will be converted to `new RegExp('^abc$')`.
<add> *
<add> * <div class="alert alert-info">
<add> * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
<add> * start at the index of the last search's match, thus not taking the whole input value into
<add> * account.
<add> * </div>
<add> *
<add> * <div class="alert alert-info">
<add> * **Note:** This directive is also added when the plain `pattern` attribute is used, with two
<add> * differences:
<add> * 1. `ngPattern` does not set the `pattern` attribute and therefore not HTML5 constraint validation
<add> * is available.
<add> * 2. The `ngPattern` attribute must be an expression, while the `pattern` value must be interpolated
<add> * </div>
<add> *
<add> * @example
<add> * <example name="ngPatternDirective" module="ngPatternExample">
<add> * <file name="index.html">
<add> * <script>
<add> * angular.module('ngPatternExample', [])
<add> * .controller('ExampleController', ['$scope', function($scope) {
<add> * $scope.regex = '\\d+';
<add> * }]);
<add> * </script>
<add> * <div ng-controller="ExampleController">
<add> * <form name="form">
<add> * <label for="regex">Set a pattern (regex string): </label>
<add> * <input type="text" ng-model="regex" id="regex" />
<add> * <br>
<add> * <label for="input">This input is restricted by the current pattern: </label>
<add> * <input type="text" ng-model="model" id="input" name="input" ng-pattern="regex" /><br>
<add> * <hr>
<add> * input valid? = <code>{{form.input.$valid}}</code><br>
<add> * model = <code>{{model}}</code>
<add> * </form>
<add> * </div>
<add> * </file>
<add> * <file name="protractor.js" type="protractor">
<add> var model = element(by.binding('model'));
<add> var input = element(by.id('input'));
<ide>
<add> it('should validate the input with the default pattern', function() {
<add> input.sendKeys('aaa');
<add> expect(model.getText()).not.toContain('aaa');
<add>
<add> input.clear().then(function() {
<add> input.sendKeys('123');
<add> expect(model.getText()).toContain('123');
<add> });
<add> });
<add> * </file>
<add> * </example>
<add> */
<ide> var patternDirective = function() {
<ide> return {
<ide> restrict: 'A',
<ide> var patternDirective = function() {
<ide> };
<ide> };
<ide>
<add>/**
<add> * @ngdoc directive
<add> * @name ngMaxlength
<add> *
<add> * @description
<add> *
<add> * ngMaxlength adds the maxlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<add> * It is most often used for text-based [@link input `input`} controls, but can also be applied to custom text-based controls.
<add> *
<add> * The validator sets the `maxlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<add> * is longer than the integer obtained by evaluating the Angular expression given in the
<add> * `ngMaxlength` attribute value.
<add> *
<add> * <div class="alert alert-info">
<add> * **Note:** This directive is also added when the plain `maxlength` attribute is used, with two
<add> * differences:
<add> * 1. `ngMaxlength` does not set the `maxlength` attribute and therefore not HTML5 constraint validation
<add> * is available.
<add> * 2. The `ngMaxlength` attribute must be an expression, while the `maxlength` value must be interpolated
<add> * </div>
<add> *
<add> * @example
<add> * <example name="ngMaxlengthDirective" module="ngMaxlengthExample">
<add> * <file name="index.html">
<add> * <script>
<add> * angular.module('ngMaxlengthExample', [])
<add> * .controller('ExampleController', ['$scope', function($scope) {
<add> * $scope.maxlength = 5;
<add> * }]);
<add> * </script>
<add> * <div ng-controller="ExampleController">
<add> * <form name="form">
<add> * <label for="maxlength">Set a maxlength: </label>
<add> * <input type="number" ng-model="maxlength" id="maxlength" />
<add> * <br>
<add> * <label for="input">This input is restricted by the current maxlength: </label>
<add> * <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br>
<add> * <hr>
<add> * input valid? = <code>{{form.input.$valid}}</code><br>
<add> * model = <code>{{model}}</code>
<add> * </form>
<add> * </div>
<add> * </file>
<add> * <file name="protractor.js" type="protractor">
<add> * var model = element(by.binding('model'));
<add> var input = element(by.id('input'));
<add>
<add> it('should validate the input with the default maxlength', function() {
<add> input.sendKeys('abcdef');
<add> expect(model.getText()).not.toContain('abcdef');
<ide>
<add> input.clear().then(function() {
<add> input.sendKeys('abcde');
<add> expect(model.getText()).toContain('abcde');
<add> });
<add> });
<add> * </file>
<add> * </example>
<add> */
<ide> var maxlengthDirective = function() {
<ide> return {
<ide> restrict: 'A',
<ide> var maxlengthDirective = function() {
<ide> };
<ide> };
<ide>
<add>/**
<add> * @ngdoc directive
<add> * @name ngMinlength
<add> *
<add> * @description
<add> *
<add> * ngMinlength adds the minlength {@link ngModel.NgModelController#$validators `validator`} to {@link ngModel `ngModel`}.
<add> * It is most often used for text-based [@link input `input`} controls, but can also be applied to custom text-based controls.
<add> *
<add> * The validator sets the `minlength` error key if the {@link ngModel.NgModelController#$viewValue `ngModel.$viewValue`}
<add> * is shorter than the integer obtained by evaluating the Angular expression given in the
<add> * `ngMinlength` attribute value.
<add> *
<add> * <div class="alert alert-info">
<add> * **Note:** This directive is also added when the plain `minlength` attribute is used, with two
<add> * differences:
<add> * 1. `ngMinlength` does not set the `minlength` attribute and therefore not HTML5 constraint validation
<add> * is available.
<add> * 2. The `ngMinlength` value must be an expression, while the `minlength` value must be interpolated
<add> * </div>
<add> *
<add> * @example
<add> * <example name="ngMinlengthDirective" module="ngMinlengthExample">
<add> * <file name="index.html">
<add> * <script>
<add> * angular.module('ngMinlengthExample', [])
<add> * .controller('ExampleController', ['$scope', function($scope) {
<add> * $scope.minlength = 3;
<add> * }]);
<add> * </script>
<add> * <div ng-controller="ExampleController">
<add> * <form name="form">
<add> * <label for="minlength">Set a minlength: </label>
<add> * <input type="number" ng-model="minlength" id="minlength" />
<add> * <br>
<add> * <label for="input">This input is restricted by the current minlength: </label>
<add> * <input type="text" ng-model="model" id="input" name="input" ng-minlength="minlength" /><br>
<add> * <hr>
<add> * input valid? = <code>{{form.input.$valid}}</code><br>
<add> * model = <code>{{model}}</code>
<add> * </form>
<add> * </div>
<add> * </file>
<add> * <file name="protractor.js" type="protractor">
<add> * var model = element(by.binding('model'));
<add> *
<add> * it('should validate the input with the default minlength', function() {
<add> * element(by.id('input')).sendKeys('ab');
<add> * expect(model.getText()).not.toContain('ab');
<add> *
<add> * element(by.id('input')).sendKeys('abc');
<add> * expect(model.getText()).toContain('abc');
<add> * });
<add> * </file>
<add> * </example>
<add> */
<ide> var minlengthDirective = function() {
<ide> return {
<ide> restrict: 'A',
| 1
|
Python
|
Python
|
fix a typo in doc comment about reset_after
|
f717f8cf0978b5e2fa3560870681e49dda248ef3
|
<ide><path>keras/layers/recurrent_v2.py
<ide> class GRU(recurrent.DropoutRNNCellMixin, recurrent.GRU):
<ide>
<ide> The second variant is compatible with CuDNNGRU (GPU-only) and allows
<ide> inference on CPU. Thus it has separate biases for `kernel` and
<del> `recurrent_kernel`. To use this variant, set `'reset_after'=True` and
<add> `recurrent_kernel`. To use this variant, set `reset_after=True` and
<ide> `recurrent_activation='sigmoid'`.
<ide>
<ide> For example:
| 1
|
Go
|
Go
|
update recommended kernel in checkkernel
|
ceae5f54b3abe805b3323476dafb00595b064ed2
|
<ide><path>daemon/daemon.go
<ide> func checkKernel() error {
<ide> // test for specific functionalities.
<ide> // Unfortunately we can't test for the feature "does not cause a kernel panic"
<ide> // without actually causing a kernel panic, so we need this workaround until
<del> // the circumstances of pre-3.8 crashes are clearer.
<add> // the circumstances of pre-3.10 crashes are clearer.
<ide> // For details see https://github.com/docker/docker/issues/407
<ide> if k, err := kernel.GetKernelVersion(); err != nil {
<ide> logrus.Warnf("%s", err)
<ide> } else {
<del> if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0}) < 0 {
<add> if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 10, Minor: 0}) < 0 {
<ide> if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
<del> logrus.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.8.0.", k.String())
<add> logrus.Warnf("You are running linux kernel version %s, which might be unstable running docker. Please upgrade your kernel to 3.10.0.", k.String())
<ide> }
<ide> }
<ide> }
| 1
|
Go
|
Go
|
restore volume refs after daemon restart
|
9acf7c765c7e074f6c75eaf162ca06ecfe40d692
|
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) restore() error {
<ide> }
<ide>
<ide> for _, c := range registeredContainers {
<del> for _, mnt := range c.VolumeMounts() {
<del> daemon.volumes.Add(mnt.volume)
<del> }
<add> c.registerVolumes()
<ide> }
<ide>
<ide> if !debug {
<ide><path>daemon/volumes.go
<ide> func (container *Container) VolumePaths() map[string]struct{} {
<ide> return paths
<ide> }
<ide>
<add>func (container *Container) registerVolumes() {
<add> for _, mnt := range container.VolumeMounts() {
<add> mnt.volume.AddContainer(container.ID)
<add> }
<add>}
<add>
<ide> func (container *Container) derefVolumes() {
<ide> for path := range container.VolumePaths() {
<ide> vol := container.daemon.volumes.Get(path)
<ide><path>integration-cli/docker_cli_daemon_test.go
<ide> package main
<ide>
<ide> import (
<add> "encoding/json"
<add> "os"
<ide> "strings"
<ide> "testing"
<ide> )
<ide> func TestDaemonRestartWithRunningContainersPorts(t *testing.T) {
<ide>
<ide> logDone("daemon - running containers on daemon restart")
<ide> }
<add>
<add>func TestDaemonRestartWithVolumesRefs(t *testing.T) {
<add> d := NewDaemon(t)
<add> if err := d.StartWithBusybox(); err != nil {
<add> t.Fatal(err)
<add> }
<add> defer d.Stop()
<add>
<add> if out, err := d.Cmd("run", "-d", "--name", "volrestarttest1", "-v", "/foo", "busybox"); err != nil {
<add> t.Fatal(err, out)
<add> }
<add> if err := d.Restart(); err != nil {
<add> t.Fatal(err)
<add> }
<add> if _, err := d.Cmd("run", "-d", "--volumes-from", "volrestarttest1", "--name", "volrestarttest2", "busybox"); err != nil {
<add> t.Fatal(err)
<add> }
<add> if out, err := d.Cmd("rm", "-fv", "volrestarttest2"); err != nil {
<add> t.Fatal(err, out)
<add> }
<add> v, err := d.Cmd("inspect", "--format", "{{ json .Volumes }}", "volrestarttest1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> volumes := make(map[string]string)
<add> json.Unmarshal([]byte(v), &volumes)
<add> if _, err := os.Stat(volumes["/foo"]); err != nil {
<add> t.Fatalf("Expected volume to exist: %s - %s", volumes["/foo"], err)
<add> }
<add>
<add> logDone("daemon - volume refs are restored")
<add>}
<ide><path>volumes/repository.go
<ide> import (
<ide> "sync"
<ide>
<ide> "github.com/docker/docker/daemon/graphdriver"
<add> "github.com/docker/docker/pkg/log"
<ide> "github.com/docker/docker/utils"
<ide> )
<ide>
<ide> func (r *Repository) restore() error {
<ide> return err
<ide> }
<ide>
<del> var ids []string
<ide> for _, v := range dir {
<ide> id := v.Name()
<del> if r.driver.Exists(id) {
<del> ids = append(ids, id)
<add> path, err := r.driver.Get(id, "")
<add> if err != nil {
<add> log.Debugf("Could not find volume for %s: %v", id, err)
<add> continue
<add> }
<add> vol := &Volume{
<add> ID: id,
<add> configPath: r.configPath + "/" + id,
<add> containers: make(map[string]struct{}),
<add> Path: path,
<add> }
<add> if err := vol.FromDisk(); err != nil {
<add> if !os.IsNotExist(err) {
<add> log.Debugf("Error restoring volume: %v", err)
<add> continue
<add> }
<add> if err := vol.initialize(); err != nil {
<add> log.Debugf("%s", err)
<add> continue
<add> }
<add> }
<add> if err := r.add(vol); err != nil {
<add> log.Debugf("Error restoring volume: %v", err)
<ide> }
<ide> }
<ide> return nil
<ide> func (r *Repository) createNewVolumePath(id string) (string, error) {
<ide>
<ide> path, err := r.driver.Get(id, "")
<ide> if err != nil {
<del> return "", fmt.Errorf("Driver %s failed to get volume rootfs %s: %s", r.driver, id, err)
<add> return "", fmt.Errorf("Driver %s failed to get volume rootfs %s: %v", r.driver, id, err)
<ide> }
<ide>
<ide> return path, nil
| 4
|
Javascript
|
Javascript
|
prevent browser console errors during testing
|
e416032b3845d337ebe4f2819ab44ca044afd159
|
<ide><path>src/display/font_loader.js
<ide> FontLoader.prototype = {
<ide> clear: function fontLoaderClear() {
<ide> var styleElement = this.styleElement;
<ide> if (styleElement) {
<del> styleElement.parentNode.removeChild(styleElement);
<add> if (styleElement.parentNode) {
<add> // Prevent "TypeError: styleElement.parentNode is null" during testing.
<add> styleElement.parentNode.removeChild(styleElement);
<add> }
<ide> styleElement = this.styleElement = null;
<ide> }
<ide> if (typeof PDFJSDev === 'undefined' || !PDFJSDev.test('MOZCENTRAL')) {
<ide><path>test/driver.js
<ide> var rasterizeAnnotationLayer = (function rasterizeAnnotationLayerClosure() {
<ide> /**
<ide> * @class
<ide> */
<del>var Driver = (function DriverClosure() {
<add>var Driver = (function DriverClosure() { // eslint-disable-line no-unused-vars
<ide> /**
<ide> * @constructs Driver
<ide> * @param {DriverOptions} options
<ide> var Driver = (function DriverClosure() {
<ide>
<ide> return Driver;
<ide> })();
<del>
<del>exports.Driver = Driver;
<ide><path>test/font/fontutils.js
<ide> var base64alphabet =
<ide> 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
<ide>
<del>function decodeFontData(base64) {
<add>function decodeFontData(base64) { // eslint-disable-line no-unused-vars
<ide> var result = [];
<ide>
<ide> var bits = 0, bitsLength = 0;
<ide> function encodeFontData(data) {
<ide> return buffer;
<ide> }
<ide>
<del>function ttx(data, callback) {
<add>function ttx(data, callback) { // eslint-disable-line no-unused-vars
<ide> var xhr = new XMLHttpRequest();
<ide> xhr.open('POST', '/ttx');
<ide>
<ide> function ttx(data, callback) {
<ide> xhr.send(encodedData);
<ide> }
<ide>
<del>function verifyTtxOutput(output) {
<add>function verifyTtxOutput(output) { // eslint-disable-line no-unused-vars
<ide> var m = /^<error>(.*?)<\/error>/.exec(output);
<ide> if (m) {
<ide> throw m[1];
<ide> }
<ide> }
<del>
<del>exports.decodeFontData = decodeFontData;
<del>exports.ttx = ttx;
<del>exports.verifyTtxOutput = verifyTtxOutput;
<ide><path>test/unit/testreporter.js
<ide> 'use strict';
<ide>
<add>// eslint-disable-next-line no-unused-vars
<ide> var TestReporter = function(browser, appPath) {
<ide> function send(action, json, cb) {
<ide> var r = new XMLHttpRequest();
<ide> var TestReporter = function(browser, appPath) {
<ide> setTimeout(sendQuitRequest, 500);
<ide> };
<ide> };
<del>
<del>exports.TestReporter = TestReporter;
| 4
|
Ruby
|
Ruby
|
document the return value of update_all [ci skip]
|
b488d8e08950685ae978b118af813516ce71fecc
|
<ide><path>activerecord/lib/active_record/relation.rb
<ide> def _exec_scope(name, *args, &block) # :nodoc:
<ide> # Updates all records in the current relation with details given. This method constructs a single SQL UPDATE
<ide> # statement and sends it straight to the database. It does not instantiate the involved models and it does not
<ide> # trigger Active Record callbacks or validations. However, values passed to #update_all will still go through
<del> # Active Record's normal type casting and serialization.
<add> # Active Record's normal type casting and serialization. Returns the number of rows affected.
<ide> #
<ide> # Note: As Active Record callbacks are not triggered, this method will not automatically update +updated_at+/+updated_on+ columns.
<ide> #
| 1
|
Python
|
Python
|
rewrite cli errors
|
5436dddf64f0103088c4ca212f16efa40c88766a
|
<ide><path>flask/cli.py
<ide> def find_best_app(script_info, module):
<ide> # Search for the most common names first.
<ide> for attr_name in ('app', 'application'):
<ide> app = getattr(module, attr_name, None)
<add>
<ide> if isinstance(app, Flask):
<ide> return app
<ide>
<ide> def find_best_app(script_info, module):
<ide> return matches[0]
<ide> elif len(matches) > 1:
<ide> raise NoAppException(
<del> 'Auto-detected multiple Flask applications in module "{module}".'
<del> ' Use "FLASK_APP={module}:name" to specify the correct'
<del> ' one.'.format(module=module.__name__)
<add> 'Detected multiple Flask applications in module "{module}". Use '
<add> '"FLASK_APP={module}:name" to specify the correct '
<add> 'one.'.format(module=module.__name__)
<ide> )
<ide>
<ide> # Search for app factory functions.
<ide> def find_best_app(script_info, module):
<ide>
<ide> if inspect.isfunction(app_factory):
<ide> try:
<del> app = call_factory(app_factory, script_info)
<add> app = call_factory(script_info, app_factory)
<add>
<ide> if isinstance(app, Flask):
<ide> return app
<ide> except TypeError:
<ide> raise NoAppException(
<del> 'Auto-detected "{function}()" in module "{module}", but '
<del> 'could not call it without specifying arguments.'.format(
<del> function=attr_name, module=module.__name__
<add> 'Detected factory "{factory}" in module "{module}", but '
<add> 'could not call it without arguments. Use '
<add> '"FLASK_APP=\'{module}:{factory}(args)\'" to specify '
<add> 'arguments.'.format(
<add> factory=attr_name, module=module.__name__
<ide> )
<ide> )
<ide>
<ide> raise NoAppException(
<del> 'Failed to find application in module "{module}". Are you sure '
<del> 'it contains a Flask application? Maybe you wrapped it in a WSGI '
<del> 'middleware.'.format(module=module.__name__)
<add> 'Failed to find Flask application or factory in module "{module}". '
<add> 'Use "FLASK_APP={module}:name to specify one.'.format(
<add> module=module.__name__
<add> )
<ide> )
<ide>
<ide>
<del>def call_factory(app_factory, script_info, arguments=()):
<add>def call_factory(script_info, app_factory, arguments=()):
<ide> """Takes an app factory, a ``script_info` object and optionally a tuple
<ide> of arguments. Checks for the existence of a script_info argument and calls
<ide> the app_factory depending on that and the arguments provided.
<ide> def call_factory(app_factory, script_info, arguments=()):
<ide> return app_factory(*arguments)
<ide> elif not arguments and len(arg_names) == 1 and arg_defaults is None:
<ide> return app_factory(script_info)
<add>
<ide> return app_factory()
<ide>
<ide>
<del>def find_app_by_string(string, script_info, module):
<del> """Checks if the given string is a variable name or a function. If it is
<del> a function, it checks for specified arguments and whether it takes
<del> a ``script_info`` argument and calls the function with the appropriate
<del> arguments."""
<del> from . import Flask
<del> function_regex = r'^(?P<name>\w+)(?:\((?P<args>.*)\))?$'
<del> match = re.match(function_regex, string)
<del> if match:
<del> name, args = match.groups()
<add>def find_app_by_string(script_info, module, app_name):
<add> """Checks if the given string is a variable name or a function. If it is a
<add> function, it checks for specified arguments and whether it takes a
<add> ``script_info`` argument and calls the function with the appropriate
<add> arguments.
<add> """
<add> from flask import Flask
<add> match = re.match(r'^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$', app_name)
<add>
<add> if not match:
<add> raise NoAppException(
<add> '"{name}" is not a valid variable name or function '
<add> 'expression.'.format(name=app_name)
<add> )
<add>
<add> name, args = match.groups()
<add>
<add> try:
<add> attr = getattr(module, name)
<add> except AttributeError as e:
<add> raise NoAppException(e.args[0])
<add>
<add> if inspect.isfunction(attr):
<add> if args:
<add> try:
<add> args = ast.literal_eval('({args},)'.format(args=args))
<add> except (ValueError, SyntaxError)as e:
<add> raise NoAppException(
<add> 'Could not parse the arguments in '
<add> '"{app_name}".'.format(e=e, app_name=app_name)
<add> )
<add> else:
<add> args = ()
<add>
<ide> try:
<del> if args is not None:
<del> args = args.rstrip(' ,')
<del> if args:
<del> args = ast.literal_eval(
<del> "({args}, )".format(args=args))
<del> else:
<del> args = ()
<del> app_factory = getattr(module, name, None)
<del> app = call_factory(app_factory, script_info, args)
<del> else:
<del> attr = getattr(module, name, None)
<del> if inspect.isfunction(attr):
<del> app = call_factory(attr, script_info)
<del> else:
<del> app = attr
<del>
<del> if isinstance(app, Flask):
<del> return app
<del> else:
<del> raise NoAppException('Failed to find application in module '
<del> '"{name}"'.format(name=module))
<add> app = call_factory(script_info, attr, args)
<ide> except TypeError as e:
<del> new_error = NoAppException(
<del> '{e}\nThe app factory "{factory}" in module "{module}" could'
<del> ' not be called with the specified arguments (and a'
<del> ' script_info argument automatically added if applicable).'
<del> ' Did you make sure to use the right number of arguments as'
<del> ' well as not using keyword arguments or'
<del> ' non-literals?'.format(e=e, factory=string, module=module))
<del> reraise(NoAppException, new_error, sys.exc_info()[2])
<add> raise NoAppException(
<add> '{e}\nThe factory "{app_name}" in module "{module}" could not '
<add> 'be called with the specified arguments.'.format(
<add> e=e, app_name=app_name, module=module.__name__
<add> )
<add> )
<ide> else:
<del> raise NoAppException(
<del> 'The provided string "{string}" is not a valid variable name'
<del> 'or function expression.'.format(string=string))
<add> app = attr
<add>
<add> if isinstance(app, Flask):
<add> return app
<add>
<add> raise NoAppException(
<add> 'A valid Flask application was not obtained from '
<add> '"{module}:{app_name}".'.format(
<add> module=module.__name__, app_name=app_name
<add> )
<add> )
<ide>
<ide>
<ide> def prepare_import(path):
<ide> def prepare_import(path):
<ide>
<ide>
<ide> def locate_app(script_info, module_name, app_name, raise_if_not_found=True):
<del> """Attempts to locate the application."""
<ide> __traceback_hide__ = True
<ide>
<ide> try:
<ide> def locate_app(script_info, module_name, app_name, raise_if_not_found=True):
<ide> if app_name is None:
<ide> return find_best_app(script_info, module)
<ide> else:
<del> return find_app_by_string(app_name, script_info, module)
<add> return find_app_by_string(script_info, module, app_name)
<ide>
<ide>
<ide> def get_version(ctx, param, value):
<ide> def load_app(self):
<ide> app = None
<ide>
<ide> if self.create_app is not None:
<del> app = call_factory(self.create_app, self)
<add> app = call_factory(self, self.create_app)
<ide> else:
<ide> if self.app_import_path:
<ide> path, name = (self.app_import_path.split(':', 1) + [None])[:2]
<ide><path>tests/test_apps/cliapp/factory.py
<ide> def create_app2(foo, bar):
<ide>
<ide> def create_app3(foo, script_info):
<ide> return Flask('_'.join(['app3', foo, script_info.data['test']]))
<add>
<add>
<add>def no_app():
<add> pass
<ide><path>tests/test_cli.py
<ide> def reset_path():
<ide> ('cliapp.factory', 'create_app2("foo", "bar", )', 'app2_foo_bar'),
<ide> # takes script_info
<ide> ('cliapp.factory', 'create_app3("foo")', 'app3_foo_spam'),
<add> # strip whitespace
<add> ('cliapp.factory', ' create_app () ', 'app'),
<ide> ))
<ide> def test_locate_app(test_apps, iname, aname, result):
<ide> info = ScriptInfo()
<ide> def test_locate_app(test_apps, iname, aname, result):
<ide> ('cliapp.app', 'notanapp'),
<ide> # not enough arguments
<ide> ('cliapp.factory', 'create_app2("foo")'),
<add> # invalid identifier
<add> ('cliapp.factory', 'create_app('),
<add> # no app returned
<add> ('cliapp.factory', 'no_app'),
<ide> # nested import error
<ide> ('cliapp.importerrorapp', None),
<ide> # not a Python file
<ide> ('cliapp.message.txt', None),
<del> # space before arg list
<del> ('cliapp.factory', 'create_app ()'),
<ide> ))
<ide> def test_locate_app_raises(test_apps, iname, aname):
<ide> info = ScriptInfo()
| 3
|
PHP
|
PHP
|
fix tests for previous commit
|
eb4c229522ae69000dd4b89b9f4feaec3c68ec5a
|
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> public function testInvokeScopedMiddleware()
<ide> 'REQUEST_METHOD' => 'GET',
<ide> 'REQUEST_URI' => '/api/ping',
<ide> ]);
<del> $handler = new TestRequestHandler();
<del> $middleware = new RoutingMiddleware($this->app(function ($req) {
<add> $app = $this->app(function ($req) {
<ide> $this->log[] = 'last';
<ide>
<ide> return new Response();
<del> }));
<del> $result = $middleware->process($request, $handler);
<add> });
<add> $middleware = new RoutingMiddleware($app);
<add> $result = $middleware->process($request, $app);
<ide> $this->assertSame(['second', 'first', 'last'], $this->log);
<ide> }
<ide>
<ide> public function testInvokeScopedMiddlewareIsolatedScopes($url, $expected)
<ide> 'REQUEST_METHOD' => 'GET',
<ide> 'REQUEST_URI' => $url,
<ide> ]);
<del> $handler = new TestRequestHandler();
<del> $middleware = new RoutingMiddleware($this->app(function ($req) {
<add> $app = $this->app(function ($req) {
<ide> $this->log[] = 'last';
<ide>
<ide> return new Response();
<del> }));
<del> $result = $middleware->process($request, $handler);
<add> });
<add> $middleware = new RoutingMiddleware($app);
<add> $result = $middleware->process($request, $app);
<ide> $this->assertSame($expected, $this->log);
<ide> }
<ide>
| 1
|
Go
|
Go
|
allow maximum possible vni
|
a95260646a160a38f276ae357031e434e7b7e2c9
|
<ide><path>libnetwork/drivers/overlay/overlay.go
<ide> const (
<ide> vethPrefix = "veth"
<ide> vethLen = 7
<ide> vxlanIDStart = 256
<del> vxlanIDEnd = 1000
<add> vxlanIDEnd = (1 << 24) - 1
<ide> vxlanPort = 4789
<ide> vxlanVethMTU = 1450
<ide> )
| 1
|
Javascript
|
Javascript
|
implement helper methods in ember.view
|
411321a81346b2d15ecfb110510a0bd9dd68108b
|
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> // Variable in which the old class value is saved. The observer function
<ide> // closes over this variable, so it knows which string to remove when
<ide> // the property changes.
<del> var oldClass, property;
<add> var oldClass;
<ide>
<ide> // Set up an observer on the context. If the property changes, toggle the
<ide> // class name.
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> }
<ide>
<ide> // Extract just the property name from bindings like 'foo:bar'
<del> property = binding.split(':')[0];
<del> addObserver(this, property, observer);
<add> var parsedPath = Ember.View._parsePropertyPath(binding);
<add> addObserver(this, parsedPath.path, observer);
<ide> }, this);
<ide> },
<ide>
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> passing `isUrgent` to this method will return `"is-urgent"`.
<ide> */
<ide> _classStringForProperty: function(property) {
<del> var split = property.split(':'),
<del> className = split[1];
<del>
<del> property = split[0];
<del>
<del> // TODO: Remove this `false` when the `getPath` globals support is removed
<del> var val = Ember.getPath(this, property, false);
<del> if (val === undefined && Ember.isGlobalPath(property)) {
<del> val = Ember.getPath(window, property);
<del> }
<del>
<del> // If the value is truthy and we're using the colon syntax,
<del> // we should return the className directly
<del> if (!!val && className) {
<del> return className;
<del>
<del> // If value is a Boolean and true, return the dasherized property
<del> // name.
<del> } else if (val === true) {
<del> // Normalize property path to be suitable for use
<del> // as a class name. For exaple, content.foo.barBaz
<del> // becomes bar-baz.
<del> var parts = property.split('.');
<del> return Ember.String.dasherize(parts[parts.length-1]);
<del>
<del> // If the value is not false, undefined, or null, return the current
<del> // value of the property.
<del> } else if (val !== false && val !== undefined && val !== null) {
<del> return val;
<del>
<del> // Nothing to display. Return null so that the old class is removed
<del> // but no new class is added.
<del> } else {
<del> return null;
<del> }
<add> var parsedPath = Ember.View._parsePropertyPath(property);
<add> return Ember.View._classStringForPath(this, parsedPath.path, parsedPath.className, parsedPath.falsyClassName);
<ide> },
<ide>
<ide> // ..........................................................
<ide> Ember.View.reopen({
<ide> domManager: DOMManager
<ide> });
<ide>
<add>Ember.View.reopenClass({
<add> _parsePropertyPath: function(path) {
<add> var split = path.split(/\?|:/),
<add> propertyPath = split[0],
<add> className,
<add> falsyClassName;
<add>
<add> // check if the property is defined as prop?trueClass:falseClass
<add> if (split.length > 1) {
<add> className = split[1];
<add> if (split.length === 3) { falsyClassName = split[2]; }
<add> }
<add>
<add> var classNames = "";
<add> if (className) {
<add> if (falsyClassName) {
<add> classNames = '?' + className + ':' + falsyClassName;
<add> } else {
<add> classNames = ':' + className;
<add> }
<add> }
<add>
<add> return {
<add> path: propertyPath,
<add> classNames: classNames,
<add> className: className,
<add> falsyClassName: falsyClassName
<add> };
<add> },
<add>
<add> _classStringForValue: function(path, val, className, falsyClassName) {
<add> // If the value is truthy and we're using the colon syntax,
<add> // we should return the className directly
<add> if (!!val && className) {
<add> return className;
<add>
<add> // If value is a Boolean and true, return the dasherized property
<add> // name.
<add> } else if (val === true) {
<add> // Normalize property path to be suitable for use
<add> // as a class name. For exaple, content.foo.barBaz
<add> // becomes bar-baz.
<add> var parts = path.split('.');
<add> return Ember.String.dasherize(parts[parts.length-1]);
<add>
<add> // If the value is false and a falsyClassName is specified, return it
<add> } else if (val === false && falsyClassName) {
<add> return falsyClassName;
<add>
<add> // If the value is not false, undefined, or null, return the current
<add> // value of the property.
<add> } else if (val !== false && val !== undefined && val !== null) {
<add> return val;
<add>
<add> // Nothing to display. Return null so that the old class is removed
<add> // but no new class is added.
<add> } else {
<add> return null;
<add> }
<add> },
<add>
<add> _classStringForPath: function(root, path, className, falsyClassName, options) {
<add> // TODO: Remove this `false` when the `getPath` globals support is removed
<add> var val = getPath(root, path, options);
<add> if (val === undefined && Ember.isGlobalPath(path)) {
<add> val = getPath(window, path);
<add> }
<add>
<add> return Ember.View._classStringForValue(path, val, className, falsyClassName);
<add> }
<add>});
<add>
<ide> // Create a global view hash.
<ide> Ember.View.views = {};
<ide>
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.