content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
update the dummy driver for all of our api changes
986cad6b12f850b669650c9952791c76f85486e1
<ide><path>libcloud/drivers/dummy.py <ide> <ide> @note: This driver is out of date <ide> """ <del>from libcloud.types import Node, NodeState <ide> from libcloud.interface import INodeDriver <add>from libcloud.base import ConnectionKey, NodeDriver, NodeSize, NodeLocation <add>from libcloud.base import NodeImage, Node <add>from libcloud.types import Provider,NodeState <ide> from zope.interface import implements <ide> <ide> import uuid <ide> <del>class DummyNodeDriver(object): <add>class DummyConnection(ConnectionKey): <add> <add> def connect(self, host=None, port=None): <add> pass <add> <add>class DummyNodeDriver(NodeDriver): <add> <add> name = "Dummy Node Provider" <add> type = Provider.DUMMY <ide> <ide> implements(INodeDriver) <ide> <ide> def __init__(self, creds): <ide> self.creds = creds <del> <del> def get_uuid(self, unique_field=None): <del> return str(uuid.uuid4()) <del> <del> def list_nodes(self): <del> return [ <del> Node(uuid=self.get_uuid(), <add> self.nl = [ <add> Node(id=1, <ide> name='dummy-1', <ide> state=NodeState.RUNNING, <del> ipaddress=['127.0.0.1'], <del> creds=self.creds, <del> attrs={'foo': 'bar'}), <del> Node(uuid=self.get_uuid(), <add> public_ip=['127.0.0.1'], <add> private_ip=[], <add> driver=self, <add> extra={'foo': 'bar'}), <add> Node(id=2, <ide> name='dummy-2', <del> state=NodeState.REBOOTING, <del> ipaddress=['127.0.0.2'], <del> creds=self.creds, <del> attrs={'foo': 'bar'}) <add> state=NodeState.RUNNING, <add> public_ip=['127.0.0.1'], <add> private_ip=[], <add> driver=self, <add> extra={'foo': 'bar'}), <ide> ] <ide> <add> def get_uuid(self, unique_field=None): <add> return str(uuid.uuid4()) <add> <add> def list_nodes(self): <add> return self.nl <add> <ide> def reboot_node(self, node): <ide> node.state = NodeState.REBOOTING <del> return node <add> return True <ide> <ide> def destroy_node(self, node): <del> pass <add> node.state = NodeState.TERMINATED <add> self.nl.remove(node) <add> return True <add> <add> def list_images(self): <add> return [ <add> NodeImage(id=1, name="Ubuntu 9.10", driver=self), <add> NodeImage(id=2, name="Ubuntu 9.04", driver=self), <add> NodeImage(id=3, name="Slackware 4", driver=self), <add> ] <add> <add> def list_sizes(self): <add> return [ <add> NodeSize(id=1, name="Small", ram=128, disk=4, bandwidth=500, price=4, driver=self), <add> NodeSize(id=2, name="Medium", ram=512, disk=16, bandwidth=1500, price=8, driver=self), <add> NodeSize(id=3, name="Big", ram=4096, disk=32, bandwidth=2500, price=32, driver=self), <add> NodeSize(id=4, name="XXL Big", ram=4096*2, disk=32*4, bandwidth=2500*3, price=32*2, driver=self), <add> ] <add> <add> def list_locations(self): <add> return [ <add> NodeLocation(id=1, name="Paul's Room", country='US', driver=self), <add> NodeLocation(id=1, name="London Loft", country='GB', driver=self), <add> NodeLocation(id=1, name="Island Datacenter", country='FJ', driver=self), <add> ] <ide> <del> def create_node(self, node): <del> pass <add> def create_node(self, **kwargs): <add> l = len(self.nl) + 1 <add> n = Node(id=l, <add> name='dummy-%d' % l, <add> state=NodeState.RUNNING, <add> public_ip=['127.0.0.%d' % l], <add> private_ip=[], <add> driver=self, <add> extra={'foo': 'bar'}) <add> self.nl.append(n) <add> return n <ide><path>libcloud/providers.py <ide> <ide> <ide> DRIVERS = { <del># Provider.DUMMY: <del># ('libcloud.drivers.dummy', 'DummyNodeDriver'), <add> Provider.DUMMY: <add> ('libcloud.drivers.dummy', 'DummyNodeDriver'), <ide> Provider.EC2_US_EAST: <ide> ('libcloud.drivers.ec2', 'EC2NodeDriver'), <ide> Provider.EC2_EU_WEST:
2
PHP
PHP
continue loop on wildcards
7cd65764ae0cd6759353cb1231c421319141caf8
<ide><path>src/Illuminate/Events/Dispatcher.php <ide> public function listen($events, $listener, $priority = 0) <ide> { <ide> if (str_contains($event, '*')) <ide> { <del> return $this->setupWildcardListen($event, $listener); <add> $this->setupWildcardListen($event, $listener); <ide> } <add> else <add> { <add> $this->listeners[$event][$priority][] = $this->makeListener($listener); <ide> <del> $this->listeners[$event][$priority][] = $this->makeListener($listener); <del> <del> unset($this->sorted[$event]); <add> unset($this->sorted[$event]); <add> } <ide> } <ide> } <ide>
1
Python
Python
add test for a wordlevel tokenizer model
3aa37b945e21019575fc183ce750a37b86efc634
<ide><path>tests/test_tokenization_common.py <ide> def test_training_new_tokenizer(self): <ide> decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) <ide> expected_result = "This is the first sentence" <ide> <del> # OpenAIGPT always lowercases and has no arg. <del> if new_tokenizer.init_kwargs.get("do_lower_case", False) or tokenizer.__class__.__name__.startswith( <del> "OpenAIGPT" <del> ): <del> expected_result = expected_result.lower() <add> if tokenizer.backend_tokenizer.normalizer is not None: <add> expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) <ide> self.assertEqual(expected_result, decoded_input) <ide> <ide> # We check that the parameters of the tokenizer remained the same <ide> def test_training_new_tokenizer_with_special_tokens_change(self): <ide> decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) <ide> expected_result = "This is the first sentence" <ide> <del> # OpenAIGPT always lowercases and has no arg. <del> if new_tokenizer.init_kwargs.get("do_lower_case", False) or tokenizer.__class__.__name__.startswith( <del> "OpenAIGPT" <del> ): <del> expected_result = expected_result.lower() <add> if tokenizer.backend_tokenizer.normalizer is not None: <add> expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) <ide> self.assertEqual(expected_result, decoded_input) <ide> <ide> <ide><path>tests/test_tokenization_fast.py <ide> # See the License for the specific language governing permissions and <ide> # limitations under the License. <ide> <add>import shutil <add>import tempfile <ide> import unittest <ide> <ide> from transformers import PreTrainedTokenizerFast <ide> def setUp(self): <ide> super().setUp() <ide> self.test_rust_tokenizer = True <ide> <del> self.tokenizers_list = [(PreTrainedTokenizerFast, "robot-test/dummy-tokenizer-fast", {})] <add> model_paths = ["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"] <ide> <del> tokenizer = PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-fast") <add> # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment) <add> self.tokenizers_list = [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths] <add> <add> tokenizer = PreTrainedTokenizerFast.from_pretrained(model_paths[0]) <ide> tokenizer.save_pretrained(self.tmpdirname) <ide> <ide> def test_pretrained_model_lists(self): <ide> def test_prepare_for_model(self): <ide> def test_rust_tokenizer_signature(self): <ide> # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature <ide> pass <add> <add> def test_training_new_tokenizer(self): <add> tmpdirname_orig = self.tmpdirname <add> # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel. <add> for tokenizer, pretrained_name, kwargs in self.tokenizers_list: <add> with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): <add> try: <add> self.tmpdirname = tempfile.mkdtemp() <add> tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) <add> <add> tokenizer.save_pretrained(self.tmpdirname) <add> super().test_training_new_tokenizer() <add> finally: <add> # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer <add> # is restored <add> shutil.rmtree(self.tmpdirname) <add> self.tmpdirname = tmpdirname_orig <add> <add> def test_training_new_tokenizer_with_special_tokens_change(self): <add> tmpdirname_orig = self.tmpdirname <add> # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel. <add> for tokenizer, pretrained_name, kwargs in self.tokenizers_list: <add> with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): <add> try: <add> self.tmpdirname = tempfile.mkdtemp() <add> tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) <add> <add> tokenizer.save_pretrained(self.tmpdirname) <add> super().test_training_new_tokenizer_with_special_tokens_change() <add> finally: <add> # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer <add> # is restored <add> shutil.rmtree(self.tmpdirname) <add> self.tmpdirname = tmpdirname_orig
2
Javascript
Javascript
remove string literal message from assertion
86456bacd85bf508303bd077865d9443ba46bd81
<ide><path>test/addons-napi/test_general/testFinalizer.js <ide> test_general.wrap(finalizeAndWrap); <ide> test_general.addFinalizerOnly(finalizeAndWrap, common.mustCall()); <ide> finalizeAndWrap = null; <ide> global.gc(); <del>assert.strictEqual(test_general.derefItemWasCalled(), true, <del> 'finalize callback was called'); <add>assert.strictEqual(test_general.derefItemWasCalled(), true);
1
Python
Python
add more tests for rackspace driver
7952a148ffb21a950e080a324988abc2fe4a950b
<ide><path>libcloud/common/rackspace.py <ide> def host(self): <ide> scheme, server, self.request_path, param, query, fragment = ( <ide> urlparse.urlparse(getattr(self, self._url_key))) <ide> <del> if scheme is "https" and self.secure is not True: <del> raise InvalidCredsError() <del> <ide> # Set host to where we want to make further requests to; <ide> self.__host = server <ide> conn.close() <ide><path>test/compute/test_rackspace.py <ide> def test_auth(self): <ide> else: <ide> self.fail('test should have thrown') <ide> <add> def test_auth_missing_key(self): <add> RackspaceMockHttp.type = 'UNAUTHORIZED_MISSING_KEY' <add> try: <add> self.driver = Rackspace(RACKSPACE_USER, RACKSPACE_KEY) <add> except InvalidCredsError, e: <add> self.assertEqual(True, isinstance(e, InvalidCredsError)) <add> else: <add> self.fail('test should have thrown') <add> <ide> def test_list_nodes(self): <ide> RackspaceMockHttp.type = 'EMPTY' <ide> ret = self.driver.list_nodes() <ide> def _v1_0(self, method, url, body, headers): <ide> def _v1_0_UNAUTHORIZED(self, method, url, body, headers): <ide> return (httplib.UNAUTHORIZED, "", {}, httplib.responses[httplib.UNAUTHORIZED]) <ide> <add> def _v1_0_UNAUTHORIZED_MISSING_KEY(self, method, url, body, headers): <add> headers = {'x-server-management-url': 'https://servers.api.rackspacecloud.com/v1.0/slug', <add> 'x-auth-token': 'FE011C19-CF86-4F87-BE5D-9229145D7A06', <add> 'x-cdn-management-url': 'https://cdn.clouddrive.com/v1/MossoCloudFS_FE011C19-CF86-4F87-BE5D-9229145D7A06'} <add> return (httplib.NO_CONTENT, "", headers, httplib.responses[httplib.NO_CONTENT]) <add> <ide> def _v1_0_slug_servers_detail_EMPTY(self, method, url, body, headers): <ide> body = self.fixtures.load('v1_slug_servers_detail_empty.xml') <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK])
2
Python
Python
fix regression for in1d with non-array input
6d3950c8ac3ad6088a473acc7d68ba405c14267c
<ide><path>numpy/lib/arraysetops.py <ide> def in1d(ar1, ar2, assume_unique=False): <ide> array([0, 2, 0]) <ide> <ide> """ <add> # Ravel both arrays, behavior for the first array could be different <add> ar1 = np.asarray(ar1).ravel() <add> ar2 = np.asarray(ar2).ravel() <add> <ide> # This code is significantly faster when the condition is satisfied. <ide> if len(ar2) < 10 * len(ar1) ** 0.145: <ide> mask = np.zeros(len(ar1), dtype=np.bool) <ide><path>numpy/lib/tests/test_arraysetops.py <ide> def test_in1d(self): <ide> # we use two different sizes for the b array here to test the <ide> # two different paths in in1d(). <ide> for mult in (1, 10): <del> a = np.array([5, 7, 1, 2]) <del> b = np.array([2, 4, 3, 1, 5] * mult) <add> # One check without np.array, to make sure lists are handled correct <add> a = [5, 7, 1, 2] <add> b = [2, 4, 3, 1, 5] * mult <ide> ec = np.array([True, False, True, True]) <ide> c = in1d(a, b, assume_unique=True) <ide> assert_array_equal(c, ec)
2
Python
Python
improve error message
22545c7da2a482ed1b86d9fedd4ef6eba917c13d
<ide><path>libcloud/common/openstack_identity.py <ide> def _get_unscoped_token_from_oidc_token(self): <ide> driver=self.driver) <ide> else: <ide> raise MalformedResponseError('Malformed response', <del> driver=self.driver) <add> driver=self.driver, <add> body=response.body) <ide> <ide> def _get_project_id(self, token): <ide> """ <ide> def _get_project_id(self, token): <ide> raise MalformedResponseError('Failed to parse JSON', e) <ide> else: <ide> raise MalformedResponseError('Malformed response', <del> driver=self.driver) <add> driver=self.driver, <add> body=response.body) <ide> <ide> <ide> class OpenStackIdentity_2_0_Connection_VOMS(OpenStackIdentityConnection, <ide> def _get_unscoped_token(self): <ide> raise MalformedResponseError('Failed to parse JSON', e) <ide> else: <ide> raise MalformedResponseError('Malformed response', <del> driver=self.driver) <add> driver=self.driver, <add> body=response.body) <ide> <ide> def _get_tenant_name(self, token): <ide> """ <ide> def _get_tenant_name(self, token): <ide> raise MalformedResponseError('Failed to parse JSON', e) <ide> else: <ide> raise MalformedResponseError('Malformed response', <del> driver=self.driver) <add> driver=self.driver, <add> body=response.body) <ide> <ide> def _authenticate_2_0_with_body(self, reqbody): <ide> resp = self.request('/v2.0/tokens', data=reqbody,
1
PHP
PHP
improve code readability
5e1faa98da07d317ffd1e2088363bf2db9c1d98c
<ide><path>src/Datasource/QueryTrait.php <ide> public function eagerLoaded(bool $value) <ide> */ <ide> public function aliasField(string $field, ?string $alias = null): array <ide> { <del> $namespaced = strpos($field, '.') !== false; <del> $aliasedField = $field; <del> <del> if ($namespaced) { <add> if (strpos($field, '.') === false) { <add> $alias = $alias ?: $this->getRepository()->getAlias(); <add> $aliasedField = $alias . '.' . $field; <add> } else { <add> $aliasedField = $field; <ide> [$alias, $field] = explode('.', $field); <ide> } <ide> <del> if (!$alias) { <del> $alias = $this->getRepository()->getAlias(); <del> } <del> <ide> $key = sprintf('%s__%s', $alias, $field); <del> if (!$namespaced) { <del> $aliasedField = $alias . '.' . $field; <del> } <ide> <ide> return [$key => $aliasedField]; <ide> }
1
Ruby
Ruby
expand word_wrap test coverage
5e71ca3c2166866f7f96b54cb3c85bfd00901078
<ide><path>actionview/test/template/text_helper_test.rb <ide> def test_excerpt_with_separator <ide> excerpt("This is a beautiful morning", "a", separator: nil) <ide> end <ide> <del> def test_word_wrap <del> assert_equal("my very very\nvery long\nstring", word_wrap("my very very very long string", line_width: 15)) <add> test "word_wrap" do <add> input = "123 1234 12 12 123 1 1 1 123" <add> assert_equal "123\n1234\n12\n12\n123\n1 1\n1\n123", word_wrap(input, line_width: 3) <add> assert_equal "123-+1234-+12-+12-+123-+1 1-+1-+123", word_wrap(input, line_width: 3, break_sequence: "-+") <ide> end <ide> <del> def test_word_wrap_with_extra_newlines <del> assert_equal("my very very\nvery long\nstring\n\nwith another\nline", word_wrap("my very very very long string\n\nwith another line", line_width: 15)) <add> test "word_wrap with newlines" do <add> input = "1\n1 1 1\n1" <add> assert_equal "1\n1 1\n1\n1", word_wrap(input, line_width: 3) <add> assert_equal "1-+1 1-+1-+1", word_wrap(input, line_width: 3, break_sequence: "-+") <ide> end <ide> <del> def test_word_wrap_with_leading_spaces <del> assert_equal(" This is a paragraph\nthat includes some\nindented lines:\n Like this sample\n blockquote", word_wrap(" This is a paragraph that includes some\nindented lines:\n Like this sample\n blockquote", line_width: 25)) <add> test "word_wrap with multiple consecutive newlines" do <add> input = "1\n\n\n1 1 1\n\n\n1" <add> assert_equal "1\n\n\n1 1\n1\n\n\n1", word_wrap(input, line_width: 3) <add> assert_equal "1-+-+-+1 1-+1-+-+-+1", word_wrap(input, line_width: 3, break_sequence: "-+") <ide> end <ide> <del> def test_word_wrap_with_custom_break_sequence <del> assert_equal("1234567890\r\n1234567890\r\n1234567890", word_wrap("1234567890 " * 3, line_width: 2, break_sequence: "\r\n")) <add> test "word_wrap with trailing newlines" do <add> input = "1\n1 1 1\n1\n\n\n" <add> assert_equal "1\n1 1\n1\n1", word_wrap(input, line_width: 3) <add> assert_equal "1-+1 1-+1-+1", word_wrap(input, line_width: 3, break_sequence: "-+") <ide> end <ide> <del> def test_word_wrap_with_non_strippable_break_sequence <del> assert_equal("11\n# 22\n# 33", word_wrap("11 22 33", line_width: 2, break_sequence: "\n# ")) <add> test "word_wrap with leading spaces" do <add> input = " 1 1\n 1 1\n" <add> assert_equal " 1\n1\n 1\n1", word_wrap(input, line_width: 3) <add> assert_equal " 1-+1-+ 1-+1", word_wrap(input, line_width: 3, break_sequence: "-+") <ide> end <ide> <ide> def test_pluralization
1
PHP
PHP
allow exception mapping
5a5a3355fa8a987e9a3a6e30c32c9f59e1fefc80
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> <ide> namespace Illuminate\Foundation\Exceptions; <ide> <add>use Closure; <ide> use Exception; <ide> use Illuminate\Auth\Access\AuthorizationException; <ide> use Illuminate\Auth\AuthenticationException; <ide> use Illuminate\Support\Traits\ReflectsClosures; <ide> use Illuminate\Support\ViewErrorBag; <ide> use Illuminate\Validation\ValidationException; <add>use InvalidArgumentException; <ide> use Psr\Log\LoggerInterface; <ide> use Symfony\Component\Console\Application as ConsoleApplication; <ide> use Symfony\Component\ErrorHandler\ErrorRenderer\HtmlErrorRenderer; <ide> class Handler implements ExceptionHandlerContract <ide> */ <ide> protected $renderCallbacks = []; <ide> <add> /** <add> * The registered exception mappings. <add> * <add> * @var array <add> */ <add> protected $exceptionMap = []; <add> <ide> /** <ide> * A list of the internal exception types that should not be reported. <ide> * <ide> public function renderable(callable $renderUsing) <ide> return $this; <ide> } <ide> <add> /** <add> * Register a new exception mapping. <add> * <add> * @param \Closure|string $from <add> * @param \Closure|string|null $to <add> * @return $this <add> */ <add> public function map($from, $to = null) <add> { <add> if (is_string($to)) { <add> $to = function ($exception) use ($to) { <add> return new $to('', 0, $exception); <add> }; <add> } <add> <add> if (is_callable($from) && is_null($to)) { <add> $from = $this->firstClosureParameterType($to = $from); <add> } <add> <add> if (! is_string($from) || ! $to instanceof Closure) { <add> throw new InvalidArgumentException('Invalid exception mapping.'); <add> } <add> <add> $this->exceptionMap[$from] = $to; <add> <add> return $this; <add> } <add> <ide> /** <ide> * Report or log an exception. <ide> * <ide> public function renderable(callable $renderUsing) <ide> */ <ide> public function report(Throwable $e) <ide> { <add> $e = $this->mapException($e); <add> <ide> if ($this->shouldntReport($e)) { <ide> return; <ide> } <ide> public function render($request, Throwable $e) <ide> return $e->toResponse($request); <ide> } <ide> <del> $e = $this->prepareException($e); <add> $e = $this->prepareException($this->mapException($e)); <ide> <ide> foreach ($this->renderCallbacks as $renderCallback) { <ide> if (is_a($e, $this->firstClosureParameterType($renderCallback))) { <ide> public function render($request, Throwable $e) <ide> : $this->prepareResponse($request, $e); <ide> } <ide> <add> /** <add> * Map the exception using a registered mapper if possible. <add> * <add> * @param \Throwable $e <add> * @return \Throwable <add> */ <add> protected function mapException(Throwable $e) <add> { <add> foreach ($this->exceptionMap as $class => $mapper) { <add> if (is_a($e, $class)) { <add> return $mapper($e); <add> } <add> } <add> <add> return $e; <add> } <add> <ide> /** <ide> * Prepare exception for rendering. <ide> *
1
PHP
PHP
avoid unneeded variable assignment
aace57acd44c005ef765cac497328d29a390431f
<ide><path>src/ORM/Table.php <ide> public function belongsToMany(string $associated, array $options = []): BelongsT <ide> */ <ide> public function find(string $type = 'all', array $options = []): Query <ide> { <del> $query = $this->query(); <del> $query->select(); <del> <del> return $this->callFinder($type, $query, $options); <add> return $this->callFinder($type, $this->query()->select(), $options); <ide> } <ide> <ide> /** <ide> public function subquery(): Query <ide> */ <ide> public function updateAll($fields, $conditions): int <ide> { <del> $query = $this->query(); <del> $query->update() <add> $statement = $this->query() <add> ->update() <ide> ->set($fields) <del> ->where($conditions); <del> $statement = $query->execute(); <add> ->where($conditions) <add> ->execute(); <ide> $statement->closeCursor(); <ide> <ide> return $statement->rowCount(); <ide> public function updateAll($fields, $conditions): int <ide> */ <ide> public function deleteAll($conditions): int <ide> { <del> $query = $this->query() <add> $statement = $this->query() <ide> ->delete() <del> ->where($conditions); <del> $statement = $query->execute(); <add> ->where($conditions) <add> ->execute(); <ide> $statement->closeCursor(); <ide> <ide> return $statement->rowCount(); <ide> protected function _insert(EntityInterface $entity, array $data) <ide> } <ide> } <ide> <del> $success = false; <ide> if (empty($data)) { <del> return $success; <add> return false; <ide> } <ide> <ide> $statement = $this->query()->insert(array_keys($data)) <ide> ->values($data) <ide> ->execute(); <ide> <add> $success = false; <ide> if ($statement->rowCount() !== 0) { <ide> $success = $entity; <ide> $entity->set($filteredKeys, ['guard' => false]); <ide> protected function _update(EntityInterface $entity, array $data) <ide> throw new InvalidArgumentException($message); <ide> } <ide> <del> $query = $this->query(); <del> $statement = $query->update() <add> $statement = $this->query() <add> ->update() <ide> ->set($data) <ide> ->where($primaryKey) <ide> ->execute(); <ide> <del> $success = false; <del> if ($statement->errorCode() === '00000') { <del> $success = $entity; <del> } <add> $success = $statement->errorCode() === '00000' ? $entity : false; <ide> $statement->closeCursor(); <ide> <ide> return $success; <ide> protected function _processDelete(EntityInterface $entity, ArrayObject $options) <ide> return $success; <ide> } <ide> <del> $query = $this->query(); <del> $conditions = $entity->extract($primaryKey); <del> $statement = $query->delete() <del> ->where($conditions) <add> $statement = $this->query() <add> ->delete() <add> ->where($entity->extract($primaryKey)) <ide> ->execute(); <ide> <del> $success = $statement->rowCount() > 0; <del> if (!$success) { <del> return $success; <add> if ($statement->rowCount() < 1) { <add> return false; <ide> } <ide> <ide> $this->dispatchEvent('Model.afterDelete', [ <ide> 'entity' => $entity, <ide> 'options' => $options, <ide> ]); <ide> <del> return $success; <add> return true; <ide> } <ide> <ide> /**
1
Javascript
Javascript
flow strict touchablehighlight
a97d104b44daa068fa3848cc6c3225356f9dc318
<ide><path>Libraries/Components/AppleTV/TVViewPropTypes.js <ide> export type TVParallaxPropertiesType = $ReadOnly<{| <ide> /** <ide> * If true, parallax effects are enabled. Defaults to true. <ide> */ <del> enabled: boolean, <add> enabled?: boolean, <ide> <ide> /** <ide> * Defaults to 2.0. <ide> */ <del> shiftDistanceX: number, <add> shiftDistanceX?: number, <ide> <ide> /** <ide> * Defaults to 2.0. <ide> */ <del> shiftDistanceY: number, <add> shiftDistanceY?: number, <ide> <ide> /** <ide> * Defaults to 0.05. <ide> */ <del> tiltAngle: number, <add> tiltAngle?: number, <ide> <ide> /** <ide> * Defaults to 1.0 <ide> */ <del> magnification: number, <add> magnification?: number, <add> <add> /** <add> * Defaults to 1.0 <add> */ <add> pressMagnification?: number, <add> <add> /** <add> * Defaults to 0.3 <add> */ <add> pressDuration?: number, <add> <add> /** <add> * Defaults to 0.3 <add> */ <add> pressDelay?: number, <ide> |}>; <ide> <ide> /** <ide><path>Libraries/Components/Touchable/TouchableHighlight.js <ide> import type {PressEvent} from 'CoreEventTypes'; <ide> import type {ViewStyleProp} from 'StyleSheet'; <ide> import type {ColorValue} from 'StyleSheetTypes'; <ide> import type {Props as TouchableWithoutFeedbackProps} from 'TouchableWithoutFeedback'; <add>import type {TVParallaxPropertiesType} from 'TVViewPropTypes'; <ide> <ide> const DEFAULT_PROPS = { <ide> activeOpacity: 0.85, <ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; <ide> <ide> type IOSProps = $ReadOnly<{| <ide> hasTVPreferredFocus?: ?boolean, <del> tvParallaxProperties?: ?Object, <add> tvParallaxProperties?: ?TVParallaxPropertiesType, <ide> |}>; <ide> <ide> type Props = $ReadOnly<{| <ide> type Props = $ReadOnly<{| <ide> activeOpacity?: ?number, <ide> underlayColor?: ?ColorValue, <ide> style?: ?ViewStyleProp, <del> onShowUnderlay?: ?Function, <del> onHideUnderlay?: ?Function, <add> onShowUnderlay?: ?() => void, <add> onHideUnderlay?: ?() => void, <ide> testOnly_pressed?: ?boolean, <ide> |}>; <ide> <ide> const TouchableHighlight = ((createReactClass({ <ide> */ <ide> hasTVPreferredFocus: PropTypes.bool, <ide> /** <del> * *(Apple TV only)* Object with properties to control Apple TV parallax effects. <del> * <del> * enabled: If true, parallax effects are enabled. Defaults to true. <del> * shiftDistanceX: Defaults to 2.0. <del> * shiftDistanceY: Defaults to 2.0. <del> * tiltAngle: Defaults to 0.05. <del> * magnification: Defaults to 1.0. <del> * pressMagnification: Defaults to 1.0. <del> * pressDuration: Defaults to 0.3. <del> * pressDelay: Defaults to 0.0. <del> * <del> * @platform ios <add> * Apple TV parallax effects <ide> */ <ide> tvParallaxProperties: PropTypes.object, <ide> /**
2
Python
Python
change version id to make pypi happy
d35aa7344ed96c8e1e17ea74ba14a760a3c8a418
<ide><path>spacy/about.py <ide> # https://github.com/pypa/warehouse/blob/master/warehouse/__about__.py <ide> <ide> __title__ = 'spacy' <del>__version__ = '1.0.0+a' <add>__version__ = '1.0.0-a' <ide> __summary__ = 'Industrial-strength NLP' <ide> __uri__ = 'https://spacy.io' <ide> __author__ = 'Matthew Honnibal'
1
Python
Python
expand initialize/training config validation
5fb8b7037aa67400a76a0545f85c3c15a2491fb6
<ide><path>spacy/cli/debug_config.py <ide> <ide> from ._util import Arg, Opt, show_validation_error, parse_config_overrides <ide> from ._util import import_code, debug_cli <del>from ..schemas import ConfigSchemaTraining <add>from ..schemas import ConfigSchemaInit, ConfigSchemaTraining <ide> from ..util import registry <ide> from .. import util <ide> <ide> def debug_config( <ide> config = util.load_config(config_path, overrides=overrides) <ide> nlp = util.load_model_from_config(config) <ide> config = nlp.config.interpolate() <add> msg.divider("Config validation for [initialize]") <add> with show_validation_error(config_path): <add> T = registry.resolve(config["initialize"], schema=ConfigSchemaInit) <add> msg.divider("Config validation for [training]") <add> with show_validation_error(config_path): <ide> T = registry.resolve(config["training"], schema=ConfigSchemaTraining) <ide> dot_names = [T["train_corpus"], T["dev_corpus"]] <ide> util.resolve_dot_names(config, dot_names) <ide><path>spacy/training/initialize.py <ide> from typing import Union, Dict, Optional, Any, List, IO, TYPE_CHECKING <add>from pydantic import BaseModel <ide> from thinc.api import Config, fix_random_seed, set_gpu_allocator <ide> from thinc.api import ConfigValidationError <ide> from pathlib import Path <ide> from ..lookups import Lookups <ide> from ..vectors import Vectors <ide> from ..errors import Errors <del>from ..schemas import ConfigSchemaTraining <add>from ..schemas import ConfigSchemaInit, ConfigSchemaTraining <ide> from ..util import registry, load_model_from_config, resolve_dot_names, logger <ide> from ..util import load_model, ensure_path, OOV_RANK, DEFAULT_OOV_PROB <ide> <ide> def init_nlp(config: Config, *, use_gpu: int = -1) -> "Language": <ide> raw_config = config <ide> config = raw_config.interpolate() <add> # Validate config before accessing values <add> _validate_config_block(config, "initialize", ConfigSchemaInit) <add> _validate_config_block(config, "training", ConfigSchemaTraining) <ide> if config["training"]["seed"] is not None: <ide> fix_random_seed(config["training"]["seed"]) <ide> allocator = config["training"]["gpu_allocator"] <ide> def ensure_shape(lines): <ide> length = len(captured) <ide> yield f"{length} {width}" <ide> yield from captured <add> <add> <add>def _validate_config_block(config: Config, block: str, schema: BaseModel): <add> try: <add> registry.resolve(config[block], validate=True, schema=schema) <add> except ConfigValidationError as e: <add> title = f"Config validation error for [{block}]" <add> desc = "For more information run: python -m spacy debug config config.cfg" <add> err = ConfigValidationError.from_error(e, title=title, desc=desc) <add> raise err from None
2
Python
Python
add a new bar class to display bar in curse ui
a6db0977c8495138271b5c473b30100f5157f767
<ide><path>glances/outputs/glances_bars.py <add># -*- coding: utf-8 -*- <add># <add># This file is part of Glances. <add># <add># Copyright (C) 2015 Nicolargo <nicolas@nicolargo.com> <add># <add># Glances is free software; you can redistribute it and/or modify <add># it under the terms of the GNU Lesser General Public License as published by <add># the Free Software Foundation, either version 3 of the License, or <add># (at your option) any later version. <add># <add># Glances is distributed in the hope that it will be useful, <add># but WITHOUT ANY WARRANTY; without even the implied warranty of <add># MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the <add># GNU Lesser General Public License for more details. <add># <add># You should have received a copy of the GNU Lesser General Public License <add># along with this program. If not, see <http://www.gnu.org/licenses/>. <add> <add>"""Manage bars for Glances output.""" <add> <add># Import system lib <add>from math import modf <add> <add># Global vars <add>curses_bars = [" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"] <add> <add> <add>class Bar(object): <add> """Manage bar (progression or status) <add> <add> import sys <add> import time <add> b = Bar(10) <add> for p in range(0, 100): <add> b.set_percent(p) <add> print("\r%s" % b), <add> time.sleep(0.1) <add> sys.stdout.flush() <add> <add> """ <add> <add> def __init__(self, size): <add> # Bar size <add> self.__size = size <add> # Bar current percent <add> self.__percent = 0 <add> <add> def get_size(self): <add> return self.__size <add> <add> def set_size(self, size): <add> self.__size = size <add> return self.__size <add> <add> def get_percent(self): <add> return self.__percent <add> <add> def set_percent(self, percent): <add> assert percent >= 0 <add> assert percent <= 100 <add> self.__percent = percent <add> return self.__percent <add> <add> def __str__(self): <add> """Return the bars""" <add> frac, whole = modf(self.get_size() * self.get_percent() / 100.0) <add> ret = curses_bars[8] * int(whole) <add> if frac > 0: <add> ret += curses_bars[int(frac * 8)] <add> whole += 1 <add> ret += '_' * int(self.get_size() - whole) <add> return ret
1
Text
Text
describe buffer limit of v8.serialize
14f6c67eda88e6da1ab512f8ff0c305ca20ab1b0
<ide><path>doc/api/v8.md <ide> added: v8.0.0 <ide> <ide> Uses a [`DefaultSerializer`][] to serialize `value` into a buffer. <ide> <add>[`ERR_BUFFER_TOO_LARGE`][] will be thrown when trying to <add>serialize a huge object which requires buffer <add>larger than [`buffer.constants.MAX_LENGTH`][]. <add> <ide> ### `v8.deserialize(buffer)` <ide> <ide> <!-- YAML <ide> A subclass of [`Deserializer`][] corresponding to the format written by <ide> [`DefaultDeserializer`]: #class-v8defaultdeserializer <ide> [`DefaultSerializer`]: #class-v8defaultserializer <ide> [`Deserializer`]: #class-v8deserializer <add>[`ERR_BUFFER_TOO_LARGE`]: errors.md#err_buffer_too_large <ide> [`Error`]: errors.md#class-error <ide> [`GetHeapSpaceStatistics`]: https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4 <ide> [`NODE_V8_COVERAGE`]: cli.md#node_v8_coveragedir <ide> [`Serializer`]: #class-v8serializer <add>[`buffer.constants.MAX_LENGTH`]: buffer.md#bufferconstantsmax_length <ide> [`deserializer._readHostObject()`]: #deserializer_readhostobject <ide> [`deserializer.transferArrayBuffer()`]: #deserializertransferarraybufferid-arraybuffer <ide> [`serialize()`]: #v8serializevalue
1
Python
Python
update version to 1.0b3
779dc154b799a6660f7f60ef50c09fc445329999
<ide><path>numpy/version.py <del>version='1.0b2' <add>version='1.0b3' <ide> release=False <ide> <ide> if not release:
1
Javascript
Javascript
note restrictions of addclass and removeclass
cd3673e51430620e91ad1b55e8eb528d4833e979
<ide><path>src/jqLite.js <ide> * ## Angular's jqLite <ide> * jqLite provides only the following jQuery methods: <ide> * <del> * - [`addClass()`](http://api.jquery.com/addClass/) <add> * - [`addClass()`](http://api.jquery.com/addClass/) - Does not support a function as first argument <ide> * - [`after()`](http://api.jquery.com/after/) <ide> * - [`append()`](http://api.jquery.com/append/) <ide> * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters <ide> * - [`ready()`](http://api.jquery.com/ready/) <ide> * - [`remove()`](http://api.jquery.com/remove/) <ide> * - [`removeAttr()`](http://api.jquery.com/removeAttr/) <del> * - [`removeClass()`](http://api.jquery.com/removeClass/) <add> * - [`removeClass()`](http://api.jquery.com/removeClass/) - Does not support a function as first argument <ide> * - [`removeData()`](http://api.jquery.com/removeData/) <ide> * - [`replaceWith()`](http://api.jquery.com/replaceWith/) <ide> * - [`text()`](http://api.jquery.com/text/)
1
Javascript
Javascript
fill empty catch block with comment
300281fde6d0444cb73f74ea22b549eea534fe4d
<ide><path>packages/ember-glimmer/lib/components/text_field.js <ide> function canSetTypeOfInput(type) { <ide> <ide> try { <ide> inputTypeTestElement.type = type; <del> } catch (e) { } <add> } catch (e) { <add> // ignored <add> } <ide> <ide> return inputTypes[type] = inputTypeTestElement.type === type; <ide> }
1
Ruby
Ruby
remove unecessary comment
1909095aeaad41c227ec4099f58dbb925811822b
<ide><path>activerecord/test/cases/comment_test.rb <ide> def test_schema_dump_omits_blank_comments <ide> end <ide> end <ide> <del>end # if ActiveRecord::Base.connection.supports_comments? <add>end
1
Text
Text
fix typo in release-notes.md
67e99a29b814af86c7c2544b42d83cdf9cb2d647
<ide><path>docs/community/release-notes.md <ide> You can determine your currently installed version using `pip show`: <ide> <ide> ### 3.9.0 <ide> <del>**Date**: [18st October 2018][3.9.0-milestone] <add>**Date**: [18th October 2018][3.9.0-milestone] <ide> <ide> * Improvements to ViewSet extra actions [#5605][gh5605] <ide> * Fix `action` support for ViewSet suffixes [#6081][gh6081]
1
Java
Java
replace mvcurls with mvcuricomponentsbuilder
cf5db8362b3b95e2555e4e1600e3c6919e952f01
<ide><path>spring-web/src/main/java/org/springframework/web/method/support/CompositeUriComponentsContributor.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.web.method.support; <add> <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.convert.ConversionService; <add>import org.springframework.format.support.DefaultFormattingConversionService; <add>import org.springframework.util.Assert; <add>import org.springframework.web.util.UriComponentsBuilder; <add> <add>import java.util.ArrayList; <add>import java.util.Collection; <add>import java.util.List; <add>import java.util.Map; <add> <add>/** <add> * A {@link UriComponentsContributor} containing a list of other contributors <add> * to delegate and also encapsulating a specific {@link ConversionService} to <add> * use for formatting method argument values to Strings. <add> * <add> * @author Rossen Stoyanchev <add> * @since 4.0 <add> */ <add>public class CompositeUriComponentsContributor implements UriComponentsContributor { <add> <add> private final List<UriComponentsContributor> contributors = new ArrayList<UriComponentsContributor>(); <add> <add> private final ConversionService conversionService; <add> <add> <add> /** <add> * Create an instance from a collection of {@link UriComponentsContributor}s or <add> * {@link HandlerMethodArgumentResolver}s. Since both of these tend to be implemented <add> * by the same class, the most convenient option is to obtain the configured <add> * {@code HandlerMethodArgumentResolvers} in {@code RequestMappingHandlerAdapter} and <add> * provide that to this constructor. <add> * <add> * @param contributors a collection of {@link UriComponentsContributor} <add> * or {@link HandlerMethodArgumentResolver}s. <add> */ <add> public CompositeUriComponentsContributor(Collection<?> contributors) { <add> this(contributors, null); <add> } <add> <add> /** <add> * Create an instance from a collection of {@link UriComponentsContributor}s or <add> * {@link HandlerMethodArgumentResolver}s. Since both of these tend to be implemented <add> * by the same class, the most convenient option is to obtain the configured <add> * {@code HandlerMethodArgumentResolvers} in the {@code RequestMappingHandlerAdapter} <add> * and provide that to this constructor. <add> * <p> <add> * If the {@link ConversionService} argument is {@code null}, <add> * {@link org.springframework.format.support.DefaultFormattingConversionService} <add> * will be used by default. <add> * <add> * @param contributors a collection of {@link UriComponentsContributor} <add> * or {@link HandlerMethodArgumentResolver}s. <add> * @param conversionService a ConversionService to use when method argument values <add> * need to be formatted as Strings before being added to the URI <add> */ <add> public CompositeUriComponentsContributor(Collection<?> contributors, ConversionService conversionService) { <add> <add> Assert.notNull(contributors, "'uriComponentsContributors' must not be null"); <add> <add> for (Object contributor : contributors) { <add> if (contributor instanceof UriComponentsContributor) { <add> this.contributors.add((UriComponentsContributor) contributor); <add> } <add> } <add> <add> this.conversionService = (conversionService != null) ? <add> conversionService : new DefaultFormattingConversionService(); <add> } <add> <add> <add> public boolean hasContributors() { <add> return this.contributors.isEmpty(); <add> } <add> <add> @Override <add> public boolean supportsParameter(MethodParameter parameter) { <add> for (UriComponentsContributor c : this.contributors) { <add> if (c.supportsParameter(parameter)) { <add> return true; <add> } <add> } <add> return false; <add> } <add> <add> @Override <add> public void contributeMethodArgument(MethodParameter parameter, Object value, <add> UriComponentsBuilder builder, Map<String, Object> uriVariables, ConversionService conversionService) { <add> <add> for (UriComponentsContributor c : this.contributors) { <add> if (c.supportsParameter(parameter)) { <add> c.contributeMethodArgument(parameter, value, builder, uriVariables, conversionService); <add> break; <add> } <add> } <add> } <add> <add> /** <add> * An overloaded method that uses the ConversionService created at construction. <add> */ <add> public void contributeMethodArgument(MethodParameter parameter, Object value, UriComponentsBuilder builder, <add> Map<String, Object> uriVariables) { <add> <add> this.contributeMethodArgument(parameter, value, builder, uriVariables, this.conversionService); <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/util/UriComponentsBuilder.java <ide> public UriComponentsBuilder queryParam(String name, Object... values) { <ide> return this; <ide> } <ide> <add> /** <add> * Adds the given query parameters. <add> * @param params the params <add> * @return this UriComponentsBuilder <add> */ <add> public UriComponentsBuilder queryParams(MultiValueMap<String, String> params) { <add> Assert.notNull(params, "'params' must not be null"); <add> this.queryParams.putAll(params); <add> return this; <add> } <add> <ide> /** <ide> * Sets the query parameter values overriding all existing query values for <ide> * the same parameter. If no values are given, the query parameter is <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/AnnotationDrivenBeanDefinitionParser.java <ide> import java.util.List; <ide> import java.util.Properties; <ide> <add>import org.springframework.beans.factory.FactoryBean; <add>import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.beans.factory.config.BeanDefinition; <ide> import org.springframework.beans.factory.config.BeanDefinitionHolder; <ide> import org.springframework.beans.factory.config.RuntimeBeanReference; <ide> import org.springframework.beans.factory.support.RootBeanDefinition; <ide> import org.springframework.beans.factory.xml.BeanDefinitionParser; <ide> import org.springframework.beans.factory.xml.ParserContext; <add>import org.springframework.core.convert.ConversionService; <ide> import org.springframework.format.support.DefaultFormattingConversionService; <ide> import org.springframework.format.support.FormattingConversionServiceFactoryBean; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.web.bind.annotation.ResponseStatus; <ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <ide> import org.springframework.web.bind.support.WebArgumentResolver; <add>import org.springframework.web.method.support.CompositeUriComponentsContributor; <ide> import org.springframework.web.servlet.HandlerAdapter; <ide> import org.springframework.web.servlet.HandlerExceptionResolver; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <ide> import org.springframework.web.servlet.mvc.method.annotation.ServletWebArgumentResolverAdapter; <ide> import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; <add>import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; <ide> import org.w3c.dom.Element; <ide> <ide> /** <ide> public BeanDefinition parse(Element element, ParserContext parserContext) { <ide> handlerAdapterDef.getPropertyValues().add("deferredResultInterceptors", deferredResultInterceptors); <ide> String handlerAdapterName = parserContext.getReaderContext().registerWithGeneratedName(handlerAdapterDef); <ide> <del> String mvcUrlsName = "mvcUrls"; <del> RootBeanDefinition mvcUrlsDef = new RootBeanDefinition(DefaultMvcUrlsFactoryBean.class); <del> mvcUrlsDef.setSource(source); <del> mvcUrlsDef.getPropertyValues().addPropertyValue("handlerAdapter", handlerAdapterDef); <del> mvcUrlsDef.getPropertyValues().addPropertyValue("conversionService", conversionService); <del> parserContext.getReaderContext().getRegistry().registerBeanDefinition(mvcUrlsName, mvcUrlsDef); <add> String uriCompContribName = MvcUriComponentsBuilder.MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME; <add> RootBeanDefinition uriCompContribDef = new RootBeanDefinition(CompositeUriComponentsContributorFactoryBean.class); <add> uriCompContribDef.setSource(source); <add> uriCompContribDef.getPropertyValues().addPropertyValue("handlerAdapter", handlerAdapterDef); <add> uriCompContribDef.getPropertyValues().addPropertyValue("conversionService", conversionService); <add> parserContext.getReaderContext().getRegistry().registerBeanDefinition(uriCompContribName, uriCompContribDef); <ide> <ide> RootBeanDefinition csInterceptorDef = new RootBeanDefinition(ConversionServiceExposingInterceptor.class); <ide> csInterceptorDef.setSource(source); <ide> public BeanDefinition parse(Element element, ParserContext parserContext) { <ide> <ide> parserContext.registerComponent(new BeanComponentDefinition(handlerMappingDef, methodMappingName)); <ide> parserContext.registerComponent(new BeanComponentDefinition(handlerAdapterDef, handlerAdapterName)); <del> parserContext.registerComponent(new BeanComponentDefinition(mvcUrlsDef, mvcUrlsName)); <add> parserContext.registerComponent(new BeanComponentDefinition(uriCompContribDef, uriCompContribName)); <ide> parserContext.registerComponent(new BeanComponentDefinition(exceptionHandlerExceptionResolver, methodExceptionResolverName)); <ide> parserContext.registerComponent(new BeanComponentDefinition(responseStatusExceptionResolver, responseStatusExceptionResolverName)); <ide> parserContext.registerComponent(new BeanComponentDefinition(defaultExceptionResolver, defaultExceptionResolverName)); <ide> private ManagedList<BeanDefinitionHolder> wrapWebArgumentResolverBeanDefs(List<B <ide> return result; <ide> } <ide> <add> <add> /** <add> * A FactoryBean for a CompositeUriComponentsContributor that obtains the <add> * HandlerMethodArgumentResolver's configured in RequestMappingHandlerAdapter <add> * after it is fully initialized. <add> */ <add> private static class CompositeUriComponentsContributorFactoryBean <add> implements InitializingBean, FactoryBean<CompositeUriComponentsContributor> { <add> <add> private RequestMappingHandlerAdapter handlerAdapter; <add> <add> private ConversionService conversionService; <add> <add> private CompositeUriComponentsContributor uriComponentsContributor; <add> <add> <add> public void setHandlerAdapter(RequestMappingHandlerAdapter handlerAdapter) { <add> this.handlerAdapter = handlerAdapter; <add> } <add> <add> public void setConversionService(ConversionService conversionService) { <add> this.conversionService = conversionService; <add> } <add> <add> @Override <add> public void afterPropertiesSet() throws Exception { <add> this.uriComponentsContributor = new CompositeUriComponentsContributor( <add> this.handlerAdapter.getArgumentResolvers(), this.conversionService); <add> } <add> <add> @Override <add> public CompositeUriComponentsContributor getObject() throws Exception { <add> return this.uriComponentsContributor; <add> } <add> <add> @Override <add> public Class<?> getObjectType() { <add> return CompositeUriComponentsContributor.class; <add> } <add> <add> @Override <add> public boolean isSingleton() { <add> return true; <add> } <add> } <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/DefaultMvcUrlsFactoryBean.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config; <del> <del>import org.springframework.beans.factory.FactoryBean; <del>import org.springframework.beans.factory.InitializingBean; <del>import org.springframework.core.convert.ConversionService; <del>import org.springframework.web.method.support.HandlerMethodArgumentResolver; <del>import org.springframework.web.method.support.UriComponentsContributor; <del>import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <del>import org.springframework.web.servlet.mvc.support.DefaultMvcUrls; <del>import org.springframework.web.servlet.mvc.support.MvcUrls; <del> <del> <del>/** <del> * A factory bean for creating an instance of {@link MvcUrls} that discovers <del> * {@link UriComponentsContributor}s by obtaining the <del> * {@link HandlerMethodArgumentResolver}s configured in a <del> * {@link RequestMappingHandlerAdapter}. <del> * <p> <del> * This is mainly provided as a convenience in XML configuration. Otherwise call the <del> * constructors of {@link DefaultMvcUrls} directly. Also note the MVC Java config and <del> * XML namespace already create an instance of {@link MvcUrls} and when using either <del> * of them this {@code FactoryBean} is not needed. <del> * <del> * @author Rossen Stoyanchev <del> * @since 4.0 <del> */ <del>public class DefaultMvcUrlsFactoryBean implements InitializingBean, FactoryBean<MvcUrls> { <del> <del> private RequestMappingHandlerAdapter handlerAdapter; <del> <del> private ConversionService conversionService; <del> <del> private MvcUrls mvcUrls; <del> <del> <del> /** <del> * Provide a {@link RequestMappingHandlerAdapter} from which to obtain <del> * the list of configured {@link HandlerMethodArgumentResolver}s. This <del> * is provided for ease of configuration in XML. <del> */ <del> public void setHandlerAdapter(RequestMappingHandlerAdapter handlerAdapter) { <del> this.handlerAdapter = handlerAdapter; <del> } <del> <del> /** <del> * Configure the {@link ConversionService} instance that {@link MvcUrls} should <del> * use to format Object values being added to a URI. <del> */ <del> public void setConversionService(ConversionService conversionService) { <del> this.conversionService = conversionService; <del> } <del> <del> @Override <del> public void afterPropertiesSet() throws Exception { <del> this.mvcUrls = new DefaultMvcUrls(this.handlerAdapter.getArgumentResolvers(), this.conversionService); <del> } <del> <del> @Override <del> public MvcUrls getObject() throws Exception { <del> return this.mvcUrls; <del> } <del> <del> @Override <del> public Class<?> getObjectType() { <del> return MvcUrls.class; <del> } <del> <del> @Override <del> public boolean isSingleton() { <del> return true; <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> import org.springframework.web.bind.annotation.ResponseStatus; <ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <ide> import org.springframework.web.context.ServletContextAware; <add>import org.springframework.web.method.support.CompositeUriComponentsContributor; <ide> import org.springframework.web.method.support.HandlerMethodArgumentResolver; <ide> import org.springframework.web.method.support.HandlerMethodReturnValueHandler; <ide> import org.springframework.web.servlet.HandlerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <ide> import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; <del>import org.springframework.web.servlet.mvc.support.DefaultMvcUrls; <del>import org.springframework.web.servlet.mvc.support.MvcUrls; <ide> <ide> /** <ide> * This is the main class providing the configuration behind the MVC Java config. <ide> public void configureAsyncSupport(AsyncSupportConfigurer configurer) { <ide> } <ide> <ide> /** <del> * Return an instance of {@link MvcUrls} for injection into controllers to create <del> * URLs by referencing controllers and controller methods. <add> * Return an instance of {@link CompositeUriComponentsContributor} for use with <add> * {@link org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder}. <ide> */ <ide> @Bean <del> public MvcUrls mvcUrls() { <del> return new DefaultMvcUrls(requestMappingHandlerAdapter().getArgumentResolvers(), mvcConversionService()); <add> public CompositeUriComponentsContributor mvcUriComponentsContributor() { <add> return new CompositeUriComponentsContributor( <add> requestMappingHandlerAdapter().getArgumentResolvers(), mvcConversionService()); <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.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.web.servlet.mvc.method.annotation; <add> <add>import org.aopalliance.intercept.MethodInterceptor; <add>import org.apache.commons.logging.Log; <add>import org.apache.commons.logging.LogFactory; <add>import org.springframework.aop.framework.ProxyFactory; <add>import org.springframework.aop.target.EmptyTargetSource; <add>import org.springframework.beans.factory.NoSuchBeanDefinitionException; <add>import org.springframework.cglib.proxy.Callback; <add>import org.springframework.cglib.proxy.Enhancer; <add>import org.springframework.cglib.proxy.Factory; <add>import org.springframework.cglib.proxy.MethodProxy; <add>import org.springframework.core.DefaultParameterNameDiscoverer; <add>import org.springframework.core.MethodParameter; <add>import org.springframework.core.ParameterNameDiscoverer; <add>import org.springframework.core.annotation.AnnotationUtils; <add>import org.springframework.objenesis.ObjenesisStd; <add>import org.springframework.util.*; <add>import org.springframework.web.bind.annotation.RequestMapping; <add>import org.springframework.web.context.WebApplicationContext; <add>import org.springframework.web.context.request.RequestAttributes; <add>import org.springframework.web.context.request.RequestContextHolder; <add>import org.springframework.web.context.request.ServletRequestAttributes; <add>import org.springframework.web.context.support.WebApplicationContextUtils; <add>import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; <add>import org.springframework.web.method.support.CompositeUriComponentsContributor; <add>import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <add>import org.springframework.web.util.UriComponents; <add>import org.springframework.web.util.UriComponentsBuilder; <add> <add>import javax.servlet.ServletContext; <add>import javax.servlet.http.HttpServletRequest; <add>import java.lang.reflect.Method; <add>import java.util.*; <add> <add>/** <add> * A UriComponentsBuilder that helps to build URIs to Spring MVC controllers and methods from their <add> * request mappings. <add> * <add> * @author Oliver Gierke <add> * @author Rossen Stoyanchev <add> * <add> * @since 4.0 <add> */ <add> <add>public class MvcUriComponentsBuilder extends UriComponentsBuilder { <add> <add> /** <add> * Well-known name for the {@link CompositeUriComponentsContributor} object in the bean factory. <add> */ <add> public static final String MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME = "mvcUriComponentsContributor"; <add> <add> <add> private static final CompositeUriComponentsContributor defaultUriComponentsContributor; <add> <add> private static final PathMatcher pathMatcher = new AntPathMatcher(); <add> <add> private static final ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); <add> <add> private final static ObjenesisStd objenesis = new ObjenesisStd(true); <add> <add> private static Log logger = LogFactory.getLog(MvcUriComponentsBuilder.class); <add> <add> <add> static { <add> defaultUriComponentsContributor = new CompositeUriComponentsContributor( <add> Arrays.asList( <add> new PathVariableMethodArgumentResolver(), <add> new RequestParamMethodArgumentResolver(null, false))); <add> } <add> <add> <add> /** <add> * Create a {@link UriComponentsBuilder} by pointing to a controller class. The <add> * resulting builder contains the current request information up to and including <add> * the Servlet mapping plus any type-level request mapping. If the controller <add> * contains multiple mappings, the first one is used. <add> * <add> * @param controllerType the controller to create a URI for <add> * <add> * @return a UriComponentsBuilder instance <add> */ <add> public static UriComponentsBuilder fromController(Class<?> controllerType) { <add> String mapping = getTypeRequestMapping(controllerType); <add> return ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping); <add> } <add> <add> /** <add> * Create a {@link UriComponentsBuilder} by pointing to a controller method and <add> * providing method argument values. The method is matched based on the provided <add> * method name and the number of argument values. If that results in a clash <add> * (i.e. overloaded methods with the same number of parameters), use <add> * {@link #fromMethod(java.lang.reflect.Method, Object...)} instead. <add> * <p> <add> * The argument values are used to prepare the URI for example expanding <add> * path variables, or adding query parameters. Any other arguments not <add> * relevant to the URI can be provided as {@literal null} and will be ignored. <add> * <p> <add> * Additional (custom) argument types can be supported through an implementation <add> * of {@link org.springframework.web.method.support.UriComponentsContributor}. <add> * <add> * @param controllerType the target controller type <add> * @param methodName the target method name <add> * @param argumentValues argument values matching to method parameters <add> * <add> * @return a UriComponentsBuilder instance <add> */ <add> public static UriComponentsBuilder fromMethodName(Class<?> controllerType, <add> String methodName, Object... argumentValues) { <add> <add> Method match = null; <add> for (Method method : controllerType.getDeclaredMethods()) { <add> if ((method.getParameterCount() == argumentValues.length) && method.getName().equals(methodName)) { <add> if (match != null) { <add> throw new IllegalStateException("Found two methods named '" + methodName <add> + "' having " + argumentValues + " arguments, controller " <add> + controllerType.getName()); <add> } <add> match = method; <add> } <add> } <add> if (match == null) { <add> throw new IllegalArgumentException("No method '" + methodName + "' with " <add> + argumentValues.length + " parameters found in " + controllerType.getName()); <add> } <add> return fromMethod(match, argumentValues); <add> } <add> <add> /** <add> * Create a {@link UriComponentsBuilder} by pointing to a controller method and <add> * providing method argument values. The method argument values are used to <add> * prepare the URI for example expanding path variables, or adding request <add> * parameters. Any other arguments not relevant to the URL can be provided as <add> * {@literal null} and will be ignored. <add> * <p> <add> * Additional (custom) argument types can be supported through an implementation <add> * of {@link org.springframework.web.method.support.UriComponentsContributor}. <add> * <add> * @param method the target controller method <add> * @param argumentValues argument values matching to method parameters <add> * <add> * @return a UriComponentsBuilder instance <add> */ <add> public static UriComponentsBuilder fromMethod(Method method, Object... argumentValues) { <add> <add> UriComponentsBuilder builder = ServletUriComponentsBuilder.newInstance().path(getMethodRequestMapping(method)); <add> UriComponents uriComponents = applyContributors(builder, method, argumentValues); <add> <add> String typePath = getTypeRequestMapping(method.getDeclaringClass()); <add> String methodPath = uriComponents.getPath(); <add> String path = pathMatcher.combine(typePath, methodPath); <add> <add> return ServletUriComponentsBuilder.fromCurrentServletMapping().path( <add> path).queryParams(uriComponents.getQueryParams()); <add> } <add> <add> /** <add> * Create a {@link UriComponents} by invoking a method on a "mock" controller, similar <add> * to how test frameworks provide mock objects and record method invocations. <add> * <p> <add> * For example given this controller: <add> * <add> * <pre class="code"> <add> * &#064;RequestMapping("/people/{id}/addresses") <add> * class AddressController { <add> * <add> * &#064;RequestMapping("/{country}") <add> * public HttpEntity<Void> getAddressesForCountry(&#064;PathVariable String country) { … } <add> * <add> * &#064;RequestMapping(value="/", method=RequestMethod.POST) <add> * public void addAddress(Address address) { … } <add> * } <add> * </pre> <add> * <add> * A "mock" controller can be used as follows: <add> * <add> * <pre> <add> * <add> * // Inline style with static import of MvcUriComponentsBuilder.mock <add> * <add> * MvcUriComponentsBuilder.fromLastCall( <add> * mock(CustomerController.class).showAddresses("US")).buildAndExpand(1); <add> * <add> * // Longer style for preparing multiple URIs and for void controller methods <add> * <add> * CustomerController controller = MvcUriComponentsBuilder.mock(CustomController.class); <add> * controller.addAddress(null); <add> * <add> * MvcUriComponentsBuilder.fromLastCall(controller); <add> * <add> * </pre> <add> * <add> * The above supports {@codce @PathVariable} and {@code @RequestParam} method parameters. <add> * Any other arguments can be provided as {@literal null} and will be ignored. <add> * <p> <add> * Additional (custom) argument types can be supported through an implementation <add> * of {@link org.springframework.web.method.support.UriComponentsContributor}. <add> * <add> * @param methodInvocationInfo either the value returned from a "mock" controller <add> * invocation or the "mock" controller itself after an invocation <add> * <add> * @return a UriComponents instance <add> */ <add> public static UriComponentsBuilder fromLastCall(Object methodInvocationInfo) { <add> <add> Assert.isInstanceOf(MethodInvocationInfo.class, methodInvocationInfo); <add> MethodInvocationInfo info = (MethodInvocationInfo) methodInvocationInfo; <add> <add> Method method = info.getControllerMethod(); <add> Object[] argumentValues = info.getArgumentValues(); <add> <add> UriComponentsBuilder builder = ServletUriComponentsBuilder.newInstance().path(getMethodRequestMapping(method)); <add> UriComponents uriComponents = applyContributors(builder, method, argumentValues); <add> <add> String typeMapping = getTypeRequestMapping(method.getDeclaringClass()); <add> String methodMapping = uriComponents.getPath(); <add> String path = pathMatcher.combine(typeMapping, methodMapping); <add> <add> return ServletUriComponentsBuilder.fromCurrentServletMapping().path( <add> path).queryParams(uriComponents.getQueryParams()); <add> } <add> <add> <add> private static String getTypeRequestMapping(Class<?> controllerType) { <add> Assert.notNull(controllerType, "'controllerType' must not be null"); <add> RequestMapping annot = AnnotationUtils.findAnnotation(controllerType, RequestMapping.class); <add> if ((annot == null) || ObjectUtils.isEmpty(annot.value()) || StringUtils.isEmpty(annot.value()[0])) { <add> return "/"; <add> } <add> if (annot.value().length > 1) { <add> logger.warn("Multiple mappings on controller " + controllerType.getName() + ", using the first one"); <add> } <add> return annot.value()[0]; <add> } <add> <add> private static String getMethodRequestMapping(Method method) { <add> RequestMapping annot = AnnotationUtils.findAnnotation(method, RequestMapping.class); <add> Assert.notNull(annot, "No @RequestMapping on: " + method.toGenericString()); <add> if (ObjectUtils.isEmpty(annot.value()) || StringUtils.isEmpty(annot.value()[0])) { <add> return "/"; <add> } <add> if (annot.value().length > 1) { <add> logger.debug("Multiple mappings on method " + method.toGenericString() + ", using first one"); <add> } <add> return annot.value()[0]; <add> } <add> <add> private static UriComponents applyContributors(UriComponentsBuilder builder, Method method, Object[] args) { <add> <add> CompositeUriComponentsContributor contributor = getConfiguredUriComponentsContributor(); <add> if (contributor == null) { <add> logger.debug("Using default CompositeUriComponentsContributor"); <add> contributor = defaultUriComponentsContributor; <add> } <add> <add> int paramCount = method.getParameterCount(); <add> int argCount = args.length; <add> <add> Assert.isTrue(paramCount == argCount, "Number of method parameters " + paramCount + <add> " does not match number of argument values " + argCount); <add> <add> Map<String, Object> uriVars = new HashMap<String, Object>(); <add> <add> for (int i=0; i < paramCount; i++) { <add> MethodParameter param = new MethodParameter(method, i); <add> param.initParameterNameDiscovery(parameterNameDiscoverer); <add> contributor.contributeMethodArgument(param, args[i], builder, uriVars); <add> } <add> <add> return builder.buildAndExpand(uriVars); <add> } <add> <add> protected static CompositeUriComponentsContributor getConfiguredUriComponentsContributor() { <add> RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); <add> if (requestAttributes == null) { <add> logger.debug("No request bound to the current thread: is DispatcherSerlvet used?"); <add> return null; <add> } <add> HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); <add> if (request == null) { <add> logger.debug("Request bound to current thread is not an HttpServletRequest"); <add> return null; <add> } <add> ServletContext servletContext = request.getServletContext(); <add> WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext); <add> if (wac == null) { <add> logger.debug("No WebApplicationContext found: no ContextLoaderListener registered?"); <add> return null; <add> } <add> try { <add> String beanName = MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME; <add> return wac.getBean(beanName, CompositeUriComponentsContributor.class); <add> } <add> catch (NoSuchBeanDefinitionException ex) { <add> if (logger.isDebugEnabled()) { <add> logger.debug("No CompositeUriComponentsContributor bean with name '" <add> + MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME + "'"); <add> } <add> return null; <add> } <add> } <add> <add> /** <add> * Return a "mock" controller instance. When a method on the mock is invoked, the <add> * supplied argument values are remembered and the result can then be used to <add> * prepare a UriComponents through the factory method {@link #fromLastCall(Object)}. <add> * <p> <add> * The controller can be invoked more than once. However, only the last invocation <add> * is remembered. This means the same mock controller can be used to create <add> * multiple links in succession, for example: <add> * <add> * <pre> <add> * CustomerController controller = MvcUriComponentsBuilder.mock(CustomController.class); <add> * <add> * MvcUriComponentsBuilder.fromLastCall(controller.getFoo(1)).build(); <add> * MvcUriComponentsBuilder.fromLastCall(controller.getFoo(2)).build(); <add> * <add> * MvcUriComponentsBuilder.fromLastCall(controller.getBar(1)).build(); <add> * MvcUriComponentsBuilder.fromLastCall(controller.getBar(2)).build(); <add> * </pre> <add> * <add> * If a controller method returns void, use the following style: <add> * <add> * <pre> <add> * CustomerController controller = MvcUriComponentsBuilder.mock(CustomController.class); <add> * <add> * controller.handleFoo(1); <add> * MvcUriComponentsBuilder.fromLastCall(controller).build(); <add> * <add> * controller.handleFoo(2) <add> * MvcUriComponentsBuilder.fromLastCall(controller).build(); <add> * </pre> <add> * <add> * @param controllerType the type of controller to mock <add> */ <add> public static <T> T mock(Class<T> controllerType) { <add> Assert.notNull(controllerType, "'controllerType' must not be null"); <add> return initProxy(controllerType, new ControllerMethodInvocationInterceptor()); <add> } <add> <add> @SuppressWarnings("unchecked") <add> private static <T> T initProxy(Class<?> type, ControllerMethodInvocationInterceptor interceptor) { <add> <add> if (type.isInterface()) { <add> ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE); <add> factory.addInterface(type); <add> factory.addInterface(MethodInvocationInfo.class); <add> factory.addAdvice(interceptor); <add> return (T) factory.getProxy(); <add> } <add> else { <add> Enhancer enhancer = new Enhancer(); <add> enhancer.setSuperclass(type); <add> enhancer.setInterfaces(new Class<?>[]{MethodInvocationInfo.class}); <add> enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class); <add> <add> Factory factory = (Factory) objenesis.newInstance(enhancer.createClass()); <add> factory.setCallbacks(new Callback[] { interceptor }); <add> return (T) factory; <add> } <add> } <add> <add> <add> private static class ControllerMethodInvocationInterceptor <add> implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor { <add> <add> private static final Method getControllerMethod = <add> ReflectionUtils.findMethod(MethodInvocationInfo.class, "getControllerMethod"); <add> <add> private static final Method getArgumentValues = <add> ReflectionUtils.findMethod(MethodInvocationInfo.class, "getArgumentValues"); <add> <add> <add> private Method controllerMethod; <add> <add> private Object[] argumentValues; <add> <add> <add> @Override <add> public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) { <add> <add> if (getControllerMethod.equals(method)) { <add> return this.controllerMethod; <add> } <add> else if (getArgumentValues.equals(method)) { <add> return this.argumentValues; <add> } <add> else if (ReflectionUtils.isObjectMethod(method)) { <add> return ReflectionUtils.invokeMethod(method, obj, args); <add> } <add> else { <add> this.controllerMethod = method; <add> this.argumentValues = args; <add> <add> Class<?> returnType = method.getReturnType(); <add> return void.class.equals(returnType) ? null : returnType.cast(initProxy(returnType, this)); <add> } <add> } <add> <add> @Override <add> public Object invoke(org.aopalliance.intercept.MethodInvocation inv) throws Throwable { <add> return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null); <add> } <add> } <add> <add> public interface MethodInvocationInfo { <add> <add> Method getControllerMethod(); <add> <add> Object[] getArgumentValues(); <add> <add> } <add> <add>} <ide>\ No newline at end of file <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/DefaultMvcUrls.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.mvc.support; <del> <del>import java.lang.reflect.Method; <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.Collection; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <del> <del>import org.springframework.core.LocalVariableTableParameterNameDiscoverer; <del>import org.springframework.core.MethodParameter; <del>import org.springframework.core.ParameterNameDiscoverer; <del>import org.springframework.core.convert.ConversionService; <del>import org.springframework.format.support.DefaultFormattingConversionService; <del>import org.springframework.util.Assert; <del>import org.springframework.util.ObjectUtils; <del>import org.springframework.web.method.support.HandlerMethodArgumentResolver; <del>import org.springframework.web.method.support.UriComponentsContributor; <del>import org.springframework.web.servlet.mvc.support.MvcUrlUtils.ControllerMethodValues; <del>import org.springframework.web.servlet.support.ServletUriComponentsBuilder; <del>import org.springframework.web.util.UriComponents; <del>import org.springframework.web.util.UriComponentsBuilder; <del>import org.springframework.web.util.UriTemplate; <del> <del>/** <del> * A default {@link MvcUrls} implementation. <del> * <del> * @author Oliver Gierke <del> * @author Rossen Stoyanchev <del> * <del> * @since 4.0 <del> */ <del>public class DefaultMvcUrls implements MvcUrls { <del> <del> private static final ParameterNameDiscoverer parameterNameDiscoverer = <del> new LocalVariableTableParameterNameDiscoverer(); <del> <del> <del> private final List<UriComponentsContributor> contributors = new ArrayList<UriComponentsContributor>(); <del> <del> private final ConversionService conversionService; <del> <del> <del> /** <del> * Create an instance providing a collection of {@link UriComponentsContributor}s or <del> * {@link HandlerMethodArgumentResolver}s. Since both of these tend to be implemented <del> * by the same class, the most convenient option is to obtain the configured <del> * {@code HandlerMethodArgumentResolvers} in the {@code RequestMappingHandlerAdapter} <del> * and provide that to this constructor. <del> * @param uriComponentsContributors a collection of {@link UriComponentsContributor} <del> * or {@link HandlerMethodArgumentResolver}s. <del> */ <del> public DefaultMvcUrls(Collection<?> uriComponentsContributors) { <del> this(uriComponentsContributors, null); <del> } <del> <del> /** <del> * Create an instance providing a collection of {@link UriComponentsContributor}s or <del> * {@link HandlerMethodArgumentResolver}s. Since both of these tend to be implemented <del> * by the same class, the most convenient option is to obtain the configured <del> * {@code HandlerMethodArgumentResolvers} in the {@code RequestMappingHandlerAdapter} <del> * and provide that to this constructor. <del> * <del> * <p>If the {@link ConversionService} argument is {@code null}, <del> * {@link DefaultFormattingConversionService} will be used by default. <del> * @param uriComponentsContributors a collection of {@link UriComponentsContributor} <del> * or {@link HandlerMethodArgumentResolver}s. <del> * @param conversionService a ConversionService to use when method argument values <del> * need to be formatted as Strings before being added to the URI <del> */ <del> public DefaultMvcUrls(Collection<?> uriComponentsContributors, ConversionService conversionService) { <del> Assert.notNull(uriComponentsContributors, "'uriComponentsContributors' must not be null"); <del> for (Object contributor : uriComponentsContributors) { <del> if (contributor instanceof UriComponentsContributor) { <del> this.contributors.add((UriComponentsContributor) contributor); <del> } <del> } <del> this.conversionService = (conversionService != null) ? <del> conversionService : new DefaultFormattingConversionService(); <del> } <del> <del> <del> @Override <del> public UriComponentsBuilder linkToController(Class<?> controllerClass) { <del> String mapping = MvcUrlUtils.getTypeLevelMapping(controllerClass); <del> return ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping); <del> } <del> <del> @Override <del> public UriComponents linkToMethod(Method method, Object... argumentValues) { <del> String mapping = MvcUrlUtils.getMethodMapping(method); <del> UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping); <del> Map<String, Object> uriVars = new HashMap<String, Object>(); <del> return applyContributers(builder, method, argumentValues, uriVars); <del> } <del> <del> private UriComponents applyContributers(UriComponentsBuilder builder, Method method, <del> Object[] argumentValues, Map<String, Object> uriVars) { <del> if (this.contributors.isEmpty()) { <del> return builder.buildAndExpand(uriVars); <del> } <del> <del> int paramCount = method.getParameters().length; <del> int argCount = argumentValues.length; <del> Assert.isTrue(paramCount == argCount, "Number of method parameters " + paramCount + <del> " does not match number of argument values " + argCount); <del> <del> for (int i=0; i < paramCount; i++) { <del> MethodParameter param = new MethodParameter(method, i); <del> param.initParameterNameDiscovery(parameterNameDiscoverer); <del> for (UriComponentsContributor c : this.contributors) { <del> if (c.supportsParameter(param)) { <del> c.contributeMethodArgument(param, argumentValues[i], builder, uriVars, this.conversionService); <del> break; <del> } <del> } <del> } <del> <del> return builder.buildAndExpand(uriVars); <del> } <del> <del> @Override <del> public UriComponents linkToMethodOn(Object mockController) { <del> Assert.isInstanceOf(ControllerMethodValues.class, mockController); <del> ControllerMethodValues controllerMethodValues = (ControllerMethodValues) mockController; <del> <del> Method method = controllerMethodValues.getControllerMethod(); <del> Object[] argumentValues = controllerMethodValues.getArgumentValues(); <del> <del> Map<String, Object> uriVars = new HashMap<String, Object>(); <del> addTypeLevelUriVaris(controllerMethodValues, uriVars); <del> <del> String mapping = MvcUrlUtils.getMethodMapping(method); <del> UriComponentsBuilder builder = ServletUriComponentsBuilder.fromCurrentServletMapping().path(mapping); <del> <del> return applyContributers(builder, method, argumentValues, uriVars); <del> } <del> <del> private void addTypeLevelUriVaris(ControllerMethodValues info, Map<String, Object> uriVariables) { <del> Object[] values = info.getTypeLevelUriVariables(); <del> if (!ObjectUtils.isEmpty(values)) { <del> <del> String mapping = MvcUrlUtils.getTypeLevelMapping(info.getControllerMethod().getDeclaringClass()); <del> <del> List<String> names = new UriTemplate(mapping).getVariableNames(); <del> Assert.isTrue(names.size() == values.length, "The provided type-level URI template variables " + <del> Arrays.toString(values) + " do not match the template " + mapping); <del> <del> for (int i=0; i < names.size(); i++) { <del> uriVariables.put(names.get(i), values[i]); <del> } <del> } <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/MvcUrlUtils.java <del>/* <del> * Copyright 2012-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.mvc.support; <del> <del>import java.lang.reflect.Method; <del>import java.util.Set; <del> <del>import org.aopalliance.intercept.MethodInterceptor; <del>import org.apache.commons.logging.Log; <del>import org.apache.commons.logging.LogFactory; <del>import org.springframework.aop.framework.ProxyFactory; <del>import org.springframework.aop.target.EmptyTargetSource; <del>import org.springframework.cglib.proxy.Callback; <del>import org.springframework.cglib.proxy.Enhancer; <del>import org.springframework.cglib.proxy.Factory; <del>import org.springframework.cglib.proxy.MethodProxy; <del>import org.springframework.core.annotation.AnnotationUtils; <del>import org.springframework.objenesis.ObjenesisStd; <del>import org.springframework.util.Assert; <del>import org.springframework.util.ObjectUtils; <del>import org.springframework.util.ReflectionUtils; <del>import org.springframework.web.bind.annotation.RequestMapping; <del>import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition; <del>import org.springframework.web.util.UriComponents; <del> <del>/** <del> * Utility methods to support the creation URLs to Spring MVC controllers and controller <del> * methods. <del> * <del> * @author Oliver Gierke <del> * @author Rossen Stoyanchev <del> * @since 4.0 <del> */ <del>public class MvcUrlUtils { <del> <del> private static Log logger = LogFactory.getLog(MvcUrlUtils.class); <del> <del> private final static ObjenesisStd OBJENESIS = new ObjenesisStd(true); <del> <del> <del> /** <del> * Extract the type-level URL mapping or return an empty String. If multiple mappings <del> * are found, the first one is used. <del> */ <del> public static String getTypeLevelMapping(Class<?> controllerType) { <del> Assert.notNull(controllerType, "'controllerType' must not be null"); <del> RequestMapping annot = AnnotationUtils.findAnnotation(controllerType, RequestMapping.class); <del> if ((annot == null) || ObjectUtils.isEmpty(annot.value())) { <del> return "/"; <del> } <del> if (annot.value().length > 1) { <del> logger.warn("Multiple class level mappings on " + controllerType.getName() + ", using the first one"); <del> } <del> return annot.value()[0]; <del> } <del> <del> /** <del> * Extract the mapping from the given controller method, including both type and <del> * method-level mappings. If multiple mappings are found, the first one is used. <del> */ <del> public static String getMethodMapping(Method method) { <del> RequestMapping methodAnnot = AnnotationUtils.findAnnotation(method, RequestMapping.class); <del> Assert.notNull(methodAnnot, "No mappings on " + method.toGenericString()); <del> PatternsRequestCondition condition = new PatternsRequestCondition(methodAnnot.value()); <del> <del> RequestMapping typeAnnot = AnnotationUtils.findAnnotation(method.getDeclaringClass(), RequestMapping.class); <del> if (typeAnnot != null) { <del> condition = new PatternsRequestCondition(typeAnnot.value()).combine(condition); <del> } <del> <del> Set<String> patterns = condition.getPatterns(); <del> if (patterns.size() > 1) { <del> logger.warn("Multiple mappings on " + method.toGenericString() + ", using the first one"); <del> } <del> <del> return (patterns.size() == 0) ? "/" : patterns.iterator().next(); <del> } <del> <del> /** <del> * Return a "mock" controller instance. When a controller method is invoked, the <del> * invoked method and argument values are remembered, and a "mock" value is returned <del> * so it can be used to help prepare a {@link UriComponents} through <del> * {@link MvcUrls#linkToMethodOn(Object)}. <del> * @param controllerType the type of controller to mock, must not be {@literal null}. <del> * @param typeLevelUriVariables URI variables to expand into the type-level mapping <del> * @return the created controller instance <del> */ <del> public static <T> T controller(Class<T> controllerType, Object... typeLevelUriVariables) { <del> Assert.notNull(controllerType, "'type' must not be null"); <del> return initProxy(controllerType, new ControllerMethodInvocationInterceptor(typeLevelUriVariables)); <del> } <del> <del> @SuppressWarnings("unchecked") <del> private static <T> T initProxy(Class<?> type, ControllerMethodInvocationInterceptor interceptor) { <del> if (type.isInterface()) { <del> ProxyFactory factory = new ProxyFactory(EmptyTargetSource.INSTANCE); <del> factory.addInterface(type); <del> factory.addInterface(ControllerMethodValues.class); <del> factory.addAdvice(interceptor); <del> return (T) factory.getProxy(); <del> } <del> else { <del> Enhancer enhancer = new Enhancer(); <del> enhancer.setSuperclass(type); <del> enhancer.setInterfaces(new Class<?>[] { ControllerMethodValues.class }); <del> enhancer.setCallbackType(org.springframework.cglib.proxy.MethodInterceptor.class); <del> <del> Factory factory = (Factory) OBJENESIS.newInstance(enhancer.createClass()); <del> factory.setCallbacks(new Callback[] { interceptor }); <del> return (T) factory; <del> } <del> } <del> <del> <del> private static class ControllerMethodInvocationInterceptor <del> implements org.springframework.cglib.proxy.MethodInterceptor, MethodInterceptor { <del> <del> private static final Method getTypeLevelUriVariables = <del> ReflectionUtils.findMethod(ControllerMethodValues.class, "getTypeLevelUriVariables"); <del> <del> private static final Method getControllerMethod = <del> ReflectionUtils.findMethod(ControllerMethodValues.class, "getControllerMethod"); <del> <del> private static final Method getArgumentValues = <del> ReflectionUtils.findMethod(ControllerMethodValues.class, "getArgumentValues"); <del> <del> <del> private final Object[] typeLevelUriVariables; <del> <del> private Method controllerMethod; <del> <del> private Object[] argumentValues; <del> <del> <del> public ControllerMethodInvocationInterceptor(Object... typeLevelUriVariables) { <del> this.typeLevelUriVariables = typeLevelUriVariables.clone(); <del> } <del> <del> <del> @Override <del> public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) { <del> <del> if (getTypeLevelUriVariables.equals(method)) { <del> return this.typeLevelUriVariables; <del> } <del> else if (getControllerMethod.equals(method)) { <del> return this.controllerMethod; <del> } <del> else if (getArgumentValues.equals(method)) { <del> return this.argumentValues; <del> } <del> else if (ReflectionUtils.isObjectMethod(method)) { <del> return ReflectionUtils.invokeMethod(method, obj, args); <del> } <del> else { <del> this.controllerMethod = method; <del> this.argumentValues = args; <del> <del> Class<?> returnType = method.getReturnType(); <del> return void.class.equals(returnType) ? null : returnType.cast(initProxy(returnType, this)); <del> } <del> } <del> <del> @Override <del> public Object invoke(org.aopalliance.intercept.MethodInvocation inv) throws Throwable { <del> return intercept(inv.getThis(), inv.getMethod(), inv.getArguments(), null); <del> } <del> } <del> <del> /** <del> * Provides information about a controller method that can be used to prepare a URL <del> * including type-level URI template variables, a method reference, and argument <del> * values collected through the invocation of a "mock" controller. <del> * <p> <del> * Instances of this interface are returned from <del> * {@link MvcUrlUtils#controller(Class, Object...) controller(Class, Object...)} and <del> * are needed for {@link MvcUrls#linkToMethodOn(Object)}. <del> */ <del> public interface ControllerMethodValues { <del> <del> Object[] getTypeLevelUriVariables(); <del> <del> Method getControllerMethod(); <del> <del> Object[] getArgumentValues(); <del> <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/support/MvcUrls.java <del>/* <del> * Copyright 2002-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.mvc.support; <del> <del>import java.lang.reflect.Method; <del> <del>import org.springframework.web.bind.annotation.PathVariable; <del>import org.springframework.web.bind.annotation.RequestParam; <del>import org.springframework.web.method.support.UriComponentsContributor; <del>import org.springframework.web.servlet.config.DefaultMvcUrlsFactoryBean; <del>import org.springframework.web.util.UriComponents; <del>import org.springframework.web.util.UriComponentsBuilder; <del> <del>/** <del> * A contract for creating URLs by referencing Spring MVC controllers and methods. <del> * <del> * <p>The MVC Java config and the MVC namespace automatically create an instance of this <del> * contract for use in controllers and anywhere else during the processing of a request. <del> * The best way for access it is to have it autowired, or otherwise injected either by <del> * type or also qualified by name ("mvcUrls") if necessary. <del> * <del> * <p>If not using either option, with explicit configuration it's easy to create an <del> * instance of {@link DefaultMvcUrls} in Java config or in XML configuration, use <del> * {@link DefaultMvcUrlsFactoryBean}. <del> * <del> * @author Oliver Gierke <del> * @author Rossen Stoyanchev <del> * @since 4.0 <del> */ <del>public interface MvcUrls { <del> <del> /** <del> * Creates a new {@link UriComponentsBuilder} by pointing to a controller class. The <del> * resulting builder contains all the current request information up to and including <del> * the Servlet mapping as well as the portion of the path matching to the controller <del> * level request mapping. If the controller contains multiple mappings, the <del> * {@link DefaultMvcUrls} will use the first one. <del> * @param controllerType the controller type to create a URL to <del> * @return a builder that can be used to further build the {@link UriComponents}. <del> */ <del> UriComponentsBuilder linkToController(Class<?> controllerType); <del> <del> /** <del> * Create a {@link UriComponents} by pointing to a controller method along with method <del> * argument values. <del> * <del> * <p>Type and method-level mappings of the controller method are extracted and the <del> * resulting {@link UriComponents} is further enriched with method argument values from <del> * {@link PathVariable} and {@link RequestParam} parameters. Any other arguments not <del> * relevant to the building of the URL can be provided as {@literal null} and will be <del> * ignored. Support for additional custom arguments can be added through a <del> * {@link UriComponentsContributor}. <del> * @param method the target controller method <del> * @param argumentValues argument values matching to method parameters <del> * @return UriComponents instance, never {@literal null} <del> */ <del> UriComponents linkToMethod(Method method, Object... argumentValues); <del> <del> /** <del> * Create a {@link UriComponents} by invoking a method on a "mock" controller similar <del> * to how test frameworks provide mock objects and record method invocations. The <del> * static method {@link MvcUrlUtils#controller(Class, Object...)} can be used to <del> * create a "mock" controller: <del> * <del> * <pre class="code"> <del> * &#064;RequestMapping("/people/{id}/addresses") <del> * class AddressController { <del> * <del> * &#064;RequestMapping("/{country}") <del> * public HttpEntity&lt;Void&gt; getAddressesForCountry(&#064;PathVariable String country) { ... } <del> * <del> * &#064;RequestMapping(value="/", method=RequestMethod.POST) <del> * public void addAddress(Address address) { ... } <del> * } <del> * <del> * // short-hand style with static import of MvcUrlUtils.controller <del> * <del> * mvcUrls.linkToMethodOn(controller(CustomerController.class, 1).showAddresses("US")); <del> * <del> * // longer style, required for void controller methods <del> * <del> * CustomerController controller = MvcUrlUtils.controller(CustomController.class, 1); <del> * controller.addAddress(null); <del> * <del> * mvcUrls.linkToMethodOn(controller); <del> * </pre> <del> * <del> * The above mechanism supports {@link PathVariable} and {@link RequestParam} method <del> * arguments. Any other arguments can be provided as {@literal null} and will be <del> * ignored. Additional custom arguments can be added through an implementation of <del> * {@link UriComponentsContributor}. <del> * @param mockController created via {@link MvcUrlUtils#controller(Class, Object...)} <del> * @return UriComponents instance, never {@literal null} <del> */ <del> UriComponents linkToMethodOn(Object mockController); <del> <del>} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/MvcNamespaceTests.java <ide> import java.lang.annotation.Retention; <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.reflect.Method; <del>import java.text.DateFormat; <del>import java.text.SimpleDateFormat; <ide> import java.util.Arrays; <ide> import java.util.Date; <ide> import java.util.List; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> import org.springframework.web.context.request.NativeWebRequest; <del>import org.springframework.web.context.request.RequestContextHolder; <del>import org.springframework.web.context.request.ServletRequestAttributes; <ide> import org.springframework.web.context.request.ServletWebRequest; <ide> import org.springframework.web.context.request.async.CallableProcessingInterceptor; <ide> import org.springframework.web.context.request.async.CallableProcessingInterceptorAdapter; <ide> import org.springframework.web.context.request.async.DeferredResultProcessingInterceptor; <ide> import org.springframework.web.context.request.async.DeferredResultProcessingInterceptorAdapter; <ide> import org.springframework.web.context.support.GenericWebApplicationContext; <ide> import org.springframework.web.method.HandlerMethod; <add>import org.springframework.web.method.support.CompositeUriComponentsContributor; <ide> import org.springframework.web.method.support.InvocableHandlerMethod; <ide> import org.springframework.web.servlet.HandlerExecutionChain; <ide> import org.springframework.web.servlet.HandlerInterceptor; <ide> import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <del>import org.springframework.web.servlet.mvc.support.MvcUrls; <add>import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; <ide> import org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler; <ide> import org.springframework.web.servlet.resource.ResourceHttpRequestHandler; <ide> import org.springframework.web.servlet.theme.ThemeChangeInterceptor; <del>import org.springframework.web.util.UriComponents; <ide> <ide> import static org.junit.Assert.*; <del>import static org.springframework.web.servlet.mvc.support.MvcUrlUtils.*; <ide> <ide> /** <ide> * @author Keith Donald <ide> public void testDefaultConfig() throws Exception { <ide> adapter.handle(request, response, handlerMethod); <ide> assertTrue(handler.recordedValidationError); <ide> <del> // MvcUrls <del> RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest())); <del> try { <del> Date now = new Date(); <del> TestController testController = controller(TestController.class); <del> testController.testBind(now, null, null); <del> MvcUrls mvcUrls = this.appContext.getBean(MvcUrls.class); <del> UriComponents uriComponents = mvcUrls.linkToMethodOn(testController); <del> DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); <del> assertEquals("http://localhost/?date=" + dateFormat.format(now), uriComponents.toUriString()); <del> } <del> finally { <del> RequestContextHolder.resetRequestAttributes(); <del> } <add> CompositeUriComponentsContributor uriComponentsContributor = this.appContext.getBean( <add> MvcUriComponentsBuilder.MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, <add> CompositeUriComponentsContributor.class); <add> <add> assertNotNull(uriComponentsContributor); <ide> } <ide> <ide> @Test(expected=TypeMismatchException.class) <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java <ide> import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.joda.time.DateTime; <del>import org.joda.time.format.ISODateTimeFormat; <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.support.ConfigurableWebBindingInitializer; <ide> import org.springframework.web.context.WebApplicationContext; <del>import org.springframework.web.context.request.RequestContextHolder; <del>import org.springframework.web.context.request.ServletRequestAttributes; <ide> import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; <add>import org.springframework.web.method.support.CompositeUriComponentsContributor; <ide> import org.springframework.web.servlet.HandlerExceptionResolver; <ide> import org.springframework.web.servlet.HandlerExecutionChain; <ide> import org.springframework.web.servlet.handler.AbstractHandlerMapping; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <ide> import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; <del>import org.springframework.web.servlet.mvc.support.MvcUrls; <del>import org.springframework.web.util.UriComponents; <add>import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; <ide> <ide> import static org.junit.Assert.*; <del>import static org.springframework.web.servlet.mvc.support.MvcUrlUtils.*; <ide> <ide> /** <ide> * A test fixture with an {@link WebMvcConfigurationSupport} instance. <ide> public void requestMappingHandlerAdapter() throws Exception { <ide> } <ide> <ide> @Test <del> public void mvcUrls() throws Exception { <del> RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest())); <del> try { <del> DateTime now = DateTime.now(); <del> MvcUrls mvcUrls = this.wac.getBean(MvcUrls.class); <del> UriComponents uriComponents = mvcUrls.linkToMethodOn(controller( <del> TestController.class).methodWithTwoPathVariables(1, now)); <del> <del> assertEquals("/foo/1/bar/" + ISODateTimeFormat.date().print(now), uriComponents.getPath()); <del> } <del> finally { <del> RequestContextHolder.resetRequestAttributes(); <del> } <add> public void uriComponentsContributor() throws Exception { <add> <add> CompositeUriComponentsContributor uriComponentsContributor = this.wac.getBean( <add> MvcUriComponentsBuilder.MVC_URI_COMPONENTS_CONTRIBUTOR_BEAN_NAME, <add> CompositeUriComponentsContributor.class); <add> <add> assertNotNull(uriComponentsContributor); <ide> } <ide> <ide> @Test <add><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsContributorTests.java <del><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/DefaultMvcUrlsTests.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.servlet.mvc.support; <del> <del>import java.lang.reflect.Method; <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.List; <add>package org.springframework.web.servlet.mvc.method.annotation; <ide> <ide> import org.hamcrest.Matchers; <ide> import org.joda.time.DateTime; <ide> import org.springframework.web.bind.annotation.RequestParam; <ide> import org.springframework.web.context.request.RequestContextHolder; <ide> import org.springframework.web.context.request.ServletRequestAttributes; <del>import org.springframework.web.method.annotation.RequestParamMethodArgumentResolver; <del>import org.springframework.web.method.support.HandlerMethodArgumentResolver; <del>import org.springframework.web.servlet.mvc.method.annotation.PathVariableMethodArgumentResolver; <add>import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; <ide> import org.springframework.web.util.UriComponents; <ide> <add>import java.util.Arrays; <add>import java.util.List; <add> <ide> import static org.hamcrest.Matchers.*; <del>import static org.junit.Assert.*; <del>import static org.springframework.web.servlet.mvc.support.MvcUrlUtils.*; <add>import static org.junit.Assert.assertThat; <add>import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.mock; <ide> <ide> /** <del> * Unit tests for {@link DefaultMvcUrls}. <add> * Unit tests for {@link org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder}. <ide> * <ide> * @author Oliver Gierke <ide> * @author Dietrich Schulten <ide> * @author Rossen Stoyanchev <ide> */ <del>public class DefaultMvcUrlsTests { <add>public class MvcUriComponentsContributorTests { <ide> <ide> private MockHttpServletRequest request; <ide> <del> private MvcUrls mvcUrls; <add> private MvcUriComponentsBuilder builder; <ide> <ide> <ide> @Before <ide> public void setUp() { <ide> this.request = new MockHttpServletRequest(); <del> ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); <del> RequestContextHolder.setRequestAttributes(requestAttributes); <del> <del> List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(); <del> resolvers.add(new PathVariableMethodArgumentResolver()); <del> resolvers.add(new RequestParamMethodArgumentResolver(null, false)); <del> <del> this.mvcUrls = new DefaultMvcUrls(resolvers, null); <add> RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(this.request)); <ide> } <ide> <ide> @After <del> public void teardown() { <add> public void tearDown() { <ide> RequestContextHolder.resetRequestAttributes(); <ide> } <ide> <ide> <ide> @Test <del> public void linkToControllerRoot() { <del> UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build(); <add> public void fromController() { <add> UriComponents uriComponents = this.builder.fromController(PersonControllerImpl.class).build(); <ide> assertThat(uriComponents.toUriString(), Matchers.endsWith("/people")); <ide> } <ide> <ide> @Test <del> public void linkToParameterizedControllerRoot() { <del> UriComponents uriComponents = this.mvcUrls.linkToController( <del> PersonsAddressesController.class).buildAndExpand(15); <del> <add> public void fromControllerUriTemplate() { <add> UriComponents uriComponents = this.builder.fromController(PersonsAddressesController.class).buildAndExpand(15); <ide> assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses")); <ide> } <ide> <ide> @Test <del> public void linkToMethodOnParameterizedControllerRoot() { <del> UriComponents uriComponents = this.mvcUrls.linkToMethodOn( <del> controller(PersonsAddressesController.class, 15).getAddressesForCountry("DE")); <del> <del> assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses/DE")); <del> } <del> <del> @Test <del> public void linkToSubResource() { <add> public void fromControllerSubResource() { <ide> UriComponents uriComponents = <del> this.mvcUrls.linkToController(PersonControllerImpl.class).pathSegment("something").build(); <add> this.builder.fromController(PersonControllerImpl.class).pathSegment("something").build(); <ide> <ide> assertThat(uriComponents.toUriString(), endsWith("/people/something")); <ide> } <ide> <ide> @Test <del> public void linkToControllerWithMultipleMappings() { <del> UriComponents uriComponents = this.mvcUrls.linkToController(InvalidController.class).build(); <add> public void fromControllerTwoTypeLevelMappings() { <add> UriComponents uriComponents = this.builder.fromController(InvalidController.class).build(); <ide> assertThat(uriComponents.toUriString(), is("http://localhost/persons")); <ide> } <ide> <ide> @Test <del> public void linkToControllerNotMapped() { <del> UriComponents uriComponents = this.mvcUrls.linkToController(UnmappedController.class).build(); <add> public void fromControllerNotMapped() { <add> UriComponents uriComponents = this.builder.fromController(UnmappedController.class).build(); <ide> assertThat(uriComponents.toUriString(), is("http://localhost/")); <ide> } <ide> <ide> @Test <del> public void linkToMethodRefWithPathVar() throws Exception { <del> Method method = ControllerWithMethods.class.getDeclaredMethod("methodWithPathVariable", String.class); <del> UriComponents uriComponents = this.mvcUrls.linkToMethod(method, new Object[] { "1" }); <add> public void fromMethodPathVariable() throws Exception { <add> UriComponents uriComponents = this.builder.fromMethodName( <add> ControllerWithMethods.class, "methodWithPathVariable", new Object[]{"1"}).build(); <ide> <ide> assertThat(uriComponents.toUriString(), is("http://localhost/something/1/foo")); <ide> } <ide> <ide> @Test <del> public void linkToMethodRefWithTwoPathVars() throws Exception { <add> public void fromMethodTypeLevelPathVariable() throws Exception { <add> this.request.setContextPath("/myapp"); <add> UriComponents uriComponents = this.builder.fromMethodName( <add> PersonsAddressesController.class, "getAddressesForCountry", "DE").buildAndExpand("1"); <add> <add> assertThat(uriComponents.toUriString(), is("http://localhost/myapp/people/1/addresses/DE")); <add> } <add> <add> @Test <add> public void fromMethodTwoPathVariables() throws Exception { <ide> DateTime now = DateTime.now(); <del> Method method = ControllerWithMethods.class.getDeclaredMethod( <del> "methodWithTwoPathVariables", Integer.class, DateTime.class); <del> UriComponents uriComponents = this.mvcUrls.linkToMethod(method, new Object[] { 1, now }); <add> UriComponents uriComponents = this.builder.fromMethodName( <add> ControllerWithMethods.class, "methodWithTwoPathVariables", 1, now).build(); <ide> <ide> assertThat(uriComponents.getPath(), is("/something/1/foo/" + ISODateTimeFormat.date().print(now))); <ide> } <ide> <ide> @Test <del> public void linkToMethodRefWithPathVarAndRequestParam() throws Exception { <del> Method method = ControllerWithMethods.class.getDeclaredMethod("methodForNextPage", String.class, Integer.class, Integer.class); <del> UriComponents uriComponents = this.mvcUrls.linkToMethod(method, new Object[] {"1", 10, 5}); <add> public void fromMethodWithPathVarAndRequestParam() throws Exception { <add> UriComponents uriComponents = this.builder.fromMethodName( <add> ControllerWithMethods.class, "methodForNextPage", "1", 10, 5).build(); <ide> <ide> assertThat(uriComponents.getPath(), is("/something/1/foo")); <del> <ide> MultiValueMap<String, String> queryParams = uriComponents.getQueryParams(); <ide> assertThat(queryParams.get("limit"), contains("5")); <ide> assertThat(queryParams.get("offset"), contains("10")); <ide> } <ide> <ide> @Test <del> public void linkToMethod() { <del> UriComponents uriComponents = this.mvcUrls.linkToMethodOn( <del> controller(ControllerWithMethods.class).myMethod(null)); <add> public void fromMethodNotMapped() throws Exception { <add> UriComponents uriComponents = this.builder.fromMethodName(UnmappedController.class, "unmappedMethod").build(); <add> <add> assertThat(uriComponents.toUriString(), is("http://localhost/")); <add> } <add> <add> @Test <add> public void fromLastCall() { <add> UriComponents uriComponents = this.builder.fromLastCall( <add> mock(ControllerWithMethods.class).myMethod(null)).build(); <ide> <ide> assertThat(uriComponents.toUriString(), startsWith("http://localhost")); <ide> assertThat(uriComponents.toUriString(), endsWith("/something/else")); <ide> } <ide> <ide> @Test <del> public void linkToMethodWithPathVar() { <del> UriComponents uriComponents = this.mvcUrls.linkToMethodOn( <del> controller(ControllerWithMethods.class).methodWithPathVariable("1")); <add> public void fromLastCallWithTypeLevelUriVars() { <add> UriComponents uriComponents = this.builder.fromLastCall( <add> mock(PersonsAddressesController.class).getAddressesForCountry("DE")).buildAndExpand(15); <add> <add> assertThat(uriComponents.toUriString(), endsWith("/people/15/addresses/DE")); <add> } <add> <add> <add> @Test <add> public void fromLastCallWithPathVar() { <add> UriComponents uriComponents = this.builder.fromLastCall( <add> mock(ControllerWithMethods.class).methodWithPathVariable("1")).build(); <ide> <ide> assertThat(uriComponents.toUriString(), startsWith("http://localhost")); <ide> assertThat(uriComponents.toUriString(), endsWith("/something/1/foo")); <ide> } <ide> <ide> @Test <del> public void linkToMethodWithPathVarAndRequestParams() { <del> UriComponents uriComponents = this.mvcUrls.linkToMethodOn( <del> controller(ControllerWithMethods.class).methodForNextPage("1", 10, 5)); <add> public void fromLastCallWithPathVarAndRequestParams() { <add> UriComponents uriComponents = this.builder.fromLastCall( <add> mock(ControllerWithMethods.class).methodForNextPage("1", 10, 5)).build(); <ide> <ide> assertThat(uriComponents.getPath(), is("/something/1/foo")); <ide> <ide> public void linkToMethodWithPathVarAndRequestParams() { <ide> } <ide> <ide> @Test <del> public void linkToMethodWithPathVarAndMultiValueRequestParams() { <del> UriComponents uriComponents = this.mvcUrls.linkToMethodOn( <del> controller(ControllerWithMethods.class).methodWithMultiValueRequestParams( <del> "1", Arrays.asList(3, 7), 5)); <add> public void fromLastCallWithPathVarAndMultiValueRequestParams() { <add> UriComponents uriComponents = this.builder.fromLastCall( <add> mock(ControllerWithMethods.class).methodWithMultiValueRequestParams( <add> "1", Arrays.asList(3, 7), 5)).build(); <ide> <ide> assertThat(uriComponents.getPath(), is("/something/1/foo")); <ide> <ide> public void linkToMethodWithPathVarAndMultiValueRequestParams() { <ide> @Test <ide> public void usesForwardedHostAsHostIfHeaderIsSet() { <ide> this.request.addHeader("X-Forwarded-Host", "somethingDifferent"); <del> UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build(); <add> UriComponents uriComponents = this.builder.fromController(PersonControllerImpl.class).build(); <ide> <ide> assertThat(uriComponents.toUriString(), startsWith("http://somethingDifferent")); <ide> } <ide> <ide> @Test <ide> public void usesForwardedHostAndPortFromHeader() { <ide> request.addHeader("X-Forwarded-Host", "foobar:8088"); <del> UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build(); <add> UriComponents uriComponents = this.builder.fromController(PersonControllerImpl.class).build(); <ide> <ide> assertThat(uriComponents.toUriString(), startsWith("http://foobar:8088")); <ide> } <ide> <ide> @Test <ide> public void usesFirstHostOfXForwardedHost() { <ide> request.addHeader("X-Forwarded-Host", "barfoo:8888, localhost:8088"); <del> UriComponents uriComponents = this.mvcUrls.linkToController(PersonControllerImpl.class).build(); <add> UriComponents uriComponents = this.builder.fromController(PersonControllerImpl.class).build(); <ide> <ide> assertThat(uriComponents.toUriString(), startsWith("http://barfoo:8888")); <ide> } <ide> class InvalidController { <ide> <ide> class UnmappedController { <ide> <add> @RequestMapping <add> public void unmappedMethod() { <add> } <ide> } <ide> <ide> @RequestMapping("/something") <ide> HttpEntity<Void> methodWithMultiValueRequestParams(@PathVariable String id, <ide> return null; <ide> } <ide> } <add> <add> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/support/MvcUrlUtilsTests.java <del>/* <del> * Copyright 2012-2013 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.mvc.support; <del> <del>import java.lang.reflect.Method; <del> <del>import org.junit.After; <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.springframework.http.HttpEntity; <del>import org.springframework.http.HttpStatus; <del>import org.springframework.http.ResponseEntity; <del>import org.springframework.mock.web.test.MockHttpServletRequest; <del>import org.springframework.web.bind.annotation.PathVariable; <del>import org.springframework.web.bind.annotation.RequestMapping; <del>import org.springframework.web.context.request.RequestContextHolder; <del>import org.springframework.web.context.request.ServletRequestAttributes; <del>import org.springframework.web.servlet.mvc.support.MvcUrlUtils.ControllerMethodValues; <del> <del>import static org.hamcrest.CoreMatchers.*; <del>import static org.junit.Assert.*; <del> <del>/** <del> * Test fixture for {@link MvcUrlUtils}. <del> * <del> * @author Oliver Gierke <del> * @author Rossen Stoyanchev <del> */ <del>public class MvcUrlUtilsTests { <del> <del> private MockHttpServletRequest request; <del> <del> <del> @Before <del> public void setUp() { <del> this.request = new MockHttpServletRequest(); <del> ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request); <del> RequestContextHolder.setRequestAttributes(requestAttributes); <del> } <del> <del> @After <del> public void teardown() { <del> RequestContextHolder.resetRequestAttributes(); <del> } <del> <del> @Test <del> public void methodOn() { <del> HttpEntity<Void> result = MvcUrlUtils.controller(SampleController.class).someMethod(1L); <del> <del> assertTrue(result instanceof ControllerMethodValues); <del> assertEquals("someMethod", ((ControllerMethodValues) result).getControllerMethod().getName()); <del> } <del> <del> @Test <del> public void typeLevelMapping() { <del> assertThat(MvcUrlUtils.getTypeLevelMapping(MyController.class), is("/type")); <del> } <del> <del> @Test <del> public void typeLevelMappingNone() { <del> assertThat(MvcUrlUtils.getTypeLevelMapping(ControllerWithoutTypeLevelMapping.class), is("/")); <del> } <del> <del> @Test <del> public void methodLevelMapping() throws Exception { <del> Method method = MyController.class.getMethod("method"); <del> assertThat(MvcUrlUtils.getMethodMapping(method), is("/type/method")); <del> } <del> <del> @Test <del> public void methodLevelMappingWithoutTypeLevelMapping() throws Exception { <del> Method method = ControllerWithoutTypeLevelMapping.class.getMethod("method"); <del> assertThat(MvcUrlUtils.getMethodMapping(method), is("/method")); <del> } <del> <del> @Test <del> public void methodMappingWithControllerMappingOnly() throws Exception { <del> Method method = MyController.class.getMethod("noMethodMapping"); <del> assertThat(MvcUrlUtils.getMethodMapping(method), is("/type")); <del> } <del> <del> <del> @RequestMapping("/sample") <del> static class SampleController { <del> <del> @RequestMapping("/{id}/foo") <del> HttpEntity<Void> someMethod(@PathVariable("id") Long id) { <del> return new ResponseEntity<Void>(HttpStatus.OK); <del> } <del> } <del> <del> @RequestMapping("/type") <del> interface MyController { <del> <del> @RequestMapping("/method") <del> void method(); <del> <del> @RequestMapping <del> void noMethodMapping(); <del> } <del> <del> interface ControllerWithoutTypeLevelMapping { <del> <del> @RequestMapping("/method") <del> void method(); <del> } <del> <del>}
13
Javascript
Javascript
use beforerun hook for handle 0
fe1350a7a2c6fc552d8d8f7e203b1366483966e0
<ide><path>lib/ProgressPlugin.js <ide> const median3 = (a, b, c) => { <ide> }; <ide> <ide> const createDefaultHandler = (profile, logger) => { <del> let wasLogged = false; <ide> /** @type {{ value: string, time: number }[]} */ <ide> const lastStateInfo = []; <ide> <ide> const createDefaultHandler = (profile, logger) => { <ide> } <ide> } <ide> } <del> if (percentage === 0 && !wasLogged) { <del> wasLogged = true; <del> return; <del> } <ide> logger.status(`${Math.floor(percentage * 100)}%`, msg, ...args); <ide> if (percentage === 1 || (!msg && args.length === 0)) logger.status(); <ide> }; <ide> class ProgressPlugin { <ide> } <ide> }); <ide> interceptHook(compiler.cache.hooks.endIdle, 0.01, "cache", "end idle"); <del> compiler.hooks.initialize.intercept({ <add> compiler.hooks.beforeRun.intercept({ <ide> name: "ProgressPlugin", <ide> call() { <ide> handler(0, "");
1
Ruby
Ruby
move lmutil to homebrew-binary
4ed9efd99520f96a2db03e9ce861a41e64f16633
<ide><path>Library/Homebrew/tap_migrations.rb <ide> 'boost149' => 'homebrew/versions', <ide> 'aimage' => 'homebrew/boneyard', <ide> 'cmucl' => 'homebrew/binary', <add> 'lmutil' => 'homebrew/binary', <ide> }
1
Go
Go
add support for swarm mode templating
6212ea669b4e92b3aa3985857f827ee9b95271fd
<ide><path>daemon/cluster/executor/container/container.go <ide> import ( <ide> "github.com/docker/swarmkit/agent/exec" <ide> "github.com/docker/swarmkit/api" <ide> "github.com/docker/swarmkit/protobuf/ptypes" <add> "github.com/docker/swarmkit/template" <ide> ) <ide> <ide> const ( <ide> func (c *containerConfig) setTask(t *api.Task) error { <ide> } <ide> <ide> c.task = t <add> <add> if t.Spec.GetContainer() != nil { <add> preparedSpec, err := template.ExpandContainerSpec(t) <add> if err != nil { <add> return err <add> } <add> c.task.Spec.Runtime = &api.TaskSpec_Container{ <add> Container: preparedSpec, <add> } <add> } <add> <ide> return nil <ide> } <ide> <ide><path>integration-cli/docker_cli_swarm_test.go <ide> func (s *DockerSwarmSuite) TestSwarmNodeListHostname(c *check.C) { <ide> c.Assert(strings.Split(out, "\n")[0], checker.Contains, "HOSTNAME") <ide> } <ide> <add>func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *check.C) { <add> d := s.AddDaemon(c, true, true) <add> <add> out, err := d.Cmd("service", "create", "--name", "test", "--hostname", "{{.Service.Name}}-{{.Task.Slot}}", "busybox", "top") <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> <add> // make sure task has been deployed. <add> waitAndAssert(c, defaultReconciliationTimeout, d.checkActiveContainerCount, checker.Equals, 1) <add> <add> containers := d.activeContainers() <add> out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.Hostname}}", containers[0]) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <add> c.Assert(strings.Split(out, "\n")[0], checker.Equals, "test-1", check.Commentf("hostname with templating invalid")) <add>} <add> <ide> // Test case for #24270 <ide> func (s *DockerSwarmSuite) TestSwarmServiceListFilter(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide> func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *check.C) { <ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <ide> <ide> out, err = d.Cmd("run", "-id", "--restart=always", "--net=foo", "--name=test", "busybox", "top") <del> c.Assert(err, checker.IsNil) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <ide> <ide> out, err = d.Cmd("ps", "-q") <del> c.Assert(err, checker.IsNil) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <ide> <ide> d.Restart() <ide> <ide> out, err = d.Cmd("ps", "-q") <del> c.Assert(err, checker.IsNil) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestSwarmContainerEndpointOptions(c *check.C) { <ide> d := s.AddDaemon(c, true, true) <ide> <ide> out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo") <del> c.Assert(err, checker.IsNil) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") <ide> <ide> _, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox", "top") <del> c.Assert(err, checker.IsNil) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> <ide> _, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox", "top") <del> c.Assert(err, checker.IsNil) <add> c.Assert(err, checker.IsNil, check.Commentf(out)) <ide> <ide> // ping first container and its alias <ide> _, err = d.Cmd("exec", "second", "ping", "-c", "1", "first") <del> c.Assert(err, check.IsNil) <add> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> _, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias") <del> c.Assert(err, check.IsNil) <add> c.Assert(err, check.IsNil, check.Commentf(out)) <ide> } <ide> <ide> func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *check.C) { <ide><path>vendor/github.com/docker/swarmkit/manager/controlapi/service.go <ide> import ( <ide> "github.com/docker/swarmkit/manager/constraint" <ide> "github.com/docker/swarmkit/manager/state/store" <ide> "github.com/docker/swarmkit/protobuf/ptypes" <add> "github.com/docker/swarmkit/template" <ide> "golang.org/x/net/context" <ide> "google.golang.org/grpc" <ide> "google.golang.org/grpc/codes" <ide> func validateTask(taskSpec api.TaskSpec) error { <ide> return grpc.Errorf(codes.Unimplemented, "RuntimeSpec: unimplemented runtime in service spec") <ide> } <ide> <del> if err := validateContainerSpec(taskSpec.GetContainer()); err != nil { <add> // Building a empty/dummy Task to validate the templating and <add> // the resulting container spec as well. This is a *best effort* <add> // validation. <add> preparedSpec, err := template.ExpandContainerSpec(&api.Task{ <add> Spec: taskSpec, <add> ServiceID: "serviceid", <add> Slot: 1, <add> NodeID: "nodeid", <add> Networks: []*api.NetworkAttachment{}, <add> Annotations: api.Annotations{ <add> Name: "taskname", <add> }, <add> ServiceAnnotations: api.Annotations{ <add> Name: "servicename", <add> }, <add> Endpoint: &api.Endpoint{}, <add> LogDriver: taskSpec.LogDriver, <add> }) <add> if err != nil { <add> return grpc.Errorf(codes.InvalidArgument, err.Error()) <add> } <add> if err := validateContainerSpec(preparedSpec); err != nil { <ide> return err <ide> } <ide> <ide><path>vendor/github.com/docker/swarmkit/template/context.go <add>package template <add> <add>import ( <add> "bytes" <add> "fmt" <add> <add> "github.com/docker/swarmkit/api" <add> "github.com/docker/swarmkit/api/naming" <add>) <add> <add>// Context defines the strict set of values that can be injected into a <add>// template expression in SwarmKit data structure. <add>type Context struct { <add> Service struct { <add> ID string <add> Name string <add> Labels map[string]string <add> } <add> <add> Node struct { <add> ID string <add> } <add> <add> Task struct { <add> ID string <add> Name string <add> Slot string <add> <add> // NOTE(stevvooe): Why no labels here? Tasks don't actually have labels <add> // (from a user perspective). The labels are part of the container! If <add> // one wants to use labels for templating, use service labels! <add> } <add>} <add> <add>// NewContextFromTask returns a new template context from the data available in <add>// task. The provided context can then be used to populate runtime values in a <add>// ContainerSpec. <add>func NewContextFromTask(t *api.Task) (ctx Context) { <add> ctx.Service.ID = t.ServiceID <add> ctx.Service.Name = t.ServiceAnnotations.Name <add> ctx.Service.Labels = t.ServiceAnnotations.Labels <add> <add> ctx.Node.ID = t.NodeID <add> <add> ctx.Task.ID = t.ID <add> ctx.Task.Name = naming.Task(t) <add> <add> if t.Slot != 0 { <add> ctx.Task.Slot = fmt.Sprint(t.Slot) <add> } else { <add> // fall back to node id for slot when there is no slot <add> ctx.Task.Slot = t.NodeID <add> } <add> <add> return <add>} <add> <add>// Expand treats the string s as a template and populates it with values from <add>// the context. <add>func (ctx *Context) Expand(s string) (string, error) { <add> tmpl, err := newTemplate(s) <add> if err != nil { <add> return s, err <add> } <add> <add> var buf bytes.Buffer <add> if err := tmpl.Execute(&buf, ctx); err != nil { <add> return s, err <add> } <add> <add> return buf.String(), nil <add>} <ide><path>vendor/github.com/docker/swarmkit/template/expand.go <add>package template <add> <add>import ( <add> "fmt" <add> "strings" <add> <add> "github.com/docker/swarmkit/api" <add> "github.com/pkg/errors" <add>) <add> <add>// ExpandContainerSpec expands templated fields in the runtime using the task <add>// state. Templating is all evaluated on the agent-side, before execution. <add>// <add>// Note that these are projected only on runtime values, since active task <add>// values are typically manipulated in the manager. <add>func ExpandContainerSpec(t *api.Task) (*api.ContainerSpec, error) { <add> container := t.Spec.GetContainer() <add> if container == nil { <add> return nil, errors.Errorf("task missing ContainerSpec to expand") <add> } <add> <add> container = container.Copy() <add> ctx := NewContextFromTask(t) <add> <add> var err error <add> container.Env, err = expandEnv(ctx, container.Env) <add> if err != nil { <add> return container, errors.Wrap(err, "expanding env failed") <add> } <add> <add> // For now, we only allow templating of string-based mount fields <add> container.Mounts, err = expandMounts(ctx, container.Mounts) <add> if err != nil { <add> return container, errors.Wrap(err, "expanding mounts failed") <add> } <add> <add> container.Hostname, err = ctx.Expand(container.Hostname) <add> return container, errors.Wrap(err, "expanding hostname failed") <add>} <add> <add>func expandMounts(ctx Context, mounts []api.Mount) ([]api.Mount, error) { <add> if len(mounts) == 0 { <add> return mounts, nil <add> } <add> <add> expanded := make([]api.Mount, len(mounts)) <add> for i, mount := range mounts { <add> var err error <add> mount.Source, err = ctx.Expand(mount.Source) <add> if err != nil { <add> return mounts, errors.Wrapf(err, "expanding mount source %q", mount.Source) <add> } <add> <add> mount.Target, err = ctx.Expand(mount.Target) <add> if err != nil { <add> return mounts, errors.Wrapf(err, "expanding mount target %q", mount.Target) <add> } <add> <add> if mount.VolumeOptions != nil { <add> mount.VolumeOptions.Labels, err = expandMap(ctx, mount.VolumeOptions.Labels) <add> if err != nil { <add> return mounts, errors.Wrap(err, "expanding volume labels") <add> } <add> <add> if mount.VolumeOptions.DriverConfig != nil { <add> mount.VolumeOptions.DriverConfig.Options, err = expandMap(ctx, mount.VolumeOptions.DriverConfig.Options) <add> if err != nil { <add> return mounts, errors.Wrap(err, "expanding volume driver config") <add> } <add> } <add> } <add> <add> expanded[i] = mount <add> } <add> <add> return expanded, nil <add>} <add> <add>func expandMap(ctx Context, m map[string]string) (map[string]string, error) { <add> var ( <add> n = make(map[string]string, len(m)) <add> err error <add> ) <add> <add> for k, v := range m { <add> v, err = ctx.Expand(v) <add> if err != nil { <add> return m, errors.Wrapf(err, "expanding map entry %q=%q", k, v) <add> } <add> <add> n[k] = v <add> } <add> <add> return n, nil <add>} <add> <add>func expandEnv(ctx Context, values []string) ([]string, error) { <add> var result []string <add> for _, value := range values { <add> var ( <add> parts = strings.SplitN(value, "=", 2) <add> entry = parts[0] <add> ) <add> <add> if len(parts) > 1 { <add> expanded, err := ctx.Expand(parts[1]) <add> if err != nil { <add> return values, errors.Wrapf(err, "expanding env %q", value) <add> } <add> <add> entry = fmt.Sprintf("%s=%s", entry, expanded) <add> } <add> <add> result = append(result, entry) <add> } <add> <add> return result, nil <add>} <ide><path>vendor/github.com/docker/swarmkit/template/template.go <add>package template <add> <add>import ( <add> "strings" <add> "text/template" <add>) <add> <add>// funcMap defines functions for our template system. <add>var funcMap = template.FuncMap{ <add> "join": func(s ...string) string { <add> // first arg is sep, remaining args are strings to join <add> return strings.Join(s[1:], s[0]) <add> }, <add>} <add> <add>func newTemplate(s string) (*template.Template, error) { <add> return template.New("expansion").Option("missingkey=error").Funcs(funcMap).Parse(s) <add>}
6
Javascript
Javascript
change var to const in ./eslint-rules
ea67c27168ad03a89c88503ebea49efb88cabe0f
<ide><path>tools/eslint-rules/required-modules.js <ide> */ <ide> 'use strict'; <ide> <del>var path = require('path'); <add>const path = require('path'); <ide> <ide> //------------------------------------------------------------------------------ <ide> // Rule Definition <ide> module.exports = function(context) { <ide> // trim required module names <ide> var requiredModules = context.options; <ide> <del> var foundModules = []; <add> const foundModules = []; <ide> <ide> // if no modules are required we don't need to check the CallExpressions <ide> if (requiredModules.length === 0) {
1
PHP
PHP
fix style issue
a7c1bc22549c4450a6c41c638a37eb54261a573c
<ide><path>src/Illuminate/Routing/Middleware/SubstituteBindings.php <ide> public function handle($request, Closure $next) <ide> <ide> $this->router->substituteImplicitBindings($route); <ide> } catch (ModelNotFoundException $exception) { <del> if($route->getMissing()) { <add> if ($route->getMissing()) { <ide> return $route->getMissing()($request); <ide> } <ide>
1
PHP
PHP
fix method visibility
43e44f50a931f02ccab063acf2ad4e433af9f9d6
<ide><path>src/Controller/Component/AuthComponent.php <ide> public function startup(Event $event) <ide> * @param \Cake\Event\Event $event Event instance. <ide> * @return void|\Cake\Network\Response <ide> */ <del> public function _authCheck(Event $event) <add> protected function _authCheck(Event $event) <ide> { <ide> $controller = $event->subject(); <ide> <ide><path>tests/test_app/TestApp/Controller/Component/TestAuthComponent.php <ide> */ <ide> class TestAuthComponent extends AuthComponent <ide> { <del> public function _authCheck(Event $event) <add> protected function _authCheck(Event $event) <ide> { <ide> if (isset($this->earlyAuthTest)) { <ide> $this->authCheckCalledFrom = $event->name;
2
Javascript
Javascript
check symbols in shared lib
ab7c627e5327d621a734a32680cbfc99453f8b20
<ide><path>test/common/shared-lib-util.js <del>/* eslint-disable node-core/required-modules */ <ide> 'use strict'; <add>const common = require('../common'); <ide> const path = require('path'); <ide> <ide> // If node executable is linked to shared lib, need to take care about the <ide> exports.addLibraryPath = function(env) { <ide> (env.PATH ? env.PATH + path.delimiter : '') + <ide> path.dirname(process.execPath); <ide> }; <add> <add>// Get the full path of shared lib <add>exports.getSharedLibPath = function() { <add> if (common.isWindows) { <add> return path.join(path.dirname(process.execPath), 'node.dll'); <add> } else if (common.isOSX) { <add> return path.join(path.dirname(process.execPath), <add> `libnode.${process.config.variables.shlib_suffix}`); <add> } else { <add> return path.join(path.dirname(process.execPath), <add> 'lib.target', <add> `libnode.${process.config.variables.shlib_suffix}`); <add> } <add>}; <ide><path>test/parallel/test-postmortem-metadata.js <ide> const common = require('../common'); <ide> const assert = require('assert'); <ide> const { spawnSync } = require('child_process'); <del>const args = [process.execPath]; <add>const { getSharedLibPath } = require('../common/shared-lib-util.js'); <add> <add>// For shared lib case, check shared lib instead <add>const args = [ <add> process.config.variables.node_shared ? <add> getSharedLibPath() : process.execPath <add>]; <ide> <ide> if (common.isAIX) <ide> args.unshift('-Xany', '-B');
2
PHP
PHP
pass exception variable
fcf13f69ae2b6331b6780e495fe09cf88ebedc6d
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php <ide> protected function renderHttpException(HttpException $e) <ide> <ide> if (view()->exists("errors.{$status}")) <ide> { <del> return response()->view("errors.{$status}", ['e' => $e], $status); <add> return response()->view("errors.{$status}", ['exception' => $e], $status); <ide> } <ide> else <ide> {
1
Python
Python
fix some bugs
6bb3fb7c9d853dec1c4dc8564debeb426b13cd30
<ide><path>keras/callbacks/tensorboard_v2.py <ide> from __future__ import print_function <ide> <ide> import tensorflow as tf <add>import warnings <ide> <ide> <ide> class TensorBoard(tf.keras.callbacks.TensorBoard): <ide><path>keras/engine/base_layer.py <ide> def get_losses_for(self, inputs): <ide> def weights(self): <ide> return self.trainable_weights + self.non_trainable_weights <ide> <add> @K.eager <ide> def set_weights(self, weights): <ide> """Sets the weights of the layer, from Numpy arrays. <ide> <ide> def set_weights(self, weights): <ide> weight_value_tuples.append((p, w)) <ide> K.batch_set_value(weight_value_tuples) <ide> <add> @K.eager <ide> def get_weights(self): <ide> """Returns the current weights of the layer. <ide> <ide><path>keras/engine/training_utils.py <ide> def call_metric_function(metric_fn, <ide> weights = mask <ide> else: <ide> # Update dimensions of weights to match with mask. <del> mask, _, weights = tf_losses_utils.squeeze_or_expand_dimensions( <add> mask, _, weights = losses_utils.squeeze_or_expand_dimensions( <ide> mask, sample_weight=weights) <ide> weights *= mask <ide> <ide><path>keras/utils/losses_utils.py <ide> def squeeze_or_expand_dimensions(y_pred, y_true=None, sample_weight=None): <ide> y_pred_rank = K.ndim(y_pred) <ide> weights_rank = K.ndim(sample_weight) <ide> if weights_rank != 0: <del> if weights_rank - y_pred_rank == 1: <add> if y_pred_rank == 0 and weights_rank == 1: <add> y_pred = K.expand_dims(y_pred, -1) <add> elif weights_rank - y_pred_rank == 1: <ide> sample_weight = K.squeeze(sample_weight, -1) <ide> elif y_pred_rank - weights_rank == 1: <ide> sample_weight = K.expand_dims(sample_weight, -1)
4
Javascript
Javascript
use endswith instead of regex
f5f2df187bf11d64671dfe40f58084bc93eaea9e
<ide><path>tools/crowdin/utils/strings.js <ide> const isReservedHeading = (context, str) => { <ide> <ide> const isCode = str => /^\/pre\/code|\/code$/.test(str); <ide> <del>const isTitle = str => /^(tests\s*->\s*\d+\s*)?->\s*title/.test(str); <add>const isTitle = str => str.endsWith('title'); <ide> <ide> const shouldHide = (text, context, challengeTitle, crowdinFilePath) => { <ide> if (crowdinFilePath.endsWith('.yml')) {
1
Python
Python
fix description of ma.average parameter
b58a854359d06dd5a61cf236c328a2aefc8ecce4
<ide><path>numpy/ma/extras.py <ide> def average(a, axis=None, weights=None, returned=False): <ide> Data to be averaged. <ide> Masked entries are not taken into account in the computation. <ide> axis : int, optional <del> Axis along which the variance is computed. The default is to compute <del> the variance of the flattened array. <add> Axis along which the average is computed. The default is to compute <add> the average of the flattened array. <ide> weights : array_like, optional <ide> The importance that each element has in the computation of the average. <ide> The weights array can either be 1-D (in which case its length must be
1
Javascript
Javascript
fix the test
4024ea956c72f5239545a0485ab6d4d4fd039ebe
<ide><path>spec/git-repository-async-spec.js <ide> describe('GitRepositoryAsync', () => { <ide> }) <ide> <ide> it('returns the old and new lines of the diff', async () => { <del> const {oldStart, newStart, oldLines, newLines} = await repo.getLineDiffs('a.txt', 'hi there') <add> const [{oldStart, newStart, oldLines, newLines}] = await repo.getLineDiffs('a.txt', 'hi there') <ide> expect(oldStart).toBe(0) <ide> expect(oldLines).toBe(0) <ide> expect(newStart).toBe(1)
1
Text
Text
add solution to match whitespace problem
13b3e3fa9ba6f5dcbc40e5bdaab48cc57dd3a8f5
<ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/regular-expressions/match-whitespace.english.md <ide> let result = sample.match(countWhiteSpace); <ide> <section id='solution'> <ide> <ide> ```js <del>// solution required <add>let sample = "Whitespace is important in separating words"; <add>let countWhiteSpace = /\s/g; <add>let result = sample.match(countWhiteSpace); <ide> ``` <ide> </section>
1
PHP
PHP
allow passing of permissions on local file driver
cf3440799657486757a2e39b077a051cddd7756c
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> protected function callCustomCreator(array $config) <ide> */ <ide> public function createLocalDriver(array $config) <ide> { <del> return $this->adapt(new Flysystem(new LocalAdapter($config['root']))); <add> $permissions = isset($config['permissions']) ? $config['permissions'] : []; <add> <add> return $this->adapt(new Flysystem(new LocalAdapter( <add> $config['root'], LOCK_EX, LocalAdapter::DISALLOW_LINKS, $permissions <add> ))); <ide> } <ide> <ide> /**
1
Text
Text
add link to linear radial axis for radar chart doc
e9f341889fe2e4a43c9ef66b379ec88cf2241415
<ide><path>docs/charts/radar.md <ide> The radar chart defines the following configuration options. These options are m <ide> ## Scale Options <ide> <ide> The radar chart supports only a single scale. The options for this scale are defined in the `scale` property. <add>The options for this scale are defined in the `scale` property, which can be referenced from the [Linear Radial Axis page](../axes/radial/linear). <ide> <ide> ```javascript <ide> options = { <ide> scale: { <del> // Hides the scale <del> display: false <add> angleLines: { <add> display: false <add> }, <add> ticks: { <add> suggestedMin: 50, <add> suggestedMax: 100 <add> } <ide> } <ide> }; <ide> ```
1
Ruby
Ruby
initialize @as before plural method is called
bb2f53b4090768e4750af66c6fed15d6596bb11c
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> class SingletonResource < Resource #:nodoc: <ide> DEFAULT_ACTIONS = [:show, :create, :update, :destroy, :new, :edit] <ide> <ide> def initialize(entities, options) <add> @as = nil <ide> @name = entities.to_s <ide> @path = (options.delete(:path) || @name).to_s <ide> @controller = (options.delete(:controller) || plural).to_s
1
Ruby
Ruby
avoid need for enumerable#sum extension
96af8b69a4ca5f5bd349d12783d6eb2724e540d3
<ide><path>activesupport/lib/active_support/xml_mini/rexml.rb <ide> def merge_texts!(hash, element) <ide> hash <ide> else <ide> # must use value to prevent double-escaping <del> merge!(hash, CONTENT_KEY, element.texts.sum(&:value)) <add> texts = '' <add> element.texts.each { |t| texts << t.value } <add> merge!(hash, CONTENT_KEY, texts) <ide> end <ide> end <ide>
1
Javascript
Javascript
add legacy methods to buffer
515f006b6e4ddeb977580037fca6c0fbc27c3ad7
<ide><path>lib/buffer.js <ide> Buffer.prototype.slice = function (start, end) { <ide> <ide> return new Buffer(this.parent, end - start, +start + this.offset); <ide> }; <add> <add> <add>// Legacy methods for backwards compatibility. <add> <add>Buffer.prototype.utf8Slice = function (start, end) { <add> return this.toString("utf8", start, end); <add>}; <add> <add>Buffer.prototype.binarySlice = function (start, end) { <add> return this.toString("binary", start, end); <add>}; <add> <add>Buffer.prototype.asciiSlice = function (start, end) { <add> return this.toString("ascii", start, end); <add>}; <add> <add>Buffer.prototype.utf8Write = function (string, offset) { <add> return this.write(string, offset, "utf8"); <add>}; <add> <add>Buffer.prototype.binaryWrite = function (string, offset) { <add> return this.write(string, offset, "binary"); <add>}; <add> <add>Buffer.prototype.asciiWrite = function (string, offset) { <add> return this.write(string, offset, "ascii"); <add>}; <add>
1
Python
Python
use six.string_types for python3
088f68252d1f3c9e5d51a5ea3ab769397a65859f
<ide><path>django/db/models/fields/related.py <ide> class MyModel(Model): <ide> else: <ide> # Look for an "app.Model" relation <ide> <del> if isinstance(relation, basestring): <add> if isinstance(relation, six.string_types): <ide> try: <ide> app_label, model_name = relation.split(".") <ide> except ValueError:
1
Text
Text
add description field
cd63b740a50d67378b0f25f71c73aa11e27c2754
<ide><path>share/doc/homebrew/Formula-Cookbook.md <ide> end <ide> <ide> **We don’t accept formulae without homepages!** <ide> <del>Homebrew doesn’t have a description field because the homepage is always up to date, and Homebrew is not. That’s way less maintenance for us. Try `brew home qt`. <del> <add>Homebrew now has a description field (`desc`). Try and summarize this from the homepage. <ide> <ide> ## Check the build system <ide>
1
PHP
PHP
remove duplication where possible
6e0e15682ffba6bedabefb430cf12d84c034ec86
<ide><path>lib/Cake/Utility/Set.php <ide> */ <ide> <ide> App::uses('String', 'Utility'); <add>App::uses('Hash', 'Utility'); <ide> <ide> /** <ide> * Class used for manipulation of arrays. <ide> class Set { <ide> */ <ide> public static function merge($arr1, $arr2 = null) { <ide> $args = func_get_args(); <del> <del> $r = (array)current($args); <del> while (($arg = next($args)) !== false) { <del> foreach ((array)$arg as $key => $val) { <del> if (!empty($r[$key]) && is_array($r[$key]) && is_array($val)) { <del> $r[$key] = Set::merge($r[$key], $val); <del> } elseif (is_int($key)) { <del> $r[] = $val; <del> } else { <del> $r[$key] = $val; <del> } <del> } <del> } <del> return $r; <add> return call_user_func_array('Hash::merge', $args); <ide> } <ide> <ide> /** <ide> public static function merge($arr1, $arr2 = null) { <ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::filter <ide> */ <ide> public static function filter(array $var) { <del> foreach ($var as $k => $v) { <del> if (is_array($v)) { <del> $var[$k] = Set::filter($v); <del> } <del> } <del> return array_filter($var, array('Set', '_filter')); <del> } <del> <del>/** <del> * Set::filter callback function <del> * <del> * @param array $var Array to filter. <del> * @return boolean <del> */ <del> protected static function _filter($var) { <del> if ($var === 0 || $var === '0' || !empty($var)) { <del> return true; <del> } <del> return false; <add> return Hash::filter($var); <ide> } <ide> <ide> /** <ide> protected static function _map(&$array, $class, $primary = false) { <ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::numeric <ide> */ <ide> public static function numeric($array = null) { <del> if (empty($array)) { <del> return null; <del> } <del> <del> if ($array === range(0, count($array) - 1)) { <del> return true; <del> } <del> <del> $numeric = true; <del> $keys = array_keys($array); <del> $count = count($keys); <del> <del> for ($i = 0; $i < $count; $i++) { <del> if (!is_numeric($array[$keys[$i]])) { <del> $numeric = false; <del> break; <del> } <del> } <del> return $numeric; <add> return Hash::numeric($array); <ide> } <ide> <ide> /** <ide> public static function classicExtract($data, $path = null) { <ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::insert <ide> */ <ide> public static function insert($list, $path, $data = null) { <del> if (!is_array($path)) { <del> $path = explode('.', $path); <del> } <del> $_list =& $list; <del> <del> $count = count($path); <del> foreach ($path as $i => $key) { <del> if (is_numeric($key) && intval($key) > 0 || $key === '0') { <del> $key = intval($key); <del> } <del> if ($i === $count - 1 && is_array($_list)) { <del> $_list[$key] = $data; <del> } else { <del> if (!isset($_list[$key])) { <del> $_list[$key] = array(); <del> } <del> $_list =& $_list[$key]; <del> } <del> if (!is_array($_list)) { <del> $_list = array(); <del> } <del> } <del> return $list; <add> return Hash::insert($list, $path, $data); <ide> } <ide> <ide> /** <ide> public static function insert($list, $path, $data = null) { <ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::remove <ide> */ <ide> public static function remove($list, $path = null) { <del> if (empty($path)) { <del> return $list; <del> } <del> if (!is_array($path)) { <del> $path = explode('.', $path); <del> } <del> $_list =& $list; <del> <del> foreach ($path as $i => $key) { <del> if (is_numeric($key) && intval($key) > 0 || $key === '0') { <del> $key = intval($key); <del> } <del> if ($i === count($path) - 1) { <del> unset($_list[$key]); <del> } else { <del> if (!isset($_list[$key])) { <del> return $list; <del> } <del> $_list =& $_list[$key]; <del> } <del> } <del> return $list; <add> return Hash::remove($list, $path); <ide> } <ide> <ide> /** <ide> public static function normalize($list, $assoc = true, $sep = ',', $trim = true) <ide> } <ide> } <ide> if ($assoc) { <del> return Set::normalize($list); <add> return Hash::normalize($list); <ide> } <ide> } elseif (is_array($list)) { <del> $keys = array_keys($list); <del> $count = count($keys); <del> $numeric = true; <del> <del> if (!$assoc) { <del> for ($i = 0; $i < $count; $i++) { <del> if (!is_int($keys[$i])) { <del> $numeric = false; <del> break; <del> } <del> } <del> } <del> if (!$numeric || $assoc) { <del> $newList = array(); <del> for ($i = 0; $i < $count; $i++) { <del> if (is_int($keys[$i])) { <del> $newList[$list[$keys[$i]]] = null; <del> } else { <del> $newList[$keys[$i]] = $list[$keys[$i]]; <del> } <del> } <del> $list = $newList; <del> } <add> $list = Hash::normalize($list, $assoc); <ide> } <ide> return $list; <ide> } <ide> public static function reverse($object) { <ide> * @link http://book.cakephp.org/2.0/en/core-utility-libraries/set.html#Set::flatten <ide> */ <ide> public static function flatten($data, $separator = '.') { <del> $result = array(); <del> $path = null; <del> <del> if (is_array($separator)) { <del> extract($separator, EXTR_OVERWRITE); <del> } <del> <del> if (!is_null($path)) { <del> $path .= $separator; <del> } <del> <del> foreach ($data as $key => $val) { <del> if (is_array($val)) { <del> $result += (array)Set::flatten($val, array( <del> 'separator' => $separator, <del> 'path' => $path . $key <del> )); <del> } else { <del> $result[$path . $key] = $val; <del> } <del> } <del> return $result; <add> return Hash::flatten($data, $separator); <ide> } <ide> <ide> /** <ide> public static function flatten($data, $separator = '.') { <ide> * @return array <ide> */ <ide> public static function expand($data, $separator = '.') { <del> $result = array(); <del> foreach ($data as $flat => $value) { <del> $keys = explode($separator, $flat); <del> $keys = array_reverse($keys); <del> $child = array( <del> $keys[0] => $value <del> ); <del> array_shift($keys); <del> foreach ($keys as $k) { <del> $child = array( <del> $k => $child <del> ); <del> } <del> $result = Set::merge($result, $child); <del> } <del> return $result; <add> return Hash::expand($data, $separator); <ide> } <ide> <ide> /** <ide> public static function get($input, $path = null) { <ide> } else { <ide> $keys = $path; <ide> } <del> if (!$keys) { <del> return $input; <del> } <del> <del> $return = $input; <del> foreach ($keys as $key) { <del> if (!isset($return[$key])) { <del> return null; <del> } <del> $return = $return[$key]; <del> } <del> return $return; <add> return Hash::get($input, $keys); <ide> } <ide> <ide> }
1
Javascript
Javascript
add canadian french locale
f2c29d6b04bab66c419f0ac7f13d18a1c6f4a803
<ide><path>src/locale/fr-CA.js <add>import "locale"; <add> <add>var d3_locale_frCA = d3.locale({ <add> decimal: ",", <add> thousands: "\xa0", <add> grouping: [3], <add> currency: ["", "$"], <add> dateTime: "%a %e %b %Y %X", <add> date: "%Y-%m-%d", <add> time: "%H:%M:%S", <add> periods: ["", ""], <add> days: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"], <add> shortDays: ["dim", "lun", "mar", "mer", "jeu", "ven", "sam"], <add> months: ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août", "septembre", "octobre", "novembre", "décembre"], <add> shortMonths: ["jan", "fév", "mar", "avr", "mai", "jui", "jul", "aoû", "sep", "oct", "nov", "déc"] <add>});
1
Ruby
Ruby
fix strange nomemoryerror on amd64. closes [wrb]
f6d45ce95dae13bce93446b678148327edeaf6b8
<ide><path>actionpack/lib/action_controller/benchmarking.rb <ide> def perform_action_with_benchmark <ide> end <ide> <ide> def rendering_runtime(runtime) <del> " | Rendering: #{sprintf("%.5f", @rendering_runtime)} (#{sprintf("%d", (@rendering_runtime * 100) / runtime)}%)" <add> percentage = @rendering_runtime * 100 / runtime <add> " | Rendering: %.5f (%d%%)" % [@rendering_runtime, percentage.to_i] <ide> end <ide> <ide> def active_record_runtime(runtime) <ide> db_runtime = ActiveRecord::Base.connection.reset_runtime <ide> db_runtime += @db_rt_before_render if @db_rt_before_render <ide> db_runtime += @db_rt_after_render if @db_rt_after_render <del> db_percentage = (db_runtime * 100) / runtime <del> " | DB: #{sprintf("%.5f", db_runtime)} (#{sprintf("%d", db_percentage)}%)" <add> db_percentage = db_runtime * 100 / runtime <add> " | DB: %.5f (%d%%)" % [db_runtime, db_percentage.to_i] <ide> end <ide> end <del>end <ide>\ No newline at end of file <add>end
1
Python
Python
add test for concatenate with none-axis
7c183a5d03ae31a6369cdcc608b4e4fabf83484f
<ide><path>numpy/core/tests/test_shape_base.py <del>from numpy.testing import * <del>from numpy.core import array, atleast_1d, atleast_2d, atleast_3d, vstack, \ <del> hstack, newaxis <add>import warnings <add>import numpy as np <add>from numpy.testing import (TestCase, assert_, assert_raises, assert_equal, <add> assert_array_equal, run_module_suite) <add>from numpy.core import (array, arange, atleast_1d, atleast_2d, atleast_3d, <add> vstack, hstack, newaxis, concatenate) <ide> <ide> class TestAtleast1d(TestCase): <ide> def test_0D_array(self): <ide> def test_2D_array2(self): <ide> desired = array([[1,2],[1,2]]) <ide> assert_array_equal(res,desired) <ide> <add>def test_concatenate_axis_None(): <add> a = np.arange(4, dtype=np.float64).reshape((2,2)) <add> b = range(3) <add> c = ['x'] <add> r = np.concatenate((a, a), axis=None) <add> assert_equal(r.dtype, a.dtype) <add> assert_equal(r.ndim, 1) <add> r = np.concatenate((a, b), axis=None) <add> assert_equal(r.size, a.size + len(b)) <add> assert_equal(r.dtype, a.dtype) <add> r = np.concatenate((a, b, c), axis=None) <add> d = array(['0', '1', '2', '3', <add> '0', '1', '2', 'x']) <add> assert_array_equal(r,d) <add> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Javascript
Javascript
invalidate cache for link[preload] in dev
5a4176cffe7d72afbf6f9071adee8d38cd93c60d
<ide><path>packages/next/pages/_document.js <ide> const Fragment = React.Fragment || function Fragment ({ children }) { <ide> <ide> export default class Document extends Component { <ide> static childContextTypes = { <del> _documentProps: PropTypes.any <add> _documentProps: PropTypes.any, <add> _devOnlyInvalidateCacheQueryString: PropTypes.string, <ide> } <ide> <ide> static getInitialProps ({ renderPage }) { <ide> export default class Document extends Component { <ide> } <ide> <ide> getChildContext () { <del> return { _documentProps: this.props } <add> return { <add> _documentProps: this.props, <add> // In dev we invalidate the cache by appending a timestamp to the resource URL. <add> // This is a workaround to fix https://github.com/zeit/next.js/issues/5860 <add> // TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed. <add> _devOnlyInvalidateCacheQueryString: process.env.NODE_ENV !== 'production' ? '?ts=' + Date.now() : '' <add> } <ide> } <ide> <ide> render () { <ide> export default class Document extends Component { <ide> <ide> export class Head extends Component { <ide> static contextTypes = { <del> _documentProps: PropTypes.any <add> _documentProps: PropTypes.any, <add> _devOnlyInvalidateCacheQueryString: PropTypes.string, <ide> } <ide> <ide> static propTypes = { <ide> export class Head extends Component { <ide> <ide> getPreloadDynamicChunks () { <ide> const { dynamicImports, assetPrefix } = this.context._documentProps <add> const { _devOnlyInvalidateCacheQueryString } = this.context <add> <ide> return dynamicImports.map((bundle) => { <ide> return <link <ide> rel='preload' <ide> key={bundle.file} <del> href={`${assetPrefix}/_next/${bundle.file}`} <add> href={`${assetPrefix}/_next/${bundle.file}${_devOnlyInvalidateCacheQueryString}`} <ide> as='script' <ide> nonce={this.props.nonce} <ide> crossOrigin={this.props.crossOrigin || process.crossOrigin} <ide> export class Head extends Component { <ide> <ide> getPreloadMainLinks () { <ide> const { assetPrefix, files } = this.context._documentProps <del> if(!files || files.length === 0) { <add> if (!files || files.length === 0) { <ide> return null <ide> } <add> const { _devOnlyInvalidateCacheQueryString } = this.context <ide> <ide> return files.map((file) => { <ide> // Only render .js files here <ide> export class Head extends Component { <ide> key={file} <ide> nonce={this.props.nonce} <ide> rel='preload' <del> href={`${assetPrefix}/_next/${file}`} <add> href={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`} <ide> as='script' <ide> crossOrigin={this.props.crossOrigin || process.crossOrigin} <ide> /> <ide> export class Head extends Component { <ide> <ide> render () { <ide> const { head, styles, assetPrefix, __NEXT_DATA__ } = this.context._documentProps <add> const { _devOnlyInvalidateCacheQueryString } = this.context <ide> const { page, buildId } = __NEXT_DATA__ <ide> const pagePathname = getPagePathname(page) <ide> <ide> export class Head extends Component { <ide> }) <ide> if (this.props.crossOrigin) console.warn('Warning: `Head` attribute `crossOrigin` is deprecated. https://err.sh/next.js/doc-crossorigin-deprecated') <ide> } <del> <ide> return <head {...this.props}> <ide> {children} <ide> {head} <del> {page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />} <del> <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages/_app.js`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} /> <add> {page !== '/_error' && <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />} <add> <link rel='preload' href={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} as='script' nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} /> <ide> {this.getPreloadDynamicChunks()} <ide> {this.getPreloadMainLinks()} <ide> {this.getCssLinks()} <ide> export class Head extends Component { <ide> <ide> export class Main extends Component { <ide> static contextTypes = { <del> _documentProps: PropTypes.any <add> _documentProps: PropTypes.any, <add> _devOnlyInvalidateCacheQueryString: PropTypes.string, <ide> } <ide> <ide> render () { <ide> export class Main extends Component { <ide> <ide> export class NextScript extends Component { <ide> static contextTypes = { <del> _documentProps: PropTypes.any <add> _documentProps: PropTypes.any, <add> _devOnlyInvalidateCacheQueryString: PropTypes.string, <ide> } <ide> <ide> static propTypes = { <ide> export class NextScript extends Component { <ide> <ide> getDynamicChunks () { <ide> const { dynamicImports, assetPrefix } = this.context._documentProps <add> const { _devOnlyInvalidateCacheQueryString } = this.context <add> <ide> return dynamicImports.map((bundle) => { <ide> return <script <ide> async <ide> key={bundle.file} <del> src={`${assetPrefix}/_next/${bundle.file}`} <add> src={`${assetPrefix}/_next/${bundle.file}${_devOnlyInvalidateCacheQueryString}`} <ide> nonce={this.props.nonce} <ide> crossOrigin={this.props.crossOrigin || process.crossOrigin} <ide> /> <ide> export class NextScript extends Component { <ide> <ide> getScripts () { <ide> const { assetPrefix, files } = this.context._documentProps <del> if(!files || files.length === 0) { <add> if (!files || files.length === 0) { <ide> return null <ide> } <add> const { _devOnlyInvalidateCacheQueryString } = this.context <ide> <ide> return files.map((file) => { <ide> // Only render .js files here <ide> export class NextScript extends Component { <ide> <ide> return <script <ide> key={file} <del> src={`${assetPrefix}/_next/${file}`} <add> src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`} <ide> nonce={this.props.nonce} <ide> async <ide> crossOrigin={this.props.crossOrigin || process.crossOrigin} <ide> export class NextScript extends Component { <ide> <ide> render () { <ide> const { staticMarkup, assetPrefix, devFiles, __NEXT_DATA__ } = this.context._documentProps <add> const { _devOnlyInvalidateCacheQueryString } = this.context <ide> const { page, buildId } = __NEXT_DATA__ <ide> const pagePathname = getPagePathname(page) <ide> <ide> export class NextScript extends Component { <ide> } <ide> <ide> return <Fragment> <del> {devFiles ? devFiles.map((file) => <script key={file} src={`${assetPrefix}/_next/${file}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />) : null} <add> {devFiles ? devFiles.map((file) => <script key={file} src={`${assetPrefix}/_next/${file}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />) : null} <ide> {staticMarkup ? null : <script id="__NEXT_DATA__" type="application/json" nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} dangerouslySetInnerHTML={{ <ide> __html: NextScript.getInlineScriptSource(this.context._documentProps) <ide> }} />} <del> {page !== '/_error' && <script async id={`__NEXT_PAGE__${page}`} src={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />} <del> <script async id={`__NEXT_PAGE__/_app`} src={`${assetPrefix}/_next/static/${buildId}/pages/_app.js`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} /> <add> {page !== '/_error' && <script async id={`__NEXT_PAGE__${page}`} src={`${assetPrefix}/_next/static/${buildId}/pages${pagePathname}${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} />} <add> <script async id={`__NEXT_PAGE__/_app`} src={`${assetPrefix}/_next/static/${buildId}/pages/_app.js${_devOnlyInvalidateCacheQueryString}`} nonce={this.props.nonce} crossOrigin={this.props.crossOrigin || process.crossOrigin} /> <ide> {staticMarkup ? null : this.getDynamicChunks()} <ide> {staticMarkup ? null : this.getScripts()} <ide> </Fragment> <ide><path>test/integration/app-document/test/rendering.js <ide> export default function ({ app }, suiteName, render, fetch) { <ide> expect($('#render-page-enhance-app').text().includes(nonce)).toBe(true) <ide> expect($('#render-page-enhance-component').text().includes(nonce)).toBe(true) <ide> }) <add> <add> // This is a workaround to fix https://github.com/zeit/next.js/issues/5860 <add> // TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed. <add> test('It adds a timestamp to link tags with preload attribute to invalidate the cache (DEV only)', async () => { <add> const $ = await get$('/') <add> $('link[rel=preload]').each((index, element) => { <add> const href = $(element).attr('href') <add> expect(href.match(/\?/g)).toHaveLength(1) <add> expect(href).toMatch(/\?ts=/) <add> }) <add> $('script[src]').each((index, element) => { <add> const src = $(element).attr('src') <add> expect(src.match(/\?/g)).toHaveLength(1) <add> expect(src).toMatch(/\?ts=/) <add> }) <add> }) <ide> }) <ide> <ide> describe('_app', () => { <ide><path>test/integration/production/test/index.test.js <ide> describe('Production Usage', () => { <ide> browser.close() <ide> }) <ide> <add> // This is a workaround to fix https://github.com/zeit/next.js/issues/5860 <add> // TODO: remove this workaround when https://bugs.webkit.org/show_bug.cgi?id=187726 is fixed. <add> it('It does not add a timestamp to link tags with preload attribute', async () => { <add> const browser = await webdriver(appPort, '/prefetch') <add> const links = await browser.elementsByCss('link[rel=preload]') <add> await Promise.all( <add> links.map(async (element) => { <add> const href = await element.getAttribute('href') <add> expect(href).not.toMatch(/\?ts=/) <add> }) <add> ) <add> const scripts = await browser.elementsByCss('script[src]') <add> await Promise.all( <add> scripts.map(async (element) => { <add> const src = await element.getAttribute('src') <add> expect(src).not.toMatch(/\?ts=/) <add> }) <add> ) <add> browser.close() <add> }) <add> <ide> it('should reload the page on page script error with prefetch', async () => { <ide> const browser = await webdriver(appPort, '/counter') <ide> const counter = await browser
3
Javascript
Javascript
fix meta and styles on error page (#600)
08548551977c03986fd1bec975abecd8b8c56cb0
<ide><path>pages/_error-debug.js <ide> import React from 'react' <add>import Head from 'next/head' <ide> import ansiHTML from 'ansi-html' <ide> <ide> export default class ErrorDebug extends React.Component { <ide> export default class ErrorDebug extends React.Component { <ide> const { name, message, stack, path } = this.props <ide> <ide> return <div className='errorDebug'> <add> <Head> <add> <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <add> </Head> <ide> {path ? <div className='heading'>Error in {path}</div> : null} <ide> { <ide> name === 'ModuleBuildError' <ide><path>pages/_error.js <ide> import React from 'react' <add>import Head from 'next/head' <ide> <ide> export default class Error extends React.Component { <ide> static getInitialProps ({ res, xhr }) { <ide> export default class Error extends React.Component { <ide> : (statusCode ? 'Internal Server Error' : 'An unexpected error has occurred') <ide> <ide> return <div className='error'> <add> <Head> <add> <meta name='viewport' content='width=device-width, initial-scale=1.0' /> <add> </Head> <ide> <div> <ide> {statusCode ? <h1>{statusCode}</h1> : null} <ide> <div className='desc'> <ide> <h2>{title}.</h2> <ide> </div> <ide> </div> <add> <style jsx global>{` <add> body { margin: 0 } <add> `}</style> <ide> <style jsx>{` <ide> .error { <ide> color: #000; <ide> background: #fff; <del> top: 0; <del> bottom: 0; <del> left: 0; <del> right: 0; <del> position: absolute; <ide> font-family: -apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", "Fira Sans", Avenir, "Helvetica Neue", "Lucida Grande", sans-serif; <add> height: 100vh; <ide> text-align: center; <del> padding-top: 20%; <add> display: flex; <add> flex-direction: column; <add> align-items: center; <add> justify-content: center; <ide> } <ide> <ide> .desc { <ide> export default class Error extends React.Component { <ide> border-right: 1px solid rgba(0, 0, 0,.3); <ide> margin: 0; <ide> margin-right: 20px; <del> padding: 10px 23px; <add> padding: 10px 23px 10px 0; <ide> font-size: 24px; <ide> font-weight: 500; <ide> vertical-align: top;
2
Javascript
Javascript
add assert map and set benchmarks
462b58e581f0e6a0f621bd478290d4c427fc8d37
<ide><path>benchmark/assert/deepequal-map.js <add>'use strict'; <add> <add>/* eslint-disable no-restricted-properties */ <add> <add>const common = require('../common.js'); <add>const assert = require('assert'); <add> <add>const bench = common.createBenchmark(main, { <add> n: [5e2], <add> len: [5e2], <add> method: [ <add> 'deepEqual_primitiveOnly', <add> 'deepStrictEqual_primitiveOnly', <add> 'deepEqual_objectOnly', <add> 'deepStrictEqual_objectOnly', <add> 'deepEqual_mixed', <add> 'deepStrictEqual_mixed', <add> 'deepEqual_looseMatches', <add> 'notDeepEqual_primitiveOnly', <add> 'notDeepStrictEqual_primitiveOnly', <add> 'notDeepEqual_objectOnly', <add> 'notDeepStrictEqual_objectOnly', <add> 'notDeepEqual_mixed', <add> 'notDeepStrictEqual_mixed', <add> 'notDeepEqual_looseMatches', <add> ] <add>}); <add> <add>function benchmark(method, n, values, values2) { <add> const actual = new Map(values); <add> // Prevent reference equal elements <add> const deepCopy = JSON.parse(JSON.stringify(values2 ? values2 : values)); <add> const expected = new Map(deepCopy); <add> bench.start(); <add> for (var i = 0; i < n; ++i) { <add> method(actual, expected); <add> } <add> bench.end(n); <add>} <add> <add>function main(conf) { <add> const n = +conf.n; <add> const len = +conf.len; <add> <add> const array = Array(len).fill(1); <add> var values, values2; <add> <add> switch (conf.method) { <add> case 'deepEqual_primitiveOnly': <add> values = array.map((_, i) => [`str_${i}`, 123]); <add> benchmark(assert.deepEqual, n, values); <add> break; <add> case 'deepStrictEqual_primitiveOnly': <add> values = array.map((_, i) => [`str_${i}`, 123]); <add> benchmark(assert.deepStrictEqual, n, values); <add> break; <add> case 'deepEqual_objectOnly': <add> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <add> benchmark(assert.deepEqual, n, values); <add> break; <add> case 'deepStrictEqual_objectOnly': <add> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <add> benchmark(assert.deepStrictEqual, n, values); <add> break; <add> case 'deepEqual_mixed': <add> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <add> benchmark(assert.deepEqual, n, values); <add> break; <add> case 'deepStrictEqual_mixed': <add> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <add> benchmark(assert.deepStrictEqual, n, values); <add> break; <add> case 'deepEqual_looseMatches': <add> values = array.map((_, i) => [i, i]); <add> values2 = values.slice().map((v) => [String(v[0]), String(v[1])]); <add> benchmark(assert.deepEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_primitiveOnly': <add> values = array.map((_, i) => [`str_${i}`, 123]); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = ['w00t', 123]; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> case 'notDeepStrictEqual_primitiveOnly': <add> values = array.map((_, i) => [`str_${i}`, 123]); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = ['w00t', 123]; <add> benchmark(assert.notDeepStrictEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_objectOnly': <add> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = [['w00t'], 123]; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> case 'notDeepStrictEqual_objectOnly': <add> values = array.map((_, i) => [[`str_${i}`, 1], 123]); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = [['w00t'], 123]; <add> benchmark(assert.notDeepStrictEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_mixed': <add> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <add> values2 = values.slice(0); <add> values2[0] = ['w00t', 123]; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> case 'notDeepStrictEqual_mixed': <add> values = array.map((_, i) => [i % 2 ? [`str_${i}`, 1] : `str_${i}`, 123]); <add> values2 = values.slice(0); <add> values2[0] = ['w00t', 123]; <add> benchmark(assert.notDeepStrictEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_looseMatches': <add> values = array.map((_, i) => [i, i]); <add> values2 = values.slice().map((v) => [String(v[0]), String(v[1])]); <add> values2[len - 1] = [String(len + 1), String(len + 1)]; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> default: <add> throw new Error('Unsupported method'); <add> } <add>} <ide><path>benchmark/assert/deepequal-set.js <add>'use strict'; <add> <add>/* eslint-disable no-restricted-properties */ <add> <add>const common = require('../common.js'); <add>const assert = require('assert'); <add> <add>const bench = common.createBenchmark(main, { <add> n: [5e2], <add> len: [5e2], <add> method: [ <add> 'deepEqual_primitiveOnly', <add> 'deepStrictEqual_primitiveOnly', <add> 'deepEqual_objectOnly', <add> 'deepStrictEqual_objectOnly', <add> 'deepEqual_mixed', <add> 'deepStrictEqual_mixed', <add> 'deepEqual_looseMatches', <add> 'notDeepEqual_primitiveOnly', <add> 'notDeepStrictEqual_primitiveOnly', <add> 'notDeepEqual_objectOnly', <add> 'notDeepStrictEqual_objectOnly', <add> 'notDeepEqual_mixed', <add> 'notDeepStrictEqual_mixed', <add> 'notDeepEqual_looseMatches', <add> ] <add>}); <add> <add>function benchmark(method, n, values, values2) { <add> const actual = new Set(values); <add> // Prevent reference equal elements <add> const deepCopy = JSON.parse(JSON.stringify(values2 ? values2 : values)); <add> const expected = new Set(deepCopy); <add> bench.start(); <add> for (var i = 0; i < n; ++i) { <add> method(actual, expected); <add> } <add> bench.end(n); <add>} <add> <add>function main(conf) { <add> const n = +conf.n; <add> const len = +conf.len; <add> <add> const array = Array(len).fill(1); <add> <add> var values, values2; <add> <add> switch (conf.method) { <add> case 'deepEqual_primitiveOnly': <add> values = array.map((_, i) => `str_${i}`); <add> benchmark(assert.deepEqual, n, values); <add> break; <add> case 'deepStrictEqual_primitiveOnly': <add> values = array.map((_, i) => `str_${i}`); <add> benchmark(assert.deepStrictEqual, n, values); <add> break; <add> case 'deepEqual_objectOnly': <add> values = array.map((_, i) => [`str_${i}`, null]); <add> benchmark(assert.deepEqual, n, values); <add> break; <add> case 'deepStrictEqual_objectOnly': <add> values = array.map((_, i) => [`str_${i}`, null]); <add> benchmark(assert.deepStrictEqual, n, values); <add> break; <add> case 'deepEqual_mixed': <add> values = array.map((_, i) => { <add> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <add> }); <add> benchmark(assert.deepEqual, n, values); <add> break; <add> case 'deepStrictEqual_mixed': <add> values = array.map((_, i) => { <add> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <add> }); <add> benchmark(assert.deepStrictEqual, n, values); <add> break; <add> case 'deepEqual_looseMatches': <add> values = array.map((_, i) => i); <add> values2 = values.slice().map((v) => String(v)); <add> benchmark(assert.deepEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_primitiveOnly': <add> values = array.map((_, i) => `str_${i}`); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = 'w00t'; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> case 'notDeepStrictEqual_primitiveOnly': <add> values = array.map((_, i) => `str_${i}`); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = 'w00t'; <add> benchmark(assert.notDeepStrictEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_objectOnly': <add> values = array.map((_, i) => [`str_${i}`, null]); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = ['w00t']; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> case 'notDeepStrictEqual_objectOnly': <add> values = array.map((_, i) => [`str_${i}`, null]); <add> values2 = values.slice(0); <add> values2[Math.floor(len / 2)] = ['w00t']; <add> benchmark(assert.notDeepStrictEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_mixed': <add> values = array.map((_, i) => { <add> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <add> }); <add> values2 = values.slice(); <add> values2[0] = 'w00t'; <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> case 'notDeepStrictEqual_mixed': <add> values = array.map((_, i) => { <add> return i % 2 ? [`str_${i}`, null] : `str_${i}`; <add> }); <add> values2 = values.slice(); <add> values2[0] = 'w00t'; <add> benchmark(assert.notDeepStrictEqual, n, values, values2); <add> break; <add> case 'notDeepEqual_looseMatches': <add> values = array.map((_, i) => i); <add> values2 = values.slice().map((v) => String(v)); <add> values2[len - 1] = String(len + 1); <add> benchmark(assert.notDeepEqual, n, values, values2); <add> break; <add> default: <add> throw new Error('Unsupported method'); <add> } <add>}
2
Ruby
Ruby
use a named arg for required `repositories`
ae73f28d0fb6ccba90462fd9e0b5660a2c835d6b
<ide><path>Library/Homebrew/dev-cmd/contributions.rb <ide> module Homebrew <ide> sig { returns(CLI::Parser) } <ide> def contributions_args <ide> Homebrew::CLI::Parser.new do <del> usage_banner "`contributions` [<email>]" <add> usage_banner "`contributions` <email> <repo1,repo2|all>" <ide> description <<~EOS <ide> Contributions to Homebrew repos for a user. <add> <add> The second argument is a comma-separated list of repos to search. <add> Specify <all> to search all repositories. <add> Supported repositories: #{SUPPORTED_REPOS.join(", ")}. <ide> EOS <ide> <ide> flag "--from=", <ide> def contributions_args <ide> flag "--to=", <ide> description: "Date (ISO-8601 format) to stop searching contributions." <ide> <del> comma_array "--repositories=", <del> description: "The Homebrew repositories to search for contributions in. " \ <del> "Comma separated. Pass `all` to search all repositories. " \ <del> "Supported repositories: #{SUPPORTED_REPOS.join(", ")}." <del> <del> named_args :email, number: 1 <add> named_args [:email, :repositories], min: 2, max: 2 <ide> end <ide> end <ide> <ide> sig { returns(NilClass) } <ide> def contributions <ide> args = contributions_args.parse <del> return ofail "Please specify `--repositories` to search, or `--repositories=all`." unless args[:repositories].empty? <ide> <ide> commits = 0 <ide> coauthorships = 0 <ide> <del> all_repos = args.repositories.first == "all" <del> repos = all_repos ? SUPPORTED_REPOS : args.repositories <add> all_repos = args.named.last == "all" <add> repos = all_repos ? SUPPORTED_REPOS : args.named.last.split(",") <add> <ide> repos.each do |repo| <ide> if SUPPORTED_REPOS.exclude?(repo) <ide> return ofail "Unsupported repository: #{repo}. Try one of #{SUPPORTED_REPOS.join(", ")}."
1
Ruby
Ruby
fix failing test
e5ee7d59f52453b28cd3f71078e8a0de53f0e227
<ide><path>Library/Homebrew/test/test_formula_validation.rb <ide> def assert_invalid(attr, &block) <ide> <ide> def test_cant_override_brew <ide> e = assert_raises(RuntimeError) { Class.new(Formula) { def brew; end } } <del> assert_equal "You cannot override Formula#brew", e.message <add> assert_match /You cannot override Formula#brew/, e.message <ide> end <ide> <ide> def test_validates_name
1
Text
Text
prevent object mutation; fixes and enhancements
97a74b68e85ade83c5efbeabe87faa4bb3b0c2a5
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/es6/prevent-object-mutation/index.md <ide> --- <ide> title: Prevent Object Mutation <ide> --- <del>![](//discourse-user-assets.s3.amazonaws.com/original/2X/3/3c8584a085a0deaea66b3400e6321eeadab552a2.jpg) <del> <ide> ![:triangular_flag_on_post:](https://forum.freecodecamp.com/images/emoji/emoji_one/triangular_flag_on_post.png?v=3 ":triangular_flag_on_post:") Remember to use <a>**`Read-Search-Ask`**</a> if you get stuck. Try to pair program ![:busts_in_silhouette:](https://forum.freecodecamp.com/images/emoji/emoji_one/busts_in_silhouette.png?v=3 ":busts_in_silhouette:") and write your own code ![:pencil:](https://forum.freecodecamp.com/images/emoji/emoji_one/pencil.png?v=3 ":pencil:") <ide> <ide> ### Problem Explanation: <ide> <del>We need to prevent `MATH_CONSTANTS` value from changing. <add>_You need to freeze the `MATH_CONSTANTS` object so that no one is able to alter the value of `PI`, add, or delete properties ._ <ide> <ide> ## ![:speech_balloon:](https://forum.freecodecamp.com/images/emoji/emoji_one/speech_balloon.png?v=3 ":speech_balloon:") Hint: 1 <ide> <del>* Use Object.freeze(obj) to prevent object from being changed. <add>* _Use `Object.freeze()` to prevent mathematical constants from changing._ <ide> <ide> > _try to solve the problem now_ <ide> <ide> ## Spoiler Alert! <ide> <ide> ![warning sign](//discourse-user-assets.s3.amazonaws.com/original/2X/2/2d6c412a50797771301e7ceabd554cef4edcd74d.gif) <ide> <del>**Solution ahead!** <add>**Solution Ahead!** <ide> <del>## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic Code Solution: <add>## ![:beginner:](https://forum.freecodecamp.com/images/emoji/emoji_one/beginner.png?v=3 ":beginner:") Basic code solution: <ide> ```javascript <ide> function freezeObj() { <ide> "use strict"; <ide> We need to prevent `MATH_CONSTANTS` value from changing. <ide> <ide> const PI = freezeObj(); <ide> ``` <del>![:rocket:](https://forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=3 ":rocket:") <a href='https://codepen.io/dylantyates/pen/OwVxYB' target='_blank' rel='nofollow'>Run Code</a> <del> <ide> # Code Explanation: <ide> <ide> By using Object.freeze() on `MATH_CONSTANTS` we can avoid manipulating it. <ide> <del>#### Relevant Links <del> <del>* <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze' target='_blank' rel='nofollow'>Object.freeze()</a> <del> <del>## ![:clipboard:](https://forum.freecodecamp.com/images/emoji/emoji_one/clipboard.png?v=3 ":clipboard:") NOTES FOR CONTRIBUTIONS: <del> <del>* ![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **DO NOT** add solutions that are similar to any existing solutions. If you think it is **_similar but better_**, then try to merge (or replace) the existing similar solution. <del>* Add an explanation of your solution. <del>* Categorize the solution in one of the following categories — **Basic**, **Intermediate** and **Advanced**. ![:traffic_light:](https://forum.freecodecamp.com/images/emoji/emoji_one/traffic_light.png?v=3 ":traffic_light:") <del>* Please add your username only if you have added any **relevant main contents**. (![:warning:](https://forum.freecodecamp.com/images/emoji/emoji_one/warning.png?v=3 ":warning:") **_DO NOT_** _remove any existing usernames_) <ide> <del>> See ![:point_right:](https://forum.freecodecamp.com/images/emoji/emoji_one/point_right.png?v=3 ":point_right:") <a href='http://forum.freecodecamp.com/t/algorithm-article-template/14272' target='_blank' rel='nofollow'>**`Wiki Challenge Solution Template`**</a> for reference. <add>### Resources <add>- ["Object.freeze()" - *MDN Javascript reference*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze)
1
Python
Python
fix stack overflow
59da3f270004088c04ceddac769f3ea41b881f5b
<ide><path>src/transformers/tokenization_utils_base.py <ide> def n_sequences(self) -> Optional[int]: <ide> :class:`~transformers.BatchEncoding`. Currently can be one of :obj:`None` (unknown), :obj:`1` (a single <ide> sentence) or :obj:`2` (a pair of sentences) <ide> """ <del> return self.n_sequences <add> return self._n_sequences <ide> <ide> @property <ide> def is_fast(self) -> bool:
1
PHP
PHP
fix documentation of fetchassoc() return value
84e89fcc7bfd5aba24bf26e1bbb9e533bb425381
<ide><path>src/Database/Statement/StatementDecorator.php <ide> public function fetch($type = self::FETCH_TYPE_NUM) <ide> <ide> /** <ide> * Returns the next row in a result set as an associative array. Calling this function is the same as calling <del> * $statement->fetch(StatementDecorator::FETCH_TYPE_ASSOC). If no results are found false is returned. <add> * $statement->fetch(StatementDecorator::FETCH_TYPE_ASSOC). If no results are found an empty array is returned. <ide> * <del> * @return array Result array containing columns and values an an associative array or an empty array if no results <add> * @return array <ide> */ <ide> public function fetchAssoc(): array <ide> {
1
Go
Go
fix vet warning in devicemapper
6b764bba8ad1c1006dadf24ec55edb9de200c706
<ide><path>pkg/devicemapper/devmapper.go <ide> import ( <ide> "os" <ide> "runtime" <ide> "syscall" <add> "unsafe" <ide> <ide> log "github.com/Sirupsen/logrus" <ide> ) <ide> func (t *Task) GetDriverVersion() (string, error) { <ide> return res, nil <ide> } <ide> <del>func (t *Task) GetNextTarget(next uintptr) (nextPtr uintptr, start uint64, <add>func (t *Task) GetNextTarget(next unsafe.Pointer) (nextPtr unsafe.Pointer, start uint64, <ide> length uint64, targetType string, params string) { <ide> <ide> return DmGetNextTarget(t.unmanaged, next, &start, &length, <ide> func GetStatus(name string) (uint64, uint64, string, string, error) { <ide> return 0, 0, "", "", fmt.Errorf("Non existing device %s", name) <ide> } <ide> <del> _, start, length, targetType, params := task.GetNextTarget(0) <add> _, start, length, targetType, params := task.GetNextTarget(unsafe.Pointer(nil)) <ide> return start, length, targetType, params, nil <ide> } <ide> <ide><path>pkg/devicemapper/devmapper_wrapper.go <ide> func dmTaskGetDriverVersionFct(task *CDmTask) string { <ide> return C.GoString((*C.char)(buffer)) <ide> } <ide> <del>func dmGetNextTargetFct(task *CDmTask, next uintptr, start, length *uint64, target, params *string) uintptr { <add>func dmGetNextTargetFct(task *CDmTask, next unsafe.Pointer, start, length *uint64, target, params *string) unsafe.Pointer { <ide> var ( <ide> Cstart, Clength C.uint64_t <ide> CtargetType, Cparams *C.char <ide> func dmGetNextTargetFct(task *CDmTask, next uintptr, start, length *uint64, targ <ide> *params = C.GoString(Cparams) <ide> }() <ide> <del> nextp := C.dm_get_next_target((*C.struct_dm_task)(task), unsafe.Pointer(next), &Cstart, &Clength, &CtargetType, &Cparams) <del> return uintptr(nextp) <add> nextp := C.dm_get_next_target((*C.struct_dm_task)(task), next, &Cstart, &Clength, &CtargetType, &Cparams) <add> return nextp <ide> } <ide> <ide> func dmUdevSetSyncSupportFct(syncWithUdev int) {
2
Python
Python
drop random.choice() in basehook.get_connection()
74ed92b3ff34fa3b6af27c17f44ad4573b517bbd
<ide><path>airflow/hooks/base_hook.py <ide> # under the License. <ide> """Base class for all hooks""" <ide> import logging <del>import random <ide> from typing import Any, List <ide> <ide> from airflow.models.connection import Connection <ide> class BaseHook(LoggingMixin): <ide> @classmethod <ide> def get_connections(cls, conn_id: str) -> List[Connection]: <ide> """ <del> Get all connections as an iterable. <add> Get all connections as an iterable, given the connection id. <ide> <ide> :param conn_id: connection id <ide> :return: array of connections <ide> def get_connections(cls, conn_id: str) -> List[Connection]: <ide> @classmethod <ide> def get_connection(cls, conn_id: str) -> Connection: <ide> """ <del> Get random connection selected from all connections configured with this connection id. <add> Get connection, given connection id. <ide> <ide> :param conn_id: connection id <ide> :return: connection <ide> """ <del> conn = random.choice(cls.get_connections(conn_id)) <add> conn = cls.get_connections(conn_id)[0] <ide> if conn.host: <ide> log.info( <ide> "Using connection to: id: %s. Host: %s, Port: %s, Schema: %s, Login: %s, Password: %s, "
1
PHP
PHP
use logs constant
15a74722b34be6b64f4c20b413c5fa84f3666132
<ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php <ide> public function testLog() { <ide> $this->assertRegExp('/DebuggerTest\:\:testLog/i', $result); <ide> $this->assertRegExp("/'cool'/", $result); <ide> <del> unlink(TMP . 'logs' . DS . 'debug.log'); <add> unlink(LOGS . 'debug.log'); <ide> <ide> Debugger::log(array('whatever', 'here')); <del> $result = file_get_contents(TMP . 'logs' . DS . 'debug.log'); <add> $result = file_get_contents(LOGS . 'debug.log'); <ide> $this->assertRegExp('/DebuggerTest\:\:testLog/i', $result); <ide> $this->assertRegExp('/\[main\]/', $result); <ide> $this->assertRegExp('/array/', $result);
1
Text
Text
add 2.15.3 to changelog.md
922aed6f70b6daae16a0c0c5a351d9e243916c77
<ide><path>CHANGELOG.md <ide> - [#15528](https://github.com/emberjs/ember.js/pull/15528) [DEPRECATION] Deprecate `Controller#content` alias. <ide> - [#15552](https://github.com/emberjs/ember.js/pull/15552) [FEATURE] Update blueprints and tests to RFC #176. <ide> <add>### 2.15.3 (October 9, 2017) <add> <add>- [#15718](https://github.com/emberjs/ember.js/pull/15718) [BUGFIX] bump backburner (fixes clock + autorun interop) <add> <ide> ### 2.15.2 (October 4, 2017) <ide> <ide> - [#15604](https://github.com/emberjs/ember.js/pull/15604) [BUGFIX] Ember Inspector Data Adapter: Only trigger model type update if the record live array count actually changed.
1
Javascript
Javascript
use environ to run compares more than once
db5d58e84252042236b8de80fe0e1b722a83e61a
<ide><path>benchmark/compare.js <del>var usage = 'node benchmark/compare.js <node-binary1> <node-binary2> [--html] [--red|-r] [--green|-g]'; <add>var usage = 'node benchmark/compare.js ' + <add> '<node-binary1> <node-binary2> ' + <add> '[--html] [--red|-r] [--green|-g]'; <ide> <ide> var show = 'both'; <ide> var nodes = []; <ide> if (!html) { <ide> var runBench = process.env.NODE_BENCH || 'bench'; <ide> <ide> if (nodes.length !== 2) <del> return console.error('usage:\n %s', usage); <add> return console.error('usage:\n %s', usage); <ide> <ide> var spawn = require('child_process').spawn; <ide> var results = {}; <del>var n = 2; <add>var n = 1; <ide> <ide> run(); <ide> <add>var RUNS = +process.env.NODE_BENCH_RUNS || 1; <add>var r = RUNS; <ide> function run() { <del> if (n === 0) <del> return compare(); <add> // Flip back and forth between the two binaries. <add> if (n === 1) { <add> n--; <add> } else { <add> r--; <add> if (r === 0) <add> return compare(); <add> else <add> n++; <add> } <ide> <del> n--; <add> if (n === -1) <add> return compare(); <ide> <del> var node = nodes[n]; <add> var node = nodes[n]; <ide> console.error('running %s', node); <del> var env = {}; <add> var env = {}; <ide> for (var i in process.env) <ide> env[i] = process.env[i]; <ide> env.NODE = node; <del> var child = spawn('make', [ runBench ], { env: env }); <add> var child = spawn('make', [runBench], { env: env }); <ide> <del> var out = ''; <del> child.stdout.setEncoding('utf8'); <del> child.stdout.on('data', function(c) { <del> out += c; <del> }); <add> var out = ''; <add> child.stdout.setEncoding('utf8'); <add> child.stdout.on('data', function(c) { <add> out += c; <add> }); <ide> <ide> child.stderr.pipe(process.stderr); <ide> <del> child.on('close', function(code) { <del> if (code) { <del> console.error('%s exited with code=%d', node, code); <del> process.exit(code); <del> } else { <del> out.trim().split(/\r?\n/).forEach(function(line) { <add> child.on('close', function(code) { <add> if (code) { <add> console.error('%s exited with code=%d', node, code); <add> process.exit(code); <add> } else { <add> out.trim().split(/\r?\n/).forEach(function(line) { <ide> line = line.trim(); <ide> if (!line) <ide> return; <ide> <del> var s = line.split(':'); <del> var num = +s.pop(); <del> if (!num && num !== 0) <del> return <add> var s = line.split(':'); <add> var num = +s.pop(); <add> if (!num && num !== 0) <add> return; <ide> <del> line = s.join(':'); <del> var res = results[line] = results[line] || {}; <del> res[node] = num; <del> }); <add> line = s.join(':'); <add> var res = results[line] = results[line] || {}; <add> res[node] = res[node] || []; <add> res[node].push(num); <add> }); <ide> <del> run(); <del> } <del> }); <add> run(); <add> } <add> }); <ide> } <ide> <ide> function compare() { <del> // each result is an object with {"foo.js arg=bar":12345,...} <del> // compare each thing, and show which node did the best. <add> // each result is an object with {"foo.js arg=bar":12345,...} <add> // compare each thing, and show which node did the best. <ide> // node[0] is shown in green, node[1] shown in red. <ide> var maxLen = -Infinity; <ide> var util = require('util'); <ide> console.log(start); <ide> <del> Object.keys(results).map(function(bench) { <add> Object.keys(results).map(function(bench) { <ide> var res = results[bench]; <del> var n0 = res[nodes[0]]; <del> var n1 = res[nodes[1]]; <add> var n0 = avg(res[nodes[0]]); <add> var n1 = avg(res[nodes[1]]); <ide> <ide> var pct = ((n0 - n1) / n1 * 100).toFixed(2); <ide> <ide> function compare() { <ide> if (show === 'green' && !g || show === 'red' && !r) <ide> return; <ide> <del> var r0 = util.format('%s%s: %d%s', g, nodes[0], n0, reset); <del> var r1 = util.format('%s%s: %d%s', r, nodes[1], n1, reset); <add> var r0 = util.format('%s%s: %d%s', g, nodes[0], n0, g ? reset : ''); <add> var r1 = util.format('%s%s: %d%s', r, nodes[1], n1, r ? reset : ''); <ide> var pct = c + pct + '%' + reset; <ide> var l = util.format('%s: %s %s', bench, r0, r1); <ide> maxLen = Math.max(l.length + pct.length, maxLen); <ide> function compare() { <ide> }); <ide> console.log(end); <ide> } <add> <add>function avg(list) { <add> if (list.length >= 3) { <add> list = list.sort(); <add> var q = Math.floor(list.length / 4) || 1; <add> list = list.slice(q, -q); <add> } <add> return (list.reduce(function(a, b) { <add> return a + b; <add> }, 0) / list.length).toPrecision(5); <add>}
1
Go
Go
remove unnecessary error returns
990655448dec63ef8add376becb1a20ae184a162
<ide><path>daemon/daemon.go <ide> func (daemon *Daemon) stats(c *Container) (*execdriver.ResourceStats, error) { <ide> return daemon.execDriver.Stats(c.ID) <ide> } <ide> <del>func (daemon *Daemon) subscribeToContainerStats(c *Container) (chan interface{}, error) { <del> ch := daemon.statsCollector.collect(c) <del> return ch, nil <add>func (daemon *Daemon) subscribeToContainerStats(c *Container) chan interface{} { <add> return daemon.statsCollector.collect(c) <ide> } <ide> <del>func (daemon *Daemon) unsubscribeToContainerStats(c *Container, ch chan interface{}) error { <add>func (daemon *Daemon) unsubscribeToContainerStats(c *Container, ch chan interface{}) { <ide> daemon.statsCollector.unsubscribe(c, ch) <del> return nil <ide> } <ide> <ide> func (daemon *Daemon) changes(container *Container) ([]archive.Change, error) { <ide><path>daemon/stats.go <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> return json.NewEncoder(config.OutStream).Encode(&types.Stats{}) <ide> } <ide> <del> updates, err := daemon.subscribeToContainerStats(container) <del> if err != nil { <del> return err <del> } <del> <ide> if config.Stream { <ide> // Write an empty chunk of data. <ide> // This is to ensure that the HTTP status code is sent immediately, <ide> func (daemon *Daemon) ContainerStats(prefixOrName string, config *ContainerStats <ide> <ide> enc := json.NewEncoder(config.OutStream) <ide> <add> updates := daemon.subscribeToContainerStats(container) <ide> defer daemon.unsubscribeToContainerStats(container, updates) <ide> <ide> noStreamFirstFrame := true
2
Go
Go
fix multiple attach test
01094c15680c0a33367e1dcc69ec9f4018efd2ac
<ide><path>integration-cli/docker_cli_attach_test.go <ide> package main <ide> <ide> import ( <add> "io" <ide> "os/exec" <ide> "strings" <ide> "sync" <ide> "testing" <ide> "time" <ide> ) <ide> <add>const attachWait = 5 * time.Second <add> <ide> func TestMultipleAttachRestart(t *testing.T) { <del> cmd := exec.Command(dockerBinary, "run", "--name", "attacher", "-d", "busybox", <del> "/bin/sh", "-c", "sleep 2 && echo hello") <del> <del> group := sync.WaitGroup{} <del> group.Add(4) <del> <del> defer func() { <del> cmd = exec.Command(dockerBinary, "kill", "attacher") <del> if _, err := runCommand(cmd); err != nil { <del> t.Fatal(err) <del> } <del> deleteAllContainers() <add> defer deleteAllContainers() <add> <add> endGroup := &sync.WaitGroup{} <add> startGroup := &sync.WaitGroup{} <add> endGroup.Add(3) <add> startGroup.Add(3) <add> <add> if err := waitForContainer("attacher", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 1; echo hello; done"); err != nil { <add> t.Fatal(err) <add> } <add> <add> startDone := make(chan struct{}) <add> endDone := make(chan struct{}) <add> <add> go func() { <add> endGroup.Wait() <add> close(endDone) <ide> }() <ide> <ide> go func() { <del> defer group.Done() <del> out, _, err := runCommandWithOutput(cmd) <del> if err != nil { <del> t.Fatal(err, out) <del> } <add> startGroup.Wait() <add> close(startDone) <ide> }() <del> time.Sleep(500 * time.Millisecond) <ide> <ide> for i := 0; i < 3; i++ { <ide> go func() { <del> defer group.Done() <ide> c := exec.Command(dockerBinary, "attach", "attacher") <ide> <del> out, _, err := runCommandWithOutput(c) <add> defer func() { <add> c.Wait() <add> endGroup.Done() <add> }() <add> <add> out, err := c.StdoutPipe() <ide> if err != nil { <del> t.Fatal(err, out) <add> t.Fatal(err) <add> } <add> <add> if _, err := startCommand(c); err != nil { <add> t.Fatal(err) <ide> } <del> if actual := strings.Trim(out, "\r\n"); actual != "hello" { <del> t.Fatalf("unexpected output %s expected hello", actual) <add> <add> buf := make([]byte, 1024) <add> <add> if _, err := out.Read(buf); err != nil && err != io.EOF { <add> t.Fatal(err) <add> } <add> <add> startGroup.Done() <add> <add> if !strings.Contains(string(buf), "hello") { <add> t.Fatalf("unexpected output %s expected hello\n", string(buf)) <ide> } <ide> }() <ide> } <ide> <del> group.Wait() <add> select { <add> case <-startDone: <add> case <-time.After(attachWait): <add> t.Fatalf("Attaches did not initialize properly") <add> } <add> <add> cmd := exec.Command(dockerBinary, "kill", "attacher") <add> if _, err := runCommand(cmd); err != nil { <add> t.Fatal(err) <add> } <add> <add> select { <add> case <-endDone: <add> case <-time.After(attachWait): <add> t.Fatalf("Attaches did not finish properly") <add> } <ide> <ide> logDone("attach - multiple attach") <ide> } <ide><path>integration-cli/utils.go <ide> import ( <ide> "strings" <ide> "syscall" <ide> "testing" <add> "time" <ide> ) <ide> <ide> func getExitCode(err error) (int, error) { <ide> func convertSliceOfStringsToMap(input []string) map[string]struct{} { <ide> } <ide> return output <ide> } <add> <add>func waitForContainer(contId string, args ...string) error { <add> args = append([]string{"run", "--name", contId}, args...) <add> cmd := exec.Command(dockerBinary, args...) <add> if _, err := runCommand(cmd); err != nil { <add> return err <add> } <add> <add> if err := waitRun(contId); err != nil { <add> return err <add> } <add> <add> return nil <add>} <add> <add>func waitRun(contId string) error { <add> after := time.After(5 * time.Second) <add> <add> for { <add> cmd := exec.Command(dockerBinary, "inspect", "-f", "{{.State.Running}}", contId) <add> out, _, err := runCommandWithOutput(cmd) <add> if err != nil { <add> return fmt.Errorf("error executing docker inspect: %v", err) <add> } <add> <add> if strings.Contains(out, "true") { <add> break <add> } <add> <add> select { <add> case <-after: <add> return fmt.Errorf("container did not come up in time") <add> default: <add> } <add> <add> time.Sleep(100 * time.Millisecond) <add> } <add> <add> return nil <add>}
2
Python
Python
resolve line-too-long in api
4cb8159165ca3738e18ce699fee8f7af829fc1f9
<ide><path>keras/api/tests/api_compatibility_test.py <ide> def _FilterGoldenProtoDict(golden_proto_dict, omit_golden_symbols_map): <ide> filtered_members = [ <ide> m for m in members if m.name not in symbol_list <ide> ] <del> # Two steps because protobuf repeated fields disallow slice assignment. <add> # Two steps because protobuf repeated fields disallow slice <add> # assignment. <ide> del members[:] <ide> members.extend(filtered_members) <ide> return filtered_proto_dict <ide> def _AssertProtoDictEquals( <ide> """Diff given dicts of protobufs and report differences a readable way. <ide> <ide> Args: <del> expected_dict: a dict of TFAPIObject protos constructed from golden files. <del> actual_dict: a ict of TFAPIObject protos constructed by reading from the <del> TF package linked to the test. <del> verbose: Whether to log the full diffs, or simply report which files were <del> different. <add> expected_dict: a dict of TFAPIObject protos constructed from golden <add> files. <add> actual_dict: a ict of TFAPIObject protos constructed by reading from <add> the TF package linked to the test. <add> verbose: Whether to log the full diffs, or simply report which files <add> were different. <ide> update_goldens: Whether to update goldens when there are diffs found. <ide> additional_missing_object_message: Message to print when a symbol is <ide> missing. <ide> def _AssertProtoDictEquals( <ide> diff_message = "Change detected in python object: %s." % key <ide> verbose_diff_message = str(e) <ide> <del> # All difference cases covered above. If any difference found, add to the <del> # list. <add> # All difference cases covered above. If any difference found, add <add> # to the list. <ide> if diff_message: <ide> diffs.append(diff_message) <ide> verbose_diffs.append(verbose_diff_message) <ide> def _AssertProtoDictEquals( <ide> filepath = _KeyToFilePath(key, api_version) <ide> tf.io.gfile.remove(filepath) <ide> <del> # If the files are only in actual (current library), these are new <del> # modules. Write them to files. Also record all updates in files. <add> # If the files are only in actual (current library), these are <add> # new modules. Write them to files. Also record all updates in <add> # files. <ide> for key in only_in_actual | set(updated_keys): <ide> filepath = _KeyToFilePath(key, api_version) <ide> file_io.write_string_to_file( <ide> def _ReadFileToProto(filename): <ide> ) <ide> <ide> # Diff them. Do not fail if called with update. <del> # If the test is run to update goldens, only report diffs but do not fail. <add> # If the test is run to update goldens, only report diffs but do not <add> # fail. <ide> self._AssertProtoDictEquals( <ide> golden_proto_dict, <ide> proto_dict,
1
Javascript
Javascript
remove console.logs and fix code style
3130a82b21691deaedbd7ee01ad3e970b386c0a6
<ide><path>lib/versions/version-info.js <ide> var currentPackage, previousVersions, cdnVersion, gitRepoInfo; <ide> var getPackage = function() { <ide> // Search up the folder hierarchy for the first package.json <ide> var packageFolder = path.resolve('.'); <del> while ( !fs.existsSync(path.join(packageFolder, 'package.json')) ) { <add> while (!fs.existsSync(path.join(packageFolder, 'package.json'))) { <ide> var parent = path.dirname(packageFolder); <del> if ( parent === packageFolder) { break; } <add> if (parent === packageFolder) { break; } <ide> packageFolder = parent; <ide> } <ide> return JSON.parse(fs.readFileSync(path.join(packageFolder,'package.json'), 'UTF-8')); <ide> var getGitRepoInfo = function() { <ide> * @return {String} The codename if found, otherwise null/undefined <ide> */ <ide> var getCodeName = function(tagName) { <del> var gitCatOutput = shell.exec('git cat-file -p '+ tagName, {silent:true}).output; <add> var gitCatOutput = shell.exec('git cat-file -p ' + tagName, {silent:true}).output; <ide> var tagMessage = gitCatOutput.match(/^.*codename.*$/mg)[0]; <ide> var codeName = tagMessage && tagMessage.match(/codename\((.*)\)/)[1]; <ide> if (!codeName) { <del> throw new Error("Could not extract release code name. The message of tag "+tagName+ <add> throw new Error("Could not extract release code name. The message of tag " + tagName + <ide> " must match '*codename(some release name)*'"); <ide> } <ide> return codeName; <ide> var getCodeName = function(tagName) { <ide> */ <ide> function getBuild() { <ide> var hash = shell.exec('git rev-parse --short HEAD', {silent: true}).output.replace('\n', ''); <del> return 'sha.'+hash; <add> return 'sha.' + hash; <ide> } <ide> <ide> <ide> function getBuild() { <ide> var getTaggedVersion = function() { <ide> var gitTagResult = shell.exec('git describe --exact-match', {silent:true}); <ide> <del> if ( gitTagResult.code === 0 ) { <add> if (gitTagResult.code === 0) { <ide> var tag = gitTagResult.output.trim(); <ide> var version = semver.parse(tag); <ide> <del> if ( version && semver.satisfies(version, currentPackage.branchVersion)) { <add> if (version && semver.satisfies(version, currentPackage.branchVersion)) { <ide> version.codeName = getCodeName(tag); <ide> version.full = version.version; <ide> version.branch = 'v' + currentPackage.branchPattern.replace('*', 'x'); <ide> var getPreviousVersions = function() { <ide> var repo_url = currentPackage.repository.url; <ide> var tagResults = shell.exec('git ls-remote --tags ' + repo_url, <ide> {silent: true}); <del> if ( tagResults.code === 0 ) { <add> if (tagResults.code === 0) { <ide> return _(tagResults.output.match(/v[0-9].*[0-9]$/mg)) <ide> .map(function(tag) { <ide> var version = semver.parse(tag); <ide> var getPreviousVersions = function() { <ide> .map(function(version) { <ide> version.docsUrl = 'http://code.angularjs.org/' + version.version + '/docs'; <ide> // Versions before 1.0.2 had a different docs folder name <del> if ( version.major < 1 || (version.major === 1 && version.minor === 0 && version.dot < 2 ) ) { <add> if (version.major < 1 || (version.major === 1 && version.minor === 0 && version.dot < 2)) { <ide> version.docsUrl += '-' + version.version; <ide> } <ide> return version; <ide> var getCdnVersion = function() { <ide> return semver.satisfies(tag, currentPackage.branchVersion); <ide> }) <ide> .reverse() <del> .tap(function(versions) { <del> console.log(versions); <del> }) <ide> .reduce(function(cdnVersion, version) { <ide> if (!cdnVersion) { <ide> // Note: need to use shell.exec and curl here <ide> // as version-infos returns its result synchronously... <del> var cdnResult = shell.exec('curl http://ajax.googleapis.com/ajax/libs/angularjs/'+version+'/angular.min.js '+ <add> var cdnResult = shell.exec('curl http://ajax.googleapis.com/ajax/libs/angularjs/' + version + '/angular.min.js ' + <ide> '--head --write-out "%{http_code}" -o /dev/null -silent', <ide> {silent: false}); <del> console.log('http://ajax.googleapis.com/ajax/libs/angularjs/'+version+'/angular.min.js'); <del> if ( cdnResult.code === 0 ) { <add> if (cdnResult.code === 0) { <ide> var statusCode = cdnResult.output.trim(); <ide> if (statusCode === '200') { <ide> cdnVersion = version; <ide> var getSnapshotVersion = function() { <ide> }) <ide> .last(); <ide> <del> if ( !version ) { <add> if (!version) { <ide> // a snapshot version before the first tag on the branch <ide> version = semver(currentPackage.branchPattern.replace('*','0-beta.1')); <ide> }
1
Javascript
Javascript
report history false on android < 4
7b739c97028be2a5d5aef679ef1f8064cd10d386
<ide><path>src/ng/sniffer.js <ide> */ <ide> function $SnifferProvider() { <ide> this.$get = ['$window', function($window) { <del> var eventSupport = {}; <add> var eventSupport = {}, <add> android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]); <ide> <ide> return { <del> history: !!($window.history && $window.history.pushState), <add> // Android has history.pushState, but it does not update location correctly <add> // so let's not use the history API at all. <add> // http://code.google.com/p/android/issues/detail?id=17471 <add> // https://github.com/angular/angular.js/issues/904 <add> history: !!($window.history && $window.history.pushState && !(android < 4)), <ide> hashchange: 'onhashchange' in $window && <ide> // IE8 compatible mode lies <ide> (!$window.document.documentMode || $window.document.documentMode > 7), <ide><path>test/ng/anchorScrollSpec.js <ide> describe('$anchorScroll', function() { <ide> elmSpy = {}; <ide> $provide.value('$window', { <ide> scrollTo: jasmine.createSpy('$window.scrollTo'), <del> document: document <add> document: document, <add> navigator: {} <ide> }); <ide> })); <ide> <ide><path>test/ng/logSpec.js <ide> describe('$log', function() { <ide> <ide> <ide> beforeEach(module(function($provide){ <del> $window = {}; <add> $window = {navigator: {}}; <ide> logger = ''; <ide> log = function() { logger+= 'log;'; }; <ide> warn = function() { logger+= 'warn;'; }; <ide><path>test/ng/snifferSpec.js <ide> describe('$sniffer', function() { <ide> <ide> function sniffer($window) { <add> $window.navigator = {}; <ide> return new $SnifferProvider().$get[1]($window); <ide> } <ide>
4
Ruby
Ruby
fix typo s/limitions/limitations/ [ci skip]
90db24436a55b7b004c07ff46ed238bfff5f06b2
<ide><path>activerecord/lib/active_record/associations.rb <ide> module ClassMethods <ide> # [:disable_joins] <ide> # Specifies whether joins should be skipped for an association. If set to true, two or more queries <ide> # will be generated. Note that in some cases, if order or limit is applied, it will be done in-memory <del> # due to database limitions. This option is only applicable on `has_many :through` associations as <add> # due to database limitations. This option is only applicable on `has_many :through` associations as <ide> # `has_many` alone do not perform a join. <ide> # <ide> # If the association on the join model is a #belongs_to, the collection can be modified
1
Javascript
Javascript
exclude forwardref and memo from stack frames
cbab25bb5159e82f0d74b0d2ad84d7ad7dd3613a
<ide><path>packages/react-reconciler/src/ReactFiberComponentStack.js <ide> import { <ide> FunctionComponent, <ide> IndeterminateComponent, <ide> ForwardRef, <del> MemoComponent, <ide> SimpleMemoComponent, <ide> Block, <ide> ClassComponent, <ide> function describeFiber(fiber: Fiber): string { <ide> return describeFunctionComponentFrame(fiber.type, source, owner); <ide> case ForwardRef: <ide> return describeFunctionComponentFrame(fiber.type.render, source, owner); <del> case MemoComponent: <del> return describeFunctionComponentFrame(fiber.type.type, source, owner); <ide> case Block: <ide> return describeFunctionComponentFrame(fiber.type._render, source, owner); <ide> case ClassComponent: <ide><path>packages/react-reconciler/src/__tests__/ReactMemo-test.js <ide> describe('memo', () => { <ide> Outer.defaultProps = {outer: 0}; <ide> <ide> // No warning expected because defaultProps satisfy both. <del> ReactNoop.render(<Outer />); <add> ReactNoop.render( <add> <div> <add> <Outer /> <add> </div>, <add> ); <ide> expect(Scheduler).toFlushWithoutYielding(); <ide> <ide> // Mount <ide> expect(() => { <del> ReactNoop.render(<Outer inner="2" middle="3" outer="4" />); <add> ReactNoop.render( <add> <div> <add> <Outer inner="2" middle="3" outer="4" /> <add> </div>, <add> ); <ide> expect(Scheduler).toFlushWithoutYielding(); <ide> }).toErrorDev([ <ide> 'Invalid prop `outer` of type `string` supplied to `Inner`, expected `number`.', <ide> describe('memo', () => { <ide> // Update <ide> expect(() => { <ide> ReactNoop.render( <del> <Outer inner={false} middle={false} outer={false} />, <add> <div> <add> <Outer inner={false} middle={false} outer={false} /> <add> </div>, <ide> ); <ide> expect(Scheduler).toFlushWithoutYielding(); <ide> }).toErrorDev([ <ide><path>packages/shared/ReactComponentStackFrame.js <ide> export function describeUnknownElementTypeFrameInDEV( <ide> case REACT_FORWARD_REF_TYPE: <ide> return describeFunctionComponentFrame(type.render, source, ownerFn); <ide> case REACT_MEMO_TYPE: <del> return describeFunctionComponentFrame(type.type, source, ownerFn); <add> // Memo may contain any component type so we recursively resolve it. <add> return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); <ide> case REACT_BLOCK_TYPE: <ide> return describeFunctionComponentFrame(type._render, source, ownerFn); <ide> case REACT_LAZY_TYPE: { <ide> const lazyComponent: LazyComponent<any, any> = (type: any); <ide> const payload = lazyComponent._payload; <ide> const init = lazyComponent._init; <ide> try { <add> // Lazy may contain any component type so we recursively resolve it. <ide> return describeUnknownElementTypeFrameInDEV( <ide> init(payload), <ide> source,
3
Javascript
Javascript
move instrumentation to the node managers
5f1cba209b0025d976c3bd5053ea1eea052f5d73
<ide><path>packages/ember-htmlbars/lib/keywords/collection.js <ide> <ide> import { readViewFactory } from "ember-views/streams/utils"; <ide> import CollectionView from "ember-views/views/collection_view"; <del>import ComponentNode from "ember-htmlbars/system/component-node"; <add>import ViewNodeManager from "ember-htmlbars/node-managers/view-node-manager"; <ide> import objectKeys from "ember-metal/keys"; <ide> import { assign } from "ember-metal/merge"; <ide> <ide> export default { <ide> hash.emptyViewClass = hash.emptyView; <ide> } <ide> <del> var componentNode = ComponentNode.create(node, env, hash, options, parentView, null, scope, template); <add> var componentNode = ViewNodeManager.create(node, env, hash, options, parentView, null, scope, template); <ide> state.manager = componentNode; <ide> <ide> componentNode.render(env, hash, visitor); <ide><path>packages/ember-htmlbars/lib/keywords/customized_outlet.js <ide> @submodule ember-htmlbars <ide> */ <ide> <del>import ComponentNode from "ember-htmlbars/system/component-node"; <add>import ViewNodeManager from "ember-htmlbars/node-managers/view-node-manager"; <ide> import { readViewFactory } from "ember-views/streams/utils"; <ide> import { isStream } from "ember-metal/streams/utils"; <ide> <ide> export default { <ide> var options = { <ide> component: state.viewClass <ide> }; <del> var componentNode = ComponentNode.create(renderNode, env, hash, options, parentView, null, null, null); <add> var componentNode = ViewNodeManager.create(renderNode, env, hash, options, parentView, null, null, null); <ide> state.manager = componentNode; <ide> componentNode.render(env, hash, visitor); <ide> } <ide><path>packages/ember-htmlbars/lib/keywords/real_outlet.js <ide> */ <ide> <ide> import { get } from "ember-metal/property_get"; <del>import ComponentNode from "ember-htmlbars/system/component-node"; <add>import ViewNodeManager from "ember-htmlbars/node-managers/view-node-manager"; <ide> import topLevelViewTemplate from "ember-htmlbars/templates/top-level-view"; <ide> topLevelViewTemplate.meta.revision = 'Ember@VERSION_STRING_PLACEHOLDER'; <ide> <ide> export default { <ide> Ember.Logger.info("Rendering " + toRender.name + " with " + ViewClass, { fullName: 'view:' + toRender.name }); <ide> } <ide> <del> var componentNode = ComponentNode.create(renderNode, env, {}, options, parentView, null, null, template); <add> var componentNode = ViewNodeManager.create(renderNode, env, {}, options, parentView, null, null, template); <ide> state.manager = componentNode; <ide> <ide> componentNode.render(env, hash, visitor); <ide><path>packages/ember-htmlbars/lib/keywords/view.js <ide> <ide> import { readViewFactory } from "ember-views/streams/utils"; <ide> import EmberView from "ember-views/views/view"; <del>import ComponentNode from "ember-htmlbars/system/component-node"; <add>import ViewNodeManager from "ember-htmlbars/node-managers/view-node-manager"; <ide> import objectKeys from "ember-metal/keys"; <ide> <ide> export default { <ide> export default { <ide> var parentView = state.parentView; <ide> <ide> var options = { component: node.state.viewClassOrInstance, layout: null }; <del> var componentNode = ComponentNode.create(node, env, hash, options, parentView, null, scope, template); <add> var componentNode = ViewNodeManager.create(node, env, hash, options, parentView, null, scope, template); <ide> state.manager = componentNode; <ide> <ide> componentNode.render(env, hash, visitor); <ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js <ide> import { set } from "ember-metal/property_set"; <ide> import setProperties from "ember-metal/set_properties"; <ide> import View from "ember-views/views/view"; <ide> import { MUTABLE_CELL } from "ember-views/compat/attrs-proxy"; <add>import { instrument } from "ember-htmlbars/system/instrumentation-support"; <ide> <ide> // In theory this should come through the env, but it should <ide> // be safe to import this until we make the hook system public <ide> ComponentNodeManager.create = function(renderNode, env, options) { <ide> ComponentNodeManager.prototype.render = function(env, visitor) { <ide> var { component, attrs } = this; <ide> <del> var newEnv = env; <del> if (component) { <del> newEnv = merge({}, env); <del> newEnv.view = component; <del> } <add> return instrument(component, function() { <ide> <del> if (component) { <del> var snapshot = takeSnapshot(attrs); <del> env.renderer.setAttrs(this.component, snapshot); <del> env.renderer.willCreateElement(component); <del> env.renderer.willRender(component); <del> env.renderedViews.push(component.elementId); <del> } <add> var newEnv = env; <add> if (component) { <add> newEnv = merge({}, env); <add> newEnv.view = component; <add> } <ide> <del> if (this.block) { <del> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <del> } <add> if (component) { <add> var snapshot = takeSnapshot(attrs); <add> env.renderer.setAttrs(this.component, snapshot); <add> env.renderer.willCreateElement(component); <add> env.renderer.willRender(component); <add> env.renderedViews.push(component.elementId); <add> } <ide> <del> if (component) { <del> var element = this.expectElement && this.renderNode.firstNode; <del> env.renderer.didCreateElement(component, element); // 2.0TODO: Remove legacy hooks. <del> env.renderer.willInsertElement(component, element); <del> env.lifecycleHooks.push({ type: 'didInsertElement', view: component }); <del> } <add> if (this.block) { <add> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <add> } <add> <add> if (component) { <add> var element = this.expectElement && this.renderNode.firstNode; <add> env.renderer.didCreateElement(component, element); // 2.0TODO: Remove legacy hooks. <add> env.renderer.willInsertElement(component, element); <add> env.lifecycleHooks.push({ type: 'didInsertElement', view: component }); <add> } <add> }, this); <ide> }; <ide> <ide> ComponentNodeManager.prototype.rerender = function(env, attrs, visitor) { <ide> var component = this.component; <add> return instrument(component, function() { <ide> <del> var newEnv = env; <del> if (component) { <del> newEnv = merge({}, env); <del> newEnv.view = component; <add> var newEnv = env; <add> if (component) { <add> newEnv = merge({}, env); <add> newEnv.view = component; <ide> <del> var snapshot = takeSnapshot(attrs); <add> var snapshot = takeSnapshot(attrs); <ide> <del> // Notify component that it has become dirty and is about to change. <del> env.renderer.willUpdate(component, snapshot); <add> // Notify component that it has become dirty and is about to change. <add> env.renderer.willUpdate(component, snapshot); <ide> <del> if (component._renderNode.shouldReceiveAttrs) { <del> env.renderer.updateAttrs(component, snapshot); <del> setProperties(component, mergeBindings({}, shadowedAttrs(component, snapshot))); <del> component._renderNode.shouldReceiveAttrs = false; <del> } <add> if (component._renderNode.shouldReceiveAttrs) { <add> env.renderer.updateAttrs(component, snapshot); <add> setProperties(component, mergeBindings({}, shadowedAttrs(component, snapshot))); <add> component._renderNode.shouldReceiveAttrs = false; <add> } <ide> <del> env.renderer.willRender(component); <add> env.renderer.willRender(component); <ide> <del> env.renderedViews.push(component.elementId); <del> } <add> env.renderedViews.push(component.elementId); <add> } <ide> <del> if (this.block) { <del> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <del> } <add> if (this.block) { <add> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <add> } <ide> <del> if (component) { <del> env.lifecycleHooks.push({ type: 'didUpdate', view: component }); <del> } <add> if (component) { <add> env.lifecycleHooks.push({ type: 'didUpdate', view: component }); <add> } <ide> <del> return newEnv; <add> return newEnv; <add> }, this); <ide> }; <ide> <ide> <add><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js <del><path>packages/ember-htmlbars/lib/system/component-node.js <ide> import View from "ember-views/views/view"; <ide> import { MUTABLE_CELL } from "ember-views/compat/attrs-proxy"; <ide> import getCellOrValue from "ember-htmlbars/hooks/get-cell-or-value"; <ide> import SafeString from "htmlbars-util/safe-string"; <add>import { instrument } from "ember-htmlbars/system/instrumentation-support"; <ide> <ide> // In theory this should come through the env, but it should <ide> // be safe to import this until we make the hook system public <ide> ComponentNode.create = function(renderNode, env, attrs, found, parentView, path, <ide> ComponentNode.prototype.render = function(env, attrs, visitor) { <ide> var component = this.component; <ide> <del> var newEnv = env; <del> if (component) { <del> newEnv = merge({}, env); <del> newEnv.view = component; <del> } <add> return instrument(component, function() { <ide> <del> if (component) { <del> var snapshot = takeSnapshot(attrs); <del> env.renderer.setAttrs(this.component, snapshot); <del> env.renderer.willCreateElement(component); <del> env.renderer.willRender(component); <del> env.renderedViews.push(component.elementId); <del> } <add> var newEnv = env; <add> if (component) { <add> newEnv = merge({}, env); <add> newEnv.view = component; <add> } <ide> <del> if (this.block) { <del> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <del> } <add> if (component) { <add> var snapshot = takeSnapshot(attrs); <add> env.renderer.setAttrs(this.component, snapshot); <add> env.renderer.willCreateElement(component); <add> env.renderer.willRender(component); <add> env.renderedViews.push(component.elementId); <add> } <ide> <del> if (component) { <del> var element = this.expectElement && this.renderNode.firstNode; <del> if (component.render) { <del> var content, node, lastChildIndex; <del> var buffer = []; <del> component.render(buffer); <del> content = buffer.join(''); <del> if (element) { <del> lastChildIndex = this.renderNode.childNodes.length - 1; <del> node = this.renderNode.childNodes[lastChildIndex]; <del> } else { <del> node = this.renderNode; <add> if (this.block) { <add> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <add> } <add> <add> if (component) { <add> var element = this.expectElement && this.renderNode.firstNode; <add> if (component.render) { <add> var content, node, lastChildIndex; <add> var buffer = []; <add> component.render(buffer); <add> content = buffer.join(''); <add> if (element) { <add> lastChildIndex = this.renderNode.childNodes.length - 1; <add> node = this.renderNode.childNodes[lastChildIndex]; <add> } else { <add> node = this.renderNode; <add> } <add> node.setContent(new SafeString(content)); <ide> } <del> node.setContent(new SafeString(content)); <add> <add> env.renderer.didCreateElement(component, element); // 2.0TODO: Remove legacy hooks. <add> env.renderer.willInsertElement(component, element); <add> env.lifecycleHooks.push({ type: 'didInsertElement', view: component }); <ide> } <add> }, this); <ide> <del> env.renderer.didCreateElement(component, element); // 2.0TODO: Remove legacy hooks. <del> env.renderer.willInsertElement(component, element); <del> env.lifecycleHooks.push({ type: 'didInsertElement', view: component }); <del> } <ide> }; <ide> <ide> ComponentNode.prototype.rerender = function(env, attrs, visitor) { <ide> var component = this.component; <ide> <del> var newEnv = env; <del> if (component) { <del> newEnv = merge({}, env); <del> newEnv.view = component; <add> return instrument(component, function() { <add> var newEnv = env; <add> if (component) { <add> newEnv = merge({}, env); <add> newEnv.view = component; <ide> <del> var snapshot = takeSnapshot(attrs); <add> var snapshot = takeSnapshot(attrs); <ide> <del> // Notify component that it has become dirty and is about to change. <del> env.renderer.willUpdate(component, snapshot); <add> // Notify component that it has become dirty and is about to change. <add> env.renderer.willUpdate(component, snapshot); <ide> <del> if (component._renderNode.shouldReceiveAttrs) { <del> env.renderer.updateAttrs(component, snapshot); <del> setProperties(component, mergeBindings({}, shadowedAttrs(component, snapshot))); <del> component._renderNode.shouldReceiveAttrs = false; <del> } <add> if (component._renderNode.shouldReceiveAttrs) { <add> env.renderer.updateAttrs(component, snapshot); <add> setProperties(component, mergeBindings({}, shadowedAttrs(component, snapshot))); <add> component._renderNode.shouldReceiveAttrs = false; <add> } <ide> <del> env.renderer.willRender(component); <add> env.renderer.willRender(component); <ide> <del> env.renderedViews.push(component.elementId); <del> } <del> <del> if (this.block) { <del> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <del> } <add> env.renderedViews.push(component.elementId); <add> } <add> if (this.block) { <add> this.block(newEnv, [], undefined, this.renderNode, this.scope, visitor); <add> } <ide> <del> if (component) { <del> env.lifecycleHooks.push({ type: 'didUpdate', view: component }); <del> } <add> if (component) { <add> env.lifecycleHooks.push({ type: 'didUpdate', view: component }); <add> } <ide> <del> return newEnv; <add> return newEnv; <add> }, this); <ide> }; <ide> <ide> export function createOrUpdateComponent(component, options, renderNode, env, attrs = {}) { <ide><path>packages/ember-htmlbars/lib/system/instrumentation-support.js <add>import { <add> _instrumentStart, <add> subscribers <add>} from "ember-metal/instrumentation"; <add> <add>/** <add> * Provides instrumentation for node managers. <add> * <add> * Wrap your node manager's render and re-render methods <add> * with this function. <add> * <add> * @param {Object} component Component or View instance (optional) <add> * @param {Function} callback The function to instrument <add> * @param {Object} context The context to call the function with <add> * @return {Object} Return value from the invoked callback <add> */ <add>export function instrument(component, callback, context) { <add> var instrumentName, val, details, end; <add> // Only instrument if there's at least one subscriber. <add> if (subscribers.length) { <add> if (component) { <add> instrumentName = component.instrumentName; <add> } else { <add> instrumentName = 'node'; <add> } <add> details = {}; <add> if (component) { <add> component.instrumentDetails(details); <add> } <add> end = _instrumentStart('render.' + instrumentName, function viewInstrumentDetails() { <add> return details; <add> }); <add> val = callback.call(context); <add> if (end) { <add> end(); <add> } <add> return val; <add> } else { <add> return callback.call(context); <add> } <add>} <ide><path>packages/ember-htmlbars/lib/system/render-view.js <ide> import defaultEnv from "ember-htmlbars/env"; <del>import ComponentNode, { createOrUpdateComponent } from "ember-htmlbars/system/component-node"; <add>import ViewNodeManager, { createOrUpdateComponent } from "ember-htmlbars/node-managers/view-node-manager"; <ide> <ide> // This function only gets called once per render of a "root view" (`appendTo`). Otherwise, <ide> // HTMLBars propagates the existing env and renders templates for a given render node. <ide> export function renderHTMLBarsBlock(view, block, renderNode) { <ide> <ide> view.env = env; <ide> createOrUpdateComponent(view, {}, renderNode, env); <del> var componentNode = new ComponentNode(view, null, renderNode, block, view.tagName !== ''); <add> var componentNode = new ViewNodeManager(view, null, renderNode, block, view.tagName !== ''); <ide> <ide> componentNode.render(env, {}); <ide> } <ide><path>packages/ember-metal-views/lib/renderer.js <ide> import run from "ember-metal/run_loop"; <ide> import { get } from "ember-metal/property_get"; <ide> import { set } from "ember-metal/property_set"; <del>import { <del> _instrumentStart, <del> subscribers <del>} from "ember-metal/instrumentation"; <ide> import buildComponentTemplate from "ember-views/system/build-component-template"; <ide> import { indexOf } from "ember-metal/enumerable_utils"; <ide> //import { deprecation } from "ember-views/compat/attrs-proxy"; <ide> Renderer.prototype.createElement = <ide> this.prerenderTopLevelView(view, morph); <ide> }; <ide> <del>Renderer.prototype.willCreateElement = function (view) { <del> if (subscribers.length && view.instrumentDetails) { <del> view._instrumentEnd = _instrumentStart('render.'+view.instrumentName, function viewInstrumentDetails() { <del> var details = {}; <del> view.instrumentDetails(details); <del> return details; <del> }); <del> } <del>}; // inBuffer <add>// inBuffer <add>Renderer.prototype.willCreateElement = function (/*view*/) {}; <ide> <ide> Renderer.prototype.didCreateElement = function (view, element) { <ide> if (element) { <ide> Renderer.prototype.didCreateElement = function (view, element) { <ide> if (view._transitionTo) { <ide> view._transitionTo('hasElement'); <ide> } <del> if (view._instrumentEnd) { <del> view._instrumentEnd(); <del> } <ide> }; // hasElement <ide> <ide> Renderer.prototype.willInsertElement = function (view) { <ide> Renderer.prototype.renderElementRemoval = <ide> } <ide> }; <ide> <del>Renderer.prototype.willRemoveElement = function (view) {}; <add>Renderer.prototype.willRemoveElement = function (/*view*/) {}; <ide> <ide> Renderer.prototype.willDestroyElement = function (view) { <ide> if (view._willDestroyElement) { <ide><path>packages/ember-routing-htmlbars/lib/keywords/render.js <ide> import { isStream, read } from "ember-metal/streams/utils"; <ide> import { camelize } from "ember-runtime/system/string"; <ide> import generateController from "ember-routing/system/generate_controller"; <ide> import { generateControllerFactory } from "ember-routing/system/generate_controller"; <del>import ComponentNode from "ember-htmlbars/system/component-node"; <add>import ViewNodeManager from "ember-htmlbars/node-managers/view-node-manager"; <ide> <ide> export default { <ide> willRender(renderNode, env) { <ide> export default { <ide> options.component = view; <ide> } <ide> <del> var componentNode = ComponentNode.create(node, env, hash, options, state.parentView, null, null, template); <add> var componentNode = ViewNodeManager.create(node, env, hash, options, state.parentView, null, null, template); <ide> state.manager = componentNode; <ide> <ide> if (router && params.length === 1) { <ide><path>packages/ember/tests/view_instrumentation_test.js <add>import EmberHandlebars from "ember-htmlbars/compat"; <add>import run from "ember-metal/run_loop"; <add>import $ from "ember-views/system/jquery"; <add>import { subscribe, unsubscribe } from "ember-metal/instrumentation"; <add> <add>var compile = EmberHandlebars.compile; <add> <add>var App, $fixture; <add> <add>function setupExample() { <add> // setup templates <add> Ember.TEMPLATES.application = compile("{{outlet}}"); <add> Ember.TEMPLATES.index = compile("<h1>Node 1</h1>"); <add> Ember.TEMPLATES.posts = compile("<h1>Node 1</h1>"); <add> <add> App.Router.map(function() { <add> this.route('posts'); <add> }); <add>} <add> <add>function handleURL(path) { <add> var router = App.__container__.lookup('router:main'); <add> return run(router, 'handleURL', path); <add>} <add> <add>QUnit.module("View Instrumentation", { <add> setup() { <add> run(function() { <add> App = Ember.Application.create({ <add> rootElement: '#qunit-fixture' <add> }); <add> App.deferReadiness(); <add> <add> App.Router.reopen({ <add> location: 'none' <add> }); <add> }); <add> <add> $fixture = $('#qunit-fixture'); <add> setupExample(); <add> }, <add> <add> teardown() { <add> run(App, 'destroy'); <add> App = null; <add> Ember.TEMPLATES = {}; <add> } <add>}); <add> <add>QUnit.test("Nodes without view instances are instrumented", function(assert) { <add> var called = false; <add> var subscriber = subscribe('render', { <add> before() { <add> called = true; <add> }, <add> after() {} <add> }); <add> run(App, 'advanceReadiness'); <add> assert.ok(called, 'Instrumentation called on first render'); <add> called = false; <add> handleURL('/posts'); <add> assert.ok(called, 'instrumentation called on transition to non-view backed route'); <add> unsubscribe(subscriber); <add>});
11
Go
Go
remove gotest.tools dependency
6ff6913ac46dfa6748f1c6a2dd34ad6dee80b495
<ide><path>pkg/signal/signal_linux_test.go <ide> import ( <ide> "syscall" <ide> "testing" <ide> "time" <del> <del> "gotest.tools/v3/assert" <del> is "gotest.tools/v3/assert/cmp" <ide> ) <ide> <ide> func TestCatchAll(t *testing.T) { <ide> func TestCatchAll(t *testing.T) { <ide> <ide> for sigStr := range listOfSignals { <ide> if signal, ok := SignalMap[sigStr]; ok { <del> syscall.Kill(syscall.Getpid(), signal) <add> _ = syscall.Kill(syscall.Getpid(), signal) <ide> s := <-sigs <del> assert.Check(t, is.Equal(s.String(), signal.String())) <add> if s.String() != signal.String() { <add> t.Errorf("expected: %q, got: %q", signal, s) <add> } <ide> } <ide> } <ide> } <ide> func TestCatchAllIgnoreSigUrg(t *testing.T) { <ide> defer StopCatch(sigs) <ide> <ide> err := syscall.Kill(syscall.Getpid(), syscall.SIGURG) <del> assert.NilError(t, err) <add> if err != nil { <add> t.Fatal(err) <add> } <ide> timer := time.NewTimer(1 * time.Second) <ide> defer timer.Stop() <ide> select { <ide> func TestStopCatch(t *testing.T) { <ide> signal := SignalMap["HUP"] <ide> channel := make(chan os.Signal, 1) <ide> CatchAll(channel) <del> syscall.Kill(syscall.Getpid(), signal) <add> _ = syscall.Kill(syscall.Getpid(), signal) <ide> signalString := <-channel <del> assert.Check(t, is.Equal(signalString.String(), signal.String())) <add> if signalString.String() != signal.String() { <add> t.Errorf("expected: %q, got: %q", signal, signalString) <add> } <ide> <ide> StopCatch(channel) <ide> _, ok := <-channel <del> assert.Check(t, is.Equal(ok, false)) <add> if ok { <add> t.Error("expected: !ok, got: ok") <add> } <ide> } <ide><path>pkg/signal/signal_test.go <ide> package signal // import "github.com/docker/docker/pkg/signal" <ide> import ( <ide> "syscall" <ide> "testing" <del> <del> "gotest.tools/v3/assert" <del> is "gotest.tools/v3/assert/cmp" <ide> ) <ide> <ide> func TestParseSignal(t *testing.T) { <del> _, checkAtoiError := ParseSignal("0") <del> assert.Check(t, is.Error(checkAtoiError, "Invalid signal: 0")) <add> _, err := ParseSignal("0") <add> expectedErr := "Invalid signal: 0" <add> if err == nil || err.Error() != expectedErr { <add> t.Errorf("expected %q, but got %v", expectedErr, err) <add> } <ide> <del> _, error := ParseSignal("SIG") <del> assert.Check(t, is.Error(error, "Invalid signal: SIG")) <add> _, err = ParseSignal("SIG") <add> expectedErr = "Invalid signal: SIG" <add> if err == nil || err.Error() != expectedErr { <add> t.Errorf("expected %q, but got %v", expectedErr, err) <add> } <ide> <ide> for sigStr := range SignalMap { <del> responseSignal, error := ParseSignal(sigStr) <del> assert.Check(t, error) <add> responseSignal, err := ParseSignal(sigStr) <add> if err != nil { <add> t.Error(err) <add> } <ide> signal := SignalMap[sigStr] <del> assert.Check(t, is.DeepEqual(signal, responseSignal)) <add> if responseSignal != signal { <add> t.Errorf("expected: %q, got: %q", signal, responseSignal) <add> } <ide> } <ide> } <ide> <ide> func TestValidSignalForPlatform(t *testing.T) { <ide> isValidSignal := ValidSignalForPlatform(syscall.Signal(0)) <del> assert.Check(t, is.Equal(false, isValidSignal)) <add> if isValidSignal { <add> t.Error("expected !isValidSignal") <add> } <ide> <ide> for _, sigN := range SignalMap { <ide> isValidSignal = ValidSignalForPlatform(sigN) <del> assert.Check(t, is.Equal(true, isValidSignal)) <add> if !isValidSignal { <add> t.Error("expected isValidSignal") <add> } <ide> } <ide> }
2
PHP
PHP
add a space
eb0d4340d81af3c99962cb15d7365b67fc866581
<ide><path>src/Illuminate/Foundation/Testing/TestCase.php <ide> public function assertSessionHasAll(array $bindings) <ide> { <ide> foreach ($bindings as $key => $value) <ide> { <del> if(is_int($key)) <add> if (is_int($key)) <ide> { <ide> $this->assertSessionHas($value); <ide> }
1
PHP
PHP
remove invalid context error on clone
0d2883a23a06f19e8cfd9c4b2658fcfc4ad2697f
<ide><path>src/View/Widget/DateTimeWidget.php <ide> protected function _deconstructDate($value, $options) <ide> <ide> $date = new DateTime(); <ide> } else { <add> /* @var \DateTime $value */ <ide> $date = clone $value; <ide> } <ide> } catch (Exception $e) {
1
Go
Go
implement docker top for containerd
2f27332836afbd114f942458459751e278a8ac25
<ide><path>daemon/top_windows.go <ide> func (daemon *Daemon) ContainerTop(name string, psArgs string) (*containertypes. <ide> procList.Titles = []string{"Name", "PID", "CPU", "Private Working Set"} <ide> <ide> for _, j := range s { <del> d := time.Duration((j.KernelTime100ns + j.UserTime100ns) * 100) // Combined time in nanoseconds <add> d := time.Duration((j.KernelTime_100Ns + j.UserTime_100Ns) * 100) // Combined time in nanoseconds <ide> procList.Processes = append(procList.Processes, []string{ <ide> j.ImageName, <del> fmt.Sprint(j.ProcessId), <add> fmt.Sprint(j.ProcessID), <ide> fmt.Sprintf("%02d:%02d:%02d.%03d", int(d.Hours()), int(d.Minutes())%60, int(d.Seconds())%60, int(d.Nanoseconds()/1000000)%1000), <ide> units.HumanSize(float64(j.MemoryWorkingSetPrivateBytes))}) <ide> } <ide><path>libcontainerd/local/local_windows.go <ide> func (c *client) Summary(_ context.Context, containerID string) ([]libcontainerd <ide> <ide> pl := make([]libcontainerdtypes.Summary, len(p)) <ide> for i := range p { <del> pl[i] = libcontainerdtypes.Summary(p[i]) <add> pl[i] = libcontainerdtypes.Summary{ <add> ImageName: p[i].ImageName, <add> CreatedAt: p[i].CreateTimestamp, <add> KernelTime_100Ns: p[i].KernelTime100ns, <add> MemoryCommitBytes: p[i].MemoryCommitBytes, <add> MemoryWorkingSetPrivateBytes: p[i].MemoryWorkingSetPrivateBytes, <add> MemoryWorkingSetSharedBytes: p[i].MemoryWorkingSetSharedBytes, <add> ProcessID: p[i].ProcessId, <add> UserTime_100Ns: p[i].UserTime100ns, <add> ExecID: "", <add> } <ide> } <ide> return pl, nil <ide> } <ide><path>libcontainerd/remote/client_windows.go <ide> import ( <ide> "os" <ide> "path/filepath" <ide> <add> "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/options" <ide> "github.com/containerd/containerd/cio" <del> "github.com/containerd/containerd/windows/hcsshimtypes" <add> <ide> libcontainerdtypes "github.com/docker/docker/libcontainerd/types" <ide> specs "github.com/opencontainers/runtime-spec/specs-go" <ide> "github.com/pkg/errors" <ide> const runtimeName = "io.containerd.runhcs.v1" <ide> <ide> func summaryFromInterface(i interface{}) (*libcontainerdtypes.Summary, error) { <ide> switch pd := i.(type) { <del> case *hcsshimtypes.ProcessDetails: <add> case *options.ProcessDetails: <ide> return &libcontainerdtypes.Summary{ <del> CreateTimestamp: pd.CreatedAt, <ide> ImageName: pd.ImageName, <del> KernelTime100ns: pd.KernelTime_100Ns, <add> CreatedAt: pd.CreatedAt, <add> KernelTime_100Ns: pd.KernelTime_100Ns, <ide> MemoryCommitBytes: pd.MemoryCommitBytes, <ide> MemoryWorkingSetPrivateBytes: pd.MemoryWorkingSetPrivateBytes, <ide> MemoryWorkingSetSharedBytes: pd.MemoryWorkingSetSharedBytes, <del> ProcessId: pd.ProcessID, <del> UserTime100ns: pd.UserTime_100Ns, <add> ProcessID: pd.ProcessID, <add> UserTime_100Ns: pd.UserTime_100Ns, <add> ExecID: pd.ExecID, <ide> }, nil <ide> default: <ide> return nil, errors.Errorf("Unknown process details type %T", pd) <ide><path>libcontainerd/types/types_windows.go <ide> import ( <ide> "time" <ide> <ide> "github.com/Microsoft/hcsshim" <add> "github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1/options" <ide> ) <ide> <del>// Summary contains a ProcessList item from HCS to support `top` <del>type Summary hcsshim.ProcessListItem <add>type Summary options.ProcessDetails <ide> <ide> // Stats contains statistics from HCS <ide> type Stats struct {
4
Java
Java
avoid one layer of httpheaders wrapping
3276f818519f9bde187c4ccb83653c21c2e0e7fb
<ide><path>spring-web/src/main/java/org/springframework/http/HttpEntity.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public HttpEntity(MultiValueMap<String, String> headers) { <ide> */ <ide> public HttpEntity(@Nullable T body, @Nullable MultiValueMap<String, String> headers) { <ide> this.body = body; <del> HttpHeaders tempHeaders = new HttpHeaders(); <del> if (headers != null) { <del> tempHeaders.putAll(headers); <del> } <del> this.headers = HttpHeaders.readOnlyHttpHeaders(tempHeaders); <add> this.headers = HttpHeaders.readOnlyHttpHeaders(headers != null ? headers : new HttpHeaders()); <ide> } <ide> <ide> <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public abstract class AbstractServerHttpRequest implements ServerHttpRequest { <ide> * @param contextPath the context path for the request <ide> * @param headers the headers for the request <ide> */ <del> public AbstractServerHttpRequest(URI uri, @Nullable String contextPath, HttpHeaders headers) { <add> public AbstractServerHttpRequest(URI uri, @Nullable String contextPath, MultiValueMap<String, String> headers) { <ide> this.uri = uri; <ide> this.path = RequestPath.parse(uri, contextPath); <ide> this.headers = HttpHeaders.readOnlyHttpHeaders(headers); <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/JettyHttpHandlerAdapter.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.MultiValueMap; <ide> <ide> /** <ide> * {@link ServletHttpHandlerAdapter} extension that uses Jetty APIs for writing <ide> private static final class JettyServerHttpRequest extends ServletServerHttpReque <ide> super(createHeaders(request), request, asyncContext, servletPath, bufferFactory, bufferSize); <ide> } <ide> <del> private static HttpHeaders createHeaders(HttpServletRequest request) { <add> private static MultiValueMap<String, String> createHeaders(HttpServletRequest request) { <ide> HttpFields fields = ((Request) request).getMetaData().getFields(); <del> return new HttpHeaders(new JettyHeadersAdapter(fields)); <add> return new JettyHeadersAdapter(fields); <ide> } <ide> } <ide> <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ReactorServerHttpRequest.java <ide> import org.springframework.core.io.buffer.DataBuffer; <ide> import org.springframework.core.io.buffer.NettyDataBufferFactory; <ide> import org.springframework.http.HttpCookie; <del>import org.springframework.http.HttpHeaders; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> class ReactorServerHttpRequest extends AbstractServerHttpRequest { <ide> public ReactorServerHttpRequest(HttpServerRequest request, NettyDataBufferFactory bufferFactory) <ide> throws URISyntaxException { <ide> <del> super(initUri(request), "", initHeaders(request)); <add> super(initUri(request), "", new NettyHeadersAdapter(request.requestHeaders())); <ide> Assert.notNull(bufferFactory, "DataBufferFactory must not be null"); <ide> this.request = request; <ide> this.bufferFactory = bufferFactory; <ide> private static String resolveRequestUri(HttpServerRequest request) { <ide> return uri; <ide> } <ide> <del> private static HttpHeaders initHeaders(HttpServerRequest channel) { <del> NettyHeadersAdapter headersMap = new NettyHeadersAdapter(channel.requestHeaders()); <del> return new HttpHeaders(headersMap); <del> } <del> <ide> <ide> @Override <ide> public String getMethodValue() { <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/ServletServerHttpRequest.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.nio.charset.Charset; <ide> import java.security.cert.X509Certificate; <ide> import java.util.Enumeration; <add>import java.util.Locale; <ide> import java.util.Map; <ide> <ide> import javax.servlet.AsyncContext; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.LinkedCaseInsensitiveMap; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> import org.springframework.util.MultiValueMap; <ide> public ServletServerHttpRequest(HttpServletRequest request, AsyncContext asyncCo <ide> this(createDefaultHttpHeaders(request), request, asyncContext, servletPath, bufferFactory, bufferSize); <ide> } <ide> <del> public ServletServerHttpRequest(HttpHeaders headers, HttpServletRequest request, AsyncContext asyncContext, <del> String servletPath, DataBufferFactory bufferFactory, int bufferSize) <add> public ServletServerHttpRequest(MultiValueMap<String, String> headers, HttpServletRequest request, <add> AsyncContext asyncContext, String servletPath, DataBufferFactory bufferFactory, int bufferSize) <ide> throws IOException, URISyntaxException { <ide> <ide> super(initUri(request), request.getContextPath() + servletPath, initHeaders(headers, request)); <ide> public ServletServerHttpRequest(HttpHeaders headers, HttpServletRequest request, <ide> } <ide> <ide> <del> private static HttpHeaders createDefaultHttpHeaders(HttpServletRequest request) { <del> HttpHeaders headers = new HttpHeaders(); <add> private static MultiValueMap<String, String> createDefaultHttpHeaders(HttpServletRequest request) { <add> MultiValueMap<String, String> headers = <add> CollectionUtils.toMultiValueMap(new LinkedCaseInsensitiveMap<>(8, Locale.ENGLISH)); <ide> for (Enumeration<?> names = request.getHeaderNames(); names.hasMoreElements(); ) { <ide> String name = (String) names.nextElement(); <ide> for (Enumeration<?> values = request.getHeaders(name); values.hasMoreElements(); ) { <ide> private static URI initUri(HttpServletRequest request) throws URISyntaxException <ide> return new URI(url.toString()); <ide> } <ide> <del> private static HttpHeaders initHeaders(HttpHeaders headers, HttpServletRequest request) { <del> MediaType contentType = headers.getContentType(); <del> if (contentType == null) { <add> private static MultiValueMap<String, String> initHeaders( <add> MultiValueMap<String, String> headerValues, HttpServletRequest request) { <add> <add> HttpHeaders headers = null; <add> MediaType contentType = null; <add> if (!StringUtils.hasLength(headerValues.getFirst(HttpHeaders.CONTENT_TYPE))) { <ide> String requestContentType = request.getContentType(); <ide> if (StringUtils.hasLength(requestContentType)) { <ide> contentType = MediaType.parseMediaType(requestContentType); <add> headers = new HttpHeaders(headerValues); <ide> headers.setContentType(contentType); <ide> } <ide> } <ide> if (contentType != null && contentType.getCharset() == null) { <ide> String encoding = request.getCharacterEncoding(); <ide> if (StringUtils.hasLength(encoding)) { <del> Charset charset = Charset.forName(encoding); <ide> Map<String, String> params = new LinkedCaseInsensitiveMap<>(); <ide> params.putAll(contentType.getParameters()); <del> params.put("charset", charset.toString()); <del> headers.setContentType( <del> new MediaType(contentType.getType(), contentType.getSubtype(), <del> params)); <add> params.put("charset", Charset.forName(encoding).toString()); <add> headers.setContentType(new MediaType(contentType, params)); <ide> } <ide> } <del> if (headers.getContentLength() == -1) { <add> if (headerValues.getFirst(HttpHeaders.CONTENT_TYPE) == null) { <ide> int contentLength = request.getContentLength(); <ide> if (contentLength != -1) { <add> headers = (headers != null ? headers : new HttpHeaders(headerValues)); <ide> headers.setContentLength(contentLength); <ide> } <ide> } <del> return headers; <add> return (headers != null ? headers : headerValues); <ide> } <ide> <ide> <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/TomcatHttpHandlerAdapter.java <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.ReflectionUtils; <ide> <ide> /** <ide> private static final class TomcatServerHttpRequest extends ServletServerHttpRequ <ide> this.bufferSize = bufferSize; <ide> } <ide> <del> private static HttpHeaders createTomcatHttpHeaders(HttpServletRequest request) { <add> private static MultiValueMap<String, String> createTomcatHttpHeaders(HttpServletRequest request) { <ide> RequestFacade requestFacade = getRequestFacade(request); <ide> org.apache.catalina.connector.Request connectorRequest = (org.apache.catalina.connector.Request) <ide> ReflectionUtils.getField(COYOTE_REQUEST_FIELD, requestFacade); <ide> Assert.state(connectorRequest != null, "No Tomcat connector request"); <ide> Request tomcatRequest = connectorRequest.getCoyoteRequest(); <del> TomcatHeadersAdapter headers = new TomcatHeadersAdapter(tomcatRequest.getMimeHeaders()); <del> return new HttpHeaders(headers); <add> return new TomcatHeadersAdapter(tomcatRequest.getMimeHeaders()); <ide> } <ide> <ide> private static RequestFacade getRequestFacade(HttpServletRequest request) { <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/UndertowServerHttpRequest.java <ide> import org.springframework.core.io.buffer.DataBufferWrapper; <ide> import org.springframework.core.io.buffer.PooledDataBuffer; <ide> import org.springframework.http.HttpCookie; <del>import org.springframework.http.HttpHeaders; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.LinkedMultiValueMap; <ide> class UndertowServerHttpRequest extends AbstractServerHttpRequest { <ide> public UndertowServerHttpRequest(HttpServerExchange exchange, DataBufferFactory bufferFactory) <ide> throws URISyntaxException { <ide> <del> super(initUri(exchange), "", initHeaders(exchange)); <add> super(initUri(exchange), "", new UndertowHeadersAdapter(exchange.getRequestHeaders())); <ide> this.exchange = exchange; <ide> this.body = new RequestBodyPublisher(exchange, bufferFactory); <ide> this.body.registerListeners(exchange); <ide> private static URI initUri(HttpServerExchange exchange) throws URISyntaxExceptio <ide> return new URI(requestUriAndQuery); <ide> } <ide> <del> private static HttpHeaders initHeaders(HttpServerExchange exchange) { <del> return new HttpHeaders(new UndertowHeadersAdapter(exchange.getRequestHeaders())); <del> } <del> <ide> @Override <ide> public String getMethodValue() { <ide> return this.exchange.getRequestMethod().toString(); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/DefaultRendering.java <ide> */ <ide> class DefaultRendering implements Rendering { <ide> <del> private static final HttpHeaders EMPTY_HEADERS = HttpHeaders.readOnlyHttpHeaders(new HttpHeaders()); <add> private static final HttpHeaders EMPTY_HEADERS = HttpHeaders.EMPTY; <ide> <ide> <ide> private final Object view;
8
Ruby
Ruby
use the key name yielded to the fetch block
857bd732723a6ca297195198b9796ba79226f83f
<ide><path>activerecord/lib/active_record/attribute_methods/read.rb <ide> def instance_cast_method(attr_name) <ide> # "2004-12-12" in a data column is cast to a date object, like Date.new(2004, 12, 12)). <ide> def read_attribute(attr_name) <ide> # If it's cached, just return it <del> @attributes_cache.fetch(attr_name) { <del> <del> column = @columns_hash.fetch(attr_name) { <del> return self.class.type_cast_attribute(attr_name, @attributes, @attributes_cache) <add> @attributes_cache.fetch(attr_name) { |name| <add> column = @columns_hash.fetch(name) { <add> return self.class.type_cast_attribute(name, @attributes, @attributes_cache) <ide> } <ide> <del> value = @attributes.fetch(attr_name) { <del> return block_given? ? yield(attr_name) : nil <add> value = @attributes.fetch(name) { <add> return block_given? ? yield(name) : nil <ide> } <ide> <del> if self.class.cache_attribute?(attr_name) <del> @attributes_cache[attr_name] ||= column.type_cast(value) <add> if self.class.cache_attribute?(name) <add> @attributes_cache[name] = column.type_cast(value) <ide> else <ide> column.type_cast value <ide> end <del> <ide> } <ide> end <ide>
1
Python
Python
simplify test of notmasked_contiguous
e2c71688e765a2c0eba4958891b0637754575f18
<ide><path>numpy/ma/tests/test_extras.py <ide> def test_contiguous(self): <ide> a = masked_array(np.arange(24).reshape(3, 8), <ide> mask=[[0, 0, 0, 0, 1, 1, 1, 1], <ide> [1, 1, 1, 1, 1, 1, 1, 1], <del> [0, 0, 0, 0, 0, 0, 1, 0], ]) <add> [0, 0, 0, 0, 0, 0, 1, 0]]) <ide> tmp = notmasked_contiguous(a, None) <del> assert_equal(tmp[-1], slice(23, 24, None)) <del> assert_equal(tmp[-2], slice(16, 22, None)) <del> assert_equal(tmp[-3], slice(0, 4, None)) <del> # <add> assert_equal(tmp, [ <add> slice(0, 4, None), <add> slice(16, 22, None), <add> slice(23, 24, None) <add> ]) <add> <ide> tmp = notmasked_contiguous(a, 0) <del> assert_(len(tmp[-1]) == 1) <del> assert_(tmp[-2] is None) <del> assert_equal(tmp[-3], tmp[-1]) <del> assert_(len(tmp[0]) == 2) <add> assert_equal(tmp, [ <add> [slice(0, 1, None), slice(2, 3, None)], <add> [slice(0, 1, None), slice(2, 3, None)], <add> [slice(0, 1, None), slice(2, 3, None)], <add> [slice(0, 1, None), slice(2, 3, None)], <add> [slice(2, 3, None)], <add> [slice(2, 3, None)], <add> None, <add> [slice(2, 3, None)] <add> ]) <ide> # <ide> tmp = notmasked_contiguous(a, 1) <del> assert_equal(tmp[0][-1], slice(0, 4, None)) <del> assert_(tmp[1] is None) <del> assert_equal(tmp[2][-1], slice(7, 8, None)) <del> assert_equal(tmp[2][-2], slice(0, 6, None)) <add> assert_equal(tmp, [ <add> [slice(0, 4, None)], <add> None, <add> [slice(0, 6, None), slice(7, 8, None)] <add> ]) <ide> <ide> <ide> class TestCompressFunctions(object):
1
Javascript
Javascript
move all helpers to the end of the module
1043fa897156c077b96de8109c7869bf5b8381ab
<ide><path>src/manipulation.js <ide> jQuery.fn.extend({ <ide> } <ide> }); <ide> <del>function findOrAppend( elem, tag ) { <del> return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); <del>} <del> <del>// Replace/restore the type attribute of script elements for safe DOM manipulation <del>function disableScript( elem ) { <del> var attr = elem.getAttributeNode("type"); <del> elem.type = ( attr && attr.specified ) + "/" + elem.type; <del> return elem; <del>} <del>function restoreScript( elem ) { <del> var match = rscriptTypeMasked.exec( elem.type ); <del> if ( match ) { <del> elem.type = match[ 1 ]; <del> } else { <del> elem.removeAttribute("type"); <del> } <del> return elem; <del>} <del> <del>// Mark scripts as having already been evaluated <del>function setGlobalEval( elems, refElements ) { <del> var elem, <del> i = 0; <del> for ( ; (elem = elems[ i ]) != null; i++ ) { <del> jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[ i ], "globalEval" ) ); <del> } <del>} <del> <del>function cloneCopyEvent( src, dest ) { <del> <del> if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { <del> return; <del> } <del> <del> var type, i, l, <del> oldData = jQuery._data( src ), <del> curData = jQuery._data( dest, oldData ), <del> events = oldData.events; <del> <del> if ( events ) { <del> delete curData.handle; <del> curData.events = {}; <del> <del> for ( type in events ) { <del> for ( i = 0, l = events[ type ].length; i < l; i++ ) { <del> jQuery.event.add( dest, type, events[ type ][ i ] ); <del> } <del> } <del> } <del> <del> // make the cloned public data object a copy from the original <del> if ( curData.data ) { <del> curData.data = jQuery.extend( {}, curData.data ); <del> } <del>} <del> <del>function fixCloneNodeIssues( src, dest ) { <del> var nodeName; <del> <del> // We do not need to do anything for non-Elements <del> if ( dest.nodeType !== 1 ) { <del> return; <del> } <del> <del> nodeName = dest.nodeName.toLowerCase(); <del> <del> if ( nodeName === "object" ) { <del> if ( dest.parentNode ) { <del> dest.outerHTML = src.outerHTML; <del> } <del> <del> // This path appears unavoidable for IE9. When cloning an object <del> // element in IE9, the outerHTML strategy above is not sufficient. <del> // If the src has innerHTML and the destination does not, <del> // copy the src.innerHTML into the dest.innerHTML. #10324 <del> if ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) { <del> dest.innerHTML = src.innerHTML; <del> } <del> <del> // IE9-10 fails to persist the checked state of a cloned checkbox or radio button. <del> } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { <del> dest.checked = src.checked; <del> <del> // IE9-10 fails to return the selected option to the default selected <del> // state when cloning options <del> } else if ( nodeName === "input" || nodeName === "textarea" ) { <del> dest.defaultValue = src.defaultValue; <del> } <del>} <del> <ide> jQuery.each({ <ide> appendTo: "append", <ide> prependTo: "prepend", <ide> jQuery.each({ <ide> }; <ide> }); <ide> <del>function getAll( context, tag ) { <del> var elems, elem, <del> i = 0, <del> ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : <del> typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : <del> undefined; <del> <del> if ( !ret ) { <del> for ( ret = [], elems = context.childNodes || context; (elem = elems[ i ]) != null; i++ ) { <del> core_push.apply( ret, !tag || jQuery.nodeName( elem, tag ) ? <del> getAll( elem, tag ) : <del> elems ); <del> } <del> } <del> <del> return tag === undefined || tag && jQuery.nodeName( context, tag ) ? <del> jQuery.merge( [ context ], ret ) : <del> ret; <del>} <del> <ide> jQuery.extend({ <ide> clone: function( elem, dataAndEvents, deepDataAndEvents ) { <ide> var destElements, srcElements, node, i, <ide> jQuery.extend({ <ide> } <ide> } <ide> }); <add> <add>function findOrAppend( elem, tag ) { <add> return elem.getElementsByTagName( tag )[ 0 ] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); <add>} <add> <add>// Replace/restore the type attribute of script elements for safe DOM manipulation <add>function disableScript( elem ) { <add> var attr = elem.getAttributeNode("type"); <add> elem.type = ( attr && attr.specified ) + "/" + elem.type; <add> return elem; <add>} <add>function restoreScript( elem ) { <add> var match = rscriptTypeMasked.exec( elem.type ); <add> if ( match ) { <add> elem.type = match[ 1 ]; <add> } else { <add> elem.removeAttribute("type"); <add> } <add> return elem; <add>} <add> <add>// Mark scripts as having already been evaluated <add>function setGlobalEval( elems, refElements ) { <add> var elem, <add> i = 0; <add> for ( ; (elem = elems[ i ]) != null; i++ ) { <add> jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[ i ], "globalEval" ) ); <add> } <add>} <add> <add>function cloneCopyEvent( src, dest ) { <add> <add> if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { <add> return; <add> } <add> <add> var type, i, l, <add> oldData = jQuery._data( src ), <add> curData = jQuery._data( dest, oldData ), <add> events = oldData.events; <add> <add> if ( events ) { <add> delete curData.handle; <add> curData.events = {}; <add> <add> for ( type in events ) { <add> for ( i = 0, l = events[ type ].length; i < l; i++ ) { <add> jQuery.event.add( dest, type, events[ type ][ i ] ); <add> } <add> } <add> } <add> <add> // make the cloned public data object a copy from the original <add> if ( curData.data ) { <add> curData.data = jQuery.extend( {}, curData.data ); <add> } <add>} <add> <add>function fixCloneNodeIssues( src, dest ) { <add> var nodeName; <add> <add> // We do not need to do anything for non-Elements <add> if ( dest.nodeType !== 1 ) { <add> return; <add> } <add> <add> nodeName = dest.nodeName.toLowerCase(); <add> <add> if ( nodeName === "object" ) { <add> if ( dest.parentNode ) { <add> dest.outerHTML = src.outerHTML; <add> } <add> <add> // This path appears unavoidable for IE9. When cloning an object <add> // element in IE9, the outerHTML strategy above is not sufficient. <add> // If the src has innerHTML and the destination does not, <add> // copy the src.innerHTML into the dest.innerHTML. #10324 <add> if ( src.innerHTML && !jQuery.trim( dest.innerHTML ) ) { <add> dest.innerHTML = src.innerHTML; <add> } <add> <add> // IE9-10 fails to persist the checked state of a cloned checkbox or radio button. <add> } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { <add> dest.checked = src.checked; <add> <add> // IE9-10 fails to return the selected option to the default selected <add> // state when cloning options <add> } else if ( nodeName === "input" || nodeName === "textarea" ) { <add> dest.defaultValue = src.defaultValue; <add> } <add>} <add> <add>function getAll( context, tag ) { <add> var elems, elem, <add> i = 0, <add> ret = typeof context.getElementsByTagName !== "undefined" ? context.getElementsByTagName( tag || "*" ) : <add> typeof context.querySelectorAll !== "undefined" ? context.querySelectorAll( tag || "*" ) : <add> undefined; <add> <add> if ( !ret ) { <add> for ( ret = [], elems = context.childNodes || context; (elem = elems[ i ]) != null; i++ ) { <add> core_push.apply( ret, !tag || jQuery.nodeName( elem, tag ) ? <add> getAll( elem, tag ) : <add> elems ); <add> } <add> } <add> <add> return tag === undefined || tag && jQuery.nodeName( context, tag ) ? <add> jQuery.merge( [ context ], ret ) : <add> ret; <add>}
1
Text
Text
update text about attached and detached semantics
1eba8cff39eb345b4d9e2e6623aa0d2235faceb9
<ide><path>docs/upgrading/upgrading-your-package.md <ide> Sometimes it is as simple as converting the requires at the top of each view pag <ide> ### Upgrading classes extending any space-pen View <ide> <ide> The `afterAttach` and `beforeRemove` hooks have been replaced with <del>`attached` and `detached`. The `attached` method semantics have changed: it will only be called when all parents of the View are attached to the DOM. The `detached` semantics have not changed. <add>`attached` and `detached` and the semantics have changed. <add> <add>`afterAttach` was called whenever the node was attached to another DOM node, even if that node itself wasn't present in the document. `afterAttach` also was called with a boolean indicating whether or not the element and its parents were on the DOM. Now the `attached` hook is only called when the node and all of its parents are actually on the DOM, and is not called with a boolean. <add> <add>`beforeRemove` was only called when `$.fn.remove` was called, which was typically used when the node was completely removed from the DOM. The `detached` hook is called whenever the DOM node is _detached_, which could happen if the node is being detached for reattachment later. In short, if `beforeRemove` is called the node is never coming back. With `detached` it might be attached again later. <ide> <ide> ```coffee <ide> # Old way
1
Python
Python
extend list of numbers for ru language
23f06dc37f8b9e309028d4d8b3ef17f6daaad8e0
<ide><path>spacy/lang/ru/lex_attrs.py <ide> from ...attrs import LIKE_NUM <ide> <ide> <del>_num_words = [ <del> "ноль", <del> "один", <del> "два", <del> "три", <del> "четыре", <del> "пять", <del> "шесть", <del> "семь", <del> "восемь", <del> "девять", <del> "десять", <del> "одиннадцать", <del> "двенадцать", <del> "тринадцать", <del> "четырнадцать", <del> "пятнадцать", <del> "шестнадцать", <del> "семнадцать", <del> "восемнадцать", <del> "девятнадцать", <del> "двадцать", <del> "тридцать", <del> "сорок", <del> "пятьдесят", <del> "шестьдесят", <del> "семьдесят", <del> "восемьдесят", <del> "девяносто", <del> "сто", <del> "двести", <del> "триста", <del> "четыреста", <del> "пятьсот", <del> "шестьсот", <del> "семьсот", <del> "восемьсот", <del> "девятьсот", <del> "тысяча", <del> "миллион", <del> "миллиард", <del> "триллион", <del> "квадриллион", <del> "квинтиллион", <del>] <add>_num_words = list( <add> set( <add> """ <add>ноль ноля нолю нолём ноле нулевой нулевого нулевому нулевым нулевом нулевая нулевую нулевое нулевые нулевых нулевыми <add> <add>один первого первому единица одного одному первой первом первый первым одним одном во-первых <add> <add>два второго второму второй втором вторым двойка двумя двум двух во-вторых двое две двоих оба обе обеим обеими <add>обеих обоим обоими обоих <add> <add>полтора полторы полутора <add> <add>три третьего третьему третьем третьим третий тройка трешка трёшка трояк трёха треха тремя трем трех трое троих трёх <add> <add>четыре четвертого четвертому четвертом четвертый четвертым четверка четырьмя четырем четырех четверо четырёх четверым <add>четверых <add> <add>пять пятерочка пятерка пятого пятому пятом пятый пятым пятью пяти пятеро пятерых пятерыми <add> <add>шесть шестерка шестого шестому шестой шестом шестым шестью шести шестеро шестерых <add> <add>семь семерка седьмого седьмому седьмой седьмом седьмым семью семи семеро <add> <add>восемь восьмерка восьмого восьмому восемью восьмой восьмом восьмым восеми восьмером восьми восьмью <add> <add>девять девятого девятому девятка девятом девятый девятым девятью девяти девятером вдевятером девятерых <add> <add>десять десятого десятому десятка десятом десятый десятым десятью десяти десятером вдесятером <add> <add>одиннадцать одиннадцатого одиннадцатому одиннадцатом одиннадцатый одиннадцатым одиннадцатью одиннадцати <add> <add>двенадцать двенадцатого двенадцатому двенадцатом двенадцатый двенадцатым двенадцатью двенадцати <add> <add>тринадцать тринадцатого тринадцатому тринадцатом тринадцатый тринадцатым тринадцатью тринадцати <add> <add>четырнадцать четырнадцатого четырнадцатому четырнадцатом четырнадцатый четырнадцатым четырнадцатью четырнадцати <add> <add>пятнадцать пятнадцатого пятнадцатому пятнадцатом пятнадцатый пятнадцатым пятнадцатью пятнадцати <add> <add>шестнадцать шестнадцатого шестнадцатому шестнадцатом шестнадцатый шестнадцатым шестнадцатью шестнадцати <add> <add>семнадцать семнадцатого семнадцатому семнадцатом семнадцатый семнадцатым семнадцатью семнадцати <add> <add>восемнадцать восемнадцатого восемнадцатому восемнадцатом восемнадцатый восемнадцатым восемнадцатью восемнадцати <add> <add>девятнадцать девятнадцатого девятнадцатому девятнадцатом девятнадцатый девятнадцатым девятнадцатью девятнадцати <add> <add>двадцать двадцатого двадцатому двадцатом двадцатый двадцатым двадцатью двадцати <add> <add>тридцать тридцатого тридцатому тридцатом тридцатый тридцатым тридцатью тридцати <add> <add>тридевять <add> <add>сорок сорокового сороковому сороковом сороковым сороковой <add> <add>пятьдесят пятьдесятого пятьдесятому пятьюдесятью пятьдесятом пятьдесятый пятьдесятым пятидесяти полтинник <add> <add>шестьдесят шестьдесятого шестьдесятому шестьюдесятью шестьдесятом шестьдесятый шестьдесятым шестидесятые шестидесяти <add> <add>семьдесят семьдесятого семьдесятому семьюдесятью семьдесятом семьдесятый семьдесятым семидесяти <add> <add>восемьдесят восемьдесятого восемьдесятому восемьюдесятью восемьдесятом восемьдесятый восемьдесятым восемидесяти <add>восьмидесяти <add> <add>девяносто девяностого девяностому девяностом девяностый девяностым девяноста <add> <add>сто сотого сотому сотка сотня сотом сотен сотый сотым ста <add> <add>двести двумястами двухсотого двухсотому двухсотом двухсотый двухсотым двумстам двухстах двухсот <add> <add>триста тремястами трехсотого трехсотому трехсотом трехсотый трехсотым тремстам трехстах трехсот <add> <add>четыреста четырехсотого четырехсотому четырьмястами четырехсотом четырехсотый четырехсотым четыремстам четырехстах <add>четырехсот <add> <add>пятьсот пятисотого пятисотому пятьюстами пятисотом пятисотый пятисотым пятистам пятистах пятисот <add> <add>шестьсот шестисотого шестисотому шестьюстами шестисотом шестисотый шестисотым шестистам шестистах шестисот <add> <add>семьсот семисотого семисотому семьюстами семисотом семисотый семисотым семистам семистах семисот <add> <add>восемьсот восемисотого восемисотому восемисотом восемисотый восемисотым восьмистами восьмистам восьмистах восьмисот <add> <add>девятьсот девятисотого девятисотому девятьюстами девятисотом девятисотый девятисотым девятистам девятистах девятисот <add> <add>тысяча тысячного тысячному тысячном тысячный тысячным тысячам тысячах тысячей тысяч тысячи тыс <add> <add>миллион миллионного миллионов миллионному миллионном миллионный миллионным миллионом миллиона миллионе миллиону <add>миллионов лям млн <add> <add>миллиард миллиардного миллиардному миллиардном миллиардный миллиардным миллиардом миллиарда миллиарде миллиарду <add>миллиардов лярд млрд <add> <add>триллион триллионного триллионному триллионном триллионный триллионным триллионом триллиона триллионе триллиону <add>триллионов трлн <add> <add>квадриллион квадриллионного квадриллионному квадриллионный квадриллионным квадриллионом квадриллиона квадриллионе <add>квадриллиону квадриллионов квадрлн <add> <add>квинтиллион квинтиллионного квинтиллионному квинтиллионный квинтиллионным квинтиллионом квинтиллиона квинтиллионе <add>квинтиллиону квинтиллионов квинтлн <add> <add>i ii iii iv vi vii viii ix xi xii xiii xiv xv xvi xvii xviii xix xx xxi xxii xxiii xxiv xxv xxvi xxvii xxvii xxix <add>""".split() <add> ) <add>) <ide> <ide> <ide> def like_num(text): <ide> if text.startswith(("+", "-", "±", "~")): <ide> text = text[1:] <add> if text.endswith("%"): <add> text = text[:-1] <ide> text = text.replace(",", "").replace(".", "") <ide> if text.isdigit(): <ide> return True
1
Java
Java
refine exception handling
97af9998d5d4dbaa885776ae71b863afa8c89263
<ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/DispatcherHandler.java <ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) <ide> logger.debug("Processing " + request.getMethod() + " request for [" + request.getURI() + "]"); <ide> } <ide> return Flux.fromIterable(this.handlerMappings) <del> .concatMap(m -> m.getHandler(request)) <add> .concatMap(mapping -> mapping.getHandler(request)) <ide> .next() <del> .then(handler -> getHandlerAdapter(handler).handle(request, response, handler)) <del> .then(result -> { <del> Mono<Void> mono = (result.hasError() ? Mono.error(result.getError()) : <del> handleResult(request, response, result)); <del> if (result.hasExceptionMapper()) { <del> return mono.otherwise(ex -> result.getExceptionMapper().apply(ex) <del> .then(exResult -> handleResult(request, response, exResult))); <del> } <del> return mono; <del> }) <add> .then(handler -> invokeHandler(request, response, handler)) <add> .then(result -> handleResult(request, response, result)) <ide> .otherwise(ex -> Mono.error(this.errorMapper.apply(ex))); <ide> } <ide> <del> protected HandlerAdapter getHandlerAdapter(Object handler) { <add> private Mono<HandlerResult> invokeHandler(ServerHttpRequest request, ServerHttpResponse response, Object handler) { <ide> for (HandlerAdapter handlerAdapter : this.handlerAdapters) { <ide> if (handlerAdapter.supports(handler)) { <del> return handlerAdapter; <add> return handlerAdapter.handle(request, response, handler); <ide> } <ide> } <del> throw new IllegalStateException("No HandlerAdapter: " + handler); <add> return Mono.error(new IllegalStateException("No HandlerAdapter: " + handler)); <ide> } <ide> <del> protected Mono<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, HandlerResult result) { <del> return getResultHandler(result).handleResult(request, response, result); <add> private Mono<Void> handleResult(ServerHttpRequest request, ServerHttpResponse response, HandlerResult result) { <add> return getResultHandler(result).handleResult(request, response, result) <add> .otherwise(ex -> result.applyExceptionHandler(ex).then(exceptionResult -> <add> getResultHandler(result).handleResult(request, response, exceptionResult))); <ide> } <ide> <del> protected HandlerResultHandler getResultHandler(HandlerResult handlerResult) { <add> private HandlerResultHandler getResultHandler(HandlerResult handlerResult) { <ide> for (HandlerResultHandler resultHandler : resultHandlers) { <ide> if (resultHandler.supports(handlerResult)) { <ide> return resultHandler; <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerAdapter.java <ide> <ide> package org.springframework.web.reactive; <ide> <del>import org.reactivestreams.Publisher; <add>import java.util.function.Function; <add> <ide> import reactor.Mono; <ide> <ide> import org.springframework.http.server.reactive.ServerHttpRequest; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> <ide> /** <del> * Interface that must be implemented for each handler type to handle an HTTP request. <del> * This interface is used to allow the {@link DispatcherHandler} to be indefinitely <del> * extensible. The {@code DispatcherHandler} accesses all installed handlers through <del> * this interface, meaning that it does not contain code specific to any handler type. <add> * Contract that decouples the {@link DispatcherHandler} from the details of <add> * invoking a handler and makes it possible to support any handler type. <ide> * <ide> * @author Rossen Stoyanchev <ide> * @author Sebastien Deleuze <ide> */ <ide> public interface HandlerAdapter { <ide> <ide> /** <del> * Given a handler instance, return whether or not this {@code HandlerAdapter} <del> * can support it. Typical HandlerAdapters will base the decision on the handler <del> * type. HandlerAdapters will usually only support one handler type each. <del> * <p>A typical implementation: <del> * <p>{@code <del> * return (handler instanceof MyHandler); <del> * } <add> * Whether this {@code HandlerAdapter} supports the given {@code handler}. <add> * <ide> * @param handler handler object to check <del> * @return whether or not this object can use the given handler <add> * @return whether or not the handler is supported <ide> */ <ide> boolean supports(Object handler); <ide> <ide> /** <del> * Use the given handler to handle this request. <del> * @param request current HTTP request <del> * @param response current HTTP response <del> * @param handler handler to use. This object must have previously been passed <del> * to the {@code supports} method of this interface, which must have <del> * returned {@code true}. <del> * @return A {@link Mono} that emits a single {@link HandlerResult} element <add> * Handle the request with the given handler. <add> * <add> * <p>Implementations are encouraged to handle exceptions resulting from the <add> * invocation of a handler in order and if necessary to return an alternate <add> * result that represents an error response. <add> * <add> * <p>Furthermore since an async {@code HandlerResult} may produce an error <add> * later during result handling implementations are also encouraged to <add> * {@link HandlerResult#setExceptionHandler(Function) set an exception <add> * handler} on the {@code HandlerResult} so that may also be applied later <add> * after result handling. <add> * <add> * @param request current request <add> * @param response current response <add> * @param handler the selected handler which must have been previously <add> * checked via {@link #supports(Object)} <add> * @return {@link Mono} that emits a single {@code HandlerResult} or none if <add> * the request has been fully handled and doesn't require further handling. <ide> */ <ide> Mono<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse response, <ide> Object handler); <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/HandlerResult.java <ide> public class HandlerResult { <ide> <ide> private final ResolvableType resultType; <ide> <del> private final Throwable error; <del> <del> private Function<Throwable, Mono<HandlerResult>> exceptionMapper; <add> private Function<Throwable, Mono<HandlerResult>> exceptionHandler; <ide> <ide> <ide> public HandlerResult(Object handler, Object result, ResolvableType resultType) { <ide> public HandlerResult(Object handler, Object result, ResolvableType resultType) { <ide> this.handler = handler; <ide> this.result = result; <ide> this.resultType = resultType; <del> this.error = null; <del> } <del> <del> public HandlerResult(Object handler, Throwable error) { <del> Assert.notNull(handler, "'handler' is required"); <del> Assert.notNull(error, "'error' is required"); <del> this.handler = handler; <del> this.result = null; <del> this.resultType = null; <del> this.error = error; <ide> } <ide> <ide> <ide> public ResolvableType getResultType() { <ide> return this.resultType; <ide> } <ide> <del> public Throwable getError() { <del> return this.error; <del> } <del> <del> /** <del> * Whether handler invocation produced a result or failed with an error. <del> * <p>If {@code true} the {@link #getError()} returns the error while <del> * {@link #getResult()} and {@link #getResultType()} return {@code null} <del> * and vice versa. <del> * @return whether this instance contains a result or an error. <del> */ <del> public boolean hasError() { <del> return (this.error != null); <del> } <del> <ide> /** <del> * Configure a function for selecting an alternate {@code HandlerResult} in <del> * case of an {@link #hasError() error result} or in case of an async result <del> * that results in an error. <del> * @param function the exception resolving function <add> * For an async result, failures may occur later during result handling. <add> * Use this property to configure an exception handler to be invoked if <add> * result handling fails. <add> * <add> * @param function a function to map the the error to an alternative result. <add> * @return the current instance <ide> */ <del> public HandlerResult setExceptionMapper(Function<Throwable, Mono<HandlerResult>> function) { <del> this.exceptionMapper = function; <add> public HandlerResult setExceptionHandler(Function<Throwable, Mono<HandlerResult>> function) { <add> this.exceptionHandler = function; <ide> return this; <ide> } <ide> <del> public Function<Throwable, Mono<HandlerResult>> getExceptionMapper() { <del> return this.exceptionMapper; <add> public boolean hasExceptionHandler() { <add> return (this.exceptionHandler != null); <ide> } <ide> <del> public boolean hasExceptionMapper() { <del> return (this.exceptionMapper != null); <add> public Mono<HandlerResult> applyExceptionHandler(Throwable ex) { <add> return (hasExceptionHandler() ? this.exceptionHandler.apply(ex) : Mono.error(ex)); <ide> } <ide> <ide> } <ide><path>spring-web-reactive/src/main/java/org/springframework/web/reactive/method/annotation/RequestMappingHandlerAdapter.java <ide> public Mono<HandlerResult> handle(ServerHttpRequest request, ServerHttpResponse <ide> Object handler) { <ide> <ide> HandlerMethod handlerMethod = (HandlerMethod) handler; <del> <ide> InvocableHandlerMethod invocable = new InvocableHandlerMethod(handlerMethod); <ide> invocable.setHandlerMethodArgumentResolvers(this.argumentResolvers); <ide> <ide> return invocable.invokeForRequest(request) <del> .otherwise(ex -> Mono.just(new HandlerResult(handler, ex))) <del> .map(result -> result.setExceptionMapper( <del> ex -> mapException(ex, handlerMethod, request, response))); <add> .map(result -> result.setExceptionHandler(ex -> handleException(ex, handlerMethod, request, response))) <add> .otherwise(ex -> handleException(ex, handlerMethod, request, response)); <ide> } <ide> <del> private Mono<HandlerResult> mapException(Throwable ex, HandlerMethod handlerMethod, <add> private Mono<HandlerResult> handleException(Throwable ex, HandlerMethod handlerMethod, <ide> ServerHttpRequest request, ServerHttpResponse response) { <ide> <ide> if (ex instanceof Exception) {
4
Python
Python
fix error when `bert_model` param is path or url
ca4e7aaa72551cdba39e49094f5a05962573c774
<ide><path>examples/run_squad.py <ide> def main(): <ide> global_step = 0 <ide> if args.do_train: <ide> cached_train_features_file = args.train_file+'_{0}_{1}_{2}_{3}'.format( <del> args.bert_model, str(args.max_seq_length), str(args.doc_stride), str(args.max_query_length)) <add> list(filter(None, args.bert_model.split('/'))).pop(), str(args.max_seq_length), str(args.doc_stride), str(args.max_query_length)) <ide> train_features = None <ide> try: <ide> with open(cached_train_features_file, "rb") as reader:
1
Python
Python
fix openstack swift driver so it works correctly
be258dc9d8100697f27078639dc24b4f256d436d
<ide><path>libcloud/storage/drivers/cloudfiles.py <ide> class OpenStackSwiftConnection(CloudFilesConnection): <ide> Connection class for the OpenStack Swift endpoint. <ide> """ <ide> <add> # TODO: Reverse the relationship - Swift -> CloudFiles <add> <ide> def __init__(self, *args, **kwargs): <ide> super(OpenStackSwiftConnection, self).__init__(*args, **kwargs) <ide> self._service_type = self._ex_force_service_type or 'object-store' <ide> self._service_name = self._ex_force_service_name or 'swift' <del> self._service_region = self._ex_force_service_region.upper() <add> <add> if self._ex_force_service_region: <add> self._service_region = self._ex_force_service_region.upper() <add> else: <add> self._service_region = None <ide> <ide> def get_endpoint(self, *args, **kwargs): <ide> if '2.0' in self._auth_version: <ide> def get_endpoint(self, *args, **kwargs): <ide> region=self._service_region) <ide> elif ('1.1' in self._auth_version) or ('1.0' in self._auth_version): <ide> endpoint = self.service_catalog.get_endpoint( <del> name=self._service_name, region=self._region_name) <add> name=self._service_name, region=self._service_region) <ide> <del> if self.endpoint_url in endpoint: <del> return endpoint[self.endpoint_url] <add> if PUBLIC_ENDPOINT_KEY in endpoint: <add> return endpoint[PUBLIC_ENDPOINT_KEY] <ide> else: <ide> raise LibcloudError('Could not find specified endpoint') <ide>
1
Text
Text
add comma after however
19c68550754e5ab32d9a13a3f991d1b5a639e121
<ide><path>guides/source/layouts_and_rendering.md <ide> And you have a view file `app/views/books/index.html.erb`: <ide> <ide> Rails will automatically render `app/views/books/index.html.erb` when you navigate to `/books` and you will see "Books are coming soon!" on your screen. <ide> <del>However a coming soon screen is only minimally useful, so you will soon create your `Book` model and add the index action to `BooksController`: <add>However, a coming soon screen is only minimally useful, so you will soon create your `Book` model and add the index action to `BooksController`: <ide> <ide> ```ruby <ide> class BooksController < ApplicationController
1
Javascript
Javascript
strengthen nested update counter test coverage
31518135c25aaa1b5c2799d2a18b6b9e9178409c
<ide><path>packages/react-dom/src/__tests__/ReactUpdates-test.js <ide> let ReactTestUtils; <ide> <ide> describe('ReactUpdates', () => { <ide> beforeEach(() => { <add> jest.resetModules(); <ide> React = require('react'); <ide> ReactDOM = require('react-dom'); <ide> ReactTestUtils = require('react-dom/test-utils'); <ide> describe('ReactUpdates', () => { <ide> ReactDOM.render(<Foo />, container); <ide> }); <ide> <add> it('resets the update counter for unrelated updates', () => { <add> const container = document.createElement('div'); <add> const ref = React.createRef(); <add> <add> class EventuallyTerminating extends React.Component { <add> state = {step: 0}; <add> componentDidMount() { <add> this.setState({step: 1}); <add> } <add> componentDidUpdate() { <add> if (this.state.step < limit) { <add> this.setState({step: this.state.step + 1}); <add> } <add> } <add> render() { <add> return this.state.step; <add> } <add> } <add> <add> let limit = 55; <add> expect(() => { <add> ReactDOM.render(<EventuallyTerminating ref={ref} />, container); <add> }).toThrow('Maximum'); <add> <add> // Verify that we don't go over the limit if these updates are unrelated. <add> limit -= 10; <add> ReactDOM.render(<EventuallyTerminating ref={ref} />, container); <add> expect(container.textContent).toBe(limit.toString()); <add> ref.current.setState({step: 0}); <add> expect(container.textContent).toBe(limit.toString()); <add> ref.current.setState({step: 0}); <add> expect(container.textContent).toBe(limit.toString()); <add> <add> limit += 10; <add> expect(() => { <add> ref.current.setState({step: 0}); <add> }).toThrow('Maximum'); <add> expect(ref.current).toBe(null); <add> }); <add> <ide> it('does not fall into an infinite update loop', () => { <ide> class NonTerminating extends React.Component { <ide> state = {step: 0}; <ide> describe('ReactUpdates', () => { <ide> }).toThrow('Maximum'); <ide> }); <ide> <add> it('does not fall into an infinite update loop with useLayoutEffect', () => { <add> function NonTerminating() { <add> const [step, setStep] = React.useState(0); <add> React.useLayoutEffect(() => { <add> setStep(x => x + 1); <add> }); <add> return step; <add> } <add> <add> const container = document.createElement('div'); <add> expect(() => { <add> ReactDOM.render(<NonTerminating />, container); <add> }).toThrow('Maximum'); <add> }); <add> <add> it('can recover after falling into an infinite update loop', () => { <add> class NonTerminating extends React.Component { <add> state = {step: 0}; <add> componentDidMount() { <add> this.setState({step: 1}); <add> } <add> componentDidUpdate() { <add> this.setState({step: 2}); <add> } <add> render() { <add> return this.state.step; <add> } <add> } <add> <add> class Terminating extends React.Component { <add> state = {step: 0}; <add> componentDidMount() { <add> this.setState({step: 1}); <add> } <add> render() { <add> return this.state.step; <add> } <add> } <add> <add> const container = document.createElement('div'); <add> expect(() => { <add> ReactDOM.render(<NonTerminating />, container); <add> }).toThrow('Maximum'); <add> <add> ReactDOM.render(<Terminating />, container); <add> expect(container.textContent).toBe('1'); <add> <add> expect(() => { <add> ReactDOM.render(<NonTerminating />, container); <add> }).toThrow('Maximum'); <add> <add> ReactDOM.render(<Terminating />, container); <add> expect(container.textContent).toBe('1'); <add> }); <add> <add> it('does not fall into mutually recursive infinite update loop with same container', () => { <add> // Note: this test would fail if there were two or more different roots. <add> <add> class A extends React.Component { <add> componentDidMount() { <add> ReactDOM.render(<B />, container); <add> } <add> render() { <add> return null; <add> } <add> } <add> <add> class B extends React.Component { <add> componentDidMount() { <add> ReactDOM.render(<A />, container); <add> } <add> render() { <add> return null; <add> } <add> } <add> <add> const container = document.createElement('div'); <add> expect(() => { <add> ReactDOM.render(<A />, container); <add> }).toThrow('Maximum'); <add> }); <add> <ide> it('does not fall into an infinite error loop', () => { <ide> function BadRender() { <ide> throw new Error('error');
1
Go
Go
remove false alarm error
0e64a4d7e7d5dd7c68ecc1df9fe8234938f12026
<ide><path>api.go <ide> func postCommit(srv *Server, version float64, w http.ResponseWriter, r *http.Req <ide> return err <ide> } <ide> config := &Config{} <del> if err := json.NewDecoder(r.Body).Decode(config); err != nil { <add> if err := json.NewDecoder(r.Body).Decode(config); err != nil && err.Error() != "EOF" { <ide> utils.Errorf("%s", err) <ide> } <ide> repo := r.Form.Get("repo")
1
PHP
PHP
show useful message for dev
c47587718d81d83d5ee18f2fa3ed3b4e63e0fa90
<ide><path>src/Http/Runner.php <ide> public function handle(ServerRequestInterface $request): ResponseInterface <ide> return $this->fallbackHandler->handle($request); <ide> } <ide> <del> return (new Response())->withStatus(500); <add> $response = new Response([ <add> 'body' => 'Middleware queue was exhausted without returning a response ' <add> . 'and no fallback request handler was set for Runner', <add> 'status' => 500, <add> ]); <add> <add> return $response; <ide> } <ide> }
1
Python
Python
fix tf gpt2 test_onnx_runtime_optimize
401fcca6c561d61db6ce25d9b1cebb75325a034f
<ide><path>tests/models/gpt2/test_modeling_tf_gpt2.py <ide> import unittest <ide> <ide> from transformers import GPT2Config, is_tf_available <del>from transformers.testing_utils import require_tf, slow <add>from transformers.testing_utils import require_tf, require_tf2onnx, slow <ide> <ide> from ...test_configuration_common import ConfigTester <ide> from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask <ide> def test_model_from_pretrained(self): <ide> model = TFGPT2Model.from_pretrained(model_name) <ide> self.assertIsNotNone(model) <ide> <add> # overwrite from common since ONNX runtime optimization doesn't work with tf.gather() when the argument <add> # `batch_dims` > 0" <add> @require_tf2onnx <add> @slow <add> def test_onnx_runtime_optimize(self): <add> if not self.test_onnx: <add> return <add> <add> import onnxruntime <add> import tf2onnx <add> <add> config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() <add> <add> for model_class in self.all_model_classes: <add> <add> # Skip these 2 classes which uses `tf.gather` with `batch_dims=1` <add> if model_class in [TFGPT2ForSequenceClassification, TFGPT2DoubleHeadsModel]: <add> continue <add> <add> model = model_class(config) <add> model(model.dummy_inputs) <add> <add> onnx_model_proto, _ = tf2onnx.convert.from_keras(model, opset=self.onnx_min_opset) <add> <add> onnxruntime.InferenceSession(onnx_model_proto.SerializeToString()) <add> <ide> <ide> @require_tf <ide> class TFGPT2ModelLanguageGenerationTest(unittest.TestCase):
1
Python
Python
fix static checks after merging
1da8379c913843834353b44861c62f332a461bdf
<ide><path>airflow/providers/google/cloud/hooks/cloud_memorystore.py <ide> def __init__( <ide> def get_conn( <ide> self, <ide> ): <del> """ <del> Retrieves client library object that allow access to Cloud Memorystore Memcached service. <del> """ <add> """Retrieves client library object that allow access to Cloud Memorystore Memcached service.""" <ide> if not self._client: <ide> self._client = CloudMemcacheClient(credentials=self._get_credentials()) <ide> return self._client
1
Text
Text
hotlink examples in readme
a5272e85156db31a578715272931f0f2180d385b
<ide><path>examples/README.md <ide> # examples <ide> <del>## commonjs <add>## [commonjs](commonjs) <ide> <ide> example demonstrating a very simple program <ide> <del>## code-splitting <add>## [code-splitting](code-splitting) <ide> <ide> example demonstrating a very simple case of Code Splitting. <ide> <del>## require.resolve <add>## [require.resolve](require.resolve) <ide> <ide> example demonstrating how to cache clearing of modules with `require.resolve` and `require.cache`. <ide> <del>## require.context <add>## [require.context](require.context) <ide> <ide> example demonstrating automatic creation of contexts when using variables in `require`. <ide> <del>## code-splitted-require.context <add>## [code-splitted-require.context](code-splitted-require.context) <ide> <ide> example demonstrating contexts in a code-split environment. <ide> <del>## code-splitted-require.context-amd <add>## [code-splitted-require.context-amd](code-splitted-require.context-amd) <ide> <ide> example demonstrating contexts in a code-split environment with AMD. <ide> <del>## loader <add>## [loader](loader) <ide> <ide> example demonstrating the usage of loaders. <ide> <del>## coffee-script <add>## [coffee-script](coffee-script) <ide> <ide> example demonstrating code written in coffee-script. <ide> <del>## code-splitting-bundle-loader <add>## [code-splitting-bundle-loader](code-splitting-bundle-loader) <ide> <ide> example demonstrating Code Splitting through the builder loader <ide> <del>## names-chunks <add>## [names-chunks](names-chunks) <ide> <ide> example demonstrating merging of chunks with named chunks <ide> <del>## mixed <add>## [mixed](mixed) <ide> <ide> example demonstrating mixing CommonJs and AMD <ide> <del>## web-worker <add>## [web-worker](web-worker) <ide> <ide> example demonstrating creating WebWorkers with webpack and the worker-loader. <ide> <del>## i18n <add>## [i18n](i18n) <ide> <ide> example demonstrating localization. <ide> <del>## multiple-entry-points <add>## [multiple-entry-points](multiple-entry-points) <ide> <ide> example demonstrating multiple entry points with Code Splitting. <ide>
1
Text
Text
fix status code in documents [ci skip]
c883fedc472f64b45b69f18d3b6c4693e1430df7
<ide><path>guides/source/layouts_and_rendering.md <ide> Rails understands both numeric status codes and the corresponding symbols shown <ide> | | 423 | :locked | <ide> | | 424 | :failed_dependency | <ide> | | 426 | :upgrade_required | <del>| | 423 | :precondition_required | <del>| | 424 | :too_many_requests | <del>| | 426 | :request_header_fields_too_large | <add>| | 428 | :precondition_required | <add>| | 429 | :too_many_requests | <add>| | 431 | :request_header_fields_too_large | <ide> | **Server Error** | 500 | :internal_server_error | <ide> | | 501 | :not_implemented | <ide> | | 502 | :bad_gateway |
1
Javascript
Javascript
add crossfadefrom & crossfadeto
8485ffd4815b506f876b18f8676a50aee13d7a29
<ide><path>test/unit/src/animation/AnimationAction.tests.js <ide> function createAnimation(){ <ide> <ide> } <ide> <add>function createTwoAnimations(){ <add> <add> var root = new Object3D(); <add> var mixer = new AnimationMixer(root); <add> var track = new NumberKeyframeTrack( ".rotation[x]", [ 0, 1000 ], [ 0, 360 ] ); <add> var clip = new AnimationClip( "clip1", 1000, [track] ); <add> var animationAction = mixer.clipAction( clip ); <add> <add> var track2 = new NumberKeyframeTrack( ".rotation[y]", [ 0, 1000 ], [ 0, 360 ] ); <add> var clip2 = new AnimationClip( "clip2", 1000, [track] ); <add> var animationAction2 = mixer.clipAction( clip2 ); <add> <add> return { <add> root: root, <add> mixer: mixer, <add> track: track, <add> clip: clip, <add> animationAction: animationAction, <add> track2: track2, <add> clip2: clip2, <add> animationAction2: animationAction2 <add> }; <add> <add>} <add> <add> <ide> export default QUnit.module( 'Animation', () => { <ide> <ide> QUnit.module( 'AnimationAction', () => { <ide> export default QUnit.module( 'Animation', () => { <ide> QUnit.test( "setEffectiveWeight", ( assert ) => { <ide> <ide> var {animationAction} = createAnimation(); <del> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <del> animationAction.setEffectiveWeight(0.3); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <add> animationAction.setEffectiveWeight(0.3); <ide> assert.equal( animationAction.getEffectiveWeight(), 0.3 , "When EffectiveWeight is set to 0.3 , EffectiveWeight is 0.3." ); <ide> <ide> <ide> var {animationAction} = createAnimation(); <del> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <del> animationAction.enabled = false; <del> animationAction.setEffectiveWeight(0.3); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <add> animationAction.enabled = false; <add> animationAction.setEffectiveWeight(0.3); <ide> assert.equal( animationAction.getEffectiveWeight(), 0 , "When EffectiveWeight is set to 0.3 when disabled , EffectiveWeight is 0." ); <ide> <ide> <ide> var { root, mixer,animationAction } = createAnimation(); <del> animationAction.setEffectiveWeight(0.5); <add> animationAction.setEffectiveWeight(0.5); <ide> animationAction.play(); <ide> mixer.update(500); <ide> assert.equal( root.rotation.x, 90 , "When an animation has weight 0.5 and runs half through the animation, it has changed to 1/4." ); <ide> export default QUnit.module( 'Animation', () => { <ide> <ide> QUnit.test( "getEffectiveWeight", ( assert ) => { <ide> <del> var {animationAction} = createAnimation(); <del> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <del> animationAction.setEffectiveWeight(0.3); <add> var {animationAction} = createAnimation(); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <add> animationAction.setEffectiveWeight(0.3); <ide> assert.equal( animationAction.getEffectiveWeight(), 0.3 , "When EffectiveWeight is set to 0.3 , EffectiveWeight is 0.3." ); <ide> <ide> <ide> var {animationAction} = createAnimation(); <del> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <del> animationAction.enabled = false; <del> animationAction.setEffectiveWeight(0.3); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation is created, EffectiveWeight is 1." ); <add> animationAction.enabled = false; <add> animationAction.setEffectiveWeight(0.3); <ide> assert.equal( animationAction.getEffectiveWeight(), 0 , "When EffectiveWeight is set to 0.3 when disabled , EffectiveWeight is 0." ); <ide> <ide> } ); <ide> <ide> QUnit.test( "fadeIn", ( assert ) => { <ide> <del> var {mixer, animationAction} = createAnimation(); <del> animationAction.fadeIn(1000); <add> var {mixer, animationAction} = createAnimation(); <add> animationAction.fadeIn(1000); <ide> animationAction.play(); <del> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation fadeIn is started, EffectiveWeight is 1." ); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation fadeIn is started, EffectiveWeight is 1." ); <ide> mixer.update(250); <ide> assert.equal( animationAction.getEffectiveWeight(), 0.25, "When an animation fadeIn happened 1/4, EffectiveWeight is 0.25." ); <ide> mixer.update(250); <ide> export default QUnit.module( 'Animation', () => { <ide> QUnit.test( "fadeOut", ( assert ) => { <ide> <ide> var {mixer, animationAction} = createAnimation(); <del> animationAction.fadeOut(1000); <add> animationAction.fadeOut(1000); <ide> animationAction.play(); <del> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation fadeOut is started, EffectiveWeight is 1." ); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation fadeOut is started, EffectiveWeight is 1." ); <ide> mixer.update(250); <ide> assert.equal( animationAction.getEffectiveWeight(), 0.75, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <ide> mixer.update(250); <ide> export default QUnit.module( 'Animation', () => { <ide> <ide> } ); <ide> <del> QUnit.todo( "crossFadeFrom", ( assert ) => { <add> QUnit.test( "crossFadeFrom", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var {mixer, animationAction, animationAction2} = createTwoAnimations(); <add> animationAction.crossFadeFrom(animationAction2, 1000, false); <add> animationAction.play(); <add> animationAction2.play(); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation crossFadeFrom is started, EffectiveWeight is 1." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 1 , "When an animation crossFadeFrom is started, EffectiveWeight is 1." ); <add> mixer.update(250); <add> assert.equal( animationAction.getEffectiveWeight(), 0.25, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0.75, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> mixer.update(250); <add> assert.equal( animationAction.getEffectiveWeight(), 0.5, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0.5, "When an animation fadeOut is halfway , EffectiveWeight is 0.5." ); <add> mixer.update(250); <add> assert.equal( animationAction.getEffectiveWeight(), 0.75, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0.25, "When an animation fadeOut is happened 3/4 , EffectiveWeight is 0.25." ); <add> mixer.update(500); <add> assert.equal( animationAction.getEffectiveWeight(), 1, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0, "When an animation fadeOut is ended , EffectiveWeight is 0." ); <ide> <ide> } ); <ide> <del> QUnit.todo( "crossFadeTo", ( assert ) => { <add> QUnit.test( "crossFadeTo", ( assert ) => { <ide> <del> assert.ok( false, "everything's gonna be alright" ); <add> var {mixer, animationAction, animationAction2} = createTwoAnimations(); <add> animationAction2.crossFadeTo(animationAction, 1000, false); <add> animationAction.play(); <add> animationAction2.play(); <add> assert.equal( animationAction.getEffectiveWeight(), 1 , "When an animation crossFadeFrom is started, EffectiveWeight is 1." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 1 , "When an animation crossFadeFrom is started, EffectiveWeight is 1." ); <add> mixer.update(250); <add> assert.equal( animationAction.getEffectiveWeight(), 0.25, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0.75, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> mixer.update(250); <add> assert.equal( animationAction.getEffectiveWeight(), 0.5, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0.5, "When an animation fadeOut is halfway , EffectiveWeight is 0.5." ); <add> mixer.update(250); <add> assert.equal( animationAction.getEffectiveWeight(), 0.75, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0.25, "When an animation fadeOut is happened 3/4 , EffectiveWeight is 0.25." ); <add> mixer.update(500); <add> assert.equal( animationAction.getEffectiveWeight(), 1, "When an animation fadeOut happened 1/4, EffectiveWeight is 0.75." ); <add> assert.equal( animationAction2.getEffectiveWeight(), 0, "When an animation fadeOut is ended , EffectiveWeight is 0." ); <ide> <ide> } ); <ide>
1
Javascript
Javascript
add a failing test for
7a74435c93726ba411eb3031b10ecf57c2693b23
<ide><path>packages/ember-metal/lib/watching.js <ide> export function isWatching(obj, key) { <ide> return (meta && meta.peekWatching(key)) > 0; <ide> } <ide> <add>export function watcherCount(obj, key) { <add> var meta = peekMeta(obj); <add> return (meta && meta.peekWatching(key)) || 0; <add>} <add> <ide> watch.flushPending = flushPendingChains; <ide> <ide> export function unwatch(obj, _keyPath, m) { <ide><path>packages/ember-runtime/tests/system/array_proxy/watching_and_listening_test.js <add>import { get } from 'ember-metal/property_get'; <add>import { listenersFor } from 'ember-metal/events'; <add>import { addObserver } from 'ember-metal/observer'; <add>import { defineProperty } from 'ember-metal/properties'; <add>import { watcherCount } from 'ember-metal/watching'; <add>import computed from 'ember-metal/computed'; <add>import ArrayProxy from 'ember-runtime/system/array_proxy'; <add>import { A } from 'ember-runtime/system/native_array'; <add> <add>function sortedListenersFor(obj, eventName) { <add> return listenersFor(obj, eventName).sort((listener1, listener2) => { <add> return (listener1[1] > listener2[1]) ? -1 : 1; <add> }); <add>} <add> <add>QUnit.module('ArrayProxy - watching and listening'); <add> <add>QUnit.test(`setting 'content' adds listeners correctly`, function() { <add> let content = A(); <add> let proxy = ArrayProxy.create(); <add> <add> deepEqual(sortedListenersFor(content, '@array:before'), []); <add> deepEqual(sortedListenersFor(content, '@array:change'), []); <add> <add> proxy.set('content', content); <add> <add> deepEqual( <add> sortedListenersFor(content, '@array:before'), <add> [[proxy, 'contentArrayWillChange'], [proxy, 'arrangedContentArrayWillChange']] <add> ); <add> deepEqual( <add> sortedListenersFor(content, '@array:change'), <add> [[proxy, 'contentArrayDidChange'], [proxy, 'arrangedContentArrayDidChange']] <add> ); <add>}); <add> <add>QUnit.test(`changing 'content' adds and removes listeners correctly`, function() { <add> let content1 = A(); <add> let content2 = A(); <add> let proxy = ArrayProxy.create({ content: content1 }); <add> <add> deepEqual( <add> sortedListenersFor(content1, '@array:before'), <add> [[proxy, 'contentArrayWillChange'], [proxy, 'arrangedContentArrayWillChange']] <add> ); <add> deepEqual( <add> sortedListenersFor(content1, '@array:change'), <add> [[proxy, 'contentArrayDidChange'], [proxy, 'arrangedContentArrayDidChange']] <add> ); <add> <add> proxy.set('content', content2); <add> <add> deepEqual(sortedListenersFor(content1, '@array:before'), []); <add> deepEqual(sortedListenersFor(content1, '@array:change'), []); <add> deepEqual( <add> sortedListenersFor(content2, '@array:before'), <add> [[proxy, 'contentArrayWillChange'], [proxy, 'arrangedContentArrayWillChange']] <add> ); <add> deepEqual( <add> sortedListenersFor(content2, '@array:change'), <add> [[proxy, 'contentArrayDidChange'], [proxy, 'arrangedContentArrayDidChange']] <add> ); <add>}); <add> <add>QUnit.test(`regression test for https://github.com/emberjs/ember.js/issues/12475`, function() { <add> let item1a = { id: 1 }; <add> let item1b = { id: 2 }; <add> let item1c = { id: 3 }; <add> let content1 = A([item1a, item1b, item1c]); <add> <add> let proxy = ArrayProxy.create({ content: content1 }); <add> let obj = { proxy }; <add> <add> defineProperty(obj, 'ids', computed('proxy.@each.id', function() { <add> return get(this, 'proxy').mapBy('id'); <add> })); <add> <add> // These manually added observers are to simulate the observers added by the <add> // rendering process in a template like: <add> // <add> // {{#each items as |item|}} <add> // {{item.id}} <add> // {{/each}} <add> addObserver(item1a, 'id', function() { }); <add> addObserver(item1b, 'id', function() { }); <add> addObserver(item1c, 'id', function() { }); <add> <add> // The EachProxy has not yet been consumed. Only the manually added <add> // observers are watching. <add> equal(watcherCount(item1a, 'id'), 1); <add> equal(watcherCount(item1b, 'id'), 1); <add> equal(watcherCount(item1c, 'id'), 1); <add> <add> // Consume the each proxy. This causes the EachProxy to add two observers <add> // per item: one for "before" events and one for "after" events. <add> deepEqual(get(obj, 'ids'), [1, 2, 3]); <add> <add> // For each item, the two each proxy observers and one manual added observer <add> // are watching. <add> equal(watcherCount(item1a, 'id'), 3); <add> equal(watcherCount(item1b, 'id'), 3); <add> equal(watcherCount(item1c, 'id'), 3); <add> <add> // This should be a no-op because observers do not fire if the value <add> // 1. is an object and 2. is the same as the old value. <add> proxy.set('content', content1); <add> <add> equal(watcherCount(item1a, 'id'), 3); <add> equal(watcherCount(item1b, 'id'), 3); <add> equal(watcherCount(item1c, 'id'), 3); <add> <add> // This is repeated to catch the regression. It should still be a no-op. <add> proxy.set('content', content1); <add> <add> equal(watcherCount(item1a, 'id'), 3); <add> equal(watcherCount(item1b, 'id'), 3); <add> equal(watcherCount(item1c, 'id'), 3); <add> <add> // Set the content to a new array with completely different items and <add> // repeat the process. <add> let item2a = { id: 4 }; <add> let item2b = { id: 5 }; <add> let item2c = { id: 6 }; <add> let content2 = A([item2a, item2b, item2c]); <add> <add> addObserver(item2a, 'id', function() { }); <add> addObserver(item2b, 'id', function() { }); <add> addObserver(item2c, 'id', function() { }); <add> <add> proxy.set('content', content2); <add> <add> deepEqual(get(obj, 'ids'), [4, 5, 6]); <add> <add> equal(watcherCount(item2a, 'id'), 3); <add> equal(watcherCount(item2b, 'id'), 3); <add> equal(watcherCount(item2c, 'id'), 3); <add> <add> // Ensure that the observers added by the EachProxy on all items in the <add> // first content array have been torn down. <add> equal(watcherCount(item1a, 'id'), 1); <add> equal(watcherCount(item1b, 'id'), 1); <add> equal(watcherCount(item1c, 'id'), 1); <add> <add> proxy.set('content', content2); <add> <add> equal(watcherCount(item2a, 'id'), 3); <add> equal(watcherCount(item2b, 'id'), 3); <add> equal(watcherCount(item2c, 'id'), 3); <add> <add> proxy.set('content', content2); <add> <add> equal(watcherCount(item2a, 'id'), 3); <add> equal(watcherCount(item2b, 'id'), 3); <add> equal(watcherCount(item2c, 'id'), 3); <add>});
2
Javascript
Javascript
enable the fuzz tester
ccbb92f9ef2348e80104094b10655b61fd22ef0d
<ide><path>src/renderers/shared/fiber/__tests__/ReactIncrementalTriangle-test.js <ide> describe('ReactIncrementalTriangle', () => { <ide> return {simulate, totalChildren, totalTriangles}; <ide> } <ide> <del> xit('renders the triangle demo without inconsistencies', () => { <add> it('renders the triangle demo without inconsistencies', () => { <ide> const {simulate} = TriangleSimulator(); <ide> simulate(step(1)); <ide> simulate(toggle(0), step(1), toggle(0)); <ide> simulate(step(1), toggle(0), flush(2), step(2), toggle(0)); <add> simulate(step(1), flush(3), toggle(0), step(0)); <add> simulate(step(1), flush(3), toggle(18), step(0)); <ide> }); <ide> <del> xit('fuzz tester', () => { <add> it('fuzz tester', () => { <ide> // This test is not deterministic because the inputs are randomized. It runs <ide> // a limited number of tests on every run. If it fails, it will output the <ide> // case that led to the failure. Add the failing case to the test above
1
Python
Python
fix linting errors
e0e4ed00f3962af1a38c3002f5266131f0e30780
<ide><path>libcloud/compute/drivers/dimensiondata.py <ide> def _to_firewall_address(self, element): <ide> port_list = element.find(fixxpath('portList', TYPES_URN)) <ide> address_list = element.find(fixxpath('ipAddressList', TYPES_URN)) <ide> if address_list is None: <del> return DimensionDataFirewallAddress ( <add> return DimensionDataFirewallAddress( <ide> any_ip=ip.get('address') == 'ANY', <ide> ip_address=ip.get('address'), <ide> ip_prefix_size=ip.get('prefixSize'), <ide> def _to_firewall_address(self, element): <ide> ) <ide> else: <ide> return DimensionDataFirewallAddress( <del> any_ip = False, <del> ip_address= None, <del> ip_prefix_size = None, <del> port_begin = None, <del> port_end = None, <add> any_ip=False, <add> ip_address=None, <add> ip_prefix_size=None, <add> port_begin=None, <add> port_end=None, <ide> port_list_id=port_list.get('id', None) <ide> if port_list is not None else None, <ide> address_list_id=address_list.get('id')
1
Python
Python
add gcp extras
596270fcde351703021f4a946066ab10b3fbceaa
<ide><path>setup.py <ide> def run(self): <ide> ] <ide> docker = ['docker-py>=1.6.0'] <ide> druid = ['pydruid>=0.2.1'] <add>gcp = [ <add> 'gcloud>=1.1.0', <add>] <ide> gcp_api = [ <ide> 'oauth2client>=1.5.2, <2.0.0', <ide> 'httplib2', <ide> def run(self): <ide> 'doc': doc, <ide> 'docker': docker, <ide> 'druid': druid, <add> 'gcp': gcp, <ide> 'gcp_api': gcp_api, <ide> 'hdfs': hdfs, <ide> 'hive': hive,
1
Text
Text
improve the changelog entry for
69e0e3f91b5297d0507441f86e13a60f37ec54d8
<ide><path>activerecord/CHANGELOG.md <ide> ## Rails 4.0.0 (unreleased) ## <ide> <del>* Fix querying with an empty hash *Damien Mathieu* <add>* Fix the return of querying with an empty hash. <add> Fix #6971. <add> <add> User.where(token: {}) <add> <add> Before: <add> <add> #=> SELECT * FROM users; <add> <add> After: <add> <add> #=> SELECT * FROM users WHERE 1 = 2; <add> <add> *Damien Mathieu* <ide> <ide> * Fix creation of through association models when using `collection=[]` <ide> on a `has_many :through` association from an unsaved model.
1
PHP
PHP
fix cs errors
d0c8cf1c79e580665befb26ae899f0a5d4d6f831
<ide><path>src/Mailer/AbstractTransport.php <ide> public function __construct(array $config = []) <ide> /** <ide> * Check that at least one destination header is set. <ide> * <del> * @param \Cake\Mailer\Message $message <add> * @param \Cake\Mailer\Message $message Message instance. <ide> * @return void <ide> * @throws \Cake\Core\Exception\Exception If at least one of to, cc or bcc is not specified. <ide> */ <ide> protected function checkRecipient(Message $message): void <ide> && $message->getCc() === [] <ide> && $message->getBcc() === [] <ide> ) { <del> throw new Exception('You must specify at least one recipient. Use one of `setTo`, `setCc` or `setBcc` to define a recipient.'); <add> throw new Exception( <add> 'You must specify at least one recipient.' <add> . ' Use one of `setTo`, `setCc` or `setBcc` to define a recipient.' <add> ); <ide> } <ide> } <ide>
1
Python
Python
fix lerp function and corresponding tests
214e8302ff92c002853ab03427cae2448a812f7c
<ide><path>numpy/lib/function_base.py <ide> def _quantile_is_valid(q): <ide> <ide> def _lerp(a, b, t, out=None): <ide> """ Linearly interpolate from a to b by a factor of t """ <del> if t < 0.5: <del> return add(a, subtract(b, a)*t, out=out) <add> #return add(a, subtract(b, a, out=out)*t, out=out) <add> diff_b_a = subtract(b, a) <add> <add> if np.isscalar(a) and np.isscalar(b) and (np.isscalar(t) or np.ndim(t) == 0): <add> if t <= 0.5: <add> return add(a, diff_b_a * t, out=out) <add> else: <add> return subtract(b, diff_b_a * (1 - t), out=out) <ide> else: <del> return subtract(b, subtract(b, a)*(1-t), out=out) <add> lerp_interpolation = add(a, diff_b_a*t, out=out) <add> subtract(b, diff_b_a * (1 - t), out=lerp_interpolation, where=t>=0.5) <add> return lerp_interpolation <ide> <ide> <ide> def _quantile_ureduce_func(a, q, axis=None, out=None, overwrite_input=False, <ide><path>numpy/lib/tests/test_function_base.py <ide> def test_lerp_monotonic(self, t0, t1, a, b): <ide> <ide> @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False, <ide> min_value=0, max_value=1), <del> a=st.floats(allow_nan=False, allow_infinity=False), <del> b=st.floats(allow_nan=False, allow_infinity=False)) <add> a=st.floats(allow_nan=False, allow_infinity=False, <add> width=32), <add> b=st.floats(allow_nan=False, allow_infinity=False, <add> width=32)) <ide> def test_lerp_bounded(self, t, a, b): <ide> if a <= b: <ide> assert a <= np.lib.function_base._lerp(a, b, t) <= b <ide> def test_lerp_bounded(self, t, a, b): <ide> <ide> @hypothesis.given(t=st.floats(allow_nan=False, allow_infinity=False, <ide> min_value=0, max_value=1), <del> a=st.floats(allow_nan=False, allow_infinity=False), <del> b=st.floats(allow_nan=False, allow_infinity=False)) <add> a=st.floats(allow_nan=False, allow_infinity=False, <add> width=32), <add> b=st.floats(allow_nan=False, allow_infinity=False, <add> width=32)) <ide> def test_lerp_symmetric(self, t, a, b): <ide> # double subtraction is needed to remove the extra precision that t < 0.5 has <ide> assert np.lib.function_base._lerp(a, b, 1 - (1 - t)) == np.lib.function_base._lerp(b, a, 1 - t)
2
Python
Python
remove import of removed train_config script
baf3ef0ddcb7b59973750443f4c0a3732dd0f12a
<ide><path>spacy/cli/__init__.py <ide> from .info import info <ide> from .link import link <ide> from .package import package <del>from .train import train, train_config <add>from .train import train <ide> from .model import model <ide> from .convert import convert
1
Ruby
Ruby
remove unnecessary require in associations_test.rb
715e845fa2e96e4c55efd962939657334ed66e7e
<ide><path>activerecord/test/cases/associations_test.rb <ide> require 'models/tagging' <ide> require 'models/person' <ide> require 'models/reader' <del>require 'models/parrot' <ide> require 'models/ship_part' <ide> require 'models/ship' <ide> require 'models/liquid'
1
Text
Text
add security contact
93f7f2e9507763816ce1ccbf518c4cbeda31d85a
<ide><path>CONTRIBUTING.md <ide> Second, read the [Troubleshooting Checklist](https://github.com/Homebrew/homebre <ide> <ide> **If you don't read these it will take us far longer to help you with your problem.** <ide> <add>Security <add>-------- <add>Please report security issues to security@brew.sh. <add> <ide> Contributing <ide> ------------ <ide> Please read: <ide><path>README.md <ide> Second, read the [Troubleshooting Checklist](https://github.com/Homebrew/homebre <ide> <ide> **If you don't read these it will take us far longer to help you with your problem.** <ide> <add>Security <add>-------- <add>Please report security issues to security@brew.sh. <add> <ide> Who Are You? <ide> ------------ <ide> Homebrew's current maintainers are [Misty De Meo][mistydemeo], [Adam Vandenberg][adamv], [Jack Nagel][jacknagel], [Mike McQuaid][mikemcquaid], [Brett Koonce][asparagui] and [Tim Smith][tdsmith].
2
PHP
PHP
implement the rest of file support
a20db3d21f379a135368023688b2a03ceac3648b
<ide><path>lib/Cake/Network/Http/FormData.php <ide> public function add($name, $value) { <ide> */ <ide> public function addFile($name, $value) { <ide> $filename = false; <add> $contentType = 'application/octet-stream'; <ide> if (is_resource($value)) { <ide> $content = stream_get_contents($value); <ide> } else { <add> $finfo = new \finfo(FILEINFO_MIME); <ide> $value = substr($value, 1); <ide> $filename = basename($value); <ide> $content = file_get_contents($value); <add> $contentType = $finfo->file($value); <ide> } <ide> $part = $this->newPart($name, $content); <add> $part->type($contentType); <ide> if ($filename) { <ide> $part->filename($filename); <ide> } <ide><path>lib/Cake/Network/Http/FormData/Part.php <ide> public function filename($filename = null) { <ide> * @param null|string $type Use null to get/string to set. <ide> * @return mixed <ide> */ <del> public function contentType($type) { <add> public function type($type) { <ide> if ($type === null) { <ide> return $this->_type; <ide> } <ide> public function __toString() { <ide> if ($this->_filename) { <ide> $out .= '; filename="' . $this->_filename . '"'; <ide> } <del> $out .= "\r\n\r\n"; <add> $out .= "\r\n"; <add> if ($this->_type) { <add> $out .= 'Content-Type: ' . $this->_type . "\r\n"; <add> } <add> $out .= "\r\n"; <ide> $out .= (string)$this->_value; <ide> return $out; <ide> } <ide><path>lib/Cake/Test/TestCase/Network/Http/FormDataTest.php <ide> public function testAddArray() { <ide> * @return void <ide> */ <ide> public function testAddArrayWithFile() { <del> $this->markTestIncomplete(); <add> $file = CAKE . 'VERSION.txt'; <add> $contents = file_get_contents($file); <add> <add> $data = new FormData(); <add> $data->add('Article', [ <add> 'title' => 'first post', <add> 'thumbnail' => '@' . $file <add> ]); <add> $boundary = $data->boundary(); <add> $result = (string)$data; <add> <add> $expected = array( <add> '--' . $boundary, <add> 'Content-Disposition: form-data; name="Article[title]"', <add> '', <add> 'first post', <add> '--' . $boundary, <add> 'Content-Disposition: form-data; name="Article[thumbnail]"; filename="VERSION.txt"', <add> 'Content-Type: text/plain; charset=us-ascii', <add> '', <add> $contents, <add> '--' . $boundary . '--', <add> '', <add> '', <add> ); <add> $this->assertEquals(implode("\r\n", $expected), $result); <add> <ide> } <ide> <ide> /** <ide> public function testAddFile() { <ide> $expected = array( <ide> '--' . $boundary, <ide> 'Content-Disposition: form-data; name="upload"; filename="VERSION.txt"', <add> 'Content-Type: text/plain; charset=us-ascii', <ide> '', <ide> $contents, <ide> '--' . $boundary . '--', <ide> public function testAddFileHandle() { <ide> $expected = array( <ide> '--' . $boundary, <ide> 'Content-Disposition: form-data; name="upload"', <add> 'Content-Type: application/octet-stream', <ide> '', <ide> $contents, <ide> '--' . $boundary . '--',
3