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
|
---|---|---|---|---|---|
PHP | PHP | remove paths that don't exist | e0e884d8fed32e091df569f2933129bd1800fe80 | <ide><path>Cake/View/View.php
<ide> protected function _paths($plugin = null, $cached = true) {
<ide> }
<ide> $paths = array();
<ide> $viewPaths = App::path('View');
<del> $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
<add> $corePaths = App::core('View');
<ide>
<ide> if (!empty($plugin)) {
<ide> $count = count($viewPaths); | 1 |
Java | Java | change converter ordering in message broker config | 670c216d3838807fef46cd28cc82165f9abaeb45 | <ide><path>spring-messaging/src/main/java/org/springframework/messaging/converter/AbstractMessageConverter.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public ContentTypeResolver getContentTypeResolver() {
<ide> */
<ide> public void setStrictContentTypeMatch(boolean strictContentTypeMatch) {
<ide> if (strictContentTypeMatch) {
<del> Assert.notEmpty(getSupportedMimeTypes(),
<del> "A strict converter requires a non-empty list of supported mime types");
<del> Assert.notNull(getContentTypeResolver(),
<del> "A strict converter requires a ContentTypeResolver");
<add> Assert.notEmpty(getSupportedMimeTypes(), "Strict match requires non-empty list of supported mime types.");
<add> Assert.notNull(getContentTypeResolver(), "Strict match requires ContentTypeResolver.");
<ide> }
<ide> this.strictContentTypeMatch = strictContentTypeMatch;
<ide> }
<ide> protected boolean supportsMimeType(MessageHeaders headers) {
<ide> return true;
<ide> }
<ide> }
<del> for (MimeType supported : getSupportedMimeTypes()) {
<del> if (supported.getType().equals(mimeType.getType()) &&
<del> supported.getSubtype().equals(mimeType.getSubtype())) {
<add> for (MimeType current : getSupportedMimeTypes()) {
<add> if (current.getType().equals(mimeType.getType()) && current.getSubtype().equals(mimeType.getSubtype())) {
<ide> return true;
<ide> }
<ide> }
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractMessageBrokerConfiguration.java
<ide> public CompositeMessageConverter brokerMessageConverter() {
<ide> List<MessageConverter> converters = new ArrayList<MessageConverter>();
<ide> boolean registerDefaults = configureMessageConverters(converters);
<ide> if (registerDefaults) {
<add> converters.add(new StringMessageConverter());
<add> converters.add(new ByteArrayMessageConverter());
<ide> if (jackson2Present) {
<ide> DefaultContentTypeResolver resolver = new DefaultContentTypeResolver();
<ide> resolver.setDefaultMimeType(MimeTypeUtils.APPLICATION_JSON);
<ide> MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
<ide> converter.setContentTypeResolver(resolver);
<ide> converters.add(converter);
<ide> }
<del> converters.add(new StringMessageConverter());
<del> converters.add(new ByteArrayMessageConverter());
<ide> }
<ide> return new CompositeMessageConverter(converters);
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/config/MessageBrokerConfigurationTests.java
<ide> public void clientOutboundChannelUsedByAnnotatedMethod() {
<ide>
<ide> assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
<ide> assertEquals("/foo", headers.getDestination());
<del> assertEquals("\"bar\"", new String((byte[]) message.getPayload()));
<add> assertEquals("bar", new String((byte[]) message.getPayload()));
<ide> }
<ide>
<ide> @Test
<ide> public void brokerChannelUsedByAnnotatedMethod() {
<ide>
<ide> assertEquals(SimpMessageType.MESSAGE, headers.getMessageType());
<ide> assertEquals("/bar", headers.getDestination());
<del> assertEquals("\"bar\"", new String((byte[]) message.getPayload()));
<add> assertEquals("bar", new String((byte[]) message.getPayload()));
<ide> }
<ide>
<ide> @Test
<ide> public void configureMessageConvertersDefault() {
<ide>
<ide> List<MessageConverter> converters = compositeConverter.getConverters();
<ide> assertThat(converters.size(), Matchers.is(3));
<del> assertThat(converters.get(0), Matchers.instanceOf(MappingJackson2MessageConverter.class));
<del> assertThat(converters.get(1), Matchers.instanceOf(StringMessageConverter.class));
<del> assertThat(converters.get(2), Matchers.instanceOf(ByteArrayMessageConverter.class));
<add> assertThat(converters.get(0), Matchers.instanceOf(StringMessageConverter.class));
<add> assertThat(converters.get(1), Matchers.instanceOf(ByteArrayMessageConverter.class));
<add> assertThat(converters.get(2), Matchers.instanceOf(MappingJackson2MessageConverter.class));
<ide>
<del> ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(0)).getContentTypeResolver();
<add> ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver();
<ide> assertEquals(MimeTypeUtils.APPLICATION_JSON, ((DefaultContentTypeResolver) resolver).getDefaultMimeType());
<ide> }
<ide>
<ide> protected boolean configureMessageConverters(List<MessageConverter> messageConve
<ide> assertThat(compositeConverter.getConverters().size(), Matchers.is(4));
<ide> Iterator<MessageConverter> iterator = compositeConverter.getConverters().iterator();
<ide> assertThat(iterator.next(), Matchers.is(testConverter));
<del> assertThat(iterator.next(), Matchers.instanceOf(MappingJackson2MessageConverter.class));
<ide> assertThat(iterator.next(), Matchers.instanceOf(StringMessageConverter.class));
<ide> assertThat(iterator.next(), Matchers.instanceOf(ByteArrayMessageConverter.class));
<add> assertThat(iterator.next(), Matchers.instanceOf(MappingJackson2MessageConverter.class));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParser.java
<ide> private RuntimeBeanReference registerBrokerMessageConverter(Element element,
<ide>
<ide> if (convertersElement == null || Boolean.valueOf(convertersElement.getAttribute("register-defaults"))) {
<ide> convertersDef.setSource(source);
<add> convertersDef.add(new RootBeanDefinition(StringMessageConverter.class));
<add> convertersDef.add(new RootBeanDefinition(ByteArrayMessageConverter.class));
<ide> if (jackson2Present) {
<ide> RootBeanDefinition jacksonConverterDef = new RootBeanDefinition(MappingJackson2MessageConverter.class);
<ide> RootBeanDefinition resolverDef = new RootBeanDefinition(DefaultContentTypeResolver.class);
<ide> resolverDef.getPropertyValues().add("defaultMimeType", MimeTypeUtils.APPLICATION_JSON);
<ide> jacksonConverterDef.getPropertyValues().add("contentTypeResolver", resolverDef);
<ide> convertersDef.add(jacksonConverterDef);
<ide> }
<del> convertersDef.add(new RootBeanDefinition(StringMessageConverter.class));
<del> convertersDef.add(new RootBeanDefinition(ByteArrayMessageConverter.class));
<ide> }
<ide>
<ide> ConstructorArgumentValues cavs = new ConstructorArgumentValues();
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/config/MessageBrokerBeanDefinitionParserTests.java
<ide> public void annotationMethodMessageHandler() {
<ide>
<ide> List<MessageConverter> converters = compositeMessageConverter.getConverters();
<ide> assertThat(converters.size(), Matchers.is(3));
<del> assertThat(converters.get(0), Matchers.instanceOf(MappingJackson2MessageConverter.class));
<del> assertThat(converters.get(1), Matchers.instanceOf(StringMessageConverter.class));
<del> assertThat(converters.get(2), Matchers.instanceOf(ByteArrayMessageConverter.class));
<add> assertThat(converters.get(0), Matchers.instanceOf(StringMessageConverter.class));
<add> assertThat(converters.get(1), Matchers.instanceOf(ByteArrayMessageConverter.class));
<add> assertThat(converters.get(2), Matchers.instanceOf(MappingJackson2MessageConverter.class));
<ide>
<del> ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(0)).getContentTypeResolver();
<add> ContentTypeResolver resolver = ((MappingJackson2MessageConverter) converters.get(2)).getContentTypeResolver();
<ide> assertEquals(MimeTypeUtils.APPLICATION_JSON, ((DefaultContentTypeResolver) resolver).getDefaultMimeType());
<ide> }
<ide>
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/messaging/StompWebSocketIntegrationTests.java
<ide> public void handleExceptionAndSendToUser() throws Exception {
<ide> String payload = clientHandler.actual.get(0).getPayload();
<ide> assertTrue(payload.startsWith("MESSAGE\n"));
<ide> assertTrue(payload.contains("destination:/user/queue/error\n"));
<del> assertTrue(payload.endsWith("\"Got error: Bad input\"\0"));
<add> assertTrue(payload.endsWith("Got error: Bad input\0"));
<ide> }
<ide> finally {
<ide> session.close();
<ide> public void webSocketScope() throws Exception {
<ide> String payload = clientHandler.actual.get(0).getPayload();
<ide> assertTrue(payload.startsWith("MESSAGE\n"));
<ide> assertTrue(payload.contains("destination:/topic/scopedBeanValue\n"));
<del> assertTrue(payload.endsWith("\"55\"\0"));
<add> assertTrue(payload.endsWith("55\0"));
<ide> }
<ide> finally {
<ide> session.close(); | 6 |
Python | Python | escape single quote in s3_keys | 8a34d25049a060a035d4db4a49cd4a0d0b07fb0b | <ide><path>airflow/providers/snowflake/transfers/s3_to_snowflake.py
<ide> def execute(self, context: Any) -> None:
<ide> f"FROM @{self.stage}/{self.prefix or ''}",
<ide> ]
<ide> if self.s3_keys:
<del> files = ", ".join(f"'{key}'" for key in self.s3_keys)
<add> files = ", ".join(map(enclose_param, self.s3_keys))
<ide> sql_parts.append(f"files=({files})")
<ide> sql_parts.append(f"file_format={self.file_format}")
<ide> if self.pattern:
<ide><path>tests/providers/snowflake/transfers/test_s3_to_snowflake.py
<ide> def test_execute(self, mock_run, schema, prefix, s3_keys, columns_array, pattern
<ide>
<ide> mock_run.assert_called_once()
<ide> assert mock_run.call_args[0][0] == copy_query
<add>
<add> @pytest.mark.parametrize("pattern", [None, '.*[.]csv'])
<add> @pytest.mark.parametrize("files", [None, ["foo.csv", "bar.json", "spam.parquet", "egg.xml"]])
<add> @mock.patch("airflow.providers.snowflake.transfers.s3_to_snowflake.enclose_param")
<add> def test_escaping_in_operator(self, mock_enclose_fn, files, pattern):
<add> mock_enclose_fn.return_value = "mock"
<add> with mock.patch("airflow.providers.snowflake.hooks.snowflake.SnowflakeHook.run"):
<add> S3ToSnowflakeOperator(
<add> s3_keys=files,
<add> table="mock",
<add> stage="mock",
<add> prefix="mock",
<add> file_format="mock",
<add> pattern=pattern,
<add> task_id="task_id",
<add> dag=None,
<add> ).execute(None)
<add>
<add> for file in files or []:
<add> assert mock.call(file) in mock_enclose_fn.call_args_list
<add>
<add> if pattern:
<add> assert mock.call(pattern) in mock_enclose_fn.call_args_list | 2 |
Text | Text | add missing quotes in default string values | 321c178faa51d1f9e7c8ac60790aeca187a50e1f | <ide><path>doc/api/crypto.md
<ide> added: REPLACEME
<ide> - `curve` {string}
<ide> - `inputEncoding` {string}
<ide> - `outputEncoding` {string}
<del>- `format` {string} **Default:** `uncompressed`
<add>- `format` {string} **Default:** `'uncompressed'`
<ide> - Returns: {Buffer | string}
<ide>
<ide> Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
<ide> its recommended for developers to handle this exception accordingly.
<ide> added: v0.11.14
<ide> -->
<ide> - `encoding` {string}
<del>- `format` {string} **Default:** `uncompressed`
<add>- `format` {string} **Default:** `'uncompressed'`
<ide> - Returns: {Buffer | string}
<ide>
<ide> Generates private and public EC Diffie-Hellman key values, and returns
<ide> added: v0.11.14
<ide> added: v0.11.14
<ide> -->
<ide> - `encoding` {string}
<del>- `format` {string} **Default:** `uncompressed`
<add>- `format` {string} **Default:** `'uncompressed'`
<ide> - Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified
<ide> `encoding` and `format`.
<ide>
<ide><path>doc/api/http.md
<ide> changes:
<ide> -->
<ide>
<ide> * `options` {Object | string | URL}
<del> * `protocol` {string} Protocol to use. **Default:** `http:`.
<add> * `protocol` {string} Protocol to use. **Default:** `'http:'`.
<ide> * `host` {string} A domain name or IP address of the server to issue the
<del> request to. **Default:** `localhost`.
<add> request to. **Default:** `'localhost'`.
<ide> * `hostname` {string} Alias for `host`. To support [`url.parse()`][],
<ide> `hostname` is preferred over `host`.
<ide> * `family` {number} IP address family to use when resolving `host` and
<ide><path>doc/api/https.md
<ide> changes:
<ide> -->
<ide> - `options` {Object | string | URL} Accepts all `options` from
<ide> [`http.request()`][], with some differences in default values:
<del> - `protocol` **Default:** `https:`
<add> - `protocol` **Default:** `'https:'`
<ide> - `port` **Default:** `443`
<ide> - `agent` **Default:** `https.globalAgent`
<ide> - `callback` {Function}
<ide><path>doc/api/process.md
<ide> added: v8.0.0
<ide> * `warning` {string|Error} The warning to emit.
<ide> * `options` {Object}
<ide> * `type` {string} When `warning` is a String, `type` is the name to use
<del> for the *type* of warning being emitted. **Default:** `Warning`.
<add> for the *type* of warning being emitted. **Default:** `'Warning'`.
<ide> * `code` {string} A unique identifier for the warning instance being emitted.
<ide> * `ctor` {Function} When `warning` is a String, `ctor` is an optional
<ide> function used to limit the generated stack trace. **Default:**
<ide> added: v6.0.0
<ide>
<ide> * `warning` {string|Error} The warning to emit.
<ide> * `type` {string} When `warning` is a String, `type` is the name to use
<del> for the *type* of warning being emitted. **Default:** `Warning`.
<add> for the *type* of warning being emitted. **Default:** `'Warning'`.
<ide> * `code` {string} A unique identifier for the warning instance being emitted.
<ide> * `ctor` {Function} When `warning` is a String, `ctor` is an optional
<ide> function used to limit the generated stack trace. **Default:**
<ide><path>doc/api/repl.md
<ide> changes:
<ide> -->
<ide>
<ide> * `options` {Object|string}
<del> * `prompt` {string} The input prompt to display. **Default:** `> `.
<add> * `prompt` {string} The input prompt to display. **Default:** `'> '`
<ide> (with a trailing space).
<ide> * `input` {stream.Readable} The Readable stream from which REPL input will be
<ide> read. **Default:** `process.stdin`.
<ide> environment variables:
<ide> - `NODE_REPL_HISTORY_SIZE` - Controls how many lines of history will be
<ide> persisted if history is available. Must be a positive number.
<ide> **Default:** `1000`.
<del> - `NODE_REPL_MODE` - May be either `sloppy` or `strict`. **Default:** `sloppy`,
<del> which will allow non-strict mode code to be run.
<add> - `NODE_REPL_MODE` - May be either `'sloppy'` or `'strict'`. **Default:**
<add> `'sloppy'`, which will allow non-strict mode code to be run.
<ide>
<ide> ### Persistent History
<ide> | 5 |
PHP | PHP | add comment for empty functions. | c0f3538710d3fb8501a78cae7f4a7cf0aa70ad22 | <ide><path>src/Illuminate/Http/RedirectResponse.php
<ide> protected function parseErrors($provider)
<ide> */
<ide> public function getOriginalContent()
<ide> {
<add> //
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | fix misprint in ar changelog | 2baa8ba9535bf181714b40375c85c20d0d06e524 | <ide><path>activerecord/CHANGELOG.md
<ide> has_one :account
<ide> end
<ide>
<del> user.build_account{ |a| a.credit_limit => 100.0 }
<add> user.build_account{ |a| a.credit_limit = 100.0 }
<ide>
<ide> The block is called after the instance has been initialized. *Andrew White*
<ide> | 1 |
Ruby | Ruby | improve test coverage | 945c53e7b54eff25e1cc1cf81ba6c96cce6664de | <ide><path>activerecord/test/cases/adapters/postgresql/postgresql_adapter_test.rb
<ide> def test_insert_sql_with_returning_disabled
<ide> @connection.use_returning = true
<ide> end
<ide>
<add> def test_exec_insert_with_returning_disabled
<add> @connection.use_returning = false
<add> result = @connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id', 'postgresql_partitioned_table_parent_id_seq')
<add> expect = @connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
<add> assert_equal expect, result.rows.first.first
<add> ensure
<add> @connection.use_returning = true
<add> end
<add>
<add> def test_exec_insert_with_returning_disabled_and_no_sequence_name_given
<add> @connection.use_returning = false
<add> result = @connection.exec_insert("insert into postgresql_partitioned_table_parent (number) VALUES (1)", nil, [], 'id')
<add> expect = @connection.query('select max(id) from postgresql_partitioned_table_parent').first.first
<add> assert_equal expect, result.rows.first.first
<add> ensure
<add> @connection.use_returning = true
<add> end
<add>
<add> def test_sql_for_insert_with_returning_disabled
<add> @connection.use_returning = false
<add> result = @connection.sql_for_insert('sql', nil, nil, nil, 'binds')
<add> assert_equal ['sql', 'binds'], result
<add> ensure
<add> @connection.use_returning = true
<add> end
<add>
<ide> def test_serial_sequence
<ide> assert_equal 'public.accounts_id_seq',
<ide> @connection.serial_sequence('accounts', 'id') | 1 |
Python | Python | extend trainer logging for sm | 49c61a4ae7f269c5f590d62334c33832a29e0c7d | <ide><path>src/transformers/trainer.py
<ide> import os
<ide> import re
<ide> import shutil
<add>import sys
<ide> import time
<ide> import warnings
<add>from logging import StreamHandler
<ide> from pathlib import Path
<ide> from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
<ide>
<ide> is_in_notebook,
<ide> is_sagemaker_distributed_available,
<ide> is_torch_tpu_available,
<add> is_training_run_on_sagemaker,
<ide> )
<ide> from .modeling_utils import PreTrainedModel, unwrap_model
<ide> from .optimization import Adafactor, AdamW, get_scheduler
<ide> else:
<ide> import torch.distributed as dist
<ide>
<add>if is_training_run_on_sagemaker():
<add> logging.add_handler(StreamHandler(sys.stdout))
<add>
<add>
<ide> if TYPE_CHECKING:
<ide> import optuna
<ide>
<ide><path>src/transformers/utils/logging.py
<ide> def enable_default_handler() -> None:
<ide> _get_library_root_logger().addHandler(_default_handler)
<ide>
<ide>
<add>def add_handler(handler: logging.Handler) -> None:
<add> """adds a handler to the HuggingFace Transformers's root logger."""
<add>
<add> _configure_library_root_logger()
<add>
<add> assert handler is not None
<add> _get_library_root_logger().addHandler(handler)
<add>
<add>
<add>def remove_handler(handler: logging.Handler) -> None:
<add> """removes given handler from the HuggingFace Transformers's root logger."""
<add>
<add> _configure_library_root_logger()
<add>
<add> assert handler is not None and handler not in _get_library_root_logger().handlers
<add> _get_library_root_logger().removeHandler(handler)
<add>
<add>
<ide> def disable_propagation() -> None:
<ide> """
<ide> Disable propagation of the library log outputs. Note that log propagation is disabled by default. | 2 |
Go | Go | switch version to -dev | 0089dd05e910852d5b821074c73287e730040630 | <ide><path>commands.go
<ide> import (
<ide> "unicode"
<ide> )
<ide>
<del>const VERSION = "0.5.0"
<add>const VERSION = "0.5.0-dev"
<ide>
<ide> var (
<ide> GITCOMMIT string | 1 |
Mixed | Javascript | add onmouseover and onmouseout events | a2e352ea76a711de67d891568301fa497a93a39c | <ide><path>docs/docs/ref-05-events.md
<ide> Event names:
<ide> ```
<ide> onClick onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave
<ide> onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
<del>onMouseMove onMouseUp
<add>onMouseMove onMouseOut onMouseOver onMouseUp
<ide> ```
<ide>
<ide> Properties:
<ide><path>src/eventPlugins/SimpleEventPlugin.js
<ide> var eventTypes = {
<ide> captured: keyOf({onMouseMoveCapture: true})
<ide> }
<ide> },
<add> mouseOut: {
<add> phasedRegistrationNames: {
<add> bubbled: keyOf({onMouseOut: true}),
<add> captured: keyOf({onMouseOutCapture: true})
<add> }
<add> },
<add> mouseOver: {
<add> phasedRegistrationNames: {
<add> bubbled: keyOf({onMouseOver: true}),
<add> captured: keyOf({onMouseOverCapture: true})
<add> }
<add> },
<ide> mouseUp: {
<ide> phasedRegistrationNames: {
<ide> bubbled: keyOf({onMouseUp: true}),
<ide> var topLevelEventsToDispatchConfig = {
<ide> topKeyUp: eventTypes.keyUp,
<ide> topMouseDown: eventTypes.mouseDown,
<ide> topMouseMove: eventTypes.mouseMove,
<add> topMouseOut: eventTypes.mouseOut,
<add> topMouseOver: eventTypes.mouseOver,
<ide> topMouseUp: eventTypes.mouseUp,
<ide> topPaste: eventTypes.paste,
<ide> topScroll: eventTypes.scroll,
<ide> var SimpleEventPlugin = {
<ide> case topLevelTypes.topDoubleClick:
<ide> case topLevelTypes.topMouseDown:
<ide> case topLevelTypes.topMouseMove:
<add> case topLevelTypes.topMouseOut:
<add> case topLevelTypes.topMouseOver:
<ide> case topLevelTypes.topMouseUp:
<ide> EventConstructor = SyntheticMouseEvent;
<ide> break; | 2 |
Ruby | Ruby | avoid uninitialized variable warning | d0621fde885ca0b61c75d0fd0b03bd431d736b42 | <ide><path>actionpack/lib/action_controller/test_case.rb
<ide> def setup_controller_request_and_response
<ide>
<ide> @request.env.delete('PATH_INFO')
<ide>
<del> if @controller
<add> if defined?(@controller) && @controller
<ide> @controller.request = @request
<ide> @controller.params = {}
<ide> end | 1 |
Javascript | Javascript | stop findposition at a fullscreenelement | 541f2e584b7a1fc8e3547ada32d7d9ceb586a1f6 | <ide><path>src/js/utils/dom.js
<ide> */
<ide> import document from 'global/document';
<ide> import window from 'global/window';
<add>import fs from '../fullscreen-api';
<ide> import log from './log.js';
<ide> import {isObject} from './obj';
<ide> import computedStyle from './computed-style';
<ide> export function findPosition(el) {
<ide> let left = 0;
<ide> let top = 0;
<ide>
<del> do {
<add> while (el.offsetParent && el !== document[fs.fullscreenElement]) {
<ide> left += el.offsetLeft;
<ide> top += el.offsetTop;
<ide>
<ide> el = el.offsetParent;
<del> } while (el);
<add> }
<ide>
<ide> return {
<ide> left, | 1 |
Ruby | Ruby | remove extra spaces from deprecation message | 08780eff79f93f5741dc80fb1fb1a091b9a9c94e | <ide><path>activerecord/lib/active_record/attribute_methods/time_zone_conversion.rb
<add>require 'active_support/core_ext/string/strip'
<add>
<ide> module ActiveRecord
<ide> module AttributeMethods
<ide> module TimeZoneConversion
<ide> def create_time_zone_conversion_attribute?(name, cast_type)
<ide> !result &&
<ide> cast_type.type == :time &&
<ide> time_zone_aware_types.include?(:not_explicitly_configured)
<del> ActiveSupport::Deprecation.warn(<<-MESSAGE)
<add> ActiveSupport::Deprecation.warn(<<-MESSAGE.strip_heredoc)
<ide> Time columns will become time zone aware in Rails 5.1. This
<ide> still causes `String`s to be parsed as if they were in `Time.zone`,
<ide> and `Time`s to be converted to `Time.zone`.
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> require "active_record/relation/where_clause"
<ide> require "active_record/relation/where_clause_factory"
<ide> require 'active_model/forbidden_attributes_protection'
<add>require 'active_support/core_ext/string/filters'
<ide>
<ide> module ActiveRecord
<ide> module QueryMethods
<ide> def limit(value)
<ide> def limit!(value) # :nodoc:
<ide> if string_containing_comma?(value)
<ide> # Remove `string_containing_comma?` when removing this deprecation
<del> ActiveSupport::Deprecation.warn(<<-WARNING)
<add> ActiveSupport::Deprecation.warn(<<-WARNING.squish)
<ide> Passing a string to limit in the form "1,2" is deprecated and will be
<ide> removed in Rails 5.1. Please call `offset` explicitly instead.
<ide> WARNING | 2 |
Text | Text | fix typo in stream doc | f7dd3bc19ffe031d4610b0250f7a0f6fa5c6eba9 | <ide><path>doc/api/stream.md
<ide> used to fill the read buffer).
<ide> Data is buffered in Writable streams when the
<ide> [`writable.write(chunk)`][stream-write] method is called repeatedly. While the
<ide> total size of the internal write buffer is below the threshold set by
<del>`highWaterMark`, calls to `writable.write()` will return `true`. Once the
<add>`highWaterMark`, calls to `writable.write()` will return `true`. Once
<ide> the size of the internal buffer reaches or exceeds the `highWaterMark`, `false`
<ide> will be returned.
<ide> | 1 |
Text | Text | add movember to users list | 25f435b4b4c586e6afb313fee5627cd0cbe35e9c | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [MFG Labs](https://github.com/MfgLabs)
<ide> 1. [MiNODES](https://www.minodes.com) [[@dice89](https://github.com/dice89), [@diazcelsa](https://github.com/diazcelsa)]
<ide> 1. [Modernizing Medicine](https://www.modmed.com/)[[@kehv1n](https://github.com/kehv1n), [@dalupus](https://github.com/dalupus)]
<add>1. [Movember](https://movember.com)
<ide> 1. [Multiply](https://www.multiply.com) [[@nrhvyc](https://github.com/nrhvyc)]
<ide> 1. [National Bank of Canada](https://nbc.ca) [[@brilhana](https://github.com/brilhana)]
<ide> 1. [Neoway](https://www.neoway.com.br/) [[@neowaylabs](https://github.com/orgs/NeowayLabs/people)] | 1 |
Javascript | Javascript | change default template context to controller | a4e4033d7ec4db777bac463efa9b7e3e6e7da53e | <ide><path>packages/ember-handlebars/tests/handlebars_test.js
<ide> test("bindings should respect keywords", function() {
<ide> museumOpen: true,
<ide>
<ide> controller: {
<add> museumOpen: true,
<ide> museumDetails: Ember.Object.create({
<ide> name: "SFMoMA",
<ide> price: 20
<ide> test("bindings should respect keywords", function() {
<ide> template: Ember.Handlebars.compile('Name: {{view.name}} Price: ${{view.dollars}}')
<ide> }),
<ide>
<del> template: Ember.Handlebars.compile('{{#if museumOpen}}{{view museumView nameBinding="controller.museumDetails.name" dollarsBinding="controller.museumDetails.price"}}{{/if}}')
<add> template: Ember.Handlebars.compile('{{#if view.museumOpen}}{{view view.museumView nameBinding="controller.museumDetails.name" dollarsBinding="controller.museumDetails.price"}}{{/if}}')
<ide> });
<ide>
<ide> Ember.run(function() {
<ide><path>packages/ember-views/lib/views/view.js
<ide> Ember.View = Ember.Object.extend(Ember.Evented,
<ide> to be re-rendered.
<ide> */
<ide> _templateContext: Ember.computed(function(key, value) {
<del> var parentView;
<add> var parentView, controller;
<ide>
<ide> if (arguments.length === 2) {
<ide> return value;
<ide> }
<ide>
<ide> if (VIEW_PRESERVES_CONTEXT) {
<add> if (controller = get(this, 'controller')) {
<add> return controller;
<add> }
<add>
<ide> parentView = get(this, '_parentView');
<ide> if (parentView) {
<ide> return get(parentView, '_templateContext');
<ide><path>packages/ember-views/tests/views/view/template_test.js
<ide> test("should call the function of the associated template", function() {
<ide> Ember.run(function(){
<ide> view.createElement();
<ide> });
<del>
<add>
<ide>
<ide> ok(view.$('#twas-called').length, "the named template was called");
<ide> });
<ide> test("should call the function of the associated template with itself as the con
<ide> Ember.run(function(){
<ide> view.createElement();
<ide> });
<del>
<add>
<ide>
<ide> equal("template was called for Tom DAAAALE", view.$('#twas-called').text(), "the named template was called with the view as the data source");
<ide> });
<ide> test("should not use defaultTemplate if template is provided", function() {
<ide> Ember.run(function(){
<ide> view.createElement();
<ide> });
<del>
<add>
<ide>
<ide> equal("foo", view.$().text(), "default template was not printed");
<ide> });
<ide> test("should not use defaultTemplate if template is provided", function() {
<ide> Ember.run(function(){
<ide> view.createElement();
<ide> });
<del>
<add>
<ide>
<ide> equal("foo", view.$().text(), "default template was not printed");
<ide> });
<ide> test("should render an empty element if no template is specified", function() {
<ide> });
<ide>
<ide> test("should provide a controller to the template if a controller is specified on the view", function() {
<del> expect(5);
<del> var controller1 = Ember.Object.create(),
<del> controller2 = Ember.Object.create(),
<add> expect(7);
<add>
<add> var Controller1 = Ember.Object.extend({
<add> toString: function() { return "Controller1"; }
<add> });
<add>
<add> var Controller2 = Ember.Object.extend({
<add> toString: function() { return "Controller2"; }
<add> });
<add>
<add> var controller1 = Controller1.create(),
<add> controller2 = Controller2.create(),
<ide> optionsDataKeywordsControllerForView,
<del> optionsDataKeywordsControllerForChildView;
<del>
<add> optionsDataKeywordsControllerForChildView,
<add> contextForView,
<add> contextForControllerlessView;
<add>
<ide> var view = Ember.View.create({
<ide> controller: controller1,
<del>
<add>
<ide> template: function(buffer, options) {
<ide> optionsDataKeywordsControllerForView = options.data.keywords.controller;
<ide> }
<ide> test("should provide a controller to the template if a controller is specified o
<ide> Ember.run(function() {
<ide> view.appendTo('#qunit-fixture');
<ide> });
<del>
<add>
<ide> strictEqual(optionsDataKeywordsControllerForView, controller1, "passes the controller in the data");
<del>
<add>
<ide> Ember.run(function(){
<ide> view.destroy();
<ide> });
<del>
<add>
<ide> var parentView = Ember.View.create({
<ide> controller: controller1,
<del>
<add>
<ide> template: function(buffer, options) {
<ide> options.data.view.appendChild(Ember.View.create({
<ide> controller: controller2,
<ide> templateData: options.data,
<del> template: function(buffer, options) {
<add> template: function(context, options) {
<add> contextForView = context;
<ide> optionsDataKeywordsControllerForChildView = options.data.keywords.controller;
<ide> }
<ide> }));
<ide> optionsDataKeywordsControllerForView = options.data.keywords.controller;
<ide> }
<ide> });
<del>
<add>
<ide> Ember.run(function() {
<ide> parentView.appendTo('#qunit-fixture');
<ide> });
<del>
<add>
<ide> strictEqual(optionsDataKeywordsControllerForView, controller1, "passes the controller in the data");
<ide> strictEqual(optionsDataKeywordsControllerForChildView, controller2, "passes the child view's controller in the data");
<del>
<add>
<ide> Ember.run(function(){
<ide> parentView.destroy();
<ide> });
<del>
<del>
<add>
<add>
<ide> var parentViewWithControllerlessChild = Ember.View.create({
<ide> controller: controller1,
<del>
<add>
<ide> template: function(buffer, options) {
<ide> options.data.view.appendChild(Ember.View.create({
<ide> templateData: options.data,
<del> template: function(buffer, options) {
<add> template: function(context, options) {
<add> contextForControllerlessView = context;
<ide> optionsDataKeywordsControllerForChildView = options.data.keywords.controller;
<ide> }
<ide> }));
<ide> optionsDataKeywordsControllerForView = options.data.keywords.controller;
<ide> }
<ide> });
<del>
<add>
<ide> Ember.run(function() {
<ide> parentViewWithControllerlessChild.appendTo('#qunit-fixture');
<ide> });
<del>
<del>
<add>
<ide> strictEqual(optionsDataKeywordsControllerForView, controller1, "passes the original controller in the data");
<ide> strictEqual(optionsDataKeywordsControllerForChildView, controller1, "passes the controller in the data to child views");
<add> strictEqual(contextForView, controller2, "passes the controller in as the main context of the parent view");
<add> strictEqual(contextForControllerlessView, controller1, "passes the controller in as the main context of the child view");
<ide> }); | 3 |
Python | Python | add tests for hermfit with deg specified as list | b8180bbf97505a544324c90f407cdf2c5913c612 | <ide><path>numpy/polynomial/tests/test_hermite.py
<ide> def test_hermfit(self):
<ide> def f(x):
<ide> return x*(x - 1)*(x - 2)
<ide>
<add> def f2(x):
<add> return x**4 + x**2 + 1
<add>
<ide> # Test exceptions
<ide> assert_raises(ValueError, herm.hermfit, [1], [1], -1)
<ide> assert_raises(TypeError, herm.hermfit, [[1]], [1], 0)
<ide> def f(x):
<ide> assert_raises(TypeError, herm.hermfit, [1], [1, 2], 0)
<ide> assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[[1]])
<ide> assert_raises(TypeError, herm.hermfit, [1], [1], 0, w=[1, 1])
<add> assert_raises(ValueError, herm.hermfit, [1], [1], [-1,])
<add> assert_raises(ValueError, herm.hermfit, [1], [1], [2, -1, 6])
<add> assert_raises(TypeError, herm.hermfit, [1], [1], [])
<ide>
<ide> # Test fit
<ide> x = np.linspace(0, 2)
<ide> def f(x):
<ide> coef3 = herm.hermfit(x, y, 3)
<ide> assert_equal(len(coef3), 4)
<ide> assert_almost_equal(herm.hermval(x, coef3), y)
<add> coef3 = herm.hermfit(x, y, [0, 1, 2, 3])
<add> assert_equal(len(coef3), 4)
<add> assert_almost_equal(herm.hermval(x, coef3), y)
<ide> #
<ide> coef4 = herm.hermfit(x, y, 4)
<ide> assert_equal(len(coef4), 5)
<ide> assert_almost_equal(herm.hermval(x, coef4), y)
<add> coef4 = herm.hermfit(x, y, [0, 1, 2, 3, 4])
<add> assert_equal(len(coef4), 5)
<add> assert_almost_equal(herm.hermval(x, coef4), y)
<add> # check things still work if deg is not in strict increasing
<add> coef4 = herm.hermfit(x, y, [2, 3, 4, 1, 0])
<add> assert_equal(len(coef4), 5)
<add> assert_almost_equal(herm.hermval(x, coef4), y)
<ide> #
<ide> coef2d = herm.hermfit(x, np.array([y, y]).T, 3)
<ide> assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
<add> coef2d = herm.hermfit(x, np.array([y, y]).T, [0, 1, 2, 3])
<add> assert_almost_equal(coef2d, np.array([coef3, coef3]).T)
<ide> # test weighting
<ide> w = np.zeros_like(x)
<ide> yw = y.copy()
<ide> w[1::2] = 1
<ide> y[0::2] = 0
<ide> wcoef3 = herm.hermfit(x, yw, 3, w=w)
<ide> assert_almost_equal(wcoef3, coef3)
<add> wcoef3 = herm.hermfit(x, yw, [0, 1, 2, 3], w=w)
<add> assert_almost_equal(wcoef3, coef3)
<ide> #
<ide> wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, 3, w=w)
<ide> assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
<add> wcoef2d = herm.hermfit(x, np.array([yw, yw]).T, [0, 1, 2, 3], w=w)
<add> assert_almost_equal(wcoef2d, np.array([coef3, coef3]).T)
<ide> # test scaling with complex values x points whose square
<ide> # is zero when summed.
<ide> x = [1, 1j, -1, -1j]
<ide> assert_almost_equal(herm.hermfit(x, x, 1), [0, .5])
<add> assert_almost_equal(herm.hermfit(x, x, [0, 1]), [0, .5])
<add> # test fitting only even Legendre polynomials
<add> x = np.linspace(-1, 1)
<add> y = f2(x)
<add> coef1 = herm.hermfit(x, y, 4)
<add> assert_almost_equal(herm.hermval(x, coef1), y)
<add> coef2 = herm.hermfit(x, y, [0, 2, 4])
<add> assert_almost_equal(herm.hermval(x, coef2), y)
<add> assert_almost_equal(coef1, coef2)
<ide>
<ide>
<ide> class TestCompanion(TestCase): | 1 |
Javascript | Javascript | fix typo in keyframetrack.optimize() | 0bb92db3df41179adce5320447798b25f672d5cd | <ide><path>src/animation/KeyframeTrack.js
<ide> Object.assign( KeyframeTrack.prototype, {
<ide>
<ide> // remove adjacent keyframes scheduled at the same time
<ide>
<del> if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
<add> if ( time !== timeNext && ( i !== 1 || time !== times[ 0 ] ) ) {
<ide>
<ide> if ( ! smoothInterpolation ) {
<ide> | 1 |
Ruby | Ruby | remove dead, unused vendor/db2.rb | d9fb021845c0481c5119eebdc534aec427072f7d | <ide><path>activerecord/lib/active_record/vendor/db2.rb
<del>require 'db2/db2cli.rb'
<del>
<del>module DB2
<del> module DB2Util
<del> include DB2CLI
<del>
<del> def free() SQLFreeHandle(@handle_type, @handle); end
<del> def handle() @handle; end
<del>
<del> def check_rc(rc)
<del> if ![SQL_SUCCESS, SQL_SUCCESS_WITH_INFO, SQL_NO_DATA_FOUND].include?(rc)
<del> rec = 1
<del> msg = ''
<del> loop do
<del> a = SQLGetDiagRec(@handle_type, @handle, rec, 500)
<del> break if a[0] != SQL_SUCCESS
<del> msg << a[3] if !a[3].nil? and a[3] != '' # Create message.
<del> rec += 1
<del> end
<del> raise "DB2 error: #{msg}"
<del> end
<del> end
<del> end
<del>
<del> class Environment
<del> include DB2Util
<del>
<del> def initialize
<del> @handle_type = SQL_HANDLE_ENV
<del> rc, @handle = SQLAllocHandle(@handle_type, SQL_NULL_HANDLE)
<del> check_rc(rc)
<del> end
<del>
<del> def data_sources(buffer_length = 1024)
<del> retval = []
<del> max_buffer_length = buffer_length
<del>
<del> a = SQLDataSources(@handle, SQL_FETCH_FIRST, SQL_MAX_DSN_LENGTH + 1, buffer_length)
<del> retval << [a[1], a[3]]
<del> max_buffer_length = [max_buffer_length, a[4]].max
<del>
<del> loop do
<del> a = SQLDataSources(@handle, SQL_FETCH_NEXT, SQL_MAX_DSN_LENGTH + 1, buffer_length)
<del> break if a[0] == SQL_NO_DATA_FOUND
<del>
<del> retval << [a[1], a[3]]
<del> max_buffer_length = [max_buffer_length, a[4]].max
<del> end
<del>
<del> if max_buffer_length > buffer_length
<del> get_data_sources(max_buffer_length)
<del> else
<del> retval
<del> end
<del> end
<del> end
<del>
<del> class Connection
<del> include DB2Util
<del>
<del> def initialize(environment)
<del> @env = environment
<del> @handle_type = SQL_HANDLE_DBC
<del> rc, @handle = SQLAllocHandle(@handle_type, @env.handle)
<del> check_rc(rc)
<del> end
<del>
<del> def connect(server_name, user_name = '', auth = '')
<del> check_rc(SQLConnect(@handle, server_name, user_name.to_s, auth.to_s))
<del> end
<del>
<del> def set_connect_attr(attr, value)
<del> value += "\0" if value.class == String
<del> check_rc(SQLSetConnectAttr(@handle, attr, value))
<del> end
<del>
<del> def set_auto_commit_on
<del> set_connect_attr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_ON)
<del> end
<del>
<del> def set_auto_commit_off
<del> set_connect_attr(SQL_ATTR_AUTOCOMMIT, SQL_AUTOCOMMIT_OFF)
<del> end
<del>
<del> def disconnect
<del> check_rc(SQLDisconnect(@handle))
<del> end
<del>
<del> def rollback
<del> check_rc(SQLEndTran(@handle_type, @handle, SQL_ROLLBACK))
<del> end
<del>
<del> def commit
<del> check_rc(SQLEndTran(@handle_type, @handle, SQL_COMMIT))
<del> end
<del> end
<del>
<del> class Statement
<del> include DB2Util
<del>
<del> def initialize(connection)
<del> @conn = connection
<del> @handle_type = SQL_HANDLE_STMT
<del> @parms = [] #yun
<del> @sql = '' #yun
<del> @numParms = 0 #yun
<del> @prepared = false #yun
<del> @parmArray = [] #yun. attributes of the parameter markers
<del> rc, @handle = SQLAllocHandle(@handle_type, @conn.handle)
<del> check_rc(rc)
<del> end
<del>
<del> def columns(table_name, schema_name = '%')
<del> check_rc(SQLColumns(@handle, '', schema_name.upcase, table_name.upcase, '%'))
<del> fetch_all
<del> end
<del>
<del> def tables(schema_name = '%')
<del> check_rc(SQLTables(@handle, '', schema_name.upcase, '%', 'TABLE'))
<del> fetch_all
<del> end
<del>
<del> def indexes(table_name, schema_name = '')
<del> check_rc(SQLStatistics(@handle, '', schema_name.upcase, table_name.upcase, SQL_INDEX_ALL, SQL_ENSURE))
<del> fetch_all
<del> end
<del>
<del> def prepare(sql)
<del> @sql = sql
<del> check_rc(SQLPrepare(@handle, sql))
<del> rc, @numParms = SQLNumParams(@handle) #number of question marks
<del> check_rc(rc)
<del> #--------------------------------------------------------------------------
<del> # parameter attributes are stored in instance variable @parmArray so that
<del> # they are available when execute method is called.
<del> #--------------------------------------------------------------------------
<del> if @numParms > 0 # get parameter marker attributes
<del> 1.upto(@numParms) do |i| # parameter number starts from 1
<del> rc, type, size, decimalDigits = SQLDescribeParam(@handle, i)
<del> check_rc(rc)
<del> @parmArray << Parameter.new(type, size, decimalDigits)
<del> end
<del> end
<del> @prepared = true
<del> self
<del> end
<del>
<del> def execute(*parms)
<del> raise "The statement was not prepared" if @prepared == false
<del>
<del> if parms.size == 1 and parms[0].class == Array
<del> parms = parms[0]
<del> end
<del>
<del> if @numParms != parms.size
<del> raise "Number of parameters supplied does not match with the SQL statement"
<del> end
<del>
<del> if @numParms > 0 #need to bind parameters
<del> #--------------------------------------------------------------------
<del> #calling bindParms may not be safe. Look comment below.
<del> #--------------------------------------------------------------------
<del> #bindParms(parms)
<del>
<del> valueArray = []
<del> 1.upto(@numParms) do |i| # parameter number starts from 1
<del> type = @parmArray[i - 1].class
<del> size = @parmArray[i - 1].size
<del> decimalDigits = @parmArray[i - 1].decimalDigits
<del>
<del> if parms[i - 1].class == String
<del> valueArray << parms[i - 1]
<del> else
<del> valueArray << parms[i - 1].to_s
<del> end
<del>
<del> rc = SQLBindParameter(@handle, i, type, size, decimalDigits, valueArray[i - 1])
<del> check_rc(rc)
<del> end
<del> end
<del>
<del> check_rc(SQLExecute(@handle))
<del>
<del> if @numParms != 0
<del> check_rc(SQLFreeStmt(@handle, SQL_RESET_PARAMS)) # Reset parameters
<del> end
<del>
<del> self
<del> end
<del>
<del> #-------------------------------------------------------------------------------
<del> # The last argument(value) to SQLBindParameter is a deferred argument, that is,
<del> # it should be available when SQLExecute is called. Even though "value" is
<del> # local to bindParms method, it seems that it is available when SQLExecute
<del> # is called. I am not sure whether it would still work if garbage collection
<del> # is done between bindParms call and SQLExecute call inside the execute method
<del> # above.
<del> #-------------------------------------------------------------------------------
<del> def bindParms(parms) # This is the real thing. It uses SQLBindParms
<del> 1.upto(@numParms) do |i| # parameter number starts from 1
<del> rc, dataType, parmSize, decimalDigits = SQLDescribeParam(@handle, i)
<del> check_rc(rc)
<del> if parms[i - 1].class == String
<del> value = parms[i - 1]
<del> else
<del> value = parms[i - 1].to_s
<del> end
<del> rc = SQLBindParameter(@handle, i, dataType, parmSize, decimalDigits, value)
<del> check_rc(rc)
<del> end
<del> end
<del>
<del> #------------------------------------------------------------------------------
<del> # bind method does not use DB2's SQLBindParams, but replaces "?" in the
<del> # SQL statement with the value before passing the SQL statement to DB2.
<del> # It is not efficient and can handle only strings since it puts everything in
<del> # quotes.
<del> #------------------------------------------------------------------------------
<del> def bind(sql, args) #does not use SQLBindParams
<del> arg_index = 0
<del> result = ""
<del> tokens(sql).each do |part|
<del> case part
<del> when '?'
<del> result << "'" + (args[arg_index]) + "'" #put it into quotes
<del> arg_index += 1
<del> when '??'
<del> result << "?"
<del> else
<del> result << part
<del> end
<del> end
<del> if arg_index < args.size
<del> raise "Too many SQL parameters"
<del> elsif arg_index > args.size
<del> raise "Not enough SQL parameters"
<del> end
<del> result
<del> end
<del>
<del> ## Break the sql string into parts.
<del> #
<del> # This is NOT a full lexer for SQL. It just breaks up the SQL
<del> # string enough so that question marks, double question marks and
<del> # quoted strings are separated. This is used when binding
<del> # arguments to "?" in the SQL string. Note: comments are not
<del> # handled.
<del> #
<del> def tokens(sql)
<del> toks = sql.scan(/('([^'\\]|''|\\.)*'|"([^"\\]|""|\\.)*"|\?\??|[^'"?]+)/)
<del> toks.collect { |t| t[0] }
<del> end
<del>
<del> def exec_direct(sql)
<del> check_rc(SQLExecDirect(@handle, sql))
<del> self
<del> end
<del>
<del> def set_cursor_name(name)
<del> check_rc(SQLSetCursorName(@handle, name))
<del> self
<del> end
<del>
<del> def get_cursor_name
<del> rc, name = SQLGetCursorName(@handle)
<del> check_rc(rc)
<del> name
<del> end
<del>
<del> def row_count
<del> rc, rowcount = SQLRowCount(@handle)
<del> check_rc(rc)
<del> rowcount
<del> end
<del>
<del> def num_result_cols
<del> rc, cols = SQLNumResultCols(@handle)
<del> check_rc(rc)
<del> cols
<del> end
<del>
<del> def fetch_all
<del> if block_given?
<del> while row = fetch do
<del> yield row
<del> end
<del> else
<del> res = []
<del> while row = fetch do
<del> res << row
<del> end
<del> res
<del> end
<del> end
<del>
<del> def fetch
<del> cols = get_col_desc
<del> rc = SQLFetch(@handle)
<del> if rc == SQL_NO_DATA_FOUND
<del> SQLFreeStmt(@handle, SQL_CLOSE) # Close cursor
<del> SQLFreeStmt(@handle, SQL_RESET_PARAMS) # Reset parameters
<del> return nil
<del> end
<del> raise "ERROR" unless rc == SQL_SUCCESS
<del>
<del> retval = []
<del> cols.each_with_index do |c, i|
<del> rc, content = SQLGetData(@handle, i + 1, c[1], c[2] + 1) #yun added 1 to c[2]
<del> retval << adjust_content(content)
<del> end
<del> retval
<del> end
<del>
<del> def fetch_as_hash
<del> cols = get_col_desc
<del> rc = SQLFetch(@handle)
<del> if rc == SQL_NO_DATA_FOUND
<del> SQLFreeStmt(@handle, SQL_CLOSE) # Close cursor
<del> SQLFreeStmt(@handle, SQL_RESET_PARAMS) # Reset parameters
<del> return nil
<del> end
<del> raise "ERROR" unless rc == SQL_SUCCESS
<del>
<del> retval = {}
<del> cols.each_with_index do |c, i|
<del> rc, content = SQLGetData(@handle, i + 1, c[1], c[2] + 1) #yun added 1 to c[2]
<del> retval[c[0]] = adjust_content(content)
<del> end
<del> retval
<del> end
<del>
<del> def get_col_desc
<del> rc, nr_cols = SQLNumResultCols(@handle)
<del> cols = (1..nr_cols).collect do |c|
<del> rc, name, bl, type, col_sz = SQLDescribeCol(@handle, c, 1024)
<del> [name.downcase, type, col_sz]
<del> end
<del> end
<del>
<del> def adjust_content(c)
<del> case c.class.to_s
<del> when 'DB2CLI::NullClass'
<del> return nil
<del> when 'DB2CLI::Time'
<del> "%02d:%02d:%02d" % [c.hour, c.minute, c.second]
<del> when 'DB2CLI::Date'
<del> "%04d-%02d-%02d" % [c.year, c.month, c.day]
<del> when 'DB2CLI::Timestamp'
<del> "%04d-%02d-%02d %02d:%02d:%02d" % [c.year, c.month, c.day, c.hour, c.minute, c.second]
<del> else
<del> return c
<del> end
<del> end
<del> end
<del>
<del> class Parameter
<del> attr_reader :type, :size, :decimalDigits
<del> def initialize(type, size, decimalDigits)
<del> @type, @size, @decimalDigits = type, size, decimalDigits
<del> end
<del> end
<del>end | 1 |
Ruby | Ruby | fix nounzip strategy ignoring block | 85eb346fb756fc8177f95024f6ad357f45820815 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> UnpackStrategy::Uncompressed.new(cached_location)
<ide> .extract(basename: basename,
<ide> verbose: verbose? && !quiet?)
<add> yield if block_given?
<ide> end
<ide> end
<ide> | 1 |
Ruby | Ruby | fix env for python3 | 370df177c46e9f13415b2da99b868fe56546764c | <ide><path>Library/Homebrew/requirements/python_requirement.rb
<ide> class PythonRequirement < Requirement
<ide> ENV.prepend_path "PATH", Formula["python"].opt_bin
<ide> end
<ide>
<del> if python_binary == "python"
<del> ENV["PYTHONPATH"] = "#{HOMEBREW_PREFIX}/lib/python#{short_version}/site-packages"
<del> end
<add> ENV["PYTHONPATH"] = "#{HOMEBREW_PREFIX}/lib/python#{short_version}/site-packages"
<ide> end
<ide>
<ide> def python_short_version
<ide> class Python3Requirement < PythonRequirement
<ide>
<ide> satisfy(:build_env => false) { which_python }
<ide>
<add> env do
<add> ENV["PYTHONPATH"] = "#{HOMEBREW_PREFIX}/lib/python#{python_short_version}/site-packages"
<add> end
<add>
<ide> def python_binary
<ide> "python3"
<ide> end | 1 |
Javascript | Javascript | remove unnecessary check | a6e9174a2774007e22ce0b2c257a2cd3f39563dd | <ide><path>src/ng/parse.js
<ide> function ensureSafeMemberName(name, fullExpression) {
<ide> return name;
<ide> }
<ide>
<del>function getStringValue(name, fullExpression) {
<del> // From the JavaScript docs:
<add>function getStringValue(name) {
<ide> // Property names must be strings. This means that non-string objects cannot be used
<ide> // as keys in an object. Any non-string object, including a number, is typecasted
<ide> // into a string via the toString method.
<add> // -- MDN, https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors#Property_names
<ide> //
<del> // So, to ensure that we are checking the same `name` that JavaScript would use,
<del> // we cast it to a string, if possible.
<del> // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
<del> // this is, this will handle objects that misbehave.
<del> name = name + '';
<del> if (!isString(name)) {
<del> throw $parseMinErr('iseccst',
<del> 'Cannot convert object to primitive value! '
<del> + 'Expression: {0}', fullExpression);
<del> }
<del> return name;
<add> // So, to ensure that we are checking the same `name` that JavaScript would use, we cast it
<add> // to a string. It's not always possible. If `name` is an object and its `toString` method is
<add> // 'broken' (doesn't return a string, isn't a function, etc.), an error will be thrown:
<add> //
<add> // TypeError: Cannot convert object to primitive value
<add> //
<add> // For performance reasons, we don't catch this error here and allow it to propagate up the call
<add> // stack. Note that you'll get the same error in JavaScript if you try to access a property using
<add> // such a 'broken' object as a key.
<add> return name + '';
<ide> }
<ide>
<ide> function ensureSafeObject(obj, fullExpression) {
<ide> ASTCompiler.prototype = {
<ide> },
<ide>
<ide> getStringValue: function(item) {
<del> this.assign(item, 'getStringValue(' + item + ',text)');
<add> this.assign(item, 'getStringValue(' + item + ')');
<ide> },
<ide>
<ide> ensureSafeAssignContext: function(item) {
<ide><path>test/ng/parseSpec.js
<ide> describe('parser', function() {
<ide> expect(scope.$eval('true || false || run()')).toBe(true);
<ide> });
<ide>
<add> it('should throw TypeError on using a \'broken\' object as a key to access a property', function() {
<add> scope.object = {};
<add> forEach([
<add> { toString: 2 },
<add> { toString: null },
<add> { toString: function() { return {}; } }
<add> ], function(brokenObject) {
<add> scope.brokenObject = brokenObject;
<add> expect(function() {
<add> scope.$eval('object[brokenObject]');
<add> }).toThrow();
<add> });
<add> });
<ide>
<ide> it('should support method calls on primitive types', function() {
<ide> scope.empty = ''; | 2 |
Text | Text | explore definition an usage for opacity | 0e8891956a403dce2d9af0777f321afcae770c4b | <ide><path>guide/english/css/image-opacity-and-transparency/index.md
<ide> The ```opacity``` property allows you to make an image transparent by lowering h
<ide> ```Opacity``` takes a value between 0.0 and 1.0.
<ide>
<ide> 1.0 is the default value for any image. It is fully opaque.
<add>(default)
<add>
<add>Note: When using the opacity property to add transparency to the background of an element, all of its child elements become transparent as well. This can make the text inside a fully transparent element hard to read. If you do not want to apply opacity to child elements, use RGBA color values instead.
<ide>
<ide> Example:
<ide> ```css | 1 |
Java | Java | use jpa from jakarta | e90225336a57fa269ec40d6e238e4a27541b56fc | <ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/orm/JpaEntityListenerTests.java
<ide>
<ide> import java.util.List;
<ide>
<del>import javax.persistence.EntityManager;
<del>import javax.persistence.EntityManagerFactory;
<del>import javax.persistence.PersistenceContext;
<ide> import javax.sql.DataSource;
<ide>
<add>import jakarta.persistence.EntityManager;
<add>import jakarta.persistence.EntityManagerFactory;
<add>import jakarta.persistence.PersistenceContext;
<ide> import org.junit.jupiter.api.BeforeEach;
<ide> import org.junit.jupiter.api.Test;
<ide>
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/orm/domain/JpaPersonRepository.java
<ide>
<ide> package org.springframework.test.context.junit.jupiter.orm.domain;
<ide>
<del>import javax.persistence.EntityManager;
<del>import javax.persistence.PersistenceContext;
<add>import jakarta.persistence.EntityManager;
<add>import jakarta.persistence.PersistenceContext;
<ide>
<ide> import org.springframework.stereotype.Repository;
<ide> import org.springframework.transaction.annotation.Transactional;
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/orm/domain/Person.java
<ide>
<ide> package org.springframework.test.context.junit.jupiter.orm.domain;
<ide>
<del>import javax.persistence.Entity;
<del>import javax.persistence.EntityListeners;
<del>import javax.persistence.GeneratedValue;
<del>import javax.persistence.GenerationType;
<del>import javax.persistence.Id;
<add>import jakarta.persistence.Entity;
<add>import jakarta.persistence.EntityListeners;
<add>import jakarta.persistence.GeneratedValue;
<add>import jakarta.persistence.GenerationType;
<add>import jakarta.persistence.Id;
<ide>
<ide> /**
<ide> * Person entity.
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/orm/domain/PersonListener.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<del>import javax.persistence.PostLoad;
<del>import javax.persistence.PostPersist;
<del>import javax.persistence.PostRemove;
<del>import javax.persistence.PostUpdate;
<del>import javax.persistence.PrePersist;
<del>import javax.persistence.PreRemove;
<del>import javax.persistence.PreUpdate;
<add>import jakarta.persistence.PostLoad;
<add>import jakarta.persistence.PostPersist;
<add>import jakarta.persistence.PostRemove;
<add>import jakarta.persistence.PostUpdate;
<add>import jakarta.persistence.PrePersist;
<add>import jakarta.persistence.PreRemove;
<add>import jakarta.persistence.PreUpdate;
<ide>
<ide> /**
<ide> * Person entity listener. | 4 |
PHP | PHP | remove deprecated method of 3.x | 69e8eac63d3922ef86af3ce82885aee8c551f318 | <ide><path>src/Datasource/EntityTrait.php
<ide> public function getVisible(): array
<ide> return array_diff($fields, $this->_hidden);
<ide> }
<ide>
<del> /**
<del> * Gets the list of visible fields.
<del> *
<del> * @deprecated 4.0.0 Use getVisible() instead. Will be removed in 5.0.
<del> * @return string[]
<del> */
<del> public function visibleProperties(): array
<del> {
<del> return $this->getVisible();
<del> }
<del>
<ide> /**
<ide> * Returns an array with all the fields that have been set
<ide> * to this entity
<ide><path>tests/TestCase/ORM/EntityTest.php
<ide> public function testGetVisible()
<ide> $this->assertSame(['foo', 'bar'], $expected);
<ide> }
<ide>
<del> /**
<del> * Tests the deprecated visibleProperties() method
<del> *
<del> * @return void
<del> */
<del> public function testVisiblePropertiesDeprecated()
<del> {
<del> $entity = new Entity();
<del> $entity->foo = 'foo';
<del> $entity->bar = 'bar';
<del>
<del> $expected = $entity->visibleProperties();
<del> $this->assertSame(['foo', 'bar'], $expected);
<del> }
<del>
<ide> /**
<ide> * Tests setting virtual properties with merging.
<ide> * | 2 |
Text | Text | add more notes to issue template | b5686dd3522f620aee760044d18e506d2de90239 | <ide><path>.github/ISSUE_TEMPLATE.md
<add><!-- Please don't delete this template or we'll close your issue -->
<ide> <!-- Before creating an issue please make sure you are using the latest version of webpack. -->
<add><!-- Also consider trying the webpack@beta version, maybe it's already fixed. -->
<ide>
<ide> **Do you want to request a *feature* or report a *bug*?**
<del><!-- Please ask questions on StackOverflow or the webpack Gitter (https://gitter.im/webpack/webpack). Questions will be closed. -->
<add>
<add><!-- Please ask questions on StackOverflow or the webpack Gitter (https://gitter.im/webpack/webpack). -->
<add><!-- Issues which contain questions or support requests will be closed. -->
<ide>
<ide> **What is the current behavior?**
<ide>
<ide> **If the current behavior is a bug, please provide the steps to reproduce.**
<add>
<ide> <!-- A great way to do this is to provide your configuration via a GitHub gist. -->
<add><!-- Best provide a minimal reproduceable repo -->
<add><!-- If your issue is caused by a plugin or loader file the issue on the plugin/loader repo -->
<ide>
<ide> **What is the expected behavior?**
<ide>
<ide> **If this is a feature request, what is motivation or use case for changing the behavior?**
<ide>
<del>**Please mention other relevant information such as the browser version, Node.js version, Operating System and programming language.**
<add>**Please mention other relevant information such as the browser version, Node.js version, webpack version and Operating System.** | 1 |
Javascript | Javascript | add key for items in textinputexample of rntester | 25f7657cf6bb49d365249ae834847ab0996da20c | <ide><path>RNTester/js/TextInputExample.ios.js
<ide> exports.examples = [
<ide> ];
<ide> const examples = clearButtonModes.map(mode => {
<ide> return (
<del> <WithLabel label={mode}>
<add> <WithLabel key={mode} label={mode}>
<ide> <TextInput
<del> key={mode}
<ide> style={styles.default}
<ide> clearButtonMode={mode}
<ide> defaultValue={mode} | 1 |
Ruby | Ruby | add comment to a table without model | f036862c0fa0377c78007daf7b79715f5cb8ff32 | <ide><path>activerecord/test/schema/postgresql_specific_schema.rb
<ide> rescue #This version of PostgreSQL either has no XML support or is was not compiled with XML support: skipping table
<ide> end
<ide>
<add> # This table is to verify if the :limit option is being ignored for text and binary columns
<ide> create_table :limitless_fields, force: true do |t|
<ide> t.binary :binary, limit: 100_000
<ide> t.text :text, limit: 100_000 | 1 |
Javascript | Javascript | move call to `$digest` into `compileinput` helper | 0ef17276e9aa0aefe5f9aa6f04da5b35dd0f9466 | <ide><path>test/ng/directive/inputSpec.js
<ide> describe('input', function() {
<ide> formElm = jqLite('<form name="form"></form>');
<ide> formElm.append(inputElm);
<ide> $compile(formElm)(scope);
<add> scope.$digest();
<ide> }
<ide>
<ide> beforeEach(inject(function($injector, _$sniffer_, _$browser_) {
<ide> describe('input', function() {
<ide> compileInput(
<ide> '<input type="text" ng-model="name" name="alias" '+
<ide> 'ng-model-options="{ updateOn: \'blur\' }" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('a');
<ide> expect(inputElm.val()).toBe('a');
<ide> describe('input', function() {
<ide> compileInput(
<ide> '<input type="text" ng-model="name" name="alias" '+
<ide> 'ng-model-options="{ debounce: 2000 }" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('a');
<ide> expect(inputElm.val()).toBe('a');
<ide> describe('input', function() {
<ide> it('should report error on assignment error', function() {
<ide> expect(function() {
<ide> compileInput('<input type="text" ng-model="throw \'\'">');
<del> scope.$digest();
<ide> }).toThrowMinErr("$parse", "syntax", "Syntax Error: Token '''' is an unexpected token at column 7 of the expression [throw ''] starting at [''].");
<ide> });
<ide>
<ide> describe('input', function() {
<ide>
<ide> it('should validate in-lined pattern', function() {
<ide> compileInput('<input type="text" ng-model="value" ng-pattern="/^\\d\\d\\d-\\d\\d-\\d\\d\\d\\d$/" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('x000-00-0000x');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide>
<ide> it('should validate in-lined pattern with modifiers', function() {
<ide> compileInput('<input type="text" ng-model="value" ng-pattern="/^abc?$/i" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('aB');
<ide> expect(inputElm).toBeValid();
<ide> describe('input', function() {
<ide>
<ide>
<ide> it('should validate pattern from scope', function() {
<del> compileInput('<input type="text" ng-model="value" ng-pattern="regexp" />');
<ide> scope.regexp = /^\d\d\d-\d\d-\d\d\d\d$/;
<del> scope.$digest();
<add> compileInput('<input type="text" ng-model="value" ng-pattern="regexp" />');
<ide>
<ide> changeInputValueTo('x000-00-0000x');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should come up blank when no value specified', function() {
<ide> compileInput('<input type="month" ng-model="test" />');
<ide>
<del> scope.$digest();
<ide> expect(inputElm.val()).toBe('');
<ide>
<ide> scope.$apply(function() {
<ide> describe('input', function() {
<ide> describe('min', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="month" ng-model="value" name="alias" min="2013-01" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> describe('max', function(){
<ide> beforeEach(function (){
<ide> compileInput('<input type="month" ng-model="value" name="alias" max="2013-01" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should validate', function (){
<ide> describe('input', function() {
<ide> it('should come up blank when no value specified', function() {
<ide> compileInput('<input type="week" ng-model="test" />');
<ide>
<del> scope.$digest();
<ide> expect(inputElm.val()).toBe('');
<ide>
<ide> scope.$apply(function() {
<ide> describe('input', function() {
<ide> describe('min', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="week" ng-model="value" name="alias" min="2013-W01" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> describe('max', function(){
<ide> beforeEach(function (){
<ide> compileInput('<input type="week" ng-model="value" name="alias" max="2013-W01" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should validate', function (){
<ide> describe('input', function() {
<ide> it('should come up blank when no value specified', function() {
<ide> compileInput('<input type="datetime-local" ng-model="test" />');
<ide>
<del> scope.$digest();
<ide> expect(inputElm.val()).toBe('');
<ide>
<ide> scope.$apply(function() {
<ide> describe('input', function() {
<ide> describe('min', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="datetime-local" ng-model="value" name="alias" min="2000-01-01T12:30" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> describe('max', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="datetime-local" ng-model="value" name="alias" max="2019-01-01T01:02" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> it('should validate even if max value changes on-the-fly', function(done) {
<ide> scope.max = '2013-01-01T01:02';
<ide> compileInput('<input type="datetime-local" ng-model="value" name="alias" max="{{max}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('2014-01-01T12:34');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should validate even if min value changes on-the-fly', function(done) {
<ide> scope.min = '2013-01-01T01:02';
<ide> compileInput('<input type="datetime-local" ng-model="value" name="alias" min="{{min}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('2010-01-01T12:34');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should come up blank when no value specified', function() {
<ide> compileInput('<input type="time" ng-model="test" />');
<ide>
<del> scope.$digest();
<ide> expect(inputElm.val()).toBe('');
<ide>
<ide> scope.$apply(function() {
<ide> describe('input', function() {
<ide> describe('min', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="time" ng-model="value" name="alias" min="09:30" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> describe('max', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="time" ng-model="value" name="alias" max="22:30" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> it('should validate even if max value changes on-the-fly', function(done) {
<ide> scope.max = '21:02';
<ide> compileInput('<input type="time" ng-model="value" name="alias" max="{{max}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('22:34');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should validate even if min value changes on-the-fly', function(done) {
<ide> scope.min = '08:45';
<ide> compileInput('<input type="time" ng-model="value" name="alias" min="{{min}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('06:15');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should come up blank when no value specified', function() {
<ide> compileInput('<input type="date" ng-model="test" />');
<ide>
<del> scope.$digest();
<ide> expect(inputElm.val()).toBe('');
<ide>
<ide> scope.$apply(function() {
<ide> describe('input', function() {
<ide> describe('min', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="date" ng-model="value" name="alias" min="2000-01-01" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> describe('max', function (){
<ide> beforeEach(function (){
<ide> compileInput('<input type="date" ng-model="value" name="alias" max="2019-01-01" />');
<del> scope.$digest();
<ide> });
<ide>
<ide> it('should invalidate', function (){
<ide> describe('input', function() {
<ide> it('should validate even if max value changes on-the-fly', function(done) {
<ide> scope.max = '2013-01-01';
<ide> compileInput('<input type="date" ng-model="value" name="alias" max="{{max}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('2014-01-01');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should validate even if min value changes on-the-fly', function(done) {
<ide> scope.min = '2013-01-01';
<ide> compileInput('<input type="date" ng-model="value" name="alias" min="{{min}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('2010-01-01');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should come up blank when no value specified', function() {
<ide> compileInput('<input type="number" ng-model="age" />');
<ide>
<del> scope.$digest();
<ide> expect(inputElm.val()).toBe('');
<ide>
<ide> scope.$apply(function() {
<ide> describe('input', function() {
<ide>
<ide> it('should validate', function() {
<ide> compileInput('<input type="number" ng-model="value" name="alias" min="10" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('1');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should validate even if min value changes on-the-fly', function(done) {
<ide> scope.min = 10;
<ide> compileInput('<input type="number" ng-model="value" name="alias" min="{{min}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('5');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide>
<ide> it('should validate', function() {
<ide> compileInput('<input type="number" ng-model="value" name="alias" max="10" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('20');
<ide> expect(inputElm).toBeInvalid();
<ide> describe('input', function() {
<ide> it('should validate even if max value changes on-the-fly', function(done) {
<ide> scope.max = 10;
<ide> compileInput('<input type="number" ng-model="value" name="alias" max="{{max}}" />');
<del> scope.$digest();
<ide>
<ide> changeInputValueTo('5');
<ide> expect(inputElm).toBeValid();
<ide> describe('input', function() {
<ide>
<ide> it('should set $invalid when model undefined', function() {
<ide> compileInput('<input type="text" ng-model="notDefined" required />');
<del> scope.$digest();
<ide> expect(inputElm).toBeInvalid();
<ide> });
<ide>
<ide> describe('input', function() {
<ide> compileInput('<input type="checkbox" ng-model="foo" ng-change="changeFn()">');
<ide>
<ide> scope.changeFn = jasmine.createSpy('changeFn');
<del> scope.$digest();
<ide> expect(scope.changeFn).not.toHaveBeenCalled();
<ide>
<ide> browserTrigger(inputElm, 'click');
<ide> describe('input', function() {
<ide> compileInput('<input type="radio" ng-model="selected" ng-value="true">' +
<ide> '<input type="radio" ng-model="selected" ng-value="false">' +
<ide> '<input type="radio" ng-model="selected" ng-value="1">');
<del> scope.$digest();
<ide>
<ide> browserTrigger(inputElm[0], 'click');
<ide> expect(scope.selected).toBe(true); | 1 |
Java | Java | fix javadoc in responseentityexceptionhandler | 1c03aaaddc6ab1034d6455ffc8d82fe9d05c54fb | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java
<ide> * individual methods that handle a specific exception, override
<ide> * {@link #handleExceptionInternal} to override common handling of all exceptions,
<ide> * or {@link #createResponseEntity} to intercept the final step of creating the
<del> * @link ResponseEntity} from the selected HTTP status code, headers, and body.
<add> * {@link ResponseEntity} from the selected HTTP status code, headers, and body.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 3.2 | 1 |
Javascript | Javascript | update example to use a module | a5f6a92c8c29115eb85b6987e64fe5987fe2694a | <ide><path>src/ngSanitize/filter/linky.js
<ide> <span ng-bind-html="linky_expression | linky"></span>
<ide> *
<ide> * @example
<del> <example module="ngSanitize" deps="angular-sanitize.js">
<add> <example module="linkyExample" deps="angular-sanitize.js">
<ide> <file name="index.html">
<ide> <script>
<del> function Ctrl($scope) {
<del> $scope.snippet =
<del> 'Pretty text with some links:\n'+
<del> 'http://angularjs.org/,\n'+
<del> 'mailto:[email protected],\n'+
<del> '[email protected],\n'+
<del> 'and one more: ftp://127.0.0.1/.';
<del> $scope.snippetWithTarget = 'http://angularjs.org/';
<del> }
<add> angular.module('linkyExample', ['ngSanitize'])
<add> .controller('ExampleController', ['$scope', function($scope) {
<add> $scope.snippet =
<add> 'Pretty text with some links:\n'+
<add> 'http://angularjs.org/,\n'+
<add> 'mailto:[email protected],\n'+
<add> '[email protected],\n'+
<add> 'and one more: ftp://127.0.0.1/.';
<add> $scope.snippetWithTarget = 'http://angularjs.org/';
<add> }]);
<ide> </script>
<del> <div ng-controller="Ctrl">
<add> <div ng-controller="ExampleController">
<ide> Snippet: <textarea ng-model="snippet" cols="60" rows="3"></textarea>
<ide> <table>
<ide> <tr> | 1 |
Javascript | Javascript | add smarter test for moment.locales | 87127e1f48114e2004b3e9dc442f29bdf8847d00 | <ide><path>src/test/moment/locale.js
<ide> test('defineLocale', function (assert) {
<ide> });
<ide>
<ide> test('locales', function (assert) {
<del> assert.equal(moment.locales().length > 0, true, 'locales returns an array of defined locales');
<add> moment.defineLocale('dude', {months: ['Movember']});
<add> assert.equal(true, !!~moment.locales().indexOf('dude'), 'locales returns an array of defined locales');
<add> assert.equal(true, !!~moment.locales().indexOf('en'), 'locales should always include english');
<ide> });
<ide>
<ide> test('library convenience', function (assert) { | 1 |
Javascript | Javascript | return different functions in timerify | 3d0fc13ba374d539cfb9a70e44310877cb6f7ceb | <ide><path>lib/internal/perf/timerify.js
<ide> const {
<ide> MathCeil,
<ide> ReflectApply,
<ide> ReflectConstruct,
<del> Symbol,
<ide> } = primordials;
<ide>
<ide> const { InternalPerformanceEntry } = require('internal/perf/performance_entry');
<ide> const {
<ide> enqueue,
<ide> } = require('internal/perf/observe');
<ide>
<del>const kTimerified = Symbol('kTimerified');
<del>
<ide> function processComplete(name, start, args, histogram) {
<ide> const duration = now() - start;
<ide> if (histogram !== undefined)
<ide> function timerify(fn, options = {}) {
<ide> histogram);
<ide> }
<ide>
<del> if (fn[kTimerified]) return fn[kTimerified];
<del>
<ide> const constructor = isConstructor(fn);
<ide>
<ide> function timerified(...args) {
<ide> function timerify(fn, options = {}) {
<ide> }
<ide>
<ide> ObjectDefineProperties(timerified, {
<del> [kTimerified]: {
<del> configurable: false,
<del> enumerable: false,
<del> value: timerified,
<del> },
<ide> length: {
<ide> configurable: false,
<ide> enumerable: true,
<ide> function timerify(fn, options = {}) {
<ide> }
<ide> });
<ide>
<del> ObjectDefineProperties(fn, {
<del> [kTimerified]: {
<del> configurable: false,
<del> enumerable: false,
<del> value: timerified,
<del> }
<del> });
<del>
<ide> return timerified;
<ide> }
<ide>
<ide><path>test/parallel/test-performance-function.js
<ide> const {
<ide> });
<ide> }
<ide>
<del>// Function can only be wrapped once, also check length and name
<add>// Function can be wrapped many times, also check length and name
<ide> {
<ide> const m = (a, b = 1) => {};
<ide> const n = performance.timerify(m);
<ide> const o = performance.timerify(m);
<ide> const p = performance.timerify(n);
<del> assert.strictEqual(n, o);
<del> assert.strictEqual(n, p);
<add> assert.notStrictEqual(n, o);
<add> assert.notStrictEqual(n, p);
<add> assert.notStrictEqual(o, p);
<ide> assert.strictEqual(n.length, m.length);
<ide> assert.strictEqual(n.name, 'timerified m');
<add> assert.strictEqual(p.name, 'timerified timerified m');
<ide> }
<ide>
<ide> (async () => { | 2 |
Java | Java | fix deadlock issue in deferredresult | db596d23dea7a8f35b52581d92b00a18c3f45335 | <ide><path>spring-web/src/main/java/org/springframework/web/context/request/async/DeferredResult.java
<ide> private boolean setResultInternal(Object result) {
<ide> return false;
<ide> }
<ide> this.result = result;
<del> if (this.resultHandler != null) {
<del> this.resultHandler.handleResult(this.result);
<del> }
<add> }
<add> if (this.resultHandler != null) {
<add> this.resultHandler.handleResult(this.result);
<ide> }
<ide> return true;
<ide> } | 1 |
PHP | PHP | remove unused code | 0667ff21568dbddaec4775bc6fbe98a8342f892a | <ide><path>src/Console/Command/Task/ControllerTask.php
<ide> public function getHelpers() {
<ide> return $helpers;
<ide> }
<ide>
<del>/**
<del> * Interact with the user and get a list of additional components
<del> *
<del> * @return array Components the user wants to use.
<del> */
<del> public function doComponents() {
<del> $components = ['Paginator'];
<del> return array_merge($components, $this->_doPropertyChoices(
<del> __d('cake_console', "Would you like this controller to use other components\nbesides PaginatorComponent?"),
<del> __d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
<del> ));
<del> }
<del>
<del>/**
<del> * Common code for property choice handling.
<del> *
<del> * @param string $prompt A yes/no question to precede the list
<del> * @param string $example A question for a comma separated list, with examples.
<del> * @return array Array of values for property.
<del> */
<del> protected function _doPropertyChoices($prompt, $example) {
<del> $proceed = $this->in($prompt, ['y', 'n'], 'n');
<del> $property = [];
<del> if (strtolower($proceed) === 'y') {
<del> $propertyList = $this->in($example);
<del> $propertyListTrimmed = str_replace(' ', '', $propertyList);
<del> $property = explode(',', $propertyListTrimmed);
<del> }
<del> return array_filter($property);
<del> }
<del>
<ide> /**
<ide> * Outputs and gets the list of possible controllers from database
<ide> * | 1 |
Ruby | Ruby | fix meson template | 4cdee1b53d0fb2573d5f2ca71d63b3d6e6156f12 | <ide><path>Library/Homebrew/dev-cmd/create.rb
<ide> class #{Formulary.class_s(name)} < Formula
<ide> <% if mode == :cmake %>
<ide> depends_on "cmake" => :build
<ide> <% elsif mode == :meson %>
<del> depends_on "meson" => :build
<add> depends_on "meson-internal" => :build
<ide> depends_on "ninja" => :build
<add> depends_on "python" => :build
<ide> <% elsif mode.nil? %>
<ide> # depends_on "cmake" => :build
<ide> <% end %>
<ide> def install
<ide> "--disable-silent-rules",
<ide> "--prefix=\#{prefix}"
<ide> <% elsif mode == :meson %>
<add> ENV.refurbish_args
<add>
<ide> mkdir "build" do
<ide> system "meson", "--prefix=\#{prefix}", ".."
<ide> system "ninja"
<del> system "ninja", "test"
<ide> system "ninja", "install"
<ide> end
<ide> <% else %> | 1 |
Python | Python | use less memory when dropout is disabled | a2fdc323818af677f88870890669f41ded0c1827 | <ide><path>keras/layers/recurrent.py
<ide> def step(self, x, states):
<ide> # states only contains the previous output.
<ide> assert len(states) == 3 # 1 state and 2 constants
<ide> prev_output = states[0]
<del> B_W = states[1]
<del> B_U = states[2]
<add> if self.dropout_W == 0 and self.dropout_U == 0:
<add> # this uses less memory when dropout is disabled
<add> B_W, B_U = 1, 1
<add> else:
<add> B_W = states[1]
<add> B_U = states[2]
<ide> h = K.dot(x * B_W, self.W) + self.b
<ide> output = self.activation(h + K.dot(prev_output * B_U, self.U))
<ide> return output, [output]
<ide>
<ide> def get_constants(self, X, train=False):
<ide> retain_p_W = 1. - self.dropout_W
<ide> retain_p_U = 1. - self.dropout_U
<del> if train and self.dropout_W > 0 and self.dropout_U > 0:
<add> if train and (self.dropout_W > 0 or self.dropout_U > 0):
<ide> nb_samples = K.shape(X)[0]
<ide> if K._BACKEND == 'tensorflow':
<ide> if not self.input_shape[0]:
<ide> def reset_states(self):
<ide> def step(self, x, states):
<ide> assert len(states) == 3 # 1 state and 2 constants
<ide> h_tm1 = states[0]
<del> B_W = states[1]
<del> B_U = states[2]
<add> if self.dropout_W == 0 and self.dropout_U == 0:
<add> # this uses less memory when dropout is disabled
<add> B_W, B_U = [1] * 3, [1] * 3
<add> else:
<add> B_W = [K.gather(states[1], i) for i in range(3)]
<add> B_U = [K.gather(states[2], i) for i in range(3)]
<ide>
<del> x_z = K.dot(x * K.gather(B_W, 0), self.W_z) + self.b_z
<del> x_r = K.dot(x * K.gather(B_W, 1), self.W_r) + self.b_r
<del> x_h = K.dot(x * K.gather(B_W, 2), self.W_h) + self.b_h
<add> x_z = K.dot(x * B_W[0], self.W_z) + self.b_z
<add> x_r = K.dot(x * B_W[1], self.W_r) + self.b_r
<add> x_h = K.dot(x * B_W[2], self.W_h) + self.b_h
<ide>
<del> z = self.inner_activation(x_z + K.dot(h_tm1 * K.gather(B_U, 0), self.U_z))
<del> r = self.inner_activation(x_r + K.dot(h_tm1 * K.gather(B_U, 1), self.U_r))
<add> z = self.inner_activation(x_z + K.dot(h_tm1 * B_U[0], self.U_z))
<add> r = self.inner_activation(x_r + K.dot(h_tm1 * B_U[1], self.U_r))
<ide>
<del> hh = self.activation(x_h + K.dot(r * h_tm1 * K.gather(B_U, 2), self.U_h))
<add> hh = self.activation(x_h + K.dot(r * h_tm1 * B_U[2], self.U_h))
<ide> h = z * h_tm1 + (1 - z) * hh
<ide> return h, [h]
<ide>
<ide> def get_constants(self, X, train=False):
<ide> retain_p_W = 1. - self.dropout_W
<ide> retain_p_U = 1. - self.dropout_U
<del> if train and self.dropout_W > 0 and self.dropout_U > 0:
<add> if train and (self.dropout_W > 0 or self.dropout_U > 0):
<ide> nb_samples = K.shape(X)[0]
<ide> if K._BACKEND == 'tensorflow':
<ide> if not self.input_shape[0]:
<ide> def step(self, x, states):
<ide> assert len(states) == 4 # 2 states and 2 constants
<ide> h_tm1 = states[0]
<ide> c_tm1 = states[1]
<del> B_W = states[2]
<del> B_U = states[3]
<del>
<del> x_i = K.dot(x * K.gather(B_W, 0), self.W_i) + self.b_i
<del> x_f = K.dot(x * K.gather(B_W, 1), self.W_f) + self.b_f
<del> x_c = K.dot(x * K.gather(B_W, 2), self.W_c) + self.b_c
<del> x_o = K.dot(x * K.gather(B_W, 3), self.W_o) + self.b_o
<del>
<del> i = self.inner_activation(x_i + K.dot(h_tm1 * K.gather(B_U, 0), self.U_i))
<del> f = self.inner_activation(x_f + K.dot(h_tm1 * K.gather(B_U, 1), self.U_f))
<del> c = f * c_tm1 + i * self.activation(x_c + K.dot(h_tm1 * K.gather(B_U, 2), self.U_c))
<del> o = self.inner_activation(x_o + K.dot(h_tm1 * K.gather(B_U, 3), self.U_o))
<add> if self.dropout_W == 0 and self.dropout_U == 0:
<add> # this uses less memory when dropout is disabled
<add> B_W, B_U = [1] * 4, [1] * 4
<add> else:
<add> B_W = [K.gather(states[2], i) for i in range(4)]
<add> B_U = [K.gather(states[3], i) for i in range(4)]
<add>
<add> x_i = K.dot(x * B_W[0], self.W_i) + self.b_i
<add> x_f = K.dot(x * B_W[1], self.W_f) + self.b_f
<add> x_c = K.dot(x * B_W[2], self.W_c) + self.b_c
<add> x_o = K.dot(x * B_W[3], self.W_o) + self.b_o
<add>
<add> i = self.inner_activation(x_i + K.dot(h_tm1 * B_U[0], self.U_i))
<add> f = self.inner_activation(x_f + K.dot(h_tm1 * B_U[1], self.U_f))
<add> c = f * c_tm1 + i * self.activation(x_c + K.dot(h_tm1 * B_U[2], self.U_c))
<add> o = self.inner_activation(x_o + K.dot(h_tm1 * B_U[3], self.U_o))
<ide> h = o * self.activation(c)
<ide> return h, [h, c]
<ide>
<ide> def get_constants(self, X, train=False):
<ide> retain_p_W = 1. - self.dropout_W
<ide> retain_p_U = 1. - self.dropout_U
<del> if train and self.dropout_W > 0 and self.dropout_U > 0:
<add> if train and (self.dropout_W > 0 or self.dropout_U > 0):
<ide> nb_samples = K.shape(X)[0]
<ide> if K._BACKEND == 'tensorflow':
<ide> if not self.input_shape[0]: | 1 |
Text | Text | add sub domain to host in url | 9acd6c9aef399dbafa8a57399fbbb45376d7a81b | <ide><path>doc/api/url.md
<ide> When parsed, a URL object is returned containing properties for each of these
<ide> components.
<ide>
<ide> The following details each of the components of a parsed URL. The example
<del>`'http://user:[email protected]:8080/p/a/t/h?query=string#hash'` is used to
<add>`'http://user:[email protected]:8080/p/a/t/h?query=string#hash'` is used to
<ide> illustrate each.
<ide>
<ide> ```txt
<del>┌─────────────────────────────────────────────────────────────────────────────┐
<del>│ href │
<del>├──────────┬┬───────────┬─────────────────┬───────────────────────────┬───────┤
<del>│ protocol ││ auth │ host │ path │ hash │
<del>│ ││ ├──────────┬──────┼──────────┬────────────────┤ │
<del>│ ││ │ hostname │ port │ pathname │ search │ │
<del>│ ││ │ │ │ ├─┬──────────────┤ │
<del>│ ││ │ │ │ │ │ query │ │
<del>" http: // user:pass @ host.com : 8080 /p/a/t/h ? query=string #hash "
<del>│ ││ │ │ │ │ │ │ │
<del>└──────────┴┴───────────┴──────────┴──────┴──────────┴─┴──────────────┴───────┘
<add>┌─────────────────────────────────────────────────────────────────────────────────┐
<add>│ href │
<add>├──────────┬┬───────────┬─────────────────────┬───────────────────────────┬───────┤
<add>│ protocol ││ auth │ host │ path │ hash │
<add>│ ││ ├──────────────┬──────┼──────────┬────────────────┤ │
<add>│ ││ │ hostname │ port │ pathname │ search │ │
<add>│ ││ │ │ │ ├─┬──────────────┤ │
<add>│ ││ │ │ │ │ │ query │ │
<add>" http: // user:pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash "
<add>│ ││ │ │ │ │ │ │ │
<add>└──────────┴┴───────────┴──────────────┴──────┴──────────┴─┴──────────────┴───────┘
<ide> (all spaces in the "" line should be ignored -- they are purely for formatting)
<ide> ```
<ide>
<ide> For example: `'#hash'`
<ide> The `host` property is the full lower-cased host portion of the URL, including
<ide> the `port` if specified.
<ide>
<del>For example: `'host.com:8080'`
<add>For example: `'sub.host.com:8080'`
<ide>
<ide> ### urlObject.hostname
<ide>
<ide> The `hostname` property is the lower-cased host name portion of the `host`
<ide> component *without* the `port` included.
<ide>
<del>For example: `'host.com'`
<add>For example: `'sub.host.com'`
<ide>
<ide> ### urlObject.href
<ide>
<ide> The `href` property is the full URL string that was parsed with both the
<ide> `protocol` and `host` components converted to lower-case.
<ide>
<del>For example: `'http://user:[email protected]:8080/p/a/t/h?query=string#hash'`
<add>For example: `'http://user:[email protected]:8080/p/a/t/h?query=string#hash'`
<ide>
<ide> ### urlObject.path
<ide>
<ide> console.log(myURL.pathname); // /foo
<ide> `delete myURL.pathname`, etc) has no effect but will still return `true`.
<ide>
<ide> A comparison between this API and `url.parse()` is given below. Above the URL
<del>`'http://user:[email protected]:8080/p/a/t/h?query=string#hash'`, properties of an
<add>`'http://user:[email protected]:8080/p/a/t/h?query=string#hash'`, properties of an
<ide> object returned by `url.parse()` are shown. Below it are properties of a WHATWG
<ide> `URL` object.
<ide>
<ide> *Note*: WHATWG URL's `origin` property includes `protocol` and `host`, but not
<ide> `username` or `password`.
<ide>
<ide> ```txt
<del>┌─────────────────────────────────────────────────────────────────────────────────────────┐
<del>│ href │
<del>├──────────┬──┬─────────────────────┬─────────────────┬───────────────────────────┬───────┤
<del>│ protocol │ │ auth │ host │ path │ hash │
<del>│ │ │ ├──────────┬──────┼──────────┬────────────────┤ │
<del>│ │ │ │ hostname │ port │ pathname │ search │ │
<del>│ │ │ │ │ │ ├─┬──────────────┤ │
<del>│ │ │ │ │ │ │ │ query │ │
<del>" http: // user : pass @ host.com : 8080 /p/a/t/h ? query=string #hash "
<del>│ │ │ │ │ hostname │ port │ │ │ │
<del>│ │ │ │ ├──────────┴──────┤ │ │ │
<del>│ protocol │ │ username │ password │ host │ │ │ │
<del>├──────────┴──┼──────────┴──────────┼─────────────────┤ │ │ │
<del>│ origin │ │ origin │ pathname │ search │ hash │
<del>├─────────────┴─────────────────────┴─────────────────┴──────────┴────────────────┴───────┤
<del>│ href │
<del>└─────────────────────────────────────────────────────────────────────────────────────────┘
<add>┌─────────────────────────────────────────────────────────────────────────────────────────────┐
<add>│ href │
<add>├──────────┬──┬─────────────────────┬─────────────────────┬───────────────────────────┬───────┤
<add>│ protocol │ │ auth │ host │ path │ hash │
<add>│ │ │ ├──────────────┬──────┼──────────┬────────────────┤ │
<add>│ │ │ │ hostname │ port │ pathname │ search │ │
<add>│ │ │ │ │ │ ├─┬──────────────┤ │
<add>│ │ │ │ │ │ │ │ query │ │
<add>" http: // user : pass @ sub.host.com : 8080 /p/a/t/h ? query=string #hash "
<add>│ │ │ │ │ hostname │ port │ │ │ │
<add>│ │ │ │ ├──────────────┴──────┤ │ │ │
<add>│ protocol │ │ username │ password │ host │ │ │ │
<add>├──────────┴──┼──────────┴──────────┼─────────────────────┤ │ │ │
<add>│ origin │ │ origin │ pathname │ search │ hash │
<add>├─────────────┴─────────────────────┴─────────────────────┴──────────┴────────────────┴───────┤
<add>│ href │
<add>└─────────────────────────────────────────────────────────────────────────────────────────────┘
<ide> (all spaces in the "" line should be ignored -- they are purely for formatting)
<ide> ```
<ide> | 1 |
Javascript | Javascript | add symbol test for assert.deepequal() | 0f99320aa0d13c83e41d14f3cbbdbd12884ce5eb | <ide><path>test/parallel/test-assert.js
<ide> assert.throws(makeBlock(a.deepEqual, 'a', ['a']), a.AssertionError);
<ide> assert.throws(makeBlock(a.deepEqual, 'a', {0: 'a'}), a.AssertionError);
<ide> assert.throws(makeBlock(a.deepEqual, 1, {}), a.AssertionError);
<ide> assert.throws(makeBlock(a.deepEqual, true, {}), a.AssertionError);
<del>if (typeof Symbol === 'symbol') {
<del> assert.throws(makeBlock(assert.deepEqual, Symbol(), {}), a.AssertionError);
<del>}
<add>assert.throws(makeBlock(a.deepEqual, Symbol(), {}), a.AssertionError);
<ide>
<ide> // primitive wrappers and object
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, new String('a'), ['a']), | 1 |
Go | Go | remove uses of pkg/urlutil.istransporturl() | 2e831c76c245b262597d3b9f26ef035e8dec0230 | <ide><path>daemon/logger/gelf/gelf.go
<ide> import (
<ide> "github.com/Graylog2/go-gelf/gelf"
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/logger/loggerutils"
<del> "github.com/docker/docker/pkg/urlutil"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<ide> func parseAddress(address string) (*url.URL, error) {
<ide> if address == "" {
<ide> return nil, fmt.Errorf("gelf-address is a required parameter")
<ide> }
<del> if !urlutil.IsTransportURL(address) {
<del> return nil, fmt.Errorf("gelf-address should be in form proto://address, got %v", address)
<del> }
<del> url, err := url.Parse(address)
<add> addr, err := url.Parse(address)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide>
<del> // we support only udp
<del> if url.Scheme != "udp" && url.Scheme != "tcp" {
<add> if addr.Scheme != "udp" && addr.Scheme != "tcp" {
<ide> return nil, fmt.Errorf("gelf: endpoint needs to be TCP or UDP")
<ide> }
<ide>
<del> // get host and port
<del> if _, _, err = net.SplitHostPort(url.Host); err != nil {
<add> if _, _, err = net.SplitHostPort(addr.Host); err != nil {
<ide> return nil, fmt.Errorf("gelf: please provide gelf-address as proto://host:port")
<ide> }
<ide>
<del> return url, nil
<add> return addr, nil
<ide> }
<ide><path>daemon/logger/gelf/gelf_test.go
<ide> func TestNewTCP(t *testing.T) {
<ide> ContainerID: "12345678901234567890",
<ide> }
<ide>
<del> logger, err := New(info)
<add> gelfLogger, err := New(info)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = logger.Close()
<add> err = gelfLogger.Close()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestNewUDP(t *testing.T) {
<ide> ContainerID: "12345678901234567890",
<ide> }
<ide>
<del> logger, err := New(info)
<add> gelfLogger, err := New(info)
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> err = logger.Close()
<add> err = gelfLogger.Close()
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> } | 2 |
Text | Text | fix links in readme.md | 3607bf489a961207d6171ea0c8a38dbdb2721261 | <ide><path>im2txt/README.md
<ide> Each caption is a list of words. During preprocessing, a dictionary is created
<ide> that assigns each word in the vocabulary to an integer-valued id. Each caption
<ide> is encoded as a list of integer word ids in the `tf.SequenceExample` protos.
<ide>
<del>We have provided a script to download and preprocess the [MSCOCO]
<del>(http://mscoco.org/) image captioning data set into this format. Downloading
<add>We have provided a script to download and preprocess the [MSCOCO](http://mscoco.org/) image captioning data set into this format. Downloading
<ide> and preprocessing the data may take several hours depending on your network and
<ide> computer speed. Please be patient.
<ide>
<ide> tensorboard --logdir="${MODEL_DIR}"
<ide> ### Fine Tune the Inception v3 Model
<ide>
<ide> Your model will already be able to generate reasonable captions after the first
<del>phase of training. Try it out! (See [Generating Captions]
<del>(#generating-captions)).
<add>phase of training. Try it out! (See [Generating Captions](#generating-captions)).
<ide>
<ide> You can further improve the performance of the model by running a
<ide> second training phase to jointly fine-tune the parameters of the *Inception v3*
<ide> expected.
<ide>
<ide> Here is the image:
<ide>
<del><center>
<ide> 
<del></center> | 1 |
Ruby | Ruby | require ruby-debug from new_base/abstract_unit | d1d9a6c26113cf4a0decb504c46e4e7fe4351ce6 | <ide><path>actionpack/test/new_base/abstract_unit.rb
<ide>
<ide> $tags[:new_base] = true
<ide>
<add>begin
<add> require 'ruby-debug'
<add> Debugger.settings[:autoeval] = true
<add> Debugger.start
<add>rescue LoadError
<add> # Debugging disabled. `gem install ruby-debug` to enable.
<add>end
<ide>
<ide> ActiveSupport::Dependencies.hook!
<ide> | 1 |
Go | Go | add unit test for validateip4address | 5a9cf7e75442ce1c76876da717b8c2f321fc04ae | <ide><path>opts_unit_test.go
<add>package docker
<add>
<add>import (
<add> "testing"
<add>)
<add>
<add>func TestValidateIP4(t *testing.T) {
<add> if ret, err := ValidateIp4Address(`1.2.3.4`); err != nil || ret == "" {
<add> t.Fatalf("ValidateIp4Address(`1.2.3.4`) got %s %s", ret, err)
<add> }
<add>
<add> if ret, err := ValidateIp4Address(`127.0.0.1`); err != nil || ret == "" {
<add> t.Fatalf("ValidateIp4Address(`127.0.0.1`) got %s %s", ret, err)
<add> }
<add>
<add> if ret, err := ValidateIp4Address(`127`); err == nil || ret != "" {
<add> t.Fatalf("ValidateIp4Address(`127`) got %s %s", ret, err)
<add> }
<add>
<add> if ret, err := ValidateIp4Address(`random invalid string`); err == nil || ret != "" {
<add> t.Fatalf("ValidateIp4Address(`random invalid string`) got %s %s", ret, err)
<add> }
<add>
<add>} | 1 |
PHP | PHP | state | d787947998089e6eac4883d90418601fdb5c529d | <ide><path>src/Illuminate/Database/Eloquent/Factories/Factory.php
<ide> protected function expandAttributes(array $definition)
<ide> /**
<ide> * Add a new state transformation to the model definition.
<ide> *
<del> * @param (callable(array<string, mixed>, \Illuminate\Database\Eloquent\Model|null=): array<string, mixed>)|array<string, mixed> $state
<add> * @param (callable(array<string, mixed>, \Illuminate\Database\Eloquent\Model|null): array<string, mixed>)|array<string, mixed> $state
<ide> * @return static
<ide> */
<ide> public function state($state) | 1 |
Ruby | Ruby | give more context from `associationmismatcherror` | 0991c4c6fc0c04764f34c6b65a42adce190440c3 | <ide><path>activerecord/lib/active_record/associations/association.rb
<ide> def raise_on_type_mismatch!(record)
<ide> unless record.is_a?(reflection.klass)
<ide> fresh_class = reflection.class_name.safe_constantize
<ide> unless fresh_class && record.is_a?(fresh_class)
<del> message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, got #{record.class}(##{record.class.object_id})"
<add> message = "#{reflection.class_name}(##{reflection.klass.object_id}) expected, "\
<add> "got #{record.inspect} which is an instance of #{record.class}(##{record.class.object_id})"
<ide> raise ActiveRecord::AssociationTypeMismatch, message
<ide> end
<ide> end
<ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb
<ide> def test_raises_type_mismatch_with_namespaced_class
<ide> e = assert_raise(ActiveRecord::AssociationTypeMismatch) {
<ide> Admin::RegionalUser.new(region: 'wrong value')
<ide> }
<del> assert_match(/^Region\([^)]+\) expected, got String\([^)]+\)$/, e.message)
<add> assert_match(/^Region\([^)]+\) expected, got "wrong value" which is an instance of String\([^)]+\)$/, e.message)
<ide> ensure
<ide> Admin.send :remove_const, "Region" if Admin.const_defined?("Region")
<ide> Admin.send :remove_const, "RegionalUser" if Admin.const_defined?("RegionalUser") | 2 |
Python | Python | fix some issues in spanish examples | 3d50b1a9898d91c1a3bf796af0e849020d564480 | <ide><path>spacy/lang/es/examples.py
<ide> sentences = [
<ide> "Apple está buscando comprar una startup del Reino Unido por mil millones de dólares.",
<ide> "Los coches autónomos delegan la responsabilidad del seguro en sus fabricantes.",
<del> "San Francisco analiza prohibir los robots delivery.",
<add> "San Francisco analiza prohibir los robots de reparto.",
<ide> "Londres es una gran ciudad del Reino Unido.",
<ide> "El gato come pescado.",
<ide> "Veo al hombre con el telescopio.",
<ide> "La araña come moscas.",
<ide> "El pingüino incuba en su nido sobre el hielo.",
<del> "¿Dónde estais?",
<del> "¿Quién es el presidente Francés?",
<del> "¿Dónde está encuentra la capital de Argentina?",
<add> "¿Dónde estáis?",
<add> "¿Quién es el presidente francés?",
<add> "¿Dónde se encuentra la capital de Argentina?",
<ide> "¿Cuándo nació José de San Martín?",
<ide> ] | 1 |
Text | Text | fix url bug in docs | 4c6726918ecabeec858134a14766c8adf727a7b1 | <ide><path>docs/introduction/Ecosystem.md
<ide> A cross-platform Electron app for inspecting React and React Native apps, includ
<ide>
<ide> #### DevTools Monitors
<ide>
<del>**[Log Monitor](https://github.com/reduxjs/redux-devtools-log-monitor)** <br />
<add>**[Log Monitor](https://github.com/reduxjs/redux-devtools/tree/master/packages/redux-devtools-log-monitor)** <br />
<ide> The default monitor for Redux DevTools with a tree view
<ide>
<del>**[Dock Monitor](https://github.com/reduxjs/redux-devtools-dock-monitor)** <br />
<add>**[Dock Monitor](https://github.com/reduxjs/redux-devtools/tree/master/packages/redux-devtools-dock-monitor)** <br />
<ide> A resizable and movable dock for Redux DevTools monitors
<ide>
<ide> **[Slider Monitor](https://github.com/calesce/redux-slider-monitor)** <br /> | 1 |
Ruby | Ruby | bring config.allow_concurrency back | 9ee6f3cc8ef1cd50648ec2882803943d3bd1f24a | <ide><path>railties/lib/rails/application.rb
<ide> def reload_dependencies? #:nodoc:
<ide> def default_middleware_stack #:nodoc:
<ide> ActionDispatch::MiddlewareStack.new.tap do |middleware|
<ide> app = self
<del> if rack_cache = config.action_dispatch.rack_cache
<del> begin
<del> require 'rack/cache'
<del> rescue LoadError => error
<del> error.message << ' Be sure to add rack-cache to your Gemfile'
<del> raise
<del> end
<del>
<del> if rack_cache == true
<del> rack_cache = {
<del> metastore: "rails:/",
<del> entitystore: "rails:/",
<del> verbose: false
<del> }
<del> end
<ide>
<add> if rack_cache = load_rack_cache
<ide> require "action_dispatch/http/rack_cache"
<ide> middleware.use ::Rack::Cache, rack_cache
<ide> end
<ide> def default_middleware_stack #:nodoc:
<ide> middleware.use ::ActionDispatch::Static, paths["public"].first, config.static_cache_control
<ide> end
<ide>
<del> middleware.use ::Rack::Lock unless config.cache_classes
<add> middleware.use ::Rack::Lock unless allow_concurrency?
<ide> middleware.use ::Rack::Runtime
<ide> middleware.use ::Rack::MethodOverride
<ide> middleware.use ::ActionDispatch::RequestId
<del> middleware.use ::Rails::Rack::Logger, config.log_tags # must come after Rack::MethodOverride to properly log overridden methods
<del> middleware.use ::ActionDispatch::ShowExceptions, config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
<add>
<add> # Must come after Rack::MethodOverride to properly log overridden methods
<add> middleware.use ::Rails::Rack::Logger, config.log_tags
<add> middleware.use ::ActionDispatch::ShowExceptions, show_exceptions_app
<ide> middleware.use ::ActionDispatch::DebugExceptions, app
<ide> middleware.use ::ActionDispatch::RemoteIp, config.action_dispatch.ip_spoofing_check, config.action_dispatch.trusted_proxies
<ide>
<ide> def default_middleware_stack #:nodoc:
<ide> end
<ide> end
<ide>
<add> def allow_concurrency?
<add> if config.allow_concurrency.nil?
<add> config.cache_classes
<add> else
<add> config.allow_concurrency
<add> end
<add> end
<add>
<add> def load_rack_cache
<add> rack_cache = config.action_dispatch.rack_cache
<add> return unless rack_cache
<add>
<add> begin
<add> require 'rack/cache'
<add> rescue LoadError => error
<add> error.message << ' Be sure to add rack-cache to your Gemfile'
<add> raise
<add> end
<add>
<add> if rack_cache == true
<add> {
<add> metastore: "rails:/",
<add> entitystore: "rails:/",
<add> verbose: false
<add> }
<add> else
<add> rack_cache
<add> end
<add> end
<add>
<add> def show_exceptions_app
<add> config.exceptions_app || ActionDispatch::PublicExceptions.new(Rails.public_path)
<add> end
<add>
<ide> def build_original_fullpath(env) #:nodoc:
<ide> path_info = env["PATH_INFO"]
<ide> query_string = env["QUERY_STRING"]
<ide><path>railties/lib/rails/application/configuration.rb
<ide> module Rails
<ide> class Application
<ide> class Configuration < ::Rails::Engine::Configuration
<del> attr_accessor :asset_host, :assets, :autoflush_log,
<add> attr_accessor :allow_concurrency, :asset_host, :assets, :autoflush_log,
<ide> :cache_classes, :cache_store, :consider_all_requests_local, :console,
<ide> :eager_load, :exceptions_app, :file_watcher, :filter_parameters,
<ide> :force_ssl, :helpers_paths, :logger, :log_formatter, :log_tags,
<ide> class Configuration < ::Rails::Engine::Configuration
<ide> def initialize(*)
<ide> super
<ide> self.encoding = "utf-8"
<add> @allow_concurrency = nil
<ide> @consider_all_requests_local = false
<ide> @filter_parameters = []
<ide> @filter_redirect = []
<ide><path>railties/test/application/middleware_test.rb
<ide> def app
<ide> assert !middleware.include?("Rack::Lock")
<ide> end
<ide>
<add> test "removes lock if allow concurrency is set" do
<add> add_to_config "config.allow_concurrency = true"
<add> boot!
<add> assert !middleware.include?("Rack::Lock")
<add> end
<add>
<ide> test "removes static asset server if serve_static_assets is disabled" do
<ide> add_to_config "config.serve_static_assets = false"
<ide> boot! | 3 |
Ruby | Ruby | trim unnecessary 'the' | 142be05c0f6070c71fa3dc38e86711bdca372fb5 | <ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_access_share_man
<ide>
<ide> def check_access_homebrew_repository
<ide> unless HOMEBREW_REPOSITORY.writable_real? then <<-EOS.undent
<del> The #{HOMEBREW_REPOSITORY} is not writable.
<add> #{HOMEBREW_REPOSITORY} is not writable.
<ide>
<ide> You should probably change the ownership and permissions of #{HOMEBREW_REPOSITORY}
<ide> back to your user account.
<ide> def check_access_usr_local
<ide> return unless HOMEBREW_PREFIX.to_s == "/usr/local"
<ide>
<ide> unless HOMEBREW_PREFIX.writable_real? then <<-EOS.undent
<del> The /usr/local directory is not writable.
<add> /usr/local is not writable.
<ide> Even if this directory was writable when you installed Homebrew, other
<ide> software may change permissions on this directory. For example, upgrading
<ide> to OS X El Capitan has been known to do this. Some versions of the | 1 |
Ruby | Ruby | ignore case in origin comparison | b24e96e28da945cf063f5868f32afeed7e002dd1 | <ide><path>Library/Homebrew/diagnostic.rb
<ide> def check_coretap_git_origin
<ide> properly. You can solve this by adding the Homebrew remote:
<ide> git -C "#{coretap_path}" remote add origin #{Formatter.url(CoreTap.instance.default_remote)}
<ide> EOS
<del> elsif origin !~ %r{#{CoreTap.instance.full_name}(\.git|/)?$}
<add> elsif origin !~ %r{#{CoreTap.instance.full_name}(\.git|/)?$}i
<ide> <<~EOS
<ide> Suspicious #{CoreTap.instance} git origin remote found.
<ide> | 1 |
Javascript | Javascript | allow wildcards in common name | 4dd70bb12c4c7be47d661ae2e950600ed7ab560d | <ide><path>lib/tls.js
<ide> function checkServerIdentity(host, cert) {
<ide> dnsNames = dnsNames.concat(uriNames);
<ide>
<ide> // And only after check if hostname matches CN
<del> // (because CN is deprecated, but should be used for compatiblity anyway)
<ide> var commonNames = cert.subject.CN;
<ide> if (Array.isArray(commonNames)) {
<ide> for (var i = 0, k = commonNames.length; i < k; ++i) {
<del> dnsNames.push(regexpify(commonNames[i], false));
<add> dnsNames.push(regexpify(commonNames[i], true));
<ide> }
<ide> } else {
<del> dnsNames.push(regexpify(commonNames, false));
<add> dnsNames.push(regexpify(commonNames, true));
<ide> }
<ide>
<ide> valid = dnsNames.some(function(re) { | 1 |
Javascript | Javascript | add deprecation for quoteless outlet names | 788c825b27b7c9b884a91635207742de1fcad8c1 | <ide><path>packages/ember-routing-handlebars/lib/helpers/outlet.js
<ide> export function outletHelper(property, options) {
<ide> property = 'main';
<ide> }
<ide>
<add> Ember.deprecate(
<add> "Using {{outlet}} with an unquoted name is not supported. " +
<add> "Please update to quoted usage '{{outlet \"" + property + "\"}}'.",
<add> arguments.length === 1 || options.types[0] === 'STRING'
<add> );
<add>
<ide> var view = options.data.view;
<ide> var container = view.container;
<ide>
<ide> export function outletHelper(property, options) {
<ide>
<ide> if (viewName) {
<ide> viewFullName = 'view:' + viewName;
<del> Ember.assert("Using a quoteless view parameter with {{outlet}} is not supported." +
<del> " Please update to quoted usage '{{outlet \"" + viewName + "\"}}.", options.hashTypes.view !== 'ID');
<del> Ember.assert("The view name you supplied '" + viewName + "' did not resolve to a view.", container.has(viewFullName));
<add> Ember.assert(
<add> "Using a quoteless view parameter with {{outlet}} is not supported." +
<add> " Please update to quoted usage '{{outlet ... view=\"" + viewName + "\"}}.",
<add> options.hashTypes.view !== 'ID'
<add> );
<add> Ember.assert(
<add> "The view name you supplied '" + viewName + "' did not resolve to a view.",
<add> container.has(viewFullName)
<add> );
<ide> }
<ide>
<ide> viewClass = viewName ? container.lookupFactory(viewFullName) : options.hash.viewClass || OutletView;
<ide><path>packages/ember-routing-htmlbars/lib/helpers/outlet.js
<ide> export function outletHelper(params, hash, options, env) {
<ide> var viewClass;
<ide> var viewFullName;
<ide>
<del> Ember.assert("Outlet names must be a string literal, e.g. {{outlet \"header\"}}",
<del> params.length === 0 || options.types[0] === 'string');
<add> Ember.assert(
<add> "Using {{outlet}} with an unquoted name is not supported.",
<add> params.length === 0 || options.types[0] === 'string'
<add> );
<ide>
<ide> var property = params[0] || 'main';
<ide>
<ide> export function outletHelper(params, hash, options, env) {
<ide>
<ide> if (viewName) {
<ide> viewFullName = 'view:' + viewName;
<del> Ember.assert("Using a quoteless view parameter with {{outlet}} is not supported." +
<del> " Please update to quoted usage '{{outlet \"" + viewName + "\"}}.", options.hashTypes.view === 'string');
<del> Ember.assert("The view name you supplied '" + viewName + "' did not resolve to a view.", this.container.has(viewFullName));
<add> Ember.assert(
<add> "Using a quoteless view parameter with {{outlet}} is not supported." +
<add> " Please update to quoted usage '{{outlet ... view=\"" + viewName + "\"}}.",
<add> options.hashTypes.view === 'string'
<add> );
<add> Ember.assert(
<add> "The view name you supplied '" + viewName + "' did not resolve to a view.",
<add> this.container.has(viewFullName)
<add> );
<ide> }
<ide>
<ide> viewClass = viewName ? this.container.lookupFactory(viewFullName) : hash.viewClass || OutletView;
<ide><path>packages/ember-routing-htmlbars/tests/helpers/outlet_test.js
<ide> test("should support layouts", function() {
<ide> // Replace whitespace for older IE
<ide> equal(trim(view.$().text()), 'HIBYE');
<ide> });
<add>
<add>test("should not throw deprecations if {{outlet}} is used without a name", function() {
<add> expectNoDeprecation();
<add> view = EmberView.create({
<add> template: compile("{{outlet}}")
<add> });
<add> appendView(view);
<add>});
<add>
<add>test("should not throw deprecations if {{outlet}} is used with a quoted name", function() {
<add> expectNoDeprecation();
<add> view = EmberView.create({
<add> template: compile("{{outlet \"foo\"}}"),
<add> });
<add> appendView(view);
<add>});
<add>
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add> test("should throw an assertion if {{outlet}} used with unquoted name", function() {
<add> view = EmberView.create({
<add> template: compile("{{outlet foo}}"),
<add> });
<add> expectAssertion(function() {
<add> appendView(view);
<add> }, "Using {{outlet}} with an unquoted name is not supported.");
<add> });
<add>} else {
<add> test("should throw a deprecation if {{outlet}} is used with an unquoted name", function() {
<add> view = EmberView.create({
<add> template: compile("{{outlet foo}}")
<add> });
<add> expectDeprecation(function() {
<add> appendView(view);
<add> }, 'Using {{outlet}} with an unquoted name is not supported. Please update to quoted usage \'{{outlet "foo"}}\'.');
<add> });
<add>} | 3 |
Ruby | Ruby | allow both 'rake' and 'rails' | 5c99a4b93e99cac2bc00fa79da6d79aa37582890 | <ide><path>railties/lib/rails/generators/actions.rb
<ide> def generate(what, *args)
<ide> in_root { run_ruby_script("bin/rails generate #{what} #{argument}", verbose: false) }
<ide> end
<ide>
<del> # Runs the supplied rake task
<add> # Runs the supplied rake task (invoked with 'rake ...')
<ide> #
<ide> # rake("db:migrate")
<ide> # rake("db:migrate", env: "production")
<ide> # rake("gems:install", sudo: true)
<ide> def rake(command, options={})
<del> log :rake, command
<del> env = options[:env] || ENV["RAILS_ENV"] || 'development'
<del> sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
<del> in_root { run("#{sudo}#{extify(:rails)} #{command} RAILS_ENV=#{env}", verbose: false) }
<add> execute_command :rake, command, options
<add> end
<add>
<add> # Runs the supplied rake task (invoked with 'rails ...')
<add> #
<add> # rails("db:migrate")
<add> # rails("db:migrate", env: "production")
<add> # rails("gems:install", sudo: true)
<add> def rails_command(command, options={})
<add> execute_command :rails, command, options
<ide> end
<del> alias :rails_command :rake
<ide>
<ide> # Just run the capify command in root
<ide> #
<ide> def log(*args)
<ide> end
<ide> end
<ide>
<add>
<add> # Runs the supplied command using either "rake ..." or "rails ..."
<add> # based on the executor parameter provided.
<add> def execute_command(executor, command, options={})
<add> log executor, command
<add> env = options[:env] || ENV["RAILS_ENV"] || 'development'
<add> sudo = options[:sudo] && RbConfig::CONFIG['host_os'] !~ /mswin|mingw/ ? 'sudo ' : ''
<add> in_root { run("#{sudo}#{extify(executor)} #{command} RAILS_ENV=#{env}", verbose: false) }
<add> end
<add>
<ide> # Add an extension to the given name based on the platform.
<ide> def extify(name)
<ide> if RbConfig::CONFIG['host_os'] =~ /mswin|mingw/
<ide><path>railties/test/generators/actions_test.rb
<ide> def test_generate_should_run_script_generate_with_argument_and_options
<ide> end
<ide>
<ide> def test_rails_should_run_rake_command_with_default_env
<del> assert_called_with(generator, :run, ["rails log:clear RAILS_ENV=development", verbose: false]) do
<add> assert_called_with(generator, :run, ["rake log:clear RAILS_ENV=development", verbose: false]) do
<ide> with_rails_env nil do
<ide> action :rake, 'log:clear'
<ide> end
<ide> end
<ide> end
<ide>
<ide> def test_rails_with_env_option_should_run_rake_command_in_env
<del> assert_called_with(generator, :run, ['rails log:clear RAILS_ENV=production', verbose: false]) do
<add> assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do
<ide> action :rake, 'log:clear', env: 'production'
<ide> end
<ide> end
<ide>
<ide> test "rails command with RAILS_ENV variable should run rake command in env" do
<del> assert_called_with(generator, :run, ['rails log:clear RAILS_ENV=production', verbose: false]) do
<add> assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do
<ide> with_rails_env "production" do
<ide> action :rake, 'log:clear'
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "env option should win over RAILS_ENV variable when running rake" do
<del> assert_called_with(generator, :run, ['rails log:clear RAILS_ENV=production', verbose: false]) do
<add> assert_called_with(generator, :run, ['rake log:clear RAILS_ENV=production', verbose: false]) do
<ide> with_rails_env "staging" do
<ide> action :rake, 'log:clear', env: 'production'
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "rails command with sudo option should run rake command with sudo" do
<del> assert_called_with(generator, :run, ["sudo rails log:clear RAILS_ENV=development", verbose: false]) do
<add> assert_called_with(generator, :run, ["sudo rake log:clear RAILS_ENV=development", verbose: false]) do
<ide> with_rails_env nil do
<ide> action :rake, 'log:clear', sudo: true
<ide> end | 2 |
Text | Text | note python compatibility | e919cb1b57a27f581c07080e341a86421df78a88 | <ide><path>docs/topics/2.2-announcement.md
<ide> Django 1.6's Python 3 support is expected to be officially labeled as 'productio
<ide>
<ide> If you want to start ensuring that your own projects are Python 3 ready, we can highly recommend Django's [Porting to Python 3][porting-python-3] documentation.
<ide>
<add>Django REST framework's Python 2.6 support now requires 2.6.5 or above, in line with [Django 1.5's Python compatibility][python-compat].
<add>
<ide> ## Deprecation policy
<ide>
<ide> We've now introduced an official deprecation policy, which is in line with [Django's deprecation policy][django-deprecation-policy]. This policy will make it easy for you to continue to track the latest, greatest version of REST framework.
<ide> From version 2.2 onwards, serializers with hyperlinked relationships *always* re
<ide> [xordoquy]: https://github.com/xordoquy
<ide> [django-python-3]: https://docs.djangoproject.com/en/dev/faq/install/#can-i-use-django-with-python-3
<ide> [porting-python-3]: https://docs.djangoproject.com/en/dev/topics/python3/
<add>[python-compat]: https://docs.djangoproject.com/en/dev/releases/1.5/#python-compatibility
<ide> [django-deprecation-policy]: https://docs.djangoproject.com/en/dev/internals/release-process/#internal-release-deprecation-policy
<ide> [credits]: http://django-rest-framework.org/topics/credits.html
<ide> [mailing-list]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework | 1 |
Javascript | Javascript | fix typo in a link | 72d63dbcc09ecfcb2e12cc3ecfbcff94648fbbfc | <ide><path>src/ng/rootScope.js
<ide> function $RootScopeProvider(){
<ide> * {@link ng.directive:ngController controllers} or in
<ide> * {@link ng.$compileProvider#directive directives}.
<ide> * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
<del> * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
<add> * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
<ide> *
<ide> * If you want to be notified whenever `$digest()` is called,
<ide> * you can register a `watchExpression` function with | 1 |
Python | Python | remove obsolete comment | 025733bae3dae4200577cb35ef3229cc0f47a5b2 | <ide><path>numpy/distutils/from_template.py
<ide> def namerepl(mobj):
<ide>
<ide> def process_str(allstr):
<ide> newstr = allstr
<del> writestr = '' #_head # using _head will break free-format files
<add> writestr = ''
<ide>
<ide> struct = parse_structure(newstr)
<ide> | 1 |
Javascript | Javascript | fix failing tests for outerhtml fallback | f870e8e98d3c09297388fd7e7e5424456e20cd22 | <ide><path>packages/ember-views/lib/system/render_buffer.js
<ide> Ember._RenderBuffer.prototype =
<ide> string: function() {
<ide> if (this._hasElement && this._element) {
<ide> // Firefox versions < 11 do not have support for element.outerHTML.
<del> return this.element().outerHTML ||
<del> new XMLSerializer().serializeToString(this.element());
<add> var thisElement = this.element(), outerHTML = thisElement.outerHTML;
<add> if (typeof outerHTML === 'undefined'){
<add> return Ember.$('<div/>').append(thisElement).html();
<add> }
<add> return outerHTML;
<ide> } else {
<ide> return this.innerString();
<ide> }
<ide><path>packages/ember-views/tests/system/render_buffer_test.js
<ide> test("handles browsers like Firefox < 11 that don't support outerHTML Issue #195
<ide> // Make sure element.outerHTML is falsy to trigger the fallback.
<ide> var elementStub = '<div></div>';
<ide> buffer.element = function(){ return elementStub; };
<del> equal(new XMLSerializer().serializeToString(elementStub), buffer.string());
<add> equal(elementStub, buffer.string());
<ide> });
<ide>
<ide> module("Ember.RenderBuffer - without tagName"); | 2 |
PHP | PHP | change cache path | b9de404ce384611e477e4fc5d8fca2a24f2ad562 | <ide><path>src/Illuminate/Foundation/Application.php
<ide> public function eventsAreCached()
<ide> */
<ide> public function getCachedEventsPath()
<ide> {
<del> return $_ENV['APP_EVENTS_CACHE'] ?? $this->storagePath().'/framework/cache/events.php';
<add> return $_ENV['APP_EVENTS_CACHE'] ?? $this->bootstrapPath().'/cache/events.php';
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add 2.10.0-beta.3 to changelog.md | 2ca045698802cf1563599561aaaff2105803c66a | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.10.0-beta.3 (November 2, 2016)
<add>
<add>- [#14537](https://github.com/emberjs/ember.js/pull/14537) [BUGFIX] Improve behavior for QPs with undefined values
<add>- [#14545](https://github.com/emberjs/ember.js/pull/14545) [BUGFIX] Refactor loading/error substates. Fixes a number of issues with substate usage with ember-engines.
<add>- [#14571](https://github.com/emberjs/ember.js/pull/14571) [BUGFIX] Prevent errors in watching infrastructure for non-object paths.
<add>- [tildeio/router.js#197](https://github.com/tildeio/router.js/pull/197) [BUGFIX] Fix redirects performed during the routers validation stages. Properly handles `replaceWith` / `transitionTo` for initial and subsequent transitions.
<add>
<ide> ### 2.10.0-beta.2 (October 26, 2016)
<ide>
<ide> - [#14499](https://github.com/emberjs/ember.js/pull/14499) [BUGFIX] Fix "Invalid value used as weak map key" error in old versions of Node.js. | 1 |
Text | Text | fix typo in run command documentation | b3913024e252e9cb1e7cba75e3f95cb23cedaf9b | <ide><path>docs/reference/commandline/run.md
<ide> Options:
<ide> -P, --publish-all Publish all exposed ports to random ports
<ide> --read-only Mount the container's root filesystem as read only
<ide> --restart string Restart policy to apply when a container exits (default "no")
<del> Possible values are : no, on-failuer[:max-retry], always, unless-stopped
<add> Possible values are : no, on-failure[:max-retry], always, unless-stopped
<ide> --rm Automatically remove the container when it exits
<ide> --runtime string Runtime to use for this container
<ide> --security-opt value Security Options (default []) | 1 |
Javascript | Javascript | add support for the "sftp" protocol in links | 5f76bc60976fd2d28f793fa72dd6ce49daf645d6 | <ide><path>src/ng/sanitizeUri.js
<ide> * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
<ide> */
<ide> function $$SanitizeUriProvider() {
<del> var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
<add> var aHrefSanitizationWhitelist = /^\s*(https?|s?ftp|mailto|tel|file):/,
<ide> imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
<ide>
<ide> /**
<ide><path>src/ngSanitize/filter/linky.js
<ide> * @kind function
<ide> *
<ide> * @description
<del> * Finds links in text input and turns them into html links. Supports `http/https/ftp/mailto` and
<add> * Finds links in text input and turns them into html links. Supports `http/https/ftp/sftp/mailto` and
<ide> * plain email address links.
<ide> *
<ide> * Requires the {@link ngSanitize `ngSanitize`} module to be installed.
<ide> */
<ide> angular.module('ngSanitize').filter('linky', ['$sanitize', function($sanitize) {
<ide> var LINKY_URL_REGEXP =
<del> /((ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
<add> /((s?ftp|https?):\/\/|(www\.)|(mailto:)?[A-Za-z0-9._%+-]+@)\S*[^\s.;,(){}<>"\u201d\u2019]/i,
<ide> MAILTO_REGEXP = /^mailto:/i;
<ide>
<ide> var linkyMinErr = angular.$$minErr('linky');
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide>
<ide> it('should allow aHrefSanitizationWhitelist to be configured', function() {
<ide> module(function($compileProvider) {
<del> expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/^\s*(https?|ftp|mailto|tel|file):/); // the default
<add> expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/^\s*(https?|s?ftp|mailto|tel|file):/); // the default
<ide> $compileProvider.aHrefSanitizationWhitelist(/other/);
<ide> expect($compileProvider.aHrefSanitizationWhitelist()).toEqual(/other/);
<ide> });
<ide><path>test/ng/sanitizeUriSpec.js
<ide> describe('sanitizeUri', function() {
<ide> testUrl = 'ftp://foo/bar';
<ide> expect(sanitizeHref(testUrl)).toBe('ftp://foo/bar');
<ide>
<add> testUrl = 'sftp://foo/bar';
<add> expect(sanitizeHref(testUrl)).toBe('sftp://foo/bar');
<add>
<ide> testUrl = 'mailto:[email protected]';
<ide> expect(sanitizeHref(testUrl)).toBe('mailto:[email protected]');
<ide>
<ide><path>test/ngSanitize/filter/linkySpec.js
<ide> describe('linky', function() {
<ide> expect(linky('HTTP://example.com')).toEqual('<a href="HTTP://example.com">HTTP://example.com</a>');
<ide> expect(linky('HTTPS://www.example.com')).toEqual('<a href="HTTPS://www.example.com">HTTPS://www.example.com</a>');
<ide> expect(linky('HTTPS://example.com')).toEqual('<a href="HTTPS://example.com">HTTPS://example.com</a>');
<add> expect(linky('FTP://www.example.com')).toEqual('<a href="FTP://www.example.com">FTP://www.example.com</a>');
<add> expect(linky('FTP://example.com')).toEqual('<a href="FTP://example.com">FTP://example.com</a>');
<add> expect(linky('SFTP://www.example.com')).toEqual('<a href="SFTP://www.example.com">SFTP://www.example.com</a>');
<add> expect(linky('SFTP://example.com')).toEqual('<a href="SFTP://example.com">SFTP://example.com</a>');
<ide> });
<ide>
<ide> it('should handle www.', function() {
<ide><path>test/ngSanitize/sanitizeSpec.js
<ide> describe('HTML', function() {
<ide>
<ide> // See https://github.com/cure53/DOMPurify/blob/a992d3a75031cb8bb032e5ea8399ba972bdf9a65/src/purify.js#L439-L449
<ide> it('should not allow JavaScript execution when creating inert document', inject(function($sanitize) {
<del> var doc = $sanitize('<svg><g onload="window.xxx = 100"></g></svg>');
<add> $sanitize('<svg><g onload="window.xxx = 100"></g></svg>');
<add>
<ide> expect(window.xxx).toBe(undefined);
<ide> delete window.xxx;
<ide> })); | 6 |
PHP | PHP | add helper methods for consoleio | 3b5f42006917b8b7c43aed0b4de88b12ad551bcb | <ide><path>src/Console/ConsoleIo.php
<ide> public function out($message = '', $newlines = 1, $level = ConsoleIo::NORMAL)
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * Convenience method for out() that wraps message between <info /> tag
<add> *
<add> * @param string|array|null $message A string or an array of strings to output
<add> * @param int $newlines Number of newlines to append
<add> * @param int $level The message's output level, see above.
<add> * @return int|bool The number of bytes returned from writing to stdout.
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<add> */
<add> public function info($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> {
<add> $messageType = 'info';
<add> $message = $this->wrapMessageWithType($messageType, $message);
<add>
<add> return $this->out($message, $newlines, $level);
<add> }
<add>
<add> /**
<add> * Convenience method for err() that wraps message between <warning /> tag
<add> *
<add> * @param string|array|null $message A string or an array of strings to output
<add> * @param int $newlines Number of newlines to append
<add> * @return int|bool The number of bytes returned from writing to stderr.
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::err
<add> */
<add> public function warning($message = null, $newlines = 1)
<add> {
<add> $messageType = 'warning';
<add> $message = $this->wrapMessageWithType($messageType, $message);
<add>
<add> return $this->err($message, $newlines);
<add> }
<add>
<add> /**
<add> * Convenience method for err() that wraps message between <error /> tag
<add> *
<add> * @param string|array|null $message A string or an array of strings to output
<add> * @param int $newlines Number of newlines to append
<add> * @return int|bool The number of bytes returned from writing to stderr.
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::err
<add> */
<add> public function error($message = null, $newlines = 1)
<add> {
<add> $messageType = 'error';
<add> $message = $this->wrapMessageWithType($messageType, $message);
<add>
<add> return $this->err($message, $newlines);
<add> }
<add>
<add> /**
<add> * Convenience method for out() that wraps message between <success /> tag
<add> *
<add> * @param string|array|null $message A string or an array of strings to output
<add> * @param int $newlines Number of newlines to append
<add> * @param int $level The message's output level, see above.
<add> * @return int|bool The number of bytes returned from writing to stdout.
<add> * @see https://book.cakephp.org/3.0/en/console-and-shells.html#Shell::out
<add> */
<add> public function success($message = null, $newlines = 1, $level = Shell::NORMAL)
<add> {
<add> $messageType = 'success';
<add> $message = $this->wrapMessageWithType($messageType, $message);
<add>
<add> return $this->out($message, $newlines, $level);
<add> }
<add>
<add> /**
<add> * Wraps a message with a given message type, e.g. <warning>
<add> *
<add> * @param string $messageType The message type, e.g. "warning".
<add> * @param string|array $message The message to wrap.
<add> * @return array|string The message wrapped with the given message type.
<add> */
<add> protected function wrapMessageWithType($messageType, $message)
<add> {
<add> if (is_array($message)) {
<add> foreach ($message as $k => $v) {
<add> $message[$k] = "<{$messageType}>{$v}</{$messageType}>";
<add> }
<add> } else {
<add> $message = "<{$messageType}>{$message}</{$messageType}>";
<add> }
<add>
<add> return $message;
<add> }
<add>
<ide> /**
<ide> * Overwrite some already output text.
<ide> *
<ide><path>tests/TestCase/Console/ConsoleIoTest.php
<ide> public function testHelper()
<ide> $this->assertInstanceOf('Cake\Console\Helper', $helper);
<ide> $helper->output(['well', 'ish']);
<ide> }
<add>
<add> /**
<add> * Provider for output helpers
<add> *
<add> * @return array
<add> */
<add> public function outHelperProvider()
<add> {
<add> return [['info'], ['success']];
<add> }
<add>
<add> /**
<add> * Provider for err helpers
<add> *
<add> * @return array
<add> */
<add> public function errHelperProvider()
<add> {
<add> return [['warning'], ['error']];
<add> }
<add>
<add> /**
<add> * test out helper methods
<add> *
<add> * @dataProvider outHelperProvider
<add> * @return void
<add> */
<add> public function testOutHelpers($method)
<add> {
<add> $this->out->expects($this->at(0))
<add> ->method('write')
<add> ->with("<{$method}>Just a test</{$method}>", 1);
<add>
<add> $this->out->expects($this->at(1))
<add> ->method('write')
<add> ->with(["<{$method}>Just</{$method}>", "<{$method}>a test</{$method}>"], 1);
<add>
<add> $this->io->{$method}('Just a test');
<add> $this->io->{$method}(['Just', 'a test']);
<add> }
<add>
<add> /**
<add> * test err helper methods
<add> *
<add> * @dataProvider errHelperProvider
<add> * @return void
<add> */
<add> public function testErrHelpers($method)
<add> {
<add> $this->err->expects($this->at(0))
<add> ->method('write')
<add> ->with("<{$method}>Just a test</{$method}>", 1);
<add>
<add> $this->err->expects($this->at(1))
<add> ->method('write')
<add> ->with(["<{$method}>Just</{$method}>", "<{$method}>a test</{$method}>"], 1);
<add>
<add> $this->io->{$method}('Just a test');
<add> $this->io->{$method}(['Just', 'a test']);
<add> }
<ide> } | 2 |
Ruby | Ruby | allow overriding macos.version | d94636cde921288aa7a33a0f368a3101fd8f3df3 | <ide><path>Library/Homebrew/cask/lib/hbc/cli.rb
<ide> def self.run_command(command, *rest)
<ide> end
<ide>
<ide> def self.process(arguments)
<add> unless ENV["MACOS_VERSION"].nil?
<add> MacOS.full_version = ENV["MACOS_VERSION"]
<add> end
<add>
<ide> command_string, *rest = *arguments
<ide> rest = process_options(rest)
<ide> command = Hbc.help ? "help" : lookup_command(command_string)
<ide><path>Library/Homebrew/os/mac.rb
<ide> def full_version
<ide> @full_version ||= Version.new((ENV["HOMEBREW_MACOS_VERSION"] || ENV["HOMEBREW_OSX_VERSION"]).chomp)
<ide> end
<ide>
<add> def full_version=(version)
<add> @full_version = Version.new(version.chomp)
<add> @version = nil
<add> end
<add>
<ide> def prerelease?
<ide> # TODO: bump version when new OS is released
<ide> version >= "10.13" | 2 |
Java | Java | avoid npe when setting warnlogcategory | ef72ef54fac1a0cde43e9ca2023f8ea1ea64d769 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> import org.springframework.core.Ordered;
<ide> import org.springframework.lang.Nullable;
<add>import org.springframework.util.StringUtils;
<ide> import org.springframework.web.servlet.HandlerExceptionResolver;
<ide> import org.springframework.web.servlet.ModelAndView;
<ide>
<ide> public void setMappedHandlerClasses(Class<?>... mappedHandlerClasses) {
<ide> /**
<ide> * Set the log category for warn logging. The name will be passed to the underlying logger
<ide> * implementation through Commons Logging, getting interpreted as a log category according
<del> * to the logger's configuration.
<del> * <p>Default is no warn logging. Specify this setting to activate warn logging into a specific
<add> * to the logger's configuration. If {@code null} is passed, warn logging is turned off.
<add> * <p>By default there is no warn logging although sub-classes like
<add> * {@link org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver}
<add> * can change that default. Specify this setting to activate warn logging into a specific
<ide> * category. Alternatively, override the {@link #logException} method for custom logging.
<ide> * @see org.apache.commons.logging.LogFactory#getLog(String)
<ide> * @see java.util.logging.Logger#getLogger(String)
<ide> */
<ide> public void setWarnLogCategory(String loggerName) {
<del> this.warnLogger = LogFactory.getLog(loggerName);
<add> this.warnLogger = !StringUtils.isEmpty(loggerName) ? LogFactory.getLog(loggerName) : null;
<ide> }
<ide>
<ide> /** | 1 |
Mixed | Javascript | remove magic mode | 4893f70d12691208abf8c668d8347240df561f14 | <ide><path>doc/api/deprecations.md
<ide> The `tls.createSecurePair()` API was deprecated in documentation in Node.js
<ide> <a id="DEP0065"></a>
<ide> ### DEP0065: repl.REPL_MODE_MAGIC and NODE_REPL_MODE=magic
<ide>
<del>Type: Documentation-only
<add>Type: End-of-Life
<ide>
<ide> The `repl` module's `REPL_MODE_MAGIC` constant, used for `replMode` option, has
<del>been deprecated. Its behavior has been functionally identical to that of
<add>been removed. Its behavior has been functionally identical to that of
<ide> `REPL_MODE_SLOPPY` since Node.js v6.0.0, when V8 5.0 was imported. Please use
<ide> `REPL_MODE_SLOPPY` instead.
<ide>
<ide> The `NODE_REPL_MODE` environment variable is used to set the underlying
<del>`replMode` of an interactive `node` session. Its default value, `magic`, is
<del>similarly deprecated in favor of `sloppy`.
<add>`replMode` of an interactive `node` session. Its value, `magic`, is also
<add>removed. Please use `sloppy` instead.
<ide>
<ide> <a id="DEP0066"></a>
<ide> ### DEP0066: outgoingMessage.\_headers, outgoingMessage.\_headerNames
<ide><path>doc/api/repl.md
<ide> Returns `true` if `keyword` is a valid keyword, otherwise `false`.
<ide> <!-- YAML
<ide> added: v0.1.91
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/REPLACEME
<add> description: The `REPL_MAGIC_MODE` replMode was removed.
<ide> - version: v5.8.0
<ide> pr-url: https://github.com/nodejs/node/pull/5388
<ide> description: The `options` parameter is optional now.
<ide> changes:
<ide> * `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode.
<ide> * `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is
<ide> equivalent to prefacing every repl statement with `'use strict'`.
<del> * `repl.REPL_MODE_MAGIC` - This value is **deprecated**, since enhanced
<del> spec compliance in V8 has rendered magic mode unnecessary. It is now
<del> equivalent to `repl.REPL_MODE_SLOPPY` (documented above).
<ide> * `breakEvalOnSigint` - Stop evaluating the current piece of code when
<ide> `SIGINT` is received, i.e. `Ctrl+C` is pressed. This cannot be used together
<ide> with a custom `eval` function. Defaults to `false`.
<ide> environment variables:
<ide> REPL history. Whitespace will be trimmed from the value.
<ide> - `NODE_REPL_HISTORY_SIZE` - Defaults to `1000`. Controls how many lines of
<ide> history will be persisted if history is available. Must be a positive number.
<del> - `NODE_REPL_MODE` - May be any of `sloppy`, `strict`, or `magic`. Defaults
<del> to `sloppy`, which will allow non-strict mode code to be run. `magic` is
<del> **deprecated** and treated as an alias of `sloppy`.
<add> - `NODE_REPL_MODE` - May be either `sloppy` or `strict`. Defaults
<add> to `sloppy`, which will allow non-strict mode code to be run.
<ide>
<ide> ### Persistent History
<ide>
<ide><path>lib/repl.js
<ide> exports.REPLServer = REPLServer;
<ide>
<ide> exports.REPL_MODE_SLOPPY = Symbol('repl-sloppy');
<ide> exports.REPL_MODE_STRICT = Symbol('repl-strict');
<del>exports.REPL_MODE_MAGIC = exports.REPL_MODE_SLOPPY;
<ide>
<ide> // prompt is a string to print on each line for the prompt,
<ide> // source is a stream to use for I/O, defaulting to stdin/stdout.
<ide><path>test/parallel/test-repl-options.js
<ide> const r2 = repl.start({
<ide> ignoreUndefined: true,
<ide> eval: evaler,
<ide> writer: writer,
<del> replMode: repl.REPL_MODE_STRICT
<add> replMode: repl.REPL_MODE_STRICT,
<add> historySize: 50
<ide> });
<ide> assert.strictEqual(r2.input, stream);
<ide> assert.strictEqual(r2.output, stream);
<ide> assert.strictEqual(r2.useGlobal, true);
<ide> assert.strictEqual(r2.ignoreUndefined, true);
<ide> assert.strictEqual(r2.writer, writer);
<ide> assert.strictEqual(r2.replMode, repl.REPL_MODE_STRICT);
<add>assert.strictEqual(r2.historySize, 50);
<ide>
<ide> // test r2 for backwards compact
<ide> assert.strictEqual(r2.rli.input, stream);
<ide> assert.strictEqual(r2.rli.input, r2.inputStream);
<ide> assert.strictEqual(r2.rli.output, r2.outputStream);
<ide> assert.strictEqual(r2.rli.terminal, false);
<ide>
<del>// testing out "magic" replMode
<del>const r3 = repl.start({
<del> input: stream,
<del> output: stream,
<del> writer: writer,
<del> replMode: repl.REPL_MODE_MAGIC,
<del> historySize: 50
<del>});
<del>
<del>assert.strictEqual(r3.replMode, repl.REPL_MODE_MAGIC);
<del>assert.strictEqual(r3.historySize, 50);
<del>
<ide> // Verify that defaults are used when no arguments are provided
<ide> const r4 = repl.start();
<ide> | 4 |
Text | Text | update changelog for 15.6 | ac2f14272989b1b4eb3060098a38ebaf5a538dd7 | <ide><path>CHANGELOG.md
<del>## 15.6.0 [Unreleased]
<del><details>
<del> <summary>Changes we plan to include in the 15.6.0 release.</summary>
<add>## 15.6.0 (June 13, 2017)
<ide>
<ide> ### React
<ide>
<ide>
<ide> * Remove PropTypes dependency from ReactLink. ([@gaearon](https://github.com/gaearon) in [#9766](https://github.com/facebook/react/pull/9766))
<ide>
<del></details>
<del>
<ide> ## 15.5.4 (April 11, 2017)
<ide>
<ide> ### React Addons | 1 |
Ruby | Ruby | update error message when inlineadapter is used | a1e925db7096483626263de088a3294ad6259d3f | <ide><path>activejob/lib/active_job/queue_adapters/inline_adapter.rb
<ide> def enqueue(job) #:nodoc:
<ide> end
<ide>
<ide> def enqueue_at(*) #:nodoc:
<del> raise NotImplementedError.new("Use a queueing backend to enqueue jobs in the future. Read more at https://github.com/rails/activejob")
<add> raise NotImplementedError.new("Use a queueing backend to enqueue jobs in the future. Read more at http://guides.rubyonrails.org/active_job_basics.html")
<ide> end
<ide> end
<ide> end | 1 |
Python | Python | add xfailing test for reverse pattern (see ) | 34a3cc26a91e50ee2461df650271fb50c064562b | <ide><path>spacy/tests/regression/test_issue1971.py
<ide> def test_issue1971(en_vocab):
<ide> # the real problem here is that it returns a duplicate match for a match_id
<ide> # that's not actually in the vocab!
<ide> assert all(match_id in en_vocab.strings for match_id, start, end in matcher(doc))
<add>
<add>
<add>@pytest.mark.xfail
<add>def test_issue_1971_2(en_vocab):
<add> matcher = Matcher(en_vocab)
<add> pattern1 = [{"LOWER": {"IN": ["eur"]}}, {"LIKE_NUM": True}]
<add> pattern2 = list(reversed(pattern1))
<add> doc = Doc(en_vocab, words=["EUR", "10", "is", "10", "EUR"])
<add> matcher.add("TEST", None, pattern1, pattern2)
<add> matches = matcher(doc)
<add> assert len(matches) == 2 | 1 |
Python | Python | improve code example | 61ee26a89260611c51a277b69155710316ae54ac | <ide><path>src/transformers/models/glpn/modeling_glpn.py
<ide> def forward(
<ide>
<ide> ```python
<ide> >>> from transformers import GLPNFeatureExtractor, GLPNForDepthEstimation
<add> >>> import torch
<add> >>> import numpy as np
<ide> >>> from PIL import Image
<ide> >>> import requests
<ide>
<del> >>> feature_extractor = GLPNFeatureExtractor.from_pretrained("vinvino02/glpn-kitti")
<del> >>> model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-kitti")
<del>
<ide> >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
<ide> >>> image = Image.open(requests.get(url, stream=True).raw)
<ide>
<add> >>> feature_extractor = GLPNFeatureExtractor.from_pretrained("vinvino02/glpn-kitti")
<add> >>> model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-kitti")
<add>
<add> >>> # prepare image for the model
<ide> >>> inputs = feature_extractor(images=image, return_tensors="pt")
<del> >>> outputs = model(**inputs)
<del> >>> predicted_depth = outputs.predicted_depth # shape (batch_size, height, width)
<add>
<add> >>> with torch.no_grad():
<add> ... outputs = model(**inputs)
<add> ... predicted_depth = outputs.predicted_depth
<add>
<add> >>> # interpolate to original size
<add> >>> prediction = torch.nn.functional.interpolate(
<add> ... predicted_depth.unsqueeze(1),
<add> ... size=image.size[::-1],
<add> ... mode="bicubic",
<add> ... align_corners=False,
<add> ... )
<add>
<add> >>> # visualize the prediction
<add> >>> output = prediction.squeeze().cpu().numpy()
<add> >>> formatted = (output * 255 / np.max(output)).astype("uint8")
<add> >>> depth = Image.fromarray(formatted)
<ide> ```"""
<ide> return_dict = return_dict if return_dict is not None else self.config.use_return_dict
<ide> output_hidden_states = ( | 1 |
PHP | PHP | accept -1 or 1 as # of rows on insert | cc7d7f27f3d0672d4079e8c448ba1dbab74907be | <ide><path>src/ORM/Table.php
<ide> protected function _insert($entity, $data) {
<ide> ->values($data)
<ide> ->execute();
<ide>
<del> if ($statement->rowCount() > 0) {
<add> if ($statement->rowCount() !== 0) {
<ide> $success = $entity;
<ide> $entity->set($filteredKeys, ['guard' => false]);
<ide> foreach ($primary as $key => $v) { | 1 |
Python | Python | fix bug in escape_curly_brackets | 37dcd553705421201f00fb7f6a75a6214afb9d60 | <ide><path>rest_framework/routers.py
<ide> def escape_curly_brackets(url_path):
<ide> """
<ide> Double brackets in regex of url_path for escape string formatting
<ide> """
<del> if ('{' and '}') in url_path:
<del> url_path = url_path.replace('{', '{{').replace('}', '}}')
<del> return url_path
<add> return url_path.replace('{', '{{').replace('}', '}}')
<ide>
<ide>
<ide> def flatten(list_of_lists): | 1 |
Ruby | Ruby | add fortran configuration to env.rb | 8991d9bf15678fd236b2c70b5f7e5a825e122d7e | <ide><path>Library/Homebrew/extend/ENV.rb
<ide> def llvm
<ide> self.O4
<ide> end
<ide>
<add> def fortran
<add> if self['FC']
<add> ohai "Building with an alternative Fortran compiler. This is unsupported."
<add> self['F77'] = self['FC'] unless self['F77']
<add>
<add> if ARGV.include? '--default-fortran-flags'
<add> self['FCFLAGS'] = self['CFLAGS'] unless self['FCFLAGS']
<add> self['FFFLAGS'] = self['CFLAGS'] unless self['FFFLAGS']
<add> elsif not self['FCFLAGS'] or self['FFLAGS']
<add> opoo <<-EOS
<add>No Fortran optimization information was provided. You may want to consider
<add>setting FCFLAGS and FFLAGS or pass the `--default-fortran-flags` option to
<add>`brew install` if your compiler is compatible with GCC.
<add>
<add>If you like the default optimization level of your compiler, ignore this
<add>warning.
<add> EOS
<add> end
<add>
<add> elsif `/usr/bin/which gfortran`.chomp.size > 0
<add> ohai <<-EOS
<add>Using Homebrew-provided fortran compiler.
<add> This may be changed by setting the FC environment variable.
<add> EOS
<add> self['FC'] = `/usr/bin/which gfortran`.chomp
<add> self['F77'] = self['FC']
<add>
<add> self['FCFLAGS'] = self['CFLAGS']
<add> self['FFLAGS'] = self['CFLAGS']
<add>
<add> else
<add> onoe <<-EOS
<add>This formula requires a fortran compiler, but we could not find one by
<add>looking at the FC environment variable or searching your PATH for `gfortran`.
<add>Please take one of the following actions:
<add>
<add> - Decide to use the build of gfortran 4.2.x provided by Homebrew using
<add> `brew install gfortran`
<add>
<add> - Choose another Fortran compiler by setting the FC environment variable:
<add> export FC=/path/to/some/fortran/compiler
<add> Using an alternative compiler may produce more efficient code, but we will
<add> not be able to provide support for build errors.
<add> EOS
<add> exit 1
<add> end
<add> end
<add>
<ide> def osx_10_4
<ide> self['MACOSX_DEPLOYMENT_TARGET']="10.4"
<ide> remove_from_cflags(/ ?-mmacosx-version-min=10\.\d/) | 1 |
PHP | PHP | remove deprecated code in filesystem and error | ee0eff1ca830105927dda2a7331ffdcb3206505f | <ide><path>src/Error/Debugger.php
<ide> public static function setOutputFormat($format)
<ide> $self->_outputFormat = $format;
<ide> }
<ide>
<del> /**
<del> * Get/Set the output format for Debugger error rendering.
<del> *
<del> * @deprecated 3.5.0 Use getOutputFormat()/setOutputFormat() instead.
<del> * @param string|null $format The format you want errors to be output as.
<del> * Leave null to get the current format.
<del> * @return string|null Returns null when setting. Returns the current format when getting.
<del> * @throws \InvalidArgumentException When choosing a format that doesn't exist.
<del> */
<del> public static function outputAs($format = null)
<del> {
<del> deprecationWarning(
<del> 'Debugger::outputAs() is deprecated. Use Debugger::getOutputFormat()/setOutputFormat() instead.'
<del> );
<del> $self = Debugger::getInstance();
<del> if ($format === null) {
<del> return $self->_outputFormat;
<del> }
<del>
<del> if (!isset($self->_templates[$format])) {
<del> throw new InvalidArgumentException('Invalid Debugger output format.');
<del> }
<del> $self->_outputFormat = $format;
<del>
<del> return null;
<del> }
<del>
<ide> /**
<ide> * Add an output format or update a format in Debugger.
<ide> *
<ide><path>src/Filesystem/Folder.php
<ide> public static function addPathElement($path, $element)
<ide> return implode(DIRECTORY_SEPARATOR, $element);
<ide> }
<ide>
<del> /**
<del> * Returns true if the Folder is in the given Cake path.
<del> *
<del> * @param string $path The path to check.
<del> * @return bool
<del> * @deprecated 3.2.12 This method will be removed in 4.0.0. Use inPath() instead.
<del> */
<del> public function inCakePath($path = '')
<del> {
<del> deprecationWarning('Folder::inCakePath() is deprecated. Use Folder::inPath() instead.');
<del> $dir = substr(Folder::slashTerm(ROOT), 0, -1);
<del> $newdir = $dir . $path;
<del>
<del> return $this->inPath($newdir);
<del> }
<del>
<ide> /**
<ide> * Returns true if the Folder is in the given path.
<ide> *
<ide><path>tests/TestCase/Error/DebuggerTest.php
<ide> public function testExcerpt()
<ide> $this->assertCount(3, $result);
<ide> }
<ide>
<del> /**
<del> * Test that outputAs works.
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testOutputAs()
<del> {
<del> $this->deprecated(function () {
<del> Debugger::outputAs('html');
<del> $this->assertEquals('html', Debugger::outputAs());
<del> });
<del> }
<del>
<ide> /**
<ide> * Test that setOutputFormat works.
<ide> *
<ide> public function testSetOutputFormat()
<ide> $this->assertEquals('html', Debugger::getOutputFormat());
<ide> }
<ide>
<del> /**
<del> * Test that choosing a non-existent format causes an exception
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testOutputAsException()
<del> {
<del> $this->expectException(\InvalidArgumentException::class);
<del> $this->deprecated(function () {
<del> Debugger::outputAs('Invalid junk');
<del> });
<del> }
<del>
<ide> /**
<ide> * Test that getOutputFormat/setOutputFormat works.
<ide> *
<ide><path>tests/TestCase/Filesystem/FolderTest.php
<ide> public function testCorrectSlashFor()
<ide> $this->assertEquals('\\', $result);
<ide> }
<ide>
<del> /**
<del> * testInCakePath method
<del> *
<del> * @group deprecated
<del> * @return void
<del> */
<del> public function testInCakePath()
<del> {
<del> $this->deprecated(function () {
<del> $Folder = new Folder();
<del> $Folder->cd(ROOT);
<del> $path = 'C:\\path\\to\\file';
<del> $result = $Folder->inCakePath($path);
<del> $this->assertFalse($result);
<del>
<del> $path = ROOT;
<del> $Folder->cd(ROOT);
<del> $result = $Folder->inCakePath($path);
<del> $this->assertFalse($result);
<del>
<del> $path = DS . 'config';
<del> $Folder->cd(ROOT . DS . 'config');
<del> $result = $Folder->inCakePath($path);
<del> $this->assertTrue($result);
<del> });
<del> }
<del>
<ide> /**
<ide> * testFind method
<ide> * | 4 |
PHP | PHP | add tests modifying the dsn class map | b69cf9c3c5b601019718072ff53315a12dd7e5a5 | <ide><path>src/Core/StaticConfigTrait.php
<ide> public static function parseDsn($dsn) {
<ide> */
<ide> public static function dsnClassMap($map = null) {
<ide> if ($map) {
<del> static::$_dsnClassMap = $map + $_dsnClassMap;
<add> static::$_dsnClassMap = $map + static::$_dsnClassMap;
<ide> }
<ide> return static::$_dsnClassMap;
<ide> }
<ide><path>tests/TestCase/Core/StaticConfigTraitTest.php
<ide> public function testParseDsnPathSetting() {
<ide> $this->assertEquals($expected, TestLogStaticConfig::parseDsn($dsn));
<ide> }
<ide>
<add>/**
<add> * Test that the dsn map can be updated/append to
<add> *
<add> * @return void
<add> */
<add> public function testCanUpdateClassMap() {
<add> $expected = [
<add> 'console' => 'Cake\Log\Engine\ConsoleLog',
<add> 'file' => 'Cake\Log\Engine\FileLog',
<add> 'syslog' => 'Cake\Log\Engine\SyslogLog',
<add> ];
<add> $result = TestLogStaticConfig::dsnClassMap();
<add> $this->assertEquals($expected, $result, "The class map should match the class property");
<add>
<add> $expected = [
<add> 'console' => 'Special\EngineLog',
<add> 'file' => 'Cake\Log\Engine\FileLog',
<add> 'syslog' => 'Cake\Log\Engine\SyslogLog',
<add> ];
<add> $result = TestLogStaticConfig::dsnClassMap(['console' => 'Special\EngineLog']);
<add> $this->assertEquals($expected, $result, "Should be possible to change the map");
<add>
<add> $expected = [
<add> 'console' => 'Special\EngineLog',
<add> 'file' => 'Cake\Log\Engine\FileLog',
<add> 'syslog' => 'Cake\Log\Engine\SyslogLog',
<add> 'my' => 'Special\OtherLog'
<add> ];
<add> $result = TestLogStaticConfig::dsnClassMap(['my' => 'Special\OtherLog']);
<add> $this->assertEquals($expected, $result, "Should be possible to add to the map");
<add> }
<add>
<ide> } | 2 |
PHP | PHP | allow usage of the worker without pcntl | f6715f4f7514c2bba44c9f80dc452fef078f19de | <ide><path>src/Illuminate/Queue/Console/WorkCommand.php
<ide> namespace Illuminate\Queue\Console;
<ide>
<ide> use Carbon\Carbon;
<add>use RuntimeException;
<ide> use Illuminate\Queue\Worker;
<ide> use Illuminate\Console\Command;
<ide> use Illuminate\Queue\WorkerOptions;
<ide> protected function runWorker($connection, $queue)
<ide> */
<ide> protected function gatherWorkerOptions()
<ide> {
<add> $timeout = $this->option('timeout', 60);
<add>
<add> if ($timeout && ! function_exist('pcntl_fork')) {
<add> throw new RuntimeException('Timeouts not supported without the pcntl_fork extension.');
<add> }
<add>
<ide> return new WorkerOptions(
<ide> $this->option('delay'), $this->option('memory'),
<del> $this->option('timeout', 60), $this->option('sleep'),
<add> $timeout, $this->option('sleep'),
<ide> $this->option('tries')
<ide> );
<ide> }
<ide><path>src/Illuminate/Queue/Worker.php
<ide> protected function daemonShouldRun()
<ide> */
<ide> protected function runNextJobForDaemon($connectionName, $queue, WorkerOptions $options)
<ide> {
<del> if ($processId = pcntl_fork()) {
<add> if (! $options->timeout) {
<add> $this->runNextJob($connectionName, $queue, $options);
<add> } elseif ($processId = pcntl_fork()) {
<ide> $this->waitForChildProcess($processId, $options->timeout);
<ide> } else {
<ide> $this->runNextJob($connectionName, $queue, $options); | 2 |
Javascript | Javascript | fix key requirements in asymmetric cipher | 78dbe74520d36de7f7bc17707848ec8ec63e67a5 | <ide><path>lib/internal/crypto/cipher.js
<ide> function rsaFunctionFor(method, defaultPadding, keyType) {
<ide> const publicEncrypt = rsaFunctionFor(_publicEncrypt, RSA_PKCS1_OAEP_PADDING,
<ide> 'public');
<ide> const publicDecrypt = rsaFunctionFor(_publicDecrypt, RSA_PKCS1_PADDING,
<del> 'private');
<add> 'public');
<ide> const privateEncrypt = rsaFunctionFor(_privateEncrypt, RSA_PKCS1_PADDING,
<ide> 'private');
<ide> const privateDecrypt = rsaFunctionFor(_privateDecrypt, RSA_PKCS1_OAEP_PADDING,
<del> 'public');
<add> 'private');
<ide>
<ide> function getDecoder(decoder, encoding) {
<ide> encoding = normalizeEncoding(encoding);
<ide><path>test/parallel/test-crypto-key-objects.js
<ide> const {
<ide> createPrivateKey,
<ide> KeyObject,
<ide> randomBytes,
<add> publicDecrypt,
<ide> publicEncrypt,
<del> privateDecrypt
<add> privateDecrypt,
<add> privateEncrypt
<ide> } = require('crypto');
<ide>
<ide> const fixtures = require('../common/fixtures');
<ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
<ide> assert(Buffer.isBuffer(privateDER));
<ide>
<ide> const plaintext = Buffer.from('Hello world', 'utf8');
<del> const ciphertexts = [
<add> const testDecryption = (fn, ciphertexts, decryptionKeys) => {
<add> for (const ciphertext of ciphertexts) {
<add> for (const key of decryptionKeys) {
<add> const deciphered = fn(key, ciphertext);
<add> assert.deepStrictEqual(deciphered, plaintext);
<add> }
<add> }
<add> };
<add>
<add> testDecryption(privateDecrypt, [
<ide> // Encrypt using the public key.
<ide> publicEncrypt(publicKey, plaintext),
<ide> publicEncrypt({ key: publicKey }, plaintext),
<ide> const privateDsa = fixtures.readKey('dsa_private_encrypted_1025.pem',
<ide> // DER-encoded data only.
<ide> publicEncrypt({ format: 'der', type: 'pkcs1', key: publicDER }, plaintext),
<ide> publicEncrypt({ format: 'der', type: 'pkcs1', key: privateDER }, plaintext)
<del> ];
<del>
<del> const decryptionKeys = [
<add> ], [
<ide> privateKey,
<ide> { format: 'pem', key: privatePem },
<ide> { format: 'der', type: 'pkcs1', key: privateDER }
<del> ];
<add> ]);
<ide>
<del> for (const ciphertext of ciphertexts) {
<del> for (const key of decryptionKeys) {
<del> const deciphered = privateDecrypt(key, ciphertext);
<del> assert(plaintext.equals(deciphered));
<del> }
<del> }
<add> testDecryption(publicDecrypt, [
<add> privateEncrypt(privateKey, plaintext)
<add> ], [
<add> // Decrypt using the public key.
<add> publicKey,
<add> { format: 'pem', key: publicPem },
<add> { format: 'der', type: 'pkcs1', key: publicDER },
<add>
<add> // Decrypt using the private key.
<add> privateKey,
<add> { format: 'pem', key: privatePem },
<add> { format: 'der', type: 'pkcs1', key: privateDER }
<add> ]);
<ide> }
<ide>
<ide> { | 2 |
PHP | PHP | unskip more tests related to secured forms | 85ccc83deea3e6fc4131d1bea677a6d78df51855 | <ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testFormSecurityMultipleInputFields() {
<ide> * @return void
<ide> */
<ide> public function testFormSecurityArrayFields() {
<del> $this->markTestIncomplete('Need to revisit once models work again.');
<del> $key = 'testKey';
<del> $this->Form->request->params['_csrfToken'] = $key;
<add> $this->Form->request->params['_Token'] = 'testKey';
<ide>
<ide> $this->Form->create('Address');
<del> $this->Form->input('Address.primary.1');
<add> $this->Form->text('Address.primary.1');
<ide> $this->assertEquals('Address.primary', $this->Form->fields[0]);
<ide>
<del> $this->Form->input('Address.secondary.1.0');
<add> $this->Form->text('Address.secondary.1.0');
<ide> $this->assertEquals('Address.secondary', $this->Form->fields[1]);
<ide> }
<ide>
<ide> public function testFormSecurityArrayFields() {
<ide> * @return void
<ide> */
<ide> public function testFormSecurityMultipleInputDisabledFields() {
<del> $this->markTestIncomplete('Need to revisit once models work again.');
<del> $key = 'testKey';
<del> $this->Form->request->params['_csrfToken'] = $key;
<ide> $this->Form->request->params['_Token'] = array(
<ide> 'unlockedFields' => array('first_name', 'address')
<ide> );
<ide> $this->Form->create();
<ide>
<ide> $this->Form->hidden('Addresses.0.id', array('value' => '123456'));
<del> $this->Form->input('Addresses.0.title');
<del> $this->Form->input('Addresses.0.first_name');
<del> $this->Form->input('Addresses.0.last_name');
<del> $this->Form->input('Addresses.0.address');
<del> $this->Form->input('Addresses.0.city');
<del> $this->Form->input('Addresses.0.phone');
<add> $this->Form->text('Addresses.0.title');
<add> $this->Form->text('Addresses.0.first_name');
<add> $this->Form->text('Addresses.0.last_name');
<add> $this->Form->text('Addresses.0.address');
<add> $this->Form->text('Addresses.0.city');
<add> $this->Form->text('Addresses.0.phone');
<ide> $this->Form->hidden('Addresses.1.id', array('value' => '654321'));
<del> $this->Form->input('Addresses.1.title');
<del> $this->Form->input('Addresses.1.first_name');
<del> $this->Form->input('Addresses.1.last_name');
<del> $this->Form->input('Addresses.1.address');
<del> $this->Form->input('Addresses.1.city');
<del> $this->Form->input('Addresses.1.phone');
<add> $this->Form->text('Addresses.1.title');
<add> $this->Form->text('Addresses.1.first_name');
<add> $this->Form->text('Addresses.1.last_name');
<add> $this->Form->text('Addresses.1.address');
<add> $this->Form->text('Addresses.1.city');
<add> $this->Form->text('Addresses.1.phone');
<ide>
<ide> $result = $this->Form->secure($this->Form->fields);
<ide> $hash = '629b6536dcece48aa41a117045628ce602ccbbb2%3AAddresses.0.id%7CAddresses.1.id';
<ide>
<ide> $expected = array(
<ide> 'div' => array('style' => 'display:none;'),
<ide> array('input' => array(
<del> 'type' => 'hidden', 'name' => '_Token[fields]',
<add> 'type' => 'hidden',
<add> 'name' => '_Token[fields]',
<ide> 'value' => $hash
<ide> )),
<ide> array('input' => array(
<del> 'type' => 'hidden', 'name' => '_Token[unlocked]',
<del> 'value' => 'address%7Cfirst_name', 'id' => 'preg:/TokenUnlocked\d+/'
<add> 'type' => 'hidden',
<add> 'name' => '_Token[unlocked]',
<add> 'value' => 'address%7Cfirst_name',
<ide> )),
<ide> '/div'
<ide> );
<ide> public function testFormSecurityMultipleInputDisabledFields() {
<ide> * @return void
<ide> */
<ide> public function testFormSecurityInputUnlockedFields() {
<del> $this->markTestIncomplete('Need to revisit once models work again.');
<del> $key = 'testKey';
<del> $this->Form->request->params['_csrfToken'] = $key;
<ide> $this->Form->request['_Token'] = array(
<ide> 'unlockedFields' => array('first_name', 'address')
<ide> );
<ide> $this->Form->create();
<ide> $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField());
<ide>
<ide> $this->Form->hidden('Addresses.id', array('value' => '123456'));
<del> $this->Form->input('Addresses.title');
<del> $this->Form->input('Addresses.first_name');
<del> $this->Form->input('Addresses.last_name');
<del> $this->Form->input('Addresses.address');
<del> $this->Form->input('Addresses.city');
<del> $this->Form->input('Addresses.phone');
<add> $this->Form->text('Addresses.title');
<add> $this->Form->text('Addresses.first_name');
<add> $this->Form->text('Addresses.last_name');
<add> $this->Form->text('Addresses.address');
<add> $this->Form->text('Addresses.city');
<add> $this->Form->text('Addresses.phone');
<ide>
<ide> $result = $this->Form->fields;
<ide> $expected = array(
<ide> public function testFormSecurityInputUnlockedFields() {
<ide> $expected = array(
<ide> 'div' => array('style' => 'display:none;'),
<ide> array('input' => array(
<del> 'type' => 'hidden', 'name' => '_Token[fields]',
<add> 'type' => 'hidden',
<add> 'name' => '_Token[fields]',
<ide> 'value' => $hash
<ide> )),
<ide> array('input' => array(
<del> 'type' => 'hidden', 'name' => '_Token[unlocked]',
<del> 'value' => 'address%7Cfirst_name', 'id' => 'preg:/TokenUnlocked\d+/'
<add> 'type' => 'hidden',
<add> 'name' => '_Token[unlocked]',
<add> 'value' => 'address%7Cfirst_name',
<ide> )),
<ide> '/div'
<ide> );
<ide> public function testFormSecuredInput() {
<ide> * @return void
<ide> */
<ide> public function testSecuredInputCustomName() {
<del> $this->markTestIncomplete('Need to revisit once models work again.');
<del> $this->Form->request->params['_csrfToken'] = 'testKey';
<add> $this->Form->request->params['_Token'] = 'testKey';
<ide> $this->assertEquals(array(), $this->Form->fields);
<ide>
<del> $this->Form->input('text_input', array(
<del> 'name' => 'data[Option][General.default_role]',
<add> $this->Form->text('text_input', array(
<add> 'name' => 'Option[General.default_role]',
<ide> ));
<ide> $expected = array('Option.General.default_role');
<ide> $this->assertEquals($expected, $this->Form->fields);
<ide>
<del> $this->Form->input('select_box', array(
<del> 'name' => 'data[Option][General.select_role]',
<del> 'type' => 'select',
<del> 'options' => array(1, 2),
<del> ));
<del> $expected = array('Option.General.default_role', 'Option.General.select_role');
<add> $this->Form->select('select_box', [1, 2], [
<add> 'name' => 'Option[General.select_role]',
<add> ]);
<add> $expected = ['Option.General.default_role', 'Option.General.select_role'];
<ide> $this->assertEquals($expected, $this->Form->fields);
<ide> }
<ide>
<ide> public function testFormSecuredAndDisabled() {
<ide> * @return void
<ide> */
<ide> public function testDisableSecurityUsingForm() {
<del> $this->markTestIncomplete('Need to revisit once models work again.');
<del> $this->Form->request->params['_csrfToken'] = 'testKey';
<del> $this->Form->request['_Token'] = array(
<del> 'disabledFields' => array()
<del> );
<add> $this->Form->request['_Token'] = [
<add> 'disabledFields' => []
<add> ];
<ide> $this->Form->create();
<ide>
<del> $this->Form->hidden('Addresses.id', array('value' => '123456'));
<del> $this->Form->input('Addresses.title');
<del> $this->Form->input('Addresses.first_name', array('secure' => false));
<del> $this->Form->input('Addresses.city', array('type' => 'textarea', 'secure' => false));
<del> $this->Form->input('Addresses.zip', array(
<del> 'type' => 'select', 'options' => array(1, 2), 'secure' => false
<del> ));
<add> $this->Form->hidden('Addresses.id', ['value' => '123456']);
<add> $this->Form->text('Addresses.title');
<add> $this->Form->text('Addresses.first_name', ['secure' => false]);
<add> $this->Form->textarea('Addresses.city', ['secure' => false]);
<add> $this->Form->select('Addresses.zip', [1, 2], ['secure' => false]);
<ide>
<ide> $result = $this->Form->fields;
<del> $expected = array(
<add> $expected = [
<ide> 'Addresses.id' => '123456', 'Addresses.title',
<del> );
<add> ];
<ide> $this->assertEquals($expected, $result);
<ide> }
<ide> | 1 |
Python | Python | fix malformed docstrings in ma. | 02d66ecd80a1851c3b206f4d778687b38c9d2c36 | <ide><path>numpy/ma/extras.py
<ide> def getdoc(self):
<ide> the new masked array version of the function. A note on application
<ide> of the function to the mask is appended.
<ide>
<del> .. warning::
<del> If the function docstring already contained a Notes section, the
<del> new docstring will have two Notes sections instead of appending a note
<del> to the existing section.
<del>
<ide> Parameters
<ide> ----------
<ide> None
<ide> def getdoc(self):
<ide> doc = getattr(npfunc, '__doc__', None)
<ide> if doc:
<ide> sig = self.__name__ + ma.get_object_signature(npfunc)
<del> locdoc = "Notes\n-----\nThe function is applied to both the _data"\
<del> " and the _mask, if any."
<del> return '\n'.join((sig, doc, locdoc))
<add> doc = ma.doc_note(doc, "The function is applied to both the _data "
<add> "and the _mask, if any.")
<add> return '\n\n'.join((sig, doc))
<ide> return
<ide>
<ide> def __call__(self, *args, **params): | 1 |
PHP | PHP | fix strict typing error | f9a541f361d70a697803d3a0f83634999dcfd217 | <ide><path>tests/test_app/TestApp/Controller/TestsAppsController.php
<ide> public function index()
<ide>
<ide> public function some_method()
<ide> {
<del> return $this->response->withStringBody(5);
<add> return $this->response->withStringBody('5');
<ide> }
<ide>
<ide> public function set_action() | 1 |
Javascript | Javascript | add test double http benchmarker | a3e71a8901bc326bcc701820d10e10d9de4d338a | <ide><path>benchmark/_http-benchmarkers.js
<ide> 'use strict';
<ide>
<ide> const child_process = require('child_process');
<add>const path = require('path');
<add>const fs = require('fs');
<ide>
<ide> // The port used by servers and wrk
<ide> exports.PORT = process.env.PORT || 12346;
<ide>
<del>function AutocannonBenchmarker() {
<del> this.name = 'autocannon';
<del> this.autocannon_exe = process.platform === 'win32' ?
<del> 'autocannon.cmd' :
<del> 'autocannon';
<del> const result = child_process.spawnSync(this.autocannon_exe, ['-h']);
<del> this.present = !(result.error && result.error.code === 'ENOENT');
<del>}
<add>class AutocannonBenchmarker {
<add> constructor() {
<add> this.name = 'autocannon';
<add> this.executable = process.platform === 'win32' ?
<add> 'autocannon.cmd' :
<add> 'autocannon';
<add> const result = child_process.spawnSync(this.executable, ['-h']);
<add> this.present = !(result.error && result.error.code === 'ENOENT');
<add> }
<ide>
<del>AutocannonBenchmarker.prototype.create = function(options) {
<del> const args = [
<del> '-d', options.duration,
<del> '-c', options.connections,
<del> '-j',
<del> '-n',
<del> `http://127.0.0.1:${options.port}${options.path}`
<del> ];
<del> const child = child_process.spawn(this.autocannon_exe, args);
<del> return child;
<del>};
<add> create(options) {
<add> const args = [
<add> '-d', options.duration,
<add> '-c', options.connections,
<add> '-j',
<add> '-n',
<add> `http://127.0.0.1:${options.port}${options.path}`
<add> ];
<add> const child = child_process.spawn(this.executable, args);
<add> return child;
<add> }
<ide>
<del>AutocannonBenchmarker.prototype.processResults = function(output) {
<del> let result;
<del> try {
<del> result = JSON.parse(output);
<del> } catch (err) {
<del> // Do nothing, let next line handle this
<add> processResults(output) {
<add> let result;
<add> try {
<add> result = JSON.parse(output);
<add> } catch (err) {
<add> return undefined;
<add> }
<add> if (!result || !result.requests || !result.requests.average) {
<add> return undefined;
<add> } else {
<add> return result.requests.average;
<add> }
<ide> }
<del> if (!result || !result.requests || !result.requests.average) {
<del> return undefined;
<del> } else {
<del> return result.requests.average;
<add>}
<add>
<add>class WrkBenchmarker {
<add> constructor() {
<add> this.name = 'wrk';
<add> this.executable = 'wrk';
<add> const result = child_process.spawnSync(this.executable, ['-h']);
<add> this.present = !(result.error && result.error.code === 'ENOENT');
<add> }
<add>
<add> create(options) {
<add> const args = [
<add> '-d', options.duration,
<add> '-c', options.connections,
<add> '-t', 8,
<add> `http://127.0.0.1:${options.port}${options.path}`
<add> ];
<add> const child = child_process.spawn(this.executable, args);
<add> return child;
<ide> }
<del>};
<ide>
<del>function WrkBenchmarker() {
<del> this.name = 'wrk';
<del> this.regexp = /Requests\/sec:[ \t]+([0-9.]+)/;
<del> const result = child_process.spawnSync('wrk', ['-h']);
<del> this.present = !(result.error && result.error.code === 'ENOENT');
<add> processResults(output) {
<add> const throughputRe = /Requests\/sec:[ \t]+([0-9.]+)/;
<add> const match = output.match(throughputRe);
<add> const throughput = match && +match[1];
<add> if (!isFinite(throughput)) {
<add> return undefined;
<add> } else {
<add> return throughput;
<add> }
<add> }
<ide> }
<ide>
<del>WrkBenchmarker.prototype.create = function(options) {
<del> const args = [
<del> '-d', options.duration,
<del> '-c', options.connections,
<del> '-t', 8,
<del> `http://127.0.0.1:${options.port}${options.path}`
<del> ];
<del> const child = child_process.spawn('wrk', args);
<del> return child;
<del>};
<add>/**
<add> * Simple, single-threaded benchmarker for testing if the benchmark
<add> * works
<add> */
<add>class TestDoubleBenchmarker {
<add> constructor() {
<add> this.name = 'test-double';
<add> this.executable = path.resolve(__dirname, '_test-double-benchmarker.js');
<add> this.present = fs.existsSync(this.executable);
<add> }
<add>
<add> create(options) {
<add> const child = child_process.fork(this.executable, {
<add> silent: true,
<add> env: {
<add> duration: options.duration,
<add> connections: options.connections,
<add> path: `http://127.0.0.1:${options.port}${options.path}`
<add> }
<add> });
<add> return child;
<add> }
<ide>
<del>WrkBenchmarker.prototype.processResults = function(output) {
<del> const match = output.match(this.regexp);
<del> const result = match && +match[1];
<del> if (!isFinite(result)) {
<del> return undefined;
<del> } else {
<del> return result;
<add> processResults(output) {
<add> let result;
<add> try {
<add> result = JSON.parse(output);
<add> } catch (err) {
<add> return undefined;
<add> }
<add> return result.throughput;
<ide> }
<del>};
<add>}
<ide>
<del>const http_benchmarkers = [new WrkBenchmarker(), new AutocannonBenchmarker()];
<add>const http_benchmarkers = [
<add> new WrkBenchmarker(),
<add> new AutocannonBenchmarker(),
<add> new TestDoubleBenchmarker()
<add>];
<ide>
<ide> const benchmarkers = {};
<ide>
<ide><path>benchmark/_test-double-benchmarker.js
<add>'use strict';
<add>
<add>const http = require('http');
<add>
<add>http.get(process.env.path, function() {
<add> console.log(JSON.stringify({throughput: 1}));
<add>}); | 2 |
Python | Python | change version to 2.2 | f5747a5b00d308d5af10cb60d92c63a4868bef60 | <ide><path>glances/__init__.py
<ide> """Init the Glances software."""
<ide>
<ide> __appname__ = 'glances'
<del>__version__ = '2.2_BETA'
<add>__version__ = '2.2'
<ide> __author__ = 'Nicolas Hennion <[email protected]>'
<ide> __license__ = 'LGPL'
<ide> | 1 |
Python | Python | create a pluggable dataseteventmanager | 28165eef2ac26c66525849e7bebb55553ea5a451 | <ide><path>airflow/datasets/manager.py
<add>#
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>from sqlalchemy.orm.session import Session
<add>
<add>from airflow.datasets import Dataset
<add>from airflow.models.dataset import DatasetDagRunQueue, DatasetEvent, DatasetModel
<add>from airflow.models.taskinstance import TaskInstance
<add>from airflow.utils.log.logging_mixin import LoggingMixin
<add>
<add>
<add>class DatasetEventManager(LoggingMixin):
<add> """
<add> A pluggable class that manages operations for dataset events.
<add>
<add> The intent is to have one place to handle all DatasetEvent-related operations, so different
<add> Airflow deployments can use plugins that broadcast dataset events to each other.
<add> """
<add>
<add> def register_dataset_change(
<add> self, *, task_instance: TaskInstance, dataset: Dataset, extra=None, session: Session, **kwargs
<add> ) -> None:
<add> """
<add> For local datasets, look them up, record the dataset event, queue dagruns, and broadcast
<add> the dataset event
<add> """
<add> dataset_model = session.query(DatasetModel).filter(DatasetModel.uri == dataset.uri).one_or_none()
<add> if not dataset_model:
<add> self.log.warning("DatasetModel %s not found", dataset_model)
<add> return
<add> session.add(
<add> DatasetEvent(
<add> dataset_id=dataset_model.id,
<add> source_task_id=task_instance.task_id,
<add> source_dag_id=task_instance.dag_id,
<add> source_run_id=task_instance.run_id,
<add> source_map_index=task_instance.map_index,
<add> extra=extra,
<add> )
<add> )
<add> self._queue_dagruns(dataset_model, session)
<add>
<add> def _queue_dagruns(self, dataset: DatasetModel, session: Session) -> None:
<add> consuming_dag_ids = [x.dag_id for x in dataset.consuming_dags]
<add> self.log.debug("consuming dag ids %s", consuming_dag_ids)
<add> for dag_id in consuming_dag_ids:
<add> session.merge(DatasetDagRunQueue(dataset_id=dataset.id, target_dag_id=dag_id))
<ide><path>airflow/models/taskinstance.py
<ide> from airflow import settings
<ide> from airflow.compat.functools import cache
<ide> from airflow.configuration import conf
<add>from airflow.datasets import Dataset
<ide> from airflow.exceptions import (
<ide> AirflowException,
<ide> AirflowFailException,
<ide> XComForMappingNotPushed,
<ide> )
<ide> from airflow.models.base import Base, StringID
<del>from airflow.models.dataset import DatasetDagRunQueue, DatasetEvent
<ide> from airflow.models.log import Log
<ide> from airflow.models.param import ParamsDict
<ide> from airflow.models.taskfail import TaskFail
<ide> def __init__(
<ide> # can be changed when calling 'run'
<ide> self.test_mode = False
<ide>
<add> self.dataset_event_manager = conf.getimport(
<add> 'core', 'dataset_event_manager_class', fallback='airflow.datasets.manager.DatasetEventManager'
<add> )()
<add>
<ide> @staticmethod
<ide> def insert_mapping(run_id: str, task: "Operator", map_index: int) -> dict:
<ide> """:meta private:"""
<ide> def _run_raw_task(
<ide> session.add(Log(self.state, self))
<ide> session.merge(self)
<ide> if self.state == TaskInstanceState.SUCCESS:
<del> self._create_dataset_dag_run_queue_records(session=session)
<add> self._register_dataset_changes(session=session)
<ide> session.commit()
<ide>
<del> def _create_dataset_dag_run_queue_records(self, *, session: Session) -> None:
<del> from airflow.datasets import Dataset
<del> from airflow.models.dataset import DatasetModel
<del>
<add> def _register_dataset_changes(self, *, session: Session) -> None:
<ide> for obj in self.task.outlets or []:
<ide> self.log.debug("outlet obj %s", obj)
<add> # Lineage can have other types of objects besides datasets
<ide> if isinstance(obj, Dataset):
<del> dataset = session.query(DatasetModel).filter(DatasetModel.uri == obj.uri).one_or_none()
<del> if not dataset:
<del> self.log.warning("Dataset %s not found", obj)
<del> continue
<del> consuming_dag_ids = [x.dag_id for x in dataset.consuming_dags]
<del> self.log.debug("consuming dag ids %s", consuming_dag_ids)
<del> session.add(
<del> DatasetEvent(
<del> dataset_id=dataset.id,
<del> source_task_id=self.task_id,
<del> source_dag_id=self.dag_id,
<del> source_run_id=self.run_id,
<del> source_map_index=self.map_index,
<del> )
<add> self.dataset_event_manager.register_dataset_change(
<add> task_instance=self,
<add> dataset=obj,
<add> session=session,
<ide> )
<del> for dag_id in consuming_dag_ids:
<del> session.merge(DatasetDagRunQueue(dataset_id=dataset.id, target_dag_id=dag_id))
<ide>
<ide> def _execute_task_with_callbacks(self, context, test_mode=False):
<ide> """Prepare Task for Execution"""
<ide><path>tests/datasets/__init__.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<ide><path>tests/datasets/test_manager.py
<add>#
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>from unittest import mock
<add>
<add>import pytest
<add>
<add>from airflow.datasets import Dataset
<add>from airflow.datasets.manager import DatasetEventManager
<add>from airflow.models.dataset import DatasetModel
<add>
<add>
<add>@pytest.fixture()
<add>def mock_task_instance():
<add> mock_ti = mock.Mock()
<add> mock_ti.task_id = "5"
<add> mock_ti.dag_id = "7"
<add> mock_ti.run_id = "11"
<add> mock_ti.map_index = "13"
<add> return mock_ti
<add>
<add>
<add>def create_mock_dag():
<add> n = 1
<add> while True:
<add> mock_dag = mock.Mock()
<add> mock_dag.dag_id = n
<add> n += 1
<add> yield mock_dag
<add>
<add>
<add>class TestDatasetEventManager:
<add> def test_register_dataset_change_dataset_doesnt_exist(self, mock_task_instance):
<add> dsem = DatasetEventManager()
<add>
<add> dataset = Dataset(uri="dataset_doesnt_exist")
<add>
<add> mock_session = mock.Mock()
<add> # Gotta mock up the query results
<add> mock_session.query.return_value.filter.return_value.one_or_none.return_value = None
<add>
<add> dsem.register_dataset_change(task_instance=mock_task_instance, dataset=dataset, session=mock_session)
<add>
<add> # Ensure that we have ignored the dataset and _not_ created a DatasetEvent or
<add> # DatasetDagRunQueue rows
<add> mock_session.add.assert_not_called()
<add> mock_session.merge.assert_not_called()
<add>
<add> def test_register_dataset_change(self, mock_task_instance):
<add> dsem = DatasetEventManager()
<add>
<add> mock_dag_1 = mock.MagicMock()
<add> mock_dag_1.dag_id = 1
<add> mock_dag_2 = mock.MagicMock()
<add> mock_dag_2.dag_id = 2
<add>
<add> ds = Dataset(uri="test_dataset_uri")
<add>
<add> dsm = DatasetModel(uri="test_dataset_uri")
<add> dsm.consuming_dags = [mock_dag_1, mock_dag_2]
<add>
<add> mock_session = mock.Mock()
<add> # Gotta mock up the query results
<add> mock_session.query.return_value.filter.return_value.one_or_none.return_value = dsm
<add>
<add> dsem.register_dataset_change(task_instance=mock_task_instance, dataset=ds, session=mock_session)
<add>
<add> # Ensure we've created a dataset
<add> mock_session.add.assert_called_once()
<add> # Ensure that we've created DatasetDagRunQueue rows
<add> assert mock_session.merge.call_count == 2 | 4 |
Javascript | Javascript | fix arrow styling | 28045696dd3ea7207b1162c2343ba142e1f75e5d | <ide><path>airflow/www/static/js/dag_dependencies.js
<ide> const renderGraph = () => {
<ide>
<ide> // Set edges
<ide> edges.forEach((edge) => {
<del> g.setEdge(edge.u, edge.v);
<add> g.setEdge(edge.u, edge.v, {
<add> curve: d3.curveBasis,
<add> arrowheadClass: 'arrowhead',
<add> });
<ide> });
<ide>
<ide> innerSvg.call(render, g); | 1 |
Java | Java | normalize indentation of apache license url | 9f5fd3afcf7196dcae1ba5813f78561f9ee0f0a1 | <ide><path>org.springframework.aop/src/test/java/org/springframework/aop/interceptor/DebugInterceptorTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.aop/src/test/java/org/springframework/aop/interceptor/SimpleTraceInterceptorTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.aop/src/test/java/org/springframework/aop/support/DelegatingIntroductionInterceptorTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.context/src/test/java/org/springframework/aop/config/AopNamespaceHandlerProxyTargetClassTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/aop/framework/adapter/AdvisorAdapterRegistrationTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/CustomEditorConfigurerTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/DateRange.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/ExceptionOnInitBean.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/PropertyPlaceholderConfigurerTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/annotation/AnnotationMetadataAssemblerTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/AbstractAutodetectTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/AbstractJmxAssemblerTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/AbstractMetadataAssemblerAutodetectTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/ICustomBase.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/ICustomJmxBean.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerMappedTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/MethodNameBasedMBeanInfoAssemblerTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/assembler/ReflectiveAssemblerTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/naming/AbstractNamingStrategyTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/naming/KeyNamingStrategyTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/naming/PropertiesFileNamingStrategyTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/org/springframework/jmx/export/naming/PropertiesNamingStrategyTests.java
<ide> * use this file except in compliance with the License. You may obtain a copy of
<ide> * the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
<ide><path>org.springframework.context/src/test/java/test/beans/CustomScope.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.core/src/main/java/org/springframework/core/env/AbstractEnvironment.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.core/src/test/java/org/springframework/core/env/DefaultEnvironmentTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.expression/src/main/java/org/springframework/expression/common/TemplateAwareExpressionParser.java
<del>/*
<ide> * Copyright 2002-2009 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> * You may obtain a copy of the License at
<ide> *
<ide> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<ide>package org.springframework.expression.common;
<ide>import java.util.LinkedList;
<ide>import java.util.List;
<ide>import java.util.Stack;
<ide>import org.springframework.expression.Expression;
<ide>import org.springframework.expression.ExpressionParser;
<ide>import org.springframework.expression.ParseException;
<ide>import org.springframework.expression.ParserContext;
<ide>/**
<ide> * An expression parser that understands templates. It can be subclassed
<ide> * by expression parsers that do not offer first class support for templating.
<ide> *
<ide> * @author Keith Donald
<ide> * @author Juergen Hoeller
<ide> * @author Andy Clement
<ide> * @since 3.0
<ide> */
<ide>public abstract class TemplateAwareExpressionParser implements ExpressionParser {
<ide> /**
<ide> * Default ParserContext instance for non-template expressions.
<ide> */
<ide> private static final ParserContext NON_TEMPLATE_PARSER_CONTEXT = new ParserContext() {
<ide> public String getExpressionPrefix() {
<ide> return null;
<ide> }
<ide> public String getExpressionSuffix() {
<ide> return null;
<ide> }
<ide> public boolean isTemplate() {
<ide> return false;
<ide> }
<ide> };
<ide> public Expression parseExpression(String expressionString) throws ParseException {
<ide> return parseExpression(expressionString, NON_TEMPLATE_PARSER_CONTEXT);
<ide> }
<ide> public Expression parseExpression(String expressionString, ParserContext context) throws ParseException {
<ide> if (context == null) {
<ide> context = NON_TEMPLATE_PARSER_CONTEXT;
<ide> }
<ide> if (context.isTemplate()) {
<ide> return parseTemplate(expressionString, context);
<ide> } else {
<ide> return doParseExpression(expressionString, context);
<ide> }
<ide> }
<ide> private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
<ide> if (expressionString.length() == 0) {
<ide> return new LiteralExpression("");
<ide> }
<ide> Expression[] expressions = parseExpressions(expressionString, context);
<ide> if (expressions.length == 1) {
<ide> return expressions[0];
<ide> } else {
<ide> return new CompositeStringExpression(expressionString, expressions);
<ide> }
<ide> }
<ide> /**
<ide> * Helper that parses given expression string using the configured parser. The expression string can contain any
<ide> * number of expressions all contained in "${...}" markers. For instance: "foo${expr0}bar${expr1}". The static
<ide> * pieces of text will also be returned as Expressions that just return that static piece of text. As a result,
<ide> * evaluating all returned expressions and concatenating the results produces the complete evaluated string.
<ide> * Unwrapping is only done of the outermost delimiters found, so the string 'hello ${foo${abc}}' would break into
<ide> * the pieces 'hello ' and 'foo${abc}'. This means that expression languages that used ${..} as part of their
<ide> * functionality are supported without any problem.
<ide> * The parsing is aware of the structure of an embedded expression. It assumes that parentheses '(',
<ide> * square brackets '[' and curly brackets '}' must be in pairs within the expression unless they are within a
<ide> * string literal and a string literal starts and terminates with a single quote '.
<ide> *
<ide> * @param expressionString the expression string
<ide> * @return the parsed expressions
<ide> * @throws ParseException when the expressions cannot be parsed
<ide> */
<ide> private Expression[] parseExpressions(String expressionString, ParserContext context) throws ParseException {
<ide> List<Expression> expressions = new LinkedList<Expression>();
<ide> String prefix = context.getExpressionPrefix();
<ide> String suffix = context.getExpressionSuffix();
<ide> int startIdx = 0;
<ide> while (startIdx < expressionString.length()) {
<ide> int prefixIndex = expressionString.indexOf(prefix,startIdx);
<ide> if (prefixIndex >= startIdx) {
<ide> // an inner expression was found - this is a composite
<ide> if (prefixIndex > startIdx) {
<ide> expressions.add(createLiteralExpression(context,expressionString.substring(startIdx, prefixIndex)));
<ide> }
<ide> int afterPrefixIndex = prefixIndex + prefix.length();
<ide> int suffixIndex = skipToCorrectEndSuffix(prefix,suffix,expressionString,afterPrefixIndex);
<ide> if (suffixIndex == -1) {
<ide> throw new ParseException(expressionString, prefixIndex, "No ending suffix '" + suffix +
<ide> "' for expression starting at character " + prefixIndex + ": " +
<ide> expressionString.substring(prefixIndex));
<ide> }
<ide> if (suffixIndex == afterPrefixIndex) {
<ide> throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" +
<ide> prefix + suffix + "' at character " + prefixIndex);
<ide> } else {
<ide> String expr = expressionString.substring(prefixIndex + prefix.length(), suffixIndex);
<ide> expr = expr.trim();
<ide> if (expr.length()==0) {
<ide> throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" +
<ide> prefix + suffix + "' at character " + prefixIndex);
<ide> }
<ide> expressions.add(doParseExpression(expr, context));
<ide> startIdx = suffixIndex + suffix.length();
<ide> }
<ide> } else {
<ide> // no more ${expressions} found in string, add rest as static text
<ide> expressions.add(createLiteralExpression(context,expressionString.substring(startIdx)));
<ide> startIdx = expressionString.length();
<ide> }
<ide> }
<ide> return expressions.toArray(new Expression[expressions.size()]);
<ide> }
<ide>
<ide> private Expression createLiteralExpression(ParserContext context, String text) {
<ide> return new LiteralExpression(text);
<ide> }
<ide>
<ide> /**
<ide> * Return true if the specified suffix can be found at the supplied position in the supplied expression string.
<ide> * @param expressionString the expression string which may contain the suffix
<ide> * @param pos the start position at which to check for the suffix
<ide> * @param suffix the suffix string
<ide> * @return
<ide> */
<ide> private boolean isSuffixHere(String expressionString,int pos,String suffix) {
<ide> int suffixPosition = 0;
<ide> for (int i=0;i<suffix.length() && pos<expressionString.length();i++) {
<ide> if (expressionString.charAt(pos++)!=suffix.charAt(suffixPosition++)) {
<ide> return false;
<ide> }
<ide> }
<ide> if (suffixPosition!=suffix.length()) {
<ide> // the expressionString ran out before the suffix could entirely be found
<ide> return false;
<ide> }
<ide> return true;
<ide> }
<ide>
<ide> /**
<ide> * Copes with nesting, for example '${...${...}}' where the correct end for the first ${ is the final }.
<ide> *
<ide> * @param prefix the prefix
<ide> * @param suffix the suffix
<ide> * @param expressionString the expression string
<ide> * @param afterPrefixIndex the most recently found prefix location for which the matching end suffix is being sought
<ide> * @return the position of the correct matching nextSuffix or -1 if none can be found
<ide> */
<ide> private int skipToCorrectEndSuffix(String prefix, String suffix, String expressionString, int afterPrefixIndex) throws ParseException {
<ide> // Chew on the expression text - relying on the rules:
<ide> // brackets must be in pairs: () [] {}
<ide> // string literals are "..." or '...' and these may contain unmatched brackets
<ide> int pos = afterPrefixIndex;
<ide> int maxlen = expressionString.length();
<ide> int nextSuffix = expressionString.indexOf(suffix,afterPrefixIndex);
<ide> if (nextSuffix ==-1 ) {
<ide> return -1; // the suffix is missing
<ide> }
<ide> Stack<Bracket> stack = new Stack<Bracket>();
<ide> while (pos<maxlen) {
<ide> if (isSuffixHere(expressionString,pos,suffix) && stack.isEmpty()) {
<ide> break;
<ide> }
<ide> char ch = expressionString.charAt(pos);
<ide> switch (ch) {
<ide> case '{': case '[': case '(':
<ide> stack.push(new Bracket(ch,pos));
<ide> break;
<ide> case '}':case ']':case ')':
<ide> if (stack.isEmpty()) {
<ide> throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" without an opening '"+Bracket.theOpenBracketFor(ch)+"'");
<ide> }
<ide> Bracket p = stack.pop();
<ide> if (!p.compatibleWithCloseBracket(ch)) {
<ide> throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" but most recent opening is '"+p.bracket+"' at position "+p.pos);
<ide> }
<ide> break;
<ide> case '\'':
<ide> case '"':
<ide> // jump to the end of the literal
<ide> int endLiteral = expressionString.indexOf(ch,pos+1);
<ide> if (endLiteral==-1) {
<ide> throw new ParseException(expressionString, pos, "Found non terminating string literal starting at position "+pos);
<ide> }
<ide> pos=endLiteral;
<ide> break;
<ide> }
<ide> pos++;
<ide> }
<ide> if (!stack.isEmpty()) {
<ide> Bracket p = stack.pop();
<ide> throw new ParseException(expressionString, p.pos, "Missing closing '"+Bracket.theCloseBracketFor(p.bracket)+"' for '"+p.bracket+"' at position "+p.pos);
<ide> }
<ide> if (!isSuffixHere(expressionString, pos, suffix)) {
<ide> return -1;
<ide> }
<ide> return pos;
<ide> }
<ide> /**
<ide> * This captures a type of bracket and the position in which it occurs in the expression. The positional
<ide> * information is used if an error has to be reported because the related end bracket cannot be found.
<ide> * Bracket is used to describe: square brackets [] round brackets () and curly brackets {}
<ide> */
<ide> private static class Bracket {
<ide>
<ide> char bracket;
<ide> int pos;
<ide>
<ide> Bracket(char bracket,int pos) {
<ide> this.bracket = bracket;
<ide> this.pos = pos;
<ide> }
<ide> boolean compatibleWithCloseBracket(char closeBracket) {
<ide> if (bracket=='{') {
<ide> return closeBracket=='}';
<ide> } else if (bracket=='[') {
<ide> return closeBracket==']';
<ide> }
<ide> return closeBracket==')';
<ide> }
<ide>
<ide> static char theOpenBracketFor(char closeBracket) {
<ide> if (closeBracket=='}') {
<ide> return '{';
<ide> } else if (closeBracket==']') {
<ide> return '[';
<ide> }
<ide> return '(';
<ide> }
<ide> static char theCloseBracketFor(char openBracket) {
<ide> if (openBracket=='{') {
<ide> return '}';
<ide> } else if (openBracket=='[') {
<ide> return ']';
<ide> }
<ide> return ')';
<ide> }
<ide> }
<ide> /**
<ide> * Actually parse the expression string and return an Expression object.
<ide> * @param expressionString the raw expression string to parse
<ide> * @param context a context for influencing this expression parsing routine (optional)
<ide> * @return an evaluator for the parsed expression
<ide> * @throws ParseException an exception occurred during parsing
<ide> */
<ide> protected abstract Expression doParseExpression(String expressionString, ParserContext context)
<ide> throws ParseException;
<ide>}
<ide>\ No newline at end of file
<add>/* http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<ide> * See the License for the specific language governing permissions and
<ide> * limitations under the License.
<ide> */
<ide>package org.springframework.expression.common;
<ide>import java.util.LinkedList;
<ide>import java.util.List;
<ide>import java.util.Stack;
<ide>import org.springframework.expression.Expression;
<ide>import org.springframework.expression.ExpressionParser;
<ide>import org.springframework.expression.ParseException;
<ide>import org.springframework.expression.ParserContext;
<ide>/**
<ide> * An expression parser that understands templates. It can be subclassed
<ide> * by expression parsers that do not offer first class support for templating.
<ide> *
<ide> * @author Keith Donald
<ide> * @author Juergen Hoeller
<ide> * @author Andy Clement
<ide> * @since 3.0
<ide> */
<ide>public abstract class TemplateAwareExpressionParser implements ExpressionParser {
<ide> /**
<ide> * Default ParserContext instance for non-template expressions.
<ide> */
<ide> private static final ParserContext NON_TEMPLATE_PARSER_CONTEXT = new ParserContext() {
<ide> public String getExpressionPrefix() {
<ide> return null;
<ide> }
<ide> public String getExpressionSuffix() {
<ide> return null;
<ide> }
<ide> public boolean isTemplate() {
<ide> return false;
<ide> }
<ide> };
<ide> public Expression parseExpression(String expressionString) throws ParseException {
<ide> return parseExpression(expressionString, NON_TEMPLATE_PARSER_CONTEXT);
<ide> }
<ide> public Expression parseExpression(String expressionString, ParserContext context) throws ParseException {
<ide> if (context == null) {
<ide> context = NON_TEMPLATE_PARSER_CONTEXT;
<ide> }
<ide> if (context.isTemplate()) {
<ide> return parseTemplate(expressionString, context);
<ide> } else {
<ide> return doParseExpression(expressionString, context);
<ide> }
<ide> }
<ide> private Expression parseTemplate(String expressionString, ParserContext context) throws ParseException {
<ide> if (expressionString.length() == 0) {
<ide> return new LiteralExpression("");
<ide> }
<ide> Expression[] expressions = parseExpressions(expressionString, context);
<ide> if (expressions.length == 1) {
<ide> return expressions[0];
<ide> } else {
<ide> return new CompositeStringExpression(expressionString, expressions);
<ide> }
<ide> }
<ide> /**
<ide> * Helper that parses given expression string using the configured parser. The expression string can contain any
<ide> * number of expressions all contained in "${...}" markers. For instance: "foo${expr0}bar${expr1}". The static
<ide> * pieces of text will also be returned as Expressions that just return that static piece of text. As a result,
<ide> * evaluating all returned expressions and concatenating the results produces the complete evaluated string.
<ide> * Unwrapping is only done of the outermost delimiters found, so the string 'hello ${foo${abc}}' would break into
<ide> * the pieces 'hello ' and 'foo${abc}'. This means that expression languages that used ${..} as part of their
<ide> * functionality are supported without any problem.
<ide> * The parsing is aware of the structure of an embedded expression. It assumes that parentheses '(',
<ide> * square brackets '[' and curly brackets '}' must be in pairs within the expression unless they are within a
<ide> * string literal and a string literal starts and terminates with a single quote '.
<ide> *
<ide> * @param expressionString the expression string
<ide> * @return the parsed expressions
<ide> * @throws ParseException when the expressions cannot be parsed
<ide> */
<ide> private Expression[] parseExpressions(String expressionString, ParserContext context) throws ParseException {
<ide> List<Expression> expressions = new LinkedList<Expression>();
<ide> String prefix = context.getExpressionPrefix();
<ide> String suffix = context.getExpressionSuffix();
<ide> int startIdx = 0;
<ide> while (startIdx < expressionString.length()) {
<ide> int prefixIndex = expressionString.indexOf(prefix,startIdx);
<ide> if (prefixIndex >= startIdx) {
<ide> // an inner expression was found - this is a composite
<ide> if (prefixIndex > startIdx) {
<ide> expressions.add(createLiteralExpression(context,expressionString.substring(startIdx, prefixIndex)));
<ide> }
<ide> int afterPrefixIndex = prefixIndex + prefix.length();
<ide> int suffixIndex = skipToCorrectEndSuffix(prefix,suffix,expressionString,afterPrefixIndex);
<ide> if (suffixIndex == -1) {
<ide> throw new ParseException(expressionString, prefixIndex, "No ending suffix '" + suffix +
<ide> "' for expression starting at character " + prefixIndex + ": " +
<ide> expressionString.substring(prefixIndex));
<ide> }
<ide> if (suffixIndex == afterPrefixIndex) {
<ide> throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" +
<ide> prefix + suffix + "' at character " + prefixIndex);
<ide> } else {
<ide> String expr = expressionString.substring(prefixIndex + prefix.length(), suffixIndex);
<ide> expr = expr.trim();
<ide> if (expr.length()==0) {
<ide> throw new ParseException(expressionString, prefixIndex, "No expression defined within delimiter '" +
<ide> prefix + suffix + "' at character " + prefixIndex);
<ide> }
<ide> expressions.add(doParseExpression(expr, context));
<ide> startIdx = suffixIndex + suffix.length();
<ide> }
<ide> } else {
<ide> // no more ${expressions} found in string, add rest as static text
<ide> expressions.add(createLiteralExpression(context,expressionString.substring(startIdx)));
<ide> startIdx = expressionString.length();
<ide> }
<ide> }
<ide> return expressions.toArray(new Expression[expressions.size()]);
<ide> }
<ide>
<ide> private Expression createLiteralExpression(ParserContext context, String text) {
<ide> return new LiteralExpression(text);
<ide> }
<ide>
<ide> /**
<ide> * Return true if the specified suffix can be found at the supplied position in the supplied expression string.
<ide> * @param expressionString the expression string which may contain the suffix
<ide> * @param pos the start position at which to check for the suffix
<ide> * @param suffix the suffix string
<ide> * @return
<ide> */
<ide> private boolean isSuffixHere(String expressionString,int pos,String suffix) {
<ide> int suffixPosition = 0;
<ide> for (int i=0;i<suffix.length() && pos<expressionString.length();i++) {
<ide> if (expressionString.charAt(pos++)!=suffix.charAt(suffixPosition++)) {
<ide> return false;
<ide> }
<ide> }
<ide> if (suffixPosition!=suffix.length()) {
<ide> // the expressionString ran out before the suffix could entirely be found
<ide> return false;
<ide> }
<ide> return true;
<ide> }
<ide>
<ide> /**
<ide> * Copes with nesting, for example '${...${...}}' where the correct end for the first ${ is the final }.
<ide> *
<ide> * @param prefix the prefix
<ide> * @param suffix the suffix
<ide> * @param expressionString the expression string
<ide> * @param afterPrefixIndex the most recently found prefix location for which the matching end suffix is being sought
<ide> * @return the position of the correct matching nextSuffix or -1 if none can be found
<ide> */
<ide> private int skipToCorrectEndSuffix(String prefix, String suffix, String expressionString, int afterPrefixIndex) throws ParseException {
<ide> // Chew on the expression text - relying on the rules:
<ide> // brackets must be in pairs: () [] {}
<ide> // string literals are "..." or '...' and these may contain unmatched brackets
<ide> int pos = afterPrefixIndex;
<ide> int maxlen = expressionString.length();
<ide> int nextSuffix = expressionString.indexOf(suffix,afterPrefixIndex);
<ide> if (nextSuffix ==-1 ) {
<ide> return -1; // the suffix is missing
<ide> }
<ide> Stack<Bracket> stack = new Stack<Bracket>();
<ide> while (pos<maxlen) {
<ide> if (isSuffixHere(expressionString,pos,suffix) && stack.isEmpty()) {
<ide> break;
<ide> }
<ide> char ch = expressionString.charAt(pos);
<ide> switch (ch) {
<ide> case '{': case '[': case '(':
<ide> stack.push(new Bracket(ch,pos));
<ide> break;
<ide> case '}':case ']':case ')':
<ide> if (stack.isEmpty()) {
<ide> throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" without an opening '"+Bracket.theOpenBracketFor(ch)+"'");
<ide> }
<ide> Bracket p = stack.pop();
<ide> if (!p.compatibleWithCloseBracket(ch)) {
<ide> throw new ParseException(expressionString, pos, "Found closing '"+ch+"' at position "+pos+" but most recent opening is '"+p.bracket+"' at position "+p.pos);
<ide> }
<ide> break;
<ide> case '\'':
<ide> case '"':
<ide> // jump to the end of the literal
<ide> int endLiteral = expressionString.indexOf(ch,pos+1);
<ide> if (endLiteral==-1) {
<ide> throw new ParseException(expressionString, pos, "Found non terminating string literal starting at position "+pos);
<ide> }
<ide> pos=endLiteral;
<ide> break;
<ide> }
<ide> pos++;
<ide> }
<ide> if (!stack.isEmpty()) {
<ide> Bracket p = stack.pop();
<ide> throw new ParseException(expressionString, p.pos, "Missing closing '"+Bracket.theCloseBracketFor(p.bracket)+"' for '"+p.bracket+"' at position "+p.pos);
<ide> }
<ide> if (!isSuffixHere(expressionString, pos, suffix)) {
<ide> return -1;
<ide> }
<ide> return pos;
<ide> }
<ide> /**
<ide> * This captures a type of bracket and the position in which it occurs in the expression. The positional
<ide> * information is used if an error has to be reported because the related end bracket cannot be found.
<ide> * Bracket is used to describe: square brackets [] round brackets () and curly brackets {}
<ide> */
<ide> private static class Bracket {
<ide>
<ide> char bracket;
<ide> int pos;
<ide>
<ide> Bracket(char bracket,int pos) {
<ide> this.bracket = bracket;
<ide> this.pos = pos;
<ide> }
<ide> boolean compatibleWithCloseBracket(char closeBracket) {
<ide> if (bracket=='{') {
<ide> return closeBracket=='}';
<ide> } else if (bracket=='[') {
<ide> return closeBracket==']';
<ide> }
<ide> return closeBracket==')';
<ide> }
<ide>
<ide> static char theOpenBracketFor(char closeBracket) {
<ide> if (closeBracket=='}') {
<ide> return '{';
<ide> } else if (closeBracket==']') {
<ide> return '[';
<ide> }
<ide> return '(';
<ide> }
<ide> static char theCloseBracketFor(char openBracket) {
<ide> if (openBracket=='{') {
<ide> return '}';
<ide> } else if (openBracket=='[') {
<ide> return ']';
<ide> }
<ide> return ')';
<ide> }
<ide> }
<ide> /**
<ide> * Actually parse the expression string and return an Expression object.
<ide> * @param expressionString the raw expression string to parse
<ide> * @param context a context for influencing this expression parsing routine (optional)
<ide> * @return an evaluator for the parsed expression
<ide> * @throws ParseException an exception occurred during parsing
<ide> */
<ide> protected abstract Expression doParseExpression(String expressionString, ParserContext context)
<ide> throws ParseException;
<ide>}
<ide>\ No newline at end of file
<ide><path>org.springframework.web.servlet/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/main/java/org/springframework/http/converter/FormHttpMessageConverter.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/main/java/org/springframework/web/context/support/AbstractRefreshableWebApplicationContext.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/main/java/org/springframework/web/context/support/GenericWebApplicationContext.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/main/java/org/springframework/web/context/support/StaticWebApplicationContext.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/main/java/org/springframework/web/filter/ShallowEtagHeaderFilter.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS,
<ide><path>org.springframework.web/src/test/java/org/springframework/web/filter/ShallowEtagHeaderFilterTests.java
<ide> * you may not use this file except in compliance with the License.
<ide> * You may obtain a copy of the License at
<ide> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<add> * http://www.apache.org/licenses/LICENSE-2.0
<ide> *
<ide> * Unless required by applicable law or agreed to in writing, software
<ide> * distributed under the License is distributed on an "AS IS" BASIS, | 34 |
Go | Go | publish empty stats on error | 0a30ef4c593607aebf2f3fd948665f2be0f74261 | <ide><path>daemon/stats/collector.go
<ide> func (s *Collector) Run() {
<ide>
<ide> default:
<ide> logrus.Errorf("collecting stats for %s: %v", pair.container.ID, err)
<add> pair.publisher.Publish(types.StatsJSON{
<add> Name: pair.container.Name,
<add> ID: pair.container.ID,
<add> })
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | reduce some constant duplication | b4658f2daa4990ef8057335cd7202b479bd8d41a | <ide><path>packages/react-dom/src/events/DOMEventProperties.js
<ide> export const topLevelEventsToReactNames: Map<
<ide> string | null,
<ide> > = new Map();
<ide>
<add>// NOTE: Capitalization is important in this list!
<add>//
<add>// E.g. it needs "pointerDown", not "pointerdown".
<add>// This is because we derive both React name ("onPointerDown")
<add>// and DOM name ("pointerdown") from the same list.
<add>//
<add>// Exceptions that don't match this convention are listed separately.
<add>//
<ide> // prettier-ignore
<del>const simpleEventPluginNames = [
<del> ('cancel': DOMEventName), 'cancel',
<del> ('click': DOMEventName), 'click',
<del> ('close': DOMEventName), 'close',
<del> ('contextmenu': DOMEventName), 'contextMenu',
<del> ('copy': DOMEventName), 'copy',
<del> ('cut': DOMEventName), 'cut',
<del> ('auxclick': DOMEventName), 'auxClick',
<del> ('dblclick': DOMEventName), 'doubleClick', // Careful!
<del> ('dragend': DOMEventName), 'dragEnd',
<del> ('dragstart': DOMEventName), 'dragStart',
<del> ('drop': DOMEventName), 'drop',
<del> ('focusin': DOMEventName), 'focus', // Careful!
<del> ('focusout': DOMEventName), 'blur', // Careful!
<del> ('input': DOMEventName), 'input',
<del> ('invalid': DOMEventName), 'invalid',
<del> ('keydown': DOMEventName), 'keyDown',
<del> ('keypress': DOMEventName), 'keyPress',
<del> ('keyup': DOMEventName), 'keyUp',
<del> ('mousedown': DOMEventName), 'mouseDown',
<del> ('mouseup': DOMEventName), 'mouseUp',
<del> ('paste': DOMEventName), 'paste',
<del> ('pause': DOMEventName), 'pause',
<del> ('play': DOMEventName), 'play',
<del> ('pointercancel': DOMEventName), 'pointerCancel',
<del> ('pointerdown': DOMEventName), 'pointerDown',
<del> ('pointerup': DOMEventName), 'pointerUp',
<del> ('ratechange': DOMEventName), 'rateChange',
<del> ('reset': DOMEventName), 'reset',
<del> ('seeked': DOMEventName), 'seeked',
<del> ('submit': DOMEventName), 'submit',
<del> ('touchcancel': DOMEventName), 'touchCancel',
<del> ('touchend': DOMEventName), 'touchEnd',
<del> ('touchstart': DOMEventName), 'touchStart',
<del> ('volumechange': DOMEventName), 'volumeChange',
<del>
<del> ('drag': DOMEventName), 'drag',
<del> ('dragenter': DOMEventName), 'dragEnter',
<del> ('dragexit': DOMEventName), 'dragExit',
<del> ('dragleave': DOMEventName), 'dragLeave',
<del> ('dragover': DOMEventName), 'dragOver',
<del> ('mousemove': DOMEventName), 'mouseMove',
<del> ('mouseout': DOMEventName), 'mouseOut',
<del> ('mouseover': DOMEventName), 'mouseOver',
<del> ('pointermove': DOMEventName), 'pointerMove',
<del> ('pointerout': DOMEventName), 'pointerOut',
<del> ('pointerover': DOMEventName), 'pointerOver',
<del> ('scroll': DOMEventName), 'scroll',
<del> ('toggle': DOMEventName), 'toggle',
<del> ('touchmove': DOMEventName), 'touchMove',
<del> ('wheel': DOMEventName), 'wheel',
<del>
<del> ('abort': DOMEventName), 'abort',
<del> (ANIMATION_END: DOMEventName), 'animationEnd',
<del> (ANIMATION_ITERATION: DOMEventName), 'animationIteration',
<del> (ANIMATION_START: DOMEventName), 'animationStart',
<del> ('canplay': DOMEventName), 'canPlay',
<del> ('canplaythrough': DOMEventName), 'canPlayThrough',
<del> ('durationchange': DOMEventName), 'durationChange',
<del> ('emptied': DOMEventName), 'emptied',
<del> ('encrypted': DOMEventName), 'encrypted',
<del> ('ended': DOMEventName), 'ended',
<del> ('error': DOMEventName), 'error',
<del> ('gotpointercapture': DOMEventName), 'gotPointerCapture',
<del> ('load': DOMEventName), 'load',
<del> ('loadeddata': DOMEventName), 'loadedData',
<del> ('loadedmetadata': DOMEventName), 'loadedMetadata',
<del> ('loadstart': DOMEventName), 'loadStart',
<del> ('lostpointercapture': DOMEventName), 'lostPointerCapture',
<del> ('playing': DOMEventName), 'playing',
<del> ('progress': DOMEventName), 'progress',
<del> ('seeking': DOMEventName), 'seeking',
<del> ('stalled': DOMEventName), 'stalled',
<del> ('suspend': DOMEventName), 'suspend',
<del> ('timeupdate': DOMEventName), 'timeUpdate',
<del> (TRANSITION_END: DOMEventName), 'transitionEnd',
<del> ('waiting': DOMEventName), 'waiting',
<add>const simpleEventPluginEvents = [
<add> 'abort',
<add> 'auxClick',
<add> 'cancel',
<add> 'canPlay',
<add> 'canPlayThrough',
<add> 'click',
<add> 'close',
<add> 'contextMenu',
<add> 'copy',
<add> 'cut',
<add> 'drag',
<add> 'dragEnd',
<add> 'dragEnter',
<add> 'dragExit',
<add> 'dragLeave',
<add> 'dragOver',
<add> 'dragStart',
<add> 'drop',
<add> 'durationChange',
<add> 'emptied',
<add> 'encrypted',
<add> 'ended',
<add> 'error',
<add> 'gotPointerCapture',
<add> 'input',
<add> 'invalid',
<add> 'keyDown',
<add> 'keyPress',
<add> 'keyUp',
<add> 'load',
<add> 'loadedData',
<add> 'loadedMetadata',
<add> 'loadStart',
<add> 'lostPointerCapture',
<add> 'mouseDown',
<add> 'mouseMove',
<add> 'mouseOut',
<add> 'mouseOver',
<add> 'mouseUp',
<add> 'paste',
<add> 'pause',
<add> 'play',
<add> 'playing',
<add> 'pointerCancel',
<add> 'pointerDown',
<add> 'pointerMove',
<add> 'pointerOut',
<add> 'pointerOver',
<add> 'pointerUp',
<add> 'progress',
<add> 'rateChange',
<add> 'reset',
<add> 'seeked',
<add> 'seeking',
<add> 'stalled',
<add> 'submit',
<add> 'suspend',
<add> 'timeUpdate',
<add> 'touchCancel',
<add> 'touchEnd',
<add> 'touchStart',
<add> 'volumeChange',
<add> 'scroll',
<add> 'toggle',
<add> 'touchMove',
<add> 'waiting',
<add> 'wheel',
<ide> ];
<ide>
<ide> if (enableCreateEventHandleAPI) {
<ide> if (enableCreateEventHandleAPI) {
<ide> topLevelEventsToReactNames.set('afterblur', null);
<ide> }
<ide>
<del>/**
<del> * Turns
<del> * ['abort', ...]
<del> *
<del> * into
<del> *
<del> * topLevelEventsToReactNames = new Map([
<del> * ['abort', 'onAbort'],
<del> * ]);
<del> *
<del> * and registers them.
<del> */
<add>function registerSimpleEvent(domEventName, reactName) {
<add> topLevelEventsToReactNames.set(domEventName, reactName);
<add> registerTwoPhaseEvent(reactName, [domEventName]);
<add>}
<add>
<ide> export function registerSimpleEvents() {
<del> // As the event types are in pairs of two, we need to iterate
<del> // through in twos. The events are in pairs of two to save code
<del> // and improve init perf of processing this array, as it will
<del> // result in far fewer object allocations and property accesses
<del> // if we only use three arrays to process all the categories of
<del> // instead of tuples.
<del> for (let i = 0; i < simpleEventPluginNames.length; i += 2) {
<del> const topEvent = ((simpleEventPluginNames[i]: any): DOMEventName);
<del> const event = ((simpleEventPluginNames[i + 1]: any): string);
<del> const capitalizedEvent = event[0].toUpperCase() + event.slice(1);
<del> const reactName = 'on' + capitalizedEvent;
<del> topLevelEventsToReactNames.set(topEvent, reactName);
<del> registerTwoPhaseEvent(reactName, [topEvent]);
<add> for (let i = 0; i < simpleEventPluginEvents.length; i++) {
<add> const eventName = ((simpleEventPluginEvents[i]: any): string);
<add> const domEventName = ((eventName.toLowerCase(): any): DOMEventName);
<add> const capitalizedEvent = eventName[0].toUpperCase() + eventName.slice(1);
<add> registerSimpleEvent(domEventName, 'on' + capitalizedEvent);
<ide> }
<add> // Special cases where event names don't match.
<add> registerSimpleEvent(ANIMATION_END, 'onAnimationEnd');
<add> registerSimpleEvent(ANIMATION_ITERATION, 'onAnimationIteration');
<add> registerSimpleEvent(ANIMATION_START, 'onAnimationStart');
<add> registerSimpleEvent('dblclick', 'onDoubleClick');
<add> registerSimpleEvent('focusin', 'onFocus');
<add> registerSimpleEvent('focusout', 'onBlur');
<add> registerSimpleEvent(TRANSITION_END, 'onTransitionEnd');
<ide> } | 1 |
Go | Go | fix restart monitor stopping on manual restart | 20390f65c487cfbe18e1f21650086a00e41eadff | <ide><path>container/container.go
<ide> func (container *Container) FullHostname() string {
<ide> func (container *Container) RestartManager(reset bool) restartmanager.RestartManager {
<ide> if reset {
<ide> container.RestartCount = 0
<add> container.restartManager = nil
<ide> }
<ide> if container.restartManager == nil {
<ide> container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy)
<ide><path>integration-cli/docker_cli_restart_test.go
<ide> func (s *DockerSuite) TestRestartWithPolicyUserDefinedNetwork(c *check.C) {
<ide> _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo")
<ide> c.Assert(err, check.IsNil)
<ide> }
<add>
<add>func (s *DockerSuite) TestRestartPolicyAfterRestart(c *check.C) {
<add> testRequires(c, SameHostDaemon)
<add>
<add> out, _ := runSleepingContainer(c, "-d", "--restart=always")
<add> id := strings.TrimSpace(out)
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> dockerCmd(c, "restart", id)
<add>
<add> c.Assert(waitRun(id), check.IsNil)
<add>
<add> pidStr := inspectField(c, id, "State.Pid")
<add>
<add> pid, err := strconv.Atoi(pidStr)
<add> c.Assert(err, check.IsNil)
<add>
<add> p, err := os.FindProcess(pid)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(p, check.NotNil)
<add>
<add> err = p.Kill()
<add> c.Assert(err, check.IsNil)
<add>
<add> err = waitInspect(id, "{{.RestartCount}}", "1", 30*time.Second)
<add> c.Assert(err, check.IsNil)
<add>
<add> err = waitInspect(id, "{{.State.Status}}", "running", 30*time.Second)
<add> c.Assert(err, check.IsNil)
<add>} | 2 |
Text | Text | fix a typo | f8527ea270e00031665e9581583f5ed3aaddd6f4 | <ide><path>guide/russian/xml/index.md
<ide> localeTitle: Расширяемый язык разметки (XML)
<ide> XML - расширяемый язык разметки. Предназначен для описания произвольных документов. Он расширяемый, поскольку не использует предопределенный набор элементов (тэгов) для описания структуры документа. Вместо этого он обеспечивает механизм для определения таких элементов. В настоящий момент одно из основных применений XML - это обмен данными. Если сравнить XML и HTML, то в отличие от HTML у XML нет предопределенного набора тегов, и теги определяют прежде всего значение, а не представление.
<ide>
<ide> ## Синтаксис XML
<add>
<ide> Синтаксис XML - это правила, определяющие способ описания документов XML. Документы XML должны содержать один корневой элемент, который является родительским для всех других элементов:
<ide> ```
<ide> <root>
<ide> XML - расширяемый язык разметки. Предназначен
<ide>
<ide> И главным достижением стало то, что он стал Рекомендацией W3C уже в феврале 1998 года.
<ide>
<add>#### Отображение XML
<add>
<add>Один из способов стилизовать вывод XML - это указать CSS, используя `xml-stylesheet` инструкцию обработки.
<add>
<add>`<?xml-stylesheet type="text/css" href="stylesheet.css"?>`
<add>
<add>Более мощным способом отображения XML является Extensible Stylesheet Language Transformations (XSLT), с помощью которого можно преобразовать XML в другие языки разметки.
<add>
<add>`<?xml-stylesheet type="text/xsl" href="transform.xsl"?>`
<add>
<ide> ### Больше информации
<ide>
<ide> * [Страница в Википедии](https://ru.wikipedia.org/wiki/XML) | 1 |
PHP | PHP | fix cs error | 7ab8924ed24ce5772992ba952082ddd9e4d9d6a0 | <ide><path>src/Console/Command/Task/FixtureTask.php
<ide> */
<ide> namespace Cake\Console\Command\Task;
<ide>
<del>use Cake\Console\ConsoleOutput;
<ide> use Cake\Console\ConsoleInput;
<add>use Cake\Console\ConsoleOutput;
<ide> use Cake\Console\Shell;
<ide> use Cake\Core\Configure;
<ide> use Cake\Database\Schema\Table; | 1 |
Javascript | Javascript | fix failing tests | 975aef2ad2fcb6e276244822b11ddaf39b13857c | <ide><path>docs/spec/ngdocSpec.js
<ide> describe('ngdoc', function(){
<ide> expect(doc.requires).toEqual([
<ide> {name:'$service', text:'<p>for \n<code>A</code></p>'},
<ide> {name:'$another', text:'<p>for <code>B</code></p>'}]);
<del> expect(doc.html()).toContain('<a href="#!angular.service.$service">$service</a>');
<del> expect(doc.html()).toContain('<a href="#!angular.service.$another">$another</a>');
<add> expect(doc.html()).toContain('<a href="#!/api/angular.service.$service">$service</a>');
<add> expect(doc.html()).toContain('<a href="#!/api/angular.service.$another">$another</a>');
<ide> expect(doc.html()).toContain('<p>for \n<code>A</code></p>');
<ide> expect(doc.html()).toContain('<p>for <code>B</code></p>');
<ide> });
<ide><path>docs/spec/sitemapSpec.js
<ide> describe('sitemap', function(){
<ide> });
<ide>
<ide> it('should render ngdoc url', function(){
<del> var map = new SiteMap([new Doc({section: 'foo', name: 'a.b.c<>\'"&'})]);
<add> var map = new SiteMap([new Doc({section: 'foo', id: 'a.b.c<>\'"&'})]);
<ide> expect(map.render()).toContain([
<ide> ' <url>',
<ide> '<loc>http://docs.angularjs.org/#!/foo/a.b.c<>'"&</loc>', | 2 |
Ruby | Ruby | skip empty files | 7501d33159aadaabe2435373ceca2bb371aa8ef8 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def write_jar_script(target_jar, script_name, java_opts = "", java_version: nil)
<ide> def install_metafiles(from = Pathname.pwd)
<ide> Pathname(from).children.each do |p|
<ide> next if p.directory?
<add> next if File.zero?(p)
<ide> next unless Metafiles.copy?(p.basename.to_s)
<ide>
<ide> # Some software symlinks these files (see help2man.rb)
<ide><path>Library/Homebrew/test/formula_installer_spec.rb
<ide> def temporary_install(formula, **options)
<ide> specify "basic installation" do
<ide> temporary_install(Testball.new) do |f|
<ide> # Test that things made it into the Keg
<del> expect(f.prefix/"readme").to exist
<add> # "readme" is empty, so it should not be installed
<add> expect(f.prefix/"readme").not_to exist
<ide>
<ide> expect(f.bin).to be_a_directory
<ide> expect(f.bin.children.count).to eq(3) | 2 |
Ruby | Ruby | add support for xz-compressed tarballs | ffd5b7d7ab9b616408d00b895f4ec0b2d38f6dd4 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def stage
<ide> # Use more than 4 characters to not clash with magicbytes
<ide> magic_bytes = "____pkg"
<ide> else
<del> # get the first four bytes
<del> File.open(@tarball_path) { |f| magic_bytes = f.read(4) }
<add> # get the first six bytes
<add> File.open(@tarball_path) { |f| magic_bytes = f.read(6) }
<ide> end
<ide>
<ide> # magic numbers stolen from /usr/share/file/magic/
<ide> def stage
<ide> # TODO check if it's really a tar archive
<ide> safe_system '/usr/bin/tar', 'xf', @tarball_path
<ide> chdir
<add> when /^\xFD7zXZ\x00/ # xz compressed
<add> raise "You must install XZutils: brew install xz" unless system "/usr/bin/which -s xz"
<add> safe_system "xz -dc #{@tarball_path} | /usr/bin/tar xf -"
<add> chdir
<ide> when '____pkg'
<ide> safe_system '/usr/sbin/pkgutil', '--expand', @tarball_path, File.basename(@url)
<ide> chdir
<ide><path>Library/Homebrew/extend/pathname.rb
<ide> def cp dst
<ide> return dst
<ide> end
<ide>
<del> # extended to support the double extensions .tar.gz and .tar.bz2
<add> # extended to support the double extensions .tar.gz, .tar.bz2, and .tar.xz
<ide> def extname
<del> /(\.tar\.(gz|bz2))$/.match to_s
<add> /(\.tar\.(gz|bz2|xz))$/.match to_s
<ide> return $1 if $1
<ide> return File.extname(to_s)
<ide> end
<ide><path>Library/Homebrew/test/test_bucket.rb
<ide> def test_supported_compressed_types
<ide> assert_nothing_raised do
<ide> MockFormula.new 'test-0.1.tar.gz'
<ide> MockFormula.new 'test-0.1.tar.bz2'
<add> MockFormula.new 'test-0.1.tar.xz'
<ide> MockFormula.new 'test-0.1.tgz'
<ide> MockFormula.new 'test-0.1.bgz'
<add> MockFormula.new 'test-0.1.txz'
<ide> MockFormula.new 'test-0.1.zip'
<ide> end
<ide> end | 3 |
Python | Python | fix tf savedmodel in roberta | 3a134f7c67c0eb4ac6887050964c9b6285651df8 | <ide><path>src/transformers/modeling_tf_longformer.py
<ide> class TFLongformerEmbeddings(tf.keras.layers.Layer):
<ide> """
<ide>
<ide> def __init__(self, config, **kwargs):
<del> super().__init__(config, **kwargs)
<add> super().__init__(**kwargs)
<ide>
<ide> self.padding_idx = 1
<ide> self.vocab_size = config.vocab_size
<ide><path>src/transformers/modeling_tf_roberta.py
<ide> class TFRobertaEmbeddings(tf.keras.layers.Layer):
<ide> """
<ide>
<ide> def __init__(self, config, **kwargs):
<del> super().__init__(config, **kwargs)
<add> super().__init__(**kwargs)
<ide>
<ide> self.padding_idx = 1
<ide> self.vocab_size = config.vocab_size | 2 |
Javascript | Javascript | fix default port | 72ad2c94df3f67674076b9d81b4e30f0cf448266 | <ide><path>lib/_http_client.js
<ide> function ClientRequest(options, cb) {
<ide> var self = this;
<ide> OutgoingMessage.call(self);
<ide>
<add> options = util._extend({}, options);
<add>
<ide> self.agent = util.isUndefined(options.agent) ? globalAgent : options.agent;
<ide>
<del> var defaultPort = options.defaultPort || 80;
<add> var defaultPort = options.defaultPort || self.agent.defaultPort;
<ide>
<del> var port = options.port || defaultPort;
<del> var host = options.hostname || options.host || 'localhost';
<add> var port = options.port = options.port || defaultPort;
<add> var host = options.host = options.hostname || options.host || 'localhost';
<ide>
<ide> if (util.isUndefined(options.setHost)) {
<ide> var setHost = true;
<ide><path>test/disabled/test-http-default-port.js
<ide>
<ide>
<ide>
<del>
<del>// This must be run as root.
<del>
<ide> var common = require('../common');
<ide> var http = require('http'),
<ide> https = require('https'),
<del> PORT = 80,
<del> SSLPORT = 443,
<add> PORT = common.PORT,
<add> SSLPORT = common.PORT + 1,
<ide> assert = require('assert'),
<ide> hostExpect = 'localhost',
<ide> fs = require('fs'),
<ide> var http = require('http'),
<ide> options = {
<ide> key: fs.readFileSync(fixtures + '/agent1-key.pem'),
<ide> cert: fs.readFileSync(fixtures + '/agent1-cert.pem')
<del> };
<add> },
<add> gotHttpsResp = false,
<add> gotHttpResp = false;
<add>
<add>process.on('exit', function() {
<add> assert(gotHttpsResp);
<add> assert(gotHttpResp);
<add> console.log('ok');
<add>});
<add>
<add>http.globalAgent.defaultPort = PORT;
<add>https.globalAgent.defaultPort = SSLPORT;
<ide>
<ide> http.createServer(function(req, res) {
<del> console.error(req.headers);
<ide> assert.equal(req.headers.host, hostExpect);
<add> assert.equal(req.headers['x-port'], PORT);
<ide> res.writeHead(200);
<ide> res.end('ok');
<ide> this.close();
<del>}).listen(PORT);
<add>}).listen(PORT, function() {
<add> http.get({
<add> host: 'localhost',
<add> headers: {
<add> 'x-port': PORT
<add> }
<add> }, function(res) {
<add> gotHttpResp = true;
<add> res.resume();
<add> });
<add>});
<ide>
<ide> https.createServer(options, function(req, res) {
<del> console.error(req.headers);
<ide> assert.equal(req.headers.host, hostExpect);
<add> assert.equal(req.headers['x-port'], SSLPORT);
<ide> res.writeHead(200);
<ide> res.end('ok');
<ide> this.close();
<del>}).listen(SSLPORT);
<del>
<del>http
<del> .get({ host: 'localhost',
<del> port: PORT,
<del> headers: { 'x-port': PORT } })
<del> .on('response', function(res) {});
<del>
<del>https
<del> .get({ host: 'localhost',
<del> port: SSLPORT,
<del> headers: { 'x-port': SSLPORT } })
<del> .on('response', function(res) {});
<add>}).listen(SSLPORT, function() {
<add> var req = https.get({
<add> host: 'localhost',
<add> rejectUnauthorized: false,
<add> headers: {
<add> 'x-port': SSLPORT
<add> }
<add> }, function(res) {
<add> gotHttpsResp = true;
<add> res.resume();
<add> });
<add>});
<ide><path>test/internet/test-http-https-default-ports.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>
<add>var https = require('https');
<add>var http = require('http');
<add>var gotHttpsResp = false;
<add>var gotHttpResp = false;
<add>
<add>process.on('exit', function() {
<add> assert(gotHttpsResp);
<add> assert(gotHttpResp);
<add> console.log('ok');
<add>});
<add>
<add>https.get('https://www.google.com/', function(res) {
<add> gotHttpsResp = true;
<add> res.resume();
<add>});
<add>
<add>http.get('http://www.google.com/', function(res) {
<add> gotHttpResp = true;
<add> res.resume();
<add>}); | 3 |
Javascript | Javascript | fix typo in descriptions | 3c7f0f7a367eb5e333843a120f29fbf44f017687 | <ide><path>test/ng/filter/filterSpec.js
<ide> describe('Filter: filter', function() {
<ide> expect(filter(items, function(i) {return i.done;}).length).toBe(1);
<ide> });
<ide>
<del> it('should take object as perdicate', function() {
<add> it('should take object as predicate', function() {
<ide> var items = [{first: 'misko', last: 'hevery'},
<ide> {first: 'adam', last: 'abrons'}];
<ide>
<ide> describe('Filter: filter', function() {
<ide> });
<ide>
<ide>
<del> it('should support predicat object with dots in the name', function() {
<add> it('should support predicate object with dots in the name', function() {
<ide> var items = [{'first.name': 'misko', 'last.name': 'hevery'},
<ide> {'first.name': 'adam', 'last.name': 'abrons'}];
<ide> | 1 |
Javascript | Javascript | add jquery.uniquesort; deprecate jquery.unique | e1090c3d2b2a988a5b41f1f1ed9f8d6dcae02200 | <ide><path>src/selector-sizzle.js
<ide> define([
<ide> jQuery.find = Sizzle;
<ide> jQuery.expr = Sizzle.selectors;
<ide> jQuery.expr[":"] = jQuery.expr.pseudos;
<del>jQuery.unique = Sizzle.uniqueSort;
<add>jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort;
<ide> jQuery.text = Sizzle.getText;
<ide> jQuery.isXMLDoc = Sizzle.isXML;
<ide> jQuery.contains = Sizzle.contains;
<ide><path>src/traversing.js
<ide> jQuery.fn.extend({
<ide> }
<ide> }
<ide>
<del> return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
<add> return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched );
<ide> },
<ide>
<ide> // Determine the position of an element within the set
<ide> jQuery.fn.extend({
<ide>
<ide> add: function( selector, context ) {
<ide> return this.pushStack(
<del> jQuery.unique(
<add> jQuery.uniqueSort(
<ide> jQuery.merge( this.get(), jQuery( selector, context ) )
<ide> )
<ide> );
<ide> jQuery.each({
<ide> if ( this.length > 1 ) {
<ide> // Remove duplicates
<ide> if ( !guaranteedUnique[ name ] ) {
<del> jQuery.unique( matched );
<add> jQuery.uniqueSort( matched );
<ide> }
<ide>
<ide> // Reverse order for parents* and prev-derivatives
<ide><path>src/traversing/findFilter.js
<ide> jQuery.fn.extend({
<ide> jQuery.find( selector, self[ i ], ret );
<ide> }
<ide>
<del> return this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
<add> return this.pushStack( len > 1 ? jQuery.uniqueSort( ret ) : ret );
<ide> },
<ide> filter: function( selector ) {
<ide> return this.pushStack( winnow(this, selector || [], false) );
<ide><path>test/unit/selector.js
<ide> test( "jQuery.contains", function() {
<ide> ok( !jQuery.contains(document, detached), "document container (negative)" );
<ide> });
<ide>
<del>test("jQuery.unique", function() {
<add>test("jQuery.uniqueSort", function() {
<ide> expect( 14 );
<ide>
<ide> function Arrayish( arr ) {
<ide> test("jQuery.unique", function() {
<ide>
<ide> jQuery.each( tests, function( label, test ) {
<ide> var length = test.length || test.input.length;
<del> deepEqual( jQuery.unique( test.input ).slice( 0, length ), test.expected, label + " (array)" );
<del> deepEqual( jQuery.unique( new Arrayish(test.input) ).slice( 0, length ), test.expected, label + " (quasi-array)" );
<add> deepEqual( jQuery.uniqueSort( test.input ).slice( 0, length ), test.expected, label + " (array)" );
<add> deepEqual( jQuery.uniqueSort( new Arrayish(test.input) ).slice( 0, length ), test.expected, label + " (quasi-array)" );
<ide> });
<ide> });
<ide>
<ide><path>test/unit/traversing.js
<ide> test("sort direction", function() {
<ide>
<ide> jQuery.each( methodDirections, function( method, reversed ) {
<ide> var actual = elems[ method ]().get(),
<del> forward = jQuery.unique( [].concat( actual ) );
<add> forward = jQuery.uniqueSort( [].concat( actual ) );
<ide> deepEqual( actual, reversed ? forward.reverse() : forward, "Correct sort direction for " + method );
<ide> });
<ide> }); | 5 |
Text | Text | update the link | e05fe7c42bb96d50d41a39ee319919b0a152d607 | <ide><path>README.md
<ide> - Intercept request and response
<ide> - Transform request and response data
<ide> - Cancel requests
<del>- Automatic transforms for JSON data
<add>- Automatic transforms for [JSON](https://www.json.org/json-en.html) data
<ide> - 🆕 Automatic data object serialization to `multipart/form-data` and `x-www-form-urlencoded` body encodings
<ide> - Client side support for protecting against [XSRF](https://en.wikipedia.org/wiki/Cross-site_request_forgery)
<ide> | 1 |
Go | Go | add grpc.withblock option | 9f73396dabf087a8dd5fa74296c2cd4c188ff889 | <ide><path>daemon/daemon.go
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> registerMetricsPluginCallback(d.PluginStore, metricsSockPath)
<ide>
<ide> gopts := []grpc.DialOption{
<add> // WithBlock makes sure that the following containerd request
<add> // is reliable.
<add> //
<add> // NOTE: In one edge case with high load pressure, kernel kills
<add> // dockerd, containerd and containerd-shims caused by OOM.
<add> // When both dockerd and containerd restart, but containerd
<add> // will take time to recover all the existing containers. Before
<add> // containerd serving, dockerd will failed with gRPC error.
<add> // That bad thing is that restore action will still ignore the
<add> // any non-NotFound errors and returns running state for
<add> // already stopped container. It is unexpected behavior. And
<add> // we need to restart dockerd to make sure that anything is OK.
<add> //
<add> // It is painful. Add WithBlock can prevent the edge case. And
<add> // n common case, the containerd will be serving in shortly.
<add> // It is not harm to add WithBlock for containerd connection.
<add> grpc.WithBlock(),
<add>
<ide> grpc.WithInsecure(),
<ide> grpc.WithBackoffMaxDelay(3 * time.Second),
<ide> grpc.WithDialer(dialer.Dialer), | 1 |
Java | Java | fix conversion of message<?> payload for replies | 72894b26c24b1ea31c6dda4634cfde67e7dc3050 | <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/adapter/AbstractAdaptableMessageListener.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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> private class MessagingMessageConverterAdapter extends MessagingMessageConverter
<ide> protected Object extractPayload(Message message) throws JMSException {
<ide> return extractMessage(message);
<ide> }
<add>
<add> @Override
<add> protected Message createMessageForPayload(Object payload, Session session) throws JMSException {
<add> MessageConverter converter = getMessageConverter();
<add> if (converter != null) {
<add> return converter.toMessage(payload, session);
<add> }
<add> throw new IllegalStateException("No message converter, cannot handle '" + payload + "'");
<add> }
<ide> }
<ide>
<ide>
<ide><path>spring-jms/src/main/java/org/springframework/jms/support/converter/MessagingMessageConverter.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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 javax.jms.Message toMessage(Object object, Session session) throws JMSExc
<ide> Message.class.getName() + "] is handled by this converter");
<ide> }
<ide> Message<?> input = (Message<?>) object;
<del> javax.jms.Message reply = this.payloadConverter.toMessage(input.getPayload(), session);
<add> javax.jms.Message reply = createMessageForPayload(input.getPayload(), session);
<ide> this.headerMapper.fromHeaders(input.getHeaders(), reply);
<ide> return reply;
<ide> }
<ide> protected Object extractPayload(javax.jms.Message message) throws JMSException {
<ide> return this.payloadConverter.fromMessage(message);
<ide> }
<ide>
<add> /**
<add> * Create a JMS message for the specified payload.
<add> * @see MessageConverter#toMessage(Object, Session)
<add> */
<add> protected javax.jms.Message createMessageForPayload(Object payload, Session session) throws JMSException {
<add> return this.payloadConverter.toMessage(payload, session);
<add> }
<add>
<ide> }
<ide><path>spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessagingMessageListenerAdapterTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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> package org.springframework.jms.listener.adapter;
<ide>
<ide> import java.lang.reflect.Method;
<add>import java.util.ArrayList;
<add>import java.util.List;
<ide> import javax.jms.Destination;
<ide> import javax.jms.JMSException;
<ide> import javax.jms.Session;
<ide> import org.springframework.beans.factory.support.StaticListableBeanFactory;
<ide> import org.springframework.jms.StubTextMessage;
<ide> import org.springframework.jms.support.JmsHeaders;
<add>import org.springframework.jms.support.converter.MessageConverter;
<ide> import org.springframework.messaging.Message;
<ide> import org.springframework.messaging.converter.MessageConversionException;
<ide> import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
<ide> public void exceptionInInvocation() {
<ide> }
<ide> }
<ide>
<add> @Test
<add> public void incomingMessageUsesMessageConverter() throws JMSException {
<add> javax.jms.Message jmsMessage = mock(javax.jms.Message.class);
<add> Session session = mock(Session.class);
<add> MessageConverter messageConverter = mock(MessageConverter.class);
<add> given(messageConverter.fromMessage(jmsMessage)).willReturn("FooBar");
<add> MessagingMessageListenerAdapter listener = getSimpleInstance("simple", Message.class);
<add> listener.setMessageConverter(messageConverter);
<add> listener.onMessage(jmsMessage, session);
<add> verify(messageConverter, times(1)).fromMessage(jmsMessage);
<add> assertEquals(1, sample.simples.size());
<add> assertEquals("FooBar", sample.simples.get(0).getPayload());
<add> }
<add>
<add> @Test
<add> public void replyUsesMessageConverterForPayload() throws JMSException {
<add> Session session = mock(Session.class);
<add> MessageConverter messageConverter = mock(MessageConverter.class);
<add> given(messageConverter.toMessage("Response", session)).willReturn(new StubTextMessage("Response"));
<add>
<add> Message<String> result = MessageBuilder.withPayload("Response")
<add> .build();
<add>
<add> MessagingMessageListenerAdapter listener = getSimpleInstance("echo", Message.class);
<add> listener.setMessageConverter(messageConverter);
<add> javax.jms.Message replyMessage = listener.buildMessage(session, result);
<add>
<add> verify(messageConverter, times(1)).toMessage("Response", session);
<add> assertNotNull("reply should never be null", replyMessage);
<add> assertEquals("Response", ((TextMessage) replyMessage).getText());
<add> }
<add>
<ide> protected MessagingMessageListenerAdapter getSimpleInstance(String methodName, Class... parameterTypes) {
<ide> Method m = ReflectionUtils.findMethod(SampleBean.class, methodName, parameterTypes);
<ide> return createInstance(m);
<ide> private void initializeFactory(DefaultMessageHandlerMethodFactory factory) {
<ide> @SuppressWarnings("unused")
<ide> private static class SampleBean {
<ide>
<add> public final List<Message<String>> simples = new ArrayList<>();
<add>
<add> public void simple(Message<String> input) {
<add> simples.add(input);
<add> }
<add>
<ide> public Message<String> echo(Message<String> input) {
<ide> return MessageBuilder.withPayload(input.getPayload())
<ide> .setHeader(JmsHeaders.TYPE, "reply") | 3 |
PHP | PHP | fix merge conflicts | a6235ca2a8e454c88083c7dab57aee3772034faa | <ide><path>src/Controller/Component/SecurityComponent.php
<ide> protected function _authRequired(Controller $controller)
<ide> * Validate submitted form
<ide> *
<ide> * @param \Cake\Controller\Controller $controller Instantiating controller
<add><<<<<<< HEAD
<ide> * @throws \Cake\Controller\Exception\SecurityException
<add>=======
<add> * @throws SecurityException
<add>>>>>>>> e73f064c716f82b627e39b5ad3730282202f6670
<ide> * @return bool true if submitted form is valid
<ide> */
<ide> protected function _validatePost(Controller $controller) | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.