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
Ruby
Ruby
restrict new tap names
f94a38e4b1c0276557a2e2807554bd729ded6864
<ide><path>Library/Homebrew/dev-cmd/tap-new.rb <ide> def tap_new_args <ide> def tap_new <ide> tap_new_args.parse <ide> <add> tap_name = args.named.first <ide> tap = Tap.fetch(args.named.first) <add> raise "Invalid tap name '#{tap_name}'" unless tap.path.to_s.match?(HOMEBREW_TAP_PATH_REGEX) <add> <ide> titleized_user = tap.user.dup <ide> titleized_repo = tap.repo.dup <ide> titleized_user[0] = titleized_user[0].upcase <ide><path>Library/Homebrew/tap.rb <ide> def self.fetch(*args) <ide> return CoreTap.instance if ["Homebrew", "Linuxbrew"].include?(user) && ["core", "homebrew"].include?(repo) <ide> <ide> cache_key = "#{user}/#{repo}".downcase <del> tap = cache.fetch(cache_key) { |key| cache[key] = Tap.new(user, repo) } <del> raise "Invalid tap name '#{args.join("/")}'" unless tap.path.to_s.match?(HOMEBREW_TAP_PATH_REGEX) <del> <del> tap <add> cache.fetch(cache_key) { |key| cache[key] = Tap.new(user, repo) } <ide> end <ide> <ide> def self.from_path(path)
2
Ruby
Ruby
use array() instead of #to_a
be3645518143f2c510623fad40550f074cbca57d
<ide><path>actionmailer/lib/action_mailer/base.rb <ide> def create!(method_name, *parameters) #:nodoc: <ide> def deliver!(mail = @mail) <ide> raise "no mail object available for delivery!" unless mail <ide> unless logger.nil? <del> logger.info "Sent mail to #{recipients.to_a.join(', ')}" <add> logger.info "Sent mail to #{Array(recipients).join(', ')}" <ide> logger.debug "\n#{mail.encoded}" <ide> end <ide>
1
Java
Java
add helper method to resourcehandlerregistry
190bf247a30a2f13ead89383e5e0476584652dd1
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistry.java <ide> package org.springframework.web.servlet.config.annotation; <ide> <ide> import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> public ResourceHandlerRegistry(ApplicationContext applicationContext, ServletCon <ide> this.servletContext = servletContext; <ide> } <ide> <add> <ide> /** <ide> * Add a resource handler for serving static resources based on the specified URL path patterns. <ide> * The handler will be invoked for every incoming request that matches to one of the specified path patterns. <ide> public ResourceHandlerRegistration addResourceHandler(String... pathPatterns) { <ide> return registration; <ide> } <ide> <add> /** <add> * Whether a resource handler has already been registered for the given pathPattern. <add> */ <add> public boolean hasMappingForPattern(String pathPattern) { <add> for (ResourceHandlerRegistration registration : registrations) { <add> if (Arrays.asList(registration.getPathPatterns()).contains(pathPattern)) { <add> return true; <add> } <add> } <add> return false; <add> } <add> <ide> /** <ide> * Specify the order to use for resource handling relative to other {@link HandlerMapping}s configured in <ide> * the Spring MVC application context. The default value used is {@code Integer.MAX_VALUE-1}. <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java <ide> <ide> package org.springframework.web.servlet.config.annotation; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.junit.Assert.assertNull; <del> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.springframework.mock.web.test.MockHttpServletRequest; <ide> import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping; <ide> import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; <ide> <add>import static org.junit.Assert.*; <add> <ide> /** <ide> * Test fixture with a {@link ResourceHandlerRegistry}. <ide> * <ide> public void order() { <ide> assertEquals(0, registry.getHandlerMapping().getOrder()); <ide> } <ide> <add> @Test <add> public void hasMappingForPattern() { <add> assertTrue(registry.hasMappingForPattern("/resources/**")); <add> assertFalse(registry.hasMappingForPattern("/whatever")); <add> } <add> <add> <ide> private ResourceHttpRequestHandler getHandler(String pathPattern) { <ide> SimpleUrlHandlerMapping handlerMapping = (SimpleUrlHandlerMapping) registry.getHandlerMapping(); <ide> return (ResourceHttpRequestHandler) handlerMapping.getUrlMap().get(pathPattern);
2
PHP
PHP
create tests for validation validate method
8665024c290a19c02e4ebf95059aed62f7351208
<ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testSometimesWorksOnArrays() <ide> $this->assertTrue($v->passes()); <ide> } <ide> <add> /** <add> * @expectedException \Illuminate\Validation\ValidationException <add> */ <add> public function testValidateThrowsOnFail() <add> { <add> $trans = $this->getRealTranslator(); <add> $v = new Validator($trans, ['foo' => 'bar'], ['baz' => 'required']); <add> <add> $v->validate(); <add> } <add> <add> public function testValidateDoesntThrowOnPass() <add> { <add> $trans = $this->getRealTranslator(); <add> $v = new Validator($trans, ['foo' => 'bar'], ['foo' => 'required']); <add> <add> $v->validate(); <add> } <add> <ide> public function testHasFailedValidationRules() <ide> { <ide> $trans = $this->getRealTranslator();
1
Go
Go
add execids in inspect
4b43a6df7acd98228b8b287eedf38ba87dc8a388
<ide><path>daemon/exec.go <ide> type execConfig struct { <ide> <ide> type execStore struct { <ide> s map[string]*execConfig <del> sync.Mutex <add> sync.RWMutex <ide> } <ide> <ide> func newExecStore() *execStore { <ide> func (e *execStore) Add(id string, execConfig *execConfig) { <ide> } <ide> <ide> func (e *execStore) Get(id string) *execConfig { <del> e.Lock() <add> e.RLock() <ide> res := e.s[id] <del> e.Unlock() <add> e.RUnlock() <ide> return res <ide> } <ide> <ide> func (e *execStore) Delete(id string) { <ide> e.Unlock() <ide> } <ide> <add>func (e *execStore) List() []string { <add> var IDs []string <add> e.RLock() <add> for id, _ := range e.s { <add> IDs = append(IDs, id) <add> } <add> e.RUnlock() <add> return IDs <add>} <add> <ide> func (execConfig *execConfig) Resize(h, w int) error { <ide> return execConfig.ProcessConfig.Terminal.Resize(h, w) <ide> } <ide> func (d *Daemon) Exec(c *Container, execConfig *execConfig, pipes *execdriver.Pi <ide> return exitStatus, err <ide> } <ide> <add>func (container *Container) GetExecIDs() []string { <add> return container.execCommands.List() <add>} <add> <ide> func (container *Container) Exec(execConfig *execConfig) error { <ide> container.Lock() <ide> defer container.Unlock() <ide><path>daemon/inspect.go <ide> func (daemon *Daemon) ContainerInspect(job *engine.Job) engine.Status { <ide> out.SetJson("VolumesRW", container.VolumesRW) <ide> out.SetJson("AppArmorProfile", container.AppArmorProfile) <ide> <add> out.SetList("ExecIDs", container.GetExecIDs()) <add> <ide> if children, err := daemon.Children(container.Name); err == nil { <ide> for linkAlias, child := range children { <ide> container.hostConfig.Links = append(container.hostConfig.Links, fmt.Sprintf("%s:%s", child.Name, linkAlias))
2
Text
Text
fix broken links in faq toc
0db96121dc8ba328a4e4d8bff16987b3e70cfac1
<ide><path>docs/FAQ.md <ide> - [Is it OK to have more than one middleware chain in my store enhancer? What is the difference between next and dispatch in a middleware function?](/docs/faq/StoreSetup.md#is-it-ok-to-have-more-than-one-middleware-chain-in-my-store-enhancer-what-is-the-difference-between-next-and-dispatch-in-a-middleware-function) <ide> - [How do I subscribe to only a portion of the state? Can I get the dispatched action as part of the subscription?](/docs/faq/StoreSetup.md#how-do-i-subscribe-to-only-a-portion-of-the-state-can-i-get-the-dispatched-action-as-part-of-the-subscription) <ide> - **Actions** <del> - [Why should type be a string, or at least serializable? Why should my action types be constants?](/docs/Actions.md#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants) <del> - [Is there always a one-to-one mapping between reducers and actions?](/docs/Actions.md#is-there-always-a-one-to-one-mapping-between-reducers-and-actions) <del> - [How can I represent “side effects” such as AJAX calls? Why do we need things like “action creators”, “thunks”, and “middleware” to do async behavior?](/docs/Actions.md#how-can-i-represent-side-effects-such-as-ajax-calls-why-do-we-need-things-like-action-creators-thunks-and-middleware-to-do-async-behavior) <del> - [What async middleware should I use? How do you decide between thunks, sagas, observables, or something else?](/docs/Actions.md#what-async-middleware-should-i-use-how-do-you-decide-between-thunks-sagas-observables-or-something-else) <del> - [Should I dispatch multiple actions in a row from one action creator?](/docs/Actions.md#should-i-dispatch-multiple-actions-in-a-row-from-one-action-creator) <add> - [Why should type be a string, or at least serializable? Why should my action types be constants?](/docs/faq/Actions.md#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants) <add> - [Is there always a one-to-one mapping between reducers and actions?](/docs/faq/Actions.md#is-there-always-a-one-to-one-mapping-between-reducers-and-actions) <add> - [How can I represent “side effects” such as AJAX calls? Why do we need things like “action creators”, “thunks”, and “middleware” to do async behavior?](/docs/faq/Actions.md#how-can-i-represent-side-effects-such-as-ajax-calls-why-do-we-need-things-like-action-creators-thunks-and-middleware-to-do-async-behavior) <add> - [What async middleware should I use? How do you decide between thunks, sagas, observables, or something else?](/docs/faq/Actions.md#what-async-middleware-should-i-use-how-do-you-decide-between-thunks-sagas-observables-or-something-else) <add> - [Should I dispatch multiple actions in a row from one action creator?](/docs/faq/Actions.md#should-i-dispatch-multiple-actions-in-a-row-from-one-action-creator) <ide> - **Immutable Data** <del> - [What are the benefits of immutability?](/docs/ImmutableData.md#what-are-the-benefits-of-immutability) <del> - [Why is immutability required by Redux?](/docs/ImmutableData.md#why-is-immutability-required-by-redux) <del> - [What approaches are there for handling data immutability? Do I have to use Immutable.JS?](/docs/ImmutableData.md#what-approaches-are-there-for-handling-data-immutability-do-i-have-to-use-immutable-js) <del> - [What are the issues with using JavaScript for immutable operations?](/docs/ImmutableData.md#what-are-the-issues-with-using-plain-javascript-for-immutable-operations) <add> - [What are the benefits of immutability?](/docs/faq/ImmutableData.md#what-are-the-benefits-of-immutability) <add> - [Why is immutability required by Redux?](/docs/faq/ImmutableData.md#why-is-immutability-required-by-redux) <add> - [What approaches are there for handling data immutability? Do I have to use Immutable.JS?](/docs/faq/ImmutableData.md#what-approaches-are-there-for-handling-data-immutability-do-i-have-to-use-immutable-js) <add> - [What are the issues with using JavaScript for immutable operations?](/docs/faq/ImmutableData.md#what-are-the-issues-with-using-plain-javascript-for-immutable-operations) <ide> - **Using Immutable.JS with Redux** <ide> - [Why should I use an immutable-focused library such as Immutable.JS?](/docs/recipes/UsingImmutableJS.md#why-should-i-use-an-immutable-focused-library-such-as-immutable-js) <ide> - [Why should I choose Immutable.JS as an immutable library?](/docs/recipes/UsingImmutableJS.md#why-should-i-choose-immutable-js-as-an-immutable-library)
1
Text
Text
fix typo "serailizers" to "serializers"
c94d1e6d3ea76eb8bdd28717364e42d14e6722d7
<ide><path>docs/topics/3.0-announcement.md <ide> You can either return `non_field_errors` from the validate method by raising a s <ide> <ide> def validate(self, attrs): <ide> # serializer.errors == {'non_field_errors': ['A non field error']} <del> raise serailizers.ValidationError('A non field error') <add> raise serializers.ValidationError('A non field error') <ide> <ide> Alternatively if you want the errors to be against a specific field, use a dictionary of when instantiating the `ValidationError`, like so: <ide> <ide> def validate(self, attrs): <ide> # serializer.errors == {'my_field': ['A field error']} <del> raise serailizers.ValidationError({'my_field': 'A field error'}) <add> raise serializers.ValidationError({'my_field': 'A field error'}) <ide> <ide> This ensures you can still write validation that compares all the input fields, but that marks the error against a particular field. <ide> <ide> Alternatively, specify the field explicitly on the serializer class: <ide> model = MyModel <ide> fields = ('id', 'email', 'notes', 'is_admin') <ide> <del>The `read_only_fields` option remains as a convenient shortcut for the more common case. <add>The `read_only_fields` option remains as a convenient shortcut for the more common case. <ide> <ide> #### Changes to `HyperlinkedModelSerializer`. <ide> <ide> The `ListSerializer` class has now been added, and allows you to create base ser <ide> class MultipleUserSerializer(ListSerializer): <ide> child = UserSerializer() <ide> <del>You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. <add>You can also still use the `many=True` argument to serializer classes. It's worth noting that `many=True` argument transparently creates a `ListSerializer` instance, allowing the validation logic for list and non-list data to be cleanly separated in the REST framework codebase. <ide> <ide> You will typically want to *continue to use the existing `many=True` flag* rather than declaring `ListSerializer` classes explicitly, but declaring the classes explicitly can be useful if you need to write custom `create` or `update` methods for bulk updates, or provide for other custom behavior. <ide> <ide> Here's a complete example of our previous `HighScoreSerializer`, that's been upd <ide> def to_internal_value(self, data): <ide> score = data.get('score') <ide> player_name = data.get('player_name') <del> <add> <ide> # Perform the data validation. <ide> if not score: <ide> raise ValidationError({ <ide> Here's a complete example of our previous `HighScoreSerializer`, that's been upd <ide> raise ValidationError({ <ide> 'player_name': 'May not be more than 10 characters.' <ide> }) <del> <add> <ide> # Return the validated values. This will be available as <ide> # the `.validated_data` property. <ide> return { <ide> Here's a complete example of our previous `HighScoreSerializer`, that's been upd <ide> 'score': obj.score, <ide> 'player_name': obj.player_name <ide> } <del> <add> <ide> def create(self, validated_data): <ide> return HighScore.objects.create(**validated_data) <ide> <ide> #### Creating new generic serializers with `BaseSerializer`. <ide> <ide> The `BaseSerializer` class is also useful if you want to implement new generic serializer classes for dealing with particular serialization styles, or for integrating with alternative storage backends. <ide> <del>The following class is an example of a generic serializer that can handle coercing aribitrary objects into primitive representations. <add>The following class is an example of a generic serializer that can handle coercing aribitrary objects into primitive representations. <ide> <ide> class ObjectSerializer(serializers.BaseSerializer): <ide> """ <ide> The `default` argument is also available and always implies that the field is no <ide> <ide> #### Coercing output types. <ide> <del>The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior. <add>The previous field implementations did not forcibly coerce returned values into the correct type in many cases. For example, an `IntegerField` would return a string output if the attribute value was a string. We now more strictly coerce to the correct return type, leading to more constrained and expected behavior. <ide> <ide> #### The `ListField` class. <ide> <ide> These classes are documented in the [Validators](../api-guide/validators.md) sec <ide> <ide> The view logic for the default method handlers has been significantly simplified, due to the new serializers API. <ide> <del>#### Changes to pre/post save hooks. <add>#### Changes to pre/post save hooks. <ide> <ide> The `pre_save` and `post_save` hooks no longer exist, but are replaced with `perform_create(self, serializer)` and `perform_update(self, serializer)`. <ide> <ide> The 3.2 release is planned to introduce an alternative admin-style interface to <ide> <ide> You can follow development on the GitHub site, where we use [milestones to indicate planning timescales](https://github.com/tomchristie/django-rest-framework/milestones). <ide> <del>[mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py <ide>\ No newline at end of file <add>[mixins.py]: https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py
1
Text
Text
remove roadmap working group
fde607eb8f54fed22b26b788491f810f26690ed3
<ide><path>WORKING_GROUPS.md <ide> back in to the CTC. <ide> * [Diagnostics](#diagnostics) <ide> * [i18n](#i18n) <ide> * [Evangelism](#evangelism) <del>* [Roadmap](#roadmap) <ide> * [Docker](#docker) <ide> * [Addon API](#addon-api) <ide> * [Benchmarking](#benchmarking) <ide> Responsibilities include: <ide> * Messaging about the future of HTTP to give the community advance notice of <ide> changes. <ide> <del>### [Roadmap](https://github.com/nodejs/roadmap) <del> <del>The Roadmap Working Group is responsible for user community outreach <del>and the translation of their concerns into a plan of action for Node.js. <del> <del>The final [ROADMAP](./ROADMAP.md) document is still owned by the TC and requires <del>the same approval for changes as any other project asset. <del> <del>Their responsibilities are: <del>* Attracting and summarizing user community needs and feedback. <del>* Finding or potentially creating tools that allow for broader participation. <del>* Creating Pull Requests for relevant changes to [ROADMAP.md](./ROADMAP.md) <del> <ide> ### [Docker](https://github.com/nodejs/docker-iojs) <ide> <ide> The Docker Working Group's purpose is to build, maintain, and improve official
1
Ruby
Ruby
fix rubocop warnings
d937f239324380c839fae6e7ebf9ab97f31e370f
<ide><path>Library/Homebrew/test/test_shell.rb <ide> require "utils/shell" <ide> <ide> class ShellSmokeTest < Homebrew::TestCase <del> def test_path_to_shell() <add> def test_path_to_shell <ide> # raw command name <ide> assert_equal :bash, Utils::Shell.path_to_shell("bash") <ide> # full path <ide> def test_path_to_shell() <ide> assert_equal :zsh, Utils::Shell.path_to_shell("zsh-5.2\n") <ide> end <ide> <del> def test_path_to_shell_failure() <add> def test_path_to_shell_failure <ide> assert_equal nil, Utils::Shell.path_to_shell("") <ide> assert_equal nil, Utils::Shell.path_to_shell("@@") <ide> assert_equal nil, Utils::Shell.path_to_shell("invalid_shell-4.2") <ide> end <ide> <del> def test_sh_quote() <add> def test_sh_quote <ide> assert_equal "''", Utils::Shell.sh_quote("") <ide> assert_equal "\\\\", Utils::Shell.sh_quote("\\") <ide> assert_equal "'\n'", Utils::Shell.sh_quote("\n") <ide> assert_equal "\\$", Utils::Shell.sh_quote("$") <ide> assert_equal "word", Utils::Shell.sh_quote("word") <ide> end <ide> <del> def test_csh_quote() <add> def test_csh_quote <ide> assert_equal "''", Utils::Shell.csh_quote("") <ide> assert_equal "\\\\", Utils::Shell.csh_quote("\\") <ide> # note this test is different than for sh <ide> def prepend_path_shell(shell, path, fragment) <ide> ENV["SHELL"] = original_shell <ide> end <ide> <del> def test_prepend_path_in_shell_profile() <add> def test_prepend_path_in_shell_profile <ide> prepend_path_shell "/bin/tcsh", "/path", "echo 'setenv PATH /path" <ide> <ide> prepend_path_shell "/bin/bash", "/path", "echo 'export PATH=\"/path"
1
PHP
PHP
fix warning when full_base_url is unknown. fixes
2d5773be6bc8cab2f15b57ac513d6c32467f4cb9
<ide><path>cake/libs/router.php <ide> function url($url = null, $full = false) { <ide> } <ide> $output = str_replace('//', '/', $output); <ide> } <del> if ($full) { <add> if ($full && defined('FULL_BASE_URL')) { <ide> $output = FULL_BASE_URL . $output; <ide> } <ide> if (!empty($extension) && substr($output, -1) === '/') {
1
Mixed
Javascript
assign missed deprecation number
ae3137049f619b0de01b063075ece994ff2dc741
<ide><path>doc/api/deprecations.md <ide> Using the `noAssert` argument has no functionality anymore. All input is going <ide> to be verified, no matter if it is set to true or not. Skipping the verification <ide> could lead to hard to find errors and crashes. <ide> <del><a id="DEP0XXX"></a> <del>### DEP0XXX: process.binding('util').is[...] typechecks <add><a id="DEP0103"></a> <add>### DEP0103: process.binding('util').is[...] typechecks <ide> <ide> Type: Documentation-only (supports [`--pending-deprecation`][]) <ide> <ide><path>lib/internal/bootstrap_node.js <ide> 'Accessing native typechecking bindings of Node ' + <ide> 'directly is deprecated. ' + <ide> `Please use \`util.types.${name}\` instead.`, <del> 'DEP0XXX') : <add> 'DEP0103') : <ide> types[name]; <ide> } <ide> }
2
Java
Java
fix memory leaks in protobufdecoder
946ec7e22e114e297bc099c89cac1ab5ead9cbb4
<ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/AbstractDataBufferAllocatingTestCase.java <ide> /* <del> * Copyright 2002-2017 the original author or authors. <add> * Copyright 2002-2018 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> protected DataBuffer createDataBuffer(int capacity) { <ide> } <ide> <ide> protected DataBuffer stringBuffer(String value) { <del> byte[] bytes = value.getBytes(StandardCharsets.UTF_8); <del> DataBuffer buffer = this.bufferFactory.allocateBuffer(bytes.length); <del> buffer.write(bytes); <add> return byteBuffer(value.getBytes(StandardCharsets.UTF_8)); <add> } <add> <add> protected DataBuffer byteBuffer(byte[] value) { <add> DataBuffer buffer = this.bufferFactory.allocateBuffer(value.length); <add> buffer.write(value); <ide> return buffer; <ide> } <ide> <ide><path>spring-web/src/main/java/org/springframework/http/codec/protobuf/ProtobufDecoder.java <ide> public Iterable<? extends Message> apply(DataBuffer input) { <ide> } while (remainingBytesToRead > 0); <ide> return messages; <ide> } <add> catch (DecodingException ex) { <add> throw ex; <add> } <ide> catch (IOException ex) { <ide> throw new DecodingException("I/O error while parsing input stream", ex); <ide> } <ide> catch (Exception ex) { <ide> throw new DecodingException("Could not read Protobuf message: " + ex.getMessage(), ex); <ide> } <add> finally { <add> DataBufferUtils.release(input); <add> } <ide> } <ide> } <ide> <ide><path>spring-web/src/test/java/org/springframework/http/codec/protobuf/ProtobufDecoderTests.java <ide> import org.springframework.util.MimeType; <ide> <ide> import static java.util.Collections.emptyMap; <del>import static org.junit.Assert.assertFalse; <del>import static org.junit.Assert.assertTrue; <add>import static org.junit.Assert.*; <ide> import static org.springframework.core.ResolvableType.forClass; <ide> <ide> /** <ide> public void canDecode() { <ide> <ide> @Test <ide> public void decodeToMono() { <del> DataBuffer data = this.bufferFactory.wrap(testMsg.toByteArray()); <add> DataBuffer data = byteBuffer(testMsg.toByteArray()); <ide> ResolvableType elementType = forClass(Msg.class); <ide> <ide> Mono<Message> mono = this.decoder.decodeToMono(Flux.just(data), elementType, null, emptyMap()); <ide> public void decodeToMonoWithLargerDataBuffer() { <ide> <ide> @Test <ide> public void decodeChunksToMono() { <del> DataBuffer buffer = this.bufferFactory.wrap(testMsg.toByteArray()); <add> DataBuffer buffer = byteBuffer(testMsg.toByteArray()); <ide> Flux<DataBuffer> chunks = Flux.just( <del> buffer.slice(0, 4), <del> buffer.slice(4, buffer.readableByteCount() - 4)); <del> DataBufferUtils.retain(buffer); <add> DataBufferUtils.retain(buffer.slice(0, 4)), <add> DataBufferUtils.retain(buffer.slice(4, buffer.readableByteCount() - 4))); <ide> ResolvableType elementType = forClass(Msg.class); <add> release(buffer); <ide> <ide> Mono<Message> mono = this.decoder.decodeToMono(chunks, elementType, null, <ide> emptyMap()); <ide> public void decodeChunksToMono() { <ide> <ide> @Test <ide> public void decode() throws IOException { <del> DataBuffer buffer = bufferFactory.allocateBuffer(); <add> DataBuffer buffer = this.bufferFactory.allocateBuffer(); <ide> testMsg.writeDelimitedTo(buffer.asOutputStream()); <del> DataBuffer buffer2 = bufferFactory.allocateBuffer(); <add> DataBuffer buffer2 = this.bufferFactory.allocateBuffer(); <ide> testMsg2.writeDelimitedTo(buffer2.asOutputStream()); <add> <ide> Flux<DataBuffer> source = Flux.just(buffer, buffer2); <ide> ResolvableType elementType = forClass(Msg.class); <ide> <ide> public void decode() throws IOException { <ide> .expectNext(testMsg) <ide> .expectNext(testMsg2) <ide> .verifyComplete(); <del> <del> DataBufferUtils.release(buffer); <del> DataBufferUtils.release(buffer2); <ide> } <ide> <ide> @Test <ide> public void decodeSplitChunks() throws IOException { <del> DataBuffer buffer = bufferFactory.allocateBuffer(); <add> DataBuffer buffer = this.bufferFactory.allocateBuffer(); <ide> testMsg.writeDelimitedTo(buffer.asOutputStream()); <del> DataBuffer buffer2 = bufferFactory.allocateBuffer(); <add> DataBuffer buffer2 = this.bufferFactory.allocateBuffer(); <ide> testMsg2.writeDelimitedTo(buffer2.asOutputStream()); <add> <ide> Flux<DataBuffer> chunks = Flux.just( <del> buffer.slice(0, 4), <del> buffer.slice(4, buffer.readableByteCount() - 4), <del> buffer2.slice(0, 2), <del> buffer2.slice(2, buffer2.readableByteCount() - 2)); <add> DataBufferUtils.retain(buffer.slice(0, 4)), <add> DataBufferUtils.retain(buffer.slice(4, buffer.readableByteCount() - 4)), <add> DataBufferUtils.retain(buffer2.slice(0, 2)), <add> DataBufferUtils.retain(buffer2 <add> .slice(2, buffer2.readableByteCount() - 2))); <add> release(buffer, buffer2); <ide> <ide> ResolvableType elementType = forClass(Msg.class); <ide> Flux<Message> messages = this.decoder.decode(chunks, elementType, null, emptyMap()); <ide> public void decodeSplitChunks() throws IOException { <ide> .expectNext(testMsg) <ide> .expectNext(testMsg2) <ide> .verifyComplete(); <del> <del> DataBufferUtils.release(buffer); <del> DataBufferUtils.release(buffer2); <ide> } <ide> <ide> @Test <ide> public void decodeMergedChunks() throws IOException { <ide> .expectNext(testMsg) <ide> .expectNext(testMsg) <ide> .verifyComplete(); <del> <del> DataBufferUtils.release(buffer); <ide> } <ide> <ide> @Test <ide> public void exceedMaxSize() { <ide> this.decoder.setMaxMessageSize(1); <del> byte[] body = testMsg.toByteArray(); <del> Flux<DataBuffer> source = Flux.just(this.bufferFactory.wrap(body)); <add> Flux<DataBuffer> source = Flux.just(byteBuffer(testMsg.toByteArray())); <ide> ResolvableType elementType = forClass(Msg.class); <ide> Flux<Message> messages = this.decoder.decode(source, elementType, null, <ide> emptyMap());
3
Ruby
Ruby
remove redundant return
b8b014036ee394084992ad2f0dda06c25964b0be
<ide><path>Library/Homebrew/extend/string.rb <ide> def remove_make_var! flags <ide> def get_make_var flag <ide> m = match Regexp.new("^#{flag}[ \\t]*=[ \\t]*(.*)$") <ide> return m[1] if m <del> return nil <ide> end <ide> end
1
Javascript
Javascript
fix regression in x-axis interaction mode
52145de5db5dc3bae093880429b35954f0034993
<ide><path>src/core/core.interaction.js <ide> module.exports = { <ide> * @private <ide> */ <ide> 'x-axis': function(chart, e) { <del> return indexMode(chart, e, {intersect: true}); <add> return indexMode(chart, e, {intersect: false}); <ide> }, <ide> <ide> /** <ide><path>test/specs/global.deprecations.tests.js <ide> describe('Deprecations', function() { <ide> }); <ide> }); <ide> <add> describe('Version 2.4.0', function() { <add> describe('x-axis mode', function() { <add> it ('behaves like index mode with intersect: false', function() { <add> var data = { <add> datasets: [{ <add> label: 'Dataset 1', <add> data: [10, 20, 30], <add> pointHoverBorderColor: 'rgb(255, 0, 0)', <add> pointHoverBackgroundColor: 'rgb(0, 255, 0)' <add> }, { <add> label: 'Dataset 2', <add> data: [40, 40, 40], <add> pointHoverBorderColor: 'rgb(0, 0, 255)', <add> pointHoverBackgroundColor: 'rgb(0, 255, 255)' <add> }], <add> labels: ['Point 1', 'Point 2', 'Point 3'] <add> }; <add> <add> var chart = window.acquireChart({ <add> type: 'line', <add> data: data <add> }); <add> var meta0 = chart.getDatasetMeta(0); <add> var meta1 = chart.getDatasetMeta(1); <add> <add> var evt = { <add> type: 'click', <add> chart: chart, <add> native: true, // needed otherwise things its a DOM event <add> x: 0, <add> y: 0 <add> }; <add> <add> var elements = Chart.Interaction.modes['x-axis'](chart, evt); <add> expect(elements).toEqual([meta0.data[0], meta1.data[0]]); <add> }); <add> }); <add> }); <add> <ide> describe('Version 2.1.5', function() { <ide> // https://github.com/chartjs/Chart.js/pull/2752 <ide> describe('Chart.pluginService', function() {
2
Ruby
Ruby
allow partial installation of resources
50d2f632d9157c953dcbaeb33c5b79ef50fee38a
<ide><path>Library/Homebrew/extend/pathname.rb <ide> require 'pathname' <ide> require 'mach' <add>require 'resource' <ide> <ide> # we enhance pathname to make our code more readable <ide> class Pathname <ide> def install *sources <ide> case src <ide> when Resource <ide> src.stage(self) <add> when Resource::Partial <add> src.resource.stage { install(*src.files) } <ide> when Array <ide> if src.empty? <ide> opoo "tried to install empty array to #{self}" <ide><path>Library/Homebrew/resource.rb <ide> def stage(target=nil) <ide> end <ide> end <ide> <add> Partial = Struct.new(:resource, :files) <add> <add> def files(*files) <add> Partial.new(self, files) <add> end <add> <ide> # For brew-fetch and others. <ide> def fetch <ide> # Ensure the cache exists
2
Go
Go
remove goroutine leak upon error
721562f29685ebf3f3698113cf0ce8000c02e606
<ide><path>execdriver/lxc/driver.go <ide> func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba <ide> // Poll lxc for RUNNING status <ide> pid, err := d.waitForStart(c, waitLock) <ide> if err != nil { <add> if c.Process != nil { <add> c.Process.Kill() <add> } <ide> return -1, err <ide> } <ide> c.ContainerPid = pid <ide><path>server.go <ide> func (srv *Server) IsRunning() bool { <ide> } <ide> <ide> func (srv *Server) Close() error { <add> if srv == nil { <add> return nil <add> } <ide> srv.SetRunning(false) <add> if srv.runtime == nil { <add> return nil <add> } <ide> return srv.runtime.Close() <ide> } <ide>
2
PHP
PHP
fix phpstan errors on interfaces - level 5
2c08e46229e5e42e0750ef28ed3e9f1412e3d83c
<ide><path>src/Database/Schema/CachedCollection.php <ide> public function listTables(): array <ide> /** <ide> * {@inheritDoc} <ide> */ <del> public function describe(string $name, array $options = []): TableSchemaInterface <add> public function describe(string $name, array $options = []): TableSchema <ide> { <ide> $options += ['forceRefresh' => false]; <ide> $cacheConfig = $this->getCacheMetadata(); <ide><path>src/Database/Schema/Collection.php <ide> public function listTables(): array <ide> * <ide> * @param string $name The name of the table to describe. <ide> * @param array $options The options to use, see above. <del> * @return \Cake\Database\Schema\TableSchemaInterface Object with column metadata. <add> * @return \Cake\Database\Schema\TableSchema Object with column metadata. <ide> * @throws \Cake\Database\Exception when table cannot be described. <ide> */ <del> public function describe(string $name, array $options = []): TableSchemaInterface <add> public function describe(string $name, array $options = []): TableSchema <ide> { <ide> $config = $this->_connection->config(); <ide> if (strpos($name, '.')) { <ide><path>src/Database/Schema/CollectionInterface.php <ide> public function listTables(): array; <ide> * <ide> * @param string $name The name of the table to describe. <ide> * @param array $options The options to use, see above. <del> * @return \Cake\Database\Schema\TableSchemaInterface Object with column metadata. <add> * @return \Cake\Database\Schema\TableSchema Object with column metadata. <ide> * @throws \Cake\Database\Exception when table cannot be described. <ide> */ <del> public function describe(string $name, array $options = []): TableSchemaInterface; <add> public function describe(string $name, array $options = []): TableSchema; <ide> } <ide><path>src/Database/Schema/SqlGeneratorInterface.php <ide> */ <ide> namespace Cake\Database\Schema; <ide> <del>use Cake\Database\Connection; <add>use Cake\Datasource\ConnectionInterface; <ide> <ide> /** <ide> * An interface used by TableSchema objects. <ide> interface SqlGeneratorInterface <ide> * Uses the connection to access the schema dialect <ide> * to generate platform specific SQL. <ide> * <del> * @param \Cake\Database\Connection $connection The connection to generate SQL for. <add> * @param \Cake\Datasource\ConnectionInterface $connection The connection to generate SQL for. <ide> * @return array List of SQL statements to create the table and the <ide> * required indexes. <ide> */ <del> public function createSql(Connection $connection): array; <add> public function createSql(ConnectionInterface $connection): array; <ide> <ide> /** <ide> * Generate the SQL to drop a table. <ide> * <ide> * Uses the connection to access the schema dialect to generate platform <ide> * specific SQL. <ide> * <del> * @param \Cake\Database\Connection $connection The connection to generate SQL for. <add> * @param \Cake\Datasource\ConnectionInterface $connection The connection to generate SQL for. <ide> * @return array SQL to drop a table. <ide> */ <del> public function dropSql(Connection $connection): array; <add> public function dropSql(ConnectionInterface $connection): array; <ide> <ide> /** <ide> * Generate the SQL statements to truncate a table <ide> * <del> * @param \Cake\Database\Connection $connection The connection to generate SQL for. <add> * @param \Cake\Datasource\ConnectionInterface $connection The connection to generate SQL for. <ide> * @return array SQL to truncate a table. <ide> */ <del> public function truncateSql(Connection $connection): array; <add> public function truncateSql(ConnectionInterface $connection): array; <ide> <ide> /** <ide> * Generate the SQL statements to add the constraints to the table <ide> * <del> * @param \Cake\Database\Connection $connection The connection to generate SQL for. <add> * @param \Cake\Datasource\ConnectionInterface $connection The connection to generate SQL for. <ide> * @return array SQL to add the constraints. <ide> */ <del> public function addConstraintSql(Connection $connection): array; <add> public function addConstraintSql(ConnectionInterface $connection): array; <ide> <ide> /** <ide> * Generate the SQL statements to drop the constraints to the table <ide> * <del> * @param \Cake\Database\Connection $connection The connection to generate SQL for. <add> * @param \Cake\Datasource\ConnectionInterface $connection The connection to generate SQL for. <ide> * @return array SQL to drop a table. <ide> */ <del> public function dropConstraintSql(Connection $connection): array; <add> public function dropConstraintSql(ConnectionInterface $connection): array; <ide> } <ide><path>src/Database/Schema/TableSchema.php <ide> */ <ide> namespace Cake\Database\Schema; <ide> <del>use Cake\Database\Connection; <ide> use Cake\Database\Exception; <ide> use Cake\Database\TypeFactory; <add>use Cake\Datasource\ConnectionInterface; <ide> <ide> /** <ide> * Represents a single table in a database schema. <ide> public function isTemporary(): bool <ide> /** <ide> * @inheritDoc <ide> */ <del> public function createSql(Connection $connection): array <add> public function createSql(ConnectionInterface $connection): array <ide> { <ide> $dialect = $connection->getDriver()->schemaDialect(); <ide> $columns = $constraints = $indexes = []; <ide> public function createSql(Connection $connection): array <ide> /** <ide> * @inheritDoc <ide> */ <del> public function dropSql(Connection $connection): array <add> public function dropSql(ConnectionInterface $connection): array <ide> { <ide> $dialect = $connection->getDriver()->schemaDialect(); <ide> <ide> public function dropSql(Connection $connection): array <ide> /** <ide> * @inheritDoc <ide> */ <del> public function truncateSql(Connection $connection): array <add> public function truncateSql(ConnectionInterface $connection): array <ide> { <ide> $dialect = $connection->getDriver()->schemaDialect(); <ide> <ide> public function truncateSql(Connection $connection): array <ide> /** <ide> * @inheritDoc <ide> */ <del> public function addConstraintSql(Connection $connection): array <add> public function addConstraintSql(ConnectionInterface $connection): array <ide> { <ide> $dialect = $connection->getDriver()->schemaDialect(); <ide> <ide> public function addConstraintSql(Connection $connection): array <ide> /** <ide> * @inheritDoc <ide> */ <del> public function dropConstraintSql(Connection $connection): array <add> public function dropConstraintSql(ConnectionInterface $connection): array <ide> { <ide> $dialect = $connection->getDriver()->schemaDialect(); <ide> <ide><path>src/Database/Statement/BufferedStatement.php <ide> class BufferedStatement implements Iterator, StatementInterface <ide> /** <ide> * The driver for the statement <ide> * <del> * @var \Cake\Database\DriverInterface <add> * @var \Cake\Database\Driver <ide> */ <ide> protected $_driver; <ide> <ide><path>src/Database/Type/DateTimeType.php <ide> public function marshal($value): ?DateTimeInterface <ide> } <ide> <ide> /** <del> * @param \Cake\I18n\Time|\DateTime $date DateTime object <add> * @param \DateTimeInterface $date DateTime object <ide> * @param mixed $value Request data <ide> * @return bool <ide> */ <ide><path>src/Datasource/ConnectionInterface.php <ide> * @method \Cake\Database\StatementInterface prepare($sql) <ide> * @method \Cake\Database\StatementInterface execute($query, $params = [], array $types = []) <ide> * @method string quote($value, $type = null) <add> * @method \Cake\Database\Driver getDriver() <ide> */ <ide> interface ConnectionInterface <ide> { <ide><path>src/Http/ActionDispatcher.php <ide> public function __construct(?ControllerFactory $factory = null) <ide> * Dispatches a Request & Response <ide> * <ide> * @param \Cake\Http\ServerRequest $request The request to dispatch. <del> * @param \Psr\Http\Message\ResponseInterface $response The response to dispatch. <add> * @param \Cake\Http\Response $response The response to dispatch. <ide> * @return \Psr\Http\Message\ResponseInterface A modified/replaced response. <ide> */ <ide> public function dispatch(ServerRequest $request, ?ResponseInterface $response = null): ResponseInterface <ide><path>src/Http/BaseApplication.php <ide> public function getPlugins(): PluginCollection <ide> * @param string $name The plugin classname <ide> * @param array $config Configuration options for the plugin <ide> * @return \Cake\Core\PluginInterface <add> * @throws \InvalidArgumentException <ide> */ <ide> protected function makePlugin(string $name, array $config): PluginInterface <ide> { <ide> public function pluginConsole(CommandCollection $commands): CommandCollection <ide> * - Create the controller that will handle this request. <ide> * - Invoke the controller. <ide> * <del> * @param \Psr\Http\Message\ServerRequestInterface $request The request <add> * @param \Cake\Http\ServerRequest $request The request <ide> * @return \Psr\Http\Message\ResponseInterface <ide> */ <ide> public function handle( <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php <ide> public function __construct(array $config = []) <ide> /** <ide> * Checks and sets the CSRF token depending on the HTTP verb. <ide> * <del> * @param \Psr\Http\Message\ServerRequestInterface $request The request. <add> * @param \Cake\Http\ServerRequest $request The request. <ide> * @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. <ide> * @return \Psr\Http\Message\ResponseInterface A response. <ide> */ <ide> public function process(ServerRequestInterface $request, RequestHandlerInterface <ide> if ($method === 'GET' && $cookieData === null) { <ide> $token = $this->_createToken(); <ide> $request = $this->_addTokenToRequest($token, $request); <add> /** @var \Cake\Http\Response $response */ <ide> $response = $handler->handle($request); <ide> <ide> return $this->_addTokenCookie($token, $request, $response); <ide> protected function _createToken(): string <ide> * Add a CSRF token to the request parameters. <ide> * <ide> * @param string $token The token to add. <del> * @param \Cake\Http\ServerRequest $request The request to augment <del> * @return \Cake\Http\ServerRequest Modified request <add> * @param \Psr\Http\Message\ServerRequestInterface $request The request to augment <add> * @return \Psr\Http\Message\ServerRequestInterface Modified request <ide> */ <del> protected function _addTokenToRequest(string $token, ServerRequest $request): ServerRequest <add> protected function _addTokenToRequest(string $token, ServerRequestInterface $request): ServerRequestInterface <ide> { <ide> $params = $request->getAttribute('params'); <ide> $params['_csrfToken'] = $token; <ide> protected function _addTokenToRequest(string $token, ServerRequest $request): Se <ide> * Add a CSRF token to the response cookies. <ide> * <ide> * @param string $token The token to add. <del> * @param \Cake\Http\ServerRequest $request The request to validate against. <add> * @param \Psr\Http\Message\ServerRequestInterface $request The request to validate against. <ide> * @param \Cake\Http\Response $response The response. <ide> * @return \Cake\Http\Response $response Modified response. <ide> */ <del> protected function _addTokenCookie(string $token, ServerRequest $request, Response $response): Response <add> protected function _addTokenCookie(string $token, ServerRequestInterface $request, ResponseInterface $response): ResponseInterface <ide> { <ide> $expiry = new Time($this->_config['expiry']); <ide> <ide><path>src/ORM/ResultSet.php <ide> class ResultSet implements ResultSetInterface <ide> /** <ide> * Default table instance <ide> * <del> * @var \Cake\ORM\Table|\Cake\Datasource\RepositoryInterface <add> * @var \Cake\ORM\Table <ide> */ <ide> protected $_defaultTable; <ide> <ide> public function __construct(Query $query, StatementInterface $statement) <ide> $repository = $query->getRepository(); <ide> $this->_statement = $statement; <ide> $this->_driver = $query->getConnection()->getDriver(); <del> $this->_defaultTable = $query->getRepository(); <add> $this->_defaultTable = $repository; <ide> $this->_calculateAssociationMap($query); <ide> $this->_hydrate = $query->isHydrationEnabled(); <ide> $this->_entityClass = $repository->getEntityClass(); <ide><path>src/Routing/Router.php <ide> public static function setRequestInfo(ServerRequestInterface $request): void <ide> * Push a request onto the request stack. Pushing a request <ide> * sets the request context used when generating URLs. <ide> * <del> * @param \Cake\Http\ServerRequest $request Request instance. <add> * @param \Psr\Http\Message\ServerRequestInterface $request Request instance. <ide> * @return void <ide> */ <del> public static function pushRequest(ServerRequest $request): void <add> public static function pushRequest(ServerRequestInterface $request): void <ide> { <ide> static::$_requests[] = $request; <ide> static::setRequestContext($request); <ide><path>src/TestSuite/Fixture/FixtureManager.php <ide> public function load(TestCase $test): void <ide> } <ide> <ide> try { <del> $createTables = function ($db, $fixtures) use ($test): void { <add> $createTables = function (ConnectionInterface $db, $fixtures) use ($test): void { <ide> $tables = $db->getSchemaCollection()->listTables(); <ide> $configName = $db->configName(); <ide> if (!isset($this->_insertionMap[$configName])) { <ide> $this->_insertionMap[$configName] = []; <ide> } <ide> <add> /** @var \Cake\Datasource\FixtureInterface[] $fixtures */ <ide> foreach ($fixtures as $fixture) { <ide> if (in_array($fixture->table, $tables, true)) { <ide> try { <ide> protected function _runOperation(array $fixtures, callable $operation): void <ide> if ($logQueries && !$this->_debug) { <ide> $db->disableQueryLogging(); <ide> } <del> $db->transactional(function ($db) use ($fixtures, $operation): void { <add> $db->transactional(function (ConnectionInterface $db) use ($fixtures, $operation): void { <ide> $db->disableConstraints(function ($db) use ($fixtures, $operation): void { <ide> $operation($db, $fixtures); <ide> }); <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> public function testReferer(): void <ide> */ <ide> public function testRefererSlash(): void <ide> { <del> $request = $this->getMockBuilder('Cake\Http\ServerRequest') <add> /** @var \Cake\Http\ServerRequest|\PHPUnit\Framework\MockObject\MockObject $request */ <add> $request = $this->getMockBuilder(ServerRequest::class) <ide> ->setMethods(['referer']) <ide> ->getMock(); <ide> $request = $request->withAttribute('base', '/base');
15
Python
Python
add shortcut class in providers.py for linode
32659f2b14cb312659b51a01eeef374138c6e371
<ide><path>libcloud/providers.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> from libcloud.types import Provider <add>from libcloud.drivers.linode import LinodeNodeDriver as Linode <ide> from libcloud.drivers.slicehost import SlicehostNodeDriver as Slicehost <ide> from libcloud.drivers.rackspace import RackspaceNodeDriver as Rackspace <ide>
1
Python
Python
fix generation docstrings regarding input_ids=none
1fec32adc6a4840123d5ec5ff5cf419c02342b5a
<ide><path>src/transformers/generation_flax_utils.py <ide> def generate( <ide> <ide> Parameters: <ide> <del> input_ids (:obj:`jnp.ndarray` of shape :obj:`(batch_size, sequence_length)`, `optional`): <add> input_ids (:obj:`jnp.ndarray` of shape :obj:`(batch_size, sequence_length)`): <ide> The sequence used as a prompt for the generation. <ide> max_length (:obj:`int`, `optional`, defaults to 20): <ide> The maximum length of the sequence to be generated. <ide><path>src/transformers/generation_tf_utils.py <ide> def generate( <ide> Parameters: <ide> <ide> input_ids (:obj:`tf.Tensor` of :obj:`dtype=tf.int32` and shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`tf.Tensor` of shape :obj:`(1,)`. <add> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it with <add> :obj:`bos_token_id` and a batch size of 1. <ide> max_length (:obj:`int`, `optional`, defaults to 20): <ide> The maximum length of the sequence to be generated. <ide> min_length (:obj:`int`, `optional`, defaults to 10): <ide><path>src/transformers/generation_utils.py <ide> def generate( <ide> Parameters: <ide> <ide> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`torch.LongTensor` of shape :obj:`(1,)`. <add> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it with <add> :obj:`bos_token_id` and a batch size of 1. <ide> max_length (:obj:`int`, `optional`, defaults to :obj:`model.config.max_length`): <ide> The maximum length of the sequence to be generated. <ide> max_new_tokens (:obj:`int`, `optional`, defaults to None): <ide> def greedy_search( <ide> <ide> Parameters: <ide> <del> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`torch.LongTensor` of shape :obj:`(1,)`. <add> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`): <add> The sequence used as a prompt for the generation. <ide> logits_processor (:obj:`LogitsProcessorList`, `optional`): <ide> An instance of :class:`~transformers.LogitsProcessorList`. List of instances of class derived from <ide> :class:`~transformers.LogitsProcessor` used to modify the prediction scores of the language modeling <ide> def sample( <ide> <ide> Parameters: <ide> <del> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`torch.LongTensor` of shape :obj:`(1,)`. <add> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`): <add> The sequence used as a prompt for the generation. <ide> logits_processor (:obj:`LogitsProcessorList`, `optional`): <ide> An instance of :class:`~transformers.LogitsProcessorList`. List of instances of class derived from <ide> :class:`~transformers.LogitsProcessor` used to modify the prediction scores of the language modeling <ide> def beam_search( <ide> <ide> Parameters: <ide> <del> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`torch.LongTensor` of shape :obj:`(1,)`. <add> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`): <add> The sequence used as a prompt for the generation. <ide> beam_scorer (:obj:`BeamScorer`): <ide> An derived instance of :class:`~transformers.BeamScorer` that defines how beam hypotheses are <ide> constructed, stored and sorted during generation. For more information, the documentation of <ide> def beam_sample( <ide> <ide> Parameters: <ide> <del> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`torch.LongTensor` of shape :obj:`(1,)`. <add> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`): <add> The sequence used as a prompt for the generation. <ide> beam_scorer (:obj:`BeamScorer`): <ide> A derived instance of :class:`~transformers.BeamScorer` that defines how beam hypotheses are <ide> constructed, stored and sorted during generation. For more information, the documentation of <ide> def group_beam_search( <ide> <ide> Parameters: <ide> <del> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`): <del> The sequence used as a prompt for the generation. If :obj:`None` the method initializes it as an empty <del> :obj:`torch.LongTensor` of shape :obj:`(1,)`. <add> input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`): <add> The sequence used as a prompt for the generation. <ide> beam_scorer (:obj:`BeamScorer`): <ide> An derived instance of :class:`~transformers.BeamScorer` that defines how beam hypotheses are <ide> constructed, stored and sorted during generation. For more information, the documentation of
3
Python
Python
fix import on initalization
cd09cd5b40fa9ccab1a40643bd5cf1245fcc4a2c
<ide><path>run_classifier_pytorch.py <ide> import logging <ide> import argparse <ide> <add>import random <ide> import numpy as np <ide> from tqdm import tqdm, trange <ide> import torch <ide><path>run_squad_pytorch.py <ide> import math <ide> import os <ide> from tqdm import tqdm, trange <add>import random <ide> <ide> import torch <ide> from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
2
Ruby
Ruby
expose active storage routes
ff25c25127405f49c0021714a9d938558c7822ab
<ide><path>activestorage/config/routes.rb <ide> # frozen_string_literal: true <ide> <ide> Rails.application.routes.draw do <del> get "/rails/active_storage/blobs/:signed_id/*filename" => "active_storage/blobs#show", as: :rails_service_blob, internal: true <add> get "/rails/active_storage/blobs/:signed_id/*filename" => "active_storage/blobs#show", as: :rails_service_blob <ide> <ide> direct :rails_blob do |blob, options| <ide> route_for(:rails_service_blob, blob.signed_id, blob.filename, options) <ide> resolve("ActiveStorage::Attachment") { |attachment, options| route_for(:rails_blob, attachment.blob, options) } <ide> <ide> <del> get "/rails/active_storage/variants/:signed_blob_id/:variation_key/*filename" => "active_storage/variants#show", as: :rails_blob_variation, internal: true <add> get "/rails/active_storage/variants/:signed_blob_id/:variation_key/*filename" => "active_storage/variants#show", as: :rails_blob_variation <ide> <ide> direct :rails_variant do |variant, options| <ide> signed_blob_id = variant.blob.signed_id <ide> resolve("ActiveStorage::Variant") { |variant, options| route_for(:rails_variant, variant, options) } <ide> <ide> <del> get "/rails/active_storage/previews/:signed_blob_id/:variation_key/*filename" => "active_storage/previews#show", as: :rails_blob_preview, internal: true <add> get "/rails/active_storage/previews/:signed_blob_id/:variation_key/*filename" => "active_storage/previews#show", as: :rails_blob_preview <ide> <ide> direct :rails_preview do |preview, options| <ide> signed_blob_id = preview.blob.signed_id <ide> resolve("ActiveStorage::Preview") { |preview, options| route_for(:rails_preview, preview, options) } <ide> <ide> <del> get "/rails/active_storage/disk/:encoded_key/*filename" => "active_storage/disk#show", as: :rails_disk_service, internal: true <del> put "/rails/active_storage/disk/:encoded_token" => "active_storage/disk#update", as: :update_rails_disk_service, internal: true <del> post "/rails/active_storage/direct_uploads" => "active_storage/direct_uploads#create", as: :rails_direct_uploads, internal: true <add> get "/rails/active_storage/disk/:encoded_key/*filename" => "active_storage/disk#show", as: :rails_disk_service <add> put "/rails/active_storage/disk/:encoded_token" => "active_storage/disk#update", as: :update_rails_disk_service <add> post "/rails/active_storage/direct_uploads" => "active_storage/direct_uploads#create", as: :rails_direct_uploads <ide> end <ide><path>railties/test/application/rake_test.rb <ide> def test_rails_routes_calls_the_route_inspector <ide> <ide> output = rails("routes") <ide> assert_equal <<-MESSAGE.strip_heredoc, output <del> Prefix Verb URI Pattern Controller#Action <del> cart GET /cart(.:format) cart#show <add> Prefix Verb URI Pattern Controller#Action <add> cart GET /cart(.:format) cart#show <add> rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show <add> rails_blob_variation GET /rails/active_storage/variants/:signed_blob_id/:variation_key/*filename(.:format) active_storage/variants#show <add> rails_blob_preview GET /rails/active_storage/previews/:signed_blob_id/:variation_key/*filename(.:format) active_storage/previews#show <add> rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show <add> update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update <add> rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create <ide> MESSAGE <ide> end <ide> <ide> def test_rails_routes_with_global_search_key <ide> <ide> output = rails("routes", "-g", "show") <ide> assert_equal <<-MESSAGE.strip_heredoc, output <del> Prefix Verb URI Pattern Controller#Action <del> cart GET /cart(.:format) cart#show <add> Prefix Verb URI Pattern Controller#Action <add> cart GET /cart(.:format) cart#show <add> rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show <add> rails_blob_variation GET /rails/active_storage/variants/:signed_blob_id/:variation_key/*filename(.:format) active_storage/variants#show <add> rails_blob_preview GET /rails/active_storage/previews/:signed_blob_id/:variation_key/*filename(.:format) active_storage/previews#show <add> rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show <ide> MESSAGE <ide> <ide> output = rails("routes", "-g", "POST") <ide> assert_equal <<-MESSAGE.strip_heredoc, output <del> Prefix Verb URI Pattern Controller#Action <del> POST /cart(.:format) cart#create <add> Prefix Verb URI Pattern Controller#Action <add> POST /cart(.:format) cart#create <add> rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create <ide> MESSAGE <ide> <ide> output = rails("routes", "-g", "basketballs") <ide> def test_rails_routes_displays_message_when_no_routes_are_defined <ide> RUBY <ide> <ide> assert_equal <<-MESSAGE.strip_heredoc, rails("routes") <del> You don't have any routes defined! <del> <del> Please add some routes in config/routes.rb. <del> <del> For more information about routes, see the Rails guide: http://guides.rubyonrails.org/routing.html. <add> Prefix Verb URI Pattern Controller#Action <add> rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show <add> rails_blob_variation GET /rails/active_storage/variants/:signed_blob_id/:variation_key/*filename(.:format) active_storage/variants#show <add> rails_blob_preview GET /rails/active_storage/previews/:signed_blob_id/:variation_key/*filename(.:format) active_storage/previews#show <add> rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show <add> update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update <add> rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create <ide> MESSAGE <ide> end <ide> <ide> def test_rake_routes_with_rake_options <ide> output = Dir.chdir(app_path) { `bin/rake --rakefile Rakefile routes` } <ide> <ide> assert_equal <<-MESSAGE.strip_heredoc, output <del> Prefix Verb URI Pattern Controller#Action <del> cart GET /cart(.:format) cart#show <add> Prefix Verb URI Pattern Controller#Action <add> cart GET /cart(.:format) cart#show <add> rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show <add> rails_blob_variation GET /rails/active_storage/variants/:signed_blob_id/:variation_key/*filename(.:format) active_storage/variants#show <add> rails_blob_preview GET /rails/active_storage/previews/:signed_blob_id/:variation_key/*filename(.:format) active_storage/previews#show <add> rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show <add> update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update <add> rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create <ide> MESSAGE <ide> end <ide>
2
Python
Python
enable ctrl-c for parallel tests
12912c6b3074371d9860e4b4eb28453493db83a1
<ide><path>tools/test.py <ide> def __init__(self, cases, flaky_tests_mode): <ide> self.total = len(cases) <ide> self.failed = [ ] <ide> self.crashed = 0 <del> self.terminate = False <ide> self.lock = threading.Lock() <add> self.shutdown_event = threading.Event() <ide> <ide> def PrintFailureHeader(self, test): <ide> if test.IsNegative(): <ide> def Run(self, tasks): <ide> for thread in threads: <ide> # Use a timeout so that signals (ctrl-c) will be processed. <ide> thread.join(timeout=10000000) <add> except (KeyboardInterrupt, SystemExit), e: <add> self.shutdown_event.set() <ide> except Exception, e: <ide> # If there's an exception we schedule an interruption for any <ide> # remaining threads. <del> self.terminate = True <add> self.shutdown_event.set() <ide> # ...and then reraise the exception to bail out <ide> raise <ide> self.Done() <ide> return not self.failed <ide> <ide> def RunSingle(self, parallel, thread_id): <del> while not self.terminate: <add> while not self.shutdown_event.is_set(): <ide> try: <ide> test = self.parallel_queue.get_nowait() <ide> except Empty: <ide> def RunSingle(self, parallel, thread_id): <ide> output = case.Run() <ide> case.duration = (datetime.now() - start) <ide> except IOError, e: <del> assert self.terminate <ide> return <del> if self.terminate: <add> if self.shutdown_event.is_set(): <ide> return <ide> self.lock.acquire() <ide> if output.UnexpectedOutput():
1
Python
Python
move read_json out to own util function
31fa73293a260a764fda000f72a167a56eab6330
<ide><path>spacy/util.py <ide> def check_renamed_kwargs(renamed, kwargs): <ide> raise TypeError("Keyword argument %s now renamed to %s" % (old, new)) <ide> <ide> <add>def read_json(location): <add> with location.open('r', encoding='utf8') as f: <add> return ujson.load(f) <add> <add> <ide> def parse_package_meta(package_path, package, require=True): <ide> location = package_path / package / 'meta.json' <ide> if location.is_file(): <del> with location.open('r', encoding='utf8') as f: <del> meta = ujson.load(f) <del> return meta <add> return read_json(location) <ide> elif require: <ide> raise IOError("Could not read meta.json from %s" % location) <ide> else:
1
Python
Python
add multiple processing
8e9526b4b56486606979f1c47d3317b0b22340fe
<ide><path>examples/run_squad.py <ide> def load_and_cache_examples(args, tokenizer, evaluate=False, output_examples=Fal <ide> doc_stride=args.doc_stride, <ide> max_query_length=args.max_query_length, <ide> is_training=not evaluate, <del> return_dataset='pt' <add> return_dataset='pt', <add> threads=args.threads, <ide> ) <ide> <ide> if args.local_rank in [-1, 0]: <ide> def main(): <ide> "See details at https://nvidia.github.io/apex/amp.html") <ide> parser.add_argument('--server_ip', type=str, default='', help="Can be used for distant debugging.") <ide> parser.add_argument('--server_port', type=str, default='', help="Can be used for distant debugging.") <add> <add> parser.add_argument('--threads', type=int, default=1, help='multiple threads for converting example to features') <ide> args = parser.parse_args() <ide> <ide> if os.path.exists(args.output_dir) and os.listdir(args.output_dir) and args.do_train and not args.overwrite_output_dir: <ide><path>transformers/data/processors/squad.py <ide> import os <ide> import json <ide> import numpy as np <add>from multiprocessing import Pool <add>from multiprocessing import cpu_count <add>from functools import partial <ide> <ide> from ...tokenization_bert import BasicTokenizer, whitespace_tokenize <ide> from .utils import DataProcessor, InputExample, InputFeatures <ide> def _is_whitespace(c): <ide> return True <ide> return False <ide> <add>def squad_convert_example_to_features(example, max_seq_length, <add> doc_stride, max_query_length, is_training): <add> features = [] <add> if is_training and not example.is_impossible: <add> # Get start and end position <add> start_position = example.start_position <add> end_position = example.end_position <add> <add> # If the answer cannot be found in the text, then skip this example. <add> actual_text = " ".join(example.doc_tokens[start_position:(end_position + 1)]) <add> cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text)) <add> if actual_text.find(cleaned_answer_text) == -1: <add> logger.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text) <add> return [] <add> <add> tok_to_orig_index = [] <add> orig_to_tok_index = [] <add> all_doc_tokens = [] <add> for (i, token) in enumerate(example.doc_tokens): <add> orig_to_tok_index.append(len(all_doc_tokens)) <add> sub_tokens = tokenizer.tokenize(token) <add> for sub_token in sub_tokens: <add> tok_to_orig_index.append(i) <add> all_doc_tokens.append(sub_token) <add> <add> if is_training and not example.is_impossible: <add> tok_start_position = orig_to_tok_index[example.start_position] <add> if example.end_position < len(example.doc_tokens) - 1: <add> tok_end_position = orig_to_tok_index[example.end_position + 1] - 1 <add> else: <add> tok_end_position = len(all_doc_tokens) - 1 <add> <add> (tok_start_position, tok_end_position) = _improve_answer_span( <add> all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text <add> ) <add> <add> spans = [] <add> <add> truncated_query = tokenizer.encode(example.question_text, add_special_tokens=False, max_length=max_query_length) <add> sequence_added_tokens = tokenizer.max_len - tokenizer.max_len_single_sentence + 1 \ <add> if 'roberta' in str(type(tokenizer)) else tokenizer.max_len - tokenizer.max_len_single_sentence <add> sequence_pair_added_tokens = tokenizer.max_len - tokenizer.max_len_sentences_pair <add> <add> span_doc_tokens = all_doc_tokens <add> while len(spans) * doc_stride < len(all_doc_tokens): <add> <add> encoded_dict = tokenizer.encode_plus( <add> truncated_query if tokenizer.padding_side == "right" else span_doc_tokens, <add> span_doc_tokens if tokenizer.padding_side == "right" else truncated_query, <add> max_length=max_seq_length, <add> return_overflowing_tokens=True, <add> pad_to_max_length=True, <add> stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens, <add> truncation_strategy='only_second' if tokenizer.padding_side == "right" else 'only_first' <add> ) <add> <add> paragraph_len = min(len(all_doc_tokens) - len(spans) * doc_stride, <add> max_seq_length - len(truncated_query) - sequence_pair_added_tokens) <add> <add> if tokenizer.pad_token_id in encoded_dict['input_ids']: <add> non_padded_ids = encoded_dict['input_ids'][:encoded_dict['input_ids'].index(tokenizer.pad_token_id)] <add> else: <add> non_padded_ids = encoded_dict['input_ids'] <add> <add> tokens = tokenizer.convert_ids_to_tokens(non_padded_ids) <add> <add> token_to_orig_map = {} <add> for i in range(paragraph_len): <add> index = len(truncated_query) + sequence_added_tokens + i if tokenizer.padding_side == "right" else i <add> token_to_orig_map[index] = tok_to_orig_index[len(spans) * doc_stride + i] <add> <add> encoded_dict["paragraph_len"] = paragraph_len <add> encoded_dict["tokens"] = tokens <add> encoded_dict["token_to_orig_map"] = token_to_orig_map <add> encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens <add> encoded_dict["token_is_max_context"] = {} <add> encoded_dict["start"] = len(spans) * doc_stride <add> encoded_dict["length"] = paragraph_len <add> <add> spans.append(encoded_dict) <add> <add> if "overflowing_tokens" not in encoded_dict: <add> break <add> span_doc_tokens = encoded_dict["overflowing_tokens"] <add> <add> for doc_span_index in range(len(spans)): <add> for j in range(spans[doc_span_index]["paragraph_len"]): <add> is_max_context = _new_check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j) <add> index = j if tokenizer.padding_side == "left" else spans[doc_span_index][ <add> "truncated_query_with_special_tokens_length"] + j <add> spans[doc_span_index]["token_is_max_context"][index] = is_max_context <add> <add> for span in spans: <add> # Identify the position of the CLS token <add> cls_index = span['input_ids'].index(tokenizer.cls_token_id) <add> <add> # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) <add> # Original TF implem also keep the classification token (set to 0) (not sure why...) <add> p_mask = np.array(span['token_type_ids']) <add> <add> p_mask = np.minimum(p_mask, 1) <add> <add> if tokenizer.padding_side == "right": <add> # Limit positive values to one <add> p_mask = 1 - p_mask <add> <add> p_mask[np.where(np.array(span["input_ids"]) == tokenizer.sep_token_id)[0]] = 1 <add> <add> # Set the CLS index to '0' <add> p_mask[cls_index] = 0 <add> <add> span_is_impossible = example.is_impossible <add> start_position = 0 <add> end_position = 0 <add> if is_training and not span_is_impossible: <add> # For training, if our document chunk does not contain an annotation <add> # we throw it out, since there is nothing to predict. <add> doc_start = span["start"] <add> doc_end = span["start"] + span["length"] - 1 <add> out_of_span = False <add> <add> if not (tok_start_position >= doc_start and tok_end_position <= doc_end): <add> out_of_span = True <add> <add> if out_of_span: <add> start_position = cls_index <add> end_position = cls_index <add> span_is_impossible = True <add> else: <add> if tokenizer.padding_side == "left": <add> doc_offset = 0 <add> else: <add> doc_offset = len(truncated_query) + sequence_added_tokens <add> <add> start_position = tok_start_position - doc_start + doc_offset <add> end_position = tok_end_position - doc_start + doc_offset <add> <add> features.append(SquadFeatures( <add> span['input_ids'], <add> span['attention_mask'], <add> span['token_type_ids'], <add> cls_index, <add> p_mask.tolist(), <add> example_index=0, <add> unique_id=0, <add> paragraph_len=span['paragraph_len'], <add> token_is_max_context=span["token_is_max_context"], <add> tokens=span["tokens"], <add> token_to_orig_map=span["token_to_orig_map"], <add> <add> start_position=start_position, <add> end_position=end_position <add> )) <add> return features <add> <add>def squad_convert_example_to_features_init(tokenizer_for_convert): <add> global tokenizer <add> tokenizer = tokenizer_for_convert <add> <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> doc_stride, max_query_length, is_training, <del> return_dataset=False): <add> return_dataset=False, threads=1): <ide> """ <ide> Converts a list of examples into a list of features that can be directly given as input to a model. <ide> It is model-dependant and takes advantage of many of the tokenizer's features to create the model's inputs. <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> return_dataset: Default False. Either 'pt' or 'tf'. <ide> if 'pt': returns a torch.data.TensorDataset, <ide> if 'tf': returns a tf.data.Dataset <add> threads: multiple processing threadsa-smi <add> <ide> <ide> Returns: <ide> list of :class:`~transformers.data.processors.squad.SquadFeatures` <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> """ <ide> <ide> # Defining helper methods <del> unique_id = 1000000000 <del> <ide> features = [] <del> for (example_index, example) in enumerate(tqdm(examples)): <del> if is_training and not example.is_impossible: <del> # Get start and end position <del> start_position = example.start_position <del> end_position = example.end_position <del> <del> # If the answer cannot be found in the text, then skip this example. <del> actual_text = " ".join(example.doc_tokens[start_position:(end_position + 1)]) <del> cleaned_answer_text = " ".join(whitespace_tokenize(example.answer_text)) <del> if actual_text.find(cleaned_answer_text) == -1: <del> logger.warning("Could not find answer: '%s' vs. '%s'", actual_text, cleaned_answer_text) <del> continue <del> <del> <del> tok_to_orig_index = [] <del> orig_to_tok_index = [] <del> all_doc_tokens = [] <del> for (i, token) in enumerate(example.doc_tokens): <del> orig_to_tok_index.append(len(all_doc_tokens)) <del> sub_tokens = tokenizer.tokenize(token) <del> for sub_token in sub_tokens: <del> tok_to_orig_index.append(i) <del> all_doc_tokens.append(sub_token) <del> <del> if is_training and not example.is_impossible: <del> tok_start_position = orig_to_tok_index[example.start_position] <del> if example.end_position < len(example.doc_tokens) - 1: <del> tok_end_position = orig_to_tok_index[example.end_position + 1] - 1 <del> else: <del> tok_end_position = len(all_doc_tokens) - 1 <del> <del> (tok_start_position, tok_end_position) = _improve_answer_span( <del> all_doc_tokens, tok_start_position, tok_end_position, tokenizer, example.answer_text <del> ) <del> <del> spans = [] <del> <del> truncated_query = tokenizer.encode(example.question_text, add_special_tokens=False, max_length=max_query_length) <del> sequence_added_tokens = tokenizer.max_len - tokenizer.max_len_single_sentence + 1 \ <del> if 'roberta' in str(type(tokenizer)) else tokenizer.max_len - tokenizer.max_len_single_sentence <del> sequence_pair_added_tokens = tokenizer.max_len - tokenizer.max_len_sentences_pair <del> <del> span_doc_tokens = all_doc_tokens <del> while len(spans) * doc_stride < len(all_doc_tokens): <del> <del> encoded_dict = tokenizer.encode_plus( <del> truncated_query if tokenizer.padding_side == "right" else span_doc_tokens, <del> span_doc_tokens if tokenizer.padding_side == "right" else truncated_query, <del> max_length=max_seq_length, <del> return_overflowing_tokens=True, <del> pad_to_max_length=True, <del> stride=max_seq_length - doc_stride - len(truncated_query) - sequence_pair_added_tokens, <del> truncation_strategy='only_second' if tokenizer.padding_side == "right" else 'only_first' <del> ) <del> <del> paragraph_len = min(len(all_doc_tokens) - len(spans) * doc_stride, max_seq_length - len(truncated_query) - sequence_pair_added_tokens) <del> <del> if tokenizer.pad_token_id in encoded_dict['input_ids']: <del> non_padded_ids = encoded_dict['input_ids'][:encoded_dict['input_ids'].index(tokenizer.pad_token_id)] <del> else: <del> non_padded_ids = encoded_dict['input_ids'] <del> <del> tokens = tokenizer.convert_ids_to_tokens(non_padded_ids) <del> <del> token_to_orig_map = {} <del> for i in range(paragraph_len): <del> index = len(truncated_query) + sequence_added_tokens + i if tokenizer.padding_side == "right" else i <del> token_to_orig_map[index] = tok_to_orig_index[len(spans) * doc_stride + i] <del> <del> encoded_dict["paragraph_len"] = paragraph_len <del> encoded_dict["tokens"] = tokens <del> encoded_dict["token_to_orig_map"] = token_to_orig_map <del> encoded_dict["truncated_query_with_special_tokens_length"] = len(truncated_query) + sequence_added_tokens <del> encoded_dict["token_is_max_context"] = {} <del> encoded_dict["start"] = len(spans) * doc_stride <del> encoded_dict["length"] = paragraph_len <del> <del> spans.append(encoded_dict) <del> <del> if "overflowing_tokens" not in encoded_dict: <del> break <del> span_doc_tokens = encoded_dict["overflowing_tokens"] <del> <del> for doc_span_index in range(len(spans)): <del> for j in range(spans[doc_span_index]["paragraph_len"]): <del> is_max_context = _new_check_is_max_context(spans, doc_span_index, doc_span_index * doc_stride + j) <del> index = j if tokenizer.padding_side == "left" else spans[doc_span_index]["truncated_query_with_special_tokens_length"] + j <del> spans[doc_span_index]["token_is_max_context"][index] = is_max_context <del> <del> for span in spans: <del> # Identify the position of the CLS token <del> cls_index = span['input_ids'].index(tokenizer.cls_token_id) <del> <del> # p_mask: mask with 1 for token than cannot be in the answer (0 for token which can be in an answer) <del> # Original TF implem also keep the classification token (set to 0) (not sure why...) <del> p_mask = np.array(span['token_type_ids']) <del> <del> p_mask = np.minimum(p_mask, 1) <del> <del> if tokenizer.padding_side == "right": <del> # Limit positive values to one <del> p_mask = 1 - p_mask <del> <del> p_mask[np.where(np.array(span["input_ids"]) == tokenizer.sep_token_id)[0]] = 1 <del> <del> # Set the CLS index to '0' <del> p_mask[cls_index] = 0 <del> <del> <del> span_is_impossible = example.is_impossible <del> start_position = 0 <del> end_position = 0 <del> if is_training and not span_is_impossible: <del> # For training, if our document chunk does not contain an annotation <del> # we throw it out, since there is nothing to predict. <del> doc_start = span["start"] <del> doc_end = span["start"] + span["length"] - 1 <del> out_of_span = False <del> <del> if not (tok_start_position >= doc_start and tok_end_position <= doc_end): <del> out_of_span = True <del> <del> if out_of_span: <del> start_position = cls_index <del> end_position = cls_index <del> span_is_impossible = True <del> else: <del> if tokenizer.padding_side == "left": <del> doc_offset = 0 <del> else: <del> doc_offset = len(truncated_query) + sequence_added_tokens <del> <del> start_position = tok_start_position - doc_start + doc_offset <del> end_position = tok_end_position - doc_start + doc_offset <del> <del> <del> features.append(SquadFeatures( <del> span['input_ids'], <del> span['attention_mask'], <del> span['token_type_ids'], <del> cls_index, <del> p_mask.tolist(), <del> <del> example_index=example_index, <del> unique_id=unique_id, <del> paragraph_len=span['paragraph_len'], <del> token_is_max_context=span["token_is_max_context"], <del> tokens=span["tokens"], <del> token_to_orig_map=span["token_to_orig_map"], <del> <del> start_position=start_position, <del> end_position=end_position <del> )) <del> <add> threads = min(threads, cpu_count()) <add> with Pool(threads, initializer=squad_convert_example_to_features_init, initargs=(tokenizer,)) as p: <add> annotate_ = partial(squad_convert_example_to_features, max_seq_length=max_seq_length, <add> doc_stride=doc_stride, max_query_length=max_query_length, is_training=is_training) <add> features = list(tqdm(p.imap(annotate_, examples, chunksize=32), total=len(examples), desc='convert squad examples to features')) <add> new_features = [] <add> unique_id = 1000000000 <add> example_index = 0 <add> for example_features in tqdm(features, total=len(features), desc='add example index and unique id'): <add> if not example_features: <add> continue <add> for example_feature in example_features: <add> example_feature.example_index = example_index <add> example_feature.unique_id = unique_id <add> new_features.append(example_feature) <ide> unique_id += 1 <del> <add> example_index += 1 <add> features = new_features <add> del new_features <ide> if return_dataset == 'pt': <ide> if not is_torch_available(): <ide> raise ImportError("Pytorch must be installed to return a pytorch dataset.") <ide> def squad_convert_examples_to_features(examples, tokenizer, max_seq_length, <ide> all_cls_index, all_p_mask) <ide> <ide> return features, dataset <del> <ide> <ide> return features <ide>
2
Python
Python
fix some compiler_cxx errors
9913769d0719b6cfca1b3d51baee8421ba7cf288
<ide><path>numpy/distutils/ccompiler.py <ide> def CCompiler_customize(self, dist, need_cxx=0): <ide> except ValueError: <ide> pass <ide> <del> if hasattr(self,'compiler') and self.compiler[0].find('gcc')>=0: <del> if sys.version[:3]>='2.3': <del> if not self.compiler_cxx: <del> self.compiler_cxx = [self.compiler[0].replace('gcc','g++')]\ <del> + self.compiler[1:] <del> else: <del> self.compiler_cxx = [self.compiler[0].replace('gcc','g++')]\ <add> if hasattr(self,'compiler') and self.compiler[0].find('cc')>=0: <add> if not self.compiler_cxx: <add> if self.compiler[0][:3] == 'gcc': <add> a, b = 'gcc', 'g++' <add> else: <add> a, b = 'cc', 'c++' <add> self.compiler_cxx = [self.compiler[0].replace(a,b)]\ <ide> + self.compiler[1:] <ide> else: <add> if hasattr(self,'compiler'): <add> log.warn("#### %s #######" % (self.compiler,)) <ide> log.warn('Missing compiler_cxx fix for '+self.__class__.__name__) <ide> return <ide>
1
Text
Text
add @linkgoron to collaborators
eaf0f0f1b57adbd1d1acac4b8aba54d29ceab36f
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> **Chengzhong Wu** &lt;legendecas@gmail.com&gt; (he/him) <ide> * [Leko](https://github.com/Leko) - <ide> **Shingo Inoue** &lt;leko.noor@gmail.com&gt; (he/him) <add>* [linkgoron](https://github.com/linkgoron) - <add>**Nitzan Uziely** &lt;linkgoron@gmail.com&gt; <ide> * [lpinca](https://github.com/lpinca) - <ide> **Luigi Pinca** &lt;luigipinca@gmail.com&gt; (he/him) <ide> * [lundibundi](https://github.com/lundibundi) -
1
Python
Python
allow unicode message for exception raised in task
108b36230263cdbd392ceaf62377f88226fa7301
<ide><path>celery/backends/base.py <ide> from celery.exceptions import ( <ide> ChordError, TimeoutError, TaskRevokedError, ImproperlyConfigured, <ide> ) <del>from celery.five import items <add>from celery.five import items, string <ide> from celery.result import ( <ide> GroupResult, ResultBase, allow_join_result, result_from_tuple, <ide> ) <ide> def prepare_exception(self, exc, serializer=None): <ide> serializer = self.serializer if serializer is None else serializer <ide> if serializer in EXCEPTION_ABLE_CODECS: <ide> return get_pickleable_exception(exc) <del> return {'exc_type': type(exc).__name__, 'exc_message': str(exc)} <add> return {'exc_type': type(exc).__name__, 'exc_message': string(exc)} <ide> <ide> def exception_to_python(self, exc): <ide> """Convert serialized exception to Python exception.""" <ide><path>t/unit/backends/test_base.py <ide> def test_regular(self): <ide> y = self.b.exception_to_python(x) <ide> assert isinstance(y, KeyError) <ide> <add> def test_unicode_message(self): <add> message = u'\u03ac' <add> x = self.b.prepare_exception(Exception(message)) <add> assert x == {'exc_message': message, 'exc_type': 'Exception'} <add> <ide> <ide> class KVBackend(KeyValueStoreBackend): <ide> mget_returns_dict = False
2
PHP
PHP
fix style ci
91e517370e1700629f7f2be252da0f0fe62cce0e
<ide><path>src/Illuminate/Console/Scheduling/ScheduleTestCommand.php <ide> public function handle(Schedule $schedule) <ide> $commandBinary = Application::phpBinary().' '.Application::artisanBinary(); <ide> <ide> $matches = array_filter($commandNames, function ($commandName) use ($commandBinary, $name) { <del> return trim(Str::replace($commandBinary, '', $commandName)) === $name; <add> return trim(Str::replace($commandBinary, '', $commandName)) === $name; <ide> }); <ide> <ide> if (count($matches) !== 1) {
1
Javascript
Javascript
use khandle symbol for accessing native handle
e7f58868b5ea1312f7bac4f152f4d928b64e0202
<ide><path>lib/internal/http2/core.js <ide> const { <ide> updateSettingsBuffer <ide> } = require('internal/http2/util'); <ide> const { <del> createWriteWrap, <ide> writeGeneric, <ide> writevGeneric, <ide> onStreamRead, <ide> kAfterAsyncWrite, <ide> kMaybeDestroy, <ide> kUpdateTimer, <add> kHandle, <ide> kSession, <ide> setStreamTimeout <ide> } = require('internal/stream_base_commons'); <ide> const TLSServer = tls.Server; <ide> const kAlpnProtocol = Symbol('alpnProtocol'); <ide> const kAuthority = Symbol('authority'); <ide> const kEncrypted = Symbol('encrypted'); <del>const kHandle = Symbol('handle'); <ide> const kID = Symbol('id'); <ide> const kInit = Symbol('init'); <ide> const kInfoHeaders = Symbol('sent-info-headers'); <ide> class Http2Stream extends Duplex { <ide> if (!this.headersSent) <ide> this[kProceed](); <ide> <del> const req = createWriteWrap(this[kHandle]); <del> req.stream = this[kID]; <add> let req; <ide> <ide> if (writev) <del> writevGeneric(this, req, data, cb); <add> req = writevGeneric(this, data, cb); <ide> else <del> writeGeneric(this, req, data, encoding, cb); <add> req = writeGeneric(this, data, encoding, cb); <ide> <ide> trackWriteState(this, req.bytes); <ide> } <ide><path>lib/internal/stream_base_commons.js <ide> const { <ide> const kMaybeDestroy = Symbol('kMaybeDestroy'); <ide> const kUpdateTimer = Symbol('kUpdateTimer'); <ide> const kAfterAsyncWrite = Symbol('kAfterAsyncWrite'); <del>const kSession = Symbol('session'); <add>const kHandle = Symbol('kHandle'); <add>const kSession = Symbol('kSession'); <ide> <ide> function handleWriteReq(req, data, encoding) { <ide> const { handle } = req; <ide> function createWriteWrap(handle) { <ide> return req; <ide> } <ide> <del>function writevGeneric(self, req, data, cb) { <add>function writevGeneric(self, data, cb) { <add> const req = createWriteWrap(self[kHandle]); <ide> var allBuffers = data.allBuffers; <ide> var chunks; <ide> var i; <ide> function writevGeneric(self, req, data, cb) { <ide> if (err === 0) req._chunks = chunks; <ide> <ide> afterWriteDispatched(self, req, err, cb); <add> return req; <ide> } <ide> <del>function writeGeneric(self, req, data, encoding, cb) { <add>function writeGeneric(self, data, encoding, cb) { <add> const req = createWriteWrap(self[kHandle]); <ide> var err = handleWriteReq(req, data, encoding); <ide> <ide> afterWriteDispatched(self, req, err, cb); <add> return req; <ide> } <ide> <ide> function afterWriteDispatched(self, req, err, cb) { <ide> module.exports = { <ide> kAfterAsyncWrite, <ide> kMaybeDestroy, <ide> kUpdateTimer, <add> kHandle, <ide> kSession, <ide> setStreamTimeout <ide> }; <ide><path>lib/net.js <ide> const { <ide> symbols: { async_id_symbol, owner_symbol } <ide> } = require('internal/async_hooks'); <ide> const { <del> createWriteWrap, <ide> writevGeneric, <ide> writeGeneric, <ide> onStreamRead, <ide> kAfterAsyncWrite, <add> kHandle, <ide> kUpdateTimer, <ide> setStreamTimeout <ide> } = require('internal/stream_base_commons'); <ide> function Socket(options) { <ide> // probably be supplied by async_hooks. <ide> this[async_id_symbol] = -1; <ide> this._hadError = false; <del> this._handle = null; <add> this[kHandle] = null; <ide> this._parent = null; <ide> this._host = null; <ide> this[kLastWriteQueueSize] = 0; <ide> Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { <ide> <ide> this._unrefTimer(); <ide> <del> var req = createWriteWrap(this._handle); <add> let req; <ide> if (writev) <del> writevGeneric(this, req, data, cb); <add> req = writevGeneric(this, data, cb); <ide> else <del> writeGeneric(this, req, data, encoding, cb); <add> req = writeGeneric(this, data, encoding, cb); <ide> if (req.async) <ide> this[kLastWriteQueueSize] = req.bytes; <ide> }; <ide> Object.defineProperty(TCP.prototype, 'owner', { <ide> set(v) { return this[owner_symbol] = v; } <ide> }); <ide> <add>Object.defineProperty(Socket.prototype, '_handle', { <add> get() { return this[kHandle]; }, <add> set(v) { return this[kHandle] = v; } <add>}); <add> <ide> <ide> Server.prototype.listenFD = internalUtil.deprecate(function(fd, type) { <ide> return this.listen({ fd: fd });
3
PHP
PHP
normalize url generation
52318f9d17c8b5c7a1ba838fadd07e9457041a89
<ide><path>cake/libs/router.php <ide> function normalize($url = '/') { <ide> $paths = Router::getPaths(); <ide> <ide> if (!empty($paths['base']) && stristr($url, $paths['base'])) { <del> $url = str_replace($paths['base'], '', $url); <add> $url = preg_replace("/{$paths['base']}/", '', $url, 1); <ide> } <ide> $url = '/' . $url; <ide> <ide><path>cake/tests/cases/libs/router.test.php <ide> function testUrlNormalization() { <ide> <ide> $result = Router::normalize('/recipe/recipes/add'); <ide> $this->assertEqual($result, '/recipe/recipes/add'); <add> <add> Router::setRequestInfo(array(array(), array('base' => 'us'))); <add> $result = Router::normalize('/us/users/logout/'); <add> $this->assertEqual($result, '/users/logout'); <add> <ide> } <ide> /** <ide> * testUrlGeneration method
2
Ruby
Ruby
add test for update_counters with empty touch
afa2da6456c0e33c1c31dbbcee66f72fd8f32005
<ide><path>activerecord/test/cases/counter_cache_test.rb <ide> class ::SpecialReply < ::Reply <ide> assert_equal previously_updated_at, @topic.updated_at <ide> end <ide> <add> test "update counters doesn't touch timestamps with touch: []" do <add> @topic.update_column :updated_at, 5.minutes.ago <add> previously_updated_at = @topic.updated_at <add> <add> Topic.update_counters(@topic.id, replies_count: -1, touch: []) <add> <add> assert_equal previously_updated_at, @topic.updated_at <add> end <add> <ide> test "update counters with touch: true" do <ide> assert_touching @topic, :updated_at do <ide> Topic.update_counters(@topic.id, replies_count: -1, touch: true)
1
Python
Python
use prepare_expires in other backends as well
e482db8eaca05a01f34fb3382d998cf8669c05b7
<ide><path>celery/backends/amqp.py <ide> import threading <ide> import time <ide> <del>from datetime import timedelta <ide> from itertools import count <ide> <ide> from kombu.entity import Exchange, Queue <ide> from celery import states <ide> from celery.backends.base import BaseDictBackend <ide> from celery.exceptions import TimeoutError <del>from celery.utils import timeutils <ide> <ide> <ide> class BacklogLimitExceeded(Exception): <ide> def __init__(self, connection=None, exchange=None, exchange_type=None, <ide> self.auto_delete = auto_delete <ide> self.expires = (conf.CELERY_AMQP_TASK_RESULT_EXPIRES if expires is None <ide> else expires) <del> if isinstance(self.expires, timedelta): <del> self.expires = timeutils.timedelta_seconds(self.expires) <ide> if self.expires is not None: <del> self.expires = int(self.expires) <add> self.expires = self.prepare_expires(self.expires) <ide> # x-expires requires RabbitMQ 2.1.0 or higher. <ide> self.queue_arguments["x-expires"] = self.expires * 1000.0 <ide> self.connection_max = (connection_max or <ide><path>celery/backends/cache.py <del>from datetime import timedelta <del> <ide> from kombu.utils import cached_property <ide> <ide> from celery.backends.base import KeyValueStoreBackend <ide> from celery.exceptions import ImproperlyConfigured <del>from celery.utils import timeutils <ide> from celery.datastructures import LocalCache <ide> <ide> _imp = [None] <ide> class CacheBackend(KeyValueStoreBackend): <ide> def __init__(self, expires=None, backend=None, options={}, **kwargs): <ide> super(CacheBackend, self).__init__(self, **kwargs) <ide> <del> self.expires = expires or self.app.conf.CELERY_TASK_RESULT_EXPIRES <del> if isinstance(self.expires, timedelta): <del> self.expires = timeutils.timedelta_seconds(self.expires) <ide> self.options = dict(self.app.conf.CELERY_CACHE_BACKEND_OPTIONS, <ide> **options) <ide> <ide> backend = backend or self.app.conf.CELERY_CACHE_BACKEND <del> self.expires = int(self.expires) <ide> self.backend, _, servers = backend.partition("://") <add> self.expires = self.prepare_expires(expires, type=int) <ide> self.servers = servers.rstrip('/').split(";") <ide> try: <ide> self.Client = backends[self.backend]() <ide><path>celery/backends/cassandra.py <ide> def __init__(self, servers=None, keyspace=None, column_family=None, <ide> self.logger = self.app.log.setup_logger( <ide> name="celery.backends.cassandra") <ide> <del> self.result_expires = kwargs.get("result_expires") or \ <del> maybe_timedelta( <add> self.expires = kwargs.get("expires") or maybe_timedelta( <ide> self.app.conf.CELERY_TASK_RESULT_EXPIRES) <ide> <ide> if not pycassa: <ide> def _do_store(): <ide> "date_done": date_done.strftime('%Y-%m-%dT%H:%M:%SZ'), <ide> "traceback": pickle.dumps(traceback)} <ide> cf.insert(task_id, meta, <del> ttl=timedelta_seconds(self.result_expires)) <add> ttl=timedelta_seconds(self.expires)) <ide> <ide> return self._retry_on_error(_do_store) <ide> <ide><path>celery/backends/database.py <ide> def _sqlalchemy_installed(): <ide> class DatabaseBackend(BaseDictBackend): <ide> """The database result backend.""" <ide> <del> def __init__(self, dburi=None, result_expires=None, <add> def __init__(self, dburi=None, expires=None, <ide> engine_options=None, **kwargs): <ide> super(DatabaseBackend, self).__init__(**kwargs) <del> self.result_expires = result_expires or \ <del> maybe_timedelta( <del> self.app.conf.CELERY_TASK_RESULT_EXPIRES) <add> self.expires = maybe_timedelta(self.prepare_expires(expires)) <ide> self.dburi = dburi or self.app.conf.CELERY_RESULT_DBURI <ide> self.engine_options = dict(engine_options or {}, <ide> **self.app.conf.CELERY_RESULT_ENGINE_OPTIONS or {}) <ide> def _forget(self, task_id): <ide> def cleanup(self): <ide> """Delete expired metadata.""" <ide> session = self.ResultSession() <del> expires = self.result_expires <add> expires = self.expires <ide> try: <ide> session.query(Task).filter( <ide> Task.date_done < (datetime.now() - expires)).delete() <ide><path>celery/backends/mongodb.py <ide> def __init__(self, *args, **kwargs): <ide> <ide> """ <ide> super(MongoBackend, self).__init__(*args, **kwargs) <del> self.result_expires = kwargs.get("result_expires") or \ <del> maybe_timedelta( <add> self.expires = kwargs.get("expires") or maybe_timedelta( <ide> self.app.conf.CELERY_TASK_RESULT_EXPIRES) <ide> <ide> if not pymongo: <ide> def cleanup(self): <ide> taskmeta_collection = db[self.mongodb_taskmeta_collection] <ide> taskmeta_collection.remove({ <ide> "date_done": { <del> "$lt": datetime.now() - self.result_expires, <add> "$lt": datetime.now() - self.expires, <ide> } <ide> }) <ide><path>celery/utils/timeutils.py <ide> <ide> def maybe_timedelta(delta): <ide> """Coerces integer to timedelta if `delta` is an integer.""" <del> if isinstance(delta, int): <add> if isinstance(delta, (int, float)): <ide> return timedelta(seconds=delta) <ide> return delta <ide>
6
Text
Text
fix the russian title
f55b1c614645f58a19a92d82b053e55961fd12fa
<ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/basic-javascript/accessing-object-properties-with-variables.russian.md <ide> title: Accessing Object Properties with Variables <ide> challengeType: 1 <ide> guideUrl: 'https://russian.freecodecamp.org/guide/certificates/accessing-objects-properties-with-variables' <ide> videoUrl: '' <del>localeTitle: Доступ к объектам с переменными <add>localeTitle: Доступ к свойствам объектов с переменными <ide> --- <ide> <ide> ## Description
1
PHP
PHP
fix some valdiation rules
8f2c68f838de27e38b3ae9819aba233a562f6616
<ide><path>src/Illuminate/Validation/Validator.php <ide> protected function validateSame($attribute, $value, $parameters) <ide> <ide> $other = Arr::get($this->data, $parameters[0]); <ide> <del> return isset($other) && $value == $other; <add> return isset($other) && $value === $other; <ide> } <ide> <ide> /** <ide> protected function validateDifferent($attribute, $value, $parameters) <ide> <ide> $other = Arr::get($this->data, $parameters[0]); <ide> <del> return isset($other) && $value != $other; <add> return isset($other) && $value !== $other; <ide> } <ide> <ide> /** <ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateConfirmed() <ide> <ide> $v = new Validator($trans, ['password' => 'foo', 'password_confirmation' => 'foo'], ['password' => 'Confirmed']); <ide> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['password' => '1e2', 'password_confirmation' => '100'], ['password' => 'Confirmed']); <add> $this->assertFalse($v->passes()); <ide> } <ide> <ide> public function testValidateSame() <ide> public function testValidateSame() <ide> <ide> $v = new Validator($trans, ['foo' => 'bar', 'baz' => 'bar'], ['foo' => 'Same:baz']); <ide> $this->assertTrue($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => '1e2', 'baz' => '100'], ['foo' => 'Same:baz']); <add> $this->assertFalse($v->passes()); <ide> } <ide> <ide> public function testValidateDifferent() <ide> public function testValidateDifferent() <ide> <ide> $v = new Validator($trans, ['foo' => 'bar', 'baz' => 'bar'], ['foo' => 'Different:baz']); <ide> $this->assertFalse($v->passes()); <add> <add> $v = new Validator($trans, ['foo' => '1e2', 'baz' => '100'], ['foo' => 'Different:baz']); <add> $this->assertTrue($v->passes()); <ide> } <ide> <ide> public function testValidateAccepted()
2
Javascript
Javascript
add missing class annotations and lock xplat/js
0ccbe5f70463b5259ae1adcb65deeb89204b1948
<ide><path>Libraries/Lists/FlatList.js <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> } <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> componentDidUpdate(prevProps: Props<ItemT>) { <ide> invariant( <ide> prevProps.numColumns === this.props.numColumns, <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> this._listRef = ref; <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _checkProps(props: Props<ItemT>) { <ide> const { <ide> // $FlowFixMe[prop-missing] this prop doesn't exist, is only used for an invariant <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> ); <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getItem = (data: Array<ItemT>, index: number) => { <ide> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> if (numColumns > 1) { <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> } <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _keyExtractor = (items: ItemT | Array<ItemT>, index: number) => { <ide> const numColumns = numColumnsOrDefault(this.props.numColumns); <ide> const keyExtractor = this.props.keyExtractor ?? defaultKeyExtractor; <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> changed: Array<ViewToken>, <ide> ... <ide> }) => void, <add> // $FlowFixMe[missing-local-annot] <ide> ) { <ide> return (info: { <ide> viewableItems: Array<ViewToken>, <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> columnWrapperStyle: ?ViewStyleProp, <ide> numColumns: ?number, <ide> extraData: ?any, <add> // $FlowFixMe[missing-local-annot] <ide> ) => { <ide> const cols = numColumnsOrDefault(numColumns); <ide> <ide> class FlatList<ItemT> extends React.PureComponent<Props<ItemT>, void> { <ide> }; <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _memoizedRenderer = memoizeOne(this._renderer); <ide> <ide> render(): React.Node { <ide><path>Libraries/Lists/VirtualizedList.js <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> viewOffset?: number, <ide> viewPosition?: number, <ide> ... <del> }) { <add> }): $FlowFixMe { <ide> const { <ide> data, <ide> horizontal, <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> }; <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getScrollMetrics = () => { <ide> return this._scrollMetrics; <ide> }; <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> return this._hasMore; <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getOutermostParentListRef = () => { <ide> if (this._isNestedWithSameOrientation()) { <ide> return this.context.getOutermostParentListRef(); <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> _getSpacerKey = (isVertical: boolean): string => <ide> isVertical ? 'height' : 'width'; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _keyExtractor(item: Item, index: number) { <ide> if (this.props.keyExtractor != null) { <ide> return this.props.keyExtractor(item, index); <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> > = new Map(); <ide> _offsetFromParentVirtualizedList: number = 0; <ide> _prevParentOffset: number = 0; <add> // $FlowFixMe[missing-local-annot] <ide> _scrollMetrics = { <ide> contentLength: 0, <ide> dOffset: 0, <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> ); <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getCellsInItemCount = (props: Props) => { <ide> const {getCellsInItemCount, data} = props; <ide> if (getCellsInItemCount) { <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> this._headerLength = this._selectLength(e.nativeEvent.layout); <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _renderDebugOverlay() { <ide> const normalize = <ide> this._scrollMetrics.visibleLength / <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> visibleLength: number, <ide> offset: number, <ide> ... <del> }) => { <add> }): $FlowFixMe => { <ide> // Offset of the top of the nested list relative to the top of its parent's viewport <ide> const offset = metrics.offset - this._offsetFromParentVirtualizedList; <ide> // Child's visible length is the same as its parent's <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> }); <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _createViewToken = (index: number, isViewable: boolean) => { <ide> const {data, getItem} = this.props; <ide> const item = getItem(data, index); <ide> class CellRenderer extends React.Component< <ide> CellRendererProps, <ide> CellRendererState, <ide> > { <add> // $FlowFixMe[missing-local-annot] <ide> state = { <ide> separatorProps: { <ide> highlighted: false, <ide> class CellRenderer extends React.Component< <ide> <ide> // TODO: consider factoring separator stuff out of VirtualizedList into FlatList since it's not <ide> // reused by SectionList and we can keep VirtualizedList simpler. <add> // $FlowFixMe[missing-local-annot] <ide> _separators = { <ide> highlight: () => { <ide> const {cellKey, prevCellKey} = this.props; <ide> class CellRenderer extends React.Component< <ide> ListItemComponent: any, <ide> item: any, <ide> index: any, <add> // $FlowFixMe[missing-local-annot] <ide> ) { <ide> if (renderItem && ListItemComponent) { <ide> console.warn( <ide> class CellRenderer extends React.Component< <ide> ); <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> render() { <ide> const { <ide> CellRendererComponent, <ide><path>Libraries/Lists/VirtualizedList_EXPERIMENTAL.js <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> viewOffset?: number, <ide> viewPosition?: number, <ide> ... <del> }) { <add> }): $FlowFixMe { <ide> const { <ide> data, <ide> horizontal, <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> }; <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getScrollMetrics = () => { <ide> return this._scrollMetrics; <ide> }; <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> return this._hasMore; <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getOutermostParentListRef = () => { <ide> if (this._isNestedWithSameOrientation()) { <ide> return this.context.getOutermostParentListRef(); <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> keyExtractor?: ?(item: Item, index: number) => string, <ide> ... <ide> }, <add> // $FlowFixMe[missing-local-annot] <ide> ) { <ide> if (props.keyExtractor != null) { <ide> return props.keyExtractor(item, index); <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> > = new Map(); <ide> _offsetFromParentVirtualizedList: number = 0; <ide> _prevParentOffset: number = 0; <add> // $FlowFixMe[missing-local-annot] <ide> _scrollMetrics = { <ide> contentLength: 0, <ide> dOffset: 0, <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> ); <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _getCellsInItemCount = (props: Props) => { <ide> const {getCellsInItemCount, data} = props; <ide> if (getCellsInItemCount) { <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> this._headerLength = this._selectLength(e.nativeEvent.layout); <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _renderDebugOverlay() { <ide> const normalize = <ide> this._scrollMetrics.visibleLength / <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> visibleLength: number, <ide> offset: number, <ide> ... <del> }) => { <add> }): $FlowFixMe => { <ide> // Offset of the top of the nested list relative to the top of its parent's viewport <ide> const offset = metrics.offset - this._offsetFromParentVirtualizedList; <ide> // Child's visible length is the same as its parent's <ide> class VirtualizedList extends React.PureComponent<Props, State> { <ide> index: number, <ide> isViewable: boolean, <ide> props: FrameMetricProps, <add> // $FlowFixMe[missing-local-annot] <ide> ) => { <ide> const {data, getItem} = props; <ide> const item = getItem(data, index); <ide> class CellRenderer extends React.Component< <ide> CellRendererProps, <ide> CellRendererState, <ide> > { <add> // $FlowFixMe[missing-local-annot] <ide> state = { <ide> separatorProps: { <ide> highlighted: false, <ide> class CellRenderer extends React.Component< <ide> <ide> // TODO: consider factoring separator stuff out of VirtualizedList into FlatList since it's not <ide> // reused by SectionList and we can keep VirtualizedList simpler. <add> // $FlowFixMe[missing-local-annot] <ide> _separators = { <ide> highlight: () => { <ide> const {cellKey, prevCellKey} = this.props; <ide> class CellRenderer extends React.Component< <ide> ListItemComponent: any, <ide> item: any, <ide> index: any, <add> // $FlowFixMe[missing-local-annot] <ide> ) { <ide> if (renderItem && ListItemComponent) { <ide> console.warn( <ide> class CellRenderer extends React.Component< <ide> ); <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> render() { <ide> const { <ide> CellRendererComponent, <ide><path>Libraries/Lists/VirtualizedSectionList.js <ide> class VirtualizedSectionList< <ide> return null; <ide> } <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _keyExtractor = (item: Item, index: number) => { <ide> const info = this._subExtractor(index); <ide> return (info && info.key) || String(index); <ide> class VirtualizedSectionList< <ide> }; <ide> <ide> _renderItem = <del> (listItemCount: number) => <add> (listItemCount: number): $FlowFixMe => <ide> // eslint-disable-next-line react/no-unstable-nested-components <ide> ({ <ide> item, <ide><path>packages/rn-tester/js/examples/FlatList/FlatList-basic.js <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> this._listRef.scrollToIndex({viewPosition: 0.5, index: Number(text)}); <ide> }; <ide> <add> // $FlowFixMe[missing-local-annot] <ide> _scrollPos = new Animated.Value(0); <add> // $FlowFixMe[missing-local-annot] <ide> _scrollSinkX = Animated.event( <ide> [{nativeEvent: {contentOffset: {x: this._scrollPos}}}], <ide> {useNativeDriver: true}, <ide> ); <add> // $FlowFixMe[missing-local-annot] <ide> _scrollSinkY = Animated.event( <ide> [{nativeEvent: {contentOffset: {y: this._scrollPos}}}], <ide> {useNativeDriver: true}, <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> ) => { <ide> this._listRef = ref; <ide> }; <add> // $FlowFixMe[missing-local-annot] <ide> _getItemLayout = (data: any, index: number) => { <ide> return getItemLayout(data, index, this.state.horizontal); <ide> }; <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> data: state.data.concat(genItemData(100, state.data.length)), <ide> })); <ide> }; <add> // $FlowFixMe[missing-local-annot] <ide> _onPressCallback = () => { <ide> const {onPressDisabled} = this.state; <ide> const warning = () => console.log('onPress disabled'); <ide> const onPressAction = onPressDisabled ? warning : this._pressItem; <ide> return onPressAction; <ide> }; <add> // $FlowFixMe[missing-local-annot] <ide> _onRefresh = () => Alert.alert('onRefresh: nothing to refresh :P'); <add> // $FlowFixMe[missing-local-annot] <ide> _renderItemComponent = () => { <ide> const flatListPropKey = this.state.useFlatListItemComponent <ide> ? 'ListItemComponent' <ide><path>packages/rn-tester/js/examples/FlatList/FlatList-multiColumn.js <ide> class MultiColumnExample extends React.PureComponent< <ide> item: Item, <ide> accessibilityCollectionItem: AccessibilityCollectionItem, <ide> ... <del> }) => { <add> }): $FlowFixMe => { <ide> return ( <ide> <View <ide> importantForAccessibility="yes"
6
Javascript
Javascript
improve punycode test coverage
c6238e2761e9ba5c35aa4842c9be2ae937d28998
<ide><path>test/parallel/test-punycode.js <ide> assert.strictEqual(punycode.ucs2.encode([0xDC00]), '\uDC00'); <ide> assert.strictEqual(punycode.ucs2.encode([0xDC00, 0x61, 0x62]), '\uDC00ab'); <ide> <ide> assert.strictEqual(errors, 0); <add> <add>// test map domain <add>assert.strictEqual(punycode.toASCII('Bücher@日本語.com'), <add> 'Bücher@xn--wgv71a119e.com'); <add>assert.strictEqual(punycode.toUnicode('Bücher@xn--wgv71a119e.com'), <add> 'Bücher@日本語.com');
1
Text
Text
clarify esm conditional exports prose
db3b209e7df254794873be5ac91345dee034e130
<ide><path>doc/api/esm.md <ide> For example, a package that wants to provide different ES module exports for <ide> } <ide> ``` <ide> <del>Node.js supports the following conditions: <add>Node.js supports the following conditions out of the box: <ide> <ide> * `"import"` - matched when the package is loaded via `import` or <ide> `import()`. Can reference either an ES module or CommonJS file, as both <ide> Node.js supports the following conditions: <ide> * `"default"` - the generic fallback that will always match. Can be a CommonJS <ide> or ES module file. _This condition should always come last._ <ide> <del>Condition matching is applied in object order from first to last within the <del>`"exports"` object. _The general rule is that conditions should be used <del>from most specific to least specific in object order._ <add>Within the `"exports"` object, key order is significant. During condition <add>matching, earlier entries have higher priority and take precedence over later <add>entries. _The general rule is that conditions should be from most specific to <add>least specific in object order_. <ide> <ide> Other conditions such as `"browser"`, `"electron"`, `"deno"`, `"react-native"`, <del>etc. are ignored by Node.js but may be used by other runtimes or tools. <del>Further restrictions, definitions or guidance on condition names may be <del>provided in the future. <add>etc. are unknown to, and thus ignored by Node.js. Runtimes or tools other than <add>Node.js may use them at their discretion. Further restrictions, definitions, or <add>guidance on condition names may occur in the future. <ide> <ide> Using the `"import"` and `"require"` conditions can lead to some hazards, <del>which are explained further in <del>[the dual CommonJS/ES module packages section][]. <add>which are further explained in [the dual CommonJS/ES module packages section][]. <ide> <ide> Conditional exports can also be extended to exports subpaths, for example: <ide> <ide> The `conditions` property on the `context` is an array of conditions for <ide> for looking up conditional mappings elsewhere or to modify the list when calling <ide> the default resolution logic. <ide> <del>The [current set of Node.js default conditions][Conditional exports] will always <del>be in the `context.conditions` list passed to the hook. If the hook wants to <del>ensure Node.js-compatible resolution logic, all items from this default <del>condition list **must** be passed through to the `defaultResolve` function. <add>The current [package exports conditions][Conditional Exports] will always be in <add>the `context.conditions` array passed into the hook. To guarantee _default <add>Node.js module specifier resolution behavior_ when calling `defaultResolve`, the <add>`context.conditions` array passed to it _must_ include _all_ elements of the <add>`context.conditions` array originally passed into the `resolve` hook. <ide> <ide> ```js <ide> /**
1
Javascript
Javascript
replace anonymous closure with arrow funct
d88e26de8e1b8d4b337290ffd712543c1ef53de9
<ide><path>test/parallel/test-http-server-stale-close.js <ide> if (process.env.NODE_TEST_FORK_PORT) { <ide> req.write('BAM'); <ide> req.end(); <ide> } else { <del> const server = http.createServer(function(req, res) { <add> const server = http.createServer((req, res) => { <ide> res.writeHead(200, { 'Content-Length': '42' }); <ide> req.pipe(res); <del> req.on('close', function() { <add> req.on('close', () => { <ide> server.close(); <ide> res.end(); <ide> });
1
Javascript
Javascript
append .eslintignore paths to grunt eslint paths
a22b43bad41592ec61e5fa0fcd2b3a3d44f8bfd3
<ide><path>Gruntfile.js <ide> module.exports = function( grunt ) { <ide> var fs = require( "fs" ), <ide> gzip = require( "gzip-js" ), <ide> isTravis = process.env.TRAVIS, <del> travisBrowsers = process.env.BROWSERS && process.env.BROWSERS.split( "," ); <add> travisBrowsers = process.env.BROWSERS && process.env.BROWSERS.split( "," ), <add> CLIEngine = require( "eslint" ).CLIEngine; <ide> <ide> if ( !grunt.option( "filename" ) ) { <ide> grunt.option( "filename", "jquery.js" ); <ide> module.exports = function( grunt ) { <ide> }, <ide> eslint: { <ide> options: { <del> <del> // See https://github.com/sindresorhus/grunt-eslint/issues/119 <del> quiet: true <add> maxWarnings: 0 <ide> }, <ide> <ide> // We have to explicitly declare "src" property otherwise "newer" <ide> module.exports = function( grunt ) { <ide> src: [ "dist/jquery.js", "dist/jquery.min.js" ] <ide> }, <ide> dev: { <del> src: [ "src/**/*.js", "Gruntfile.js", "test/**/*.js", "build/**/*.js" ] <add> src: [ <add> "src/**/*.js", <add> "Gruntfile.js", <add> "test/**/*.js", <add> "build/**/*.js", <add> <add> // Ignore files from .eslintignore <add> // See https://github.com/sindresorhus/grunt-eslint/issues/119 <add> ...new CLIEngine() <add> .getConfigForFile( "Gruntfile.js" ) <add> .ignorePatterns.map( ( p ) => `!${ p }` ) <add> ] <ide> } <ide> }, <ide> testswarm: {
1
PHP
PHP
add pool() method to cache
c259c5507fd00a1368baa7ec3c8c0b08ad5ff6a8
<ide><path>src/Cache/Cache.php <ide> public static function engine($config) <ide> return $registry->{$config}; <ide> } <ide> <add> /** <add> * Get a SimpleCacheEngine object for the named cache pool. <add> * <add> * @param string $pool The name of the configured cache backend. <add> * @return \Cake\Cache\SimpleCacheEngine <add> */ <add> public static function pool($config) <add> { <add> return new SimpleCacheEngine(static::engine($config)); <add> } <add> <ide> /** <ide> * Garbage collection <ide> * <ide><path>tests/TestCase/Cache/CacheTest.php <ide> use Cake\TestSuite\TestCase; <ide> use InvalidArgumentException; <ide> use PHPUnit\Framework\Error\Error; <add>use Psr\SimpleCache\CacheInterface as SimpleCacheInterface; <ide> <ide> /** <ide> * CacheTest class <ide> public function testSetAndGetRegistry() <ide> <ide> $this->assertSame($registry, Cache::getRegistry()); <ide> } <add> <add> /** <add> * Test getting instances with pool <add> * <add> * @return void <add> */ <add> public function testPool() <add> { <add> $this->_configCache(); <add> <add> $pool = Cache::pool('tests'); <add> $this->assertInstanceOf(SimpleCacheInterface::class, $pool); <add> } <add> <add> /** <add> * Test getting instances with pool <add> * <add> * @return void <add> */ <add> public function testPoolCacheDisabled() <add> { <add> Cache::disable(); <add> $pool = Cache::pool('tests'); <add> $this->assertInstanceOf(SimpleCacheInterface::class, $pool); <add> } <ide> }
2
Python
Python
test empty warning for split with manual inputs
f29c387272a9279f82ab04bbbe1bb68040b6d383
<ide><path>numpy/lib/tests/test_shape_base.py <ide> def test_integer_split_2D_rows(self): <ide> compare_results(res, desired) <ide> assert_(a.dtype.type is res[-1].dtype.type) <ide> <add> # Same thing for manual splits: <add> res = assert_warns(FutureWarning, array_split, a, [0, 1, 2], axis=0) <add> <add> # After removing the FutureWarning, the last should be zeros((0, 10)) <add> desired = [np.array([]), np.array([np.arange(10)]), <add> np.array([np.arange(10)])] <add> compare_results(res, desired) <add> assert_(a.dtype.type is res[-1].dtype.type) <add> <ide> def test_integer_split_2D_cols(self): <ide> a = np.array([np.arange(10), np.arange(10)]) <ide> res = array_split(a, 3, axis=-1)
1
Go
Go
fix progress reader output on close
aa3083f577224ad74384f648b17c1474ab47b44f
<ide><path>pkg/progressreader/progressreader.go <ide> package progressreader <ide> <ide> import ( <add> "io" <add> <ide> "github.com/docker/docker/pkg/jsonmessage" <ide> "github.com/docker/docker/pkg/streamformatter" <del> "io" <ide> ) <ide> <ide> // Reader with progress bar <ide> func (config *Config) Read(p []byte) (n int, err error) { <ide> return read, err <ide> } <ide> func (config *Config) Close() error { <add> config.Current = config.Size <ide> config.Out.Write(config.Formatter.FormatProgress(config.ID, config.Action, &jsonmessage.JSONProgress{Current: config.Current, Total: config.Size})) <ide> return config.In.Close() <ide> }
1
Javascript
Javascript
fix bug in directionallighthelper
82dd6c5a237aab59e1261ec114a5e40c82f00cfc
<ide><path>src/extras/helpers/DirectionalLightHelper.js <ide> THREE.DirectionalLightHelper = function ( light, sphereSize ) { <ide> this.targetLine = new THREE.Line( lineGeometry, lineMaterial ); <ide> this.targetLine.properties.isGizmo = true; <ide> <add> } <add> else { <add> <add> this.targetSphere = null; <add> <ide> } <ide> <ide> // <ide> THREE.DirectionalLightHelper.prototype.update = function () { <ide> this.lightSphere.material.color.copy( this.color ); <ide> this.lightRays.material.color.copy( this.color ); <ide> <del> this.targetSphere.material.color.copy( this.color ); <del> this.targetLine.material.color.copy( this.color ); <add> // Only update targetSphere and targetLine if available <add> if ( this.targetSphere ) { <ide> <del> // update target line vertices <add> this.targetSphere.material.color.copy( this.color ); <add> this.targetLine.material.color.copy( this.color ); <ide> <del> this.targetLine.geometry.vertices[ 0 ].copy( this.light.position ); <del> this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position ); <add> // update target line vertices <ide> <del> this.targetLine.geometry.computeLineDistances(); <del> this.targetLine.geometry.verticesNeedUpdate = true; <add> this.targetLine.geometry.vertices[ 0 ].copy( this.light.position ); <add> this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position ); <add> <add> this.targetLine.geometry.computeLineDistances(); <add> this.targetLine.geometry.verticesNeedUpdate = true; <add> <add> } <ide> <ide> } <ide>
1
Javascript
Javascript
add support for json files to `js_file` rule
ef91708fdbe1aee274833137e386ebf93bff6bc8
<ide><path>packager/react-packager/src/ModuleGraph/worker.js <ide> <ide> // RUNS UNTRANSFORMED IN A WORKER PROCESS. ONLY USE NODE 4 COMPATIBLE FEATURES! <ide> <del>const fs = require('fs'); <del>const dirname = require('path').dirname; <del> <ide> const babel = require('babel-core'); <del>const generate = require('babel-generator').default; <del> <del>const mkdirp = require('mkdirp'); <del>const series = require('async/series'); <del>const sourceMap = require('source-map'); <del> <add>const babelGenerate = require('babel-generator').default; <ide> const collectDependencies = require('../JSTransformer/worker/collect-dependencies'); <ide> const constantFolding = require('../JSTransformer/worker/constant-folding').plugin; <add>const docblock = require('../node-haste/DependencyGraph/docblock'); <add>const fs = require('fs'); <ide> const inline = require('../JSTransformer/worker/inline').plugin; <ide> const minify = require('../JSTransformer/worker/minify'); <add>const mkdirp = require('mkdirp'); <add>const path = require('path'); <add>const series = require('async/series'); <add>const sourceMap = require('source-map'); <ide> <del>const docblock = require('../node-haste/DependencyGraph/docblock'); <add>const basename = path.basename; <add>const dirname = path.dirname; <add>const defaultVariants = {default: {}}; <add>const moduleFactoryParameters = ['require', 'module', 'global', 'exports']; <add> <add>function transformJSON(infile, options, outfile, callback) { <add> let json, value; <add> try { <add> json = fs.readFileSync(infile, 'utf8'); <add> value = JSON.parse(json); <add> } catch (readError) { <add> callback(readError); <add> return; <add> } <add> <add> const filename = options.filename || infile; <add> const code = <add> `__d(function(${moduleFactoryParameters.join(', ')}) { module.exports = \n${ <add> json <add> }\n})`; <add> <add> const moduleData = { <add> code, <add> map: null, // no source map for JSON files! <add> dependencies: [], <add> }; <add> const transformed = {}; <add> <add> Object <add> .keys(options.variants || defaultVariants) <add> .forEach(key => (transformed[key] = moduleData)); <add> <add> const result = { <add> file: filename, <add> code: json, <add> transformed, <add> hasteID: value.name, <add> }; <add> <add> if (basename(filename) === 'package.json') { <add> result.package = { <add> name: value.name, <add> browser: value.browser, <add> 'react-native': value['react-native'], <add> }; <add> } <add> <add> try { <add> writeResult(outfile, result); <add> } catch (writeError) { <add> callback(writeError); <add> return; <add> } <add> <add> callback(null); <add>} <ide> <ide> function transformModule(infile, options, outfile, callback) { <add> const filename = options.filename || infile; <add> if (filename.endsWith('.json')) { <add> return transformJSON(infile, options, outfile, callback); <add> } <add> <ide> let code, transform; <ide> try { <ide> transform = require(options.transform); <ide> function transformModule(infile, options, outfile, callback) { <ide> return; <ide> } <ide> <del> const filename = options.filename || infile; <del> const variants = options.variants || {default: {}}; <del> <add> const variants = options.variants || defaultVariants; <ide> const tasks = {}; <ide> Object.keys(variants).forEach(name => { <ide> tasks[name] = cb => transform({ <ide> function makeResult(ast, filename, sourceCode) { <ide> const dependencies = collectDependencies(ast); <ide> const file = wrapModule(ast); <ide> <del> const gen = generate(file, { <del> comments: false, <del> compact: true, <del> filename, <del> sourceMaps: true, <del> sourceMapTarget: filename, <del> sourceFileName: filename, <del> }, sourceCode); <add> const gen = generate(file, filename, sourceCode); <ide> return {code: gen.code, map: gen.map, dependencies}; <ide> } <ide> <ide> function wrapModule(file) { <ide> const p = file.program; <ide> const t = babel.types; <del> const factory = t.functionExpression(t.identifier(''), [ <del> t.identifier('require'), <del> t.identifier('module'), <del> t.identifier('global'), <del> t.identifier('exports') <del> ], t.blockStatement(p.body, p.directives)); <add> const factory = t.functionExpression( <add> t.identifier(''), <add> moduleFactoryParameters.map(makeIdentifier), <add> t.blockStatement(p.body, p.directives), <add> ); <ide> const def = t.callExpression(t.identifier('__d'), [factory]); <ide> return t.file(t.program([t.expressionStatement(def)])); <ide> } <ide> function optimize(transformed, file, originalCode, options) { <ide> const dependencies = collectDependencies.forOptimization( <ide> optimized.ast, transformed.dependencies); <ide> <del> const gen = generate(optimized.ast, { <add> const inputMap = transformed.map; <add> const gen = generate(optimized.ast, file, originalCode); <add> <add> const min = minify( <add> file, <add> gen.code, <add> inputMap && mergeSourceMaps(file, inputMap, gen.map), <add> ); <add> return {code: min.code, map: inputMap && min.map, dependencies}; <add>} <add> <add>function optimizeCode(code, map, filename, options) { <add> const inlineOptions = Object.assign({isWrapped: true}, options); <add> return babel.transform(code, { <add> plugins: [[constantFolding], [inline, inlineOptions]], <add> babelrc: false, <add> code: false, <add> filename, <add> }); <add>} <add> <add>function generate(ast, filename, sourceCode) { <add> return babelGenerate(ast, { <ide> comments: false, <ide> compact: true, <del> filename: file, <add> filename, <add> sourceFileName: filename, <ide> sourceMaps: true, <del> sourceMapTarget: file, <del> sourceFileName: file, <del> }, originalCode); <add> sourceMapTarget: filename, <add> }, sourceCode); <add>} <ide> <add>function mergeSourceMaps(file, originalMap, secondMap) { <ide> const merged = new sourceMap.SourceMapGenerator(); <del> const inputMap = new sourceMap.SourceMapConsumer(transformed.map); <del> new sourceMap.SourceMapConsumer(gen.map) <add> const inputMap = new sourceMap.SourceMapConsumer(originalMap); <add> new sourceMap.SourceMapConsumer(secondMap) <ide> .eachMapping(mapping => { <ide> const original = inputMap.originalPositionFor({ <ide> line: mapping.originalLine, <ide> function optimize(transformed, file, originalCode, options) { <ide> name: original.name || mapping.name, <ide> }); <ide> }); <del> <del> const min = minify(file, gen.code, merged.toJSON()); <del> return {code: min.code, map: min.map, dependencies}; <del>} <del> <del>function optimizeCode(code, map, filename, options) { <del> const inlineOptions = Object.assign({isWrapped: true}, options); <del> return babel.transform(code, { <del> plugins: [[constantFolding], [inline, inlineOptions]], <del> babelrc: false, <del> code: false, <del> filename, <del> }); <add> return merged.toJSON(); <ide> } <ide> <ide> function writeResult(outfile, result) { <ide> mkdirp.sync(dirname(outfile)); <ide> fs.writeFileSync(outfile, JSON.stringify(result), 'utf8'); <ide> } <ide> <add>function makeIdentifier(name) { <add> return babel.types.identifier(name); <add>} <add> <ide> exports.transformModule = transformModule; <ide> exports.optimizeModule = optimizeModule;
1
Python
Python
remove unique1d, setmember1d and intersect1d_nu
44ae46c70d0b9cb4909bfafe1e4dbef3cd90f5b9
<ide><path>numpy/lib/arraysetops.py <ide> union1d, <ide> setdiff1d <ide> <del>:Deprecated: <del> unique1d, <del> intersect1d_nu, <del> setmember1d <del> <ide> :Notes: <ide> <ide> For floating point arrays, inaccurate results may appear due to usual round-off <ide> <ide> :Author: Robert Cimrman <ide> """ <del>__all__ = ['ediff1d', 'unique1d', 'intersect1d', 'intersect1d_nu', 'setxor1d', <del> 'setmember1d', 'union1d', 'setdiff1d', 'unique', 'in1d'] <add>__all__ = ['ediff1d', 'intersect1d', 'setxor1d', 'union1d', 'setdiff1d', <add> 'unique', 'in1d'] <ide> <ide> import numpy as np <ide> from numpy.lib.utils import deprecate <ide> def setdiff1d(ar1, ar2, assume_unique=False): <ide> return aux <ide> else: <ide> return np.asarray(ar1)[aux == 0] <del> <del>@deprecate <del>def unique1d(ar1, return_index=False, return_inverse=False): <del> """ <del> This function is deprecated. Use unique() instead. <del> """ <del> if return_index: <del> import warnings <del> warnings.warn("The order of the output arguments for " <del> "`return_index` has changed. Before, " <del> "the output was (indices, unique_arr), but " <del> "has now been reversed to be more consistent.") <del> <del> ar = np.asanyarray(ar1).flatten() <del> if ar.size == 0: <del> if return_inverse and return_index: <del> return ar, np.empty(0, np.bool), np.empty(0, np.bool) <del> elif return_inverse or return_index: <del> return ar, np.empty(0, np.bool) <del> else: <del> return ar <del> <del> if return_inverse or return_index: <del> perm = ar.argsort() <del> aux = ar[perm] <del> flag = np.concatenate(([True], aux[1:] != aux[:-1])) <del> if return_inverse: <del> iflag = np.cumsum(flag) - 1 <del> iperm = perm.argsort() <del> if return_index: <del> return aux[flag], perm[flag], iflag[iperm] <del> else: <del> return aux[flag], iflag[iperm] <del> else: <del> return aux[flag], perm[flag] <del> <del> else: <del> ar.sort() <del> flag = np.concatenate(([True], ar[1:] != ar[:-1])) <del> return ar[flag] <del> <del>@deprecate <del>def intersect1d_nu(ar1, ar2): <del> """ <del> This function is deprecated. Use intersect1d() <del> instead. <del> """ <del> # Might be faster than unique1d( intersect1d( ar1, ar2 ) )? <del> aux = np.concatenate((unique1d(ar1), unique1d(ar2))) <del> aux.sort() <del> return aux[aux[1:] == aux[:-1]] <del> <del>@deprecate <del>def setmember1d(ar1, ar2): <del> """ <del> This function is deprecated. Use in1d(assume_unique=True) <del> instead. <del> """ <del> # We need this to be a stable sort, so always use 'mergesort' here. The <del> # values from the first array should always come before the values from the <del> # second array. <del> ar = np.concatenate( (ar1, ar2 ) ) <del> order = ar.argsort(kind='mergesort') <del> sar = ar[order] <del> equal_adj = (sar[1:] == sar[:-1]) <del> flag = np.concatenate( (equal_adj, [False] ) ) <del> <del> indx = order.argsort(kind='mergesort')[:len( ar1 )] <del> return flag[indx] <ide><path>numpy/lib/benchmarks/bench_arraysetops.py <del>import numpy as np <del>import time <del>from numpy.lib.arraysetops import * <del> <del>def bench_unique1d( plot_results = False ): <del> exponents = np.linspace( 2, 7, 9 ) <del> ratios = [] <del> nItems = [] <del> dt1s = [] <del> dt2s = [] <del> for ii in exponents: <del> <del> nItem = 10 ** ii <del> print 'using %d items:' % nItem <del> a = np.fix( nItem / 10 * np.random.random( nItem ) ) <del> <del> print 'unique:' <del> tt = time.clock() <del> b = np.unique( a ) <del> dt1 = time.clock() - tt <del> print dt1 <del> <del> print 'unique1d:' <del> tt = time.clock() <del> c = unique1d( a ) <del> dt2 = time.clock() - tt <del> print dt2 <del> <del> <del> if dt1 < 1e-8: <del> ratio = 'ND' <del> else: <del> ratio = dt2 / dt1 <del> print 'ratio:', ratio <del> print 'nUnique: %d == %d\n' % (len( b ), len( c )) <del> <del> nItems.append( nItem ) <del> ratios.append( ratio ) <del> dt1s.append( dt1 ) <del> dt2s.append( dt2 ) <del> <del> assert np.alltrue( b == c ) <del> <del> print nItems <del> print dt1s <del> print dt2s <del> print ratios <del> <del> if plot_results: <del> import pylab <del> <del> def plotMe( fig, fun, nItems, dt1s, dt2s ): <del> pylab.figure( fig ) <del> fun( nItems, dt1s, 'g-o', linewidth = 2, markersize = 8 ) <del> fun( nItems, dt2s, 'b-x', linewidth = 2, markersize = 8 ) <del> pylab.legend( ('unique', 'unique1d' ) ) <del> pylab.xlabel( 'nItem' ) <del> pylab.ylabel( 'time [s]' ) <del> <del> plotMe( 1, pylab.loglog, nItems, dt1s, dt2s ) <del> plotMe( 2, pylab.plot, nItems, dt1s, dt2s ) <del> pylab.show() <del> <del>if __name__ == '__main__': <del> bench_unique1d( plot_results = True ) <ide><path>numpy/lib/tests/test_arraysetops.py <ide> def test_unique( self ): <ide> assert_array_equal( c, ec ) <ide> <ide> vals, indices = unique( a, return_index=True ) <del> <add> <ide> <ide> ed = np.array( [2, 3, 0, 1] ) <ide> assert_array_equal(vals, ec) <ide> assert_array_equal(indices, ed) <ide> <ide> vals, ind0, ind1 = unique( a, return_index=True, <ide> return_inverse=True ) <del> <add> <ide> <ide> ee = np.array( [2, 3, 0, 1, 0, 2, 3] ) <ide> assert_array_equal(vals, ec) <ide> def test_intersect1d( self ): <ide> <ide> assert_array_equal([], intersect1d([],[])) <ide> <del> def test_intersect1d_nu( self ): <del> # This should be removed when intersect1d_nu is removed. <del> a = np.array( [5, 5, 7, 1, 2] ) <del> b = np.array( [2, 1, 4, 3, 3, 1, 5] ) <del> <del> ec = np.array( [1, 2, 5] ) <del> warnings.filterwarnings('ignore', message='\s*`intersect1d_nu` is deprecated!') <del> warnings.filterwarnings('ignore', message='\s*`unique1d` is deprecated!') <del> c = intersect1d_nu( a, b ) <del> assert_array_equal( c, ec ) <del> assert_array_equal([], intersect1d_nu([],[])) <del> warnings.filters.pop(0) <del> warnings.filters.pop(0) <del> <del> <ide> def test_setxor1d( self ): <ide> a = np.array( [5, 7, 1, 2] ) <ide> b = np.array( [2, 4, 3, 1, 5] ) <ide> def test_ediff1d(self): <ide> assert_array_equal([],ediff1d(one_elem)) <ide> assert_array_equal([1],ediff1d(two_elem)) <ide> <del> def test_setmember1d( self ): <del> # This should be removed when setmember1d is removed. <del> a = np.array( [5, 7, 1, 2] ) <del> b = np.array( [2, 4, 3, 1, 5] ) <del> <del> ec = np.array( [True, False, True, True] ) <del> warnings.filterwarnings('ignore', '\s*`setmember1d` is deprecated!') <del> c = setmember1d( a, b ) <del> <del> assert_array_equal( c, ec ) <del> <del> a[0] = 8 <del> ec = np.array( [False, False, True, True] ) <del> c = setmember1d( a, b ) <del> assert_array_equal( c, ec ) <del> <del> a[0], a[3] = 4, 8 <del> ec = np.array( [True, False, True, False] ) <del> c = setmember1d( a, b ) <del> assert_array_equal( c, ec ) <del> <del> assert_array_equal([], setmember1d([],[])) <del> warnings.filters.pop(0) <del> <ide> def test_in1d(self): <ide> a = np.array( [5, 7, 1, 2] ) <ide> b = np.array( [2, 4, 3, 1, 5] ) <ide> def test_in1d(self): <ide> ec = np.array( [True, False, True, False] ) <ide> c = in1d( a, b, assume_unique=True ) <ide> assert_array_equal( c, ec ) <del> <add> <ide> a = np.array([5,4,5,3,4,4,3,4,3,5,2,1,5,5]) <ide> b = [2,3,4] <ide> <ide><path>numpy/ma/extras.py <ide> def intersect1d(ar1, ar2, assume_unique=False): <ide> if assume_unique: <ide> aux = ma.concatenate((ar1, ar2)) <ide> else: <del> # Might be faster than unique1d( intersect1d( ar1, ar2 ) )? <add> # Might be faster than unique( intersect1d( ar1, ar2 ) )? <ide> aux = ma.concatenate((unique(ar1), unique(ar2))) <ide> aux.sort() <ide> return aux[aux[1:] == aux[:-1]] <ide> def flatnotmasked_edges(a): <ide> <ide> See Also <ide> -------- <del> flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges, <add> flatnotmasked_contiguous, notmasked_contiguous, notmasked_edges, <ide> clump_masked, clump_unmasked <ide> <ide> Notes <ide> def flatnotmasked_contiguous(a): <ide> >>> a = np.ma.arange(10) <ide> >>> np.ma.extras.flatnotmasked_contiguous(a) <ide> slice(0, 10, None) <del> <add> <ide> >>> mask = (a < 3) | (a > 8) | (a == 5) <ide> >>> a[mask] = np.ma.masked <ide> >>> np.array(a[~a.mask]) <ide> def clump_unmasked(a): <ide> <ide> See Also <ide> -------- <del> flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, <add> flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, <ide> notmasked_contiguous, clump_masked <ide> <ide> Examples <ide> def clump_masked(a): <ide> <ide> See Also <ide> -------- <del> flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, <add> flatnotmasked_edges, flatnotmasked_contiguous, notmasked_edges, <ide> notmasked_contiguous, clump_unmasked <ide> <ide> Examples
4
Java
Java
add `clienthttprequestinitializer` support
5d785390eb4fae08922d2d98f61a31e617cd0115
<ide><path>spring-web/src/main/java/org/springframework/http/client/ClientHttpRequestInitializer.java <add>/* <add> * Copyright 2002-2019 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.http.client; <add> <add>import org.springframework.http.client.support.HttpAccessor; <add> <add>/** <add> * Callback interface for initializing a {@link ClientHttpRequest} prior to it <add> * being used. <add> * <add> * <p> Typically used with {@link HttpAccessor} and subclasses such as <add> * {@link org.springframework.web.client.RestTemplate RestTemplate} to apply <add> * consistent settings or headers to each request. <add> * <add> * <p>Unlike {@link ClientHttpRequestInterceptor}, this interface can apply <add> * customizations without needing to read the entire request body into memory. <add> * <add> * @author Phillip Webb <add> * @since 5.2 <add> * @see HttpAccessor#getClientHttpRequestInitializers() <add> */ <add>@FunctionalInterface <add>public interface ClientHttpRequestInitializer { <add> <add> /** <add> * Initialize the given client HTTP request. <add> * @param request the request to configure <add> */ <add> void initialize(ClientHttpRequest request); <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/http/client/support/HttpAccessor.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2019 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> import java.io.IOException; <ide> import java.net.URI; <add>import java.util.ArrayList; <add>import java.util.List; <ide> <ide> import org.apache.commons.logging.Log; <ide> <add>import org.springframework.core.annotation.AnnotationAwareOrderComparator; <ide> import org.springframework.http.HttpLogging; <ide> import org.springframework.http.HttpMethod; <ide> import org.springframework.http.client.ClientHttpRequest; <ide> import org.springframework.http.client.ClientHttpRequestFactory; <add>import org.springframework.http.client.ClientHttpRequestInitializer; <ide> import org.springframework.http.client.SimpleClientHttpRequestFactory; <ide> import org.springframework.util.Assert; <ide> <ide> public abstract class HttpAccessor { <ide> <ide> private ClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); <ide> <add> private List<ClientHttpRequestInitializer> clientHttpRequestInitializers = new ArrayList<>(); <add> <ide> <ide> /** <ide> * Set the request factory that this accessor uses for obtaining client request handles. <ide> public ClientHttpRequestFactory getRequestFactory() { <ide> } <ide> <ide> <add> /** <add> * Set the request initializers the this accessor should use. <add> * <p>The initializers will get sorted according to their order <add> * before the {@link ClientHttpRequest} is initialized. <add> */ <add> public void setClientHttpRequestInitializers( <add> List<ClientHttpRequestInitializer> clientHttpRequestInitializers) { <add> if (this.clientHttpRequestInitializers != clientHttpRequestInitializers) { <add> this.clientHttpRequestInitializers.clear(); <add> this.clientHttpRequestInitializers.addAll(clientHttpRequestInitializers); <add> AnnotationAwareOrderComparator.sort(this.clientHttpRequestInitializers); <add> } <add> } <add> <add> /** <add> * Return the request initializers that this accessor uses. <add> * <p>The returned {@link List} is active and may get appended to. <add> */ <add> public List<ClientHttpRequestInitializer> getClientHttpRequestInitializers() { <add> return this.clientHttpRequestInitializers; <add> } <add> <ide> /** <ide> * Create a new {@link ClientHttpRequest} via this template's {@link ClientHttpRequestFactory}. <ide> * @param url the URL to connect to <ide> public ClientHttpRequestFactory getRequestFactory() { <ide> */ <ide> protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException { <ide> ClientHttpRequest request = getRequestFactory().createRequest(url, method); <add> initialize(request); <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("HTTP " + method.name() + " " + url); <ide> } <ide> return request; <ide> } <ide> <add> private void initialize(ClientHttpRequest request) { <add> this.clientHttpRequestInitializers.forEach( <add> initializer -> initializer.initialize(request)); <add> } <add> <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/client/RestTemplateTests.java <ide> import org.springframework.http.ResponseEntity; <ide> import org.springframework.http.client.ClientHttpRequest; <ide> import org.springframework.http.client.ClientHttpRequestFactory; <add>import org.springframework.http.client.ClientHttpRequestInitializer; <ide> import org.springframework.http.client.ClientHttpRequestInterceptor; <ide> import org.springframework.http.client.ClientHttpResponse; <ide> import org.springframework.http.converter.GenericHttpMessageConverter; <ide> public void requestInterceptorCanAddExistingHeaderValueWithBody() throws Excepti <ide> verify(response).close(); <ide> } <ide> <add> @Test <add> public void clientHttpRequestInitializerAndRequestInterceptorAreBothApplied() throws Exception { <add> ClientHttpRequestInitializer initializer = request -> <add> request.getHeaders().add("MyHeader", "MyInitializerValue"); <add> ClientHttpRequestInterceptor interceptor = (request, body, execution) -> { <add> request.getHeaders().add("MyHeader", "MyInterceptorValue"); <add> return execution.execute(request, body); <add> }; <add> template.setClientHttpRequestInitializers(Collections.singletonList(initializer)); <add> template.setInterceptors(Collections.singletonList(interceptor)); <add> <add> MediaType contentType = MediaType.TEXT_PLAIN; <add> given(converter.canWrite(String.class, contentType)).willReturn(true); <add> HttpHeaders requestHeaders = new HttpHeaders(); <add> mockSentRequest(POST, "https://example.com", requestHeaders); <add> mockResponseStatus(HttpStatus.OK); <add> <add> HttpHeaders entityHeaders = new HttpHeaders(); <add> entityHeaders.setContentType(contentType); <add> HttpEntity<String> entity = new HttpEntity<>("Hello World", entityHeaders); <add> template.exchange("https://example.com", POST, entity, Void.class); <add> assertThat(requestHeaders.get("MyHeader")).contains("MyInterceptorValue", "MyInitializerValue"); <add> <add> verify(response).close(); <add> } <add> <ide> private void mockSentRequest(HttpMethod method, String uri) throws Exception { <ide> mockSentRequest(method, uri, new HttpHeaders()); <ide> }
3
Javascript
Javascript
use module alias, don't break module bindings
c959fc5cc68b83621371f713b4926ec09f7b5abd
<ide><path>packages/ember-metal/lib/computed.js <ide> import Ember from 'ember-metal/core'; <ide> import { set } from 'ember-metal/property_set'; <ide> import { inspect } from 'ember-metal/utils'; <del>import { meta } from 'ember-metal/meta'; <add>import { meta as metaFor } from 'ember-metal/meta'; <ide> import expandProperties from 'ember-metal/expand_properties'; <ide> import EmberError from 'ember-metal/error'; <ide> import { <ide> import { <ide> @submodule ember-metal <ide> */ <ide> <del>var metaFor = meta; <ide> <ide> function UNDEFINED() { } <ide>
1
Javascript
Javascript
deprecate some usage of netinfo
bca825ee50d6ca343ce704086dff5841312a7f8b
<ide><path>Libraries/Network/NetInfo.js <ide> type ConnectivityStateAndroid = $Enum<{ <ide> <ide> const _subscriptions = new Map(); <ide> <del>let _isConnected; <add>let _isConnectedDeprecated; <ide> if (Platform.OS === 'ios') { <del> _isConnected = function( <add> _isConnectedDeprecated = function( <ide> reachability: ReachabilityStateIOS, <ide> ): bool { <ide> return reachability !== 'none' && reachability !== 'unknown'; <ide> }; <ide> } else if (Platform.OS === 'android') { <del> _isConnected = function( <add> _isConnectedDeprecated = function( <ide> connectionType: ConnectivityStateAndroid, <ide> ): bool { <ide> return connectionType !== 'NONE' && connectionType !== 'UNKNOWN'; <ide> }; <ide> } <ide> <add>function _isConnected(connection) { <add> return connection.type !== 'none' && connection.type !== 'unknown'; <add>} <add> <ide> const _isConnectedSubscriptions = new Map(); <ide> <ide> /** <ide> const NetInfo = { <ide> handler: Function <ide> ): {remove: () => void} { <ide> const listener = (connection) => { <del> handler(_isConnected(connection)); <add> if (eventName === 'change') { <add> handler(_isConnectedDeprecated(connection)); <add> } else if (eventName === 'connectionChange') { <add> handler(_isConnected(connection)); <add> } <ide> }; <ide> _isConnectedSubscriptions.set(handler, listener); <ide> NetInfo.addEventListener( <ide> const NetInfo = { <ide> }, <ide> <ide> fetch(): Promise<any> { <del> return NetInfo.fetch().then( <del> (connection) => _isConnected(connection) <del> ); <add> return NetInfo.getConnectionInfo().then(_isConnected); <ide> }, <ide> }, <ide>
1
Go
Go
fix cross compilation breakage
48a7860211cdb0b087658fc684ebd0f8168fb16e
<ide><path>libnetwork/ipams/windowsipam/windowsipam.go <ide> import ( <ide> "net" <ide> <ide> log "github.com/Sirupsen/logrus" <add> "github.com/docker/libnetwork/discoverapi" <ide> "github.com/docker/libnetwork/ipamapi" <ide> "github.com/docker/libnetwork/types" <ide> ) <ide> func (a *allocator) ReleaseAddress(poolID string, address net.IP) error { <ide> log.Debugf("ReleaseAddress(%s, %v)", poolID, address) <ide> return nil <ide> } <add> <add>// DiscoverNew informs the allocator about a new global scope datastore <add>func (a *allocator) DiscoverNew(dType discoverapi.DiscoveryType, data interface{}) error { <add> return nil <add>} <add> <add>// DiscoverDelete is a notification of no interest for the allocator <add>func (a *allocator) DiscoverDelete(dType discoverapi.DiscoveryType, data interface{}) error { <add> return nil <add>}
1
Javascript
Javascript
add "烘焙帮" case
8770fd9c11300e0adf1eb7d5193a6a57178e68be
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.plasticaromantica.utayomin', <ide> author: 'Takayuki IMAI' <ide> }, <add> { <add> name: '烘焙帮', <add> icon: 'http://a1.mzstatic.com/us/r30/Purple69/v4/79/85/ba/7985ba1d-a807-7c34-98f1-e9e2ed5d2cb5/icon175x175.jpeg', <add> linkAppStore: 'https://itunes.apple.com/cn/app/hong-bei-bang-hai-liang-hong/id1007812319?mt=8', <add> author: 'Hongbeibang' <add> }, <ide> ]; <ide> <ide> var AppList = React.createClass({
1
Python
Python
generalize the setting of macosx_deployment_target
56a6330e2a69392a7e230f4b0417f9cc623b8dde
<ide><path>numpy/distutils/fcompiler/gnu.py <ide> import re <ide> import os <add>import platform <ide> import sys <ide> import warnings <ide> <ide> class GnuFCompiler(FCompiler): <ide> def get_flags_linker_so(self): <ide> opt = self.linker_so[1:] <ide> if sys.platform=='darwin': <add> osx_version = platform.mac_ver()[0][:4] <add> osx_major, osx_minor = osx_version.split('.') <ide> target = os.environ.get('MACOSX_DEPLOYMENT_TARGET', None) <del> if target is None: <del> target = '10.3' <add> if target is None or target == '': <add> target = osx_version <ide> major, minor = target.split('.') <ide> if int(minor) < 3: <del> minor = '3' <add> minor = osx_minor <ide> warnings.warn('Environment variable ' <del> 'MACOSX_DEPLOYMENT_TARGET reset to 10.3') <add> 'MACOSX_DEPLOYMENT_TARGET reset to %s.%s' % (major, minor)) <ide> os.environ['MACOSX_DEPLOYMENT_TARGET'] = '%s.%s' % (major, <ide> minor) <ide>
1
Text
Text
update code order to help with confusion
00f047728b390f54dbba2ceea43db64238f1b8d8
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/es6/use-destructuring-assignment-with-the-rest-parameter-to-reassign-array-elements.md <ide> Variables `a` and `b` take the first and second values from the array. After tha <ide> <ide> # --instructions-- <ide> <del>Use destructuring assignment with the rest parameter to perform an effective `Array.prototype.slice()` so that `arr` is a sub-array of the original array `source` with the first two elements omitted. <add>Use a destructuring assignment with the rest parameter to emulate the behavior of `Array.prototype.slice()`. `removeFirstTwo()` should return a sub-array of the original array `list` with the first two elements omitted. <ide> <ide> # --hints-- <ide> <del>`arr` should be `[3,4,5,6,7,8,9,10]` <add>`removeFirstTwo([1, 2, 3, 4, 5])` should be `[3, 4, 5]` <ide> <ide> ```js <del>assert(arr.every((v, i) => v === i + 3) && arr.length === 8); <add>const testArr_ = [1, 2, 3, 4, 5]; <add>const testArrWORemoved_ = removeFirstTwo(testArr_); <add>assert(testArrWORemoved_.every((e, i) => e === i + 3) && testArrWORemoved_.length === 3); <ide> ``` <ide> <del>`source` should be `[1,2,3,4,5,6,7,8,9,10]` <add>`removeFirstTwo()` should not modify `list` <ide> <ide> ```js <del>assert(source.every((v, i) => v === i + 1) && source.length === 10); <add>const testArr_ = [1, 2, 3, 4, 5]; <add>const testArrWORemoved_ = removeFirstTwo(testArr_); <add>assert(testArr_.every((e, i) => e === i + 1) && testArr_.length === 5); <ide> ``` <ide> <ide> `Array.slice()` should not be used. <ide> Destructuring on `list` should be used. <ide> assert( <ide> __helpers <ide> .removeWhiteSpace(code) <del> .match(/\[(([_$a-z]\w*)?,){1,}\.\.\.arr\]=list/i) <add> .match(/\[(([_$a-z]\w*)?,){1,}\.\.\.shorterList\]=list/i) <ide> ); <ide> ``` <ide> <ide> assert( <ide> ## --seed-contents-- <ide> <ide> ```js <del>const source = [1,2,3,4,5,6,7,8,9,10]; <ide> function removeFirstTwo(list) { <ide> // Only change code below this line <del> const arr = list; // Change this line <add> const shorterList = list; // Change this line <ide> // Only change code above this line <del> return arr; <add> return shorterList; <ide> } <del>const arr = removeFirstTwo(source); <add> <add>const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; <add>const sourceWithoutFirstTwo = removeFirstTwo(source); <ide> ``` <ide> <ide> # --solutions-- <ide> <ide> ```js <del>const source = [1,2,3,4,5,6,7,8,9,10]; <ide> function removeFirstTwo(list) { <del> const [, , ...arr] = list; <del> return arr; <add> const [, , ...shorterList] = list; <add> return shorterList; <ide> } <del>const arr = removeFirstTwo(source); <add> <add>const source = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; <add>const sourceWithoutFirstTwo = removeFirstTwo(source); <ide> ```
1
PHP
PHP
apply fixes from styleci
fd53bf979f46e5c9841e07a44a49c7893be58f5c
<ide><path>src/Illuminate/Foundation/Console/EventCacheCommand.php <ide> namespace Illuminate\Foundation\Console; <ide> <ide> use Illuminate\Console\Command; <del>use Illuminate\Support\Collection; <del>use Symfony\Component\Finder\Finder; <del>use Symfony\Component\Finder\SplFileInfo; <ide> use Illuminate\Foundation\Support\Providers\EventServiceProvider; <ide> <ide> class EventCacheCommand extends Command <ide><path>src/Illuminate/Foundation/Console/EventClearCommand.php <ide> <ide> namespace Illuminate\Foundation\Console; <ide> <del>use RuntimeException; <ide> use Illuminate\Console\Command; <ide> use Illuminate\Filesystem\Filesystem; <ide> <ide><path>src/Illuminate/Foundation/Providers/ArtisanServiceProvider.php <ide> use Illuminate\Foundation\Console\ViewCacheCommand; <ide> use Illuminate\Foundation\Console\ViewClearCommand; <ide> use Illuminate\Session\Console\SessionTableCommand; <add>use Illuminate\Contracts\Support\DeferrableProvider; <ide> use Illuminate\Foundation\Console\EventCacheCommand; <ide> use Illuminate\Foundation\Console\EventClearCommand; <del>use Illuminate\Contracts\Support\DeferrableProvider; <ide> use Illuminate\Foundation\Console\PolicyMakeCommand; <ide> use Illuminate\Foundation\Console\RouteCacheCommand; <ide> use Illuminate\Foundation\Console\RouteClearCommand;
3
Text
Text
add unreachable code on events example
cee396ea586c02fd22c438f65d5f0e0ab7f12d67
<ide><path>doc/api/events.md <ide> const { on, EventEmitter } = require('events'); <ide> // if concurrent execution is required. <ide> console.log(event); // prints ['bar'] [42] <ide> } <add> // Unreachable here <ide> })(); <ide> ``` <ide>
1
Go
Go
remove unwanted lock
3342e5591b8cdf0cb8d0dda4fae55881fe2568ed
<ide><path>libnetwork/endpoint_info.go <ide> func (ep *endpoint) AddStaticRoute(destination *net.IPNet, routeType int, nextHo <ide> ep.joinInfo.StaticRoutes = append(ep.joinInfo.StaticRoutes, &r) <ide> } else { <ide> // If the route doesn't specify a next-hop, it must be a connected route, bound to an interface. <del> if err := ep.addInterfaceRoute(&r); err != nil { <del> return err <del> } <add> ep.iface.routes = append(ep.iface.routes, r.Destination) <ide> } <ide> return nil <ide> } <ide> <del>func (ep *endpoint) addInterfaceRoute(route *types.StaticRoute) error { <del> ep.Lock() <del> defer ep.Unlock() <del> <del> iface := ep.iface <del> iface.routes = append(iface.routes, route.Destination) <del> return nil <del>} <del> <ide> func (ep *endpoint) Sandbox() Sandbox { <ide> cnt, ok := ep.getSandbox() <ide> if !ok {
1
PHP
PHP
remove check for non-existent param
bfea79aabd3df1178ef4eafcadfa09f4d0776ae2
<ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> public function respondAs($type, array $options = []): bool <ide> return false; <ide> } <ide> <del> if (!$request->getParam('requested')) { <del> $response = $response->withType($cType); <del> } <add> $response = $response->withType($cType); <add> <ide> if (!empty($options['charset'])) { <ide> $response = $response->withCharset($options['charset']); <ide> }
1
Text
Text
remove getdomnode from docs
97b44085ffc2308f0003f37b606d1c2fb93da78f
<ide><path>docs/docs/ref-02-component-api.it-IT.md <ide> Chiamare `forceUpdate()` causerà la chiamata di `render()` sul componente, salt <ide> Normalmente dovresti cercare di evitare l'uso di `forceUpdate()` e leggere soltanto `this.props` e `this.state` all'interno di `render()`. Ciò rende il tuo componente "puro" e la tua applicazione molto più semplice ed efficiente. <ide> <ide> <del>### getDOMNode <del> <del>```javascript <del>DOMElement getDOMNode() <del>``` <del> <del>Se questo componente è stato montato nel DOM, restituisce il corrispondente elemento DOM nativo del browser. Questo metodo è utile per leggere valori dal DOM, come valori dei campi dei moduli ed effettuare misure sul DOM. Quando `render` restituisce `null` o `false`, `this.getDOMNode()` restituisce `null`. <del> <del>> Nota: <del>> <del>> getDOMNode è deprecato ed è stato sostituito da [ReactDOM.findDOMNode()](/react/docs/top-level-api.html#reactdom.finddomnode). <del>> <del>> Questo metodo non è disponibile il componenti `class` ES6 che estendono `React.Component`. Potrebbe essere eliminato del tutto in una versione futura di React. <del> <del> <ide> ### isMounted <ide> <ide> ```javascript <ide><path>docs/docs/ref-02-component-api.ko-KR.md <ide> React 컴포넌트의 인스턴스는 React가 렌더링 시에 내부적으로 <ide> <ide> ```javascript <ide> void setState( <del> function|object nextState, <add> function|object nextState, <ide> [function callback] <ide> ) <ide> ``` <ide> setState(function(previousState, currentProps) { <ide> <ide> ```javascript <ide> void replaceState( <del> object nextState, <add> object nextState, <ide> [function callback] <ide> ) <ide> ``` <ide> void forceUpdate( <ide> 특별한 경우가 아니면 `forceUpdate()`는 되도록 피하시고 `render()`에서는 `this.props`와 `this.state`에서만 읽어오세요. 그렇게 하는 것이 컴포넌트를 "순수"하게 하고 애플리케이션을 훨씬 단순하고 효율적으로 만들어줍니다. <ide> <ide> <del>### getDOMNode <del> <del>```javascript <del>DOMElement getDOMNode() <del>``` <del> <del>이 컴포넌트가 DOM에 마운트된 경우 해당하는 네이티브 브라우저 DOM 엘리먼트를 리턴합니다. 이 메소드는 폼 필드의 값이나 DOM의 크기/위치 등 DOM에서 정보를 읽을 때 유용합니다. `render`가 `null`이나 `false`를 리턴하였다면 `this.getDOMNode()`는 `null`을 리턴합니다. <del> <del>> 주의: <del>> <del>> getDOMNode는 [ReactDOM.findDOMNode()](/react/docs/top-level-api.html#reactdom.finddomnode)로 교체되었습니다. <del>> <del>> 이 메소드는 `React.Component`를 확장한 ES6 `class` 컴포넌트에서는 사용할 수 없습니다. React의 미래 버전에서 이는 완전히 사라지게 될 것입니다. <del> <del> <ide> ### isMounted <ide> <ide> ```javascript <ide> boolean isMounted() <ide> <ide> ```javascript <ide> void setProps( <del> object nextProps, <add> object nextProps, <ide> [function callback] <ide> ) <ide> ``` <ide> void setProps( <ide> <ide> ```javascript <ide> void replaceProps( <del> object nextProps, <add> object nextProps, <ide> function callback] <ide> ) <ide> ``` <ide><path>docs/docs/ref-02-component-api.md <ide> Calling `forceUpdate()` will cause `render()` to be called on the component, ski <ide> Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your component "pure" and your application much simpler and more efficient. <ide> <ide> <del>### getDOMNode <del> <del>```javascript <del>DOMElement getDOMNode() <del>``` <del> <del>If this component has been mounted into the DOM, this returns the corresponding native browser DOM element. This method is useful for reading values out of the DOM, such as form field values and performing DOM measurements. When `render` returns `null` or `false`, `this.getDOMNode()` returns `null`. <del> <del>> Note: <del>> <del>> getDOMNode is deprecated and has been replaced with [ReactDOM.findDOMNode()](/react/docs/top-level-api.html#reactdom.finddomnode). <del>> <del>> This method is not available on ES6 `class` components that extend `React.Component`. It may be removed entirely in a future version of React. <del> <del> <ide> ### isMounted <ide> <ide> ```javascript <ide><path>docs/docs/ref-02-component-api.zh-CN.md <ide> void forceUpdate( <ide> 通常你应该试着避免所有对 `forceUpdate()` 的使用并且在 `render()` 里只从 `this.props` 和 `this.state` 读取。这会使你的组件 "纯粹" 并且你的组件会更简单和高效。 <ide> <ide> <del>### getDOMNode <del> <del>```javascript <del>DOMElement getDOMNode() <del>``` <del> <del>如果这个组件已经被挂载到了 DOM,它返回相应的浏览器原生的 DOM 元素。这个方法对于读取 DOM 的值很有用,比如表单域的值和执行 DOM 的测量。如果 `render` 返回 `null` 或者 `false` 的时候,`this.getDOMNode()` 返回 `null`。 <del> <del>> Note: <del>> <del>> getDOMNode 被废弃了,已经被 [ReactDOM.findDOMNode()] 替换(/react/docs/top-level-api-zh-CN.html#reactdom.finddomnode). <del>> <del>> 这个方法在从 `React.Component` 扩展的 ES6 `class` 组件里不可用。它也许会在未来的 React 版本中被完全移除。 <del> <del> <ide> ### isMounted <ide> <ide> ```javascript
4
PHP
PHP
resolve ambiguous column names
c06b7162ef172c4c60d626cdd80f530e3a7aebfb
<ide><path>lib/Cake/Test/Case/Model/Datasource/DboSourceTest.php <ide> public function testJoinsAfterFind() { <ide> <ide> $User->Article = $Article; <ide> $User->find('first', array( <del> 'fields' => '*', <add> 'fields' => array('User.*', 'Article.*'), <ide> 'conditions' => array('User.id' => 1), <ide> 'recursive' => -1, <ide> 'joins' => array(
1
Mixed
Ruby
fix behavior of json encoding for exception
91386c1b355947955b05ee3846e4aedd4eec0eb1
<ide><path>activesupport/CHANGELOG.md <add>* Fix behavior of JSON encoding for `Exception`. <add> <add> *namusyaka* <add> <ide> * Make `number_to_phone` format number with regexp pattern. <ide> <ide> number_to_phone(18812345678, pattern: /(\d{3})(\d{4})(\d{4})/) <ide><path>activesupport/lib/active_support/core_ext/object/json.rb <ide> def as_json(options = nil) <ide> { :exitstatus => exitstatus, :pid => pid } <ide> end <ide> end <add> <add>class Exception <add> def as_json(options = nil) <add> to_s <add> end <add>end <ide><path>activesupport/test/json/encoding_test.rb <ide> def test_twz_to_json_when_wrapping_a_date_time <ide> assert_equal '"1999-12-31T19:00:00.000-05:00"', ActiveSupport::JSON.encode(time) <ide> end <ide> <add> def test_exception_to_json <add> exception = Exception.new("foo") <add> assert_equal '"foo"', ActiveSupport::JSON.encode(exception) <add> end <add> <ide> protected <ide> <ide> def object_keys(json_object)
3
PHP
PHP
deprecate public properties in view class
583dd73c1a33c46e6665010e694f290620f6d306
<ide><path>src/View/View.php <ide> class View implements EventDispatcherInterface <ide> * The name of the subfolder containing templates for this View. <ide> * <ide> * @var string <add> * @deprecated 3.7.0 The property will become protected in 4.0.0. Use getTemplatePath()/setTemplatePath() instead. <ide> */ <ide> public $templatePath; <ide> <ide> class View implements EventDispatcherInterface <ide> * is the filename in /src/Template/<SubFolder> without the .ctp extension. <ide> * <ide> * @var string <add> * @deprecated 3.7.0 The property will become protected in 4.0.0. Use getTemplate()/setTemplate() instead. <ide> */ <ide> public $template; <ide> <ide> class View implements EventDispatcherInterface <ide> * extension. <ide> * <ide> * @var string <add> * @deprecated 3.7.0 The property will become protected in 4.0.0. Use getLayout()/setLayout() instead. <ide> */ <ide> public $layout = 'default'; <ide> <ide> /** <ide> * The name of the layouts subfolder containing layouts for this View. <ide> * <ide> * @var string <add> * @deprecated 3.7.0 The property will become protected in 4.0.0. Use getLayoutPath()/setLayoutPath() instead. <ide> */ <ide> public $layoutPath; <ide> <ide> class View implements EventDispatcherInterface <ide> * Setting to off means that layouts will not be automatically applied to rendered templates. <ide> * <ide> * @var bool <add> * @deprecated 3.7.0 The property will become protected in 4.0.0. Use enableAutoLayout()/isAutoLayoutEnabled() instead. <ide> */ <ide> public $autoLayout = true; <ide> <ide> class View implements EventDispatcherInterface <ide> * The view theme to use. <ide> * <ide> * @var string|null <add> * @deprecated 3.7.0 The property will become protected in 4.0.0. Use getTheme()/setTheme() instead. <ide> */ <ide> public $theme; <ide> <ide> class View implements EventDispatcherInterface <ide> * List of generated DOM UUIDs. <ide> * <ide> * @var array <add> * @deprecated 3.7.0 The property is unused and will be removed in 4.0.0. <ide> */ <ide> public $uuids = []; <ide>
1
Ruby
Ruby
add fixme note about the thor bug
848776c3da0e4c45d77ad573bb2a250845522b96
<ide><path>railties/lib/rails/generators/named_base.rb <ide> def template(source, *args, &block) <ide> protected <ide> attr_reader :file_name <ide> <add> # FIXME: We are avoiding to use alias because a bug on thor that make <add> # this method public and add it to the task list. <ide> def singular_name <ide> file_name <ide> end
1
Javascript
Javascript
fix typo in menu-sort-helpers-spec.js
2beb93b0d7a0447150f52a9326d2c925e64254d2
<ide><path>spec/menu-sort-helpers-spec.js <ide> describe('contextMenu', () => { <ide> expect(sortMenuItems(items)).toEqual(expected); <ide> }); <ide> <del> it('preserves separators at the begining of set two', () => { <add> it('preserves separators at the beginning of set two', () => { <ide> const items = [ <ide> { command: 'core:one' }, <ide> { type: 'separator' },
1
Ruby
Ruby
allow select to have multiple arguments
04cc446d178653d362510e79a22db5300d463161
<ide><path>activerecord/lib/active_record/relation/query_methods.rb <ide> def preload(*args) <ide> relation <ide> end <ide> <del> def select(value = Proc.new) <add> def select(*args, &blk) <add> if !block_given? && args.blank? <add> raise ArgumentError <add> end <ide> if block_given? <del> to_a.select {|*block_args| value.call(*block_args) } <add> to_a.select {|*block_args| blk.call(*block_args) } <ide> else <ide> relation = clone <del> relation.select_values += Array.wrap(value) <add> relation.select_values += args <ide> relation <ide> end <ide> end <ide><path>activerecord/test/cases/base_test.rb <ide> def test_select_symbol <ide> assert_equal Topic.all.map(&:id).sort, topic_ids <ide> end <ide> <add> def test_select_symbol_for_many_arguments <add> topics = Topic.select(:id, :author_name).map{|topic| [topic.id, topic.author_name]}.sort <add> assert_equal Topic.all.map{|topic| [topic.id,topic.author_name]}.sort, topics <add> end <add> <ide> def test_table_exists <ide> assert !NonExistentTable.table_exists? <ide> assert Topic.table_exists?
2
Text
Text
add v3.9.0-beta.3 to changelog
514787c9b01461162ce780ff766d3c531b77d16e
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.9.0-beta.3 (March 4, 2019) <add> <add>- [#17684](https://github.com/emberjs/ember.js/pull/17684) [BUGFIX] Enable maximum rerendering limit to be customized. <add>- [#17691](https://github.com/emberjs/ember.js/pull/17691) [BUGFIX] Ensure tagForProperty works on class constructors <add> <ide> ### v3.9.0-beta.2 (February 26, 2019) <ide> <ide> - [#17618](https://github.com/emberjs/ember.js/pull/17618) [BUGFIX] Migrate autorun microtask queue to Promise.then
1
Python
Python
fix xcom arg.py .zip bug
f219bfbe22e662a8747af19d688bbe843e1a953d
<ide><path>airflow/models/xcom_arg.py <ide> from airflow.utils.context import Context <ide> from airflow.utils.edgemodifier import EdgeModifier <ide> from airflow.utils.session import NEW_SESSION, provide_session <del>from airflow.utils.types import NOTSET <add>from airflow.utils.types import NOTSET, ArgNotSet <ide> <ide> if TYPE_CHECKING: <ide> from airflow.models.dag import DAG <ide> def get_task_map_length(self, run_id: str, *, session: Session) -> int | None: <ide> def resolve(self, context: Context, session: Session = NEW_SESSION) -> Any: <ide> task_id = self.operator.task_id <ide> result = context["ti"].xcom_pull(task_ids=task_id, key=str(self.key), default=NOTSET, session=session) <del> if result is not NOTSET: <add> if not isinstance(result, ArgNotSet): <ide> return result <ide> if self.key == XCOM_RETURN_KEY: <ide> return None <ide> def __getitem__(self, index: Any) -> Any: <ide> <ide> def __len__(self) -> int: <ide> lengths = (len(v) for v in self.values) <del> if self.fillvalue is NOTSET: <add> if isinstance(self.fillvalue, ArgNotSet): <ide> return min(lengths) <ide> return max(lengths) <ide> <ide> def __repr__(self) -> str: <ide> args_iter = iter(self.args) <ide> first = repr(next(args_iter)) <ide> rest = ", ".join(repr(arg) for arg in args_iter) <del> if self.fillvalue is NOTSET: <add> if isinstance(self.fillvalue, ArgNotSet): <ide> return f"{first}.zip({rest})" <ide> return f"{first}.zip({rest}, fillvalue={self.fillvalue!r})" <ide> <ide> def _serialize(self) -> dict[str, Any]: <ide> args = [serialize_xcom_arg(arg) for arg in self.args] <del> if self.fillvalue is NOTSET: <add> if isinstance(self.fillvalue, ArgNotSet): <ide> return {"args": args} <ide> return {"args": args, "fillvalue": self.fillvalue} <ide> <ide> def get_task_map_length(self, run_id: str, *, session: Session) -> int | None: <ide> ready_lengths = [length for length in all_lengths if length is not None] <ide> if len(ready_lengths) != len(self.args): <ide> return None # If any of the referenced XComs is not ready, we are not ready either. <del> if self.fillvalue is NOTSET: <add> if isinstance(self.fillvalue, ArgNotSet): <ide> return min(ready_lengths) <ide> return max(ready_lengths) <ide>
1
Javascript
Javascript
call tolowercase on the resolved module
8a00f1d129ac5fcbbce8e115a2576e0ea080e4ed
<ide><path>test/parallel/test-require-resolve.js <ide> assert.strictEqual( <ide> require.resolve(fixtures.path('a')).toLowerCase()); <ide> assert.strictEqual( <ide> fixtures.path('nested-index', 'one', 'index.js').toLowerCase(), <del> require.resolve(fixtures.path('nested-index', 'one').toLowerCase())); <add> require.resolve(fixtures.path('nested-index', 'one')).toLowerCase()); <ide> assert.strictEqual('path', require.resolve('path')); <ide> <ide> // Test configurable resolve() paths.
1
Javascript
Javascript
fix jslint errors
fd30eb21526bdaa5aabb15523b0a766e0cbbe535
<ide><path>lib/_debugger.js <ide> Interface.prototype.unwatch = function(expr) { <ide> <ide> // List watchers <ide> Interface.prototype.watchers = function() { <del> var self = this, <del> verbose = arguments[0] || false, <del> callback = arguments[1] || function() {}, <del> waiting = this._watchers.length, <del> values = []; <add> var self = this; <add> var verbose = arguments[0] || false; <add> var callback = arguments[1] || function() {}; <add> var waiting = this._watchers.length; <add> var values = []; <ide> <ide> this.pause(); <ide> <ide><path>lib/_http_client.js <ide> ClientRequest.prototype._deferToConnect = function(method, arguments_, cb) { <ide> if (cb) { cb(); } <ide> }); <ide> } <del> } <add> }; <ide> if (!self.socket) { <ide> self.once('socket', onSocket); <ide> } else { <ide><path>lib/events.js <ide> EventEmitter.prototype.once = function once(type, listener) { <ide> // emits a 'removeListener' event iff the listener was removed <ide> EventEmitter.prototype.removeListener = <ide> function removeListener(type, listener) { <del> var list, position, length, i; <del> <del> if (!util.isFunction(listener)) <del> throw TypeError('listener must be a function'); <del> <del> if (!this._events || !this._events[type]) <del> return this; <del> <del> list = this._events[type]; <del> length = list.length; <del> position = -1; <del> <del> if (list === listener || <del> (util.isFunction(list.listener) && list.listener === listener)) { <del> delete this._events[type]; <del> if (this._events.removeListener) <del> this.emit('removeListener', type, listener); <del> <del> } else if (util.isObject(list)) { <del> for (i = length; i-- > 0;) { <del> if (list[i] === listener || <del> (list[i].listener && list[i].listener === listener)) { <del> position = i; <del> break; <add> var list, position, length, i; <add> <add> if (!util.isFunction(listener)) <add> throw TypeError('listener must be a function'); <add> <add> if (!this._events || !this._events[type]) <add> return this; <add> <add> list = this._events[type]; <add> length = list.length; <add> position = -1; <add> <add> if (list === listener || <add> (util.isFunction(list.listener) && list.listener === listener)) { <add> delete this._events[type]; <add> if (this._events.removeListener) <add> this.emit('removeListener', type, listener); <add> <add> } else if (util.isObject(list)) { <add> for (i = length; i-- > 0;) { <add> if (list[i] === listener || <add> (list[i].listener && list[i].listener === listener)) { <add> position = i; <add> break; <add> } <add> } <add> <add> if (position < 0) <add> return this; <add> <add> if (list.length === 1) { <add> list.length = 0; <add> delete this._events[type]; <add> } else { <add> spliceOne(list, position); <add> } <add> <add> if (this._events.removeListener) <add> this.emit('removeListener', type, listener); <ide> } <del> } <ide> <del> if (position < 0) <ide> return this; <del> <del> if (list.length === 1) { <del> list.length = 0; <del> delete this._events[type]; <del> } else { <del> spliceOne(list, position); <del> } <del> <del> if (this._events.removeListener) <del> this.emit('removeListener', type, listener); <del> } <del> <del> return this; <del>}; <add> }; <ide> <ide> EventEmitter.prototype.removeAllListeners = <ide> function removeAllListeners(type) { <del> var key, listeners; <del> <del> if (!this._events) <del> return this; <del> <del> // not listening for removeListener, no need to emit <del> if (!this._events.removeListener) { <del> if (arguments.length === 0) <del> this._events = {}; <del> else if (this._events[type]) <del> delete this._events[type]; <del> return this; <del> } <add> var key, listeners; <add> <add> if (!this._events) <add> return this; <add> <add> // not listening for removeListener, no need to emit <add> if (!this._events.removeListener) { <add> if (arguments.length === 0) <add> this._events = {}; <add> else if (this._events[type]) <add> delete this._events[type]; <add> return this; <add> } <ide> <del> // emit removeListener for all listeners on all events <del> if (arguments.length === 0) { <del> for (key in this._events) { <del> if (key === 'removeListener') continue; <del> this.removeAllListeners(key); <del> } <del> this.removeAllListeners('removeListener'); <del> this._events = {}; <del> return this; <del> } <add> // emit removeListener for all listeners on all events <add> if (arguments.length === 0) { <add> for (key in this._events) { <add> if (key === 'removeListener') continue; <add> this.removeAllListeners(key); <add> } <add> this.removeAllListeners('removeListener'); <add> this._events = {}; <add> return this; <add> } <ide> <del> listeners = this._events[type]; <add> listeners = this._events[type]; <ide> <del> if (util.isFunction(listeners)) { <del> this.removeListener(type, listeners); <del> } else if (Array.isArray(listeners)) { <del> // LIFO order <del> while (listeners.length) <del> this.removeListener(type, listeners[listeners.length - 1]); <del> } <del> delete this._events[type]; <add> if (util.isFunction(listeners)) { <add> this.removeListener(type, listeners); <add> } else if (Array.isArray(listeners)) { <add> // LIFO order <add> while (listeners.length) <add> this.removeListener(type, listeners[listeners.length - 1]); <add> } <add> delete this._events[type]; <ide> <del> return this; <del>}; <add> return this; <add> }; <ide> <ide> EventEmitter.prototype.listeners = function listeners(type) { <ide> var ret; <ide><path>lib/repl.js <ide> function ArrayStream() { <ide> data.forEach(function(line) { <ide> self.emit('data', line + '\n'); <ide> }); <del> } <add> }; <ide> } <ide> util.inherits(ArrayStream, Stream); <ide> ArrayStream.prototype.readable = true; <ide><path>lib/timers.js <ide> exports.setTimeout = function(callback, after) { <ide> var args = Array.prototype.slice.call(arguments, 2); <ide> timer._onTimeout = function() { <ide> callback.apply(timer, args); <del> } <add> }; <ide> } <ide> <ide> if (process.domain) timer.domain = process.domain; <ide><path>lib/util.js <ide> function formatPrimitive(ctx, value) { <ide> return ctx.stylize('undefined', 'undefined'); <ide> if (isString(value)) { <ide> var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') <del> .replace(/'/g, "\\'") <del> .replace(/\\"/g, '"') + '\''; <add> .replace(/'/g, "\\'") <add> .replace(/\\"/g, '"') + '\''; <ide> return ctx.stylize(simple, 'string'); <ide> } <ide> if (isNumber(value)) { <ide><path>src/node.js <ide> <ide> // strip the gyp comment line at the beginning <ide> config = config.split('\n') <del> .slice(1) <del> .join('\n') <del> .replace(/"/g, '\\"') <del> .replace(/'/g, '"'); <add> .slice(1) <add> .join('\n') <add> .replace(/"/g, '\\"') <add> .replace(/'/g, '"'); <ide> <ide> process.config = JSON.parse(config, function(key, value) { <ide> if (value === 'true') return true; <ide> <ide> NativeModule.getCached = function(id) { <ide> return NativeModule._cache[id]; <del> } <add> }; <ide> <ide> NativeModule.exists = function(id) { <ide> return NativeModule._source.hasOwnProperty(id); <del> } <add> }; <ide> <ide> NativeModule.getSource = function(id) { <ide> return NativeModule._source[id]; <del> } <add> }; <ide> <ide> NativeModule.wrap = function(script) { <ide> return NativeModule.wrapper[0] + script + NativeModule.wrapper[1];
7
Text
Text
update changelog.md for 3.16.7
a3638c9a3f3d3b8f0d760bfec11c1b1c06adcb55
<ide><path>CHANGELOG.md <ide> - [#18694](https://github.com/emberjs/ember.js/pull/18694) [BUGFIX] Ensure tag updates are buffered, remove error message <ide> - [#18709](https://github.com/emberjs/ember.js/pull/18709) [BUGFIX] Fix `this` in `@tracked` initializer <ide> <del>### v3.16.6 <add>### v3.16.7 (April 13, 2020) <add> <add>- [#18854](https://github.com/emberjs/ember.js/pull/18854) Pass value through to `PROPERTY_DID_CHANGE` to avoid calling `get` when setting values for computed props <add> <add>### v3.16.6 (March 24, 2020) <ide> <ide> - [#18835](https://github.com/emberjs/ember.js/pull/18835) [BUGFIX] Make `ArrayProxy` Lazy. <ide>
1
Ruby
Ruby
reduce effective scope of pipe variables
479ad0265b4998531be1682d9ac96f8dec10a553
<ide><path>Library/Homebrew/formula.rb <ide> def test_defined? <ide> # Pretty titles the command and buffers stdout/stderr <ide> # Throws if there's an error <ide> def system cmd, *args <del> rd, wr = IO.pipe <del> <ide> # remove "boring" arguments so that the important ones are more likely to <ide> # be shown considering that we trim long ohai lines to the terminal width <ide> pretty_args = args.dup <ide> def system cmd, *args <ide> logfn = "#{logd}/%02d.%s" % [@exec_count, File.basename(cmd).split(' ').first] <ide> mkdir_p(logd) <ide> <del> pid = fork { exec_cmd(cmd, args, rd, wr, logfn) } <del> wr.close <del> <del> File.open(logfn, 'w') do |f| <del> f.puts Time.now, "", cmd, args, "" <add> rd, wr = IO.pipe <ide> <del> if ARGV.verbose? <del> while buf = rd.gets <del> f.puts buf <del> puts buf <add> begin <add> pid = fork { exec_cmd(cmd, args, rd, wr, logfn) } <add> wr.close <add> <add> File.open(logfn, 'w') do |f| <add> f.puts Time.now, "", cmd, args, "" <add> <add> if ARGV.verbose? <add> while buf = rd.gets <add> f.puts buf <add> puts buf <add> end <add> elsif IO.respond_to?(:copy_stream) <add> IO.copy_stream(rd, f) <add> else <add> buf = "" <add> f.write(buf) while rd.read(1024, buf) <ide> end <del> elsif IO.respond_to?(:copy_stream) <del> IO.copy_stream(rd, f) <del> else <del> buf = "" <del> f.write(buf) while rd.read(1024, buf) <del> end <ide> <del> Process.wait(pid) <add> Process.wait(pid) <ide> <del> $stdout.flush <add> $stdout.flush <ide> <del> unless $?.success? <del> f.flush <del> Kernel.system "/usr/bin/tail", "-n", "5", logfn unless ARGV.verbose? <del> f.puts <del> require 'cmd/config' <del> Homebrew.dump_build_config(f) <del> raise BuildError.new(self, cmd, args) <add> unless $?.success? <add> f.flush <add> Kernel.system "/usr/bin/tail", "-n", "5", logfn unless ARGV.verbose? <add> f.puts <add> require 'cmd/config' <add> Homebrew.dump_build_config(f) <add> raise BuildError.new(self, cmd, args) <add> end <ide> end <add> ensure <add> rd.close unless rd.closed? <ide> end <del> ensure <del> rd.close unless rd.closed? <ide> end <ide> <ide> private
1
Ruby
Ruby
resolve url to get real file extension
fbcaa8c85ae42f127fd94a5d82f86a3eafb34848
<ide><path>Library/Homebrew/cask/lib/hbc/download.rb <ide> require "fileutils" <add>require "hbc/cache" <ide> require "hbc/quarantine" <ide> require "hbc/verify" <ide> <ide> def perform <ide> downloaded_path <ide> end <ide> <del> private <del> <del> attr_reader :force <del> attr_accessor :downloaded_path <del> <ide> def downloader <ide> @downloader ||= begin <ide> strategy = DownloadStrategyDetector.detect(cask.url.to_s, cask.url.using) <ide> strategy.new(cask.url.to_s, cask.token, cask.version, cache: Cache.path, **cask.url.specs) <ide> end <ide> end <ide> <add> private <add> <add> attr_reader :force <add> attr_accessor :downloaded_path <add> <ide> def clear_cache <ide> downloader.clear_cache if force || cask.version.latest? <ide> end <ide> def fetch <ide> downloader.fetch <ide> @downloaded_path = downloader.cached_location <ide> rescue StandardError => e <del> raise CaskError, "Download failed on Cask '#{cask}' with message: #{e}" <add> error = CaskError.new("Download failed on Cask '#{cask}' with message: #{e}") <add> error.set_backtrace e.backtrace <add> raise error <ide> end <ide> <ide> def quarantine <ide><path>Library/Homebrew/cleanup.rb <ide> def prune?(days) <ide> end <ide> <ide> def stale?(scrub = false) <del> return false unless file? <add> return false unless file? || (symlink? && resolved_path.file?) <ide> <ide> stale_formula?(scrub) || stale_cask?(scrub) <ide> end <ide> def cleanup_logs <ide> end <ide> end <ide> <add> def cleanup_unreferenced_downloads <add> return if dry_run? <add> return unless (cache/"downloads").directory? <add> <add> downloads = (cache/"downloads").children.reject { |path| path.incomplete? } # rubocop:disable Style/SymbolProc <add> referenced_downloads = [cache, cache/"Cask"].select(&:directory?) <add> .flat_map(&:children) <add> .select(&:symlink?) <add> .map(&:resolved_path) <add> <add> (downloads - referenced_downloads).each(&:unlink) <add> end <add> <ide> def cleanup_cache(entries = nil) <ide> entries ||= [cache, cache/"Cask"].select(&:directory?).flat_map(&:children) <ide> <ide> def cleanup_cache(entries = nil) <ide> next cleanup_path(path) { FileUtils.rm_rf path } if path.nested_cache? <ide> <ide> if path.prune?(days) <del> if path.file? <add> if path.symlink? <add> resolved_path = path.resolved_path <add> <add> cleanup_path(path) do <add> resolved_path.unlink if resolved_path.exist? <add> path.unlink <add> end <add> elsif path.file? <ide> cleanup_path(path) { path.unlink } <ide> elsif path.directory? && path.to_s.include?("--") <ide> cleanup_path(path) { FileUtils.rm_rf path } <ide> def cleanup_cache(entries = nil) <ide> <ide> next cleanup_path(path) { path.unlink } if path.stale?(scrub?) <ide> end <add> <add> cleanup_unreferenced_downloads <ide> end <ide> <ide> def cleanup_path(path) <ide><path>Library/Homebrew/cmd/update-report.rb <ide> require "formulary" <ide> require "descriptions" <ide> require "cleanup" <add>require "hbc/download" <ide> <ide> module Homebrew <ide> module_function <ide> def update_report <ide> <ide> migrate_legacy_cache_if_necessary <ide> migrate_cache_entries_to_double_dashes(initial_version) <add> migrate_cache_entries_to_symlinks(initial_version) <ide> migrate_legacy_keg_symlinks_if_necessary <ide> <ide> if !updated <ide> def migrate_legacy_cache_if_necessary <ide> end <ide> end <ide> <add> def formula_resources(formula) <add> specs = [formula.stable, formula.devel, formula.head].compact <add> <add> [*formula.bottle&.resource] + specs.flat_map do |spec| <add> [ <add> spec, <add> *spec.resources.values, <add> *spec.patches.select(&:external?).map(&:resource), <add> ] <add> end <add> end <add> <add> def parse_extname(url) <add> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ url <add> uri = URI(url) <add> uri.query ? "#{uri.path}?#{uri.query}" : uri.path <add> else <add> url <add> end <add> <add> # Given a URL like https://example.com/download.php?file=foo-1.0.tar.gz <add> # the extension we want is ".tar.gz", not ".php". <add> Pathname.new(uri_path).ascend do |path| <add> ext = path.extname[/[^?&]+/] <add> return ext if ext <add> end <add> <add> nil <add> end <add> <ide> def migrate_cache_entries_to_double_dashes(initial_version) <ide> return if initial_version && initial_version > "1.7.1" <ide> <ide> def migrate_cache_entries_to_double_dashes(initial_version) <ide> ohai "Migrating cache entries..." <ide> <ide> Formula.each do |formula| <del> specs = [*formula.stable, *formula.devel, *formula.head] <del> <del> resources = [*formula.bottle&.resource] + specs.flat_map do |spec| <del> [ <del> spec, <del> *spec.resources.values, <del> *spec.patches.select(&:external?).map(&:resource), <del> ] <del> end <del> <del> resources.each do |resource| <add> formula_resources(formula).each do |resource| <ide> downloader = resource.downloader <ide> <add> url = downloader.url <ide> name = resource.download_name <ide> version = resource.version <ide> <del> new_location = downloader.cached_location <del> extname = new_location.extname <del> old_location = downloader.cached_location.dirname/"#{name}-#{version}#{extname}" <add> extname = parse_extname(url) <add> old_location = downloader.cache/"#{name}-#{version}#{extname}" <add> new_location = downloader.cache/"#{name}--#{version}#{extname}" <ide> <ide> next unless old_location.file? <ide> <ide> def migrate_cache_entries_to_double_dashes(initial_version) <ide> end <ide> end <ide> <add> def migrate_cache_entries_to_symlinks(initial_version) <add> return if initial_version && initial_version > "1.7.2" <add> <add> return if ENV.key?("HOMEBREW_DISABLE_LOAD_FORMULA") <add> <add> ohai "Migrating cache entries..." <add> <add> load_formula = lambda do |formula| <add> begin <add> Formula[formula] <add> rescue FormulaUnavailableError <add> nil <add> end <add> end <add> <add> load_cask = lambda do |cask| <add> begin <add> Hbc::CaskLoader.load(cask) <add> rescue Hbc::CaskUnavailableError <add> nil <add> end <add> end <add> <add> formula_downloaders = if HOMEBREW_CACHE.directory? <add> HOMEBREW_CACHE.children <add> .select(&:file?) <add> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") } <add> .uniq <add> .map(&load_formula) <add> .compact <add> .flat_map { |formula| formula_resources(formula) } <add> .map { |resource| [resource.downloader, resource.download_name, resource.version] } <add> else <add> [] <add> end <add> <add> cask_downloaders = if (HOMEBREW_CACHE/"Cask").directory? <add> (HOMEBREW_CACHE/"Cask").children <add> .map { |child| child.basename.to_s.sub(/\-\-.*/, "") } <add> .uniq <add> .map(&load_cask) <add> .compact <add> .map { |cask| [Hbc::Download.new(cask).downloader, cask.token, cask.version] } <add> else <add> [] <add> end <add> <add> downloaders = formula_downloaders + cask_downloaders <add> <add> downloaders.each do |downloader, name, version| <add> next unless downloader.respond_to?(:symlink_location) <add> <add> url = downloader.url <add> extname = parse_extname(url) <add> old_location = downloader.cache/"#{name}--#{version}#{extname}" <add> next unless old_location.file? <add> <add> new_symlink_location = downloader.symlink_location <add> new_location = downloader.cached_location <add> <add> if new_location.exist? && new_symlink_location.symlink? <add> begin <add> FileUtils.rm_rf old_location unless old_location == new_symlink_location <add> rescue Errno::EACCES <add> opoo "Could not remove #{old_location}, please do so manually." <add> end <add> else <add> begin <add> new_location.dirname.mkpath <add> FileUtils.mv old_location, new_location unless new_location.exist? <add> symlink_target = new_location.relative_path_from(new_symlink_location.dirname) <add> new_symlink_location.dirname.mkpath <add> FileUtils.ln_s symlink_target, new_symlink_location, force: true <add> rescue Errno::EACCES <add> opoo "Could not move #{old_location} to #{new_location}, please do so manually." <add> end <add> end <add> end <add> end <add> <ide> def migrate_legacy_repository_if_necessary <ide> return unless HOMEBREW_PREFIX.to_s == "/usr/local" <ide> return unless HOMEBREW_REPOSITORY.to_s == "/usr/local" <ide><path>Library/Homebrew/dev-cmd/tests.rb <ide> def tests <ide> ENV.delete("HOMEBREW_COLOR") <ide> ENV.delete("HOMEBREW_NO_COLOR") <ide> ENV.delete("HOMEBREW_VERBOSE") <add> ENV.delete("HOMEBREW_DEBUG") <ide> ENV.delete("VERBOSE") <ide> ENV.delete("HOMEBREW_CASK_OPTS") <ide> ENV.delete("HOMEBREW_TEMP") <ide><path>Library/Homebrew/download_strategy.rb <ide> require "rexml/document" <ide> require "time" <ide> require "unpack_strategy" <add>require "lazy_object" <add>require "cgi" <ide> <ide> class AbstractDownloadStrategy <ide> extend Forwardable <ide> def stage <ide> end <ide> end <ide> <del> attr_reader :cached_location <add> attr_reader :cache, :cached_location, :url <ide> attr_reader :meta, :name, :version, :shutup <ide> private :meta, :name, :version, :shutup <ide> <ide> def stage <ide> UnpackStrategy.detect(cached_location, <ide> extension_only: true, <ide> ref_type: @ref_type, ref: @ref) <del> .extract_nestedly(basename: basename_without_params, <add> .extract_nestedly(basename: basename, <ide> extension_only: true, <ide> verbose: ARGV.verbose? && !shutup) <ide> chdir <ide> def clear_cache <ide> rm_rf(cached_location) <ide> end <ide> <del> def basename_without_params <del> return unless @url <del> <del> # Strip any ?thing=wad out of .c?thing=wad style extensions <del> File.basename(@url)[/[^?]+/] <add> def basename <add> nil <ide> end <ide> <ide> private <ide> def initialize(url, name, version, **meta) <ide> end <ide> <ide> def fetch <del> ohai "Cloning #{@url}" <add> ohai "Cloning #{url}" <ide> <ide> if cached_location.exist? && repo_valid? <ide> puts "Updating #{cached_location}" <ide> class AbstractFileDownloadStrategy < AbstractDownloadStrategy <ide> <ide> def initialize(url, name, version, **meta) <ide> super <del> @cached_location = @cache/"#{name}--#{version}#{ext}" <ide> @temporary_path = Pathname.new("#{cached_location}.incomplete") <ide> end <ide> <add> def symlink_location <add> return @symlink_location if defined?(@symlink_location) <add> ext = Pathname(parse_basename(url)).extname <add> @symlink_location = @cache/"#{name}--#{version}#{ext}" <add> end <add> <add> def cached_location <add> return @cached_location if defined?(@cached_location) <add> <add> url_sha256 = Digest::SHA256.hexdigest(url) <add> downloads = Pathname.glob(HOMEBREW_CACHE/"downloads/#{url_sha256}--*") <add> <add> @cached_location = if downloads.count == 1 <add> downloads.first <add> else <add> HOMEBREW_CACHE/"downloads/#{url_sha256}--#{resolved_basename}" <add> end <add> end <add> <add> def basename <add> cached_location.basename.sub(/^[\da-f]{64}\-\-/, "") <add> end <add> <ide> private <ide> <del> def ext <del> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ @url <del> uri = URI(@url) <add> def resolved_url <add> resolved_url, = resolved_url_and_basename <add> resolved_url <add> end <add> <add> def resolved_basename <add> _, resolved_basename = resolved_url_and_basename <add> resolved_basename <add> end <add> <add> def resolved_url_and_basename <add> return @resolved_url_and_basename if defined?(@resolved_url_and_basename) <add> @resolved_url_and_basename = [url, parse_basename(url)] <add> end <add> <add> def parse_basename(url) <add> uri_path = if URI::DEFAULT_PARSER.make_regexp =~ url <add> uri = URI(url) <add> <add> if uri.query <add> query_params = CGI.parse(uri.query) <add> query_params["response-content-disposition"].each do |param| <add> query_basename = param[/attachment;\s*filename=(["']?)(.+)\1/i, 2] <add> return query_basename if query_basename <add> end <add> end <add> <ide> uri.query ? "#{uri.path}?#{uri.query}" : uri.path <ide> else <del> @url <add> url <ide> end <ide> <add> uri_path = URI.decode_www_form_component(uri_path) <add> <ide> # We need a Pathname because we've monkeypatched extname to support double <ide> # extensions (e.g. tar.gz). <del> # We can't use basename_without_params, because given a URL like <del> # https://example.com/download.php?file=foo-1.0.tar.gz <del> # the extension we want is ".tar.gz", not ".php". <add> # Given a URL like https://example.com/download.php?file=foo-1.0.tar.gz <add> # the basename we want is "foo-1.0.tar.gz", not "download.php". <ide> Pathname.new(uri_path).ascend do |path| <ide> ext = path.extname[/[^?&]+/] <del> return ext if ext <add> return path.basename.to_s[/[^?&]+#{Regexp.escape(ext)}/] if ext <ide> end <del> nil <add> <add> File.basename(uri_path) <ide> end <ide> end <ide> <ide> def initialize(url, name, version, **meta) <ide> end <ide> <ide> def fetch <del> ohai "Downloading #{@url}" <add> urls = [url, *mirrors] <ide> <del> if cached_location.exist? <del> puts "Already downloaded: #{cached_location}" <del> else <del> begin <del> _fetch <del> rescue ErrorDuringExecution <del> raise CurlDownloadStrategyError, @url <add> begin <add> url = urls.shift <add> <add> ohai "Downloading #{url}" <add> <add> if cached_location.exist? <add> puts "Already downloaded: #{cached_location}" <add> else <add> begin <add> resolved_url, = resolve_url_and_basename(url) <add> <add> _fetch(url: url, resolved_url: resolved_url) <add> rescue ErrorDuringExecution <add> raise CurlDownloadStrategyError, url <add> end <add> ignore_interrupts do <add> temporary_path.rename(cached_location) <add> symlink_location.dirname.mkpath <add> FileUtils.ln_s cached_location.relative_path_from(symlink_location.dirname), symlink_location, force: true <add> end <ide> end <del> ignore_interrupts { temporary_path.rename(cached_location) } <add> rescue CurlDownloadStrategyError <add> raise if urls.empty? <add> puts "Trying a mirror..." <add> retry <ide> end <del> rescue CurlDownloadStrategyError <del> raise if mirrors.empty? <del> puts "Trying a mirror..." <del> @url = mirrors.shift <del> retry <ide> end <ide> <ide> def clear_cache <ide> def clear_cache <ide> <ide> private <ide> <del> # Private method, can be overridden if needed. <del> def _fetch <del> url = @url <add> def resolved_url_and_basename <add> return @resolved_url_and_basename if defined?(@resolved_url_and_basename) <add> @resolved_url_and_basename = resolve_url_and_basename(url) <add> end <ide> <add> def resolve_url_and_basename(url) <ide> if ENV["HOMEBREW_ARTIFACT_DOMAIN"] <ide> url = url.sub(%r{^((ht|f)tps?://)?}, ENV["HOMEBREW_ARTIFACT_DOMAIN"].chomp("/") + "/") <del> ohai "Downloading from #{url}" <ide> end <ide> <add> out, _, status= curl_output("--location", "--silent", "--head", url.to_s) <add> <add> lines = status.success? ? out.lines.map(&:chomp) : [] <add> <add> locations = lines.map { |line| line[/^Location:\s*(.*)$/i, 1] } <add> .compact <add> <add> redirect_url = locations.reduce(url) do |current_url, location| <add> if location.start_with?("/") <add> uri = URI(current_url) <add> "#{uri.scheme}://#{uri.host}#{location}" <add> else <add> location <add> end <add> end <add> <add> filenames = lines.map { |line| line[/^Content\-Disposition:\s*attachment;\s*filename=(["']?)(.+)\1$/i, 2] } <add> .compact <add> <add> basename = filenames.last || parse_basename(redirect_url) <add> <add> [redirect_url, basename] <add> end <add> <add> def _fetch(url:, resolved_url:) <ide> temporary_path.dirname.mkpath <ide> <del> curl_download resolved_url(url), to: temporary_path <add> ohai "Downloading from #{resolved_url}" if url != resolved_url <add> <add> if ENV["HOMEBREW_NO_INSECURE_REDIRECT"] && <add> url.start_with?("https://") && !resolved_url.start_with?("https://") <add> $stderr.puts "HTTPS to HTTP redirect detected & HOMEBREW_NO_INSECURE_REDIRECT is set." <add> raise CurlDownloadStrategyError, url <add> end <add> <add> curl_download resolved_url, to: temporary_path <ide> end <ide> <ide> # Curl options to be always passed to curl, <ide> def _curl_opts <ide> {} <ide> end <ide> <del> def resolved_url(url) <del> redirect_url, _, status = curl_output( <del> "--silent", "--head", <del> "--write-out", "%{redirect_url}", <del> "--output", "/dev/null", <del> url.to_s <del> ) <del> <del> return url unless status.success? <del> return url if redirect_url.empty? <del> <del> ohai "Downloading from #{redirect_url}" <del> if ENV["HOMEBREW_NO_INSECURE_REDIRECT"] && <del> url.start_with?("https://") && !redirect_url.start_with?("https://") <del> puts "HTTPS to HTTP redirect detected & HOMEBREW_NO_INSECURE_REDIRECT is set." <del> raise CurlDownloadStrategyError, url <del> end <del> <del> redirect_url <del> end <del> <ide> def curl_output(*args, **options) <ide> super(*_curl_args, *args, **_curl_opts, **options) <ide> end <ide> def curl(*args, **options) <ide> <ide> # Detect and download from Apache Mirror <ide> class CurlApacheMirrorDownloadStrategy < CurlDownloadStrategy <del> def apache_mirrors <del> mirrors, = curl_output("--silent", "--location", "#{@url}&asjson=1") <del> JSON.parse(mirrors) <add> def mirrors <add> return @combined_mirrors if defined?(@combined_mirrors) <add> <add> backup_mirrors = apache_mirrors.fetch("backup", []) <add> .map { |mirror| "#{mirror}#{apache_mirrors["path_info"]}" } <add> <add> @combined_mirrors = [*@mirrors, *backup_mirrors] <ide> end <ide> <del> def _fetch <del> return super if @tried_apache_mirror <del> @tried_apache_mirror = true <add> private <ide> <del> mirrors = apache_mirrors <del> path_info = mirrors.fetch("path_info") <del> @url = mirrors.fetch("preferred") + path_info <del> @mirrors |= %W[https://archive.apache.org/dist/#{path_info}] <add> def resolved_url_and_basename <add> return @resolved_url_and_basename if defined?(@resolved_url_and_basename) <add> @resolved_url_and_basename = [ <add> "#{apache_mirrors["preferred"]}#{apache_mirrors["path_info"]}", <add> File.basename(apache_mirrors["path_info"]), <add> ] <add> end <ide> <del> ohai "Best Mirror #{@url}" <del> super <del> rescue IndexError, JSON::ParserError <add> def apache_mirrors <add> return @apache_mirrors if defined?(@apache_mirrors) <add> json, = curl_output("--silent", "--location", "#{url}&asjson=1") <add> @apache_mirrors = JSON.parse(json) <add> rescue JSON::ParserError <ide> raise CurlDownloadStrategyError, "Couldn't determine mirror, try again later." <ide> end <ide> end <ide> <ide> # Download via an HTTP POST. <ide> # Query parameters on the URL are converted into POST parameters <ide> class CurlPostDownloadStrategy < CurlDownloadStrategy <del> def _fetch <add> private <add> <add> def _fetch(url:, resolved_url:) <ide> args = if meta.key?(:data) <ide> escape_data = ->(d) { ["-d", URI.encode_www_form([d])] } <del> [@url, *meta[:data].flat_map(&escape_data)] <add> [url, *meta[:data].flat_map(&escape_data)] <ide> else <del> url, query = @url.split("?", 2) <add> url, query = url.split("?", 2) <ide> query.nil? ? [url, "-X", "POST"] : [url, "-d", query] <ide> end <ide> <ide> def _fetch <ide> class NoUnzipCurlDownloadStrategy < CurlDownloadStrategy <ide> def stage <ide> UnpackStrategy::Uncompressed.new(cached_location) <del> .extract(basename: basename_without_params, <add> .extract(basename: basename, <ide> verbose: ARGV.verbose? && !shutup) <ide> end <ide> end <ide> def initialize(path) <ide> # because it lets you use a private S3 bucket as a repo for internal <ide> # distribution. (It will work for public buckets as well.) <ide> class S3DownloadStrategy < CurlDownloadStrategy <del> def _fetch <del> if @url !~ %r{^https?://([^.].*)\.s3\.amazonaws\.com/(.+)$} && <del> @url !~ %r{^s3://([^.].*?)/(.+)$} <del> raise "Bad S3 URL: " + @url <add> def _fetch(url:, resolved_url:) <add> if url !~ %r{^https?://([^.].*)\.s3\.amazonaws\.com/(.+)$} && <add> url !~ %r{^s3://([^.].*?)/(.+)$} <add> raise "Bad S3 URL: " + url <ide> end <ide> bucket = Regexp.last_match(1) <ide> key = Regexp.last_match(2) <ide> def _fetch <ide> s3url = signer.presigned_url :get_object, bucket: bucket, key: key <ide> rescue Aws::Sigv4::Errors::MissingCredentialsError <ide> ohai "AWS credentials missing, trying public URL instead." <del> s3url = @url <add> s3url = url <ide> end <ide> <ide> curl_download s3url, to: temporary_path <ide> def initialize(url, name, version, **meta) <ide> end <ide> <ide> def parse_url_pattern <del> url_pattern = %r{https://github.com/([^/]+)/([^/]+)/(\S+)} <del> unless @url =~ url_pattern <add> unless match = url.match(%r{https://github.com/([^/]+)/([^/]+)/(\S+)}) <ide> raise CurlDownloadStrategyError, "Invalid url pattern for GitHub Repository." <ide> end <ide> <del> _, @owner, @repo, @filepath = *@url.match(url_pattern) <add> _, @owner, @repo, @filepath = *match <ide> end <ide> <ide> def download_url <ide> "https://#{@github_token}@github.com/#{@owner}/#{@repo}/#{@filepath}" <ide> end <ide> <del> def _fetch <add> private <add> <add> def _fetch(url:, resolved_url:) <ide> curl_download download_url, to: temporary_path <ide> end <ide> <del> private <del> <ide> def set_github_token <ide> @github_token = ENV["HOMEBREW_GITHUB_API_TOKEN"] <ide> unless @github_token <ide> def download_url <ide> "https://#{@github_token}@api.github.com/repos/#{@owner}/#{@repo}/releases/assets/#{asset_id}" <ide> end <ide> <del> def _fetch <add> private <add> <add> def _fetch(url:, resolved_url:) <ide> # HTTP request header `Accept: application/octet-stream` is required. <ide> # Without this, the GitHub API will respond with metadata, not binary. <ide> curl_download download_url, "--header", "Accept: application/octet-stream", to: temporary_path <ide> end <ide> <del> private <del> <ide> def asset_id <ide> @asset_id ||= resolve_asset_id <ide> end <ide><path>Library/Homebrew/extend/pathname.rb <ide> def abv <ide> private <ide> <ide> def compute_disk_usage <add> if symlink? && !exist? <add> @file_count = 1 <add> @disk_usage = 0 <add> return <add> end <add> <ide> path = if symlink? <ide> resolved_path <ide> else <ide><path>Library/Homebrew/test/cask/cli/reinstall_spec.rb <ide> <ide> output = Regexp.new <<~EOS <ide> ==> Downloading file:.*caffeine.zip <del> Already downloaded: .*local-caffeine--1.2.3.zip <add> Already downloaded: .*caffeine.zip <ide> ==> Verifying checksum for Cask local-caffeine <ide> ==> Uninstalling Cask local-caffeine <ide> ==> Backing App 'Caffeine.app' up to '.*Caffeine.app'. <ide><path>Library/Homebrew/test/cmd/--cache_spec.rb <ide> <ide> it "prints all cache files for a given Formula" do <ide> expect { brew "--cache", testball } <del> .to output(%r{#{HOMEBREW_CACHE}/testball-}).to_stdout <add> .to output(%r{#{HOMEBREW_CACHE}/downloads/[\da-f]{64}\-\-testball\-}).to_stdout <ide> .and not_to_output.to_stderr <ide> .and be_a_success <ide> end <ide><path>Library/Homebrew/test/cmd/fetch_spec.rb <ide> it "downloads the Formula's URL" do <ide> setup_test_formula "testball" <ide> <del> expect(HOMEBREW_CACHE/"testball--0.1.tbz").not_to exist <del> <ide> expect { brew "fetch", "testball" }.to be_a_success <ide> <add> expect(HOMEBREW_CACHE/"testball--0.1.tbz").to be_a_symlink <ide> expect(HOMEBREW_CACHE/"testball--0.1.tbz").to exist <ide> end <ide> end <ide><path>Library/Homebrew/test/cmd/update-report_spec.rb <ide> expect(new_cache_file).not_to exist <ide> end <ide> end <add> <add> describe "::migrate_cache_entries_to_symlinks" do <add> let(:formula_name) { "foo" } <add> let(:f) { <add> formula formula_name do <add> url "https://example.com/foo-1.2.3.tar.gz" <add> version "1.2.3" <add> end <add> } <add> let(:old_cache_file) { HOMEBREW_CACHE/"#{formula_name}--1.2.3.tar.gz" } <add> let(:new_cache_symlink) { HOMEBREW_CACHE/"#{formula_name}--1.2.3.tar.gz" } <add> let(:new_cache_file) { HOMEBREW_CACHE/"downloads/5994e3a27baa3f448a001fb071ab1f0bf25c87aebcb254d91a6d0b02f46eef86--foo-1.2.3.tar.gz" } <add> <add> before(:each) do <add> old_cache_file.dirname.mkpath <add> FileUtils.touch old_cache_file <add> allow(Formula).to receive(:[]).and_return(f) <add> end <add> <add> it "moves old files to use symlinks when upgrading from <= 1.7.2" do <add> Homebrew.migrate_cache_entries_to_symlinks(Version.new("1.7.2")) <add> <add> expect(old_cache_file).to eq(new_cache_symlink) <add> expect(new_cache_symlink).to be_a_symlink <add> expect(new_cache_symlink.readlink.to_s) <add> .to eq "downloads/5994e3a27baa3f448a001fb071ab1f0bf25c87aebcb254d91a6d0b02f46eef86--foo-1.2.3.tar.gz" <add> expect(new_cache_file).to exist <add> expect(new_cache_file).to be_a_file <add> end <add> <add> it "does not move files if upgrading from > 1.7.2" do <add> Homebrew.migrate_cache_entries_to_symlinks(Version.new("1.7.3")) <add> <add> expect(old_cache_file).to exist <add> expect(new_cache_file).not_to exist <add> expect(new_cache_symlink).not_to be_a_symlink <add> end <add> end <ide> end <ide><path>Library/Homebrew/test/download_strategies_spec.rb <ide> def setup_git_repo <ide> let(:url) { "https://bucket.s3.amazonaws.com/foo.tar.gz" } <ide> let(:version) { nil } <ide> <del> describe "#_fetch" do <del> subject { described_class.new(url, name, version)._fetch } <del> <add> describe "#fetch" do <ide> context "when given Bad S3 URL" do <ide> let(:url) { "https://example.com/foo.tar.gz" } <ide> <ide> it "raises Bad S3 URL error" do <del> expect { <del> subject._fetch <del> }.to raise_error(RuntimeError) <add> expect { subject.fetch }.to raise_error(RuntimeError, /S3/) <ide> end <ide> end <ide> end <ide> def setup_git_repo <ide> subject { described_class.new(url, name, version, **specs).cached_location } <ide> <ide> context "when URL ends with file" do <del> it { is_expected.to eq(HOMEBREW_CACHE/"foo--1.2.3.tar.gz") } <add> it { is_expected.to eq(HOMEBREW_CACHE/"downloads/3d1c0ae7da22be9d83fb1eb774df96b7c4da71d3cf07e1cb28555cf9a5e5af70--foo.tar.gz") } <ide> end <ide> <ide> context "when URL file is in middle" do <ide> let(:url) { "https://example.com/foo.tar.gz/from/this/mirror" } <ide> <del> it { is_expected.to eq(HOMEBREW_CACHE/"foo--1.2.3.tar.gz") } <add> it { is_expected.to eq(HOMEBREW_CACHE/"downloads/1ab61269ba52c83994510b1e28dd04167a2f2e8393a35a9c50c1f7d33fd8f619--foo.tar.gz") } <ide> end <ide> end <ide> <ide> describe "#fetch" do <ide> before(:each) do <add> subject.temporary_path.dirname.mkpath <ide> FileUtils.touch subject.temporary_path <ide> end <ide> <ide> def setup_git_repo <ide> its("cached_location.extname") { is_expected.to eq(".dmg") } <ide> end <ide> <del> context "with no discernible file name in it" do <del> let(:url) { "https://example.com/download" } <del> its("cached_location.basename.to_path") { is_expected.to eq("foo--1.2.3") } <del> end <del> <ide> context "with a file name trailing the first query parameter" do <ide> let(:url) { "https://example.com/download?file=cask.zip&a=1" } <ide> its("cached_location.extname") { is_expected.to eq(".zip") } <ide> def setup_git_repo <ide> <ide> describe "#fetch" do <ide> before(:each) do <add> subject.temporary_path.dirname.mkpath <ide> FileUtils.touch subject.temporary_path <ide> end <ide>
11
Ruby
Ruby
add pinned status to info
040138164bf3f8e17ba05be4b135455c03bb0cf5
<ide><path>Library/Homebrew/cmd/info.rb <ide> def info_formula f <ide> specs << "devel #{f.devel.version}" if f.devel <ide> specs << "HEAD" if f.head <ide> <del> puts "#{f.name}: #{specs*', '}" <add> puts "#{f.name}: #{specs*', '}#{' (pinned)' if f.pinned?}" <ide> <ide> puts f.homepage <ide>
1
Javascript
Javascript
drop inaccessible methods
8181272fe8e4897391335b14b0c9aac3db4bd3c9
<ide><path>src/core/ReactComponent.js <ide> var ReactComponent = { <ide> mountImageIntoNode(markup, container, shouldReuseMarkup); <ide> }, <ide> <del> /** <del> * Checks if this component is owned by the supplied `owner` component. <del> * <del> * @param {ReactComponent} owner Component to check. <del> * @return {boolean} True if `owners` owns this component. <del> * @final <del> * @internal <del> */ <del> isOwnedBy: function(owner) { <del> return this._owner === owner; <del> }, <del> <del> /** <del> * Gets another component, that shares the same owner as this one, by ref. <del> * <del> * @param {string} ref of a sibling Component. <del> * @return {?ReactComponent} the actual sibling Component. <del> * @final <del> * @internal <del> */ <del> getSiblingByRef: function(ref) { <del> var owner = this._owner; <del> if (!owner || !owner.refs) { <del> return null; <del> } <del> return owner.refs[ref]; <del> }, <del> <ide> /** <ide> * Get the publicly accessible representation of this component - i.e. what <ide> * is exposed by refs and renderComponent. Can be null for stateless <ide><path>src/core/ReactOwner.js <ide> var ReactOwner = { <ide> * @private <ide> */ <ide> attachRef: function(ref, component) { <del> // TODO: Remove this invariant. This is never exposed and cannot be called <del> // by user code. The unit test is already removed. <del> invariant( <del> component.isOwnedBy(this), <del> 'attachRef(%s, ...): Only a component\'s owner can store a ref to it.', <del> ref <del> ); <ide> var inst = this.getPublicInstance(); <ide> var refs = inst.refs === emptyObject ? (inst.refs = {}) : inst.refs; <ide> refs[ref] = component.getPublicInstance();
2
Text
Text
fix links to 09-advanced.md (was 07-advanced.md)
9d7a0fb93ef23fd76ee41596b36235aaf988dcf4
<ide><path>CONTRIBUTING.md <ide> Using issues <ide> <ide> The [issue tracker](https://github.com/chartjs/Chart.js/issues) is the preferred channel for reporting bugs, requesting new features and submitting pull requests. <ide> <del>If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#writing-new-chart-types) in the documentation or consider [creating a plugin](https://github.com/chartjs/Chart.js/blob/master/docs/07-Advanced.md#creating-plugins). <add>If you're suggesting a new chart type, please take a look at [writing new chart types](https://github.com/chartjs/Chart.js/blob/master/docs/09-Advanced.md#writing-new-chart-types) in the documentation or consider [creating a plugin](https://github.com/chartjs/Chart.js/blob/master/docs/09-Advanced.md#creating-plugins). <ide> <ide> To keep the library lightweight for everyone, it's unlikely we'll add many more chart types to the core of Chart.js, but issues are a good medium to design and spec out how new chart types could work and look. <ide>
1
Ruby
Ruby
dup the callback and set the chain
91e002e31eb50329a5936dab3286b41571868653
<ide><path>activesupport/lib/active_support/callbacks.rb <ide> def deprecate_per_key_option(options) <ide> end <ide> end <ide> <del> def clone(chain) <del> obj = super() <del> obj.chain = chain <del> obj.options = @options.dup <del> obj.options[:if] = @options[:if].dup <del> obj.options[:unless] = @options[:unless].dup <del> obj <add> def initialize_copy(other) <add> super <add> @options = { <add> :if => other.options[:if].dup, <add> :unless => other.options[:unless].dup <add> } <ide> end <ide> <ide> def normalize_options!(options) <ide> def skip_callback(name, *filter_list, &block) <ide> filter = chain.find {|c| c.matches?(type, filter) } <ide> <ide> if filter && options.any? <del> new_filter = filter.clone(chain) <add> new_filter = filter.dup <add> new_filter.chain = chain <ide> chain.insert(chain.index(filter), new_filter) <ide> new_filter.recompile!(options) <ide> end
1
Javascript
Javascript
escape path variables in replaced values
362e5d37d67d8c582dd11a48d3019bbeefa590fa
<ide><path>lib/TemplatedPathPlugin.js <ide> const getReplacer = (value, allowEmpty) => { <ide> return fn; <ide> }; <ide> <add>const escapePathVariables = value => { <add> return typeof value === "string" <add> ? value.replace( <add> /\[(name|id|moduleid|file|query|filebase|url|hash|chunkhash|modulehash|contenthash)\]/g, <add> "[\\$1\\]" <add> ) <add> : value; <add>}; <add> <ide> const replacePathVariables = (path, data) => { <ide> const chunk = data.chunk; <del> const chunkId = chunk && chunk.id; <del> const chunkName = chunk && (chunk.name || chunk.id); <add> let chunkId = chunk && chunk.id; <add> let chunkName = chunk && (chunk.name || chunk.id); <ide> const chunkHash = chunk && (chunk.renderedHash || chunk.hash); <ide> const chunkHashWithLength = chunk && chunk.hashWithLength; <ide> const contentHashType = data.contentHashType; <ide> const replacePathVariables = (path, data) => { <ide> chunk.contentHashWithLength[contentHashType]) || <ide> data.contentHashWithLength; <ide> const module = data.module; <del> const moduleId = module && module.id; <add> let moduleId = module && module.id; <ide> const moduleHash = module && (module.renderedHash || module.hash); <ide> const moduleHashWithLength = module && module.hashWithLength; <ide> <ide> const replacePathVariables = (path, data) => { <ide> ); <ide> } <ide> <add> // we need to escape path variables e.g. [name] in replaced values <add> // to prevent unexpected extra replaces from a filename having the variable <add> chunkId = escapePathVariables(chunkId); <add> moduleId = escapePathVariables(moduleId); <add> chunkName = escapePathVariables(chunkName); <add> <ide> return ( <ide> path <ide> .replace( <ide> const replacePathVariables = (path, data) => { <ide> .replace(REGEXP_ID, getReplacer(chunkId)) <ide> .replace(REGEXP_MODULEID, getReplacer(moduleId)) <ide> .replace(REGEXP_NAME, getReplacer(chunkName)) <del> .replace(REGEXP_FILE, getReplacer(data.filename)) <del> .replace(REGEXP_FILEBASE, getReplacer(data.basename)) <add> .replace(REGEXP_FILE, getReplacer(escapePathVariables(data.filename))) <add> .replace(REGEXP_FILEBASE, getReplacer(escapePathVariables(data.basename))) <ide> // query is optional, it's OK if it's in a path but there's nothing to replace it with <ide> .replace(REGEXP_QUERY, getReplacer(data.query, true)) <ide> // only available in sourceMappingURLComment <ide> .replace(REGEXP_URL, getReplacer(data.url)) <add> .replace(/\[\\/g, "[") <add> .replace(/\\\]/g, "]") <ide> ); <ide> }; <ide> <ide><path>test/HotModuleReplacementPlugin.test.js <ide> describe("HotModuleReplacementPlugin", () => { <ide> }); <ide> }); <ide> }); <add> <add> it("should handle entryFile that contains path variable", done => { <add> const entryFile = path.join( <add> __dirname, <add> "js", <add> "HotModuleReplacementPlugin", <add> "[name]", <add> "entry.js" <add> ); <add> const statsFile3 = path.join( <add> __dirname, <add> "js", <add> "HotModuleReplacementPlugin", <add> "HotModuleReplacementPlugin.test.stats3.txt" <add> ); <add> const statsFile4 = path.join( <add> __dirname, <add> "js", <add> "HotModuleReplacementPlugin", <add> "HotModuleReplacementPlugin.test.stats4.txt" <add> ); <add> const recordsFile = path.join( <add> __dirname, <add> "js", <add> "HotModuleReplacementPlugin", <add> "records.json" <add> ); <add> try { <add> mkdirp.sync( <add> path.join(__dirname, "js", "HotModuleReplacementPlugin", "[name]") <add> ); <add> } catch (e) { <add> // empty <add> } <add> try { <add> fs.unlinkSync(recordsFile); <add> } catch (e) { <add> // empty <add> } <add> const compiler = webpack({ <add> mode: "development", <add> cache: false, <add> entry: { <add> "[name]/entry.js": entryFile <add> }, <add> recordsPath: recordsFile, <add> output: { <add> filename: "[name]", <add> chunkFilename: "[name].js", <add> path: path.join(__dirname, "js", "HotModuleReplacementPlugin"), <add> hotUpdateChunkFilename: "static/webpack/[id].[hash].hot-update.js", <add> hotUpdateMainFilename: "static/webpack/[hash].hot-update.json" <add> }, <add> plugins: [new webpack.HotModuleReplacementPlugin()], <add> optimization: { <add> namedChunks: true <add> } <add> }); <add> fs.writeFileSync(entryFile, "1", "utf-8"); <add> compiler.run((err, stats) => { <add> if (err) throw err; <add> fs.writeFileSync(statsFile3, stats.toString()); <add> compiler.run((err, stats) => { <add> if (err) throw err; <add> fs.writeFileSync(statsFile4, stats.toString()); <add> fs.writeFileSync(entryFile, "2", "utf-8"); <add> compiler.run((err, stats) => { <add> if (err) throw err; <add> fs.writeFileSync(statsFile3, stats.toString()); <add> <add> let foundUpdates = false; <add> <add> Object.keys(stats.compilation.assets).forEach(key => { <add> foundUpdates = <add> foundUpdates || <add> !!key.match( <add> /static\/webpack\/\[name\]\/entry\.js\..*?\.hot-update\.js/ <add> ); <add> }); <add> <add> expect(foundUpdates).toBe(true); <add> done(); <add> }); <add> }); <add> }); <add> }); <ide> });
2
Python
Python
add do_lower_case in examples
0541442558edb3771ec469b46bf236c0679a1cb2
<ide><path>examples/extract_features.py <ide> def main(): <ide> "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese.") <ide> <ide> ## Other parameters <add> parser.add_argument("--do_lower_case", default=False, action='store_true', help="Set this flag if you are using an uncased model.") <ide> parser.add_argument("--layers", default="-1,-2,-3,-4", type=str) <ide> parser.add_argument("--max_seq_length", default=128, type=int, <ide> help="The maximum total input sequence length after WordPiece tokenization. Sequences longer " <ide> def main(): <ide> <ide> layer_indexes = [int(x) for x in args.layers.split(",")] <ide> <del> tokenizer = BertTokenizer.from_pretrained(args.bert_model) <add> tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case) <ide> <ide> examples = read_examples(args.input_file) <ide> <ide><path>examples/run_classifier.py <ide> def main(): <ide> default=False, <ide> action='store_true', <ide> help="Whether to run eval on the dev set.") <add> parser.add_argument("--do_lower_case", <add> default=False, <add> action='store_true', <add> help="Set this flag if you are using an uncased model.") <ide> parser.add_argument("--train_batch_size", <ide> default=32, <ide> type=int, <ide> def main(): <ide> processor = processors[task_name]() <ide> label_list = processor.get_labels() <ide> <del> tokenizer = BertTokenizer.from_pretrained(args.bert_model) <add> tokenizer = BertTokenizer.from_pretrained(args.bert_model, do_lower_case=args.do_lower_case) <ide> <ide> train_examples = None <ide> num_train_steps = None
2
Ruby
Ruby
combine git existence and version checks
255c6e7c3fb34fbf8bd8899a051beec930fc7a4d
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_filesystem_case_sensitive <ide> EOS <ide> end <ide> <add>def __check_git_version <add> # https://help.github.com/articles/https-cloning-errors <add> `git --version`.chomp =~ /git version ((?:\d+\.?)+)/ <add> <add> if Version.new($1) < Version.new("1.7.10") then <<-EOS.undent <add> An outdated version of Git was detected in your PATH. <add> Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub. <add> Please upgrade: brew upgrade git <add> EOS <add> end <add>end <add> <ide> def check_for_git <del> unless which "git" then <<-EOS.undent <add> if which "git" <add> __check_git_version <add> else <<-EOS.undent <ide> Git could not be found in your PATH. <ide> Homebrew uses Git for several internal functions, and some formulae use Git <ide> checkouts instead of stable tarballs. You may want to install Git: <ide> def check_for_leopard_ssl <ide> end <ide> end <ide> <del>def check_git_version <del> # https://help.github.com/articles/https-cloning-errors <del> return unless which "git" <del> <del> `git --version`.chomp =~ /git version ((?:\d+\.?)+)/ <del> <del> if Version.new($1) < Version.new("1.7.10") then <<-EOS.undent <del> An outdated version of Git was detected in your PATH. <del> Git 1.7.10 or newer is required to perform checkouts over HTTPS from GitHub. <del> Please upgrade: brew upgrade git <del> EOS <del> end <del>end <del> <ide> def check_for_enthought_python <ide> if which "enpkg" then <<-EOS.undent <ide> Enthought Python was found in your PATH.
1
PHP
PHP
add check for simple equals
4df653ef08ce2d6035acb21c4192bb2886e3f6e1
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php <ide> protected function originalIsEquivalent($key, $current) <ide> return false; <ide> } <ide> <del> $original = $this->getOriginal($key); <add> if ($current === $original = $this->getOriginal($key)) { <add> return true; <add> } <ide> <ide> if ($this->isDateAttribute($key)) { <ide> return $this->fromDateTime($current) === $this->fromDateTime($original);
1
Python
Python
add 5 epoch warmup to resnet
9bf586de5199644ef88e4f3899b33a52f8329e44
<ide><path>official/resnet/cifar10_test.py <ide> def test_cifar10_end_to_end_synthetic_v2(self): <ide> extra_flags=['-resnet_version', '2'] <ide> ) <ide> <del> def test_flag_restriction(self): <del> with self.assertRaises(SystemExit): <del> integration.run_synthetic( <del> main=cifar10_main.run_cifar, tmp_root=self.get_temp_dir(), <del> extra_flags=['-resnet_version', '1', "-dtype", "fp16"] <del> ) <del> <ide> <ide> if __name__ == '__main__': <ide> tf.test.main() <ide><path>official/resnet/imagenet_main.py <ide> def _get_block_sizes(resnet_size): <ide> <ide> def imagenet_model_fn(features, labels, mode, params): <ide> """Our model_fn for ResNet to be used with our Estimator.""" <add> <add> # Warmup and higher lr may not be valid for fine tuning with small batches <add> # and smaller numbers of training images. <add> if params['fine_tune']: <add> warmup = False <add> base_lr = .1 <add> else: <add> warmup = True <add> base_lr = .128 <add> <ide> learning_rate_fn = resnet_run_loop.learning_rate_with_decay( <ide> batch_size=params['batch_size'], batch_denom=256, <ide> num_images=_NUM_IMAGES['train'], boundary_epochs=[30, 60, 80, 90], <del> decay_rates=[1, 0.1, 0.01, 0.001, 1e-4]) <add> decay_rates=[1, 0.1, 0.01, 0.001, 1e-4], warmup=warmup, base_lr=base_lr) <ide> <ide> return resnet_run_loop.resnet_model_fn( <ide> features=features, <ide><path>official/resnet/imagenet_test.py <ide> def test_imagenet_end_to_end_synthetic_v2_huge(self): <ide> extra_flags=['-resnet_version', '2', '-resnet_size', '200'] <ide> ) <ide> <del> def test_flag_restriction(self): <del> with self.assertRaises(SystemExit): <del> integration.run_synthetic( <del> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(), <del> extra_flags=['-resnet_version', '1', '-dtype', 'fp16'] <del> ) <del> <ide> <ide> if __name__ == '__main__': <ide> tf.test.main() <ide><path>official/resnet/resnet_run_loop.py <ide> def input_fn(is_training, data_dir, batch_size, *args, **kwargs): # pylint: dis <ide> # Functions for running training/eval/validation loops for the model. <ide> ################################################################################ <ide> def learning_rate_with_decay( <del> batch_size, batch_denom, num_images, boundary_epochs, decay_rates): <add> batch_size, batch_denom, num_images, boundary_epochs, decay_rates, <add> base_lr=0.1, warmup=False): <ide> """Get a learning rate that decays step-wise as training progresses. <ide> <ide> Args: <ide> def learning_rate_with_decay( <ide> decay_rates: list of floats representing the decay rates to be used <ide> for scaling the learning rate. It should have one more element <ide> than `boundary_epochs`, and all elements should have the same type. <del> <add> base_lr: Initial learning rate scaled based on batch_denom. <add> warmup: Run a 5 epoch warmup to the initial lr. <ide> Returns: <ide> Returns a function that takes a single argument - the number of batches <ide> trained so far (global_step)- and returns the learning rate to be used <ide> for training the next batch. <ide> """ <del> initial_learning_rate = 0.1 * batch_size / batch_denom <add> initial_learning_rate = base_lr * batch_size / batch_denom <ide> batches_per_epoch = num_images / batch_size <ide> <ide> # Reduce the learning rate at certain epochs. <ide> def learning_rate_with_decay( <ide> vals = [initial_learning_rate * decay for decay in decay_rates] <ide> <ide> def learning_rate_fn(global_step): <del> global_step = tf.cast(global_step, tf.int32) <del> return tf.train.piecewise_constant(global_step, boundaries, vals) <add> """Builds scaled learning rate function with 5 epoch warm up.""" <add> lr = tf.train.piecewise_constant(global_step, boundaries, vals) <add> if warmup: <add> warmup_steps = int(batches_per_epoch * 5) <add> warmup_lr = ( <add> initial_learning_rate * tf.cast(global_step, tf.float32) / tf.cast( <add> warmup_steps, tf.float32)) <add> return tf.cond(global_step < warmup_steps, lambda: warmup_lr, lambda: lr) <add> return lr <ide> <ide> return learning_rate_fn <ide> <ide> def define_resnet_flags(resnet_size_choices=None): <ide> flags.DEFINE_string(**choice_kwargs) <ide> else: <ide> flags.DEFINE_enum(enum_values=resnet_size_choices, **choice_kwargs) <del> <del> # The current implementation of ResNet v1 is numerically unstable when run <del> # with fp16 and will produce NaN errors soon after training begins. <del> msg = ('ResNet version 1 is not currently supported with fp16. ' <del> 'Please use version 2 instead.') <del> @flags.multi_flags_validator(['dtype', 'resnet_version'], message=msg) <del> def _forbid_v1_fp16(flag_values): # pylint: disable=unused-variable <del> return (flags_core.DTYPE_MAP[flag_values['dtype']][0] != tf.float16 or <del> flag_values['resnet_version'] != '1')
4
Python
Python
fix the error message in run_t5_mlm_flax.py
e150c4e2fec67d6cbe8458d989a139b07ea1fe05
<ide><path>examples/flax/language-modeling/run_t5_mlm_flax.py <ide> def __call__(self, examples: List[Dict[str, np.ndarray]]) -> BatchEncoding: <ide> if batch["input_ids"].shape[-1] != self.input_length: <ide> raise ValueError( <ide> f"`input_ids` are incorrectly preprocessed. `input_ids` length is {batch['input_ids'].shape[-1]}, but" <del> f" should be {self.target_length}." <add> f" should be {self.input_length}." <ide> ) <ide> <ide> if batch["labels"].shape[-1] != self.target_length:
1
Java
Java
add support for @serverendpoint annotated classes
914e969ac3a90270d262c4cb817a5ed1eecb2baa
<ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointExporter.java <ide> */ <ide> package org.springframework.websocket.server.endpoint; <ide> <add>import java.util.Map; <add> <ide> import javax.websocket.DeploymentException; <ide> import javax.websocket.server.ServerContainer; <ide> import javax.websocket.server.ServerContainerProvider; <add>import javax.websocket.server.ServerEndpoint; <ide> import javax.websocket.server.ServerEndpointConfig; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.beans.BeansException; <add>import org.springframework.beans.factory.BeanFactory; <add>import org.springframework.beans.factory.BeanFactoryAware; <ide> import org.springframework.beans.factory.InitializingBean; <add>import org.springframework.beans.factory.ListableBeanFactory; <ide> import org.springframework.beans.factory.config.BeanPostProcessor; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.ObjectUtils; <ide> <ide> /** <ide> * BeanPostProcessor that detects beans of type <del> * {@link javax.websocket.server.ServerEndpointConfig} and registers them with a standard <del> * Java WebSocket runtime and also configures the underlying <del> * {@link javax.websocket.server.ServerContainer}. <add> * {@link javax.websocket.server.ServerEndpointConfig} and registers the corresponding <add> * {@link javax.websocket.Endpoint} with a standard Java WebSocket runtime. <ide> * <ide> * <p>If the runtime is a Servlet container, use {@link ServletEndpointExporter}. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @since 4.0 <ide> */ <del>public class EndpointExporter implements BeanPostProcessor, InitializingBean { <add>public class EndpointExporter implements InitializingBean, BeanPostProcessor, BeanFactoryAware { <ide> <ide> private static Log logger = LogFactory.getLog(EndpointExporter.class); <ide> <add> private Class<?>[] annotatedEndpointClasses; <add> <ide> private Long maxSessionIdleTimeout; <ide> <ide> private Integer maxTextMessageBufferSize; <ide> <ide> private Integer maxBinaryMessageBufferSize; <ide> <ide> <add> /** <add> * TODO <add> * @param annotatedEndpointClasses <add> */ <add> public void setAnnotatedEndpointClasses(Class<?>... annotatedEndpointClasses) { <add> this.annotatedEndpointClasses = annotatedEndpointClasses; <add> } <add> <ide> /** <ide> * If this property set it is in turn used to configure <ide> * {@link ServerContainer#setDefaultMaxSessionIdleTimeout(long)}. <ide> public Integer getMaxBinaryMessageBufferSize() { <ide> return this.maxBinaryMessageBufferSize; <ide> } <ide> <add> @Override <add> public void setBeanFactory(BeanFactory beanFactory) throws BeansException { <add> if (beanFactory instanceof ListableBeanFactory) { <add> ListableBeanFactory lbf = (ListableBeanFactory) beanFactory; <add> Map<String, Object> annotatedEndpoints = lbf.getBeansWithAnnotation(ServerEndpoint.class); <add> for (String beanName : annotatedEndpoints.keySet()) { <add> Class<?> beanType = lbf.getType(beanName); <add> try { <add> if (logger.isInfoEnabled()) { <add> logger.info("Detected @ServerEndpoint bean '" + beanName + "', registering it as an endpoint by type"); <add> } <add> ServerContainerProvider.getServerContainer().addEndpoint(beanType); <add> } <add> catch (DeploymentException e) { <add> throw new IllegalStateException("Failed to register @ServerEndpoint bean type " + beanName, e); <add> } <add> } <add> } <add> } <add> <ide> @Override <ide> public void afterPropertiesSet() throws Exception { <add> <ide> ServerContainer serverContainer = ServerContainerProvider.getServerContainer(); <ide> Assert.notNull(serverContainer, "javax.websocket.server.ServerContainer not available"); <ide> <ide> public void afterPropertiesSet() throws Exception { <ide> if (this.maxBinaryMessageBufferSize != null) { <ide> serverContainer.setDefaultMaxBinaryMessageBufferSize(this.maxBinaryMessageBufferSize); <ide> } <add> <add> if (!ObjectUtils.isEmpty(this.annotatedEndpointClasses)) { <add> for (Class<?> clazz : this.annotatedEndpointClasses) { <add> try { <add> logger.info("Registering @ServerEndpoint type " + clazz); <add> serverContainer.addEndpoint(clazz); <add> } <add> catch (DeploymentException e) { <add> throw new IllegalStateException("Failed to register @ServerEndpoint type " + clazz, e); <add> } <add> } <add> } <ide> } <ide> <ide> @Override <ide> public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { <ide> if (bean instanceof ServerEndpointConfig) { <ide> ServerEndpointConfig sec = (ServerEndpointConfig) bean; <del> ServerContainer serverContainer = ServerContainerProvider.getServerContainer(); <ide> try { <del> logger.debug("Registering javax.websocket.Endpoint for path " + sec.getPath()); <del> serverContainer.addEndpoint(sec); <add> if (logger.isInfoEnabled()) { <add> logger.info("Registering bean '" + beanName <add> + "' as javax.websocket.Endpoint under path " + sec.getPath()); <add> } <add> ServerContainerProvider.getServerContainer().addEndpoint(sec); <ide> } <ide> catch (DeploymentException e) { <del> throw new IllegalStateException("Failed to deploy Endpoint " + bean, e); <add> throw new IllegalStateException("Failed to deploy Endpoint bean " + bean, e); <ide> } <ide> } <ide> return bean; <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/EndpointRegistration.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ClassUtils; <ide> import org.springframework.web.context.ContextLoader; <add>import org.springframework.web.context.WebApplicationContext; <ide> import org.springframework.websocket.WebSocketHandler; <ide> import org.springframework.websocket.endpoint.StandardWebSocketHandlerAdapter; <ide> <ide> public class EndpointRegistration implements ServerEndpointConfig, BeanFactoryAw <ide> <ide> private final String path; <ide> <add> private final Class<? extends Endpoint> endpointClass; <add> <ide> private final Object bean; <ide> <ide> private List<String> subprotocols = new ArrayList<String>(); <ide> public class EndpointRegistration implements ServerEndpointConfig, BeanFactoryAw <ide> private final Configurator configurator = new Configurator() {}; <ide> <ide> <del> // ContextLoader.getCurrentWebApplicationContext().getAutowireCapableBeanFactory().createBean(Class<T>) <add> /** <add> * Class constructor with the {@code javax.webscoket.Endpoint} class. <add> * TODO <add> * <add> * @param path <add> * @param endpointClass <add> */ <add> public EndpointRegistration(String path, Class<? extends Endpoint> endpointClass) { <add> this(path, endpointClass, null); <add> } <add> <add> public EndpointRegistration(String path, Object bean) { <add> this(path, null, bean); <add> } <ide> <ide> public EndpointRegistration(String path, String beanName) { <del> Assert.hasText(path, "path must not be empty"); <del> Assert.notNull(beanName, "beanName is required"); <del> this.path = path; <del> this.bean = beanName; <add> this(path, null, beanName); <ide> } <ide> <del> public EndpointRegistration(String path, Object bean) { <add> private EndpointRegistration(String path, Class<? extends Endpoint> endpointClass, Object bean) { <ide> Assert.hasText(path, "path must not be empty"); <del> Assert.notNull(bean, "bean is required"); <add> Assert.isTrue((endpointClass != null || bean != null), "Neither endpoint class nor endpoint bean provided"); <ide> this.path = path; <add> this.endpointClass = endpointClass; <ide> this.bean = bean; <add> // this will fail if the bean is not a valid Endpoint type <add> getEndpointClass(); <ide> } <ide> <ide> @Override <ide> public String getPath() { <ide> @SuppressWarnings("unchecked") <ide> @Override <ide> public Class<? extends Endpoint> getEndpointClass() { <add> if (this.endpointClass != null) { <add> return this.endpointClass; <add> } <ide> Class<?> beanClass = this.bean.getClass(); <ide> if (beanClass.equals(String.class)) { <ide> beanClass = this.beanFactory.getType((String) this.bean); <ide> } <ide> beanClass = ClassUtils.getUserClass(beanClass); <del> if (WebSocketHandler.class.isAssignableFrom(beanClass)) { <add> if (Endpoint.class.isAssignableFrom(beanClass)) { <add> return (Class<? extends Endpoint>) beanClass; <add> } <add> else if (WebSocketHandler.class.isAssignableFrom(beanClass)) { <ide> return StandardWebSocketHandlerAdapter.class; <ide> } <ide> else { <del> return (Class<? extends Endpoint>) beanClass; <add> throw new IllegalStateException("Invalid endpoint bean: must be of type ... TODO "); <ide> } <ide> } <ide> <ide> public Endpoint getEndpoint() { <add> if (this.endpointClass != null) { <add> WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); <add> if (wac == null) { <add> throw new IllegalStateException("Failed to find WebApplicationContext. " <add> + "Was org.springframework.web.context.ContextLoader used to load the WebApplicationContext?"); <add> } <add> return wac.getAutowireCapableBeanFactory().createBean(this.endpointClass); <add> } <ide> Object bean = this.bean; <ide> if (this.bean instanceof String) { <ide> bean = this.beanFactory.getBean((String) this.bean); <ide><path>spring-websocket/src/main/java/org/springframework/websocket/server/endpoint/SpringConfigurator.java <add>/* <add> * Copyright 2002-2013 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.websocket.server.endpoint; <add> <add>import java.util.Map; <add> <add>import javax.websocket.server.ServerEndpoint; <add>import javax.websocket.server.ServerEndpointConfig.Configurator; <add> <add>import org.springframework.web.context.ContextLoader; <add>import org.springframework.web.context.WebApplicationContext; <add> <add> <add>/** <add> * This should be used in conjuction with {@link ServerEndpoint @ServerEndpoint} classes. <add> * <add> * <p>For {@link javax.websocket.Endpoint}, see {@link EndpointExporter}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class SpringConfigurator extends Configurator { <add> <add> <add> @Override <add> public <T> T getEndpointInstance(Class<T> endpointClass) throws InstantiationException { <add> <add> WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext(); <add> if (wac == null) { <add> throw new IllegalStateException("Failed to find WebApplicationContext. " <add> + "Was org.springframework.web.context.ContextLoader used to load the WebApplicationContext?"); <add> } <add> <add> Map<String, T> beans = wac.getBeansOfType(endpointClass); <add> if (beans.isEmpty()) { <add> // Initialize a new bean instance <add> return wac.getAutowireCapableBeanFactory().createBean(endpointClass); <add> } <add> if (beans.size() == 1) { <add> // Return the matching bean instance <add> return beans.values().iterator().next(); <add> } <add> else { <add> // This should never happen (@ServerEndpoint has a single path mapping) .. <add> throw new IllegalStateException("Found more than one matching beans of type " + endpointClass); <add> } <add> } <add> <add>}
3
Go
Go
simplify networkoverlaps function
26ac09e004a0d0b82c74d84d0936030940ac8454
<ide><path>libnetwork/netutils/utils.go <ide> func CheckRouteOverlaps(toCheck *net.IPNet) error { <ide> <ide> // NetworkOverlaps detects overlap between one IPNet and another <ide> func NetworkOverlaps(netX *net.IPNet, netY *net.IPNet) bool { <del> // Check if both netX and netY are ipv4 or ipv6 <del> if (netX.IP.To4() != nil && netY.IP.To4() != nil) || <del> (netX.IP.To4() == nil && netY.IP.To4() == nil) { <del> if firstIP, _ := NetworkRange(netX); netY.Contains(firstIP) { <del> return true <del> } <del> if firstIP, _ := NetworkRange(netY); netX.Contains(firstIP) { <del> return true <del> } <del> } <del> return false <add> return netX.Contains(netY.IP) || netY.Contains(netX.IP) <ide> } <ide> <ide> // NetworkRange calculates the first and last IP addresses in an IPNet
1
Go
Go
unify readmeminfo implementation
ec878a3d895a635e1fefaa27efe83869a1b6b601
<ide><path>pkg/sysinfo/meminfo.go <ide> package sysinfo <ide> <add>// ReadMemInfo retrieves memory statistics of the host system and returns a <add>// Memory type. It is only supported on Linux and Windows, and returns an <add>// error on other platforms. <add>func ReadMemInfo() (*Memory, error) { <add> return readMemInfo() <add>} <add> <ide> // Memory contains memory statistics of the host system. <ide> type Memory struct { <ide> // Total usable RAM (i.e. physical RAM minus a few reserved bits and the <ide><path>pkg/sysinfo/meminfo_linux.go <ide> import ( <ide> "strings" <ide> ) <ide> <del>// ReadMemInfo retrieves memory statistics of the host system and returns a <add>// readMemInfo retrieves memory statistics of the host system and returns a <ide> // Memory type. <del>func ReadMemInfo() (*Memory, error) { <add>func readMemInfo() (*Memory, error) { <ide> file, err := os.Open("/proc/meminfo") <ide> if err != nil { <ide> return nil, err <ide><path>pkg/sysinfo/meminfo_unsupported.go <ide> package sysinfo <ide> <ide> import "errors" <ide> <del>// ReadMemInfo is not supported on platforms other than linux and windows. <del>func ReadMemInfo() (*Memory, error) { <add>// readMemInfo is not supported on platforms other than linux and windows. <add>func readMemInfo() (*Memory, error) { <ide> return nil, errors.New("platform and architecture is not supported") <ide> } <ide><path>pkg/sysinfo/meminfo_windows.go <ide> type memorystatusex struct { <ide> <ide> // ReadMemInfo retrieves memory statistics of the host system and returns a <ide> // Memory type. <del>func ReadMemInfo() (*Memory, error) { <add>func readMemInfo() (*Memory, error) { <ide> msi := &memorystatusex{ <ide> dwLength: 64, <ide> }
4
Go
Go
use correct logger
1d2a6694450e8f2883e98823d9d937dab4241c7f
<ide><path>libcontainerd/supervisor/remote_daemon.go <ide> func (r *remote) startContainerd() error { <ide> <ide> if pid != -1 { <ide> r.daemonPid = pid <del> logrus.WithField("pid", pid). <del> Infof("libcontainerd: %s is still running", binaryName) <add> r.logger.WithField("pid", pid).Infof("%s is still running", binaryName) <ide> return nil <ide> } <ide> <ide> func (r *remote) startContainerd() error { <ide> return errors.Wrap(err, "libcontainerd: failed to save daemon pid to disk") <ide> } <ide> <del> logrus.WithField("pid", r.daemonPid). <del> Infof("libcontainerd: started new %s process", binaryName) <add> r.logger.WithField("pid", r.daemonPid).Infof("started new %s process", binaryName) <ide> <ide> return nil <ide> } <ide> func (r *remote) monitorDaemon(ctx context.Context) { <ide> delay = 100 * time.Millisecond <ide> continue <ide> } <del> logrus.WithField("address", r.GRPC.Address).Debug("Created containerd monitoring client") <add> r.logger.WithField("address", r.GRPC.Address).Debug("created containerd monitoring client") <ide> } <ide> <ide> if client != nil {
1
PHP
PHP
use file cache as the default cache engine
2f7f5e13224537eaa4da6b825b1d106bebc35d05
<ide><path>app/Config/core.php <ide> //date_default_timezone_set('UTC'); <ide> <ide> /** <del> * Pick the caching engine to use. If APC is enabled use it. <del> * If running via cli - apc is disabled by default. ensure it's available and enabled in this case <add> * Configure the cache handlers that CakePHP will use for internal <add> * metadata like class maps, and model schema. <add> * <add> * By default File is used, but for improved performance you should use APC. <ide> * <ide> * Note: 'default' and other application caches should be configured in app/Config/bootstrap.php. <ide> * Please check the comments in boostrap.php for more info on the cache engines available <ide> * and their setttings. <ide> */ <ide> $engine = 'File'; <del>if (extension_loaded('apc') && function_exists('apc_dec') && (php_sapi_name() !== 'cli' || ini_get('apc.enable_cli'))) { <del> $engine = 'Apc'; <del>} <ide> <ide> // In development mode, caches should expire quickly. <ide> $duration = '+999 days'; <ide><path>lib/Cake/Console/Templates/skel/Config/core.php <ide> */ <ide> <ide> /** <del> * Pick the caching engine to use. If APC is enabled use it. <del> * If running via cli - apc is disabled by default. ensure it's available and enabled in this case <add> * Configure the cache handlers that CakePHP will use for internal <add> * metadata like class maps, and model schema. <ide> * <add> * By default File is used, but for improved performance you should use APC. <add> * <add> * Note: 'default' and other application caches should be configured in app/Config/bootstrap.php. <add> * Please check the comments in boostrap.php for more info on the cache engines available <add> * and their setttings. <ide> */ <ide> $engine = 'File'; <del>if (extension_loaded('apc') && function_exists('apc_dec') && (php_sapi_name() !== 'cli' || ini_get('apc.enable_cli'))) { <del> $engine = 'Apc'; <del>} <ide> <ide> // In development mode, caches should expire quickly. <ide> $duration = '+999 days';
2
Go
Go
return listenbuffer behavior
281a48d092fa84500c63b984ad45c59a06f301c4
<ide><path>api/server/server.go <ide> func (s *Server) Close() { <ide> } <ide> <ide> // ServeAPI loops through all initialized servers and spawns goroutine <del>// with Server method for each. It sets CreateMux() as Handler also. <add>// with Serve() method for each. <ide> func (s *Server) ServeAPI() error { <ide> var chErrors = make(chan error, len(s.servers)) <ide> for _, srv := range s.servers { <del> srv.srv.Handler = s.CreateMux() <ide> go func(srv *HTTPServer) { <ide> var err error <ide> logrus.Infof("API listen on %s", srv.l.Addr()) <ide> func (s *Server) makeHTTPHandler(handler httputils.APIFunc) http.HandlerFunc { <ide> } <ide> <ide> // InitRouters initializes a list of routers for the server. <add>// Sets those routers as Handler for each server. <ide> func (s *Server) InitRouters(d *daemon.Daemon) { <ide> s.addRouter(local.NewRouter(d)) <ide> s.addRouter(network.NewRouter(d)) <add> for _, srv := range s.servers { <add> srv.srv.Handler = s.CreateMux() <add> } <ide> } <ide> <ide> // addRouter adds a new router to the server. <ide><path>docker/daemon.go <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> logrus.Fatal(err) <ide> } <ide> <add> // The serve API routine never exits unless an error occurs <add> // We need to start it as a goroutine and wait on it so <add> // daemon doesn't exit <add> // All servers must be protected with some mechanism (systemd socket, listenbuffer) <add> // which prevents real handling of request until routes will be set. <add> serveAPIWait := make(chan error) <add> go func() { <add> if err := api.ServeAPI(); err != nil { <add> logrus.Errorf("ServeAPI error: %v", err) <add> serveAPIWait <- err <add> return <add> } <add> serveAPIWait <- nil <add> }() <add> <ide> if err := migrateKey(); err != nil { <ide> logrus.Fatal(err) <ide> } <ide> func (cli *DaemonCli) CmdDaemon(args ...string) error { <ide> <ide> api.InitRouters(d) <ide> <del> // The serve API routine never exits unless an error occurs <del> // We need to start it as a goroutine and wait on it so <del> // daemon doesn't exit <del> serveAPIWait := make(chan error) <del> go func() { <del> if err := api.ServeAPI(); err != nil { <del> logrus.Errorf("ServeAPI error: %v", err) <del> serveAPIWait <- err <del> return <del> } <del> serveAPIWait <- nil <del> }() <del> <ide> signal.Trap(func() { <ide> api.Close() <ide> <-serveAPIWait
2
Text
Text
fix a typo of microtaskmode
4cca942a86af6a6ce2cb8d6ea8ea6e1325d8c58a
<ide><path>doc/api/vm.md <ide> changes: <ide> * `wasm` {boolean} If set to false any attempt to compile a WebAssembly <ide> module will throw a `WebAssembly.CompileError`. **Default:** `true`. <ide> * `microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks <del> scheduled through `Promise`s any `async function`s) will be run immediately <add> scheduled through `Promise`s and `async function`s) will be run immediately <ide> after the script has run. They are included in the `timeout` and <ide> `breakOnSigint` scopes in that case. <ide> * Returns: {any} the result of the very last statement executed in the script. <ide> changes: <ide> * `wasm` {boolean} If set to false any attempt to compile a WebAssembly <ide> module will throw a `WebAssembly.CompileError`. **Default:** `true`. <ide> * `microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks <del> scheduled through `Promise`s any `async function`s) will be run immediately <add> scheduled through `Promise`s and `async function`s) will be run immediately <ide> after a script has run through [`script.runInContext()`][]. <ide> They are included in the `timeout` and `breakOnSigint` scopes in that case. <ide> * Returns: {Object} contextified object. <ide> changes: <ide> recommended in order to take advantage of error tracking, and to avoid <ide> issues with namespaces that contain `then` function exports. <ide> * `microtaskMode` {string} If set to `afterEvaluate`, microtasks (tasks <del> scheduled through `Promise`s any `async function`s) will be run immediately <add> scheduled through `Promise`s and `async function`s) will be run immediately <ide> after the script has run. They are included in the `timeout` and <ide> `breakOnSigint` scopes in that case. <ide> * Returns: {any} the result of the very last statement executed in the script.
1
Javascript
Javascript
add stdio checks to cp-exec-maxbuffer
5f866821adf71ff3ed909d4be8c808197663c110
<ide><path>test/parallel/test-child-process-exec-maxBuffer.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const cp = require('child_process'); <ide> <del>function checkFactory(streamName) { <del> return common.mustCall((err) => { <del> assert.strictEqual(err.message, `${streamName} maxBuffer length exceeded`); <del> assert(err instanceof RangeError); <del> assert.strictEqual(err.code, 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'); <del> }); <add>function runChecks(err, stdio, streamName, expected) { <add> assert.strictEqual(err.message, `${streamName} maxBuffer length exceeded`); <add> assert(err instanceof RangeError); <add> assert.strictEqual(err.code, 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'); <add> assert.deepStrictEqual(stdio[streamName], expected); <ide> } <ide> <ide> { <ide> function checkFactory(streamName) { <ide> { <ide> const cmd = 'echo "hello world"'; <ide> <del> cp.exec(cmd, { maxBuffer: 5 }, checkFactory('stdout')); <add> cp.exec( <add> cmd, <add> { maxBuffer: 5 }, <add> common.mustCall((err, stdout, stderr) => { <add> runChecks(err, { stdout, stderr }, 'stdout', ''); <add> }) <add> ); <ide> } <ide> <ide> const unicode = '中文测试'; // length = 4, byte length = 12 <ide> <ide> { <ide> const cmd = `"${process.execPath}" -e "console.log('${unicode}');"`; <ide> <del> cp.exec(cmd, { maxBuffer: 10 }, checkFactory('stdout')); <add> cp.exec( <add> cmd, <add> { maxBuffer: 10 }, <add> common.mustCall((err, stdout, stderr) => { <add> runChecks(err, { stdout, stderr }, 'stdout', ''); <add> }) <add> ); <ide> } <ide> <ide> { <ide> const cmd = `"${process.execPath}" -e "console.error('${unicode}');"`; <ide> <del> cp.exec(cmd, { maxBuffer: 10 }, checkFactory('stderr')); <add> cp.exec( <add> cmd, <add> { maxBuffer: 3 }, <add> common.mustCall((err, stdout, stderr) => { <add> runChecks(err, { stdout, stderr }, 'stderr', ''); <add> }) <add> ); <ide> } <ide> <ide> { <ide> const unicode = '中文测试'; // length = 4, byte length = 12 <ide> const child = cp.exec( <ide> cmd, <ide> { encoding: null, maxBuffer: 10 }, <del> checkFactory('stdout')); <add> common.mustCall((err, stdout, stderr) => { <add> runChecks(err, { stdout, stderr }, 'stdout', ''); <add> }) <add> ); <ide> <ide> child.stdout.setEncoding('utf-8'); <ide> } <ide> const unicode = '中文测试'; // length = 4, byte length = 12 <ide> <ide> const child = cp.exec( <ide> cmd, <del> { encoding: null, maxBuffer: 10 }, <del> checkFactory('stderr')); <add> { encoding: null, maxBuffer: 3 }, <add> common.mustCall((err, stdout, stderr) => { <add> runChecks(err, { stdout, stderr }, 'stderr', ''); <add> }) <add> ); <ide> <ide> child.stderr.setEncoding('utf-8'); <ide> }
1
Javascript
Javascript
move _scrypt call out of handleerror funct
882e8fea669911a008ccdddd889b92414ca68949
<ide><path>lib/internal/crypto/scrypt.js <ide> function scrypt(password, salt, keylen, options, callback = defaults) { <ide> callback.call(wrap, null, keybuf.toString(encoding)); <ide> }; <ide> <del> handleError(keybuf, password, salt, N, r, p, maxmem, wrap); <add> handleError(_scrypt(keybuf, password, salt, N, r, p, maxmem, wrap)); <ide> } <ide> <ide> function scryptSync(password, salt, keylen, options = defaults) { <ide> options = check(password, salt, keylen, options); <ide> const { N, r, p, maxmem } = options; <ide> ({ password, salt, keylen } = options); <ide> const keybuf = Buffer.alloc(keylen); <del> handleError(keybuf, password, salt, N, r, p, maxmem); <add> handleError(_scrypt(keybuf, password, salt, N, r, p, maxmem)); <ide> const encoding = getDefaultEncoding(); <ide> if (encoding === 'buffer') return keybuf; <ide> return keybuf.toString(encoding); <ide> } <ide> <del>function handleError(keybuf, password, salt, N, r, p, maxmem, wrap) { <del> const ex = _scrypt(keybuf, password, salt, N, r, p, maxmem, wrap); <del> <add>function handleError(ex) { <ide> if (ex === undefined) <ide> return; <ide>
1
Text
Text
update functional api guide
f981bdb5514c3b1489fd7def6acf91433dd11bda
<ide><path>docs/templates/getting-started/complete_guide_to_the_keras_functional_api.md <ide> <ide> The `Sequential` model is probably a better choice to implement such a network, but it helps to start with something really simple. <ide> <add>- As you can see, a layer instance is callable (on a tensor), and it returns a tensor <add>- Input tensor(s) and output tensor(s) can then be used to define a `Model` <add>- such a model can be trained just like Keras `Sequential` models. <add> <ide> ```python <ide> from keras.layers import Input, Dense <ide> from keras.models import Model <ide> model = Model(input=inputs, output=predictions) <ide> model.compile(optimizer='rmsprop', <ide> loss='categorical_crossentropy', <ide> metrics=['accuracy']) <del>model.fit(data, labels) <add>model.fit(data, labels) # starts training <ide> ``` <ide> <del>As you can see, a layer instance is callable (on a tensor), and it returns a tensor. Input tensor(s) and output tensor(s) can then be used to define a model, which can be trained just like `Sequential` models. <add>## All models are callable, just like layers <add> <add>With the functional API, it is easy to re-use trained models: you can use any model as if it were a layer, by calling it on a tensor. Note that by calling a model you aren't just re-using the *architecture* of the model, you are also re-using its weights. <add> <add>```python <add>x = Input(shape=(784,)) <add># this works, and returns the 10-way softmax we defined above. <add>y = model(x) <add>``` <add> <add>This can allow, for instance, to quickly create models that can process *sequences* of inputs. You could turn an image classification model into a video classification model, in just one line. <add> <add>```python <add>from keras.layers import TimeDistributed <add> <add># input tensor for sequences of 20 timesteps, <add># each containing a 784-dimensional vector <add>input_sequences = Input(shape=(20, 784)) <add> <add># this applies our previous model to every timestep in the input sequences. <add># the output of the previous model was a 10-way softmax, <add># so the output of the layer below will be a sequence of 20 vectors of size 10. <add>processed_sequences = TimeDistributed(model)(input_sequences) <add>``` <ide> <ide> ## Multi-input and multi-output models <ide> <del>A good use case for the functional API: models with multiple inputs and outputs. The functional API makes it really easy to manipulate a large number of intertwinned datastreams. <add>Here's a good use case for the functional API: models with multiple inputs and outputs. The functional API makes it really easy to manipulate a large number of intertwinned datastreams. <ide> <del>Let's consider a model that learns question-answering, this model learns a relevance embedding space where questions and their answers will be embedded at close positions. This embedding will allow us to quickly query a database of answers to find those that are relevant to a new question based on distances. <add>Let's consider a model for question-answering. The model learns a "relevance" embedding space where questions and their answers will be embedded at close positions. This embedding will allow us to quickly query a database of answers to find those that are relevant to a new question, based on the distances between the new question and stored answers. <ide> <del>The model has three input branches: an embedding for the question, and two embeddings for two different answers, a relevant answer and an unrelated answer. We'll train the model with a triplet loss, teaching the model to maximize the dot product between the question embedding and the embedding for the relevant answer, while minimizing the dot product between the question and the irrelevant answer. Dot products only has all information necessary to calculate distances when talking about unit norm vectors. For simplicity, let us assume dot products are sufficient here. <add>The model has three input branches: an embedding for the question, and two embeddings for two different answers, a relevant answer and an unrelated answer. We'll train the model with a triplet loss, teaching the model to maximize the dot product (i.e. cosine distance) between the question embedding and the embedding for the relevant answer, while minimizing the dot product between the question and the irrelevant answer. <ide> <ide> [model graph] <ide> <ide> Implementing this with the functional API is quick and simple: <ide> <ide> ```python <add>from keras.layers import Input, Embedding, LSTM, merge, Lambda <ide> <ide> # an input question will be a vector of 100 integers, <ide> # each being the index of a word in a vocabulary <ide> bad_answer_input = Input(shape=(100,), dtype='int32') <ide> embedded_question = Embedding(output_dim=1024)(question_input) <ide> encoded_question = LSTM(512)(embedded_question) <ide> <del># these two layers will be shared across the two answer inputs. <add># the two layers below will be shared across the two answer inputs. <ide> # we'll go over shared layers in detail in the next section. <ide> answer_embedding = Embedding(output_dim=1024) <ide> answer_lstm = LSTM(512) <ide> You can also define a separate model that just embeds a single question, using t <ide> question_embedder = Model(input=question_input, output=encoded_question) <ide> embedded_qs = question_embedder.predict(q_data) <ide> ``` <add> <ide> And one that can embed any answer: <ide> ```python <ide> answer_embedder = Model(input=good_answer_input, output=encoded_good_answer) <ide> Another good use for the functional API are models that use shared layers. Let's <ide> <ide> Let's consider a dataset of tweets. We want to build a model that can tell whether two tweets are from the same person or not (this can allow us to compare users by the similarity of their tweets, for instance). <ide> <del>One way to achieve this is to build a model that encodes two tweets into two vectors, concatenates the vectors and adds a logistic regression of top, outputting a probability that the tweets share the same author. The model would then be trained on positive tweet pairs and negative tweet pairs. <add>One way to achieve this is to build a model that encodes two tweets into two vectors, concatenates the vectors and adds a logistic regression of top, outputting a probability that the two tweets share the same author. The model would then be trained on positive tweet pairs and negative tweet pairs. <ide> <ide> Because the problem is symetric, the mechanism that encodes the first tweet should be reused (weights and all) to encode the second tweet, as such: <ide> <del>(graph: shared lstm) <add>[graph: shared lstm] <ide> <ide> Here we use an LSTM layer to encode the tweets. <ide> <ide> tweet_a = Input(shape=(140, 256)) <ide> tweet_b = Input(shape=(140, 256)) <ide> ``` <ide> <del>Sharing a layer across different inputs is easy: simply instantiate the layer once, then call it on as many inputs as you want: <add>To share a layer across different inputs, simply instantiate the layer once, then call it on as many inputs as you want: <ide> <del>``` <add>```python <ide> # this layer can take as input a matrix <ide> # and will return a vector of size 64 <ide> shared_lstm = LSTM(64) <ide> encoded_b = lstm(b) <ide> lstm.output <ide> ``` <ide> ``` <del>AssertionError: Layer lstm_4541336528 has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `get_output_at(node_index)` instead. <add>AssertionError: Layer lstm_1 has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `get_output_at(node_index)` instead. <ide> ``` <ide> <ide> Okay then. The following works: <add> <ide> ```python <ide> assert lstm.get_output_at(0) == encoded_a <ide> assert lstm.get_output_at(1) == encoded_b <ide> ``` <ide> <ide> Simple enough, right? <ide> <del>The same is true for `input_shape` and `output_shape`: as long as the layer has only one node, or as long as all nodes have the same input/output shape, then the notion of "layer output/input shape" is well defined, and that one shape will be returned by `layer.output_shape`/`layer.input_shape`. But if, for instance, you apply a same `Convolution2D` layer to an input of shape (3, 32, 32) then to an input of shape (3, 64, 64), the layer will have multiple input/output shapes, and you will have to fetch them via the index of the node they belong to: <add>The same is true for the properties `input_shape` and `output_shape`: as long as the layer has only one node, or as long as all nodes have the same input/output shape, then the notion of "layer output/input shape" is well defined, and that one shape will be returned by `layer.output_shape`/`layer.input_shape`. But if, for instance, you apply a same `Convolution2D` layer to an input of shape (3, 32, 32) then to an input of shape `(3, 64, 64)`, the layer will have multiple input/output shapes, and you will have to fetch them via the index of the node they belong to: <ide> <ide> ```python <add>from keras.layers import merge, Convolution2D <add> <ide> a = Input(shape=(3, 32, 32)) <ide> b = Input(shape=(3, 64, 64)) <ide> <ide> assert conv.get_input_shape_at(0) == (None, 3, 32, 32) <ide> assert conv.get_input_shape_at(1) == (None, 3, 64, 64) <ide> ``` <ide> <add># More examples <add> <add>Code examples are still the best way to get started, so here are a few more. <add> <add>### Inception module <add> <add>For more information about the Inception architecture, see [Going Deeper with Convolutions](http://arxiv.org/abs/1409.4842). <ide> <add>```python <add>input_img = Input(shape=(3, 256, 256)) <add> <add>tower_1 = Convolution2D(64, 1, 1, border_mode='same', activation='relu')(input_img) <add>tower_1 = Convolution2D(64, 3, 3, border_mode='same', activation='relu')(tower_1) <add> <add>tower_2 = Convolution2D(64, 1, 1, border_mode='same', activation='relu')(input_img) <add>tower_2 = Convolution2D(64, 5, 5, border_mode='same', activation='relu')(tower_2) <add> <add>tower_3 = MaxPooling2D((3, 3), strides=(1, 1), border_mode='same')(input_img) <add>tower_3 = Convolution2D(64, 1, 1, border_mode='same', activation='relu')(tower_3) <add> <add>output = merge([tower_1, tower_2, tower_3], mode='concat', concat_axis=1) <add>``` <ide> <add>### Residual connection on a convolution layer <ide> <add>For more information about residual networks, see [Deep Residual Learning for Image Recognition](http://arxiv.org/abs/1512.03385). <add> <add>```python <add>from keras.layers import merge, Convolution2D, Input <add> <add># input tensor for a 3-channel 256x256 image <add>x = Input(shape=(3, 256, 256)) <add># 3x3 conv with 16 output channels <add>y = Convolution2D(16, 3, 3, border_mode='same') <add># this returns x + y. <add>z = merge([x, y], mode='sum') <add>``` <add> <add>### Shared vision model <add> <add>This model re-uses the same image-processing module on two inputs, to classify whether two MNIST digits are the same digit or different digits. <add> <add>```python <add> <add># first, define the vision modules <add>digit_input = Input(shape=(1, 27, 27)) <add>x = Convolution2D(64, 3, 3)(x) <add>x = Convolution2D(64, 3, 3)(x) <add>out = MaxPooling2D((2, 2))(x) <add> <add>vision_model = Model(digit_input, out) <add> <add># then define the tell-digits-apart model <add>digit_a = Input(shape=(1, 27, 27)) <add>digit_b = Input(shape=(1, 27, 27)) <add> <add># the vision model will be shared, weights and all <add>out_a = vision_model(digit_a) <add>out_b = vision_model(digit_b) <add> <add>concatenated = merge([out_a, out_b], mode='concat') <add>out = Dense(1, activation='sigmoid')(concatenated) <add> <add>classification_model = Model([digit_a, digit_b], out) <add>``` <add> <add>### Visual question answering model <add> <add>This model can select the correct one-word answer when asked a natural-language question about a picture. <add> <add>It works by encoding the question into a vector, encoding the image into a vector, concatenating the two, and training on top a logistic regression over some vocabulary of potential answers. <add> <add>```python <add>[TODO] <add>``` <add> <add>### Video question answering model. <add> <add>Now that we have trained our image QA model, we can quickly turn it into a video QA model. With appropriate training, you will be able to show it a short video (e.g. 100-frame human action) and ask a natural language question about the video (e.g. "what sport is the boy playing?" -> "footbal"). <add> <add>```python <add>[TODO] <add>``` <ide>\ No newline at end of file
1
Text
Text
remove outdated notes on stdio in workers
a5b92a7bb4f1b85f0901a2872da93bb4449aa42e
<ide><path>doc/api/process.md <ide> a [Writable][] stream. <ide> `process.stderr` differs from other Node.js streams in important ways, see <ide> [note on process I/O][] for more information. <ide> <del>This feature is not available in [`Worker`][] threads. <del> <ide> ## process.stdin <ide> <ide> * {Stream} <ide> In "old" streams mode the `stdin` stream is paused by default, so one <ide> must call `process.stdin.resume()` to read from it. Note also that calling <ide> `process.stdin.resume()` itself would switch stream to "old" mode. <ide> <del>This feature is not available in [`Worker`][] threads. <del> <ide> ## process.stdout <ide> <ide> * {Stream} <ide> process.stdin.pipe(process.stdout); <ide> `process.stdout` differs from other Node.js streams in important ways, see <ide> [note on process I/O][] for more information. <ide> <del>This feature is not available in [`Worker`][] threads. <del> <ide> ### A note on process I/O <ide> <ide> `process.stdout` and `process.stderr` differ from other Node.js streams in
1
Javascript
Javascript
add test cases
68c44ad842bf7ce7c0886099efc74815e15f9540
<ide><path>test/cases/parsing/harmony-commonjs/a.js <add>export default function test() { <add> return "OK"; <add>} <ide><path>test/cases/parsing/harmony-commonjs/index.js <add>it("should pass when required by CommonJS module", function () { <add> var test1 = require('./a').default; <add> test1().should.be.eql("OK"); <add>}); <add> <add>it("should pass when use babeljs transpiler", function() { <add> //the following are generated code by use babeljs. <add> // use it this way will save trouble to setup babel-loader <add> // the babeljs transpiled code depends on the __esMoudule to be set <add> var _test = require('./a'); <add> var _test2 = _interopRequireDefault(_test); <add> function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } <add> var test2 = (0, _test2.default)(); <add> test2.should.be.eql("OK"); <add>})
2
Ruby
Ruby
add alias method
4613c9ecf5fbb0023fe44cde5c1ce1664b602b74
<ide><path>Library/Homebrew/tap.rb <ide> def formula_names <ide> formula_files.map { |f| "#{name}/#{f.basename(".rb")}" } <ide> end <ide> <add> # an array of all alias files of this {Tap}. <add> # @private <add> def alias_files <add> Pathname.glob("#{path}/Aliases/*").select(&:file?) <add> end <add> <add> # an array of all aliases of this {Tap}. <add> # @private <add> def aliases <add> alias_files.map { |f| f.basename.to_s } <add> end <add> <ide> # an array of all commands files of this {Tap}. <ide> def command_files <ide> Pathname.glob("#{path}/cmd/brew-*").select(&:executable?)
1
Java
Java
improve method order in mockmvcrequestbuilders
9bda734e0a1bd571078bc2e7c7b41065a7d53fa3
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.java <ide> public class MockHttpServletRequestBuilder implements RequestBuilder, Mergeable <ide> * the {@code MockHttpServletRequest} can be plugged in via <ide> * {@link #with(RequestPostProcessor)}. <ide> * @param httpMethod the HTTP method (GET, POST, etc) <del> * @param url the URL <add> * @param uri the URL <ide> * @since 4.0.3 <ide> */ <del> MockHttpServletRequestBuilder(HttpMethod httpMethod, URI url) { <add> MockHttpServletRequestBuilder(HttpMethod httpMethod, URI uri) { <ide> Assert.notNull(httpMethod, "httpMethod is required"); <del> Assert.notNull(url, "url is required"); <add> Assert.notNull(uri, "uri is required"); <ide> this.method = httpMethod; <del> this.uriComponents = UriComponentsBuilder.fromUri(url).build(); <add> this.uriComponents = UriComponentsBuilder.fromUri(uri).build(); <ide> } <ide> <ide> /** <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockMultipartHttpServletRequestBuilder.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2014 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class MockMultipartHttpServletRequestBuilder extends MockHttpServletReque <ide> * <p>For other ways to initialize a {@code MockMultipartHttpServletRequest}, <ide> * see {@link #with(RequestPostProcessor)} and the <ide> * {@link RequestPostProcessor} extension point. <del> * @param url the URL <add> * @param uri the URL <ide> * @since 4.0.3 <ide> */ <del> MockMultipartHttpServletRequestBuilder(URI url) { <del> super(HttpMethod.POST, url); <add> MockMultipartHttpServletRequestBuilder(URI uri) { <add> super(HttpMethod.POST, uri); <ide> super.contentType(MediaType.MULTIPART_FORM_DATA); <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/request/MockMvcRequestBuilders.java <ide> public static MockHttpServletRequestBuilder get(String urlTemplate, Object... ur <ide> return new MockHttpServletRequestBuilder(HttpMethod.GET, urlTemplate, urlVariables); <ide> } <ide> <add> /** <add> * Create a {@link MockHttpServletRequestBuilder} for a GET request. <add> * @param uri the URL <add> * @since 4.0.3 <add> */ <add> public static MockHttpServletRequestBuilder get(URI uri) { <add> return new MockHttpServletRequestBuilder(HttpMethod.GET, uri); <add> } <add> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for a POST request. <ide> * @param urlTemplate a URL template; the resulting URL will be encoded <ide> public static MockHttpServletRequestBuilder post(String urlTemplate, Object... u <ide> return new MockHttpServletRequestBuilder(HttpMethod.POST, urlTemplate, urlVariables); <ide> } <ide> <add> /** <add> * Create a {@link MockHttpServletRequestBuilder} for a POST request. <add> * @param uri the URL <add> * @since 4.0.3 <add> */ <add> public static MockHttpServletRequestBuilder post(URI uri) { <add> return new MockHttpServletRequestBuilder(HttpMethod.POST, uri); <add> } <add> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for a PUT request. <ide> * @param urlTemplate a URL template; the resulting URL will be encoded <ide> public static MockHttpServletRequestBuilder put(String urlTemplate, Object... ur <ide> return new MockHttpServletRequestBuilder(HttpMethod.PUT, urlTemplate, urlVariables); <ide> } <ide> <add> /** <add> * Create a {@link MockHttpServletRequestBuilder} for a PUT request. <add> * @param uri the URL <add> * @since 4.0.3 <add> */ <add> public static MockHttpServletRequestBuilder put(URI uri) { <add> return new MockHttpServletRequestBuilder(HttpMethod.PUT, uri); <add> } <add> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for a PATCH request. <ide> * @param urlTemplate a URL template; the resulting URL will be encoded <ide> public static MockHttpServletRequestBuilder patch(String urlTemplate, Object... <ide> return new MockHttpServletRequestBuilder(HttpMethod.PATCH, urlTemplate, urlVariables); <ide> } <ide> <add> /** <add> * Create a {@link MockHttpServletRequestBuilder} for a PATCH request. <add> * @param uri the URL <add> * @since 4.0.3 <add> */ <add> public static MockHttpServletRequestBuilder patch(URI uri) { <add> return new MockHttpServletRequestBuilder(HttpMethod.PATCH, uri); <add> } <add> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for a DELETE request. <ide> * @param urlTemplate a URL template; the resulting URL will be encoded <ide> public static MockHttpServletRequestBuilder delete(String urlTemplate, Object... <ide> return new MockHttpServletRequestBuilder(HttpMethod.DELETE, urlTemplate, urlVariables); <ide> } <ide> <add> /** <add> * Create a {@link MockHttpServletRequestBuilder} for a DELETE request. <add> * @param uri the URL <add> * @since 4.0.3 <add> */ <add> public static MockHttpServletRequestBuilder delete(URI uri) { <add> return new MockHttpServletRequestBuilder(HttpMethod.DELETE, uri); <add> } <add> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request. <ide> * @param urlTemplate a URL template; the resulting URL will be encoded <ide> public static MockHttpServletRequestBuilder options(String urlTemplate, Object.. <ide> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, urlTemplate, urlVariables); <ide> } <ide> <add> /** <add> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request. <add> * @param uri the URL <add> * @since 4.0.3 <add> */ <add> public static MockHttpServletRequestBuilder options(URI uri) { <add> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, uri); <add> } <ide> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method. <ide> public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, Strin <ide> } <ide> <ide> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a multipart request. <del> * @param urlTemplate a URL template; the resulting URL will be encoded <del> * @param urlVariables zero or more URL variables <del> */ <del> public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) { <del> return new MockMultipartHttpServletRequestBuilder(urlTemplate, urlVariables); <del> } <del> <del> <del> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a GET request. <del> * @param url the URL <del> * @since 4.0.3 <del> */ <del> public static MockHttpServletRequestBuilder get(URI url) { <del> return new MockHttpServletRequestBuilder(HttpMethod.GET, url); <del> } <del> <del> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a POST request. <del> * @param url the URL <del> * @since 4.0.3 <del> */ <del> public static MockHttpServletRequestBuilder post(URI url) { <del> return new MockHttpServletRequestBuilder(HttpMethod.POST, url); <del> } <del> <del> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a PUT request. <del> * @param url the URL <del> * @since 4.0.3 <del> */ <del> public static MockHttpServletRequestBuilder put(URI url) { <del> return new MockHttpServletRequestBuilder(HttpMethod.PUT, url); <del> } <del> <del> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a PATCH request. <del> * @param url the URL <del> * @since 4.0.3 <del> */ <del> public static MockHttpServletRequestBuilder patch(URI url) { <del> return new MockHttpServletRequestBuilder(HttpMethod.PATCH, url); <del> } <del> <del> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a DELETE request. <del> * @param url the URL <del> * @since 4.0.3 <del> */ <del> public static MockHttpServletRequestBuilder delete(URI url) { <del> return new MockHttpServletRequestBuilder(HttpMethod.DELETE, url); <del> } <del> <del> /** <del> * Create a {@link MockHttpServletRequestBuilder} for an OPTIONS request. <del> * @param url the URL <add> * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method. <add> * @param httpMethod the HTTP method (GET, POST, etc) <add> * @param uri the URL <ide> * @since 4.0.3 <ide> */ <del> public static MockHttpServletRequestBuilder options(URI url) { <del> return new MockHttpServletRequestBuilder(HttpMethod.OPTIONS, url); <add> public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, URI uri) { <add> return new MockHttpServletRequestBuilder(httpMethod, uri); <ide> } <ide> <ide> /** <del> * Create a {@link MockHttpServletRequestBuilder} for a request with the given HTTP method. <del> * @param httpMethod the HTTP method (GET, POST, etc) <del> * @param url the URL <del> * @since 4.0.3 <add> * Create a {@link MockHttpServletRequestBuilder} for a multipart request. <add> * @param urlTemplate a URL template; the resulting URL will be encoded <add> * @param urlVariables zero or more URL variables <ide> */ <del> public static MockHttpServletRequestBuilder request(HttpMethod httpMethod, URI url) { <del> return new MockHttpServletRequestBuilder(httpMethod, url); <add> public static MockMultipartHttpServletRequestBuilder fileUpload(String urlTemplate, Object... urlVariables) { <add> return new MockMultipartHttpServletRequestBuilder(urlTemplate, urlVariables); <ide> } <ide> <ide> /** <ide> * Create a {@link MockHttpServletRequestBuilder} for a multipart request. <del> * @param url the URL <add> * @param uri the URL <ide> * @since 4.0.3 <ide> */ <del> public static MockMultipartHttpServletRequestBuilder fileUpload(URI url) { <del> return new MockMultipartHttpServletRequestBuilder(url); <add> public static MockMultipartHttpServletRequestBuilder fileUpload(URI uri) { <add> return new MockMultipartHttpServletRequestBuilder(uri); <ide> } <ide> <ide> /**
3
PHP
PHP
remove duplicate trans methods on translator
8557dc56b11c5e4dc746cb5558d6e694131f0dd8
<ide><path>src/Illuminate/Contracts/Translation/Translator.php <ide> interface Translator <ide> * @param string|null $locale <ide> * @return mixed <ide> */ <del> public function trans($key, array $replace = [], $locale = null); <add> public function get($key, array $replace = [], $locale = null); <ide> <ide> /** <ide> * Get a translation according to an integer value. <ide> public function trans($key, array $replace = [], $locale = null); <ide> * @param string|null $locale <ide> * @return string <ide> */ <del> public function transChoice($key, $number, array $replace = [], $locale = null); <add> public function choice($key, $number, array $replace = [], $locale = null); <ide> <ide> /** <ide> * Get the default locale being used. <ide><path>src/Illuminate/Foundation/helpers.php <ide> function trans($key = null, $replace = [], $locale = null) <ide> return app('translator'); <ide> } <ide> <del> return app('translator')->trans($key, $replace, $locale); <add> return app('translator')->get($key, $replace, $locale); <ide> } <ide> } <ide> <ide> function trans($key = null, $replace = [], $locale = null) <ide> */ <ide> function trans_choice($key, $number, array $replace = [], $locale = null) <ide> { <del> return app('translator')->transChoice($key, $number, $replace, $locale); <add> return app('translator')->choice($key, $number, $replace, $locale); <ide> } <ide> } <ide> <ide><path>src/Illuminate/Translation/Translator.php <ide> public function has($key, $locale = null, $fallback = true) <ide> return $this->get($key, [], $locale, $fallback) !== $key; <ide> } <ide> <del> /** <del> * Get the translation for a given key. <del> * <del> * @param string $key <del> * @param array $replace <del> * @param string|null $locale <del> * @return string|array <del> */ <del> public function trans($key, array $replace = [], $locale = null) <del> { <del> return $this->get($key, $replace, $locale); <del> } <del> <ide> /** <ide> * Get the translation for the given key. <ide> * <ide> public function get($key, array $replace = [], $locale = null, $fallback = true) <ide> return $this->makeReplacements($line ?: $key, $replace); <ide> } <ide> <del> /** <del> * Get a translation according to an integer value. <del> * <del> * @param string $key <del> * @param int|array|\Countable $number <del> * @param array $replace <del> * @param string|null $locale <del> * @return string <del> */ <del> public function transChoice($key, $number, array $replace = [], $locale = null) <del> { <del> return $this->choice($key, $number, $replace, $locale); <del> } <del> <ide> /** <ide> * Get a translation according to an integer value. <ide> * <ide><path>src/Illuminate/Validation/Concerns/FormatsMessages.php <ide> protected function getMessage($attribute, $rule) <ide> // messages out of the translator service for this validation rule. <ide> $key = "validation.{$lowerRule}"; <ide> <del> if ($key != ($value = $this->translator->trans($key))) { <add> if ($key != ($value = $this->translator->get($key))) { <ide> return $value; <ide> } <ide> <ide> protected function getFromLocalArray($attribute, $lowerRule, $source = null) <ide> */ <ide> protected function getCustomMessageFromTranslator($key) <ide> { <del> if (($message = $this->translator->trans($key)) !== $key) { <add> if (($message = $this->translator->get($key)) !== $key) { <ide> return $message; <ide> } <ide> <ide> protected function getCustomMessageFromTranslator($key) <ide> ); <ide> <ide> return $this->getWildcardCustomMessages(Arr::dot( <del> (array) $this->translator->trans('validation.custom') <add> (array) $this->translator->get('validation.custom') <ide> ), $shortKey, $key); <ide> } <ide> <ide> protected function getSizeMessage($attribute, $rule) <ide> <ide> $key = "validation.{$lowerRule}.{$type}"; <ide> <del> return $this->translator->trans($key); <add> return $this->translator->get($key); <ide> } <ide> <ide> /** <ide> public function getDisplayableAttribute($attribute) <ide> */ <ide> protected function getAttributeFromTranslations($name) <ide> { <del> return Arr::get($this->translator->trans('validation.attributes'), $name); <add> return Arr::get($this->translator->get('validation.attributes'), $name); <ide> } <ide> <ide> /** <ide> public function getDisplayableValue($attribute, $value) <ide> <ide> $key = "validation.values.{$attribute}.{$value}"; <ide> <del> if (($line = $this->translator->trans($key)) !== $key) { <add> if (($line = $this->translator->get($key)) !== $key) { <ide> return $line; <ide> } <ide> <ide><path>tests/Translation/TranslationTranslatorTest.php <ide> public function testTransMethodProperlyLoadsAndRetrievesItemWithHTMLInTheMessage <ide> $t = new Translator($this->getLoader(), 'en'); <ide> $t->getLoader()->shouldReceive('load')->once()->with('en', '*', '*')->andReturn([]); <ide> $t->getLoader()->shouldReceive('load')->once()->with('en', 'foo', '*')->andReturn(['bar' => 'breeze <p>test</p>']); <del> $this->assertSame('breeze <p>test</p>', $t->trans('foo.bar', [], 'en')); <add> $this->assertSame('breeze <p>test</p>', $t->get('foo.bar', [], 'en')); <ide> } <ide> <ide> public function testGetMethodProperlyLoadsAndRetrievesItemWithCapitalization()
5
Javascript
Javascript
fix deadlock when sending handles
1bd4f3a605216838619e4d7dc1eb1600b1deb91f
<ide><path>lib/child_process.js <ide> function setupChannel(target, channel) { <ide> if (obj.simultaneousAccepts) { <ide> net._setSimultaneousAccepts(handle); <ide> } <del> } else if (this._handleQueue) { <add> } else if (this._handleQueue && <add> !(message && message.cmd === 'NODE_HANDLE_ACK')) { <ide> // Queue request anyway to avoid out-of-order messages. <ide> this._handleQueue.push({ message: message, handle: null }); <ide> return; <ide><path>test/simple/test-cluster-send-deadlock.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>// Testing mutual send of handles: from master to worker, and from worker to <add>// master. <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var cluster = require('cluster'); <add>var net = require('net'); <add> <add>if (cluster.isMaster) { <add> var worker = cluster.fork(); <add> worker.on('exit', function(code, signal) { <add> assert.equal(code, 0, 'Worker exited with an error code'); <add> assert(!signal, 'Worker exited by a signal'); <add> server.close(); <add> }); <add> <add> var server = net.createServer(function(socket) { <add> worker.send('handle', socket); <add> }); <add> <add> server.listen(common.PORT, function() { <add> worker.send('listen'); <add> }); <add>} else { <add> process.on('message', function(msg, handle) { <add> if (msg === 'listen') { <add> var client1 = net.connect({ host: 'localhost', port: common.PORT }); <add> var client2 = net.connect({ host: 'localhost', port: common.PORT }); <add> var waiting = 2; <add> client1.on('close', onclose); <add> client2.on('close', onclose); <add> function onclose() { <add> if (--waiting === 0) <add> cluster.worker.disconnect(); <add> } <add> setTimeout(function() { <add> client1.end(); <add> client2.end(); <add> }, 50); <add> } else { <add> process.send('reply', handle); <add> } <add> }); <add>}
2
Ruby
Ruby
fix minor typo in code comment
03647a3b7443eed0a11cd43d6cc327120e59f6a1
<ide><path>lib/action_text/attribute.rb <ide> module Attribute <ide> # If you wish to preload the dependent RichText model, you can use the named scope: <ide> # <ide> # Message.all.with_rich_text_content # Avoids N+1 queries when you just want the body, not the attachments. <del> # Message.all.with_rich_text_content_and_emebds # Avoids N+1 queries when you just want the body and attachments. <add> # Message.all.with_rich_text_content_and_embeds # Avoids N+1 queries when you just want the body and attachments. <ide> def has_rich_text(name) <ide> class_eval <<-CODE, __FILE__, __LINE__ + 1 <ide> def #{name}
1
PHP
PHP
refactor the mysql connector
ace9702a1a7b17cb33b2f61eb46973de5e4111e6
<ide><path>src/Illuminate/Database/Connectors/MySqlConnector.php <ide> public function connect(array $config) <ide> $connection->exec("use `{$config['database']}`;"); <ide> } <ide> <del> $collation = $config['collation']; <add> $this->configureEncoding($connection, $config); <ide> <del> // Next we will set the "names" and "collation" on the clients connections so <del> // a correct character set will be used by this client. The collation also <del> // is set on the server but needs to be set here on this client objects. <del> if (isset($config['charset'])) { <del> $charset = $config['charset']; <del> <del> $names = "set names '{$charset}'". <del> (! is_null($collation) ? " collate '{$collation}'" : ''); <del> <del> $connection->prepare($names)->execute(); <del> } <ide> // Next, we will check to see if a timezone has been specified in this config <ide> // and if it has we will issue a statement to modify the timezone with the <ide> // database. Setting this DB timezone is an optional configuration item. <del> if (isset($config['timezone'])) { <del> $connection->prepare( <del> 'set time_zone="'.$config['timezone'].'"' <del> )->execute(); <del> } <add> $this->configureTimezone($connection, $config); <ide> <ide> $this->setModes($connection, $config); <ide> <ide> return $connection; <ide> } <ide> <add> /** <add> * Set the connection character set and collation. <add> * <add> * @param \PDO $connection <add> * @param array $config <add> * @return void <add> */ <add> protected function configureEncoding($connection, array $config) <add> { <add> if (! isset($config['charset'])) { <add> return $connection; <add> } <add> <add> $connection->prepare( <add> "set names '{$config['charset']}'".$this->getCollation($config) <add> )->execute(); <add> } <add> <add> /** <add> * Get the collation for the configuration. <add> * <add> * @param array $config <add> * @return string <add> */ <add> protected function getCollation(array $config) <add> { <add> return ! is_null($config['collation']) ? " collate '{$config['collation']}'" : ''; <add> } <add> <add> /** <add> * Set the timezone on the connection. <add> * <add> * @param \PDO $connection <add> * @param array $config <add> * @return void <add> */ <add> protected function configureTimezone($connection, array $config) <add> { <add> if (isset($config['timezone'])) { <add> $connection->prepare('set time_zone="'.$config['timezone'].'"')->execute(); <add> } <add> } <add> <ide> /** <ide> * Create a DSN string from a configuration. <ide> * <ide> public function connect(array $config) <ide> */ <ide> protected function getDsn(array $config) <ide> { <del> return $this->configHasSocket($config) ? $this->getSocketDsn($config) : $this->getHostDsn($config); <add> return $this->hasSocket($config) <add> ? $this->getSocketDsn($config) <add> : $this->getHostDsn($config); <ide> } <ide> <ide> /** <ide> protected function getDsn(array $config) <ide> * @param array $config <ide> * @return bool <ide> */ <del> protected function configHasSocket(array $config) <add> protected function hasSocket(array $config) <ide> { <ide> return isset($config['unix_socket']) && ! empty($config['unix_socket']); <ide> } <ide> protected function getHostDsn(array $config) <ide> extract($config, EXTR_SKIP); <ide> <ide> return isset($port) <del> ? "mysql:host={$host};port={$port};dbname={$database}" <del> : "mysql:host={$host};dbname={$database}"; <add> ? "mysql:host={$host};port={$port};dbname={$database}" <add> : "mysql:host={$host};dbname={$database}"; <ide> } <ide> <ide> /** <ide> protected function getHostDsn(array $config) <ide> protected function setModes(PDO $connection, array $config) <ide> { <ide> if (isset($config['modes'])) { <del> $modes = implode(',', $config['modes']); <del> <del> $connection->prepare("set session sql_mode='{$modes}'")->execute(); <add> $this->setCustomModes($connection, $config); <ide> } elseif (isset($config['strict'])) { <ide> if ($config['strict']) { <del> $connection->prepare("set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'")->execute(); <add> $connection->prepare($this->strictMode())->execute(); <ide> } else { <ide> $connection->prepare("set session sql_mode='NO_ENGINE_SUBSTITUTION'")->execute(); <ide> } <ide> } <ide> } <add> <add> /** <add> * Set the custom modes on the connection. <add> * <add> * @param \PDO $connection <add> * @param array $config <add> * @return void <add> */ <add> protected function setCustomModes(PDO $connection, array $config) <add> { <add> $modes = implode(',', $config['modes']); <add> <add> $connection->prepare("set session sql_mode='{$modes}'")->execute(); <add> } <add> <add> /** <add> * Get the query to enable strict mode. <add> * <add> * @return string <add> */ <add> protected function strictMode() <add> { <add> return "set session sql_mode='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'"; <add> } <ide> }
1
Ruby
Ruby
assign this inline
381255adecbbd16fca0d2ae1b52330a254bfae76
<ide><path>Library/Homebrew/extend/ENV.rb <ide> def clang <ide> @compiler = :clang <ide> end <ide> <del> def remove_macosxsdk v=MacOS.version <add> def remove_macosxsdk version=MacOS.version <ide> # Clear all lib and include dirs from CFLAGS, CPPFLAGS, LDFLAGS that were <ide> # previously added by macosxsdk <del> v = v.to_s <add> version = version.to_s <ide> remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/) <ide> delete('MACOSX_DEPLOYMENT_TARGET') <ide> delete('CPATH') <ide> remove 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" <del> sdk = MacOS.sdk_path(v) <del> unless sdk.nil? or MacOS::CLT.installed? <add> unless (sdk = MacOS.sdk_path(version)).nil? or MacOS::CLT.installed? <ide> delete('SDKROOT') <ide> remove_from_cflags "-isysroot #{sdk}" <ide> remove 'CPPFLAGS', "-isysroot #{sdk}" <ide> def remove_macosxsdk v=MacOS.version <ide> end <ide> end <ide> <del> def macosxsdk v=MacOS.version <add> def macosxsdk version=MacOS.version <ide> return unless MACOS <ide> # Sets all needed lib and include dirs to CFLAGS, CPPFLAGS, LDFLAGS. <ide> remove_macosxsdk <del> # Allow cool style of ENV.macosxsdk 10.8 here (no "" :) <del> v = v.to_s <del> append_to_cflags("-mmacosx-version-min=#{v}") <del> self['MACOSX_DEPLOYMENT_TARGET'] = v <add> version = version.to_s <add> append_to_cflags("-mmacosx-version-min=#{version}") <add> self['MACOSX_DEPLOYMENT_TARGET'] = version <ide> self['CPATH'] = "#{HOMEBREW_PREFIX}/include" <ide> prepend 'LDFLAGS', "-L#{HOMEBREW_PREFIX}/lib" <del> sdk = MacOS.sdk_path(v) <del> unless sdk.nil? or MacOS::CLT.installed? <add> unless (sdk = MacOS.sdk_path(version)).nil? or MacOS::CLT.installed? <ide> # Extra setup to support Xcode 4.3+ without CLT. <ide> self['SDKROOT'] = sdk <ide> # Tell clang/gcc where system include's are:
1
Javascript
Javascript
clarify parameters description
b11120be0ad2fe27e85556ad89c3201c04e217cb
<ide><path>src/ngCookies/cookies.js <ide> angular.module('ngCookies', ['ng']). <ide> * The object may have following properties: <ide> * <ide> * - **path** - `{string}` - The cookie will be available only for this path and its <del> * sub-paths. By default, this would be the URL that appears in your base tag. <add> * sub-paths. By default, this is the URL that appears in your `<base>` tag. <ide> * - **domain** - `{string}` - The cookie will be available only for this domain and <del> * its sub-domains. For obvious security reasons the user agent will not accept the <del> * cookie if the current domain is not a sub domain or equals to the requested domain. <add> * its sub-domains. For security reasons the user agent will not accept the cookie <add> * if the current domain is not a sub-domain of this domain or equal to it. <ide> * - **expires** - `{string|Date}` - String of the form "Wdy, DD Mon YYYY HH:MM:SS GMT" <ide> * or a Date object indicating the exact date/time this cookie will expire. <del> * - **secure** - `{boolean}` - The cookie will be available only in secured connection. <add> * - **secure** - `{boolean}` - If `true`, then the cookie will only be available through a <add> * secured connection. <ide> * <del> * Note: by default the address that appears in your `<base>` tag will be used as path. <del> * This is important so that cookies will be visible for all routes in case html5mode is enabled <add> * Note: By default, the address that appears in your `<base>` tag will be used as the path. <add> * This is important so that cookies will be visible for all routes when html5mode is enabled. <ide> * <ide> **/ <ide> var defaults = this.defaults = {};
1