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
add integration tests for psr7 + request bodies
a8567c5d3845057832e024557d564491a5d1fcf1
<ide><path>src/TestSuite/MiddlewareDispatcher.php <ide> use LogicException; <ide> use ReflectionClass; <ide> use ReflectionException; <add>use Zend\Diactoros\Stream; <ide> <ide> /** <ide> * Dispatches a request capturing the response for integration <ide> public function execute($request) <ide> ); <ide> <ide> $server = new Server($app); <del> $psrRequest = ServerRequestFactory::fromGlobals( <del> array_merge($_SERVER, $request['environment'], ['REQUEST_URI' => $request['url']]), <del> $request['query'], <del> $request['post'], <del> $request['cookies'] <del> ); <del> $psrRequest = $psrRequest->withAttribute('session', $request['session']); <add> $psrRequest = $this->_createRequest($request); <ide> $response = $server->run($psrRequest); <ide> return ResponseTransformer::toCake($response); <ide> } <add> <add> /** <add> * Create a PSR7 request from the request spec. <add> * <add> * @param array $spec The request spec. <add> * @return Psr\Http\Message\RequestInterface <add> */ <add> protected function _createRequest($spec) <add> { <add> if (isset($spec['input'])) { <add> $spec['post'] = []; <add> } <add> $request = ServerRequestFactory::fromGlobals( <add> array_merge($_SERVER, $spec['environment'], ['REQUEST_URI' => $spec['url']]), <add> $spec['query'], <add> $spec['post'], <add> $spec['cookies'] <add> ); <add> $request = $request->withAttribute('session', $spec['session']); <add> <add> if (isset($spec['input'])) { <add> $stream = new Stream('php://memory', 'rw'); <add> $stream->write($spec['input']); <add> $stream->rewind(); <add> $request = $request->withBody($stream); <add> } <add> return $request; <add> } <ide> } <ide><path>tests/TestCase/TestSuite/IntegrationTestCaseTest.php <ide> public function testGetCookiesHttpServer() <ide> } <ide> <ide> /** <del> * Test that the PSR7 requests get post data <add> * Test that the PSR7 requests receive post data <ide> * <ide> * @return void <ide> */ <ide> public function testPostDataHttpServer() <ide> $this->assertHeader('X-Middleware', 'true'); <ide> } <ide> <add> /** <add> * Test that the PSR7 requests receive encoded data. <add> * <add> * @return void <add> */ <add> public function testInputDataHttpServer() <add> { <add> $this->useHttpServer(true); <add> <add> $this->post('/request_action/input_test', '{"hello":"world"}'); <add> $this->assertSame('world', $this->_response->body()); <add> $this->assertHeader('X-Middleware', 'true'); <add> } <add> <ide> /** <ide> * Test that the PSR7 requests get cookies <ide> * <ide><path>tests/test_app/TestApp/Controller/RequestActionController.php <ide> public function session_test() <ide> return $this->response; <ide> } <ide> <add> /** <add> * Tests input data transmission <add> * <add> * @return \Cake\Network\Response <add> */ <add> public function input_test() <add> { <add> $this->response->body($this->request->input('json_decode')->hello); <add> return $this->response; <add> } <add> <ide> /** <ide> * Tests exception handling <ide> *
3
Javascript
Javascript
use multistep hmr by default
69b5e548d5138cd5ee30e440937e1582cbf69822
<ide><path>bin/convert-argv.js <ide> module.exports = function(optimist, argv, convertOptions) { <ide> ifBooleanArg("hot", function() { <ide> ensureArray(options, "plugins"); <ide> var HotModuleReplacementPlugin = require("../lib/HotModuleReplacementPlugin"); <del> options.plugins.push(new HotModuleReplacementPlugin()); <add> options.plugins.push(new HotModuleReplacementPlugin({ <add> multiStep: true <add> })); <ide> }); <ide> <ide> mapArgToBoolean("debug"); <ide><path>lib/HotModuleReplacement.runtime.js <ide> module.exports = function() { <ide> } <ide> <ide> hotSetStatus("idle"); <del> Promise.resolve(outdatedModules); <add> return Promise.resolve(outdatedModules); <ide> } <ide> };
2
Text
Text
fix broken docs link
3d708ac7005e29ca75aa68b447edb8d9dc111637
<ide><path>docs/topics/rest-hypermedia-hateoas.md <ide> REST framework also includes [serialization] and [parser]/[renderer] components <ide> <ide> What REST framework doesn't do is give you machine readable hypermedia formats such as [HAL][hal], [Collection+JSON][collection], [JSON API][json-api] or HTML [microformats] by default, or the ability to auto-magically create fully HATEOAS style APIs that include hypermedia-based form descriptions and semantically labelled hyperlinks. Doing so would involve making opinionated choices about API design that should really remain outside of the framework's scope. <ide> <del>[cite]: https://vimeo.com/channels/restfest/page:2 <add>[cite]: https://vimeo.com/channels/restfest/49503453 <ide> [dissertation]: https://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm <ide> [hypertext-driven]: https://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven <ide> [restful-web-apis]: http://restfulwebapis.org/
1
Python
Python
show tasks in grid view based on topological sort.
34154803ac73d62d3e969e480405df3073032622
<ide><path>airflow/models/dag.py <ide> import sys <ide> import traceback <ide> import warnings <del>from collections import OrderedDict <ide> from datetime import datetime, timedelta <ide> from inspect import signature <ide> from typing import ( <ide> def topological_sort(self, include_subdag_tasks: bool = False): <ide> Sorts tasks in topographical order, such that a task comes after any of its <ide> upstream dependencies. <ide> <del> Heavily inspired by: <del> http://blog.jupo.org/2012/04/06/topological-sorting-acyclic-directed-graphs/ <del> <del> :param include_subdag_tasks: whether to include tasks in subdags, default to False <del> :return: list of tasks in topological order <del> """ <del> from airflow.operators.subdag import SubDagOperator # Avoid circular import <del> <del> # convert into an OrderedDict to speedup lookup while keeping order the same <del> graph_unsorted = OrderedDict((task.task_id, task) for task in self.tasks) <del> <del> graph_sorted: List[Operator] = [] <del> <del> # special case <del> if len(self.tasks) == 0: <del> return tuple(graph_sorted) <del> <del> # Run until the unsorted graph is empty. <del> while graph_unsorted: <del> # Go through each of the node/edges pairs in the unsorted <del> # graph. If a set of edges doesn't contain any nodes that <del> # haven't been resolved, that is, that are still in the <del> # unsorted graph, remove the pair from the unsorted graph, <del> # and append it to the sorted graph. Note here that by using <del> # using the items() method for iterating, a copy of the <del> # unsorted graph is used, allowing us to modify the unsorted <del> # graph as we move through it. We also keep a flag for <del> # checking that graph is acyclic, which is true if any <del> # nodes are resolved during each pass through the graph. If <del> # not, we need to exit as the graph therefore can't be <del> # sorted. <del> acyclic = False <del> for node in list(graph_unsorted.values()): <del> for edge in node.upstream_list: <del> if edge.node_id in graph_unsorted: <del> break <del> # no edges in upstream tasks <del> else: <del> acyclic = True <del> del graph_unsorted[node.task_id] <del> graph_sorted.append(node) <del> if include_subdag_tasks and isinstance(node, SubDagOperator): <del> graph_sorted.extend(node.subdag.topological_sort(include_subdag_tasks=True)) <add> Deprecated in place of ``task_group.topological_sort`` <add> """ <add> from airflow.utils.task_group import TaskGroup <ide> <del> if not acyclic: <del> raise AirflowException(f"A cyclic dependency occurred in dag: {self.dag_id}") <add> def nested_topo(group): <add> for node in group.topological_sort(_include_subdag_tasks=include_subdag_tasks): <add> if isinstance(node, TaskGroup): <add> yield from nested_topo(node) <add> else: <add> yield node <ide> <del> return tuple(graph_sorted) <add> return tuple(nested_topo(self.task_group)) <ide> <ide> @provide_session <ide> def set_dag_runs_state( <ide><path>airflow/models/taskmixin.py <ide> def label(self) -> Optional[str]: <ide> def has_dag(self) -> bool: <ide> return self.dag is not None <ide> <add> @property <add> def dag_id(self) -> str: <add> """Returns dag id if it has one or an adhoc/meaningless ID""" <add> if self.dag: <add> return self.dag.dag_id <add> return "_in_memory_dag_" <add> <ide> @property <ide> def log(self) -> "Logger": <ide> raise NotImplementedError() <ide><path>airflow/serialization/serialized_objects.py <ide> def deserialize_dag(cls, encoded_dag: Dict[str, Any]) -> 'SerializedDAG': <ide> dag.timetable = create_timetable(dag.schedule_interval, dag.timezone) <ide> <ide> # Set _task_group <del> <ide> if "_task_group" in encoded_dag: <del> dag._task_group = SerializedTaskGroup.deserialize_task_group( # type: ignore <del> encoded_dag["_task_group"], None, dag.task_dict <add> dag._task_group = SerializedTaskGroup.deserialize_task_group( <add> encoded_dag["_task_group"], None, dag.task_dict, dag <ide> ) <ide> else: <ide> # This must be old data that had no task_group. Create a root TaskGroup and add <ide> def deserialize_task_group( <ide> encoded_group: Dict[str, Any], <ide> parent_group: Optional[TaskGroup], <ide> task_dict: Dict[str, Operator], <del> ) -> Optional[TaskGroup]: <add> dag: SerializedDAG, <add> ) -> TaskGroup: <ide> """Deserializes a TaskGroup from a JSON object.""" <del> if not encoded_group: <del> return None <del> <ide> group_id = cls._deserialize(encoded_group["_group_id"]) <ide> kwargs = { <ide> key: cls._deserialize(encoded_group[key]) <ide> for key in ["prefix_group_id", "tooltip", "ui_color", "ui_fgcolor"] <ide> } <del> group = SerializedTaskGroup(group_id=group_id, parent_group=parent_group, **kwargs) <add> group = SerializedTaskGroup(group_id=group_id, parent_group=parent_group, dag=dag, **kwargs) <ide> <ide> def set_ref(task: Operator) -> Operator: <ide> task.task_group = weakref.proxy(group) <ide> def set_ref(task: Operator) -> Operator: <ide> group.children = { <ide> label: set_ref(task_dict[val]) # type: ignore <ide> if _type == DAT.OP # type: ignore <del> else SerializedTaskGroup.deserialize_task_group(val, group, task_dict) <add> else SerializedTaskGroup.deserialize_task_group(val, group, task_dict, dag=dag) <ide> for label, (_type, val) in encoded_group["children"].items() <ide> } <ide> group.upstream_group_ids.update(cls._deserialize(encoded_group["upstream_group_ids"])) <ide><path>airflow/utils/task_group.py <ide> import weakref <ide> from typing import TYPE_CHECKING, Any, Dict, Generator, Iterable, List, Optional, Sequence, Set, Tuple, Union <ide> <del>from airflow.exceptions import AirflowException, DuplicateTaskIdFound <add>from airflow.exceptions import AirflowDagCycleException, AirflowException, DuplicateTaskIdFound <ide> from airflow.models.taskmixin import DAGNode, DependencyMixin <ide> from airflow.serialization.enums import DagAttributeTypes <ide> from airflow.utils.helpers import validate_group_key <ide> def expand(self, arg: Iterable) -> "MappedTaskGroup": <ide> self.task_group._remove(self) <ide> return MappedTaskGroup(group_id=self._group_id, dag=self.dag, mapped_arg=arg) <ide> <add> def topological_sort(self, _include_subdag_tasks: bool = False): <add> """ <add> Sorts children in topographical order, such that a task comes after any of its <add> upstream dependencies. <add> <add> :return: list of tasks in topological order <add> """ <add> # This uses a modified version of Kahn's Topological Sort algorithm to <add> # not have to pre-compute the "in-degree" of the nodes. <add> from airflow.operators.subdag import SubDagOperator # Avoid circular import <add> <add> graph_unsorted = copy.copy(self.children) <add> <add> graph_sorted: List[DAGNode] = [] <add> <add> # special case <add> if len(self.children) == 0: <add> return graph_sorted <add> <add> # Run until the unsorted graph is empty. <add> while graph_unsorted: <add> # Go through each of the node/edges pairs in the unsorted graph. If a set of edges doesn't contain <add> # any nodes that haven't been resolved, that is, that are still in the unsorted graph, remove the <add> # pair from the unsorted graph, and append it to the sorted graph. Note here that by using using <add> # the values() method for iterating, a copy of the unsorted graph is used, allowing us to modify <add> # the unsorted graph as we move through it. <add> # <add> # We also keep a flag for checking that graph is acyclic, which is true if any nodes are resolved <add> # during each pass through the graph. If not, we need to exit as the graph therefore can't be <add> # sorted. <add> acyclic = False <add> for node in list(graph_unsorted.values()): <add> for edge in node.upstream_list: <add> if edge.node_id in graph_unsorted: <add> break <add> # Check for task's group is a child (or grand child) of this TG, <add> tg = edge.task_group <add> while tg: <add> if tg.node_id in graph_unsorted: <add> break <add> tg = tg.task_group <add> <add> if tg: <add> # We are already going to visit that TG <add> break <add> else: <add> acyclic = True <add> del graph_unsorted[node.node_id] <add> graph_sorted.append(node) <add> if _include_subdag_tasks and isinstance(node, SubDagOperator): <add> graph_sorted.extend( <add> node.subdag.task_group.topological_sort(_include_subdag_tasks=True) <add> ) <add> <add> if not acyclic: <add> raise AirflowDagCycleException(f"A cyclic dependency occurred in dag: {self.dag_id}") <add> <add> return graph_sorted <add> <ide> <ide> class MappedTaskGroup(TaskGroup): <ide> """ <ide><path>airflow/www/views.py <ide> def task_group_to_tree(task_item_or_group, dag, dag_runs, tis, session): <ide> task_group = task_item_or_group <ide> <ide> children = [ <del> task_group_to_tree(child, dag, dag_runs, tis, session) for child in task_group.children.values() <add> task_group_to_tree(child, dag, dag_runs, tis, session) for child in task_group.topological_sort() <ide> ] <ide> <ide> def get_summary(dag_run, children): <ide><path>tests/models/test_dag.py <ide> def test_dag_topological_sort_include_subdag_tasks(self): <ide> assert self._occur_before('a_child', 'b_parent', topological_list) <ide> assert self._occur_before('b_child', 'b_parent', topological_list) <ide> <del> def test_dag_topological_sort1(self): <del> dag = DAG('dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) <del> <del> # A -> B <del> # A -> C -> D <del> # ordered: B, D, C, A or D, B, C, A or D, C, B, A <del> with dag: <del> op1 = DummyOperator(task_id='A') <del> op2 = DummyOperator(task_id='B') <del> op3 = DummyOperator(task_id='C') <del> op4 = DummyOperator(task_id='D') <del> op1.set_upstream([op2, op3]) <del> op3.set_upstream(op4) <del> <del> topological_list = dag.topological_sort() <del> logging.info(topological_list) <del> <del> tasks = [op2, op3, op4] <del> assert topological_list[0] in tasks <del> tasks.remove(topological_list[0]) <del> assert topological_list[1] in tasks <del> tasks.remove(topological_list[1]) <del> assert topological_list[2] in tasks <del> tasks.remove(topological_list[2]) <del> assert topological_list[3] == op1 <del> <del> def test_dag_topological_sort2(self): <del> dag = DAG('dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) <del> <del> # C -> (A u B) -> D <del> # C -> E <del> # ordered: E | D, A | B, C <del> with dag: <del> op1 = DummyOperator(task_id='A') <del> op2 = DummyOperator(task_id='B') <del> op3 = DummyOperator(task_id='C') <del> op4 = DummyOperator(task_id='D') <del> op5 = DummyOperator(task_id='E') <del> op1.set_downstream(op3) <del> op2.set_downstream(op3) <del> op1.set_upstream(op4) <del> op2.set_upstream(op4) <del> op5.set_downstream(op3) <del> <del> topological_list = dag.topological_sort() <del> logging.info(topological_list) <del> <del> set1 = [op4, op5] <del> assert topological_list[0] in set1 <del> set1.remove(topological_list[0]) <del> <del> set2 = [op1, op2] <del> set2.extend(set1) <del> assert topological_list[1] in set2 <del> set2.remove(topological_list[1]) <del> <del> assert topological_list[2] in set2 <del> set2.remove(topological_list[2]) <del> <del> assert topological_list[3] in set2 <del> <del> assert topological_list[4] == op3 <del> <ide> def test_dag_topological_sort_dag_without_tasks(self): <ide> dag = DAG('dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) <ide> <ide><path>tests/serialization/test_dag_serialization.py <ide> def test_task_group_serialization(self): <ide> assert serialized_dag.task_group.children.keys() == dag.task_group.children.keys() <ide> <ide> def check_task_group(node): <add> assert node.dag is serialized_dag <ide> try: <ide> children = node.children.values() <ide> except AttributeError: <ide> def test_mapped_task_group_serde(): <ide> ], <ide> } <ide> <del> with DAG("test", start_date=execution_date): <del> SerializedTaskGroup.deserialize_task_group(serialized, None, dag.task_dict) <add> with DAG("test", start_date=execution_date) as new_dag: <add> SerializedTaskGroup.deserialize_task_group(serialized, None, dag.task_dict, new_dag) <ide><path>tests/utils/test_task_group.py <ide> def my_task_group(my_arg_1: str, unmapped: bool): <ide> tg = dag.task_group.get_child_by_label("my_task_group") <ide> assert isinstance(tg, MappedTaskGroup) <ide> assert "my_arg_1" in tg.mapped_kwargs <add> <add> <add>def test_topological_sort1(): <add> dag = DAG('dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) <add> <add> # A -> B <add> # A -> C -> D <add> # ordered: B, D, C, A or D, B, C, A or D, C, B, A <add> with dag: <add> op1 = DummyOperator(task_id='A') <add> op2 = DummyOperator(task_id='B') <add> op3 = DummyOperator(task_id='C') <add> op4 = DummyOperator(task_id='D') <add> [op2, op3] >> op1 <add> op3 >> op4 <add> <add> topological_list = dag.task_group.topological_sort() <add> <add> tasks = [op2, op3, op4] <add> assert topological_list[0] in tasks <add> tasks.remove(topological_list[0]) <add> assert topological_list[1] in tasks <add> tasks.remove(topological_list[1]) <add> assert topological_list[2] in tasks <add> tasks.remove(topological_list[2]) <add> assert topological_list[3] == op1 <add> <add> <add>def test_topological_sort2(): <add> dag = DAG('dag', start_date=DEFAULT_DATE, default_args={'owner': 'owner1'}) <add> <add> # C -> (A u B) -> D <add> # C -> E <add> # ordered: E | D, A | B, C <add> with dag: <add> op1 = DummyOperator(task_id='A') <add> op2 = DummyOperator(task_id='B') <add> op3 = DummyOperator(task_id='C') <add> op4 = DummyOperator(task_id='D') <add> op5 = DummyOperator(task_id='E') <add> op3 << [op1, op2] <add> op4 >> [op1, op2] <add> op5 >> op3 <add> <add> topological_list = dag.task_group.topological_sort() <add> <add> set1 = [op4, op5] <add> assert topological_list[0] in set1 <add> set1.remove(topological_list[0]) <add> <add> set2 = [op1, op2] <add> set2.extend(set1) <add> assert topological_list[1] in set2 <add> set2.remove(topological_list[1]) <add> <add> assert topological_list[2] in set2 <add> set2.remove(topological_list[2]) <add> <add> assert topological_list[3] in set2 <add> <add> assert topological_list[4] == op3 <add> <add> <add>def test_topological_nested_groups(): <add> execution_date = pendulum.parse("20200101") <add> with DAG("test_dag_edges", start_date=execution_date) as dag: <add> task1 = DummyOperator(task_id="task1") <add> task5 = DummyOperator(task_id="task5") <add> with TaskGroup("group_a") as group_a: <add> with TaskGroup("group_b"): <add> task2 = DummyOperator(task_id="task2") <add> task3 = DummyOperator(task_id="task3") <add> task4 = DummyOperator(task_id="task4") <add> task2 >> [task3, task4] <add> <add> task1 >> group_a <add> group_a >> task5 <add> <add> def nested_topo(group): <add> return [ <add> nested_topo(node) if isinstance(node, TaskGroup) else node for node in group.topological_sort() <add> ] <add> <add> topological_list = nested_topo(dag.task_group) <add> <add> assert topological_list == [ <add> task1, <add> [ <add> [ <add> task2, <add> task3, <add> task4, <add> ], <add> ], <add> task5, <add> ] <add> <add> <add>def test_topological_group_dep(): <add> execution_date = pendulum.parse("20200101") <add> with DAG("test_dag_edges", start_date=execution_date) as dag: <add> task1 = DummyOperator(task_id="task1") <add> task6 = DummyOperator(task_id="task6") <add> with TaskGroup("group_a") as group_a: <add> task2 = DummyOperator(task_id="task2") <add> task3 = DummyOperator(task_id="task3") <add> with TaskGroup("group_b") as group_b: <add> task4 = DummyOperator(task_id="task4") <add> task5 = DummyOperator(task_id="task5") <add> <add> task1 >> group_a >> group_b >> task6 <add> <add> def nested_topo(group): <add> return [ <add> nested_topo(node) if isinstance(node, TaskGroup) else node for node in group.topological_sort() <add> ] <add> <add> topological_list = nested_topo(dag.task_group) <add> <add> assert topological_list == [ <add> task1, <add> [ <add> task2, <add> task3, <add> ], <add> [ <add> task4, <add> task5, <add> ], <add> task6, <add> ]
8
PHP
PHP
apply fixes from styleci
92ffcb35f2e863984aff235f7d094f8b5ae1a3af
<ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php <ide> public function get($path) <ide> */ <ide> public function put($path, $contents, $options = []) <ide> { <del> $options = is_string($options) <add> $options = is_string($options) <ide> ? ['visibility' => $options] <ide> : (array) $options; <ide>
1
Python
Python
add sslerror to retry decorator exceptions
5733de362d198e70ae5c81082f96de83f307d4b2
<ide><path>libcloud/test/common/test_retry_limit.py <ide> <ide> import socket <ide> import tempfile <add>import ssl <ide> <ide> from mock import Mock, patch, MagicMock <ide> <ide> from libcloud.utils.py3 import httplib <add>from libcloud.utils.misc import TRANSIENT_SSL_ERROR <ide> from libcloud.common.base import Connection <ide> from libcloud.common.base import Response <ide> from libcloud.common.exceptions import RateLimitReachedError <ide> SIMPLE_RESPONSE_STATUS = ('HTTP/1.1', 429, 'CONFLICT') <ide> <ide> <add>@patch('os.environ', {'LIBCLOUD_RETRY_FAILED_HTTP_REQUESTS': True}) <ide> class FailedRequestRetryTestCase(unittest.TestCase): <ide> <ide> def _raise_socket_error(self): <ide> def test_retry_connection(self): <ide> except Exception: <ide> self.fail('Failed to raise socket exception') <ide> <add> def test_retry_connection_ssl_error(self): <add> conn = Connection(timeout=1, retry_delay=0.1) <add> <add> with patch.object(conn, 'connect', Mock()): <add> with patch.object(conn, 'connection') as connection: <add> connection.request = MagicMock( <add> __name__='request', <add> side_effect=ssl.SSLError(TRANSIENT_SSL_ERROR)) <add> <add> self.assertRaises(ssl.SSLError, conn.request, '/') <add> self.assertGreater(connection.request.call_count, 1) <add> <ide> def test_rate_limit_error(self): <ide> sock = Mock() <ide> con = Connection() <ide><path>libcloud/utils/misc.py <ide> import socket <ide> from datetime import datetime, timedelta <ide> import time <add>import ssl <ide> <ide> from libcloud.common.exceptions import RateLimitReachedError <ide> <add> <add>TRANSIENT_SSL_ERROR = 'The read operation timed out' <add> <add> <add>class TransientSSLError(ssl.SSLError): <add> """Represent transient SSL errors, e.g. timeouts""" <add> pass <add> <add> <ide> DEFAULT_TIMEOUT = 30 <del>DEFAULT_SLEEP = 1 <del>DEFAULT_BACKCOFF = 1 <del>EXCEPTION_TYPES = (RateLimitReachedError, socket.error, socket.gaierror, <del> httplib.NotConnected, httplib.ImproperConnectionState) <add>DEFAULT_DELAY = 1 <add>DEFAULT_BACKOFF = 1 <add>RETRY_EXCEPTIONS = (RateLimitReachedError, socket.error, socket.gaierror, <add> httplib.NotConnected, httplib.ImproperConnectionState, <add> TransientSSLError) <ide> <ide> __all__ = [ <ide> 'find', <ide> def __str__(self): <ide> return str(self.__repr__()) <ide> <ide> <del>def retry(retry_exceptions=EXCEPTION_TYPES, retry_delay=None, <del> timeout=None, backoff=None): <add>def retry(retry_exceptions=None, retry_delay=None, timeout=None, <add> backoff=None): <ide> """ <del> Retry method that helps to handle common exception. <add> Retry decorator that helps to handle common transient exceptions. <ide> <ide> :param retry_exceptions: types of exceptions to retry on. <ide> :param retry_delay: retry delay between the attempts. <ide> def retry(retry_exceptions=EXCEPTION_TYPES, retry_delay=None, <ide> retry_request = retry(timeout=1, retry_delay=1, backoff=1) <ide> retry_request(self.connection.request)() <ide> """ <del> def deco_retry(func): <add> if retry_exceptions is None: <add> retry_exceptions = RETRY_EXCEPTIONS <add> if retry_delay is None: <add> retry_delay = DEFAULT_DELAY <add> if timeout is None: <add> timeout = DEFAULT_TIMEOUT <add> if backoff is None: <add> backoff = DEFAULT_BACKOFF <add> <add> timeout = max(timeout, 0) <add> <add> def transform_ssl_error(func, *args, **kwargs): <add> try: <add> return func(*args, **kwargs) <add> except ssl.SSLError: <add> exc = sys.exc_info()[1] <add> <add> if TRANSIENT_SSL_ERROR in str(exc): <add> raise TransientSSLError(*exc.args) <add> <add> raise exc <add> <add> def decorator(func): <ide> @wraps(func) <ide> def retry_loop(*args, **kwargs): <del> delay = retry_delay <add> current_delay = retry_delay <ide> end = datetime.now() + timedelta(seconds=timeout) <del> exc_info = None <del> while datetime.now() < end: <add> <add> while True: <ide> try: <del> result = func(*args, **kwargs) <del> return result <add> return transform_ssl_error(func, *args, **kwargs) <ide> except retry_exceptions: <del> e = sys.exc_info()[1] <add> exc = sys.exc_info()[1] <ide> <del> if isinstance(e, RateLimitReachedError): <del> time.sleep(e.retry_after) <add> if isinstance(exc, RateLimitReachedError): <add> time.sleep(exc.retry_after) <add> <add> # Reset retries if we're told to wait due to rate <add> # limiting <add> current_delay = retry_delay <ide> end = datetime.now() + timedelta( <del> seconds=e.retry_after + timeout) <add> seconds=exc.retry_after + timeout) <add> elif datetime.now() >= end: <add> raise <ide> else: <del> exc_info = e <del> time.sleep(delay) <del> delay *= backoff <del> if exc_info: <del> raise exc_info <del> return func(*args, **kwargs) <add> time.sleep(current_delay) <add> current_delay *= backoff <add> <ide> return retry_loop <del> return deco_retry <add> return decorator
2
Go
Go
fix flaky testruncontainerwithrmflag tests
585c147b7a78c02f04773ab611bb41268ed1aa3b
<ide><path>integration-cli/docker_cli_run_test.go <ide> func (s *DockerSuite) TestRunVolumesFromRestartAfterRemoved(c *testing.T) { <ide> <ide> // run container with --rm should remove container if exit code != 0 <ide> func (s *DockerSuite) TestRunContainerWithRmFlagExitCodeNotEqualToZero(c *testing.T) { <del> existingContainers := ExistingContainerIDs(c) <ide> name := "flowers" <ide> cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "ls", "/notexists")).Assert(c, icmd.Expected{ <ide> ExitCode: 1, <ide> }) <ide> <del> out := cli.DockerCmd(c, "ps", "-q", "-a").Combined() <del> out = RemoveOutputForExistingElements(out, existingContainers) <del> if out != "" { <del> c.Fatal("Expected not to have containers", out) <del> } <add> cli.Docker(cli.Args("container", "inspect", name)).Assert(c, icmd.Expected{ <add> ExitCode: 1, <add> Out: "[]\n", <add> Err: "o such container", // (N|n)o such container <add> }) <ide> } <ide> <ide> func (s *DockerSuite) TestRunContainerWithRmFlagCannotStartContainer(c *testing.T) { <del> existingContainers := ExistingContainerIDs(c) <ide> name := "sparkles" <ide> cli.Docker(cli.Args("run", "--name", name, "--rm", "busybox", "commandNotFound")).Assert(c, icmd.Expected{ <ide> ExitCode: 127, <ide> }) <del> out := cli.DockerCmd(c, "ps", "-q", "-a").Combined() <del> out = RemoveOutputForExistingElements(out, existingContainers) <del> if out != "" { <del> c.Fatal("Expected not to have containers", out) <del> } <add> <add> cli.Docker(cli.Args("container", "inspect", name)).Assert(c, icmd.Expected{ <add> ExitCode: 1, <add> Out: "[]\n", <add> Err: "o such container", // (N|n)o such container <add> }) <ide> } <ide> <ide> func (s *DockerSuite) TestRunPIDHostWithChildIsKillable(c *testing.T) {
1
Python
Python
use underscore, not -
f8bdf9a02fb8027487e9a07bd9cb73a9d1149f71
<ide><path>libcloud/drivers/slicehost.py <ide> def _to_node(self, element): <ide> <ide> # for consistency with other drivers, we put this in two places. <ide> node_attrs['password'] = node_attrs['root-password'] <add> extra = {} <add> for k in node_attrs.keys(): <add> ek = k.replace("-", "_") <add> extra[ek] = node_attrs[k] <ide> n = Node(id=element.findtext('id'), <ide> name=element.findtext('name'), <ide> state=state, <ide> public_ip=[public_ip], <ide> private_ip=[private_ip], <ide> driver=self.connection.driver, <del> extra=node_attrs) <add> extra=extra) <ide> return n <ide> <ide> def _to_sizes(self, object):
1
Javascript
Javascript
use different port numbers per build
84187b6d94179edf04512038f68c14f34a8e6219
<ide><path>lib/browser-stack/start-tunnel.js <ide> var http = require('http'); <ide> var BrowserStackTunnel = require('browserstacktunnel-wrapper'); <ide> <ide> var HOSTNAME = 'localhost'; <del>var PORTS = [9090, 9876]; <add>var PORTS = require('../grunt/utils').availablePorts; <ide> var ACCESS_KEY = process.env.BROWSER_STACK_ACCESS_KEY; <ide> var READY_FILE = process.env.SAUCE_CONNECT_READY_FILE; <ide> <ide><path>lib/grunt/utils.js <ide> var spawn = require('child_process').spawn; <ide> var version; <ide> var CSP_CSS_HEADER = '/* Include this file in your html if you are using the CSP mode. */\n\n'; <ide> <add>var PORT_MIN = 8000; <add>var PORT_MAX = 9999; <add>var TRAVIS_BUILD_NUMBER = parseInt(process.env.TRAVIS_BUILD_NUMBER, 10); <add>var getRandomPorts = function() { <add> if (!process.env.TRAVIS) { <add> return [9876, 9877]; <add> } <add> <add> // Generate two numbers between PORT_MIN and PORT_MAX, based on TRAVIS_BUILD_NUMBER. <add> return [ <add> PORT_MIN + (TRAVIS_BUILD_NUMBER % (PORT_MAX - PORT_MIN)), <add> PORT_MIN + ((TRAVIS_BUILD_NUMBER + 100) % (PORT_MAX - PORT_MIN)) <add> ]; <add>}; <add> <add> <ide> module.exports = { <ide> <ide> init: function() { <ide> module.exports = { <ide> stream: options && options.stream <ide> }; <ide> <del> args.push('--port=' + this.sauceLabsAvailablePorts.pop()); <add> args.push('--port=' + this.availablePorts.pop()); <ide> <ide> if (args.indexOf('test:e2e') !== -1 && grunt.option('e2e-browsers')) { <ide> args.push('--browsers=' + grunt.option('e2e-browsers')); <ide> module.exports = { <ide> }, <ide> <ide> // see http://saucelabs.com/docs/connect#localhost <del> sauceLabsAvailablePorts: [9000, 9001, 9080, 9090, 9876] <add> sauceLabsAvailablePorts: [9000, 9001, 9080, 9090, 9876], <add> // pseudo-random port numbers for BrowserStack <add> availablePorts: getRandomPorts() <ide> };
2
Javascript
Javascript
remove typos in code example
3c3e77a72ff52b8ee3aaef9af145ddae8685cd16
<ide><path>lib/ember.js <ide> Ember.empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.i <ide> Ember.compare('hello', 'hello'); // 0 <ide> Ember.compare('abc', 'dfg'); // -1 <ide> Ember.compare(2, 1); // 1 <del> ```javascript <add> ``` <ide> <ide> @method compare <ide> @for Ember <ide><path>packages/ember-runtime/lib/core.js <ide> Ember.empty = Ember.deprecateFunc("Ember.empty is deprecated. Please use Ember.i <ide> Ember.compare('hello', 'hello'); // 0 <ide> Ember.compare('abc', 'dfg'); // -1 <ide> Ember.compare(2, 1); // 1 <del> ```javascript <add> ``` <ide> <ide> @method compare <ide> @for Ember
2
PHP
PHP
test broken case
c52e1a467345607926c9378fb2646f8ead6cc1a4
<ide><path>src/Illuminate/Mail/Mailable.php <ide> public function replyTo($address, $name = null) <ide> */ <ide> protected function setAddress($address, $name = null, $property = 'to') <ide> { <del> if (! is_array($address) && ! $address instanceof Collection) { <del> $address = [$address]; <del> } <del> <del> foreach ($address as $recipient) { <add> foreach ($this->recipientToArray($address, $name) as $recipient) { <ide> $recipient = $this->normalizeRecipient($recipient); <ide> <ide> $this->{$property}[] = [ <ide> protected function setAddress($address, $name = null, $property = 'to') <ide> return $this; <ide> } <ide> <add> /** <add> * Convert the given recipient arguments to an array. <add> * <add> * @param object|array|string $address <add> * @param string|null $name <add> * @return array <add> */ <add> protected function recipientToArray($address, $name) <add> { <add> if (! is_array($address) && ! $address instanceof Collection) { <add> $address = is_string($name) ? [['name' => $name, 'email' => $address]] : [$address]; <add> } <add> <add> return $address; <add> } <add> <ide> /** <ide> * Convert the given recipient into an object. <ide> * <ide><path>tests/Mail/MailMailableTest.php <ide> public function testMailableSetsRecipientsCorrectly() <ide> $mailable->to('[email protected]'); <ide> $this->assertEquals([['name' => null, 'address' => '[email protected]']], $mailable->to); <ide> <add> $mailable = new WelcomeMailableStub; <add> $mailable->to('[email protected]', 'Taylor Otwell'); <add> $this->assertEquals([['name' => 'Taylor Otwell', 'address' => '[email protected]']], $mailable->to); <add> <ide> $mailable = new WelcomeMailableStub; <ide> $mailable->to(['[email protected]']); <ide> $this->assertEquals([['name' => null, 'address' => '[email protected]']], $mailable->to);
2
Python
Python
fix f401 flake8 warning (x28)
939148b050930897510c26f6d2833ef8e8029fa2
<ide><path>examples/run_bertology.py <ide> from tqdm import tqdm <ide> <ide> from run_glue import ALL_MODELS, MODEL_CLASSES, load_and_cache_examples, set_seed <del>from transformers import ( <del> WEIGHTS_NAME, <del> BertConfig, <del> BertForSequenceClassification, <del> BertTokenizer, <del> XLMConfig, <del> XLMForSequenceClassification, <del> XLMTokenizer, <del> XLNetConfig, <del> XLNetForSequenceClassification, <del> XLNetTokenizer, <del>) <ide> from transformers import glue_compute_metrics as compute_metrics <ide> from transformers import glue_output_modes as output_modes <ide> from transformers import glue_processors as processors <ide><path>templates/adding_a_new_model/tests/modeling_tf_xxx_test.py <ide> TFXxxForSequenceClassification, <ide> TFXxxForTokenClassification, <ide> TFXxxForQuestionAnswering, <del> TF_XXX_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> ) <ide> <ide> <ide><path>templates/adding_a_new_model/tests/modeling_xxx_test.py <ide> XxxConfig, <ide> XxxModel, <ide> XxxForMaskedLM, <del> XxxForNextSentencePrediction, <del> XxxForPreTraining, <ide> XxxForQuestionAnswering, <ide> XxxForSequenceClassification, <ide> XxxForTokenClassification, <del> XxxForMultipleChoice, <ide> ) <ide> from transformers.modeling_xxx import XXX_PRETRAINED_MODEL_ARCHIVE_MAP <ide> <ide><path>transformers/convert_pytorch_checkpoint_to_tf2.py <ide> TFCTRLLMHeadModel, <ide> TFDistilBertForMaskedLM, <ide> TFDistilBertForQuestionAnswering, <del> TFDistilBertForSequenceClassification, <ide> TFGPT2LMHeadModel, <ide> TFOpenAIGPTLMHeadModel, <ide> TFRobertaForMaskedLM, <ide><path>transformers/convert_roberta_original_pytorch_checkpoint_to_pytorch.py <ide> from fairseq.modules import TransformerSentenceEncoderLayer <ide> from transformers.modeling_bert import ( <ide> BertConfig, <del> BertEncoder, <ide> BertIntermediate, <ide> BertLayer, <del> BertModel, <ide> BertOutput, <ide> BertSelfAttention, <ide> BertSelfOutput, <ide> ) <del>from transformers.modeling_roberta import ( <del> RobertaEmbeddings, <del> RobertaForMaskedLM, <del> RobertaForSequenceClassification, <del> RobertaModel, <del>) <add>from transformers.modeling_roberta import RobertaForMaskedLM, RobertaForSequenceClassification <ide> <ide> <ide> if version.parse(fairseq.__version__) < version.parse("0.9.0"): <ide><path>transformers/modeling_auto.py <ide> from .modeling_camembert import ( <ide> CAMEMBERT_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> CamembertForMaskedLM, <del> CamembertForMultipleChoice, <ide> CamembertForSequenceClassification, <ide> CamembertForTokenClassification, <ide> CamembertModel, <ide> from .modeling_xlm_roberta import ( <ide> XLM_ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> XLMRobertaForMaskedLM, <del> XLMRobertaForMultipleChoice, <ide> XLMRobertaForSequenceClassification, <ide> XLMRobertaForTokenClassification, <ide> XLMRobertaModel, <ide><path>transformers/modeling_tf_utils.py <ide> from tensorflow.python.keras.saving import hdf5_format <ide> <ide> from .configuration_utils import PretrainedConfig <del>from .file_utils import ( <del> DUMMY_INPUTS, <del> TF2_WEIGHTS_NAME, <del> TF_WEIGHTS_NAME, <del> WEIGHTS_NAME, <del> cached_path, <del> hf_bucket_url, <del> is_remote_url, <del>) <add>from .file_utils import DUMMY_INPUTS, TF2_WEIGHTS_NAME, WEIGHTS_NAME, cached_path, hf_bucket_url, is_remote_url <ide> from .modeling_tf_pytorch_utils import load_pytorch_checkpoint_in_tf2_model <ide> <ide> <ide><path>transformers/modeling_tf_xlm.py <ide> <ide> from .configuration_xlm import XLMConfig <ide> from .file_utils import add_start_docstrings <del>from .modeling_tf_utils import ( <del> DUMMY_INPUTS, <del> TFPreTrainedModel, <del> TFSequenceSummary, <del> TFSharedEmbeddings, <del> get_initializer, <del> shape_list, <del>) <add>from .modeling_tf_utils import TFPreTrainedModel, TFSequenceSummary, TFSharedEmbeddings, get_initializer, shape_list <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide><path>transformers/modeling_xlnet.py <ide> <ide> from .configuration_xlnet import XLNetConfig <ide> from .file_utils import add_start_docstrings <del>from .modeling_utils import ( <del> PoolerAnswerClass, <del> PoolerEndLogits, <del> PoolerStartLogits, <del> PreTrainedModel, <del> SequenceSummary, <del> prune_linear_layer, <del>) <add>from .modeling_utils import PoolerAnswerClass, PoolerEndLogits, PoolerStartLogits, PreTrainedModel, SequenceSummary <ide> <ide> <ide> logger = logging.getLogger(__name__) <ide><path>transformers/tests/modeling_common_test.py <ide> BertModel, <ide> BertConfig, <ide> BERT_PRETRAINED_MODEL_ARCHIVE_MAP, <del> GPT2LMHeadModel, <del> GPT2Config, <del> GPT2_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> ) <ide> <ide> if sys.version_info[0] == 2: <ide><path>transformers/tests/modeling_tf_bert_test.py <ide> TFBertForMultipleChoice, <ide> TFBertForTokenClassification, <ide> TFBertForQuestionAnswering, <del> TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> ) <ide> <ide>
11
Ruby
Ruby
fix number_to_human docs [ci skip]
848276dfba42f996a01e720a252e5fee83a4b6c2
<ide><path>actionpack/lib/action_view/helpers/number_helper.rb <ide> def number_to_human_size(number, options = {}) <ide> # * *integers*: <tt>:unit</tt>, <tt>:ten</tt>, <tt>:hundred</tt>, <tt>:thousand</tt>, <tt>:million</tt>, <tt>:billion</tt>, <tt>:trillion</tt>, <tt>:quadrillion</tt> <ide> # * *fractionals*: <tt>:deci</tt>, <tt>:centi</tt>, <tt>:mili</tt>, <tt>:micro</tt>, <tt>:nano</tt>, <tt>:pico</tt>, <tt>:femto</tt> <ide> # * <tt>:format</tt> - Sets the format of the output string (defaults to "%n %u"). The field types are: <del> # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. <del> # <ide> # %u The quantifier (ex.: 'thousand') <ide> # %n The number <add> # * <tt>:raise</tt> - If true, raises +InvalidNumberError+ when the argument is invalid. <add> # <ide> # <ide> # ==== Examples <ide> # number_to_human(123) # => "123"
1
Java
Java
fix failing tests
5345bd4a85cc5f9ba723bec7c558f685ccb22bac
<ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/DefaultControllerSpec.java <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.annotation.AnnotationConfigApplicationContext; <ide> import org.springframework.format.FormatterRegistry; <del>import org.springframework.http.codec.HttpMessageReader; <del>import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.http.codec.ServerHttpMessageReader; <add>import org.springframework.http.codec.ServerHttpMessageWriter; <ide> import org.springframework.util.Assert; <ide> import org.springframework.util.ObjectUtils; <ide> import org.springframework.validation.Validator; <ide> public DefaultControllerSpec pathMatching(Consumer<PathMatchConfigurer> consumer <ide> } <ide> <ide> @Override <del> public DefaultControllerSpec messageReaders(Consumer<List<HttpMessageReader<?>>> consumer) { <add> public DefaultControllerSpec messageReaders(Consumer<List<ServerHttpMessageReader<?>>> consumer) { <ide> this.configurer.readersConsumer = consumer; <ide> return this; <ide> } <ide> <ide> @Override <del> public DefaultControllerSpec messageWriters(Consumer<List<HttpMessageWriter<?>>> consumer) { <add> public DefaultControllerSpec messageWriters(Consumer<List<ServerHttpMessageWriter<?>>> consumer) { <ide> this.configurer.writersConsumer = consumer; <ide> return this; <ide> } <ide> private class TestWebFluxConfigurer implements WebFluxConfigurer { <ide> <ide> private Consumer<PathMatchConfigurer> pathMatchConsumer; <ide> <del> private Consumer<List<HttpMessageReader<?>>> readersConsumer; <add> private Consumer<List<ServerHttpMessageReader<?>>> readersConsumer; <ide> <del> private Consumer<List<HttpMessageWriter<?>>> writersConsumer; <add> private Consumer<List<ServerHttpMessageWriter<?>>> writersConsumer; <ide> <ide> private Consumer<FormatterRegistry> formattersConsumer; <ide> <ide> public void configurePathMatching(PathMatchConfigurer configurer) { <ide> } <ide> <ide> @Override <del> public void extendMessageReaders(List<HttpMessageReader<?>> readers) { <add> public void extendMessageReaders(List<ServerHttpMessageReader<?>> readers) { <ide> if (this.readersConsumer != null) { <ide> this.readersConsumer.accept(readers); <ide> } <ide> } <ide> <ide> @Override <del> public void extendMessageWriters(List<HttpMessageWriter<?>> writers) { <add> public void extendMessageWriters(List<ServerHttpMessageWriter<?>> writers) { <ide> if (this.writersConsumer != null) { <ide> this.writersConsumer.accept(writers); <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/web/reactive/server/WebTestClient.java <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.MediaType; <ide> import org.springframework.http.client.reactive.ClientHttpRequest; <del>import org.springframework.http.codec.HttpMessageReader; <del>import org.springframework.http.codec.HttpMessageWriter; <add>import org.springframework.http.codec.ServerHttpMessageReader; <add>import org.springframework.http.codec.ServerHttpMessageWriter; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.validation.Validator; <ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolverBuilder; <ide> interface ControllerSpec extends MockServerSpec<ControllerSpec> { <ide> * Modify or extend the list of built-in message readers. <ide> * @see WebFluxConfigurer#configureMessageReaders <ide> */ <del> ControllerSpec messageReaders(Consumer<List<HttpMessageReader<?>>> readers); <add> ControllerSpec messageReaders(Consumer<List<ServerHttpMessageReader<?>>> readers); <ide> <ide> /** <ide> * Modify or extend the list of built-in message writers. <ide> * @see WebFluxConfigurer#configureMessageWriters <ide> */ <del> ControllerSpec messageWriters(Consumer<List<HttpMessageWriter<?>>> writers); <add> ControllerSpec messageWriters(Consumer<List<ServerHttpMessageWriter<?>>> writers); <ide> <ide> /** <ide> * Register formatters and converters to use for type conversion.
2
Javascript
Javascript
add spec for networking
e8037cb942bf7dab13cc7e18baee53db720411f8
<ide><path>Libraries/Network/NativeNetworkingAndroid.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>type Header = [string, string]; <add> <add>export interface Spec extends TurboModule { <add> +sendRequest: ( <add> method: string, <add> url: string, <add> requestId: number, <add> headers: Array<Header>, <add> data: Object, <add> responseType: Object, // TODO: Use stricter type. <add> useIncrementalUpdates: boolean, <add> timeout: number, <add> withCredentials: boolean, <add> ) => void; <add> +abortRequest: (requestId: number) => void; <add> +clearCookies: (callback: (result: boolean) => mixed) => void; <add> <add> // RCTEventEmitter <add> +addListener: (eventName: string) => void; <add> +removeListeners: (count: number) => void; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('Networking'); <ide><path>Libraries/Network/NativeNetworkingIOS.js <add>/** <add> * Copyright (c) Facebook, Inc. and its affiliates. <add> * <add> * This source code is licensed under the MIT license found in the <add> * LICENSE file in the root directory of this source tree. <add> * <add> * @flow <add> * @format <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>export interface Spec extends TurboModule { <add> +sendRequest: ( <add> query: {| <add> method: string, <add> url: string, <add> data: Object, <add> headers: Object, <add> responseType: Object, // TODO: Use stricter type. <add> incrementalUpdates: boolean, <add> timeout: number, <add> withCredentials: boolean, <add> |}, <add> callback: (requestId: number) => mixed, <add> ) => void; <add> +abortRequest: (requestId: number) => void; <add> +clearCookies: (callback: (result: boolean) => mixed) => void; <add> <add> // RCTEventEmitter <add> +addListener: (eventName: string) => void; <add> +removeListeners: (count: number) => void; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('Networking'); <ide><path>Libraries/Network/RCTNetworking.android.js <ide> // Do not require the native RCTNetworking module directly! Use this wrapper module instead. <ide> // It will add the necessary requestId, so that you don't have to generate it yourself. <ide> const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter'); <del>const RCTNetworkingNative = require('../BatchedBridge/NativeModules') <del> .Networking; <add>import NativeNetworkingAndroid from './NativeNetworkingAndroid'; <ide> const convertRequestBody = require('./convertRequestBody'); <ide> <ide> import type {RequestBody} from './convertRequestBody'; <ide> function generateRequestId(): number { <ide> */ <ide> class RCTNetworking extends NativeEventEmitter { <ide> constructor() { <del> super(RCTNetworkingNative); <add> super(NativeNetworkingAndroid); <ide> } <ide> <ide> sendRequest( <ide> class RCTNetworking extends NativeEventEmitter { <ide> responseType: 'text' | 'base64', <ide> incrementalUpdates: boolean, <ide> timeout: number, <del> callback: (requestId: number) => any, <add> callback: (requestId: number) => mixed, <ide> withCredentials: boolean, <ide> ) { <ide> const body = convertRequestBody(data); <ide> class RCTNetworking extends NativeEventEmitter { <ide> })); <ide> } <ide> const requestId = generateRequestId(); <del> RCTNetworkingNative.sendRequest( <add> NativeNetworkingAndroid.sendRequest( <ide> method, <ide> url, <ide> requestId, <ide> class RCTNetworking extends NativeEventEmitter { <ide> } <ide> <ide> abortRequest(requestId: number) { <del> RCTNetworkingNative.abortRequest(requestId); <add> NativeNetworkingAndroid.abortRequest(requestId); <ide> } <ide> <ide> clearCookies(callback: (result: boolean) => any) { <del> RCTNetworkingNative.clearCookies(callback); <add> NativeNetworkingAndroid.clearCookies(callback); <ide> } <ide> } <ide> <ide><path>Libraries/Network/RCTNetworking.ios.js <ide> 'use strict'; <ide> <ide> const NativeEventEmitter = require('../EventEmitter/NativeEventEmitter'); <del>const RCTNetworkingNative = require('../BatchedBridge/NativeModules') <del> .Networking; <add>import NativeNetworkingIOS from './NativeNetworkingIOS'; <ide> const convertRequestBody = require('./convertRequestBody'); <ide> <ide> import type {RequestBody} from './convertRequestBody'; <ide> import type {NativeResponseType} from './XMLHttpRequest'; <ide> <ide> class RCTNetworking extends NativeEventEmitter { <ide> constructor() { <del> super(RCTNetworkingNative); <add> super(NativeNetworkingIOS); <ide> } <ide> <ide> sendRequest( <ide> class RCTNetworking extends NativeEventEmitter { <ide> responseType: NativeResponseType, <ide> incrementalUpdates: boolean, <ide> timeout: number, <del> callback: (requestId: number) => any, <add> callback: (requestId: number) => mixed, <ide> withCredentials: boolean, <ide> ) { <ide> const body = convertRequestBody(data); <del> RCTNetworkingNative.sendRequest( <add> NativeNetworkingIOS.sendRequest( <ide> { <ide> method, <ide> url, <ide> class RCTNetworking extends NativeEventEmitter { <ide> } <ide> <ide> abortRequest(requestId: number) { <del> RCTNetworkingNative.abortRequest(requestId); <add> NativeNetworkingIOS.abortRequest(requestId); <ide> } <ide> <del> clearCookies(callback: (result: boolean) => any) { <del> RCTNetworkingNative.clearCookies(callback); <add> clearCookies(callback: (result: boolean) => mixed) { <add> NativeNetworkingIOS.clearCookies(callback); <ide> } <ide> } <ide>
4
Python
Python
enable xception to work on theano and cntk
24daab1c7b3ceebf04a19d3df3fdcdef11fe773b
<ide><path>keras/applications/xception.py <ide> and that the input preprocessing function <ide> is also different (same as Inception V3). <ide> <del>Also do note that this model is only available for the TensorFlow backend, <del>due to its reliance on `SeparableConvolution` layers. <del> <ide> # Reference <ide> <ide> - [Xception: Deep Learning with Depthwise Separable Convolutions](https://arxiv.org/abs/1610.02357) <ide> from ..layers import GlobalMaxPooling2D <ide> from ..engine import get_source_inputs <ide> from ..utils.data_utils import get_file <add>from ..utils import layer_utils <ide> from .. import backend as K <ide> from . import imagenet_utils <ide> from .imagenet_utils import decode_predictions <ide> def Xception(include_top=True, weights='imagenet', <ide> classes=1000): <ide> """Instantiates the Xception architecture. <ide> <del> Optionally loads weights pre-trained <del> on ImageNet. This model is available for TensorFlow only, <del> and can only be used with inputs following the TensorFlow <del> data format `(width, height, channels)`. <add> Optionally loads weights pre-trained on ImageNet. This model can <add> only be used with the data format `(width, height, channels)`. <ide> You should set `image_data_format='channels_last'` in your Keras config <ide> located at ~/.keras/keras.json. <ide> <ide> def Xception(include_top=True, weights='imagenet', <ide> raise ValueError('If using `weights` as imagenet with `include_top`' <ide> ' as true, `classes` should be 1000') <ide> <del> if K.backend() != 'tensorflow': <del> raise RuntimeError('The Xception model is only available with ' <del> 'the TensorFlow backend.') <ide> if K.image_data_format() != 'channels_last': <ide> warnings.warn('The Xception model is only available for the ' <ide> 'input data format "channels_last" ' <ide> def Xception(include_top=True, weights='imagenet', <ide> cache_subdir='models', <ide> file_hash='b0042744bf5b25fce3cb969f33bebb97') <ide> model.load_weights(weights_path) <add> if K.backend() == 'theano': <add> layer_utils.convert_all_kernels_in_model(model) <ide> elif weights is not None: <ide> model.load_weights(weights) <ide> <ide><path>tests/keras/applications/applications_test.py <ide> def test_vgg(): <ide> _test_app_pooling(app, last_dim) <ide> <ide> <del>@pytest.mark.skipif((K.backend() != 'tensorflow'), <del> reason='Requires TensorFlow backend') <ide> def test_xception(): <ide> app = applications.Xception <ide> last_dim = 2048
2
Javascript
Javascript
fix race condition in test-dgram-pingpong
fafb5848819d3a17ae54955467ed651685d98672
<ide><path>test/simple/test-dgram-pingpong.js <ide> function pingPongTest(port, host) { <ide> client.send(buf, 0, buf.length, port, 'localhost'); <ide> } else { <ide> sent_final_ping = true; <del> client.send(buf, 0, buf.length, port, 'localhost'); <del> process.nextTick(function() { <add> client.send(buf, 0, buf.length, port, 'localhost', function() { <ide> client.close(); <ide> }); <ide> }
1
PHP
PHP
remove uneeded method
6af16ddb23f5973513f3a5ddf230f99f5915a6cf
<ide><path>src/Mailer/Message.php <ide> public function __construct(?array $config = null) <ide> } <ide> } <ide> <del> /** <del> * Clone Renderer instance when email object is cloned. <del> * <del> * @return void <del> */ <del> public function __clone() <del> { <del> if ($this->renderer) { <del> $this->renderer = clone $this->renderer; <del> } <del> } <del> <ide> /** <ide> * Sets "from" address. <ide> *
1
Javascript
Javascript
add tests for outgoingmessage settimeout
730ec83a00626a361d5a91dc4ef14b6f4aeb89da
<ide><path>test/parallel/test-http-outgoing-settimeout.js <add>'use strict'; <add>const common = require('../common'); <add>const assert = require('assert'); <add> <add>const { OutgoingMessage } = require('http'); <add> <add>{ <add> // tests for settimeout method with socket <add> const expectedMsecs = 42; <add> const outgoingMessage = new OutgoingMessage(); <add> outgoingMessage.socket = { <add> setTimeout: common.mustCall((msecs) => { <add> assert.strictEqual(msecs, expectedMsecs); <add> }) <add> }; <add> outgoingMessage.setTimeout(expectedMsecs); <add>} <add> <add>{ <add> // tests for settimeout method without socket <add> const expectedMsecs = 23; <add> const outgoingMessage = new OutgoingMessage(); <add> outgoingMessage.setTimeout(expectedMsecs); <add> <add> outgoingMessage.emit('socket', { <add> setTimeout: common.mustCall((msecs) => { <add> assert.strictEqual(msecs, expectedMsecs); <add> }) <add> }); <add>}
1
Ruby
Ruby
restore some line breaks
3898010309d51d9c7a91fecb2f5bdbcb80e38180
<ide><path>Library/Homebrew/cmd/doctor.rb <ide> def check_for_linked_kegonly_brews <ide> EOS <ide> <ide> puts *warnings.keys.collect { |f| " #{f}" } <add> puts <ide> end <ide> end <ide> <ide> def check_missing_deps <ide> if s.length > 0 <ide> ohai "You should brew install these missing dependencies:" <ide> puts s <add> puts <ide> end <ide> end <ide> <ide> def check_git_status <ide> if system "/usr/bin/which -s git" and not `#{status_cmd}`.empty? <ide> ohai "You have uncommitted modifications to Homebrew core" <ide> puts "Unless you know what you are doing, you should: git reset --hard" <add> puts <ide> end <ide> end <ide>
1
Go
Go
fix silly little syntax mistake
6292354dc359a6d8f47b3199284147d557d2c697
<ide><path>api/client/utils.go <ide> func (cli *DockerCli) monitorTtySize(id string, isExec bool) error { <ide> sigchan := make(chan os.Signal, 1) <ide> gosignal.Notify(sigchan, signal.SIGWINCH) <ide> go func() { <del> for _ := range sigchan { <add> for _ = range sigchan { <ide> cli.resizeTty(id, isExec) <ide> } <ide> }()
1
Ruby
Ruby
remove unused requires
b8533ec9f0ef4afe1bba701effc68824f0c6cfed
<ide><path>activerecord/lib/active_record/attribute_methods.rb <del>require "active_support/core_ext/enumerable" <del>require "active_support/core_ext/string/filters" <ide> require "mutex_m" <del>require "concurrent/map" <ide> <ide> module ActiveRecord <ide> # = Active Record Attribute Methods <ide><path>activerecord/lib/active_record/core.rb <del>require "thread" <ide> require "active_support/core_ext/hash/indifferent_access" <del>require "active_support/core_ext/object/duplicable" <ide> require "active_support/core_ext/string/filters" <ide> <ide> module ActiveRecord
2
Ruby
Ruby
add branch support in rev_list
22e47ffa435fdacc12b7c5b65f64dfba36998201
<ide><path>Library/Homebrew/cmd/versions.rb <ide> def entry_name <ide> end <ide> end <ide> <del> def rev_list <add> def rev_list branch='HEAD' <ide> repository.cd do <del> `git rev-list --abbrev-commit HEAD -- #{entry_name}`.split <add> `git rev-list --abbrev-commit #{branch} -- #{entry_name}`.split <ide> end <ide> end <ide>
1
Text
Text
update changelog for 0.68.2
1839f68fa6282fefe32f0424f944642fd9ad63e2
<ide><path>CHANGELOG.md <ide> # Changelog <ide> <add>## v0.68.2 <add> <add>### Changed <add> <add>- Bump used version of react-native-codegen to 0.0.17 ([dfda480a98](https://github.com/facebook/react-native/commit/dfda480a9888d95c542cea40f25e8e783565c1db) by [@cortinico](https://github.com/cortinico)) <add>- Bump react-native-codegen to 0.0.17 ([a5ddc2e165](https://github.com/facebook/react-native/commit/a5ddc2e16523ea336ffbecf7acfd4820469a29e7) by [@cortinico](https://github.com/cortinico)) <add> <add>### Fixed <add> <add>#### Android specific <add> <add>- Working around Long paths limitation on Windows ([62ef6f5fa1](https://github.com/facebook/react-native/commit/62ef6f5fa1ecb918bde130a6024b65afcd34c7e3) by [@mganandraj](https://github.com/mganandraj)) <add> <ide> ## v0.68.1 <ide> <ide> ### Changed
1
Ruby
Ruby
fix root not being defined on travis
519467babcce795193877ab4f8eefb23200e664f
<ide><path>railties/lib/rails/test_unit/reporter.rb <ide> def format_rerun_snippet(result) <ide> end <ide> <ide> def app_root <del> @app_root ||= defined?(ENGINE_ROOT) ? ENGINE_ROOT : Rails.root <add> @app_root ||= <add> if defined?(ENGINE_ROOT) <add> ENGINE_ROOT <add> elsif Rails.respond_to?(:root) <add> Rails.root <add> end <ide> end <ide> <ide> def colored_output?
1
Go
Go
fix typo in godoc
881a30c707141b06af0cc7a076b62ff338615f2b
<ide><path>daemon/logger/context.go <ide> func (ctx *Context) ImageID() string { <ide> return ctx.ContainerImageID[:12] <ide> } <ide> <del>// ImageFullID is an alias of ContainerID. <add>// ImageFullID is an alias of ContainerImageID. <ide> func (ctx *Context) ImageFullID() string { <ide> return ctx.ContainerImageID <ide> }
1
Text
Text
fix punctuation of layout and rendering doc
d5962ff062be42d3ce0a4cb43ca4fed601399cc6
<ide><path>guides/source/layouts_and_rendering.md <ide> To include `http://example.com/main.js`: <ide> <ide> The [`stylesheet_link_tag`][] helper returns an HTML `<link>` tag for each source provided. <ide> <del>If you are using Rails with the "Asset Pipeline" enabled, this helper will generate a link to `/assets/stylesheets/`. This link is then processed by the Sprockets gem. A stylesheet file can be stored in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. <add>If you are using Rails with the "Asset Pipeline" enabled, this helper will generate a link to `/assets/stylesheets/`. This link is then processed by the Sprockets gem. A stylesheet file can be stored in one of three locations: `app/assets`, `lib/assets`, or `vendor/assets`. <ide> <del>You can specify a full path relative to the document root, or a URL. For example, to link to a stylesheet file that is inside a directory called `stylesheets` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this: <add>You can specify a full path relative to the document root, or a URL. For example, to link to a stylesheet file that is inside a directory called `stylesheets` inside of one of `app/assets`, `lib/assets`, or `vendor/assets`, you would do this: <ide> <ide> ```erb <ide> <%= stylesheet_link_tag "main" %>
1
Javascript
Javascript
fix minor typos in react-native-codegen errors
375ef14c04adafb80947e67f7d8756d21682fbe5
<ide><path>packages/react-native-codegen/src/parsers/flow/components/events.js <ide> function buildEventSchema( <ide> } <ide> <ide> if (argumentProps === null) { <del> throw new Error(`Unabled to determine event arguments for "${name}"`); <add> throw new Error(`Unable to determine event arguments for "${name}"`); <ide> } <ide> <ide> if (bubblingType === null) { <del> throw new Error(`Unabled to determine event arguments for "${name}"`); <add> throw new Error(`Unable to determine event arguments for "${name}"`); <ide> } <ide> } <ide>
1
Javascript
Javascript
fix race condition when using loadmodule
985e6fb001541931e4f7f3b80a280f7fd37ae228
<ide><path>lib/dependencies/LoaderPlugin.js <ide> class LoaderPlugin { <ide> }` <ide> ) <ide> ); <add> compilation.semaphore.release(); <ide> compilation.addModuleDependencies( <ide> module, <ide> [ <ide> class LoaderPlugin { <ide> "lm", <ide> false, <ide> err => { <del> if (err) return callback(err); <add> compilation.semaphore.acquire(() => { <add> if (err) return callback(err); <ide> <del> if (!dep.module) <del> return callback(new Error("Cannot load the module")); <add> if (!dep.module) <add> return callback(new Error("Cannot load the module")); <ide> <del> if (dep.module.error) return callback(dep.module.error); <del> if (!dep.module._source) <del> throw new Error( <del> "The module created for a LoaderDependency must have a property _source" <del> ); <del> let source, map; <del> const moduleSource = dep.module._source; <del> if (moduleSource.sourceAndMap) { <del> const sourceAndMap = moduleSource.sourceAndMap(); <del> map = sourceAndMap.map; <del> source = sourceAndMap.source; <del> } else { <del> map = moduleSource.map(); <del> source = moduleSource.source(); <del> } <del> if (dep.module.buildInfo.fileDependencies) { <del> for (const d of dep.module.buildInfo.fileDependencies) { <del> loaderContext.addDependency(d); <add> if (dep.module.error) return callback(dep.module.error); <add> if (!dep.module._source) <add> throw new Error( <add> "The module created for a LoaderDependency must have a property _source" <add> ); <add> let source, map; <add> const moduleSource = dep.module._source; <add> if (moduleSource.sourceAndMap) { <add> const sourceAndMap = moduleSource.sourceAndMap(); <add> map = sourceAndMap.map; <add> source = sourceAndMap.source; <add> } else { <add> map = moduleSource.map(); <add> source = moduleSource.source(); <ide> } <del> } <del> if (dep.module.buildInfo.contextDependencies) { <del> for (const d of dep.module.buildInfo.contextDependencies) { <del> loaderContext.addContextDependency(d); <add> if (dep.module.buildInfo.fileDependencies) { <add> for (const d of dep.module.buildInfo.fileDependencies) { <add> loaderContext.addDependency(d); <add> } <ide> } <del> } <del> return callback(null, source, map, dep.module); <add> if (dep.module.buildInfo.contextDependencies) { <add> for (const d of dep.module.buildInfo.contextDependencies) { <add> loaderContext.addContextDependency(d); <add> } <add> } <add> return callback(null, source, map, dep.module); <add> }); <ide> } <ide> ); <ide> }; <ide><path>lib/util/Semaphore.js <ide> class Semaphore { <ide> constructor(available) { <ide> this.available = available; <ide> this.waiters = []; <add> this._continue = this._continue.bind(this); <ide> } <ide> <ide> acquire(callback) { <ide> class Semaphore { <ide> } <ide> <ide> release() { <add> this.available++; <ide> if (this.waiters.length > 0) { <del> const callback = this.waiters.pop(); <del> process.nextTick(callback); <del> } else { <del> this.available++; <add> process.nextTick(this._continue); <add> } <add> } <add> <add> _continue() { <add> if (this.available > 0) { <add> if (this.waiters.length > 0) { <add> this.available--; <add> const callback = this.waiters.pop(); <add> callback(); <add> } <ide> } <ide> } <ide> } <ide><path>test/configCases/race-conditions/load-module/index.js <add>it("should not deadlock when using loadModule", () => { <add> const result = require("./loader!"); <add> result.should.match(/console.log\(42\)/); <add>}); <ide><path>test/configCases/race-conditions/load-module/loader.js <add>module.exports = function() { <add> const callback = this.async(); <add> let finished = false; <add> this.loadModule("./module.js", (err, result) => { <add> if (err) return callback(err); <add> if (finished) return; <add> finished = true; <add> callback(null, `module.exports = ${JSON.stringify(result)};`); <add> }); <add> setTimeout(() => { <add> if (finished) return; <add> finished = true; <add> callback(new Error("loadModule is hanging")); <add> }, 2000); <add>}; <ide><path>test/configCases/race-conditions/load-module/module.js <add>console.log(42); <ide><path>test/configCases/race-conditions/load-module/webpack.config.js <add>module.exports = { <add> parallelism: 1 <add>};
6
Javascript
Javascript
replace fixturesdir with common.fixtures
6b5433dcd2f518643d67a16a5f89ad4e845e4902
<ide><path>test/parallel/test-http2-respond-file-304.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <add>const fixtures = require('../common/fixtures'); <ide> const http2 = require('http2'); <ide> const assert = require('assert'); <del>const path = require('path'); <ide> <ide> const { <ide> HTTP2_HEADER_CONTENT_TYPE, <ide> HTTP2_HEADER_STATUS <ide> } = http2.constants; <ide> <del>const fname = path.resolve(common.fixturesDir, 'elipses.txt'); <add>const fname = fixtures.path('elipses.txt'); <ide> <ide> const server = http2.createServer(); <ide> server.on('stream', (stream) => {
1
Text
Text
replace the word "dashes" with "hyphens"
7f4531aed089faad044477c390b54ce4b9031a1f
<ide><path>curriculum/challenges/english/01-responsive-web-design/basic-css/create-a-custom-css-variable.english.md <ide> forumTopicId: 301086 <ide> <ide> ## Description <ide> <section id='description'> <del>To create a CSS variable, you just need to give it a name with two dashes in front of it and assign it a value like this: <add>To create a CSS variable, you just need to give it a name with two hyphens in front of it and assign it a value like this: <ide> <ide> ```css <ide> --penguin-skin: gray;
1
Ruby
Ruby
use delegated logger
04aed03c896f661143bce1e4b879cff480963fe6
<ide><path>lib/action_cable/connection/subscriptions.rb <ide> def add(data) <ide> if subscription_klass <ide> subscriptions[id_key] = subscription_klass.new(connection, id_key, id_options) <ide> else <del> connection.logger.error "Subscription class not found (#{data.inspect})" <add> logger.error "Subscription class not found (#{data.inspect})" <ide> end <ide> end <ide> <ide> def remove(data) <del> connection.logger.info "Unsubscribing from channel: #{data['identifier']}" <add> logger.info "Unsubscribing from channel: #{data['identifier']}" <ide> subscriptions[data['identifier']].perform_disconnection <ide> subscriptions.delete(data['identifier']) <ide> end <ide> def cleanup <ide> <ide> private <ide> attr_reader :connection, :subscriptions <add> delegate :logger, to: :connection <ide> end <ide> end <ide> end <ide>\ No newline at end of file
1
Ruby
Ruby
make ci test with and without im
056f05adcd030634dc6a6e3054f25d80b7fd4445
<ide><path>ci/ci_build.rb <ide> def rake(*tasks) <ide> rm_f "#{root_dir}/activerecord/debug.log" <ide> cd "#{root_dir}/activerecord" do <ide> puts <del> puts "[CruiseControl] Building Active Record with MySQL" <add> puts "[CruiseControl] Building Active Record with MySQL IM enabled" <ide> puts <add> ENV['IM'] = true <ide> build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'mysql:test' <ide> build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test' <ide> end <ide> <ide> cd "#{root_dir}/activerecord" do <ide> puts <del> puts "[CruiseControl] Building Active Record with MySQL2" <add> puts "[CruiseControl] Building Active Record with MySQL IM disabled" <ide> puts <add> ENV['IM'] = false <add> build_results[:activerecord_mysql] = rake 'mysql:rebuild_databases', 'mysql:test' <add> build_results[:activerecord_mysql_isolated] = rake 'mysql:rebuild_databases', 'mysql:isolated_test' <add>end <add> <add>cd "#{root_dir}/activerecord" do <add> puts <add> puts "[CruiseControl] Building Active Record with MySQL2 IM enabled" <add> puts <add> ENV['IM'] = true <add> build_results[:activerecord_mysql2] = rake 'mysql:rebuild_databases', 'mysql2:test' <add> build_results[:activerecord_mysql2_isolated] = rake 'mysql:rebuild_databases', 'mysql2:isolated_test' <add>end <add> <add>cd "#{root_dir}/activerecord" do <add> puts <add> puts "[CruiseControl] Building Active Record with MySQL2 IM disabled" <add> puts <add> ENV['IM'] = false <ide> build_results[:activerecord_mysql2] = rake 'mysql:rebuild_databases', 'mysql2:test' <ide> build_results[:activerecord_mysql2_isolated] = rake 'mysql:rebuild_databases', 'mysql2:isolated_test' <ide> end <ide> <ide> cd "#{root_dir}/activerecord" do <ide> puts <del> puts "[CruiseControl] Building Active Record with PostgreSQL" <add> puts "[CruiseControl] Building Active Record with PostgreSQL IM enabled" <ide> puts <add> ENV['IM'] = true <ide> build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'postgresql:test' <ide> build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test' <ide> end <ide> <ide> cd "#{root_dir}/activerecord" do <ide> puts <del> puts "[CruiseControl] Building Active Record with SQLite 3" <add> puts "[CruiseControl] Building Active Record with PostgreSQL IM disabled" <add> puts <add> ENV['IM'] = false <add> build_results[:activerecord_postgresql8] = rake 'postgresql:rebuild_databases', 'postgresql:test' <add> build_results[:activerecord_postgresql8_isolated] = rake 'postgresql:rebuild_databases', 'postgresql:isolated_test' <add>end <add> <add>cd "#{root_dir}/activerecord" do <add> puts <add> puts "[CruiseControl] Building Active Record with SQLite 3 IM enabled" <add> puts <add> ENV['IM'] = true <add> build_results[:activerecord_sqlite3] = rake 'sqlite3:test' <add> build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test' <add>end <add> <add>cd "#{root_dir}/activerecord" do <add> puts <add> puts "[CruiseControl] Building Active Record with SQLite 3 IM disabled" <ide> puts <add> ENV['IM'] = false <ide> build_results[:activerecord_sqlite3] = rake 'sqlite3:test' <ide> build_results[:activerecord_sqlite3_isolated] = rake 'sqlite3:isolated_test' <ide> end
1
Javascript
Javascript
pass all extra, owned properties as params
acb545ec3ebf099db68561033645941c900973b5
<ide><path>src/ngResource/resource.js <ide> angular.module('ngResource', ['ng']). <ide> encodedVal, <ide> protocolAndDomain = ''; <ide> <del> var urlParams = self.urlParams = {}; <add> var urlParams = self.urlParams = Object.create(null); <ide> forEach(url.split(/\W/), function(param) { <ide> if (param === 'hasOwnProperty') { <ide> throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name."); <ide><path>test/ngResource/resourceSpec.js <ide> describe("basic usage", function() { <ide> }); <ide> }); <ide> <add>describe('extra params', function() { <add> var $http; <add> var $httpBackend; <add> var $resource; <add> <add> beforeEach(module('ngResource')); <add> <add> beforeEach(module(function($provide) { <add> $provide.decorator('$http', function($delegate) { <add> return jasmine.createSpy('$http').and.callFake($delegate); <add> }); <add> })); <add> <add> beforeEach(inject(function(_$http_, _$httpBackend_, _$resource_) { <add> $http = _$http_; <add> $httpBackend = _$httpBackend_; <add> $resource = _$resource_; <add> })); <add> <add> afterEach(function() { <add> $httpBackend.verifyNoOutstandingExpectation(); <add> }); <add> <add> <add> it('should pass extra params to `$http` as `config.params`', function() { <add> $httpBackend.expectGET('/bar?baz=qux').respond('{}'); <add> <add> var R = $resource('/:foo'); <add> R.get({foo: 'bar', baz: 'qux'}); <add> <add> expect($http).toHaveBeenCalledWith(jasmine.objectContaining({params: {baz: 'qux'}})); <add> }); <add> <add> it('should pass extra params even if `Object.prototype` has properties with the same name', <add> function() { <add> $httpBackend.expectGET('/foo?toString=bar').respond('{}'); <add> <add> var R = $resource('/foo'); <add> R.get({toString: 'bar'}); <add> } <add> ); <add>}); <add> <ide> describe('errors', function() { <ide> var $httpBackend, $resource, $q; <ide>
2
PHP
PHP
add additional test
f63d955f73d6717bfa266d41eb277f00b6d53261
<ide><path>lib/Cake/Test/Case/View/Helper/PaginatorHelperTest.php <ide> public function testPagingLinks() { <ide> ); <ide> $this->assertTags($result, $expected); <ide> <add> $result = $this->Paginator->prev('<i class="fa fa-angle-left"></i>', array('escape' => false), null, array('escape' => true)); <add> $expected = array( <add> 'span' => array('class' => 'prev'), <add> 'a' => array('href' => '/', 'rel' => 'prev'), <add> '&lt;i class=&quot;fa fa-angle-left&quot;&gt;&lt;/i&gt;', <add> '/a', <add> '/span' <add> ); <add> $this->assertTags($result, $expected); <add> <ide> $result = $this->Paginator->prev('<< Previous', null, '<strong>Disabled</strong>'); <ide> $expected = array( <ide> 'span' => array('class' => 'prev'), <ide><path>lib/Cake/View/Helper/PaginatorHelper.php <ide> protected function _pagingLink($which, $title = null, $options = array(), $disab <ide> if (!empty($disabledTitle) && $disabledTitle !== true) { <ide> $title = $disabledTitle; <ide> } <del> <del> $options = (array)$disabledOptions + array_intersect_key($options, array_keys($_defaults)) + $_defaults; <add> $options = (array)$disabledOptions + array_intersect_key($options, $_defaults) + $_defaults; <ide> } elseif (!$this->{$check}($options['model'])) { <ide> return ''; <ide> }
2
Javascript
Javascript
update isnumeric tests for pre-es2015 safety
2868db0d41b8d1d7b141c0494c262120dd9864b7
<ide><path>test/unit/core.js <ide> QUnit.test( "isFunction", function( assert ) { <ide> } ); <ide> <ide> QUnit.test( "isNumeric", function( assert ) { <del> assert.expect( 41 ); <add> assert.expect( 43 ); <ide> <ide> var t = jQuery.isNumeric, <ide> ToString = function( value ) { <ide> QUnit.test( "isNumeric", function( assert ) { <ide> assert.ok( t( -16 ), "Negative integer number" ); <ide> assert.ok( t( 0 ), "Zero integer number" ); <ide> assert.ok( t( 32 ), "Positive integer number" ); <add> assert.ok( t( "-1.6" ), "Negative floating point string" ); <add> assert.ok( t( "4.536" ), "Positive floating point string" ); <add> assert.ok( t( -2.6 ), "Negative floating point number" ); <add> assert.ok( t( 3.1415 ), "Positive floating point number" ); <add> assert.ok( t( 1.5999999999999999 ), "Very precise floating point number" ); <add> assert.ok( t( 8e5 ), "Exponential notation" ); <add> assert.ok( t( "123e-2" ), "Exponential notation string" ); <add> assert.ok( t( "040" ), "Legacy octal integer literal string" ); <add> assert.ok( t( "0xFF" ), "Hexadecimal integer literal string (0x...)" ); <add> assert.ok( t( "0Xba" ), "Hexadecimal integer literal string (0X...)" ); <add> assert.ok( t( 0xFFF ), "Hexadecimal integer literal" ); <ide> <ide> if ( +"0b1" === 1 ) { <del> assert.ok( t( "0b111110" ), "Binary integer literal string" ); // jshint ignore:line <del> } else { <del> assert.ok( true, "Browser does not support binary integer literal" ); <del> } <del> <del> assert.ok( t( "040" ), "Octal integer literal string" ); <del> <del> assert.ok( t( "0xFF" ), "Hexadecimal integer literal string" ); <del> <del> if ( +"0b1" === 1 ) { <del> assert.ok( t( 0b111110 ), "Binary integer literal" ); // jshint ignore:line <add> assert.ok( t( "0b111110" ), "Binary integer literal string (0b...)" ); <add> assert.ok( t( "0B111110" ), "Binary integer literal string (0B...)" ); <ide> } else { <del> assert.ok( true, "Browser does not support binary integer literal" ); <add> assert.ok( true, "Browser does not support binary integer literal (0b...)" ); <add> assert.ok( true, "Browser does not support binary integer literal (0B...)" ); <ide> } <ide> <ide> if ( +"0o1" === 1 ) { <del> assert.ok( t( 0o76 ), "Octal integer literal" ); // jshint ignore:line <add> assert.ok( t( "0o76" ), "Octal integer literal string (0o...)" ); <add> assert.ok( t( "0O76" ), "Octal integer literal string (0O...)" ); <ide> } else { <del> assert.ok( true, "Browser does not support octal integer literal" ); <add> assert.ok( true, "Browser does not support octal integer literal (0o...)" ); <add> assert.ok( true, "Browser does not support octal integer literal (0O...)" ); <ide> } <ide> <del> assert.ok( t( 0xFFF ), "Hexadecimal integer literal" ); <del> assert.ok( t( "-1.6" ), "Negative floating point string" ); <del> assert.ok( t( "4.536" ), "Positive floating point string" ); <del> assert.ok( t( -2.6 ), "Negative floating point number" ); <del> assert.ok( t( 3.1415 ), "Positive floating point number" ); <del> assert.ok( t( 1.5999999999999999 ), "Very precise floating point number" ); <del> assert.ok( t( 8e5 ), "Exponential notation" ); <del> assert.ok( t( "123e-2" ), "Exponential notation string" ); <del> <ide> assert.equal( t( new ToString( "42" ) ), false, "Only limited to strings and numbers" ); <ide> assert.equal( t( "" ), false, "Empty string" ); <ide> assert.equal( t( " " ), false, "Whitespace characters string" );
1
Javascript
Javascript
improve coverage of lib/_http_outgoing.js
5a1140222379f7b75203648e73b5daf7d3d3ef76
<ide><path>test/parallel/test-http-information-headers.js <ide> 'use strict'; <del>require('../common'); <add>const common = require('../common'); <ide> const assert = require('assert'); <ide> const http = require('http'); <ide> const Countdown = require('../common/countdown'); <ide> const server = http.createServer((req, res) => { <ide> // to call res.writeHead instead <ide> res._writeRaw('HTTP/1.1 102 Processing\r\n'); <ide> res._writeRaw('Foo: Bar\r\n'); <del> res._writeRaw('\r\n'); <add> res._writeRaw('\r\n', common.mustCall()); <ide> console.error('Server sending full response...'); <ide> res.writeHead(200, { <ide> 'Content-Type': 'text/plain', <ide><path>test/parallel/test-http-mutable-headers.js <ide> const s = http.createServer(common.mustCall((req, res) => { <ide> const exoticObj = Object.create(null); <ide> assert.deepStrictEqual(headers, exoticObj); <ide> assert.deepStrictEqual(res.getHeaderNames(), []); <add> assert.deepStrictEqual(res.getRawHeaderNames(), []); <ide> assert.deepStrictEqual(res.hasHeader('Connection'), false); <ide> assert.deepStrictEqual(res.getHeader('Connection'), undefined); <ide>
2
PHP
PHP
add message for "not regex" validation rule
293fae6bd8285d076cedf2b8147a20e4090aa5bc
<ide><path>resources/lang/en/validation.php <ide> 'array' => 'The :attribute must have at least :min items.', <ide> ], <ide> 'not_in' => 'The selected :attribute is invalid.', <add> 'not_regex' => 'The :attribute format is invalid.', <ide> 'numeric' => 'The :attribute must be a number.', <ide> 'present' => 'The :attribute field must be present.', <ide> 'regex' => 'The :attribute format is invalid.',
1
Text
Text
add thekemkid to collaborators
4daab7f8edf4176dc9be2e7051fc11588fd971c2
<ide><path>README.md <ide> information about the governance of the Node.js project, see <ide> * [tellnes](https://github.com/tellnes) - **Christian Tellnes** &lt;[email protected]&gt; <ide> * [thealphanerd](https://github.com/thealphanerd) - **Myles Borins** &lt;[email protected]&gt; <ide> * [thefourtheye](https://github.com/thefourtheye) - **Sakthipriyan Vairamani** &lt;[email protected]&gt; <add>* [thekemkid](https://github.com/thekemkid) - **Glen Keane** &lt;[email protected]&gt; <ide> * [thlorenz](https://github.com/thlorenz) - **Thorsten Lorenz** &lt;[email protected]&gt; <ide> * [tunniclm](https://github.com/tunniclm) - **Mike Tunnicliffe** &lt;[email protected]&gt; <ide> * [vkurchatkin](https://github.com/vkurchatkin) - **Vladimir Kurchatkin** &lt;[email protected]&gt;
1
Java
Java
raise exception on missing request parameters
3c09b07652ed3c7a2e4cee1295a450aee387f99b
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMapping.java <ide> import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.springframework.http.MediaType; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.util.MultiValueMap; <ide> import org.springframework.util.StringUtils; <ide> import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.HttpMediaTypeNotSupportedException; <ide> import org.springframework.web.HttpRequestMethodNotSupportedException; <add>import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> import org.springframework.web.method.HandlerMethod; <ide> import org.springframework.web.servlet.HandlerMapping; <ide> import org.springframework.web.servlet.handler.AbstractHandlerMethodMapping; <add>import org.springframework.web.servlet.mvc.condition.NameValueExpression; <add>import org.springframework.web.servlet.mvc.condition.ParamsRequestCondition; <ide> import org.springframework.web.util.WebUtils; <ide> <ide> /** <ide> else if (patternAndMethodMatches.isEmpty() && !allowedMethods.isEmpty()) { <ide> <ide> Set<MediaType> consumableMediaTypes; <ide> Set<MediaType> producibleMediaTypes; <add> Set<String> paramConditions; <ide> <ide> if (patternAndMethodMatches.isEmpty()) { <ide> consumableMediaTypes = getConsumableMediaTypes(request, patternMatches); <ide> producibleMediaTypes = getProdicubleMediaTypes(request, patternMatches); <add> paramConditions = getRequestParams(request, patternMatches); <ide> } <ide> else { <ide> consumableMediaTypes = getConsumableMediaTypes(request, patternAndMethodMatches); <ide> producibleMediaTypes = getProdicubleMediaTypes(request, patternAndMethodMatches); <add> paramConditions = getRequestParams(request, patternAndMethodMatches); <ide> } <ide> <ide> if (!consumableMediaTypes.isEmpty()) { <ide> else if (patternAndMethodMatches.isEmpty() && !allowedMethods.isEmpty()) { <ide> else if (!producibleMediaTypes.isEmpty()) { <ide> throw new HttpMediaTypeNotAcceptableException(new ArrayList<MediaType>(producibleMediaTypes)); <ide> } <add> else if (!CollectionUtils.isEmpty(paramConditions)) { <add> String[] params = paramConditions.toArray(new String[paramConditions.size()]); <add> throw new UnsatisfiedServletRequestParameterException(params, request.getParameterMap()); <add> } <ide> else { <ide> return null; <ide> } <ide> private Set<MediaType> getProdicubleMediaTypes(HttpServletRequest request, Set<R <ide> return result; <ide> } <ide> <add> private Set<String> getRequestParams(HttpServletRequest request, Set<RequestMappingInfo> partialMatches) { <add> for (RequestMappingInfo partialMatch : partialMatches) { <add> ParamsRequestCondition condition = partialMatch.getParamsCondition(); <add> if (!CollectionUtils.isEmpty(condition.getExpressions()) && (condition.getMatchingCondition(request) == null)) { <add> Set<String> expressions = new HashSet<String>(); <add> for (NameValueExpression expr : condition.getExpressions()) { <add> expressions.add(expr.toString()); <add> } <add> return expressions; <add> } <add> } <add> return null; <add> } <add> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoHandlerMappingTests.java <ide> import org.springframework.web.HttpMediaTypeNotAcceptableException; <ide> import org.springframework.web.HttpMediaTypeNotSupportedException; <ide> import org.springframework.web.HttpRequestMethodNotSupportedException; <add>import org.springframework.web.bind.UnsatisfiedServletRequestParameterException; <ide> import org.springframework.web.bind.annotation.RequestBody; <ide> import org.springframework.web.bind.annotation.RequestMapping; <ide> import org.springframework.web.bind.annotation.RequestMethod; <ide> private void testMediaTypeNotAccepted(String url) throws Exception { <ide> } <ide> } <ide> <add> @Test <add> public void testUnsatisfiedServletRequestParameterException() throws Exception { <add> try { <add> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/params"); <add> this.handlerMapping.getHandler(request); <add> fail("UnsatisfiedServletRequestParameterException expected"); <add> } <add> catch (UnsatisfiedServletRequestParameterException ex) { <add> assertArrayEquals("Invalid request parameter conditions", <add> new String[] { "foo=bar" }, ex.getParamConditions()); <add> } <add> } <add> <ide> @Test <ide> public void uriTemplateVariables() { <ide> PatternsRequestCondition patterns = new PatternsRequestCondition("/{path1}/{path2}"); <ide> public String produces() { <ide> return ""; <ide> } <ide> <add> @RequestMapping(value = "/params", params="foo=bar") <add> public String param() { <add> return ""; <add> } <add> <ide> @RequestMapping(value = "/content", produces="application/xml") <ide> public String xmlContent() { <ide> return "";
2
Javascript
Javascript
expose underlying buffer object always
c21458a15dcbff405b18a680e9ed18863567736b
<ide><path>lib/buffer.js <ide> Object.defineProperty(Buffer.prototype, 'parent', { <ide> get: function() { <ide> if (!(this instanceof Buffer)) <ide> return undefined; <del> if (this.byteLength === 0 || <del> this.byteLength === this.buffer.byteLength) { <del> return undefined; <del> } <ide> return this.buffer; <ide> } <ide> }); <ide><path>test/parallel/test-buffer-alloc.js <ide> if (common.hasCrypto) { <ide> <ide> const ps = Buffer.poolSize; <ide> Buffer.poolSize = 0; <del>assert.strictEqual(Buffer.allocUnsafe(1).parent, undefined); <add>assert(Buffer.allocUnsafe(1).parent instanceof ArrayBuffer); <ide> Buffer.poolSize = ps; <ide> <ide> // Test Buffer.copy() segfault <ide><path>test/parallel/test-buffer-arraybuffer.js <ide> const buf = Buffer.from(ab); <ide> <ide> <ide> assert.ok(buf instanceof Buffer); <del>// For backwards compatibility of old .parent property test that if buf is not <del>// a slice then .parent should be undefined. <del>assert.equal(buf.parent, undefined); <add>assert.equal(buf.parent, buf.buffer); <ide> assert.equal(buf.buffer, ab); <ide> assert.equal(buf.length, ab.byteLength); <ide> <ide><path>test/parallel/test-buffer-parent-property.js <add>'use strict'; <add> <add>/* <add> * Fix for https://github.com/nodejs/node/issues/8266 <add> * <add> * Zero length Buffer objects should expose the `buffer` property of the <add> * TypedArrays, via the `parent` property. <add> */ <add>require('../common'); <add>const assert = require('assert'); <add> <add>// If the length of the buffer object is zero <add>assert((new Buffer(0)).parent instanceof ArrayBuffer); <add> <add>// If the length of the buffer object is equal to the underlying ArrayBuffer <add>assert((new Buffer(Buffer.poolSize)).parent instanceof ArrayBuffer); <add> <add>// Same as the previous test, but with user created buffer <add>const arrayBuffer = new ArrayBuffer(0); <add>assert.strictEqual(new Buffer(arrayBuffer).parent, arrayBuffer); <add>assert.strictEqual(new Buffer(arrayBuffer).buffer, arrayBuffer); <add>assert.strictEqual(Buffer.from(arrayBuffer).parent, arrayBuffer); <add>assert.strictEqual(Buffer.from(arrayBuffer).buffer, arrayBuffer);
4
Python
Python
fix message error to the keras standards
67d3fb98bfa82c20e816a4d156e677d4f27553bc
<ide><path>keras/layers/convolutional.py <ide> def compute_output_shape(self, input_shape): <ide> <ide> def call(self, inputs): <ide> if tf.not_equal(tf.size(inputs), 0) and sum(self.cropping) >= inputs.shape[1]: <del> raise ValueError( <del> 'cropping parameter of Cropping layer is too high,' + <del> 'the result of crop' + str(inputs.shape) + ' with cropping ' + <del> str(self.cropping) + ' is an empty tensor' <del> ) <add> raise ValueError('cropping parameter of Cropping layer must be ' <add> 'greater than the input shape. Recieved: inputs.shape=' <add> f'{inputs.shape}, and cropping={self.cropping}') <ide> if self.cropping[1] == 0: <ide> return inputs[:, self.cropping[0]:, :] <ide> else:
1
PHP
PHP
add error() and haserror()
fd950cc628d69ee45d5fdb54fee16d5e18487a54
<ide><path>src/View/Form/ArrayContext.php <ide> * Important keys: <ide> * <ide> * - `defaults` The default values for fields. These values <del> * will be used when there is no request data set. <add> * will be used when there is no request data set. Data should be nested following <add> * the dot separated paths you access your fields with. <ide> * - `required` A nested array of fields, relationships and boolean <ide> * flags to indicate a field is required. <del> * - `schema` An array of data that emulate the structures that <add> * - `schema` An array of data that emulate the column structures that <ide> * Cake\Database\Schema\Table uses. This array allows you to control <ide> * the inferred type for fields and allows auto generation of attributes <ide> * like maxlength, step and other HTML attributes. <add> * - `errors` An array of validation errors. Errors should be nested following <add> * the dot separated paths you access your fields with. <ide> */ <ide> class ArrayContext { <ide> <ide> public function __construct(Request $request, array $context) { <ide> 'schema' => [], <ide> 'required' => [], <ide> 'defaults' => [], <add> 'errors' => [], <ide> ]; <ide> $this->_context = $context; <ide> } <ide> public function attributes($field) { <ide> return array_intersect_key($schema, $whitelist); <ide> } <ide> <add>/** <add> * Check whether or not a field has an error attached to it <add> * <add> * @param string $field A dot separated path to check errors on. <add> * @return boolean Returns true if the errors for the field are not empty. <add> */ <add> public function hasError($field) { <add> if (empty($this->_context['errors'])) { <add> return false; <add> } <add> return (bool)Hash::check($this->_context['errors'], $field); <add> } <add> <add>/** <add> * Get the errors for a given field <add> * <add> * @param string $field A dot separated path to check errors on. <add> * @return mixed Either a string or an array of errors. Null <add> * will be returned when the field path is undefined. <add> */ <add> public function error($field) { <add> if (empty($this->_context['errors'])) { <add> return null; <add> } <add> return Hash::get($this->_context['errors'], $field); <add> } <add> <ide> } <ide><path>tests/TestCase/View/Form/ArrayContextTest.php <ide> public function testAttributes() { <ide> $this->assertEquals(['precision' => 2, 'length' => 5], $context->attributes('Comments.floaty')); <ide> } <ide> <add>/** <add> * Test fetching errors. <add> * <add> * @return void <add> */ <add> public function testError() { <add> $context = new ArrayContext($this->request, [ <add> 'errors' => [ <add> 'Comments' => [ <add> 'comment' => ['Comment is required'], <add> 'empty' => [], <add> 'user_id' => 'A valid userid is required', <add> ] <add> ] <add> ]); <add> $this->assertEquals(['Comment is required'], $context->error('Comments.comment')); <add> $this->assertEquals('A valid userid is required', $context->error('Comments.user_id')); <add> $this->assertEquals([], $context->error('Comments.empty')); <add> $this->assertNull($context->error('Comments.not_there')); <add> } <add> <add>/** <add> * Test checking errors. <add> * <add> * @return void <add> */ <add> public function testHasError() { <add> $context = new ArrayContext($this->request, [ <add> 'errors' => [ <add> 'Comments' => [ <add> 'comment' => ['Comment is required'], <add> 'empty' => [], <add> 'user_id' => 'A valid userid is required', <add> ] <add> ] <add> ]); <add> $this->assertFalse($context->hasError('Comments.not_there')); <add> $this->assertFalse($context->hasError('Comments.empty')); <add> $this->assertTrue($context->hasError('Comments.user_id')); <add> $this->assertTrue($context->hasError('Comments.comment')); <add> } <add> <ide> }
2
Go
Go
increase timeout to reduce flakiness
87b89475803595970b512377f3a644ead7493b39
<ide><path>integration/network/dns_test.go <ide> func TestDaemonDNSFallback(t *testing.T) { <ide> cid := container.Run(ctx, t, c, container.WithNetworkMode("test"), container.WithCmd("nslookup", "docker.com")) <ide> defer c.ContainerRemove(ctx, cid, types.ContainerRemoveOptions{Force: true}) <ide> <del> poll.WaitOn(t, container.IsSuccessful(ctx, c, cid), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(2*time.Second)) <add> poll.WaitOn(t, container.IsSuccessful(ctx, c, cid), poll.WithDelay(100*time.Millisecond), poll.WithTimeout(4*time.Second)) <ide> }
1
Python
Python
add timer to evaluate
a44c4c3a5b91dcf85681df57865942a888485a65
<ide><path>spacy/cli/evaluate.py <ide> model=("Model name or path", "positional", None, str), <ide> data_path=("Location of JSON-formatted evaluation data", "positional", None, str), <ide> gold_preproc=("Use gold preprocessing", "flag", "G", bool), <add> gpu_id=("Use GPU", "option", "g", int), <ide> ) <del>def evaluate(cmd, model, data_path, gold_preproc=False): <add>def evaluate(cmd, model, data_path, gpu_id=-1, gold_preproc=False): <ide> """ <ide> Train a model. Expects data in spaCy's JSON format. <ide> """ <add> util.use_gpu(gpu_id) <ide> util.set_env_log(True) <ide> data_path = util.ensure_path(data_path) <ide> if not data_path.exists(): <ide> prints(data_path, title="Evaluation data not found", exits=1) <ide> corpus = GoldCorpus(data_path, data_path) <ide> nlp = util.load_model(model) <del> scorer = nlp.evaluate(list(corpus.dev_docs(nlp, gold_preproc=gold_preproc))) <add> dev_docs = list(corpus.dev_docs(nlp, gold_preproc=gold_preproc)) <add> begin = timer() <add> scorer = nlp.evaluate(dev_docs, verbose=False) <add> end = timer() <add> nwords = sum(len(doc_gold[0]) for doc_gold in dev_docs) <add> print('Time', end-begin, 'words', nwords, 'w.p.s', nwords/(end-begin)) <ide> print_results(scorer) <ide> <ide>
1
Python
Python
use conn_name_attr for sqlitehook connection
4a0fdb6308400ddda38b0904cfe14b5872e5c0eb
<ide><path>airflow/providers/sqlite/hooks/sqlite.py <ide> class SqliteHook(DbApiHook): <ide> <ide> conn_name_attr = 'sqlite_conn_id' <ide> default_conn_name = 'sqlite_default' <del> supports_autocommit = False <ide> <ide> def get_conn(self): <ide> """ <ide> Returns a sqlite connection object <ide> """ <del> conn = self.get_connection(self.sqlite_conn_id) # pylint: disable=no-member <del> conn = sqlite3.connect(conn.host) <add> conn_id = getattr(self, self.conn_name_attr) <add> airflow_conn = self.get_connection(conn_id) <add> conn = sqlite3.connect(airflow_conn.host) <ide> return conn <ide><path>tests/providers/sqlite/hooks/test_sqlite.py <ide> def setUp(self): <ide> self.connection = Connection(host='host') <ide> <ide> class UnitTestSqliteHook(SqliteHook): <del> conn_name_attr = 'sqlite_conn_id' <add> conn_name_attr = 'test_conn_id' <ide> <ide> self.db_hook = UnitTestSqliteHook() <ide> self.db_hook.get_connection = mock.Mock() <ide> def test_get_conn(self, mock_connect): <ide> self.db_hook.get_conn() <ide> mock_connect.assert_called_once_with('host') <ide> <add> @patch('airflow.providers.sqlite.hooks.sqlite.sqlite3.connect') <add> def test_get_conn_non_default_id(self, mock_connect): <add> self.db_hook.test_conn_id = 'non_default' # pylint: disable=attribute-defined-outside-init <add> self.db_hook.get_conn() <add> mock_connect.assert_called_once_with('host') <add> self.db_hook.get_connection.assert_called_once_with('non_default') <add> <ide> <ide> class TestSqliteHook(unittest.TestCase): <ide>
2
Text
Text
remove use of "random port" re dgram send
cdfe47b323b8f8b495c23f65b6570021eea16239
<ide><path>doc/api/dgram.md <ide> the error is emitted as an `'error'` event on the `socket` object. <ide> Offset and length are optional but both *must* be set if either are used. <ide> They are supported only when the first argument is a `Buffer` or `Uint8Array`. <ide> <del>Example of sending a UDP packet to a random port on `localhost`; <add>Example of sending a UDP packet to a port on `localhost`; <ide> <ide> ```js <ide> const dgram = require('dgram'); <ide> client.send(message, 41234, 'localhost', (err) => { <ide> }); <ide> ``` <ide> <del>Example of sending a UDP packet composed of multiple buffers to a random port <del>on `127.0.0.1`; <add>Example of sending a UDP packet composed of multiple buffers to a port on <add>`127.0.0.1`; <ide> <ide> ```js <ide> const dgram = require('dgram');
1
Javascript
Javascript
add isintersectionsphere to sphere
dcd25863e4d083c1945fab6380bdf06543d7397e
<ide><path>src/math/Sphere.js <ide> THREE.Sphere.prototype = { <ide> <ide> }, <ide> <add> isIntersectionSphere: function(sphere) { <add> <add> return ( sphere.center.distanceToSquared( this.center ) <= ( this.radius * this.radius + sphere.radius * sphere.radius) ); <add> <add> }, <add> <ide> clampPoint: function ( point, optionalTarget ) { <ide> <ide> var deltaLengthSq = this.center.distanceToSquared( point );
1
Java
Java
use text blocks with junit jupiter 5.8.1
08bce08018596d4e46ba01d1899062428d7b2c7e
<ide><path>spring-context/src/test/java/org/springframework/scheduling/annotation/ScheduledAnnotationBeanPostProcessorTests.java <ide> void closeContextAfterTest() { <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "FixedDelay, 5000", <del> "FixedDelayInSeconds, 5000", <del> "FixedDelayInMinutes, 180000" <del> }) <add> @CsvSource(textBlock = """ <add> FixedDelay, 5_000 <add> FixedDelayInSeconds, 5_000 <add> FixedDelayInMinutes, 180_000 <add> """) <ide> void fixedDelayTask(@NameToClass Class<?> beanClass, long expectedInterval) { <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(beanClass); <ide> void fixedDelayTask(@NameToClass Class<?> beanClass, long expectedInterval) { <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "FixedRate, 3000", <del> "FixedRateInSeconds, 5000", <del> "FixedRateInMinutes, 180000" <del> }) <add> @CsvSource(textBlock = """ <add> FixedRate, 3_000 <add> FixedRateInSeconds, 5_000 <add> FixedRateInMinutes, 180_000 <add> """) <ide> void fixedRateTask(@NameToClass Class<?> beanClass, long expectedInterval) { <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(beanClass); <ide> void fixedRateTask(@NameToClass Class<?> beanClass, long expectedInterval) { <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "FixedRateWithInitialDelay, 1000, 3000", <del> "FixedRateWithInitialDelayInSeconds, 5000, 3000", <del> "FixedRateWithInitialDelayInMinutes, 60000, 180000" <del> }) <add> @CsvSource(textBlock = """ <add> FixedRateWithInitialDelay, 1_000, 3_000 <add> FixedRateWithInitialDelayInSeconds, 5_000, 3_000 <add> FixedRateWithInitialDelayInMinutes, 60_000, 180_000 <add> """) <ide> void fixedRateTaskWithInitialDelay(@NameToClass Class<?> beanClass, long expectedInitialDelay, long expectedInterval) { <ide> BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); <ide> BeanDefinition targetDefinition = new RootBeanDefinition(beanClass); <ide> private void severalFixedRates(StaticApplicationContext context, <ide> assertThat(targetObject).isEqualTo(target); <ide> assertThat(targetMethod.getName()).isEqualTo("fixedRate"); <ide> assertThat(task1.getInitialDelay()).isEqualTo(0); <del> assertThat(task1.getInterval()).isEqualTo(4000L); <add> assertThat(task1.getInterval()).isEqualTo(4_000L); <ide> IntervalTask task2 = fixedRateTasks.get(1); <ide> ScheduledMethodRunnable runnable2 = (ScheduledMethodRunnable) task2.getRunnable(); <ide> targetObject = runnable2.getTarget(); <ide> targetMethod = runnable2.getMethod(); <ide> assertThat(targetObject).isEqualTo(target); <ide> assertThat(targetMethod.getName()).isEqualTo("fixedRate"); <del> assertThat(task2.getInitialDelay()).isEqualTo(2000L); <del> assertThat(task2.getInterval()).isEqualTo(4000L); <add> assertThat(task2.getInitialDelay()).isEqualTo(2_000L); <add> assertThat(task2.getInterval()).isEqualTo(4_000L); <ide> } <ide> <ide> @Test <ide> void metaAnnotationWithFixedRate() { <ide> Method targetMethod = runnable.getMethod(); <ide> assertThat(targetObject).isEqualTo(target); <ide> assertThat(targetMethod.getName()).isEqualTo("checkForUpdates"); <del> assertThat(task.getInterval()).isEqualTo(5000L); <add> assertThat(task.getInterval()).isEqualTo(5_000L); <ide> } <ide> <ide> @Test <ide> void composedAnnotationWithInitialDelayAndFixedRate() { <ide> Method targetMethod = runnable.getMethod(); <ide> assertThat(targetObject).isEqualTo(target); <ide> assertThat(targetMethod.getName()).isEqualTo("checkForUpdates"); <del> assertThat(task.getInterval()).isEqualTo(5000L); <del> assertThat(task.getInitialDelay()).isEqualTo(1000L); <add> assertThat(task.getInterval()).isEqualTo(5_000L); <add> assertThat(task.getInitialDelay()).isEqualTo(1_000L); <ide> } <ide> <ide> @Test <ide> void propertyPlaceholderWithInactiveCron() { <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "PropertyPlaceholderWithFixedDelay, 5000, 1000, 5000, 1000", <del> "PropertyPlaceholderWithFixedDelay, PT5S, PT1S, 5000, 1000", <del> "PropertyPlaceholderWithFixedDelayInSeconds, 5000, 1000, 5000000, 1000000", <del> "PropertyPlaceholderWithFixedDelayInSeconds, PT5S, PT1S, 5000, 1000" <del> }) <add> @CsvSource(textBlock = """ <add> PropertyPlaceholderWithFixedDelay, 5000, 1000, 5_000, 1_000 <add> PropertyPlaceholderWithFixedDelay, PT5S, PT1S, 5_000, 1_000 <add> PropertyPlaceholderWithFixedDelayInSeconds, 5000, 1000, 5_000_000, 1_000_000 <add> PropertyPlaceholderWithFixedDelayInSeconds, PT5S, PT1S, 5_000, 1_000 <add> """) <ide> void propertyPlaceholderWithFixedDelay(@NameToClass Class<?> beanClass, String fixedDelay, String initialDelay, <ide> long expectedInterval, long expectedInitialDelay) { <ide> <ide> void propertyPlaceholderWithFixedDelay(@NameToClass Class<?> beanClass, String f <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "PropertyPlaceholderWithFixedRate, 3000, 1000, 3000, 1000", <del> "PropertyPlaceholderWithFixedRate, PT3S, PT1S, 3000, 1000", <del> "PropertyPlaceholderWithFixedRateInSeconds, 3000, 1000, 3000000, 1000000", <del> "PropertyPlaceholderWithFixedRateInSeconds, PT3S, PT1S, 3000, 1000" <del> }) <add> @CsvSource(textBlock = """ <add> PropertyPlaceholderWithFixedRate, 3000, 1000, 3_000, 1_000 <add> PropertyPlaceholderWithFixedRate, PT3S, PT1S, 3_000, 1_000 <add> PropertyPlaceholderWithFixedRateInSeconds, 3000, 1000, 3_000_000, 1_000_000 <add> PropertyPlaceholderWithFixedRateInSeconds, PT3S, PT1S, 3_000, 1_000 <add> """) <ide> void propertyPlaceholderWithFixedRate(@NameToClass Class<?> beanClass, String fixedRate, String initialDelay, <ide> long expectedInterval, long expectedInitialDelay) { <ide> <ide> void nonEmptyParamList() { <ide> <ide> static class FixedDelay { <ide> <del> @Scheduled(fixedDelay = 5000) <add> @Scheduled(fixedDelay = 5_000) <ide> void fixedDelay() { <ide> } <ide> } <ide> void fixedDelay() { <ide> <ide> static class FixedRate { <ide> <del> @Scheduled(fixedRate = 3000) <add> @Scheduled(fixedRate = 3_000) <ide> void fixedRate() { <ide> } <ide> } <ide> void fixedRate() { <ide> <ide> static class FixedRateWithInitialDelay { <ide> <del> @Scheduled(fixedRate = 3000, initialDelay = 1000) <add> @Scheduled(fixedRate = 3_000, initialDelay = 1_000) <ide> void fixedRate() { <ide> } <ide> } <ide> void fixedRate() { <ide> <ide> static class SeveralFixedRatesWithSchedulesContainerAnnotationTestBean { <ide> <del> @Schedules({@Scheduled(fixedRate = 4000), @Scheduled(fixedRate = 4000, initialDelay = 2000)}) <add> @Schedules({@Scheduled(fixedRate = 4_000), @Scheduled(fixedRate = 4_000, initialDelay = 2_000)}) <ide> void fixedRate() { <ide> } <ide> } <ide> <ide> <ide> static class SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean { <ide> <del> @Scheduled(fixedRate = 4000) <del> @Scheduled(fixedRate = 4000, initialDelay = 2000) <add> @Scheduled(fixedRate = 4_000) <add> @Scheduled(fixedRate = 4_000, initialDelay = 2_000) <ide> void fixedRate() { <ide> } <ide> <ide> static SeveralFixedRatesWithRepeatedScheduledAnnotationTestBean nestedProxy() { <ide> <ide> static class FixedRatesBaseBean { <ide> <del> @Scheduled(fixedRate = 4000) <del> @Scheduled(fixedRate = 4000, initialDelay = 2000) <add> @Scheduled(fixedRate = 4_000) <add> @Scheduled(fixedRate = 4_000, initialDelay = 2_000) <ide> void fixedRate() { <ide> } <ide> } <ide> static class FixedRatesSubBean extends FixedRatesBaseBean { <ide> <ide> interface FixedRatesDefaultMethod { <ide> <del> @Scheduled(fixedRate = 4000) <del> @Scheduled(fixedRate = 4000, initialDelay = 2000) <add> @Scheduled(fixedRate = 4_000) <add> @Scheduled(fixedRate = 4_000, initialDelay = 2_000) <ide> default void fixedRate() { <ide> } <ide> } <ide> void invalid() { <ide> <ide> static class NonEmptyParamListTestBean { <ide> <del> @Scheduled(fixedRate = 3000) <add> @Scheduled(fixedRate = 3_000) <ide> void invalid(String oops) { <ide> } <ide> } <ide> <ide> <del> @Scheduled(fixedRate = 5000) <add> @Scheduled(fixedRate = 5_000) <ide> @Target(ElementType.METHOD) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> private @interface EveryFiveSeconds { <ide> void invalid(String oops) { <ide> private @interface Hourly { <ide> } <ide> <del> @Scheduled(initialDelay = 1000) <add> @Scheduled(initialDelay = 1_000) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> private @interface WaitASec { <ide> <ide> void checkForUpdates() { <ide> <ide> static class ComposedAnnotationFixedRateTestBean { <ide> <del> @WaitASec(fixedRate = 5000) <add> @WaitASec(fixedRate = 5_000) <ide> void checkForUpdates() { <ide> } <ide> } <ide><path>spring-core/src/test/java/org/springframework/util/ClassUtilsTests.java <ide> public Class<?> loadClass(String name) throws ClassNotFoundException { <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "boolean, boolean", <del> "byte, byte", <del> "char, char", <del> "short, short", <del> "int, int", <del> "long, long", <del> "float, float", <del> "double, double", <del> "[Z, boolean[]", <del> "[B, byte[]", <del> "[C, char[]", <del> "[S, short[]", <del> "[I, int[]", <del> "[J, long[]", <del> "[F, float[]", <del> "[D, double[]" <del> }) <add> @CsvSource(textBlock = """ <add> boolean, boolean <add> byte, byte <add> char, char <add> short, short <add> int, int <add> long, long <add> float, float <add> double, double <add> [Z, boolean[] <add> [B, byte[] <add> [C, char[] <add> [S, short[] <add> [I, int[] <add> [J, long[] <add> [F, float[] <add> [D, double[] <add> """) <ide> void resolvePrimitiveClassName(String input, Class<?> output) { <ide> assertThat(ClassUtils.resolvePrimitiveClassName(input)).isEqualTo(output); <ide> } <ide><path>spring-web/src/test/java/org/springframework/core/convert/support/IntegerToEnumConverterFactoryTests.java <ide> class IntegerToEnumConverterFactoryTests { <ide> <ide> <ide> @ParameterizedTest <del> @CsvSource({ <del> "0, RED", <del> "1, BLUE", <del> "2, GREEN" <del> }) <add> @CsvSource(textBlock = """ <add> 0, RED <add> 1, BLUE <add> 2, GREEN <add> """) <ide> void convertsIntegerToEnum(int index, Color color) { <ide> assertThat(converter.convert(index)).isEqualTo(color); <ide> } <ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/client/SockJsUrlInfoTests.java <ide> void sessionId() throws Exception { <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource( { <del> "http, http", <del> "https, https", <del> "ws, http", <del> "wss, https", <del> }) <add> @CsvSource(textBlock = """ <add> http, http <add> https, https <add> ws, http <add> wss, https <add> """) <ide> void infoUrl(String scheme, String expectedScheme) throws Exception { <ide> SockJsUrlInfo info = new SockJsUrlInfo(new URI(scheme + "://example.com")); <ide> assertThat(info.getInfoUrl()).isEqualTo(new URI(expectedScheme + "://example.com/info")); <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource( { <del> "http, http, XHR_STREAMING", <del> "http, ws, WEBSOCKET", <del> "https, https, XHR_STREAMING", <del> "https, wss, WEBSOCKET", <del> "ws, http, XHR_STREAMING", <del> "ws, ws, WEBSOCKET", <del> "wss, https, XHR_STREAMING", <del> "wss, wss, WEBSOCKET" <del> }) <add> @CsvSource(textBlock = """ <add> http, http, XHR_STREAMING <add> http, ws, WEBSOCKET <add> https, https, XHR_STREAMING <add> https, wss, WEBSOCKET <add> ws, http, XHR_STREAMING <add> ws, ws, WEBSOCKET <add> wss, https, XHR_STREAMING <add> wss, wss, WEBSOCKET <add> """) <ide> void transportUrl(String scheme, String expectedScheme, TransportType transportType) throws Exception { <ide> SockJsUrlInfo info = new SockJsUrlInfo(new URI(scheme + "://example.com")); <ide> String serverId = info.getServerId();
4
Javascript
Javascript
expose result of send()
67368d8553977a281f778a144de9b0a75bc17f90
<ide><path>lib/cluster.js <ide> Worker.prototype.kill = function() { <ide> }; <ide> <ide> Worker.prototype.send = function() { <del> this.process.send.apply(this.process, arguments); <add> return this.process.send.apply(this.process, arguments); <ide> }; <ide> <ide> Worker.prototype.isDead = function isDead() { <ide> function masterInit() { <ide> } <ide> <ide> function send(worker, message, handle, cb) { <del> sendHelper(worker.process, message, handle, cb); <add> return sendHelper(worker.process, message, handle, cb); <ide> } <ide> } <ide> <ide> function workerInit() { <ide> }; <ide> <ide> function send(message, cb) { <del> sendHelper(process, message, null, cb); <add> return sendHelper(process, message, null, cb); <ide> } <ide> <ide> function _disconnect(masterInitiated) { <ide> function sendHelper(proc, message, handle, cb) { <ide> if (cb) callbacks[seq] = cb; <ide> message.seq = seq; <ide> seq += 1; <del> proc.send(message, handle); <add> return proc.send(message, handle); <ide> } <ide> <ide> <ide><path>test/parallel/test-cluster-fork-env.js <ide> var assert = require('assert'); <ide> var cluster = require('cluster'); <ide> <ide> if (cluster.isWorker) { <del> cluster.worker.send({ <add> const result = cluster.worker.send({ <ide> prop: process.env['cluster_test_prop'], <ide> overwrite: process.env['cluster_test_overwrite'] <ide> }); <ide> <add> assert.strictEqual(result, true); <ide> } else if (cluster.isMaster) { <ide> <ide> var checks = { <ide><path>test/parallel/test-cluster-worker-events.js <ide> if (cluster.isMaster) { <ide> process.exit(0); <ide> }); <ide> <del> worker.send('SOME MESSAGE'); <add> const result = worker.send('SOME MESSAGE'); <add> assert.strictEqual(result, true); <ide> <ide> return; <ide> }
3
Text
Text
keep the other translations table
6f7b65dd660f4c3fe9b3ef9f3a8c3b29e33a71c6
<ide><path>docs/portuguese/how-to-catch-outgoing-emails-locally.md <add><table> <add> <tr> <add> <td> Read these guidelines in </td> <add> <td><a href="/CONTRIBUTING.md"> English </a></td> <add> <td><a href="/docs/chinese/CONTRIBUTING.md"> 中文 </a></td> <add> <td><a href="/docs/russian/CONTRIBUTING.md"> русский </a></td> <add> <td><a href="/docs/arabic/CONTRIBUTING.md"> عربى </a></td> <add> <td><a href="/docs/spanish/CONTRIBUTING.md"> Español </a></td> <add> <td><a href="/docs/portuguese/CONTRIBUTING.md"> Português </a></td> <add> </tr> <add></table> <add> <ide> # Como obter localmente os emails enviados (para fluxos de emails) <ide> <ide> > **Nota:** Este passo é **opcional** - Obrigatório apenas quando estiver trabalhando com fluxos de emails
1
Ruby
Ruby
fix installation error from argv `--head` filter
d9c3f19e6a7e13081982c93ba335e23a136c688f
<ide><path>Library/Homebrew/formula_installer.rb <ide> def install <ide> else <ide> ARGV.filter_for_dependencies do <ide> # Re-create the formula object so that args like `--HEAD` won't <del> # affect properties like the installation prefix. <add> # affect properties like the installation prefix. Also need to <add> # re-check installed status as the Formula may have changed. <ide> dep = Formula.factory dep.name <del> install_dependency dep <add> install_dependency dep unless dep.installed? <ide> end <ide> end <ide> end
1
Python
Python
update pt to tf cli for audio models
67a3511443fdcfd7ea616d6fb70ab823f300a7a0
<ide><path>src/transformers/commands/pt_to_tf.py <ide> def _get_audio_input(): <ide> raw_samples = [x["array"] for x in speech_samples] <ide> return raw_samples <ide> <add> model_config_class = type(pt_model.config) <add> if model_config_class in PROCESSOR_MAPPING: <add> processor = AutoProcessor.from_pretrained(self._local_dir) <add> if model_config_class in TOKENIZER_MAPPING and processor.tokenizer.pad_token is None: <add> processor.tokenizer.pad_token = processor.tokenizer.eos_token <add> elif model_config_class in FEATURE_EXTRACTOR_MAPPING: <add> processor = AutoFeatureExtractor.from_pretrained(self._local_dir) <add> elif model_config_class in TOKENIZER_MAPPING: <add> processor = AutoTokenizer.from_pretrained(self._local_dir) <add> if processor.pad_token is None: <add> processor.pad_token = processor.eos_token <add> else: <add> raise ValueError(f"Unknown data processing type (model config type: {model_config_class})") <add> <ide> model_forward_signature = set(inspect.signature(pt_model.forward).parameters.keys()) <ide> processor_inputs = {} <ide> if "input_ids" in model_forward_signature: <ide> def _get_audio_input(): <ide> sample_images = load_dataset("cifar10", "plain_text", split="test")[:2]["img"] <ide> processor_inputs.update({"images": sample_images}) <ide> if "input_features" in model_forward_signature: <del> processor_inputs.update({"raw_speech": _get_audio_input(), "padding": True}) <add> feature_extractor_signature = inspect.signature(processor.feature_extractor).parameters <add> # Pad to the largest input length by default but take feature extractor default <add> # padding value if it exists e.g. "max_length" and is not False or None <add> if "padding" in feature_extractor_signature: <add> default_strategy = feature_extractor_signature["padding"].default <add> if default_strategy is not False and default_strategy is not None: <add> padding_strategy = default_strategy <add> else: <add> padding_strategy = True <add> else: <add> padding_strategy = True <add> processor_inputs.update({"audio": _get_audio_input(), "padding": padding_strategy}) <ide> if "input_values" in model_forward_signature: # Wav2Vec2 audio input <del> processor_inputs.update({"raw_speech": _get_audio_input(), "padding": True}) <del> <del> model_config_class = type(pt_model.config) <del> if model_config_class in PROCESSOR_MAPPING: <del> processor = AutoProcessor.from_pretrained(self._local_dir) <del> if model_config_class in TOKENIZER_MAPPING and processor.tokenizer.pad_token is None: <del> processor.tokenizer.pad_token = processor.tokenizer.eos_token <del> elif model_config_class in FEATURE_EXTRACTOR_MAPPING: <del> processor = AutoFeatureExtractor.from_pretrained(self._local_dir) <del> elif model_config_class in TOKENIZER_MAPPING: <del> processor = AutoTokenizer.from_pretrained(self._local_dir) <del> if processor.pad_token is None: <del> processor.pad_token = processor.eos_token <del> else: <del> raise ValueError(f"Unknown data processing type (model config type: {model_config_class})") <del> <add> processor_inputs.update({"audio": _get_audio_input(), "padding": True}) <ide> pt_input = processor(**processor_inputs, return_tensors="pt") <ide> tf_input = processor(**processor_inputs, return_tensors="tf") <ide>
1
Text
Text
add documentation for stream.destroyed
70bb570bfb9e35e8a2295efe7277d35437235074
<ide><path>doc/api/stream.md <ide> the `'drain'` event before destroying the stream. <ide> Implementors should not override this method, <ide> but instead implement [`writable._destroy()`][writable-_destroy]. <ide> <add>##### writable.destroyed <add><!-- YAML <add>added: v8.0.0 <add>--> <add> <add>* {boolean} <add> <add>Is `true` after [`writable.destroy()`][writable-destroy] has been called. <add> <ide> ##### writable.end([chunk][, encoding][, callback]) <ide> <!-- YAML <ide> added: v0.9.4 <ide> will be ignored. <ide> Implementors should not override this method, but instead implement <ide> [`readable._destroy()`][readable-_destroy]. <ide> <add>##### readable.destroyed <add><!-- YAML <add>added: v8.0.0 <add>--> <add> <add>* {boolean} <add> <add>Is `true` after [`readable.destroy()`][readable-destroy] has been called. <add> <ide> ##### readable.isPaused() <ide> <!-- YAML <ide> added: v0.11.14
1
Java
Java
remove erroneous javadoc link
9ec937c843de372ea9e4d7e6c1312c936b58ef22
<ide><path>spring-test/src/main/java/org/springframework/test/context/SmartContextLoader.java <ide> public interface SmartContextLoader extends ContextLoader { <ide> * @return a new application context <ide> * @throws ContextLoadException if context loading failed <ide> * @see #processContextConfiguration(ContextConfigurationAttributes) <del> * @see #loadContextForAotProcessing(MergedContextConfiguration) <ide> * @see org.springframework.context.annotation.AnnotationConfigUtils#registerAnnotationConfigProcessors(org.springframework.beans.factory.support.BeanDefinitionRegistry) <ide> * @see org.springframework.context.ConfigurableApplicationContext#getEnvironment() <ide> */
1
Javascript
Javascript
use $readonlyarray for section stuff
5084e1ba0fcfc6409898d746086629011e7134da
<ide><path>Libraries/Lists/SectionList.js <ide> type SectionBase<SectionItemT> = { <ide> /** <ide> * The data for rendering items in this section. <ide> */ <del> data: Array<SectionItemT>, <add> data: $ReadOnlyArray<SectionItemT>, <ide> /** <ide> * Optional key to keep track of section re-ordering. If you don't plan on re-ordering sections, <ide> * the array index will be used by default. <ide> type RequiredProps<SectionT: SectionBase<any>> = { <ide> * <ide> * General shape: <ide> * <del> * sections: Array<{ <del> * data: Array<SectionItem>, <add> * sections: $ReadOnlyArray<{ <add> * data: $ReadOnlyArray<SectionItem>, <ide> * renderItem?: ({item: SectionItem, ...}) => ?React.Element<*>, <ide> * ItemSeparatorComponent?: ?ReactClass<{highlighted: boolean, ...}>, <ide> * }> <ide> */ <del> sections: Array<SectionT>, <add> sections: $ReadOnlyArray<SectionT>, <ide> }; <ide> <ide> type OptionalProps<SectionT: SectionBase<any>> = { <ide><path>Libraries/Lists/VirtualizedSectionList.js <ide> type SectionItem = any; <ide> <ide> type SectionBase = { <ide> // Must be provided directly on each section. <del> data: Array<SectionItem>, <add> data: $ReadOnlyArray<SectionItem>, <ide> key?: string, <ide> <ide> // Optional props will override list-wide props just for this section. <ide> type SectionBase = { <ide> }; <ide> <ide> type RequiredProps<SectionT: SectionBase> = { <del> sections: Array<SectionT>, <add> sections: $ReadOnlyArray<SectionT>, <ide> }; <ide> <ide> type OptionalProps<SectionT: SectionBase> = { <ide> export type Props<SectionT> = <ide> OptionalProps<SectionT> & <ide> VirtualizedListProps; <ide> <del>type DefaultProps = (typeof VirtualizedList.defaultProps) & {data: Array<Item>}; <add>type DefaultProps = (typeof VirtualizedList.defaultProps) & {data: $ReadOnlyArray<Item>}; <ide> type State = {childProps: VirtualizedListProps}; <ide> <ide> /** <ide> class ItemWithSeparator extends React.Component { <ide> } <ide> } <ide> <del>function getItem(sections: ?Array<Item>, index: number): ?Item { <add>function getItem(sections: ?$ReadOnlyArray<Item>, index: number): ?Item { <ide> if (!sections) { <ide> return null; <ide> }
2
Text
Text
fix typo in the security guide
5c2678056ac5d7af1a2f82a6e1e98401467cb5eb
<ide><path>guides/source/security.md <ide> The two dashes start a comment ignoring everything after it. So the query return <ide> Usually a web application includes access control. The user enters their login credentials and the web application tries to find the matching record in the users table. The application grants access when it finds a record. However, an attacker may possibly bypass this check with SQL injection. The following shows a typical database query in Rails to find the first record in the users table which matches the login credentials parameters supplied by the user. <ide> <ide> ```ruby <del>User.first("login = '#{params[:name]}' AND password = '#{params[:password]}'") <add>User.find_by("login = '#{params[:name]}' AND password = '#{params[:password]}'") <ide> ``` <ide> <ide> If an attacker enters ' OR '1'='1 as the name, and ' OR '2'>'1 as the password, the resulting SQL query will be: <ide> s = sanitize(user_input, tags: tags, attributes: %w(href title)) <ide> <ide> This allows only the given tags and does a good job, even against all kinds of tricks and malformed tags. <ide> <del>As a second step, _it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &amp;, &quot;, &lt;, and &gt; by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt;`, and `&gt;`). <add>As a second step, _it is good practice to escape all output of the application_, especially when re-displaying user input, which hasn't been input-filtered (as in the search form example earlier on). _Use `escapeHTML()` (or its alias `h()`) method_ to replace the HTML input characters &amp;, &quot;, &lt;, and &gt; by their uninterpreted representations in HTML (`&amp;`, `&quot;`, `&lt;`, and `&gt;`). <ide> <ide> ##### Obfuscation and Encoding Injection <ide>
1
Python
Python
fix resnet tests
092def7b4b4a49cc5d2583d1265c37227ed27fea
<ide><path>official/resnet/keras/keras_cifar_test.py <ide> from official.resnet import cifar10_main <ide> from official.resnet.keras import keras_cifar_main <ide> from official.resnet.keras import keras_common <add>from official.utils.misc import keras_utils <ide> from official.utils.testing import integration <ide> # pylint: disable=ungrouped-imports <ide> from tensorflow.python.eager import context <ide> def tearDown(self): <ide> <ide> def test_end_to_end_no_dist_strat(self): <ide> """Test Keras model with 1 GPU, no distribution strategy.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> extra_flags = [ <ide> def test_end_to_end_graph_no_dist_strat(self): <ide> <ide> def test_end_to_end_1_gpu(self): <ide> """Test Keras model with 1 GPU.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 1: <ide> def test_end_to_end_graph_1_gpu(self): <ide> <ide> def test_end_to_end_2_gpu(self): <ide> """Test Keras model with 2 GPUs.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 2: <ide><path>official/resnet/keras/keras_imagenet_test.py <ide> from official.resnet import imagenet_main <ide> from official.resnet.keras import keras_common <ide> from official.resnet.keras import keras_imagenet_main <add>from official.utils.misc import keras_utils <ide> from official.utils.testing import integration <ide> # pylint: disable=ungrouped-imports <ide> from tensorflow.python.eager import context <ide> def tearDown(self): <ide> <ide> def test_end_to_end_no_dist_strat(self): <ide> """Test Keras model with 1 GPU, no distribution strategy.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> extra_flags = [ <ide> def test_end_to_end_graph_no_dist_strat(self): <ide> <ide> def test_end_to_end_1_gpu(self): <ide> """Test Keras model with 1 GPU.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 1: <ide> def test_end_to_end_graph_1_gpu(self): <ide> <ide> def test_end_to_end_2_gpu(self): <ide> """Test Keras model with 2 GPUs.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 2: <ide> def test_end_to_end_2_gpu(self): <ide> <ide> def test_end_to_end_xla_2_gpu(self): <ide> """Test Keras model with XLA and 2 GPUs.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 2: <ide> def test_end_to_end_xla_2_gpu(self): <ide> <ide> def test_end_to_end_2_gpu_fp16(self): <ide> """Test Keras model with 2 GPUs and fp16.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 2: <ide> def test_end_to_end_2_gpu_fp16(self): <ide> <ide> def test_end_to_end_xla_2_gpu_fp16(self): <ide> """Test Keras model with XLA, 2 GPUs and fp16.""" <del> config = keras_common.get_config_proto_v1() <add> config = keras_utils.get_config_proto_v1() <ide> tf.compat.v1.enable_eager_execution(config=config) <ide> <ide> if context.num_gpus() < 2:
2
Java
Java
describe merge() error handling.
a694145b6775960520dcd3964d9bcf3540fced24
<ide><path>src/main/java/io/reactivex/Flowable.java <ide> public static <T> Flowable<T> mergeArray(int maxConcurrency, int bufferSize, Pub <ide> * backpressure; if violated, the operator <em>may</em> signal {@code MissingBackpressureException}.</dd> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> <add> * <dt><b>Error handling:</b></dt> <add> * <dd>If any of the source {@code Publisher}s signal a {@code Throwable} via {@code onError}, the resulting <add> * {@code Flowable} terminates with that {@code Throwable} and all other source {@code Publisher}s are cancelled. <add> * If more than one {@code Publisher} signals an error, the resulting {@code Flowable} may terminate with the <add> * first one's error or, depending on the concurrency of the sources, may terminate with a <add> * {@code CompositeException} containing two or more of the various error signals. <add> * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via <add> * {@link RxJavaPlugins#onError(Throwable)} method as <em>undeliverable errors</em>. Similarly, {@code Throwable}s <add> * signaled by source(s) after the returned {@code Flowable} has been cancelled or terminated with a <add> * (composite) error will be sent to the same global error handler. <add> * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code Publisher}s <add> * have completed or failed with an error. <add> * </dd> <ide> * </dl> <ide> * <ide> * @param <T> the common element base type <ide> public static <T> Flowable<T> mergeArray(int maxConcurrency, int bufferSize, Pub <ide> * @return a Flowable that emits items that are the result of flattening the items emitted by the <ide> * Publishers in the Iterable <ide> * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> <add> * @see #mergeDelayError(Iterable) <ide> */ <ide> @SuppressWarnings({ "unchecked", "rawtypes" }) <ide> @CheckReturnValue
1
Ruby
Ruby
remove unneeded requires at active record
61b5f5d2f1f2de0aaa4a6c8445c47c2df7ef1f36
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/range.rb <del>require "active_support/core_ext/string/filters" <del> <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> module PostgreSQL <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" <del>require "active_support/core_ext/string/filters" <ide> <ide> module ActiveRecord <ide> module QueryMethods <ide><path>activerecord/lib/active_record/tasks/database_tasks.rb <del>require "active_support/core_ext/string/filters" <del> <ide> module ActiveRecord <ide> module Tasks # :nodoc: <ide> class DatabaseAlreadyExists < StandardError; end # :nodoc:
3
Go
Go
prevent potential panic in testlogsapiuntil
e77de7856bf212c764555ab8c2f346f2c529467c
<ide><path>integration-cli/docker_api_logs_test.go <ide> func (s *DockerSuite) TestLogsAPIUntil(c *check.C) { <ide> <ide> // Get timestamp of second log line <ide> allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true}) <add> c.Assert(len(allLogs), checker.GreaterOrEqualThan, 3) <add> <ide> t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0]) <ide> c.Assert(err, checker.IsNil) <ide> until := t.Format(time.RFC3339Nano)
1
Text
Text
fix grammatical typo
8365bf62df45d1cafdfbd8c4aad0a6f3ced5f854
<ide><path>docs/basic-features/data-fetching/get-static-paths.md <ide> In development (`next dev`), `getStaticPaths` will be called on every request. <ide> <ide> `getStaticProps` allows you to control which pages are generated during the build instead of on-demand with [`fallback`](/docs/api-reference/data-fetching/get-static-paths.md#fallback-blocking). Generating more pages during a build will cause slower builds. <ide> <del>You can defer generating all pages on-demand by returning an empty array for `paths`. This can be especially helpful when deploying you Next.js application to multiple environments. For example, you can have faster builds by generating all pages on-demand for previews (but not production builds). This is helpful for sites with hundreds/thousands of static pages. <add>You can defer generating all pages on-demand by returning an empty array for `paths`. This can be especially helpful when deploying your Next.js application to multiple environments. For example, you can have faster builds by generating all pages on-demand for previews (but not production builds). This is helpful for sites with hundreds/thousands of static pages. <ide> <ide> ```jsx <ide> // pages/posts/[id].js
1
Javascript
Javascript
use correct arg name in domains benchmark
feba43c40e97aa40e79923a326d91d5a23f10537
<ide><path>test/parallel/test-benchmark-domain.js <ide> require('../common'); <ide> <ide> const runBenchmark = require('../common/benchmark'); <ide> <del>runBenchmark('domain', ['n=1', 'arguments=0']); <add>runBenchmark('domain', ['n=1', 'args=0']);
1
Text
Text
replace stub with hints and code solution
3ac898b041bcbaaf9f6268b9aef4519014389070
<ide><path>guide/english/certifications/apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model/index.md <ide> --- <ide> title: Create and Save a Record of a Model <ide> --- <del>## Create and Save a Record of a Model <add># Create and Save a Record of a Model <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/apis-and-microservices/mongodb-and-mongoose/create-and-save-a-record-of-a-model/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>## Hints <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>### Hint #1 <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add>You need to do the following: <add>1. Create a model of a person, using the schema from exercise 2 <add>2. Create a new person, including their attributes <add>3. Save the new person you created <add>4. Put your new person inside the `createAndSavePerson` function <add> <add>## Solutions <add> <add><details><summary>Solution #1 (Click to Show/Hide)</summary> <add> <add>Code for `myApp.js` <add> <add>```javascript <add>/** 1) Install & Set up mongoose */ <add> <add>const mongoose = require('mongoose'); <add>mongoose.connect(process.env.MONGO_URI); <add> <add>/** 2) Create a 'Person' Model */ <add>var personSchema = new mongoose.Schema({ <add> name: String, <add> age: Number, <add> favoriteFoods: [String] <add>}); <add> <add>/** 3) Create and Save a Person */ <add>var Person = mongoose.model('Person', personSchema); <add> <add>var createAndSavePerson = function(done) { <add> var janeFonda = new Person({name: "Jane Fonda", age: 84, favoriteFoods: ["vodka", "air"]}); <add> <add> janeFonda.save(function(err, data) { <add> if (err) return console.error(err); <add> done(null, data) <add> }); <add>}; <add>``` <add></details>
1
PHP
PHP
update trait description
45b79ddd13075865fffeba1846e3fa9a44ab5435
<ide><path>src/TestSuite/StringCompareTrait.php <ide> /** <ide> * Compare a string to the contents of a file <ide> * <del> * Implementing objects are expected to declare a `$_compareBasePath` property. <add> * Implementing objects are expected to modify the `$_compareBasePath` property <add> * before use. <ide> */ <ide> trait StringCompareTrait { <ide>
1
Python
Python
modify compression tools to be python3 compatible
e8adaffd4bd5cea79a23c3ae440e8933fc6c3723
<ide><path>compression/decoder.py <ide> <ide> def get_input_tensor_names(): <ide> name_list = ['GruBinarizer/SignBinarizer/Sign:0'] <del> for i in xrange(1, 16): <add> for i in range(1, 16): <ide> name_list.append('GruBinarizer/SignBinarizer/Sign_{}:0'.format(i)) <ide> return name_list <ide> <ide> <ide> def get_output_tensor_names(): <del> return ['loop_{0:02d}/add:0'.format(i) for i in xrange(0, 16)] <add> return ['loop_{0:02d}/add:0'.format(i) for i in range(0, 16)] <ide> <ide> <ide> def main(_): <ide> if (FLAGS.input_codes is None or FLAGS.output_directory is None or <ide> FLAGS.model is None): <del> print ('\nUsage: python decoder.py --input_codes=output_codes.pkl ' <del> '--iteration=15 --output_directory=/tmp/compression_output/ ' <del> '--model=residual_gru.pb\n\n') <add> print('\nUsage: python decoder.py --input_codes=output_codes.pkl ' <add> '--iteration=15 --output_directory=/tmp/compression_output/ ' <add> '--model=residual_gru.pb\n\n') <ide> return <ide> <ide> if FLAGS.iteration < -1 or FLAGS.iteration > 15: <del> print ('\n--iteration must be between 0 and 15 inclusive, or -1 to infer ' <del> 'from file.\n') <add> print('\n--iteration must be between 0 and 15 inclusive, or -1 to infer ' <add> 'from file.\n') <ide> return <ide> iteration = FLAGS.iteration <ide> <ide> if not tf.gfile.Exists(FLAGS.output_directory): <ide> tf.gfile.MkDir(FLAGS.output_directory) <ide> <ide> if not tf.gfile.Exists(FLAGS.input_codes): <del> print '\nInput codes not found.\n' <add> print('\nInput codes not found.\n') <ide> return <ide> <ide> contents = '' <ide><path>compression/encoder.py <ide> <ide> def get_output_tensor_names(): <ide> name_list = ['GruBinarizer/SignBinarizer/Sign:0'] <del> for i in xrange(1, 16): <add> for i in range(1, 16): <ide> name_list.append('GruBinarizer/SignBinarizer/Sign_{}:0'.format(i)) <ide> return name_list <ide> <ide> <ide> def main(_): <ide> if (FLAGS.input_image is None or FLAGS.output_codes is None or <ide> FLAGS.model is None): <del> print ('\nUsage: python encoder.py --input_image=/your/image/here.png ' <del> '--output_codes=output_codes.pkl --iteration=15 ' <del> '--model=residual_gru.pb\n\n') <add> print('\nUsage: python encoder.py --input_image=/your/image/here.png ' <add> '--output_codes=output_codes.pkl --iteration=15 ' <add> '--model=residual_gru.pb\n\n') <ide> return <ide> <ide> if FLAGS.iteration < 0 or FLAGS.iteration > 15: <del> print '\n--iteration must be between 0 and 15 inclusive.\n' <add> print('\n--iteration must be between 0 and 15 inclusive.\n') <ide> return <ide> <ide> with tf.gfile.FastGFile(FLAGS.input_image) as input_image: <ide><path>compression/msssim.py <ide> def MultiScaleSSIM(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, <ide> im1, im2 = [x.astype(np.float64) for x in [img1, img2]] <ide> mssim = np.array([]) <ide> mcs = np.array([]) <del> for _ in xrange(levels): <add> for _ in range(levels): <ide> ssim, cs = _SSIMForMultiScale( <ide> im1, im2, max_val=max_val, filter_size=filter_size, <ide> filter_sigma=filter_sigma, k1=k1, k2=k2) <ide> def MultiScaleSSIM(img1, img2, max_val=255, filter_size=11, filter_sigma=1.5, <ide> <ide> def main(_): <ide> if FLAGS.original_image is None or FLAGS.compared_image is None: <del> print ('\nUsage: python msssim.py --original_image=original.png ' <del> '--compared_image=distorted.png\n\n') <add> print('\nUsage: python msssim.py --original_image=original.png ' <add> '--compared_image=distorted.png\n\n') <ide> return <ide> <ide> if not tf.gfile.Exists(FLAGS.original_image): <del> print '\nCannot find --original_image.\n' <add> print('\nCannot find --original_image.\n') <ide> return <ide> <ide> if not tf.gfile.Exists(FLAGS.compared_image): <del> print '\nCannot find --compared_image.\n' <add> print('\nCannot find --compared_image.\n') <ide> return <ide> <ide> with tf.gfile.FastGFile(FLAGS.original_image) as image_file: <ide> def main(_): <ide> img1 = sess.run(decoded_image, feed_dict={input_img: img1_str}) <ide> img2 = sess.run(decoded_image, feed_dict={input_img: img2_str}) <ide> <del> print MultiScaleSSIM(img1, img2, max_val=255) <add> print((MultiScaleSSIM(img1, img2, max_val=255))) <ide> <ide> <ide> if __name__ == '__main__':
3
Javascript
Javascript
support old private properties and function
b377034359aa07f2ba83a5a0c9f859418cb80e39
<ide><path>lib/_http_outgoing.js <ide> function OutgoingMessage() { <ide> util.inherits(OutgoingMessage, Stream); <ide> <ide> <add>Object.defineProperty(OutgoingMessage.prototype, '_headers', { <add> get: function() { <add> return this.getHeaders(); <add> }, <add> set: function(val) { <add> if (val == null) { <add> this[outHeadersKey] = null; <add> } else if (typeof val === 'object') { <add> const headers = this[outHeadersKey] = {}; <add> const keys = Object.keys(val); <add> for (var i = 0; i < keys.length; ++i) { <add> const name = keys[i]; <add> headers[name.toLowerCase()] = [name, val[name]]; <add> } <add> } <add> } <add>}); <add> <add>Object.defineProperty(OutgoingMessage.prototype, '_headerNames', { <add> get: function() { <add> const headers = this[outHeadersKey]; <add> if (headers) { <add> const out = new StorageObject(); <add> const keys = Object.keys(headers); <add> for (var i = 0; i < keys.length; ++i) { <add> const key = keys[i]; <add> const val = headers[key][0]; <add> out[key] = val; <add> } <add> return out; <add> } else { <add> return headers; <add> } <add> }, <add> set: function(val) { <add> if (typeof val === 'object' && val !== null) { <add> const headers = this[outHeadersKey]; <add> if (!headers) <add> return; <add> const keys = Object.keys(val); <add> for (var i = 0; i < keys.length; ++i) { <add> const header = headers[keys[i]]; <add> if (header) <add> header[0] = val[keys[i]]; <add> } <add> } <add> } <add>}); <add> <add> <add>OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { <add> if (this._header) { <add> throw new Error('Can\'t render headers after they are sent to the client'); <add> } <add> <add> var headersMap = this[outHeadersKey]; <add> if (!headersMap) return {}; <add> <add> var headers = {}; <add> var keys = Object.keys(headersMap); <add> <add> for (var i = 0, l = keys.length; i < l; i++) { <add> var key = keys[i]; <add> headers[headersMap[key][0]] = headersMap[key][1]; <add> } <add> return headers; <add>}; <add> <add> <ide> exports.OutgoingMessage = OutgoingMessage; <ide> <ide>
1
Python
Python
catch cpuinfo importerror
5c78b9d7620dd1350b86d66ad5c94d19fe53d1bb
<ide><path>official/utils/logs/logger.py <ide> def _collect_cpu_info(run_info): <ide> <ide> cpu_info["num_cores"] = multiprocessing.cpu_count() <ide> <del> # Note: cpuinfo is not installed in the TensorFlow OSS tree. <del> # It is installable via pip. <del> import cpuinfo # pylint: disable=g-import-not-at-top <add> try: <add> # Note: cpuinfo is not installed in the TensorFlow OSS tree. <add> # It is installable via pip. <add> import cpuinfo # pylint: disable=g-import-not-at-top <ide> <del> info = cpuinfo.get_cpu_info() <del> cpu_info["cpu_info"] = info["brand"] <del> cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6 <add> info = cpuinfo.get_cpu_info() <add> cpu_info["cpu_info"] = info["brand"] <add> cpu_info["mhz_per_cpu"] = info["hz_advertised_raw"][0] / 1.0e6 <ide> <del> run_info["machine_config"]["cpu_info"] = cpu_info <add> run_info["machine_config"]["cpu_info"] = cpu_info <add> except ImportError: <add> tf.logging.warn("'cpuinfo' not imported. CPU info will not be logged.") <ide> <ide> <ide> def _collect_gpu_info(run_info): <ide> def _collect_gpu_info(run_info): <ide> <ide> <ide> def _collect_memory_info(run_info): <del> # Note: psutil is not installed in the TensorFlow OSS tree. <del> # It is installable via pip. <del> import psutil # pylint: disable=g-import-not-at-top <del> vmem = psutil.virtual_memory() <del> run_info["machine_config"]["memory_total"] = vmem.total <del> run_info["machine_config"]["memory_available"] = vmem.available <add> try: <add> # Note: psutil is not installed in the TensorFlow OSS tree. <add> # It is installable via pip. <add> import psutil # pylint: disable=g-import-not-at-top <add> vmem = psutil.virtual_memory() <add> run_info["machine_config"]["memory_total"] = vmem.total <add> run_info["machine_config"]["memory_available"] = vmem.available <add> except ImportError: <add> tf.logging.warn("'psutil' not imported. Memory info will not be logged.") <ide> <ide> <ide> def _parse_gpu_model(physical_device_desc):
1
Javascript
Javascript
upgrade warncasesensitivemodulesplugin to es6
7140b7dd057ceb7f434308724d6a8b56554b7703
<ide><path>lib/WarnCaseSensitiveModulesPlugin.js <ide> MIT License http://www.opensource.org/licenses/mit-license.php <ide> Author Tobias Koppers @sokra <ide> */ <del>var CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); <add>"use strict"; <ide> <del>function WarnCaseSensitiveModulesPlugin() {} <del>module.exports = WarnCaseSensitiveModulesPlugin; <add>const CaseSensitiveModulesWarning = require("./CaseSensitiveModulesWarning"); <ide> <del>WarnCaseSensitiveModulesPlugin.prototype.apply = function(compiler) { <del> compiler.plugin("compilation", function(compilation) { <del> compilation.plugin("seal", function() { <del> var moduleWithoutCase = {}; <del> this.modules.forEach(function(module) { <del> var ident = module.identifier().toLowerCase(); <del> if(moduleWithoutCase["$" + ident]) { <del> moduleWithoutCase["$" + ident].push(module); <del> } else { <del> moduleWithoutCase["$" + ident] = [module]; <del> } <del> }, this); <del> Object.keys(moduleWithoutCase).forEach(function(key) { <del> if(moduleWithoutCase[key].length > 1) <del> this.warnings.push(new CaseSensitiveModulesWarning(moduleWithoutCase[key])); <del> }, this); <add>class WarnCaseSensitiveModulesPlugin { <add> apply(compiler) { <add> compiler.plugin("compilation", compilation => { <add> compilation.plugin("seal", function() { <add> const moduleWithoutCase = {}; <add> this.modules.forEach(module => { <add> const ident = module.identifier().toLowerCase(); <add> if(moduleWithoutCase[`$${ident}`]) { <add> moduleWithoutCase[`$${ident}`].push(module); <add> } else { <add> moduleWithoutCase[`$${ident}`] = [module]; <add> } <add> }, this); <add> Object.keys(moduleWithoutCase).forEach(key => { <add> if(moduleWithoutCase[key].length > 1) <add> this.warnings.push(new CaseSensitiveModulesWarning(moduleWithoutCase[key])); <add> }, this); <add> }); <ide> }); <del> }); <del>}; <add> } <add>} <add> <add>module.exports = WarnCaseSensitiveModulesPlugin;
1
Ruby
Ruby
remove documentation duplicates
c175563b88a2114258120cacaf3f4bce5a615736
<ide><path>activemodel/lib/active_model/validations/acceptance.rb <ide> module HelperMethods <ide> # Configuration options: <ide> # * <tt>:message</tt> - A custom error message (default is: "must be <ide> # accepted"). <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <ide> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default <ide> # is +true+). <ide> # * <tt>:accept</tt> - Specifies value that is considered accepted. <ide> # The default value is a string "1", which makes it easy to relate to <ide> # an HTML checkbox. This should be set to +true+ if you are validating <ide> # a database column, since the attribute is typecast from "1" to +true+ <ide> # before validation. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should occur (e.g. <tt>if: :allow_validation</tt>, <del> # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to <del> # determine if the validation should not occur (for example, <del> # <tt>unless: :skip_validation</tt>, or <del> # <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). <del> # The method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_acceptance_of(*attr_names) <ide> validates_with AcceptanceValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/confirmation.rb <ide> module HelperMethods <ide> # Configuration options: <ide> # * <tt>:message</tt> - A custom error message (default is: "doesn't match <ide> # confirmation"). <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should occur (e.g. <tt>if: :allow_validation</tt>, <del> # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to <del> # determine if the validation should not occur (e.g. <del> # <tt>unless: :skip_validation</tt>, or <del> # <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_confirmation_of(*attr_names) <ide> validates_with ConfirmationValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/exclusion.rb <ide> module HelperMethods <ide> # attribute is +nil+ (default is +false+). <ide> # * <tt>:allow_blank</tt> - If set to true, skips this validation if the <ide> # attribute is blank(default is +false+). <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if <del> # the validation should occur (e.g. <tt>if: :allow_validation</tt>, or <del> # <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, <del> # proc or string should return or evaluate to a +true+ or +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <del> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_exclusion_of(*attr_names) <ide> validates_with ExclusionValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/format.rb <ide> module HelperMethods <ide> # match will result in a successful validation. This can be provided as <ide> # a proc or lambda returning regular expression which will be called at <ide> # runtime. <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should occur (e.g. <tt>if: :allow_validation</tt>, <del> # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, <del> # proc or string should return or evaluate to a +true+ or +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <del> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <ide> # * <tt>:multiline</tt> - Set to true if your regular expression contains <ide> # anchors that match the beginning or end of lines as opposed to the <ide> # beginning or end of the string. These anchors are <tt>^</tt> and <tt>$</tt>. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_format_of(*attr_names) <ide> validates_with FormatValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/inclusion.rb <ide> module HelperMethods <ide> # attribute is +nil+ (default is +false+). <ide> # * <tt>:allow_blank</tt> - If set to +true+, skips this validation if the <ide> # attribute is blank (default is +false+). <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if <del> # the validation should occur (e.g. <tt>if: :allow_validation</tt>, or <del> # <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, proc <del> # or string should return or evaluate to a +true+ or +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <del> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_inclusion_of(*attr_names) <ide> validates_with InclusionValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/length.rb <ide> module HelperMethods <ide> # * <tt>:message</tt> - The error message to use for a <tt>:minimum</tt>, <ide> # <tt>:maximum</tt>, or <tt>:is</tt> violation. An alias of the appropriate <ide> # <tt>too_long</tt>/<tt>too_short</tt>/<tt>wrong_length</tt> message. <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine if <del> # the validation should occur (e.g. <tt>if: :allow_validation</tt>, or <del> # <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, <del> # proc or string should return or evaluate to a +true+ or +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <del> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <ide> # * <tt>:tokenizer</tt> - Specifies how to split up the attribute string. <ide> # (e.g. <tt>tokenizer: ->(str) { str.scan(/\w+/) }</tt> to count words <ide> # as in above example). Defaults to <tt>->(value) { value.split(//) }</tt> <ide> # which counts individual characters. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_length_of(*attr_names) <ide> validates_with LengthValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/numericality.rb <ide> module HelperMethods <ide> # <ide> # Configuration options: <ide> # * <tt>:message</tt> - A custom error message (default is: "is not a number"). <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <ide> # * <tt>:only_integer</tt> - Specifies whether the value has to be an <ide> # integer, e.g. an integral value (default is +false+). <ide> # * <tt>:allow_nil</tt> - Skip validation if attribute is +nil+ (default is <ide> module HelperMethods <ide> # supplied value. <ide> # * <tt>:odd</tt> - Specifies the value must be an odd number. <ide> # * <tt>:even</tt> - Specifies the value must be an even number. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should occur (e.g. <tt>if: :allow_validation</tt>, <del> # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, <del> # proc or string should return or evaluate to a +true+ or +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <del> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+ . <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> # <ide> # The following checks can also be supplied with a proc or a symbol which <ide> # corresponds to a method: <ide><path>activemodel/lib/active_model/validations/presence.rb <ide> module HelperMethods <ide> # <ide> # Configuration options: <ide> # * <tt>:message</tt> - A custom error message (default is: "can't be blank"). <del> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <del> # validation contexts by default (+nil+), other options are <tt>:create</tt> <del> # and <tt>:update</tt>. <del> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should occur (e.g. <tt>if: :allow_validation</tt>, <del> # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, <del> # proc or string should return or evaluate to a +true+ or +false+ value. <del> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <del> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <del> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <del> # method, proc or string should return or evaluate to a +true+ or <del> # +false+ value. <del> # * <tt>:strict</tt> - Specifies whether validation should be strict. <del> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # There is also a list of default options supported by every validator: <add> # +:if+, +:unless+, +:on+ and +:strict+. <add> # See <tt>ActiveModel::Validation#validates</tt> for more information <ide> def validates_presence_of(*attr_names) <ide> validates_with PresenceValidator, _merge_attributes(attr_names) <ide> end <ide><path>activemodel/lib/active_model/validations/validates.rb <ide> module ClassMethods <ide> # validator's initializer as +options[:in]+ while other types including <ide> # regular expressions and strings are passed as +options[:with]+ <ide> # <add> # There is also a list of options that could be used along with validators: <add> # * <tt>:on</tt> - Specifies when this validation is active. Runs in all <add> # validation contexts by default (+nil+), other options are <tt>:create</tt> <add> # and <tt>:update</tt>. <add> # * <tt>:if</tt> - Specifies a method, proc or string to call to determine <add> # if the validation should occur (e.g. <tt>if: :allow_validation</tt>, <add> # or <tt>if: Proc.new { |user| user.signup_step > 2 }</tt>). The method, <add> # proc or string should return or evaluate to a +true+ or +false+ value. <add> # * <tt>:unless</tt> - Specifies a method, proc or string to call to determine <add> # if the validation should not occur (e.g. <tt>unless: :skip_validation</tt>, <add> # or <tt>unless: Proc.new { |user| user.signup_step <= 2 }</tt>). The <add> # method, proc or string should return or evaluate to a +true+ or <add> # +false+ value. <add> # * <tt>:strict</tt> - Specifies whether validation should be strict. <add> # See <tt>ActiveModel::Validation#validates!</tt> for more information. <add> # <add> # Example: <add> # <add> # validates :password, :presence => true, :confirmation => true, :if => :password_required? <add> # <ide> # Finally, the options +:if+, +:unless+, +:on+, +:allow_blank+, +:allow_nil+ and +:strict+ <ide> # can be given to one specific validator, as a hash: <ide> # <ide> # validates :password, :presence => { :if => :password_required? }, :confirmation => true <ide> # <del> # Or to all at the same time: <del> # <del> # validates :password, :presence => true, :confirmation => true, :if => :password_required? <ide> # <ide> def validates(*attributes) <ide> defaults = attributes.extract_options!.dup
9
Javascript
Javascript
enable continuous replay flag
3f9480f0f5ceb5a32a3751066f0b8e9eae5f1b10
<ide><path>packages/shared/ReactFeatureFlags.js <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> <ide> export const enableSuspenseAvoidThisFallback = false; <ide> <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> <ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableComponentStackLocations = false; <ide> export const enableLegacyFBSupport = false; <ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableComponentStackLocations = false; <ide> export const enableLegacyFBSupport = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js <ide> export const enableNewReconciler = false; <ide> export const deferRenderPhaseUpdateToNextBatch = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableStrictEffects = false; <ide> export const createRootStrictEffectsByDefault = false; <ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = false; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = false; <ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js <ide> export const warnUnstableRenderSubtreeIntoContainer = false; <ide> export const warnAboutSpreadingKeyToJSX = false; <ide> export const warnOnSubscriptionInsideStartTransition = false; <ide> export const enableSuspenseAvoidThisFallback = false; <del>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = false; <add>export const enableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay = true; <ide> export const enableClientRenderFallbackOnHydrationMismatch = true; <ide> export const enableComponentStackLocations = true; <ide> export const enableLegacyFBSupport = !__EXPERIMENTAL__;
8
Python
Python
enable v2 layers for resnet_model
caa5158fde0532d31f64cb05061b5cb7444c6265
<ide><path>official/vision/image_classification/resnet_model.py <ide> from __future__ import division <ide> from __future__ import print_function <ide> <add>import tensorflow as tf <add> <ide> from tensorflow.python.keras import backend <ide> from tensorflow.python.keras import initializers <del>from tensorflow.python.keras import layers <ide> from tensorflow.python.keras import models <ide> from tensorflow.python.keras import regularizers <ide> from official.vision.image_classification import imagenet_preprocessing <ide> <add>layers = tf.keras.layers <add> <ide> L2_WEIGHT_DECAY = 1e-4 <ide> BATCH_NORM_DECAY = 0.9 <ide> BATCH_NORM_EPSILON = 1e-5
1
PHP
PHP
remove unused variable
f3e92bac8b0bc12776e2693917d5cfe4076e835b
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php <ide> protected function appendFilePath($contents) <ide> protected function getOpenAndClosingPhpTokens($contents) <ide> { <ide> return collect(token_get_all($contents)) <del> ->pluck($tokenNumber = 0) <add> ->pluck(0) <ide> ->filter(function ($token) { <ide> return in_array($token, [T_OPEN_TAG, T_OPEN_TAG_WITH_ECHO, T_CLOSE_TAG]); <ide> });
1
Javascript
Javascript
fix incorrect comment
6a33aa63cd3f0497baa5587b0335a793ffd02864
<ide><path>validate-commit-msg.js <ide> * <ide> * Installation: <ide> * >> cd <angular-repo> <del> * >> ln -s ../../validate-commit-msg.js .git/hooks/commit-msg <add> * >> ln -s validate-commit-msg.js .git/hooks/commit-msg <ide> */ <ide> var fs = require('fs'); <ide> var util = require('util');
1
Ruby
Ruby
apply suggestions from code review
e8eb781470df7463ca2147862d257815f5062314
<ide><path>Library/Homebrew/extend/os/mac/formula_cellar_checks.rb <ide> def check_openssl_links <ide> These object files were linked against the deprecated system OpenSSL or <ide> the system's private LibreSSL. <ide> Adding `depends_on "openssl"` to the formula may help. <del> #{system_openssl * "\n "} <add> #{system_openssl * "\n "} <ide> EOS <ide> end <ide> <ide> def check_flat_namespace(formula) <ide> next true unless file.dylib? <ide> <ide> macho = MachO.open(file) <del> if file.universal? <add> if MachO::Utils.fat_magic?(macho.magic) <ide> macho.machos.map(&:header).all? { |h| h.flag? :MH_TWOLEVEL } <ide> else <del> macho.header.flag?(:MH_TWOLEVEL) <add> macho.header.flag? :MH_TWOLEVEL <ide> end <ide> end <ide> return if flat_namespace_files.empty?
1
Javascript
Javascript
avoid clones while interpolating values
281f51051c30a1d9ceb6cc120a9bf0e695d1a724
<ide><path>src/animation/AnimationUtils.js <ide> <ide> }, <ide> <add> clone: function( exemplarValue ) { <add> <add> var typeName = typeof exemplarValue; <add> if( typeName === "object" ) { <add> if( exemplarValue.clone ) { <add> return exemplarValue.clone(); <add> } <add> console.error( "can not figure out how to copy exemplarValue", exemplarValue ); <add> } <add> <add> return exemplarValue; <add> <add> }, <ide> <ide> lerp: function( a, b, alpha, interTrack ) { <ide> <ide> <ide> return function( a, b, alpha ) { <ide> //console.log( a, b ); <del> return a.clone().lerp( b, alpha ); <add> return a.lerp( b, alpha ); <ide> } <ide> <ide> } <ide> if( exemplarValue.slerp ) { <ide> <ide> return function( a, b, alpha ) { <ide> //console.log( a, b ); <del> return a.clone().slerp( b, alpha ); <add> return a.slerp( b, alpha ); <ide> } <ide> <ide> } <ide><path>src/animation/KeyframeTrack.js <ide> THREE.KeyframeTrack = function ( name, keys ) { <ide> <ide> this.name = name; <del> this.keys = keys || []; // time in seconds, value as value <add> this.keys = keys; // time in seconds, value as value <add> <add> // local cache of value type to avoid allocations during runtime. <add> this.result = THREE.AnimationUtils.clone( this.keys[0].value ); <add> //console.log( 'constructor result', this.result ) <ide> <ide> this.sort(); <ide> this.validate(); <ide> THREE.KeyframeTrack.prototype = { <ide> <ide> constructor: THREE.KeyframeTrack, <ide> <add> // TODO: this is a straight forward linear search for the key that corresponds to this time, this <add> // should be optimized. <ide> getAt: function( time ) { <ide> //console.log( 'KeyframeTrack[' + this.name + '].getAt( ' + time + ' )' ); <ide> <ide> THREE.KeyframeTrack.prototype = { <ide> if( this.keys[0].time >= time ) { <ide> <ide> //console.log( ' before: ' + this.keys[0].value ); <del> return this.keys[0].value; <add> this.setResult( this.keys[0].value ); <add> <add> //console.log( 'first result', this.result ) <add> <add> return this.result; <ide> <ide> } <ide> <ide> // past the end of the track, return the last key value <ide> if( this.keys[ this.keys.length - 1 ].time <= time ) { <ide> <ide> //console.log( ' after: ' + this.keys[ this.keys.length - 1 ].value ); <del> return this.keys[ this.keys.length - 1 ].value; <add> this.setResult( this.keys[ this.keys.length - 1 ].value ); <add> <add> //console.log( 'last result', this.result ) <add> <add> return this.result; <ide> <ide> } <ide> <ide> // interpolate to the required time <add> // TODO: Optimize this better than a linear search for each key. <ide> for( var i = 1; i < this.keys.length; i ++ ) { <ide> <ide> if( time <= this.keys[ i ].time ) { <ide> <ide> // linear interpolation to start with <ide> var alpha = ( time - this.keys[ i - 1 ].time ) / ( this.keys[ i ].time - this.keys[ i - 1 ].time ); <ide> <del> var interpolatedValue = this.lerp( this.keys[ i - 1 ].value, this.keys[ i ].value, alpha ); <add> this.setResult( this.keys[ i - 1 ].value ); <ide> <add> this.result = this.lerp( this.result, this.keys[ i ].value, alpha ); <add> //console.log( 'lerp result', this.result ) <ide> /*console.log( ' interpolated: ', { <ide> value: interpolatedValue, <ide> alpha: alpha, <ide> THREE.KeyframeTrack.prototype = { <ide> value1: this.keys[ i ].value <ide> } );*/ <ide> <del> return interpolatedValue; <add> return this.result; <ide> <ide> } <ide> } <ide> <ide> throw new Error( "should never get here." ); <ide> <ide> }, <add> setResult: function( value ) { <add> if( this.result.copy ) { <add> this.result.copy( value ); <add> } <add> else { <add> this.result = value; <add> } <add> }, <ide> <ide> // memoization of the lerp function for speed. <ide> // NOTE: Do not optimize as a prototype initialization closure, as value0 will be different on a per class basis. <ide><path>src/animation/PropertyBinding.js <ide> THREE.PropertyBinding.prototype = { <ide> <ide> if( this.cumulativeWeight === 0 ) { <ide> <del> this.cumulativeValue = value; <add> if( this.cumulativeValue === null ) { <add> this.cumulativeValue = THREE.AnimationUtils.clone( value ); <add> } <ide> this.cumulativeWeight = weight; <del> <add> //console.log( this ); <add> <ide> } <ide> else { <ide> <ide> var lerpAlpha = weight / ( this.cumulativeWeight + weight ); <ide> this.cumulativeValue = lerp( this.cumulativeValue, value, lerpAlpha ); <ide> this.cumulativeWeight += weight; <add> //console.log( this ); <ide> <ide> } <ide> }
3
Javascript
Javascript
remove unused variable
60ff02d81b7676da4fc0fc98b874eef99c8c9f1e
<ide><path>packages/ember-views/lib/system/sanitize_attribute_value.js <ide> /* jshint scripturl:true */ <ide> <del>var parsingNode; <ide> var badProtocols = { <ide> 'javascript:': true, <ide> 'vbscript:': true
1
PHP
PHP
extract registercreator method
0081f75ee8acc8c16fe3c165b7e41dacbbf14df5
<ide><path>src/Illuminate/Database/MigrationServiceProvider.php <ide> protected function registerInstallCommand() <ide> */ <ide> protected function registerMakeCommand() <ide> { <del> $this->app->bindShared('migration.creator', function($app) <del> { <del> return new MigrationCreator($app['files']); <del> }); <add> $this->registerCreator(); <ide> <ide> $this->app->bindShared('command.migrate.make', function($app) <ide> { <ide> protected function registerMakeCommand() <ide> }); <ide> } <ide> <add> /** <add> * Register the migration creator. <add> * <add> * @return void <add> */ <add> protected function registerCreator() <add> { <add> $this->app->bindShared('migration.creator', function($app) <add> { <add> return new MigrationCreator($app['files']); <add> }); <add> } <add> <ide> /** <ide> * Get the services provided by the provider. <ide> *
1
Ruby
Ruby
use in_memory_db? test helper
8a91f7293d16caeed04e1fd7fd1c26aafcd78ad5
<ide><path>activerecord/test/cases/migration/foreign_key_test.rb <ide> def test_schema_dumping_with_defferable_initially_immediate <ide> end <ide> end <ide> <del> def test_does_not_create_foreign_keys_when_bypassed_by_config <del> if current_adapter?(:SQLite3Adapter) && !ActiveRecord::Base.connection.supports_concurrent_connections? <del> skip("Can't reopen in-memory database") <del> else <del> begin <del> connection = ActiveRecord::Base.establish_connection( <del> { <del> adapter: "sqlite3", <del> database: "test/db/test.sqlite3", <del> foreign_keys: false, <del> } <del> ).connection <del> <del> connection.create_table "rockets", force: true do |t| <del> t.string :name <del> end <del> connection.create_table "astronauts", force: true do |t| <del> t.string :name <del> t.references :rocket <del> end <add> unless in_memory_db? <add> def test_does_not_create_foreign_keys_when_bypassed_by_config <add> connection = ActiveRecord::Base.establish_connection( <add> { <add> adapter: "sqlite3", <add> database: "test/db/test.sqlite3", <add> foreign_keys: false, <add> } <add> ).connection <add> <add> connection.create_table "rockets", force: true do |t| <add> t.string :name <add> end <add> connection.create_table "astronauts", force: true do |t| <add> t.string :name <add> t.references :rocket <add> end <ide> <del> connection.add_foreign_key :astronauts, :rockets <add> connection.add_foreign_key :astronauts, :rockets <ide> <del> foreign_keys = connection.foreign_keys("astronauts") <del> assert_equal 0, foreign_keys.size <del> ensure <del> connection.drop_table "astronauts", if_exists: true rescue nil <del> connection.drop_table "rockets", if_exists: true rescue nil <add> foreign_keys = connection.foreign_keys("astronauts") <add> assert_equal 0, foreign_keys.size <add> ensure <add> connection.drop_table "astronauts", if_exists: true rescue nil <add> connection.drop_table "rockets", if_exists: true rescue nil <ide> <del> ActiveRecord::Base.establish_connection(:arunit) <del> end <add> ActiveRecord::Base.establish_connection(:arunit) <ide> end <ide> end <ide> <ide><path>activerecord/test/cases/schema_dumper_test.rb <ide> def test_do_not_dump_foreign_keys_for_ignored_tables <ide> assert_equal ["authors"], output.scan(/^\s*add_foreign_key "([^"]+)".+$/).flatten <ide> end <ide> <del> def test_do_not_dump_foreign_keys_when_bypassed_by_config <del> if current_adapter?(:SQLite3Adapter) && !ActiveRecord::Base.connection.supports_concurrent_connections? <del> skip("Can't reopen in-memory database") <del> end <del> <del> begin <add> unless in_memory_db? <add> def test_do_not_dump_foreign_keys_when_bypassed_by_config <ide> ActiveRecord::Base.establish_connection( <ide> { <ide> adapter: "sqlite3",
2
PHP
PHP
remove unique index
4df192314896f4afe5da51f68fb689186bbc8526
<ide><path>src/Illuminate/Database/Migrations/DatabaseMigrationRepository.php <ide> public function createRepository() <ide> // The migrations table is responsible for keeping track of which of the <ide> // migrations have actually run for the application. We'll create the <ide> // table to hold the migration file's path as well as the batch ID. <del> $table->string('migration')->unique(); <add> $table->string('migration'); <ide> <ide> $table->integer('batch'); <ide> });
1
PHP
PHP
correct doc block
3100118a4e7d5b90a0b58235888a51cd670dcceb
<ide><path>lib/Cake/Utility/String.php <ide> public static function uuid() { <ide> * @param string $separator The token to split the data on. <ide> * @param string $leftBound The left boundary to ignore separators in. <ide> * @param string $rightBound The right boundary to ignore separators in. <del> * @return array Array of tokens in $data. <add> * @return mixed Array of tokens in $data or original input if empty. <ide> */ <ide> public static function tokenize($data, $separator = ',', $leftBound = '(', $rightBound = ')') { <ide> if (empty($data) || is_array($data)) {
1
PHP
PHP
prevent repeated calls
8ea72714480e03c0288f80ac0bed5265381222ba
<ide><path>src/Illuminate/Foundation/Testing/CrawlerTrait.php <ide> protected function seeJsonContains(array $data) <ide> $expected = $this->formatToExpectedJson($key, $value); <ide> <ide> $this->assertTrue( <del> Str::contains($actual, $this->formatToExpectedJson($key, $value)), <add> Str::contains($actual, $expected), <ide> "Unable to find JSON fragment [{$expected}] within [{$actual}]." <ide> ); <ide> }
1
Javascript
Javascript
add comments to describe the modification
9b781b1542ac5376d4f58f92c38b5f191bc0d6d7
<ide><path>examples/js/loaders/STLLoader.js <ide> THREE.STLLoader.prototype = { <ide> <ide> } <ide> <add> // some binary files will have different size from expected, <add> // checking characters higher than ASCII to confirm is binary <ide> var fileLength = reader.byteLength; <del> <ide> for ( var index = 0; index < fileLength; index ++ ) { <ide> <ide> if ( reader.getUint8(index, false) > 127 ) {
1
PHP
PHP
fix method descriptions in frozentime
4e35047d26f23b350124704cbfac0f04ab80d950
<ide><path>src/I18n/FrozenTime.php <ide> public static function listTimezones($filter = null, $country = null, $options = <ide> } <ide> <ide> /** <del> * Returns true this instance will happen within the specified interval <add> * Returns true this instance happened within the specified interval <ide> * <ide> * This overridden method provides backwards compatible behavior for integers, <ide> * or strings with trailing spaces. This behavior is *deprecated* and will be <ide> public function wasWithinLast($timeInterval) <ide> } <ide> <ide> /** <del> * Returns true this instance happened within the specified interval <add> * Returns true this instance will happen within the specified interval <ide> * <ide> * This overridden method provides backwards compatible behavior for integers, <ide> * or strings with trailing spaces. This behavior is *deprecated* and will be
1
Text
Text
modify guides for a better sounding sentence
b7aa845c018f3b01e70f274a9b30112276a6dcaa
<ide><path>guides/source/getting_started.md <ide> second argument, and then the options as another argument. The `method: :delete` <ide> and `data: { confirm: 'Are you sure?' }` options are used as HTML5 attributes so <ide> that when the link is clicked, Rails will first show a confirm dialog to the <ide> user, and then submit the link with method `delete`. This is done via the <del>JavaScript file `jquery_ujs` which is automatically included into your <add>JavaScript file `jquery_ujs` which is automatically included in your <ide> application's layout (`app/views/layouts/application.html.erb`) when you <del>generated the application. Without this file, the confirmation dialog box <del>wouldn't appear. <add>generated the application. Without this file, the confirmation dialog box won't <add>appear. <ide> <ide> ![Confirm Dialog](images/getting_started/confirm_dialog.png) <ide>
1
Text
Text
change "ocsp request" to "ocsp request"
84ea25223eca444e9eeb259d5b38db08db12b2f3
<ide><path>doc/api/tls.md <ide> no OCSP response. <ide> <ide> Calling `callback(err)` will result in a `socket.destroy(err)` call. <ide> <del>The typical flow of an OCSP Request is as follows: <add>The typical flow of an OCSP request is as follows: <ide> <ide> 1. Client connects to the server and sends an `'OCSPRequest'` (via the status <ide> info extension in ClientHello).
1
Java
Java
adjust checkforleaks timeout settings
3d89acf9ea0bce8c41d2084b55e7eca15d481be4
<ide><path>spring-core/src/test/java/org/springframework/core/codec/ResourceRegionEncoderTests.java <ide> void canEncode() { <ide> } <ide> <ide> @Test <del> void shouldEncodeResourceRegionFileResource() throws Exception { <add> void shouldEncodeResourceRegionFileResource() { <ide> ResourceRegion region = new ResourceRegion( <ide> new ClassPathResource("ResourceRegionEncoderTests.txt", getClass()), 0, 6); <ide> Flux<DataBuffer> result = this.encoder.encode(Mono.just(region), this.bufferFactory, <ide><path>spring-core/src/test/java/org/springframework/core/io/buffer/LeakAwareDataBufferFactoryTests.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2022 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> class LeakAwareDataBufferFactoryTests { <ide> void leak() { <ide> DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(); <ide> try { <del> assertThatExceptionOfType(AssertionError.class).isThrownBy( <del> this.bufferFactory::checkForLeaks); <add> assertThatExceptionOfType(AssertionError.class).isThrownBy(this.bufferFactory::checkForLeaks); <ide> } <ide> finally { <ide> release(dataBuffer); <ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/AbstractLeakCheckingTests.java <ide> <ide> package org.springframework.core.testfixture.io.buffer; <ide> <add>import java.time.Duration; <add> <ide> import org.junit.jupiter.api.AfterEach; <ide> <ide> import org.springframework.core.io.buffer.DataBufferFactory; <ide> public abstract class AbstractLeakCheckingTests { <ide> */ <ide> @AfterEach <ide> final void checkForLeaks() { <del> this.bufferFactory.checkForLeaks(); <add> this.bufferFactory.checkForLeaks(Duration.ofSeconds(1)); <ide> } <ide> <ide> } <ide><path>spring-core/src/testFixtures/java/org/springframework/core/testfixture/io/buffer/LeakAwareDataBufferFactory.java <ide> public LeakAwareDataBufferFactory(DataBufferFactory delegate) { <ide> * method. <ide> */ <ide> public void checkForLeaks() { <add> checkForLeaks(Duration.ofSeconds(0)); <add> } <add> <add> /** <add> * Variant of {@link #checkForLeaks()} with the option to wait for buffer release. <add> * @param timeout how long to wait for buffers to be released; 0 for no waiting <add> */ <add> public void checkForLeaks(Duration timeout) { <ide> this.trackCreated.set(false); <ide> Instant start = Instant.now(); <ide> while (true) { <ide> if (this.created.stream().noneMatch(LeakAwareDataBuffer::isAllocated)) { <ide> return; <ide> } <del> if (Instant.now().isBefore(start.plus(Duration.ofSeconds(5)))) { <add> if (Instant.now().isBefore(start.plus(timeout))) { <ide> try { <ide> Thread.sleep(50); <ide> }
4
Ruby
Ruby
run multiple files on runner
b58c0914f4d85faa39f22eb3408970ac8a176913
<ide><path>railties/lib/rails/test_unit/runner.rb <ide> def self.parse(args) <ide> <ide> opt_parser.order!(args) <ide> <del> if arg = args.shift <add> options[:patterns] = [] <add> while arg = args.shift <ide> if Dir.exists?(arg) <del> options[:pattern] = "#{arg}/**/*_test.rb" <add> options[:patterns] << "#{arg}/**/*_test.rb" <ide> else <ide> options[:filename], options[:line] = arg.split(':') <ide> options[:filename] = File.expand_path options[:filename] <ide> def run_tests <ide> <ide> def test_files <ide> return [@options[:filename]] if @options[:filename] <del> if @options[:pattern] <del> pattern = @options[:pattern] <add> if @options[:patterns] <add> pattern = @options[:patterns] <ide> else <ide> pattern = "test/**/*_test.rb" <ide> end <ide><path>railties/test/test_unit/runner_test.rb <ide> class TestUnitTestRunnerTest < ActiveSupport::TestCase <ide> test "run all tests in a directory" do <ide> options = @options.parse([__dir__]) <ide> <del> assert_equal "#{__dir__}/**/*_test.rb", options[:pattern] <add> assert_equal ["#{__dir__}/**/*_test.rb"], options[:patterns] <ide> assert_nil options[:filename] <ide> assert_nil options[:line] <ide> end <ide> <ide> test "run multiple files" do <del> skip "needs implementation" <add> application_dir = File.expand_path("#{__dir__}/../application") <add> options = @options.parse([__dir__, application_dir]) <add> <add> assert_equal ["#{__dir__}/**/*_test.rb", "#{application_dir}/**/*_test.rb"], options[:patterns] <add> assert_nil options[:filename] <add> assert_nil options[:line] <add> end <add> <add> test "run multiple files and run one file by line" do <add> line = __LINE__ <add> options = @options.parse([__dir__, "#{__FILE__}:#{line}"]) <add> <add> assert_equal ["#{__dir__}/**/*_test.rb"], options[:patterns] <add> assert_equal __FILE__, options[:filename] <add> assert_equal line, options[:line] <ide> end <ide> end
2
Text
Text
update webcrypto docs for global access
46dcfb3c7be167ed27a3e8db4e40ff8b17d892fb
<ide><path>doc/api/webcrypto.md <ide> changes: <ide> <ide> Node.js provides an implementation of the standard [Web Crypto API][]. <ide> <del>Use `require('node:crypto').webcrypto` to access this module. <add>Use `globalThis.crypto` or `require('node:crypto').webcrypto` to access this <add>module. <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> (async function() { <ide> <ide> or asymmetric key pairs (public key and private key). <ide> #### AES keys <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function generateAesKey(length = 256) { <ide> const key = await subtle.generateKey({ <ide> async function generateAesKey(length = 256) { <ide> #### ECDSA key pairs <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function generateEcKey(namedCurve = 'P-521') { <ide> const { <ide> async function generateEcKey(namedCurve = 'P-521') { <ide> > Stability: 1 - Experimental <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function generateEd25519Key() { <ide> return subtle.generateKey({ <ide> async function generateX25519Key() { <ide> #### HMAC keys <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function generateHmacKey(hash = 'SHA-256') { <ide> const key = await subtle.generateKey({ <ide> async function generateHmacKey(hash = 'SHA-256') { <ide> #### RSA key pairs <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> const publicExponent = new Uint8Array([1, 0, 1]); <ide> <ide> async function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') { <ide> async function generateRsaKey(modulusLength = 2048, hash = 'SHA-256') { <ide> ### Encryption and decryption <ide> <ide> ```js <del>const crypto = require('node:crypto').webcrypto; <add>const crypto = globalThis.crypto; <ide> <ide> async function aesEncrypt(plaintext) { <ide> const ec = new TextEncoder(); <ide> async function aesDecrypt(ciphertext, key, iv) { <ide> ### Exporting and importing keys <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function generateAndExportHmacKey(format = 'jwk', hash = 'SHA-512') { <ide> const key = await subtle.generateKey({ <ide> async function importHmacKey(keyData, format = 'jwk', hash = 'SHA-512') { <ide> ### Wrapping and unwrapping keys <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function generateAndWrapHmacKey(format = 'jwk', hash = 'SHA-512') { <ide> const [ <ide> async function unwrapHmacKey( <ide> ### Sign and verify <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function sign(key, data) { <ide> const ec = new TextEncoder(); <ide> async function verify(key, signature, data) { <ide> ### Deriving bits and keys <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function pbkdf2(pass, salt, iterations = 1000, length = 256) { <ide> const ec = new TextEncoder(); <ide> async function pbkdf2Key(pass, salt, iterations = 1000, length = 256) { <ide> ### Digest <ide> <ide> ```js <del>const { subtle } = require('node:crypto').webcrypto; <add>const { subtle } = globalThis.crypto; <ide> <ide> async function digest(data, algorithm = 'SHA-512') { <ide> const ec = new TextEncoder(); <ide> implementation and the APIs supported for each: <ide> added: v15.0.0 <ide> --> <ide> <del>Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` <add>`globalThis.crypto` is an instance of the `Crypto` <ide> class. `Crypto` is a singleton that provides access to the remainder of the <ide> crypto API. <ide>
1
Javascript
Javascript
fix bug in 'y' tooltip mode
274aa290ca69f38aac5fd1a5fb55cc5043ea5d8c
<ide><path>src/core/core.interaction.js <ide> module.exports = function(Chart) { <ide> var position = helpers.getRelativePosition(e, chart.chart); <ide> var items = []; <ide> parseVisibleItems(chart, function(element) { <del> if (element.inYRange(position.x)) { <add> if (element.inYRange(position.y)) { <ide> items.push(element); <ide> } <ide> });
1
Javascript
Javascript
remove redundant checks
ce50b6c0cdd50ec1fe380704aa1efec07a16b419
<ide><path>src/renderers/WebGLRenderer.js <ide> function WebGLRenderer( parameters ) { <ide> var size = geometryAttribute.itemSize; <ide> var buffer = objects.getAttributeBuffer( geometryAttribute ); <ide> <del> if ( geometryAttribute && geometryAttribute.isInterleavedBufferAttribute ) { <add> if ( geometryAttribute.isInterleavedBufferAttribute ) { <ide> <ide> var data = geometryAttribute.data; <ide> var stride = data.stride; <ide> function WebGLRenderer( parameters ) { <ide> <ide> } else { <ide> <del> if ( geometryAttribute && geometryAttribute.isInstancedBufferAttribute ) { <add> if ( geometryAttribute.isInstancedBufferAttribute ) { <ide> <ide> state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension ); <ide>
1
Ruby
Ruby
fix latest_tag error
f345f554c898748967a0b7768387d88eaa03176d
<ide><path>Library/Homebrew/dev-cmd/update-license-data.rb <ide> def update_license_data <ide> ohai "git add" <ide> safe_system "git", "add", SPDX::JSON_PATH <ide> ohai "git commit" <del> system "git", "commit", "--message", "data/spdx.json: update to #{latest_tag}" <add> system "git", "commit", "--message", "data/spdx.json: update to #{SPDX.latest_tag}" <ide> end <ide> end <ide><path>Library/Homebrew/utils/spdx.rb <ide> def spdx_data <ide> @spdx_data ||= JSON.parse(JSON_PATH.read) <ide> end <ide> <add> def latest_tag <add> @latest_tag ||= GitHub.open_api(API_URL)["tag_name"] <add> end <add> <ide> def download_latest_license_data!(to: JSON_PATH) <del> latest_tag = GitHub.open_api(API_URL)["tag_name"] <ide> data_url = "https://raw.githubusercontent.com/spdx/license-list-data/#{latest_tag}/json/licenses.json" <ide> curl_download(data_url, to: to, partial: false) <ide> end
2
Text
Text
release readme file for example project
707c4ef8b769eda7127e91b3f0175a849a09b824
<ide><path>official/vision/beta/projects/example/README.md <add># TF Vision Example Project <add> <add>This is a minimal example project to demonstrate how to use TF Model Garden's <add>building blocks to implement a new vision project from scratch. <add> <add>Below we use classification as an example. We will walk you through the process <add>of creating a new projects leveraging existing components, such as tasks, data <add>loaders, models, etc. You will get better understanding of these components by <add>going through the process. You can also refer to the docstring of corresponding <add>components to get more information. <add> <add>## Create Model <add> <add>In <add>[example_model.py](example_model.py), <add>we show how to create a new model. The `ExampleModel` is a subclass of <add>`tf.keras.Model` that defines necessary parameters. Here, you need to have <add>`input_specs` to specify the input shape and dimensions, and build layers within <add>constructor: <add> <add>```python <add>class ExampleModel(tf.keras.Model): <add> def __init__( <add> self, <add> num_classes: int, <add> input_specs: tf.keras.layers.InputSpec = tf.keras.layers.InputSpec( <add> shape=[None, None, None, 3]), <add> **kwargs): <add> # Build layers. <add>``` <add> <add>Given the `ExampleModel`, you can define a function that takes a model config as <add>input and return an `ExampleModel` instance, similar as <add>[build_example_model](example_model.py#L80). <add>As a simple example, we define a single model. However, you can split the model <add>implementation to individual components, such as backbones, decoders, heads, as <add>what we do <add>[here](https://github.com/tensorflow/models/blob/master/official/vision/beta/modeling). <add>And then in `build_example_model` function, you can hook up these components <add>together to obtain your full model. <add> <add>## Create Dataloader <add> <add>A dataloader reads, decodes and parses the input data. We have created various <add>[dataloaders](https://github.com/tensorflow/models/blob/master/official/vision/beta/dataloaders) <add>to handle standard input formats for classification, detection and segmentation. <add>If you have non-standard or complex data, you may want to create your own <add>dataloader. It contains a `Decoder` and a `Parser`. <add> <add>- The <add> [Decoder](example_input.py#L33) <add> decodes a TF Example record and returns a dictionary of decoded tensors: <add> <add> ```python <add> class Decoder(decoder.Decoder): <add> """A tf.Example decoder for classification task.""" <add> def __init__(self): <add> """Initializes the decoder. <add> <add> The constructor defines the mapping between the field name and the value <add> from an input tf.Example. For example, we define two fields for image bytes <add> and labels. There is no limit on the number of fields to decode. <add> """ <add> self._keys_to_features = { <add> 'image/encoded': <add> tf.io.FixedLenFeature((), tf.string, default_value=''), <add> 'image/class/label': <add> tf.io.FixedLenFeature((), tf.int64, default_value=-1) <add> } <add> ``` <add> <add>- The <add> [Parser](example_input.py#L68) <add> parses the decoded tensors and performs pre-processing to the input data, <add> such as image decoding, augmentation and resizing, etc. It should have <add> `_parse_train_data` and `_parse_eval_data` functions, in which the processed <add> images and labels are returned. <add> <add>## Create Config <add> <add>Next you will define configs for your project. All configs are defined as <add>`dataclass` objects, and can have default parameter values. <add> <add>First, you will define your <add>[`ExampleDataConfig`](example_config.py#L27). <add>It inherits from `config_definitions.DataConfig` that already defines a few <add>common fields, like `input_path`, `file_type`, `global_batch_size`, etc. You can <add>add more fields in your own config as needed. <add> <add>You can then define you model config <add>[`ExampleModel`](example_config.py#L39) <add>that inherits from `hyperparams.Config`. Expose your own model parameters here. <add> <add>You can then define your `Loss` and `Evaluation` configs. <add> <add>Next, you will put all the above configs into an <add>[`ExampleTask`](example_config.py#L56) <add>config. Here you list the configs for your data, model, loss, and evaluation, <add>etc. <add> <add>Finally, you can define a <add>[`tf_vision_example_experiment`](example_config.py#L66), <add>which creates a template for your experiments and fills with default parameters. <add>These default parameter values can be overridden by a YAML file, like <add>[example_config_tpu.yaml](example_config_tpu.yaml). <add>Also, make sure you give a unique name to your experiment template by the <add>decorator: <add> <add>```python <add>@exp_factory.register_config_factory('tf_vision_example_experiment') <add>def tf_vision_example_experiment() -> cfg.ExperimentConfig: <add> """Definition of a full example experiment.""" <add> # Create and return experiment template. <add>``` <add> <add>## Create Task <add> <add>A task is a class that encapsules the logic of loading data, building models, <add>performing one-step training and validation, etc. It connects all components <add>together and is called by the base <add>[Trainer](https://github.com/tensorflow/models/blob/master/official/core/base_trainer.py). <add> <add>You can create your own task by inheriting from base <add>[Task](https://github.com/tensorflow/models/blob/master/official/core/base_task.py), <add>or from one of the <add>[tasks](https://github.com/tensorflow/models/blob/master/official/vision/beta/tasks/) <add>we already defined, if most of the operations can be reused. An `ExampleTask` <add>inheriting from <add>[ImageClassificationTask](https://github.com/tensorflow/models/blob/master/official/vision/beta/tasks/image_classification.py#L32) <add>can be found <add>[here](example_task.py). <add>We will go through each important components in the task in the following. <add> <add>- `build_model`: you can instantiate a model you have defined above. It is <add> also good practice to run forward pass with a dummy input to ensure layers <add> within the model are properly initialized. <add> <add>- `build_inputs`: here you can instantiate a Decoder object and a Parser <add> object. They are used to create an `InputReader` that will generate a <add> `tf.data.Dataset` object. <add> <add>- `build_losses`: it takes groundtruth labels and model outputs as input, and <add> computes the loss. It will be called in `train_step` and `validation_step`. <add> You can also define different losses for training and validation, for <add> example, `build_train_losses` and `build_validation_losses`. Just make sure <add> they are called by the corresponding functions properly. <add> <add>- `build_metrics`: here you can define your own metrics. It should return a <add> list of `tf.keras.metrics.Metric` objects. You can create your own metric <add> class by subclassing `tf.keras.metrics.Metric`. <add> <add>- `train_step` and `validation_step`: they perform one-step training and <add> validation. They take one batch of training/validation data, run forward <add> pass, gather losses and update metrics. They assume the data format is <add> consistency with that from the `Parser` output. `train_step` also contains <add> backward pass to update model weights. <add> <add>## Import registry <add> <add>To use your custom dataloaders, models, tasks, etc., you will need to register <add>them properly. The recommended way is to have a single file with all relevant <add>files imported, for example, <add>[registry_imports.py](registry_imports.py). <add>You can see in this file we import all our custom components: <add> <add>```python <add># pylint: disable=unused-import <add>from official.common import registry_imports <add>from official.vision.beta.projects.example import example_config <add>from official.vision.beta.projects.example import example_input <add>from official.vision.beta.projects.example import example_model <add>from official.vision.beta.projects.example import example_task <add>``` <add> <add>## Training <add> <add>You can create your own trainer by branching from our core <add>[trainer](https://github.com/tensorflow/models/blob/master/official/vision/beta/train.py). <add>Just make sure you import the registry like this: <add> <add>```python <add>from official.vision.beta.projects.example import registry_imports # pylint: disable=unused-import <add>``` <add> <add>You can run training locally for testing purpose: <add> <add>```bash <add># Assume you are under official/vision/beta/projects. <add>python3 example/train.py \ <add> --experiment=tf_vision_example_experiment \ <add> --config_file=${PWD}/example/example_config_local.yaml \ <add> --mode=train \ <add> --model_dir=/tmp/tfvision_test/ <add>``` <add> <add>It can also run on Google Cloud using Cloud TPU. <add>[Here](https://cloud.google.com/tpu/docs/how-to) is the instruction of using <add>Cloud TPU and here is a more detailed <add>[tutorial](https://cloud.google.com/tpu/docs/tutorials/resnet-rs-2.x) of <add>training a ResNet-RS model. Following the instructions to set up Cloud TPU and <add>launch training by: <add> <add>```bash <add>EXP_TYPE=tf_vision_example_experiment # This should match the registered name of your experiment template. <add>EXP_NAME=exp_001 # You can give any name to the experiment. <add>TPU_NAME=experiment01 <add># Now launch the experiment. <add>python3 example/train.py \ <add> --experiment=$EXP_TYPE \ <add> --mode=train \ <add> --tpu=$TPU_NAME \ <add> --model_dir=/tmp/tfvision_test/ <add> --config_file=third_party/tensorflow_models/official/vision/beta/projects/example/example_config_tpu.yaml <add>```
1
PHP
PHP
implement simple methods in associations class
766f1db16e2fdd5ce88222d8605b7f3a520fc998
<ide><path>Cake/ORM/Associations.php <ide> <?php <ide> /** <del> * PHP Version 5.4 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> */ <ide> namespace Cake\ORM; <ide> <add>use Cake\ORM\Association; <add>use Cake\ORM\Entity; <add> <ide> /** <ide> * A container/collection for association classes. <ide> * <ide> */ <ide> class Associations { <ide> <add> protected $_items = []; <add> <add>/** <add> * Add an association to the collection <add> * <add> * @param string $alias The association alias <add> * @param Association The association to add. <add> * @return void <add> */ <ide> public function add($alias, Association $association) { <add> $this->_items[strtolower($alias)] = $association; <ide> } <ide> <add>/** <add> * Fetch an attached association by name. <add> * <add> * @param string $alias The association alias to get. <add> * @return Association|null Either the association or null. <add> */ <ide> public function get($alias) { <add> $alias = strtolower($alias); <add> if (isset($this->_items[$alias])) { <add> return $this->_items[$alias]; <add> } <add> return null; <ide> } <ide> <add>/** <add> * Check for an attached association by name. <add> * <add> * @param string $alias The association alias to get. <add> * @return boolean Whether or not the association exists. <add> */ <ide> public function has($alias) { <add> return isset($this->_items[strtolower($alias)]); <ide> } <ide> <ide> public function drop($alias) { <ide><path>Cake/Test/TestCase/ORM/AssociationsTest.php <add><?php <add>/** <add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) <add> * @link http://cakephp.org CakePHP(tm) Project <add> * @since CakePHP(tm) v 3.0.0 <add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <add> */ <add>namespace Cake\Test\TestCase\ORM; <add> <add>use Cake\ORM\Association\BelongsTo; <add>use Cake\ORM\Associations; <add>use Cake\TestSuite\TestCase; <add> <add>/** <add> * Associations test case. <add> */ <add>class AssociationsTest extends TestCase { <add> <add>/** <add> * setup <add> * <add> * @return void <add> */ <add> public function setUp() { <add> parent::setUp(); <add> $this->associations = new Associations(); <add> } <add> <add>/** <add> * Test the simple add/has and get methods. <add> * <add> * @return void <add> */ <add> public function testAddHasAndGet() { <add> $this->assertFalse($this->associations->has('users')); <add> $this->assertFalse($this->associations->has('Users')); <add> <add> $this->assertNull($this->associations->get('users')); <add> $this->assertNull($this->associations->get('Users')); <add> <add> $belongsTo = new BelongsTo([]); <add> $this->assertNull($this->associations->add('Users', $belongsTo)); <add> $this->assertTrue($this->associations->has('users')); <add> $this->assertTrue($this->associations->has('Users')); <add> <add> $this->assertSame($belongsTo, $this->associations->get('users')); <add> $this->assertSame($belongsTo, $this->associations->get('Users')); <add> } <add> <add>}
2
Text
Text
fix typos in readme.md and examples/readme.md
38086edaaaa3eae4a3439ff7c18bb1fa720a8660
<ide><path>README.md <ide> define(["amd-module", "../file"], function (amdModule, file) { <ide> // this is async <ide> require(["big-module/big/file"], function (big) { <ide> // For async dependencies, webpack splits <del> // your application into multiple "chunks." <add> // your application into multiple "chunks". <ide> // This part of your application is <ide> // loaded on demand (code-splitting). <ide> var stuff = require("../my/stuff"); <ide><path>examples/README.md <ide> <ide> ## commonjs <ide> <del>example demonstrating a very simple programm <add>example demonstrating a very simple program <ide> <ide> ## code-splitting <ide> <ide> example demonstrating a very simple case of Code Splitting. <ide> <ide> ## require.resolve <ide> <del>example demonstrating to cache clearing of modules with `require.resolve` and `require.cache`. <add>example demonstrating how to cache clearing of modules with `require.resolve` and `require.cache`. <ide> <ide> ## require.context <ide> <del>example demonstrating to automatic creation of contexts when using variables in `require`. <add>example demonstrating automatic creation of contexts when using variables in `require`. <ide> <ide> ## code-splitted-require.context <ide> <ide> example demonstrating contexts in a code-split environment with AMD. <ide> <ide> ## loader <ide> <del>example demonstrating to usage of loaders. <add>example demonstrating the usage of loaders. <ide> <ide> ## coffee-script <ide> <ide> example demonstrating Labeled Modules <ide> <ide> ## mixed <ide> <del>example demonstrating mixing CommonJs, AMD and Labeled Modules <add>example demonstrating mixing CommonJs, AMD, and Labeled Modules <ide> <ide> ## web-worker <ide> <ide> example demonstrating multiple entry points with Code Splitting. <ide> <ide> # Requests <ide> <del>If you think a example is missing, please report it as issue. :) <add>If you think an example is missing, please report it as issue. :) <ide> <ide> # Build <ide>
2
Ruby
Ruby
avoid formula lookup when we know it will fail
26a2e4c4d38f111ab89093c12e3532529fc8da0b
<ide><path>Library/Homebrew/formulary.rb <ide> def get_formula(spec) <ide> end <ide> end <ide> <add> class NullLoader < FormulaLoader <add> def initialize(name) <add> @name = name <add> end <add> <add> def get_formula(spec) <add> raise FormulaUnavailableError.new(name) <add> end <add> end <add> <ide> # Return a Formula instance for the given reference. <ide> # `ref` is string containing: <ide> # * a formula name <ide> def self.loader_for(ref) <ide> return FormulaLoader.new(ref, possible_cached_formula) <ide> end <ide> <del> return FormulaLoader.new(ref, Formula.path(ref)) <add> return NullLoader.new(ref) <ide> end <ide> end
1
Java
Java
remove unnecessary imports
40ea9ffd636923275af2788939f12a29459db476
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebConnection.java <ide> import org.springframework.test.web.servlet.MockMvc; <ide> import org.springframework.test.web.servlet.RequestBuilder; <ide> import org.springframework.test.web.servlet.ResultActions; <del>import org.springframework.test.web.servlet.htmlunit.webdriver.WebConnectionHtmlUnitDriver; <ide> import org.springframework.util.Assert; <ide> <ide> import com.gargoylesoftware.htmlunit.WebClient; <ide> * @author Rob Winch <ide> * @author Sam Brannen <ide> * @since 4.2 <del> * @see WebConnectionHtmlUnitDriver <add> * @see org.springframework.test.web.servlet.htmlunit.webdriver.WebConnectionHtmlUnitDriver <ide> */ <ide> public final class MockMvcWebConnection implements WebConnection { <ide> <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/htmlunit/webdriver/WebConnectionHtmlUnitDriver.java <ide> import org.openqa.selenium.Capabilities; <ide> import org.openqa.selenium.htmlunit.HtmlUnitDriver; <ide> <del>import org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection; <ide> import org.springframework.util.Assert; <ide> <ide> import com.gargoylesoftware.htmlunit.BrowserVersion; <ide> * {@code WebConnectionHtmlUnitDriver} enables configuration of the <ide> * {@link WebConnection} for an {@link HtmlUnitDriver} instance. <ide> * <del> * <p>This is useful because it allows a {@link MockMvcWebConnection} to <del> * be injected. <add> * <p>This is useful because it allows a <add> * {@link org.springframework.test.web.servlet.htmlunit.MockMvcWebConnection <add> * MockMvcWebConnection} to be injected. <ide> * <ide> * @author Rob Winch <ide> * @author Sam Brannen
2
Python
Python
test the best dev acc model when model is training
3c7e676f8b3cafd501a2616030f4bd1e512212f9
<ide><path>examples/single_model_scripts/run_multiple_choice.py <ide> def train(args, train_dataset, model, tokenizer): <ide> results = evaluate(args, model, tokenizer) <ide> for key, value in results.items(): <ide> tb_writer.add_scalar('eval_{}'.format(key), value, global_step) <del> if results["eval_loss"] < best_dev_loss: <add> if results["eval_acc"] < best_dev_acc: <ide> best_dev_acc = results["eval_acc"] <ide> best_dev_loss = results["eval_loss"] <ide> best_steps = global_step <ide> def main(): <ide> model.to(args.device) <ide> <ide> logger.info("Training/evaluation parameters %s", args) <del> <add> best_steps = 0 <ide> <ide> # Training <ide> if args.do_train: <ide> train_dataset = load_and_cache_examples(args, args.task_name, tokenizer, evaluate=False) <del> global_step, tr_loss, _ = train(args, train_dataset, model, tokenizer) <add> global_step, tr_loss, best_steps = train(args, train_dataset, model, tokenizer) <ide> logger.info(" global_step = %s, average loss = %s", global_step, tr_loss) <ide> <ide> <ide> def main(): <ide> if not args.do_train: <ide> args.output_dir = args.model_name_or_path <ide> checkpoints = [args.output_dir] <del> if args.eval_all_checkpoints: <add> if args.eval_all_checkpoints: #can not use this to do test!! just for different paras <ide> checkpoints = list(os.path.dirname(c) for c in sorted(glob.glob(args.output_dir + '/**/' + WEIGHTS_NAME, recursive=True))) <ide> logging.getLogger("pytorch_transformers.modeling_utils").setLevel(logging.WARN) # Reduce logging <ide> logger.info("Evaluate the following checkpoints: %s", checkpoints) <ide> def main(): <ide> result = evaluate(args, model, tokenizer, prefix=global_step, test=True) <ide> result = dict((k + '_{}'.format(global_step), v) for k, v in result.items()) <ide> results.update(result) <del> <add> if best_steps: <add> logger.info("best steps of eval acc is the following checkpoints: %s", best_steps) <ide> return results <ide> <ide>
1
Java
Java
allow custom instances of webjarassetlocator
977840884bf9c670a88bac1aeee3b3c8f1f9bf7b
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ResourceChainRegistration.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public class ResourceChainRegistration { <ide> <ide> private boolean hasCssLinkTransformer; <ide> <add> private boolean hasWebjarsResolver; <add> <ide> <ide> public ResourceChainRegistration(boolean cacheResources) { <ide> this(cacheResources, cacheResources ? new ConcurrentMapCache(DEFAULT_CACHE_NAME) : null); <ide> public ResourceChainRegistration addResolver(ResourceResolver resolver) { <ide> else if (resolver instanceof PathResourceResolver) { <ide> this.hasPathResolver = true; <ide> } <add> else if (resolver instanceof WebJarsResourceResolver) { <add> this.hasWebjarsResolver = true; <add> } <ide> return this; <ide> } <ide> <ide> public ResourceChainRegistration addTransformer(ResourceTransformer transformer) <ide> protected List<ResourceResolver> getResourceResolvers() { <ide> if (!this.hasPathResolver) { <ide> List<ResourceResolver> result = new ArrayList<ResourceResolver>(this.resolvers); <del> if (isWebJarsAssetLocatorPresent) { <add> if (isWebJarsAssetLocatorPresent && !this.hasWebjarsResolver) { <ide> result.add(new WebJarsResourceResolver()); <ide> } <ide> result.add(new PathResourceResolver()); <ide> protected List<ResourceResolver> getResourceResolvers() { <ide> } <ide> <ide> protected List<ResourceTransformer> getResourceTransformers() { <del> if (this.hasVersionResolver && !this.hasCssLinkTransformer) { <add> if (this.hasVersionResolver && !this.hasCssLinkTransformer) { <ide> List<ResourceTransformer> result = new ArrayList<ResourceTransformer>(this.transformers); <ide> boolean hasTransformers = !this.transformers.isEmpty(); <ide> boolean hasCaching = hasTransformers && this.transformers.get(0) instanceof CachingResourceTransformer; <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/WebJarsResourceResolver.java <ide> package org.springframework.web.servlet.resource; <ide> <ide> import java.util.List; <add> <ide> import javax.servlet.http.HttpServletRequest; <ide> <ide> import org.webjars.MultipleMatchesException; <ide> public class WebJarsResourceResolver extends AbstractResourceResolver { <ide> <ide> private final static int WEBJARS_LOCATION_LENGTH = WEBJARS_LOCATION.length(); <ide> <del> private final WebJarAssetLocator webJarAssetLocator = new WebJarAssetLocator(); <add> private final WebJarAssetLocator webJarAssetLocator; <add> <add> /** <add> * Create a {@code WebJarsResourceResolver} with a default {@code WebJarAssetLocator} instance. <add> */ <add> public WebJarsResourceResolver() { <add> this(new WebJarAssetLocator()); <add> } <ide> <add> /** <add> * Create a {@code WebJarsResourceResolver} with a custom {@code WebJarAssetLocator} instance, <add> * e.g. with a custom index. <add> * @since 4.3.0 <add> */ <add> public WebJarsResourceResolver(WebJarAssetLocator webJarAssetLocator) { <add> this.webJarAssetLocator = webJarAssetLocator; <add> } <ide> <ide> @Override <ide> protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath, <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ResourceHandlerRegistryTests.java <ide> public void resourceChainWithVersionResolver() throws Exception { <ide> public void resourceChainWithOverrides() throws Exception { <ide> CachingResourceResolver cachingResolver = Mockito.mock(CachingResourceResolver.class); <ide> VersionResourceResolver versionResolver = Mockito.mock(VersionResourceResolver.class); <add> WebJarsResourceResolver webjarsResolver = Mockito.mock(WebJarsResourceResolver.class); <ide> PathResourceResolver pathResourceResolver = new PathResourceResolver(); <ide> CachingResourceTransformer cachingTransformer = Mockito.mock(CachingResourceTransformer.class); <ide> AppCacheManifestTransformer appCacheTransformer = Mockito.mock(AppCacheManifestTransformer.class); <ide> public void resourceChainWithOverrides() throws Exception { <ide> .resourceChain(false) <ide> .addResolver(cachingResolver) <ide> .addResolver(versionResolver) <add> .addResolver(webjarsResolver) <ide> .addResolver(pathResourceResolver) <ide> .addTransformer(cachingTransformer) <ide> .addTransformer(appCacheTransformer) <ide> .addTransformer(cssLinkTransformer); <ide> <ide> ResourceHttpRequestHandler handler = getHandler("/resources/**"); <ide> List<ResourceResolver> resolvers = handler.getResourceResolvers(); <del> assertThat(resolvers.toString(), resolvers, Matchers.hasSize(3)); <add> assertThat(resolvers.toString(), resolvers, Matchers.hasSize(4)); <ide> assertThat(resolvers.get(0), Matchers.sameInstance(cachingResolver)); <ide> assertThat(resolvers.get(1), Matchers.sameInstance(versionResolver)); <del> assertThat(resolvers.get(2), Matchers.sameInstance(pathResourceResolver)); <add> assertThat(resolvers.get(2), Matchers.sameInstance(webjarsResolver)); <add> assertThat(resolvers.get(3), Matchers.sameInstance(pathResourceResolver)); <ide> <ide> List<ResourceTransformer> transformers = handler.getResourceTransformers(); <ide> assertThat(transformers, Matchers.hasSize(3));
3
PHP
PHP
correct small typos
6c3a63ea9b15fc3931ff32cf087f896e7a73c682
<ide><path>lib/Cake/Console/Command/TestShell.php <ide> public function getOptionParser() { <ide> */ <ide> public function initialize() { <ide> $this->_dispatcher = new CakeTestSuiteDispatcher(); <del> $sucess = $this->_dispatcher->loadTestFramework(); <del> if (!$sucess) { <add> $success = $this->_dispatcher->loadTestFramework(); <add> if (!$success) { <ide> throw new Exception(__d('cake_dev', 'Please install PHPUnit framework <info>(http://www.phpunit.de)</info>')); <ide> } <ide> } <ide><path>lib/Cake/Test/Case/Controller/Component/Auth/BasicAuthenticateTest.php <ide> public function testAuthenticateChallenge() { <ide> } <ide> <ide> /** <del> * test authenticate sucesss <add> * test authenticate success <ide> * <ide> * @return void <ide> */
2