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 | enable colors for windows conemu user | bfa1cd0a69a9ae3fe8941f718d226f55d0952ecf | <ide><path>src/Console/ConsoleOutput.php
<ide> class ConsoleOutput
<ide> /**
<ide> * Construct the output object.
<ide> *
<del> * Checks for a pretty console environment. Ansicon allows pretty consoles
<del> * on windows, and is supported.
<add> * Checks for a pretty console environment. Ansicon and ConEmu allows
<add> * pretty consoles on windows, and is supported.
<ide> *
<ide> * @param string $stream The identifier of the stream to write output to.
<ide> */
<ide> public function __construct($stream = 'php://stdout')
<ide> {
<ide> $this->_output = fopen($stream, 'w');
<ide>
<del> if ((DS === '\\' && !(bool)env('ANSICON')) ||
<add> if ((DS === '\\' && !(bool)env('ANSICON') && env('ConEmuANSI') !== 'ON') ||
<ide> (function_exists('posix_isatty') && !posix_isatty($this->_output))
<ide> ) {
<ide> $this->_outputAs = self::PLAIN;
<ide><path>src/Log/Engine/ConsoleLog.php
<ide> class ConsoleLog extends BaseLog
<ide> */
<ide> public function __construct(array $config = [])
<ide> {
<del> if ((DS === '\\' && !(bool)env('ANSICON')) ||
<add> if ((DS === '\\' && !(bool)env('ANSICON') && env('ConEmuANSI') !== 'ON') ||
<ide> (function_exists('posix_isatty') && !posix_isatty($this->_output))
<ide> ) {
<ide> $this->_defaultConfig['outputAs'] = ConsoleOutput::PLAIN;
<ide><path>tests/TestCase/Log/Engine/ConsoleLogTest.php
<ide> public function testlogToFileStream()
<ide> */
<ide> public function testDefaultOutputAs()
<ide> {
<del> if ((DS === '\\' && !(bool)env('ANSICON')) ||
<add> if ((DS === '\\' && !(bool)env('ANSICON') && env('ConEmuANSI') !== 'ON') ||
<ide> (function_exists('posix_isatty') && !posix_isatty(null))
<ide> ) {
<ide> $expected = ConsoleOutput::PLAIN; | 3 |
Javascript | Javascript | add test for td append | acb206a4886f53c3eb9628e17d699dbb1b96ef25 | <ide><path>test/unit/manipulation.js
<ide> var testAppendForObject = function( valueObj, isFragment ) {
<ide>
<ide> var testAppend = function( valueObj ) {
<ide>
<del> expect( 67 );
<add> expect( 68 );
<ide>
<ide> testAppendForObject( valueObj, false );
<ide> testAppendForObject( valueObj, true );
<ide> var testAppend = function( valueObj ) {
<ide>
<ide> $table = jQuery("#table");
<ide>
<del> jQuery.each( "thead tbody tfoot colgroup caption tr".split(" "), function( i, name ) {
<add> jQuery.each( "thead tbody tfoot colgroup caption tr td".split(" "), function( i, name ) {
<ide> $table.append( valueObj( "<" + name + "/>" ) );
<ide> equal( $table.find( name ).length, 1, "Append " + name );
<ide> }); | 1 |
Python | Python | clean the code, go back try / except | f2aca6be2036ddc95fa6480d39796f1b95e9e03a | <ide><path>glances/glances.py
<ide> def __get_process_stats__(self, proc):
<ide> procstat['pid'] = proc.pid
<ide> procstat['username'] = proc.username
<ide>
<del> try:
<add> if hasattr(proc, 'nice'):
<ide> # Deprecated in PsUtil 0.5.0
<ide> procstat['nice'] = proc.nice
<del> except:
<add> elif hasattr(proc, 'get_nice'):
<ide> # Specific for PsUtil 0.5.0+
<ide> procstat['nice'] = proc.get_nice()
<add> else:
<add> # Never here...
<add> procstat['nice'] = 0
<ide>
<ide> procstat['status'] = str(proc.status)[:1].upper()
<ide> procstat['cpu_times'] = proc.get_cpu_times()
<ide> def __update__(self):
<ide> """
<ide>
<ide> # CPU
<del> try:
<del> self.cputime_old
<del> except Exception:
<add> if not hasattr(self, 'cputime_old'):
<ide> self.cputime_old = psutil.cpu_times()
<ide> self.cputime_total_old = (self.cputime_old.user +
<ide> self.cputime_old.system +
<ide> self.cputime_old.idle)
<ide> # Only available on some OS
<del> try:
<add> if hasattr(self.cputime_old, 'nice'):
<ide> self.cputime_total_old += self.cputime_old.nice
<del> except Exception:
<del> pass
<del> try:
<add> if hasattr(self.cputime_old, 'iowait'):
<ide> self.cputime_total_old += self.cputime_old.iowait
<del> except Exception:
<del> pass
<del> try:
<add> if hasattr(self.cputime_old, 'irq'):
<ide> self.cputime_total_old += self.cputime_old.irq
<del> except Exception:
<del> pass
<del> try:
<add> if hasattr(self.cputime_old, 'softirq'):
<ide> self.cputime_total_old += self.cputime_old.softirq
<del> except Exception:
<del> pass
<ide> self.cpu = {}
<ide> else:
<ide> try:
<ide> def __update__(self):
<ide> self.cputime_new.system +
<ide> self.cputime_new.idle)
<ide> # Only available on some OS
<del> try:
<add> if hasattr(self.cputime_new, 'nice'):
<ide> self.cputime_total_new += self.cputime_new.nice
<del> except Exception:
<del> pass
<del> try:
<add> if hasattr(self.cputime_new, 'iowait'):
<ide> self.cputime_total_new += self.cputime_new.iowait
<del> except Exception:
<del> pass
<del> try:
<add> if hasattr(self.cputime_new, 'irq'):
<ide> self.cputime_total_new += self.cputime_new.irq
<del> except Exception:
<del> pass
<del> try:
<add> if hasattr(self.cputime_new, 'softirq'):
<ide> self.cputime_total_new += self.cputime_new.softirq
<del> except Exception:
<del> pass
<ide> percent = 100 / (self.cputime_total_new -
<ide> self.cputime_total_old)
<ide> self.cpu = {'kernel':
<ide> def __update__(self):
<ide> self.cpu = {}
<ide>
<ide> # PerCPU
<del> try:
<del> self.percputime_old
<del> except Exception:
<add> if not hasattr(self, 'percputime_old'):
<ide> self.percputime_old = psutil.cpu_times(percpu = True)
<ide> self.percputime_total_old = []
<ide> for i in range(len(self.percputime_old)):
<ide> self.percputime_total_old.append(self.percputime_old[i].user +
<ide> self.percputime_old[i].system +
<ide> self.percputime_old[i].idle)
<ide> # Only available on some OS
<del> try:
<del> for i in range(len(self.percputime_old)):
<add> for i in range(len(self.percputime_old)):
<add> if hasattr(self.percputime_old[i], 'nice'):
<ide> self.percputime_total_old[i] += self.percputime_old[i].nice
<del> except Exception:
<del> pass
<del> try:
<del> for i in range(len(self.percputime_old)):
<add> for i in range(len(self.percputime_old)):
<add> if hasattr(self.percputime_old[i], 'iowait'):
<ide> self.percputime_total_old[i] += self.percputime_old[i].iowait
<del> except Exception:
<del> pass
<del> try:
<del> for i in range(len(self.percputime_old)):
<add> for i in range(len(self.percputime_old)):
<add> if hasattr(self.percputime_old[i], 'irq'):
<ide> self.percputime_total_old[i] += self.percputime_old[i].irq
<del> except Exception:
<del> pass
<del> try:
<del> for i in range(len(self.percputime_old)):
<add> for i in range(len(self.percputime_old)):
<add> if hasattr(self.percputime_old[i], 'softirq'):
<ide> self.percputime_total_old[i] += self.percputime_old[i].softirq
<del> except Exception:
<del> pass
<ide> self.percpu = []
<ide> else:
<ide> try:
<ide> def __update__(self):
<ide> self.percputime_new[i].system +
<ide> self.percputime_new[i].idle)
<ide> # Only available on some OS
<del> try:
<del> for i in range(len(self.percputime_new)):
<add> for i in range(len(self.percputime_new)):
<add> if hasattr(self.percputime_new[i], 'nice'):
<ide> self.percputime_total_new[i] += self.percputime_new[i].nice
<del> except Exception:
<del> pass
<del> try:
<del> for i in range(len(self.percputime_new)):
<add> for i in range(len(self.percputime_new)):
<add> if hasattr(self.percputime_new[i], 'iowait'):
<ide> self.percputime_total_new[i] += self.percputime_new[i].iowait
<del> except Exception:
<del> pass
<del> try:
<del> for i in range(len(self.percputime_new)):
<add> for i in range(len(self.percputime_new)):
<add> if hasattr(self.percputime_new[i], 'irq'):
<ide> self.percputime_total_new[i] += self.percputime_new[i].irq
<del> except Exception:
<del> pass
<del> try:
<del> for i in range(len(self.percputime_new)):
<add> for i in range(len(self.percputime_new)):
<add> if hasattr(self.percputime_new[i], 'softirq'):
<ide> self.percputime_total_new[i] += self.percputime_new[i].softirq
<del> except Exception:
<del> pass
<ide> perpercent = []
<ide> self.percpu = []
<ide> for i in range(len(self.percputime_new)):
<ide> def __update__(self):
<ide> self.percpu = []
<ide>
<ide> # LOAD
<del> try:
<add> if hasattr(os, 'getloadavg'):
<ide> getload = os.getloadavg()
<ide> self.load = {'min1': getload[0],
<ide> 'min5': getload[1],
<ide> 'min15': getload[2]}
<del> except Exception:
<add> else:
<ide> self.load = {}
<ide>
<ide> # MEM
<ide> def __update__(self):
<ide> 'percent': virtmem.percent}
<ide> else:
<ide> # For olders PsUtil version
<del> try:
<add> # Physical memory (RAM)
<add> if hasattr(psutil, 'phymem_usage'):
<ide> phymem = psutil.phymem_usage()
<del> try:
<add> if hasattr(psutil, 'cached_usage') and hasattr(psutil, 'phymem_buffers'):
<ide> # Cache stat only available for Linux
<ide> cachemem = psutil.cached_phymem() + psutil.phymem_buffers()
<del> except Exception:
<add> else:
<ide> cachemem = 0
<ide> self.mem = {'cache': cachemem,
<ide> 'total': phymem.total,
<ide> 'used': phymem.used,
<ide> 'free': phymem.free,
<ide> 'percent': phymem.percent}
<del> except Exception:
<add> else:
<ide> self.mem = {}
<del> try:
<add> # Virtual memory (SWAP)
<add> if hasattr(psutil, 'virtmem_usage'):
<ide> virtmem = psutil.virtmem_usage()
<ide> self.memswap = {'total': virtmem.total,
<ide> 'used': virtmem.used,
<ide> 'free': virtmem.free,
<ide> 'percent': virtmem.percent}
<del> except Exception:
<add> else:
<ide> self.memswap = {}
<ide>
<ide> # NET | 1 |
PHP | PHP | update exception namespaces for api | fe06e153fe589422a1a676a7cdfdc79f85c7211b | <ide><path>src/Datasource/RepositoryInterface.php
<ide> public function find($type = 'all', $options = []);
<ide> *
<ide> * @param mixed $primaryKey primary key value to find
<ide> * @param array|\ArrayAccess $options options accepted by `Table::find()`
<del> * @throws \Cake\ORM\Exception\RecordNotFoundException if the record with such id
<add> * @throws \Cake\Datasource\Exception\RecordNotFoundException if the record with such id
<ide> * could not be found
<ide> * @return \Cake\Datasource\EntityInterface
<ide> * @see RepositoryInterface::find()
<ide><path>src/ORM/Behavior/TreeBehavior.php
<ide> protected function _removeFromTree($node)
<ide> *
<ide> * @param \Cake\ORM\Entity $node The node to move
<ide> * @param int|bool $number How many places to move the node, or true to move to first position
<del> * @throws \Cake\ORM\Exception\RecordNotFoundException When node was not found
<add> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found
<ide> * @return \Cake\ORM\Entity|bool $node The node after being moved or false on failure
<ide> */
<ide> public function moveUp(Entity $node, $number = 1)
<ide> public function moveUp(Entity $node, $number = 1)
<ide> *
<ide> * @param \Cake\ORM\Entity $node The node to move
<ide> * @param int|bool $number How many places to move the node, or true to move to first position
<del> * @throws \Cake\ORM\Exception\RecordNotFoundException When node was not found
<add> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found
<ide> * @return \Cake\ORM\Entity|bool $node The node after being moved or false on failure
<ide> */
<ide> protected function _moveUp($node, $number)
<ide> protected function _moveUp($node, $number)
<ide> *
<ide> * @param \Cake\ORM\Entity $node The node to move
<ide> * @param int|bool $number How many places to move the node or true to move to last position
<del> * @throws \Cake\ORM\Exception\RecordNotFoundException When node was not found
<add> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found
<ide> * @return \Cake\ORM\Entity|bool the entity after being moved or false on failure
<ide> */
<ide> public function moveDown(Entity $node, $number = 1)
<ide> public function moveDown(Entity $node, $number = 1)
<ide> *
<ide> * @param \Cake\ORM\Entity $node The node to move
<ide> * @param int|bool $number How many places to move the node, or true to move to last position
<del> * @throws \Cake\ORM\Exception\RecordNotFoundException When node was not found
<add> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found
<ide> * @return \Cake\ORM\Entity|bool $node The node after being moved or false on failure
<ide> */
<ide> protected function _moveDown($node, $number)
<ide> protected function _moveDown($node, $number)
<ide> *
<ide> * @param mixed $id Record id.
<ide> * @return \Cake\ORM\Entity
<del> * @throws \Cake\ORM\Exception\RecordNotFoundException When node was not found
<add> * @throws \Cake\Datasource\Exception\RecordNotFoundException When node was not found
<ide> */
<ide> protected function _getNode($id)
<ide> {
<ide><path>src/ORM/Table.php
<ide> protected function _setFieldMatchers($options, $keys)
<ide> /**
<ide> * {@inheritDoc}
<ide> *
<del> * @throws Cake\Datasource\Exception\InvalidPrimaryKeyException When $primaryKey has an
<add> * @throws \Cake\Datasource\Exception\InvalidPrimaryKeyException When $primaryKey has an
<ide> * incorrect number of elements.
<ide> */
<ide> public function get($primaryKey, $options = []) | 3 |
Ruby | Ruby | add unnecessary whitespace check | 73194b460d047bec3a4d6fb31cf969a2b9e7aa77 | <ide><path>Library/Homebrew/rubocops/formula_desc_cop.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> module FormulaAuditStrict
<ide> # This cop audits `desc` in Formulae
<ide> #
<add> # - Checks for leading/trailing whitespace in `desc`
<ide> # - Checks if `desc` begins with an article
<ide> # - Checks for correct usage of `command-line` in `desc`
<ide> # - Checks description starts with a capital letter
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide>
<ide> desc = parameters(desc_call).first
<ide>
<add> # Check for leading whitespace.
<add> if regex_match_group(desc, /^\s+/)
<add> problem "Description shouldn't have a leading space"
<add> end
<add>
<add> # Check for trailing whitespace.
<add> if regex_match_group(desc, /\s+$/)
<add> problem "Description shouldn't have a trailing space"
<add> end
<add>
<ide> # Check if command-line is wrongly used in formula's desc
<ide> if match = regex_match_group(desc, /(command ?line)/i)
<ide> c = match.to_s.chars.first
<ide> def autocorrect(node)
<ide> correction.gsub!(/^(['"]?)\s+/, "\\1")
<ide> correction.gsub!(/\s+(['"]?)$/, "\\1")
<ide> correction.gsub!(/\.(['"]?)$/, "\\1")
<add> correction.gsub!(/^\s+/, "")
<add> correction.gsub!(/\s+$/, "")
<ide> corrector.insert_before(node.source_range, correction)
<ide> corrector.remove(node.source_range)
<ide> end | 1 |
Text | Text | update 1.2.26 release name | 8da08a1ebd92468cb999b4842b53a4fb187e2403 | <ide><path>CHANGELOG.md
<ide> as those errors are shown to the user, but the erroneous state was
<ide> caused by incorrect application logic and not by the user.
<ide>
<ide> <a name="1.2.26"></a>
<del># 1.2.26 zucchini-expansion (2014-10-01)
<add># 1.2.26 captivating-disinterest (2014-10-01)
<ide>
<ide> ## Bug Fixes
<ide> | 1 |
Javascript | Javascript | get test-http-response-no-headers.js to pass | 6e1e9e2fcb8dd79eada404581c2cc3eb2cd245f8 | <ide><path>test/simple/test-http-response-no-headers.js
<ide> var assert = require('assert');
<ide> var http = require('http');
<ide> var net = require('net');
<ide>
<del>var expected = 'I AM THE WALRUS';
<add>var expected = {
<add> '0.9': 'I AM THE WALRUS',
<add> '1.0': 'I AM THE WALRUS',
<add> '1.1': '',
<add>}
<ide>
<ide> var gotExpected = false;
<ide>
<ide> function test(httpVersion, callback) {
<ide> });
<ide>
<ide> var server = net.createServer(function(conn) {
<del> var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + expected;
<add> var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + expected[httpVersion];
<ide>
<ide> conn.write(reply, function() {
<ide> conn.destroy();
<ide> function test(httpVersion, callback) {
<ide> });
<ide>
<ide> res.on('end', function() {
<del> assert.equal(body, expected);
<add> assert.equal(body, expected[httpVersion]);
<ide> gotExpected = true;
<ide> server.close();
<ide> if (callback) process.nextTick(callback); | 1 |
Python | Python | use better type signatures in the array api module | 74478e2d943f4d61917d4d9122a042214eed94fd | <ide><path>numpy/_array_api/_array_object.py
<ide> def __le__(self: Array, other: Union[int, float, Array], /) -> Array:
<ide> res = self._array.__le__(other._array)
<ide> return self.__class__._new(res)
<ide>
<del> def __len__(self, /):
<add> # Note: __len__ may end up being removed from the array API spec.
<add> def __len__(self, /) -> int:
<ide> """
<ide> Performs the operation __len__.
<ide> """
<ide> def __rxor__(self: Array, other: Union[int, bool, Array], /) -> Array:
<ide> return self.__class__._new(res)
<ide>
<ide> @property
<del> def dtype(self):
<add> def dtype(self) -> Dtype:
<ide> """
<ide> Array API compatible wrapper for :py:meth:`np.ndaray.dtype <numpy.ndarray.dtype>`.
<ide>
<ide> def dtype(self):
<ide> return self._array.dtype
<ide>
<ide> @property
<del> def device(self):
<add> def device(self) -> Device:
<ide> """
<ide> Array API compatible wrapper for :py:meth:`np.ndaray.device <numpy.ndarray.device>`.
<ide>
<ide> def device(self):
<ide> raise NotImplementedError("The device attribute is not yet implemented")
<ide>
<ide> @property
<del> def ndim(self):
<add> def ndim(self) -> int:
<ide> """
<ide> Array API compatible wrapper for :py:meth:`np.ndaray.ndim <numpy.ndarray.ndim>`.
<ide>
<ide> def ndim(self):
<ide> return self._array.ndim
<ide>
<ide> @property
<del> def shape(self):
<add> def shape(self) -> Tuple[int, ...]:
<ide> """
<ide> Array API compatible wrapper for :py:meth:`np.ndaray.shape <numpy.ndarray.shape>`.
<ide>
<ide> def shape(self):
<ide> return self._array.shape
<ide>
<ide> @property
<del> def size(self):
<add> def size(self) -> int:
<ide> """
<ide> Array API compatible wrapper for :py:meth:`np.ndaray.size <numpy.ndarray.size>`.
<ide>
<ide> def size(self):
<ide> return self._array.size
<ide>
<ide> @property
<del> def T(self):
<add> def T(self) -> Array:
<ide> """
<ide> Array API compatible wrapper for :py:meth:`np.ndaray.T <numpy.ndarray.T>`.
<ide>
<ide><path>numpy/_array_api/_creation_functions.py
<ide>
<ide> import numpy as np
<ide>
<del>def asarray(obj: Union[float, NestedSequence[bool|int|float], SupportsDLPack, SupportsBufferProtocol], /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, copy: Optional[bool] = None) -> Array:
<add>def asarray(obj: Union[Array, float, NestedSequence[bool|int|float], SupportsDLPack, SupportsBufferProtocol], /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None, copy: Optional[bool] = None) -> Array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.asarray <numpy.asarray>`.
<ide>
<ide><path>numpy/_array_api/_data_type_functions.py
<ide>
<ide> from ._array_object import Array
<ide>
<add>from dataclasses import dataclass
<ide> from typing import TYPE_CHECKING
<ide> if TYPE_CHECKING:
<ide> from ._types import List, Tuple, Union, Dtype
<ide> def can_cast(from_: Union[Dtype, Array], to: Dtype, /) -> bool:
<ide> from_ = from_._array
<ide> return np.can_cast(from_, to)
<ide>
<add># These are internal objects for the return types of finfo and iinfo, since
<add># the NumPy versions contain extra data that isn't part of the spec.
<add>@dataclass
<add>class finfo_object:
<add> bits: int
<add> # Note: The types of the float data here are float, whereas in NumPy they
<add> # are scalars of the corresponding float dtype.
<add> eps: float
<add> max: float
<add> min: float
<add> # Note: smallest_normal is part of the array API spec, but cannot be used
<add> # until https://github.com/numpy/numpy/pull/18536 is merged.
<add>
<add> # smallest_normal: float
<add>
<add>@dataclass
<add>class iinfo_object:
<add> bits: int
<add> max: int
<add> min: int
<add>
<ide> def finfo(type: Union[Dtype, Array], /) -> finfo_object:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.finfo <numpy.finfo>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<del> return np.finfo(type)
<add> fi = np.finfo(type)
<add> # Note: The types of the float data here are float, whereas in NumPy they
<add> # are scalars of the corresponding float dtype.
<add> return finfo_object(
<add> fi.bits,
<add> float(fi.eps),
<add> float(fi.max),
<add> float(fi.min),
<add> # TODO: Uncomment this when #18536 is merged.
<add> # float(fi.smallest_normal),
<add> )
<ide>
<ide> def iinfo(type: Union[Dtype, Array], /) -> iinfo_object:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.iinfo <numpy.iinfo>`.
<ide>
<ide> See its docstring for more information.
<ide> """
<del> return np.iinfo(type)
<add> ii = np.iinfo(type)
<add> return iinfo_object(ii.bits, ii.max, ii.min)
<ide>
<ide> def result_type(*arrays_and_dtypes: Sequence[Union[Array, Dtype]]) -> Dtype:
<ide> """
<ide><path>numpy/_array_api/_manipulation_functions.py
<ide> import numpy as np
<ide>
<ide> # Note: the function name is different here
<del>def concat(arrays: Tuple[Array, ...], /, *, axis: Optional[int] = 0) -> Array:
<add>def concat(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: Optional[int] = 0) -> Array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.concatenate <numpy.concatenate>`.
<ide>
<ide> def squeeze(x: Array, /, axis: Optional[Union[int, Tuple[int, ...]]] = None) ->
<ide> """
<ide> return Array._new(np.squeeze(x._array, axis=axis))
<ide>
<del>def stack(arrays: Tuple[Array, ...], /, *, axis: int = 0) -> Array:
<add>def stack(arrays: Union[Tuple[Array, ...], List[Array]], /, *, axis: int = 0) -> Array:
<ide> """
<ide> Array API compatible wrapper for :py:func:`np.stack <numpy.stack>`.
<ide> | 4 |
Javascript | Javascript | make use of destructuring possibilities | 2740fda412ca23d4d632ab226fd75adae3809c69 | <ide><path>lib/DelegatedModuleFactoryPlugin.js
<ide> class DelegatedModuleFactoryPlugin {
<ide> normalModuleFactory.hooks.factorize.tapAsync(
<ide> "DelegatedModuleFactoryPlugin",
<ide> (data, callback) => {
<del> const dependency = data.dependencies[0];
<del> const request = dependency.request;
<add> const [dependency] = data.dependencies;
<add> const {request} = dependency.request;
<ide> if (request && request.indexOf(scope + "/") === 0) {
<ide> const innerRequest = "." + request.substr(scope.length);
<ide> let resolved; | 1 |
Ruby | Ruby | fix sequence name with abstract classes | 82ae5c40ea29eecc2c0d017ffc7c2f2a23a7e21f | <ide><path>activerecord/lib/active_record/base.rb
<ide> def set_inheritance_column(value = nil, &block) #:nodoc:
<ide> end
<ide>
<ide> def sequence_name
<del> if superclass == Base
<add> if base_class == self
<ide> @sequence_name ||= reset_sequence_name
<ide> else
<del> (@sequence_name ||= nil) || superclass.sequence_name
<add> (@sequence_name ||= nil) || base_class.sequence_name
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_original_sequence_name
<ide> end
<ide> end
<ide>
<add> def test_sequence_name_with_abstract_class
<add> ak = Class.new(ActiveRecord::Base)
<add> ak.abstract_class = true
<add> k = Class.new(ak)
<add> k.table_name = "projects"
<add> orig_name = k.sequence_name
<add> return skip "sequences not supported by db" unless orig_name
<add> assert_equal k.reset_sequence_name, orig_name
<add> end
<add>
<ide> def test_count_with_join
<ide> res = Post.count_by_sql "SELECT COUNT(*) FROM posts LEFT JOIN comments ON posts.id=comments.post_id WHERE posts.#{QUOTED_TYPE} = 'Post'"
<ide> | 2 |
PHP | PHP | remove code that is in 8.x | ac5ee4f4cacba0e79849c9d0de922f6e18b0725f | <ide><path>src/Illuminate/Mail/MailManager.php
<ide> public function setDefaultDriver(string $name)
<ide> $this->app['config']['mail.default'] = $name;
<ide> }
<ide>
<del> /**
<del> * Forget a mailer instance by name.
<del> *
<del> * @param array|string|null $name
<del> * @return void
<del> */
<del> public function forgetMailer($name = null)
<del> {
<del> $name = $name ?? $this->getDefaultDriver();
<del>
<del> foreach ((array) $name as $mailerName) {
<del> if (isset($this->mailers[$mailerName])) {
<del> unset($this->mailers[$mailerName]);
<del> }
<del> }
<del>
<del> return $this;
<del> }
<del>
<ide> /**
<ide> * Register a custom transport creator Closure.
<ide> *
<ide><path>tests/Mail/MailManagerTest.php
<ide> public function emptyTransportConfigDataProvider()
<ide> [null], [''], [' '],
<ide> ];
<ide> }
<del>
<del> public function testForgetMailer()
<del> {
<del> $this->app['config']->set('mail.mailers.custom_smtp', [
<del> 'transport' => 'smtp',
<del> 'host' => 'example.com',
<del> 'port' => '25',
<del> 'encryption' => 'tls',
<del> 'username' => 'username',
<del> 'password' => 'password',
<del> 'timeout' => 10,
<del> ]);
<del>
<del> /** @var MailManager $mailManager */
<del> $mailManager = $this->app['mail.manager'];
<del> $mailManager->mailer('custom_smtp');
<del>
<del> $mailersProperty = new \ReflectionProperty($mailManager, 'mailers');
<del> $mailersProperty->setAccessible(true);
<del>
<del> $this->assertArrayHasKey('custom_smtp', $mailersProperty->getValue($mailManager), 'Mailer must exist in the $mailers-property');
<del>
<del> $mailManager->forgetMailer('custom_smtp');
<del>
<del> $this->assertArrayNotHasKey('custom_smtp', $mailersProperty->getValue($mailManager), 'Mailer must not exist in the $mailers-property as it must have been removed with MailManager::forgetMailer()');
<del> }
<ide> } | 2 |
PHP | PHP | implement array access on models | 9e9f32a4f371fdb8c18ddb21c7eabb51a8a63a78 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide>
<ide> use Closure;
<ide> use DateTime;
<add>use ArrayAccess;
<ide> use Illuminate\Events\Dispatcher;
<ide> use Illuminate\Database\Connection;
<ide> use Illuminate\Database\Eloquent\Relations\HasOne;
<ide> use Illuminate\Database\Eloquent\Relations\BelongsToMany;
<ide> use Illuminate\Database\ConnectionResolverInterface as Resolver;
<ide>
<del>abstract class Model implements ArrayableInterface, JsonableInterface {
<add>abstract class Model implements ArrayAccess, ArrayableInterface, JsonableInterface {
<ide>
<ide> /**
<ide> * The connection name for the model.
<ide> public function __set($key, $value)
<ide> $this->setAttribute($key, $value);
<ide> }
<ide>
<add> /**
<add> * Determine if the given attribute exists.
<add> *
<add> * @param mixed $offset
<add> * @return bool
<add> */
<add> public function offsetExists($offset)
<add> {
<add> return isset($this->$offset);
<add> }
<add>
<add> /**
<add> * Get the value for a given offset.
<add> *
<add> * @param mixed $offset
<add> * @return mixed
<add> */
<add> public function offsetGet($offset)
<add> {
<add> return $this->$offset;
<add> }
<add>
<add> /**
<add> * Set the value for a given offset.
<add> *
<add> * @param mixed $offset
<add> * @param mixed $value
<add> * @return void
<add> */
<add> public function offsetSet($offset, $value)
<add> {
<add> $this->$offset = $value;
<add> }
<add>
<add> /**
<add> * Unset the value for a given offset.
<add> *
<add> * @param mixed $offset
<add> * @return void
<add> */
<add> public function offsetUnset($offset)
<add> {
<add> unset($this->$offset);
<add> }
<add>
<ide> /**
<ide> * Determine if an attribute exists on the model.
<ide> * | 1 |
Python | Python | fix comparison to 0 in scalarmath test | 004082f81f89021deb931f8da1b4db1aaed87806 | <ide><path>numpy/core/tests/test_scalarmath.py
<ide> def check_float_repr(self):
<ide> # through a Python float, which will lose
<ide> # precision
<ide> continue
<del> assert_equal( val, val2 )
<add> if not (val == 0 and val2 < 1e-100):
<add> assert_equal(val, val2)
<ide>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run() | 1 |
Javascript | Javascript | exclude elclob test in edge 17 | 3cf4eed6b58c4b09a44d59cba68f3d6a7283a2a4 | <ide><path>test/ngSanitize/sanitizeSpec.js
<ide> describe('HTML', function() {
<ide> });
<ide> });
<ide>
<del> if (!/Edge\/16/.test(window.navigator.userAgent)) {
<add> if (!/Edge\/(16|17)/.test(window.navigator.userAgent)) {
<ide> // Skip test on Edge 16 due to browser bug.
<ide> it('should throw on a form with an input named "nextSibling"', function() {
<ide> inject(function($sanitize) { | 1 |
Go | Go | replace strings.replace with strings.replaceall | 7873c27cfbd812dca60d90367d375bbae5a27014 | <ide><path>builder/dockerfile/dispatchers_windows.go
<ide> func normalizeWorkdirUnix(current string, requested string) (string, error) {
<ide> if requested == "" {
<ide> return "", errors.New("cannot normalize nothing")
<ide> }
<del> current = strings.Replace(current, string(os.PathSeparator), "/", -1)
<del> requested = strings.Replace(requested, string(os.PathSeparator), "/", -1)
<add> current = strings.ReplaceAll(current, string(os.PathSeparator), "/")
<add> requested = strings.ReplaceAll(requested, string(os.PathSeparator), "/")
<ide> if !path.IsAbs(requested) {
<ide> return path.Join(`/`, current, requested), nil
<ide> }
<ide><path>daemon/links/links.go
<ide> func (l *Link) ToEnv() []string {
<ide> env := []string{}
<ide>
<ide> _, n := path.Split(l.Name)
<del> alias := strings.Replace(strings.ToUpper(n), "-", "_", -1)
<add> alias := strings.ReplaceAll(strings.ToUpper(n), "-", "_")
<ide>
<ide> if p := l.getDefaultPort(); p != nil {
<ide> env = append(env, fmt.Sprintf("%s_PORT=%s://%s:%s", alias, p.Proto(), l.ChildIP, p.Port()))
<ide><path>daemon/oci_linux.go
<ide> func WithMounts(daemon *Daemon, c *container.Container) coci.SpecOpts {
<ide> // sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
<ide> // exist, so do not add the default ones if running on an old kernel.
<ide> func sysctlExists(s string) bool {
<del> f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
<add> f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
<ide> _, err := os.Stat(f)
<ide> return err == nil
<ide> }
<ide><path>distribution/manifest_test.go
<ide> func TestManifestStore(t *testing.T) {
<ide> dgst := digest.Canonical.FromBytes(serialized)
<ide>
<ide> setupTest := func(t *testing.T) (specs.Descriptor, *mockManifestGetter, *manifestStore, content.Store, func(*testing.T)) {
<del> root, err := os.MkdirTemp("", strings.Replace(t.Name(), "/", "_", -1))
<add> root, err := os.MkdirTemp("", strings.ReplaceAll(t.Name(), "/", "_"))
<ide> assert.NilError(t, err)
<ide> defer func() {
<ide> if t.Failed() {
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
<ide> e2 := removeLogTimestamps(result2.Error.Error())
<ide>
<ide> // Ignore whitespace since that's what were verifying doesn't change stuff
<del> if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
<add> if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
<ide> c.Fatalf("Build 2's error wasn't the same as build 1's\n1:%s\n2:%s", result1.Error, result2.Error)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
<ide> e2 = removeLogTimestamps(result2.Error.Error())
<ide>
<ide> // Ignore whitespace since that's what were verifying doesn't change stuff
<del> if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
<add> if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
<ide> c.Fatalf("Build 3's error wasn't the same as build 1's\n1:%s\n3:%s", result1.Error, result2.Error)
<ide> }
<ide>
<ide> func (s *DockerSuite) TestBuildSpaces(c *testing.T) {
<ide> e2 = removeLogTimestamps(result2.Error.Error())
<ide>
<ide> // Ignore whitespace since that's what were verifying doesn't change stuff
<del> if strings.Replace(e1, " ", "", -1) != strings.Replace(e2, " ", "", -1) {
<add> if strings.ReplaceAll(e1, " ", "") != strings.ReplaceAll(e2, " ", "") {
<ide> c.Fatalf("Build 4's error wasn't the same as build 1's\n1:%s\n4:%s", result1.Error, result2.Error)
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_events_test.go
<ide> func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *testing.T) {
<ide> func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) {
<ide> dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true")
<ide> timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano)
<del> timeBeginning = strings.Replace(timeBeginning, "Z", ".000000000Z", -1)
<add> timeBeginning = strings.ReplaceAll(timeBeginning, "Z", ".000000000Z")
<ide> out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c))
<ide> events := strings.Split(out, "\n")
<ide> events = events[:len(events)-1]
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunDNSOptions(c *testing.T) {
<ide> c.Fatalf("Expected warning on stderr about localhost resolver, but got %q", result.Stderr())
<ide> }
<ide>
<del> actual := strings.Replace(strings.Trim(result.Stdout(), "\r\n"), "\n", " ", -1)
<add> actual := strings.ReplaceAll(strings.Trim(result.Stdout(), "\r\n"), "\n", " ")
<ide> if actual != "search mydomain nameserver 127.0.0.1 options ndots:9" {
<ide> c.Fatalf("expected 'search mydomain nameserver 127.0.0.1 options ndots:9', but says: %q", actual)
<ide> }
<ide>
<ide> out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns-search=.", "--dns-opt=ndots:3", "busybox", "cat", "/etc/resolv.conf").Combined()
<ide>
<del> actual = strings.Replace(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ", -1)
<add> actual = strings.ReplaceAll(strings.Trim(strings.Trim(out, "\r\n"), " "), "\n", " ")
<ide> if actual != "nameserver 1.1.1.1 options ndots:3" {
<ide> c.Fatalf("expected 'nameserver 1.1.1.1 options ndots:3', but says: %q", actual)
<ide> }
<ide> func (s *DockerSuite) TestRunDNSRepeatOptions(c *testing.T) {
<ide> testRequires(c, DaemonIsLinux)
<ide> out := cli.DockerCmd(c, "run", "--dns=1.1.1.1", "--dns=2.2.2.2", "--dns-search=mydomain", "--dns-search=mydomain2", "--dns-opt=ndots:9", "--dns-opt=timeout:3", "busybox", "cat", "/etc/resolv.conf").Stdout()
<ide>
<del> actual := strings.Replace(strings.Trim(out, "\r\n"), "\n", " ", -1)
<add> actual := strings.ReplaceAll(strings.Trim(out, "\r\n"), "\n", " ")
<ide> if actual != "search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3" {
<ide> c.Fatalf("expected 'search mydomain mydomain2 nameserver 1.1.1.1 nameserver 2.2.2.2 options ndots:9 timeout:3', but says: %q", actual)
<ide> }
<ide> func (s *DockerSuite) TestRunSetMacAddress(c *testing.T) {
<ide> var out string
<ide> if testEnv.OSType == "windows" {
<ide> out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'")
<del> mac = strings.Replace(strings.ToUpper(mac), ":", "-", -1) // To Windows-style MACs
<add> mac = strings.ReplaceAll(strings.ToUpper(mac), ":", "-") // To Windows-style MACs
<ide> } else {
<ide> out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'")
<ide> }
<ide> func (s *DockerSuite) TestRunCreateVolumeEtc(c *testing.T) {
<ide> }
<ide>
<ide> out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts")
<del> out = strings.Replace(out, "\n", " ", -1)
<add> out = strings.ReplaceAll(out, "\n", " ")
<ide> if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") {
<ide> c.Fatal("/etc volume mount hides /etc/hosts")
<ide> }
<ide> func (s *DockerSuite) TestRunNonLocalMacAddress(c *testing.T) {
<ide> args = append(args, "busybox", "ifconfig")
<ide> } else {
<ide> args = append(args, testEnv.PlatformDefaults.BaseImage, "ipconfig", "/all")
<del> expected = strings.Replace(strings.ToUpper(addr), ":", "-", -1)
<add> expected = strings.ReplaceAll(strings.ToUpper(addr), ":", "-")
<ide> }
<ide>
<ide> if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) {
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) {
<ide> // sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
<ide> // exist, so do not add the default ones if running on an old kernel.
<ide> func sysctlExists(s string) bool {
<del> f := filepath.Join("/proc", "sys", strings.Replace(s, ".", "/", -1))
<add> f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
<ide> _, err := os.Stat(f)
<ide> return err == nil
<ide> }
<ide><path>libnetwork/cmd/diagnostic/main.go
<ide> func fetchTable(ip string, port int, network, tableName string, clusterPeers, ne
<ide> logrus.Warnf("The following keys:%v results as orphan, do you want to proceed with the deletion (this operation is irreversible)? [Yes/No]", orphanKeys)
<ide> reader := bufio.NewReader(os.Stdin)
<ide> text, _ := reader.ReadString('\n')
<del> text = strings.Replace(text, "\n", "", -1)
<add> text = strings.ReplaceAll(text, "\n", "")
<ide> if strings.Compare(text, "Yes") == 0 {
<ide> for _, k := range orphanKeys {
<ide> resp, err := http.Get(fmt.Sprintf(deleteEntry, ip, port, network, tableName, k))
<ide><path>libnetwork/drivers/windows/windows.go
<ide> func (d *driver) CreateEndpoint(nid, eid string, ifInfo driverapi.InterfaceInfo,
<ide> macAddress := ifInfo.MacAddress()
<ide> // Use the macaddress if it was provided
<ide> if macAddress != nil {
<del> endpointStruct.MacAddress = strings.Replace(macAddress.String(), ":", "-", -1)
<add> endpointStruct.MacAddress = strings.ReplaceAll(macAddress.String(), ":", "-")
<ide> }
<ide>
<ide> portMapping := epConnectivity.PortBindings
<ide><path>libnetwork/osl/kernel/knobs_linux.go
<ide> import (
<ide> // writeSystemProperty writes the value to a path under /proc/sys as determined from the key.
<ide> // For e.g. net.ipv4.ip_forward translated to /proc/sys/net/ipv4/ip_forward.
<ide> func writeSystemProperty(key, value string) error {
<del> keyPath := strings.Replace(key, ".", "/", -1)
<add> keyPath := strings.ReplaceAll(key, ".", "/")
<ide> return os.WriteFile(path.Join("/proc/sys", keyPath), []byte(value), 0644)
<ide> }
<ide>
<ide> // readSystemProperty reads the value from the path under /proc/sys and returns it
<ide> func readSystemProperty(key string) (string, error) {
<del> keyPath := strings.Replace(key, ".", "/", -1)
<add> keyPath := strings.ReplaceAll(key, ".", "/")
<ide> value, err := os.ReadFile(path.Join("/proc/sys", keyPath))
<ide> if err != nil {
<ide> return "", err
<ide><path>pkg/archive/copy.go
<ide> var (
<ide> // clean path already ends in the separator, then another is not added.
<ide> func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string {
<ide> // Ensure paths are in platform semantics
<del> cleanedPath = strings.Replace(cleanedPath, "/", string(sep), -1)
<del> originalPath = strings.Replace(originalPath, "/", string(sep), -1)
<add> cleanedPath = strings.ReplaceAll(cleanedPath, "/", string(sep))
<add> originalPath = strings.ReplaceAll(originalPath, "/", string(sep))
<ide>
<ide> if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) {
<ide> if !hasTrailingPathSeparator(cleanedPath, sep) {
<ide><path>pkg/stack/stackdump.go
<ide> func Dump() {
<ide> func DumpToFile(dir string) (string, error) {
<ide> var f *os.File
<ide> if dir != "" {
<del> path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.Replace(time.Now().Format(time.RFC3339), ":", "", -1)))
<add> path := filepath.Join(dir, fmt.Sprintf(stacksLogNameTemplate, strings.ReplaceAll(time.Now().Format(time.RFC3339), ":", "")))
<ide> var err error
<ide> f, err = os.OpenFile(path, os.O_CREATE|os.O_WRONLY, 0666)
<ide> if err != nil {
<ide><path>registry/config_windows.go
<ide> var defaultCertsDir = os.Getenv("programdata") + `\docker\certs.d`
<ide> // https:\index.docker.io\v1. Not all platforms support directory names
<ide> // which contain those characters (such as : on Windows)
<ide> func cleanPath(s string) string {
<del> return filepath.FromSlash(strings.Replace(s, ":", "", -1))
<add> return filepath.FromSlash(strings.ReplaceAll(s, ":", ""))
<ide> }
<ide><path>testutil/environment/environment.go
<ide> func getPlatformDefaults(info types.Info, osType string) PlatformDefaults {
<ide> // Make sure in context of daemon, not the local platform. Note we can't
<ide> // use filepath.FromSlash or ToSlash here as they are a no-op on Unix.
<ide> func toSlash(path string) string {
<del> return strings.Replace(path, `\`, `/`, -1)
<add> return strings.ReplaceAll(path, `\`, `/`)
<ide> }
<ide>
<ide> // IsLocalDaemon is true if the daemon under test is on the same
<ide><path>volume/mounts/linux_parser.go
<ide> func linuxSplitRawSpec(raw string) ([]string, error) {
<ide> }
<ide>
<ide> func linuxValidateNotRoot(p string) error {
<del> p = path.Clean(strings.Replace(p, `\`, `/`, -1))
<add> p = path.Clean(strings.ReplaceAll(p, `\`, `/`))
<ide> if p == "/" {
<ide> return ErrVolumeTargetIsRoot
<ide> }
<ide> return nil
<ide> }
<ide> func linuxValidateAbsolute(p string) error {
<del> p = strings.Replace(p, `\`, `/`, -1)
<add> p = strings.ReplaceAll(p, `\`, `/`)
<ide> if path.IsAbs(p) {
<ide> return nil
<ide> }
<ide><path>volume/mounts/windows_parser.go
<ide> func windowsValidMountMode(mode string) bool {
<ide> }
<ide>
<ide> func windowsValidateNotRoot(p string) error {
<del> p = strings.ToLower(strings.Replace(p, `/`, `\`, -1))
<add> p = strings.ToLower(strings.ReplaceAll(p, `/`, `\`))
<ide> if p == "c:" || p == `c:\` {
<ide> return fmt.Errorf("destination path cannot be `c:` or `c:\\`: %v", p)
<ide> }
<ide> func (p *windowsParser) parseMount(arr []string, raw, volumeDriver string, conve
<ide> return nil, errInvalidSpec(raw)
<ide> }
<ide> // Host Source Path or Name + Destination
<del> spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
<add> spec.Source = strings.ReplaceAll(arr[0], `/`, `\`)
<ide> spec.Target = arr[1]
<ide> case 3:
<ide> // HostSourcePath+DestinationPath+Mode
<del> spec.Source = strings.Replace(arr[0], `/`, `\`, -1)
<add> spec.Source = strings.ReplaceAll(arr[0], `/`, `\`)
<ide> spec.Target = arr[1]
<ide> mode = arr[2]
<ide> default:
<ide> return nil, errInvalidSpec(raw)
<ide> }
<ide> if convertTargetToBackslash {
<del> spec.Target = strings.Replace(spec.Target, `/`, `\`, -1)
<add> spec.Target = strings.ReplaceAll(spec.Target, `/`, `\`)
<ide> }
<ide>
<ide> if !windowsValidMountMode(mode) {
<ide> func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash
<ide> Spec: cfg,
<ide> }
<ide> if convertTargetToBackslash {
<del> mp.Destination = strings.Replace(cfg.Target, `/`, `\`, -1)
<add> mp.Destination = strings.ReplaceAll(cfg.Target, `/`, `\`)
<ide> }
<ide>
<ide> switch cfg.Type {
<ide> func (p *windowsParser) parseMountSpec(cfg mount.Mount, convertTargetToBackslash
<ide> }
<ide> }
<ide> case mount.TypeBind:
<del> mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
<add> mp.Source = strings.ReplaceAll(cfg.Source, `/`, `\`)
<ide> case mount.TypeNamedPipe:
<del> mp.Source = strings.Replace(cfg.Source, `/`, `\`, -1)
<add> mp.Source = strings.ReplaceAll(cfg.Source, `/`, `\`)
<ide> }
<ide> // cleanup trailing `\` except for paths like `c:\`
<ide> if len(mp.Source) > 3 && mp.Source[len(mp.Source)-1] == '\\' {
<ide><path>volume/service/store_test.go
<ide> var cmpVolume = cmp.AllowUnexported(volumetestutils.FakeVolume{}, volumeWrapper{
<ide> func setupTest(t *testing.T) (*VolumeStore, func()) {
<ide> t.Helper()
<ide>
<del> dirName := strings.Replace(t.Name(), string(os.PathSeparator), "_", -1)
<add> dirName := strings.ReplaceAll(t.Name(), string(os.PathSeparator), "_")
<ide> dir, err := os.MkdirTemp("", dirName)
<ide> assert.NilError(t, err)
<ide> | 18 |
Javascript | Javascript | guarantee stable sort | 762580ff347e733397c70cb192ca023e7d06f581 | <ide><path>src/ng/filter/orderBy.js
<ide> * dummy predicate that returns the item's index as `value`.
<ide> * (If you are using a custom comparator, make sure it can handle this predicate as well.)
<ide> *
<add> * If a custom comparator still can't distinguish between two items, then they will be sorted based
<add> * on their index using the built-in comparator.
<add> *
<ide> * Finally, in an attempt to simplify things, if a predicate returns an object as the extracted
<ide> * value for an item, `orderBy` will try to convert that object to a primitive value, before passing
<ide> * it to the comparator. The following rules govern the conversion:
<ide> function orderByFilter($parse) {
<ide> }
<ide> }
<ide>
<del> return compare(v1.tieBreaker, v2.tieBreaker) * descending;
<add> return (compare(v1.tieBreaker, v2.tieBreaker) || defaultCompare(v1.tieBreaker, v2.tieBreaker)) * descending;
<ide> }
<ide> };
<ide>
<ide><path>test/ng/filter/orderBySpec.js
<ide> describe('Filter: orderBy', function() {
<ide>
<ide> expect(orderBy(items, expr, reverse, comparator)).toEqual(sorted);
<ide> });
<add>
<add> it('should use the default comparator to break ties on a provided comparator', function() {
<add> // Some list that won't be sorted "naturally", i.e. should sort to ['a', 'B', 'c']
<add> var items = ['c', 'a', 'B'];
<add> var expr = null;
<add> function comparator() {
<add> return 0;
<add> }
<add> var reversed = ['B', 'a', 'c'];
<add>
<add> expect(orderBy(items, expr, false, comparator)).toEqual(items);
<add> expect(orderBy(items, expr, true, comparator)).toEqual(reversed);
<add> });
<ide> });
<ide>
<ide> describe('(object as `value`)', function() { | 2 |
Text | Text | update translation timsort | 14260bb4b34a2b40491a4873db2a283bf2731036 | <ide><path>guide/portuguese/algorithms/sorting-algorithms/timsort/index.md
<ide> O Timsort é um algoritmo de classificação rápida que trabalha na complexidad
<ide> Timsort é uma mistura em Insertion Sort e Mergesort. Esse algoritmo é implementado no Arrays.sort () do Java, bem como no class () e no sort () do Python. A parte menor é classificada usando Insertion Sort e é posteriormente mesclada usando o Mergesort.
<ide>
<ide> Uma implementação rápida em Python:
<del>```
<add>```py
<ide> def binary_search(the_array, item, start, end):
<ide> if start == end:
<ide> if the_array[start] > item:
<ide> O Tim Sort tem uma Complexidade estável de O (N log (N)) e compara muito bem co
<ide>
<ide> #### Créditos:
<ide>
<del>[Implementação Python](https://hackernoon.com/timsort-the-fastest-sorting-algorithm-youve-never-heard-of-36b28417f399)
<ide>\ No newline at end of file
<add>[Implementação Python](https://hackernoon.com/timsort-the-fastest-sorting-algorithm-youve-never-heard-of-36b28417f399) | 1 |
Go | Go | add comments to api/common constants, closes | c136591f40c34de51bbb0691ae69f393ff8b2f0e | <ide><path>api/common.go
<ide> import (
<ide> "github.com/docker/libtrust"
<ide> )
<ide>
<add>// Common constants for daemon and client.
<ide> const (
<del> APIVERSION version.Version = "1.18"
<del> DEFAULTHTTPHOST = "127.0.0.1"
<del> DEFAULTUNIXSOCKET = "/var/run/docker.sock"
<del> DefaultDockerfileName string = "Dockerfile"
<add> APIVERSION version.Version = "1.18" // Current REST API version
<add> DEFAULTHTTPHOST = "127.0.0.1" // Default HTTP Host used if only port is provided to -H flag e.g. docker -d -H tcp://:8080
<add> DEFAULTUNIXSOCKET = "/var/run/docker.sock" // Docker daemon by default always listens on the default unix socket
<add> DefaultDockerfileName string = "Dockerfile" // Default filename with Docker commands, read by docker build
<ide> )
<ide>
<ide> func ValidateHost(val string) (string, error) { | 1 |
Javascript | Javascript | add missing createmockwindow() | 670ca75c8ab3072af289ad6b136208c6ac2e0aa7 | <ide><path>docs/component-spec/annotationsSpec.js
<ide> describe('Docs Annotations', function() {
<ide> var $scope, parent, element, url, window;
<ide> beforeEach(function() {
<ide> module(function($provide, $animateProvider) {
<del> $provide.value('$window', window = angular.mock.createMockWindow());
<add> $provide.value('$window', window = createMockWindow());
<ide> $animateProvider.register('.foldout', function($timeout) {
<ide> return {
<ide> enter : function(element, done) {
<ide> describe('Docs Annotations', function() {
<ide> var window, $scope, ctrl;
<ide> beforeEach(function() {
<ide> module(function($provide, $animateProvider) {
<del> $provide.value('$window', window = angular.mock.createMockWindow());
<add> $provide.value('$window', window = createMockWindow());
<ide> });
<ide> inject(function($rootScope, $controller, $location, $cookies, sections) {
<ide> $scope = $rootScope.$new();
<ide><path>docs/component-spec/mocks.js
<add>var createMockWindow = function() {
<add> var mockWindow = {};
<add> var setTimeoutQueue = [];
<add>
<add> mockWindow.location = window.location;
<add> mockWindow.document = window.document;
<add> mockWindow.getComputedStyle = angular.bind(window, window.getComputedStyle);
<add> mockWindow.scrollTo = angular.bind(window, window.scrollTo);
<add> mockWindow.navigator = window.navigator;
<add> mockWindow.setTimeout = function(fn, delay) {
<add> setTimeoutQueue.push({fn: fn, delay: delay});
<add> };
<add> mockWindow.setTimeout.queue = setTimeoutQueue;
<add> mockWindow.setTimeout.expect = function(delay) {
<add> if (setTimeoutQueue.length > 0) {
<add> return {
<add> process: function() {
<add> var tick = setTimeoutQueue.shift();
<add> expect(tick.delay).toEqual(delay);
<add> tick.fn();
<add> }
<add> };
<add> } else {
<add> expect('SetTimoutQueue empty. Expecting delay of ').toEqual(delay);
<add> }
<add> };
<add>
<add> return mockWindow;
<add>};
<ide><path>docs/component-spec/versionJumpSpec.js
<ide> describe('DocsApp', function() {
<ide> '1.1.4',
<ide> '2.1.3'
<ide> ]);
<del> $provide.value('$window', window = angular.mock.createMockWindow());
<add> $provide.value('$window', window = createMockWindow());
<ide> });
<ide> inject(function($controller, $rootScope) {
<ide> $scope = $rootScope.$new(); | 3 |
PHP | PHP | remove addhidden method | a284f906193c22e0e0a5d827da9fc5f8916e081b | <ide><path>src/Illuminate/Database/Eloquent/Concerns/HidesAttributes.php
<ide> public function setHidden(array $hidden)
<ide> return $this;
<ide> }
<ide>
<del> /**
<del> * Add hidden attributes for the model.
<del> *
<del> * @param array|string|null $attributes
<del> * @return void
<del> */
<del> public function addHidden($attributes = null)
<del> {
<del> $this->hidden = array_merge(
<del> $this->hidden, is_array($attributes) ? $attributes : func_get_args()
<del> );
<del> }
<del>
<ide> /**
<ide> * Get the visible attributes for the model.
<ide> * | 1 |
Javascript | Javascript | fix benchmark script | 36ab982b813db42ed1aef3ba43eefeb5334dc594 | <ide><path>benchmark/createFixtures.js
<ide> var fs = require("fs");
<ide>
<ide> var fixtures = path.join(__dirname, "fixtures");
<ide>
<add>try { fs.mkdirSync(fixtures); } catch(e) {}
<add>
<ide>
<ide> for(var i = 0; i < 1000; i++) {
<ide> var source = []; | 1 |
Text | Text | fix example from to avoid double rendering | f5a9a26a43474ed902a6a2fa10e6a3b457c7333e | <ide><path>docs/tips/12-initial-ajax.md
<ide> var UserGist = React.createClass({
<ide> },
<ide>
<ide> componentDidMount: function() {
<del> this.setState({
<del> serverRequest: $.get(this.props.source, function(result) {
<del> var lastGist = result[0];
<del> this.setState({
<del> username: lastGist.owner.login,
<del> lastGistUrl: lastGist.html_url
<del> });
<del> }.bind(this))
<del> });
<add> this.serverRequest = $.get(this.props.source, function (result) {
<add> var lastGist = result[0];
<add> this.setState({
<add> username: lastGist.owner.login,
<add> lastGistUrl: lastGist.html_url
<add> });
<add> }.bind(this));
<ide> },
<del>
<add>
<ide> componentWillUnmount: function() {
<del> this.state.serverRequest.abort();
<add> this.serverRequest.abort();
<ide> },
<ide>
<ide> render: function() { | 1 |
Python | Python | fix equality check in test | 41744771611305363484f046b0271b5f0ea071aa | <ide><path>spacy/tests/parser/test_parse_navigate.py
<ide> def test_parser_parse_navigate_consistency(en_tokenizer, text, heads):
<ide> doc = get_doc(tokens.vocab, [t.text for t in tokens], heads=heads)
<ide> for head in doc:
<ide> for child in head.lefts:
<del> assert child.head is head
<add> assert child.head == head
<ide> for child in head.rights:
<del> assert child.head is head
<add> assert child.head == head
<ide>
<ide>
<ide> def test_parser_parse_navigate_child_consistency(en_tokenizer, text, heads): | 1 |
Text | Text | remove space before parens in anon-func | 35edaf26cbc6edafc7bbef063db01c17cac5a3e2 | <ide><path>STYLEGUIDE.md
<ide> if (foo === 'bara') {
<ide> }
<ide>
<ide> // parameters
<del>function (test, foo) {
<add>function(test, foo) {
<ide> }
<ide> ```
<ide> | 1 |
Javascript | Javascript | use weakmap for dom data | 8610f9967340b9ae7fc73d41ff0e9d17a54b0604 | <ide><path>src/js/component.js
<ide> import window from 'global/window';
<ide> import evented from './mixins/evented';
<ide> import stateful from './mixins/stateful';
<ide> import * as Dom from './utils/dom.js';
<del>import * as DomData from './utils/dom-data';
<add>import DomData from './utils/dom-data';
<ide> import * as Fn from './utils/fn.js';
<ide> import * as Guid from './utils/guid.js';
<ide> import toTitleCase from './utils/to-title-case.js';
<ide> class Component {
<ide> this.el_.parentNode.removeChild(this.el_);
<ide> }
<ide>
<del> DomData.removeData(this.el_);
<add> if (DomData.has(this.el_)) {
<add> DomData.delete(this.el_);
<add> }
<ide> this.el_ = null;
<ide> }
<ide>
<ide><path>src/js/utils/dom-data.js
<ide> * @file dom-data.js
<ide> * @module dom-data
<ide> */
<del>import * as Guid from './guid.js';
<del>import window from 'global/window';
<ide>
<ide> /**
<ide> * Element Data Store.
<ide> import window from 'global/window';
<ide> * @type {Object}
<ide> * @private
<ide> */
<del>export const elData = {};
<del>
<del>/*
<del> * Unique attribute name to store an element's guid in
<del> *
<del> * @type {String}
<del> * @constant
<del> * @private
<del> */
<del>const elIdAttr = 'vdata' + Math.floor(window.performance && window.performance.now() || Date.now());
<del>
<del>/**
<del> * Returns the cache object where data for an element is stored
<del> *
<del> * @param {Element} el
<del> * Element to store data for.
<del> *
<del> * @return {Object}
<del> * The cache object for that el that was passed in.
<del> */
<del>export function getData(el) {
<del> let id = el[elIdAttr];
<del>
<del> if (!id) {
<del> id = el[elIdAttr] = Guid.newGUID();
<del> }
<del>
<del> if (!elData[id]) {
<del> elData[id] = {};
<del> }
<del>
<del> return elData[id];
<del>}
<del>
<del>/**
<del> * Returns whether or not an element has cached data
<del> *
<del> * @param {Element} el
<del> * Check if this element has cached data.
<del> *
<del> * @return {boolean}
<del> * - True if the DOM element has cached data.
<del> * - False otherwise.
<del> */
<del>export function hasData(el) {
<del> const id = el[elIdAttr];
<del>
<del> if (!id) {
<del> return false;
<del> }
<del>
<del> return !!Object.getOwnPropertyNames(elData[id]).length;
<del>}
<del>
<del>/**
<del> * Delete data for the element from the cache and the guid attr from getElementById
<del> *
<del> * @param {Element} el
<del> * Remove cached data for this element.
<del> */
<del>export function removeData(el) {
<del> const id = el[elIdAttr];
<del>
<del> if (!id) {
<del> return;
<del> }
<del>
<del> // Remove all stored data
<del> delete elData[id];
<del>
<del> // Remove the elIdAttr property from the DOM node
<del> try {
<del> delete el[elIdAttr];
<del> } catch (e) {
<del> if (el.removeAttribute) {
<del> el.removeAttribute(elIdAttr);
<del> } else {
<del> // IE doesn't appear to support removeAttribute on the document element
<del> el[elIdAttr] = null;
<del> }
<del> }
<del>}
<add>export default new WeakMap();
<ide><path>src/js/utils/events.js
<ide> * @file events.js
<ide> * @module events
<ide> */
<del>import * as DomData from './dom-data';
<add>import DomData from './dom-data';
<ide> import * as Guid from './guid.js';
<ide> import log from './log.js';
<ide> import window from 'global/window';
<ide> import document from 'global/document';
<ide> * Type of event to clean up
<ide> */
<ide> function _cleanUpEvents(elem, type) {
<del> const data = DomData.getData(elem);
<add> if (!DomData.has(elem)) {
<add> return;
<add> }
<add> const data = DomData.get(elem);
<ide>
<ide> // Remove the events of a particular type if there are none left
<ide> if (data.handlers[type].length === 0) {
<ide> function _cleanUpEvents(elem, type) {
<ide>
<ide> // Finally remove the element data if there is no data left
<ide> if (Object.getOwnPropertyNames(data).length === 0) {
<del> DomData.removeData(elem);
<add> DomData.delete(elem);
<ide> }
<ide> }
<ide>
<ide> export function on(elem, type, fn) {
<ide> return _handleMultipleEvents(on, elem, type, fn);
<ide> }
<ide>
<del> const data = DomData.getData(elem);
<add> if (!DomData.has(elem)) {
<add> DomData.set(elem, {});
<add> }
<add>
<add> const data = DomData.get(elem);
<ide>
<ide> // We need a place to store all our handler data
<ide> if (!data.handlers) {
<ide> export function on(elem, type, fn) {
<ide> */
<ide> export function off(elem, type, fn) {
<ide> // Don't want to add a cache object through getElData if not needed
<del> if (!DomData.hasData(elem)) {
<add> if (!DomData.has(elem)) {
<ide> return;
<ide> }
<ide>
<del> const data = DomData.getData(elem);
<add> const data = DomData.get(elem);
<ide>
<ide> // If no events exist, nothing to unbind
<ide> if (!data.handlers) {
<ide> export function trigger(elem, event, hash) {
<ide> // Fetches element data and a reference to the parent (for bubbling).
<ide> // Don't want to add a data object to cache for every parent,
<ide> // so checking hasElData first.
<del> const elemData = (DomData.hasData(elem)) ? DomData.getData(elem) : {};
<add> const elemData = DomData.has(elem) ? DomData.get(elem) : {};
<ide> const parent = elem.parentNode || elem.ownerDocument;
<ide> // type = event.type || event,
<ide> // handler;
<ide> export function trigger(elem, event, hash) {
<ide>
<ide> // If at the top of the DOM, triggers the default action unless disabled.
<ide> } else if (!parent && !event.defaultPrevented && event.target && event.target[event.type]) {
<del> const targetData = DomData.getData(event.target);
<add> if (!DomData.has(event.target)) {
<add> DomData.set(event.target, {});
<add> }
<add> const targetData = DomData.get(event.target);
<ide>
<ide> // Checks if the target has a default action for this event.
<ide> if (event.target[event.type]) {
<ide><path>test/unit/component.test.js
<ide> import window from 'global/window';
<ide> import Component from '../../src/js/component.js';
<ide> import * as Dom from '../../src/js/utils/dom.js';
<del>import * as DomData from '../../src/js/utils/dom-data';
<add>import DomData from '../../src/js/utils/dom-data';
<ide> import * as Events from '../../src/js/utils/events.js';
<ide> import * as Obj from '../../src/js/utils/obj';
<ide> import * as browser from '../../src/js/utils/browser.js';
<ide> QUnit.test('should dispose of component and children', function(assert) {
<ide> return true;
<ide> });
<ide> const el = comp.el();
<del> const data = DomData.getData(el);
<add> const data = DomData.get(el);
<ide>
<ide> let hasDisposed = false;
<ide> let bubbles = null;
<ide> QUnit.test('should dispose of component and children', function(assert) {
<ide> assert.ok(!comp.el(), 'component element was deleted');
<ide> assert.ok(!child.children(), 'child children were deleted');
<ide> assert.ok(!child.el(), 'child element was deleted');
<del> assert.ok(!DomData.hasData(el), 'listener data nulled');
<add> assert.ok(!DomData.has(el), 'listener data nulled');
<ide> assert.ok(
<ide> !Object.getOwnPropertyNames(data).length,
<ide> 'original listener data object was emptied'
<ide> QUnit.test('*AnimationFrame methods fall back to timers if rAF not supported', f
<ide> QUnit.test('setTimeout should remove dispose handler on trigger', function(assert) {
<ide> const comp = new Component(getFakePlayer());
<ide> const el = comp.el();
<del> const data = DomData.getData(el);
<add> const data = DomData.get(el);
<ide>
<ide> comp.setTimeout(() => {}, 1);
<ide>
<ide> QUnit.test('setTimeout should remove dispose handler on trigger', function(asser
<ide> QUnit.test('requestAnimationFrame should remove dispose handler on trigger', function(assert) {
<ide> const comp = new Component(getFakePlayer());
<ide> const el = comp.el();
<del> const data = DomData.getData(el);
<add> const data = DomData.get(el);
<ide> const oldRAF = window.requestAnimationFrame;
<ide> const oldCAF = window.cancelAnimationFrame;
<ide>
<ide><path>test/unit/menu.test.js
<ide> /* eslint-env qunit */
<del>import * as DomData from '../../src/js/utils/dom-data';
<add>import DomData from '../../src/js/utils/dom-data';
<ide> import MenuButton from '../../src/js/menu/menu-button.js';
<ide> import Menu from '../../src/js/menu/menu.js';
<ide> import CaptionSettingsMenuItem from '../../src/js/control-bar/text-track-controls/caption-settings-menu-item';
<ide> QUnit.test('should remove old event listeners when the menu item adds to the new
<ide> * A reusable collection of assertions.
<ide> */
<ide> function validateMenuEventListeners(watchedMenu) {
<del> const eventData = DomData.getData(menuItem.eventBusEl_);
<add> const eventData = DomData.get(menuItem.eventBusEl_);
<ide> // `MenuButton`.`unpressButton` will be called when triggering click event on the menu item.
<ide> const unpressButtonSpy = sinon.spy(menuButton, 'unpressButton');
<ide> // `MenuButton`.`focus` will be called when triggering click event on the menu item.
<ide><path>test/unit/utils/dom-data.test.js
<del>/* eslint-env qunit */
<del>import document from 'global/document';
<del>import * as DomData from '../../../src/js/utils/dom-data';
<del>import videojs from '../../../src/js/video.js';
<del>import window from 'global/window';
<del>
<del>QUnit.module('dom-data');
<del>
<del>QUnit.test('should get and remove data from an element', function(assert) {
<del> const el = document.createElement('div');
<del> const data = DomData.getData(el);
<del>
<del> assert.strictEqual(typeof data, 'object', 'data object created');
<del>
<del> // Add data
<del> const testData = {asdf: 'fdsa'};
<del>
<del> data.test = testData;
<del> assert.strictEqual(DomData.getData(el).test, testData, 'data added');
<del>
<del> // Remove all data
<del> DomData.removeData(el);
<del>
<del> assert.notOk(DomData.hasData(el), 'cached item emptied');
<del>});
<del>
<del>let memoryTestRun = false;
<del>
<del>QUnit.done(function(details) {
<del> // don't run the extra dom data test on failures, there will likely be
<del> // memory leaks
<del> if (details.failed || memoryTestRun) {
<del> return;
<del> }
<del>
<del> memoryTestRun = true;
<del>
<del> QUnit.module('dom-data memory');
<del>
<del> /**
<del> * If this test fails you will want to add a debug statement
<del> * in DomData.getData with the `id`. For instance if DomData.elData
<del> * had 2 objects in it {5: {...}, 2003: {...} you would add:
<del> *
<del> * ```js
<del> * if (id === 5) {
<del> * debugger;
<del> * }
<del> * ```
<del> * to the tests to see what test. Then re-run the tests to see
<del> * what leaking and where.
<del> *
<del> * > Note that the id can be off by 1-2 in either direction
<del> * for larger guids, so you may have to account for that.
<del> */
<del> QUnit.test('Memory is not leaking', function(assert) {
<del> if (Object.keys(DomData.elData).length > 0) {
<del> videojs.domData = DomData;
<del> window.videojs = videojs;
<del> }
<del> assert.equal(Object.keys(DomData.elData).length, 0, 'no leaks, check videojs.domData.elData if failure');
<del> });
<del>});
<ide><path>test/unit/videojs-integration.test.js
<ide> import videojs from '../../src/js/video.js';
<ide> import window from 'global/window';
<ide> import document from 'global/document';
<del>import * as DomData from '../../src/js/utils/dom-data';
<ide> import * as Fn from '../../src/js/utils/fn';
<ide>
<ide> /**
<ide> QUnit.test('create a real player and dispose', function(assert) {
<ide>
<ide> player.muted(true);
<ide>
<del> const checkDomData = function() {
<del> Object.keys(DomData.elData).forEach(function(elId) {
<del> const data = DomData.elData[elId] || {};
<del>
<del> Object.keys(data.handlers || {}).forEach(function(eventName) {
<del> const listeners = data.handlers[eventName];
<del> const uniqueList = [];
<del>
<del> (listeners || []).forEach(function(listener) {
<del> let add = true;
<del>
<del> for (let i = 0; i < uniqueList.length; i++) {
<del> const obj = uniqueList[i];
<del>
<del> if (listener.og_ && listener.cx_ && obj.fn === listener.og_ && obj.cx === listener.cx_) {
<del> add = false;
<del> break;
<del> }
<del>
<del> if (listener.og_ && !listener.cx_ && obj.fn === listener.og_) {
<del> add = false;
<del> break;
<del> }
<del>
<del> if (!listener.og_ && !listener.cx_ && obj.fn === listener) {
<del> add = false;
<del> break;
<del> }
<del> }
<del> const obj = {fn: listener.og_ || listener, cx: listener.cx_};
<del>
<del> if (add) {
<del> uniqueList.push(obj);
<del> assert.ok(true, `${elId}/${eventName}/${obj.fn.name} is unique`);
<del> } else {
<del> assert.ok(false, `${elId}/${eventName}/${obj.fn.name} is not unique`);
<del> }
<del> });
<del> });
<del> });
<del> };
<del>
<ide> player.addTextTrack('captions', 'foo', 'en');
<ide> player.ready(function() {
<ide> assert.ok(player.tech_, 'tech exists');
<ide> assert.equal(player.textTracks().length, 1, 'should have one text track');
<ide>
<del> checkDomData();
<ide> player.dispose();
<ide>
<ide> Object.keys(old).forEach(function(k) { | 7 |
Javascript | Javascript | fix vertical alignment of legend labels | a9308301e34d3fb39462a8ed24e0fd09c7f388ef | <ide><path>src/plugins/plugin.legend.js
<ide> module.exports = function(Chart) {
<ide>
<ide> // Canvas setup
<ide> ctx.textAlign = 'left';
<del> ctx.textBaseline = 'top';
<add> ctx.textBaseline = 'middle';
<ide> ctx.lineWidth = 0.5;
<ide> ctx.strokeStyle = fontColor; // for strikethrough effect
<ide> ctx.fillStyle = fontColor; // render in correct colour
<ide> module.exports = function(Chart) {
<ide> ctx.restore();
<ide> };
<ide> var fillText = function(x, y, legendItem, textWidth) {
<del> ctx.fillText(legendItem.text, boxWidth + (fontSize / 2) + x, y);
<add> var halfFontSize = fontSize / 2;
<add> var xLeft = boxWidth + halfFontSize + x;
<add> var yMiddle = y + halfFontSize;
<add>
<add> ctx.fillText(legendItem.text, xLeft, yMiddle);
<ide>
<ide> if (legendItem.hidden) {
<ide> // Strikethrough the text if hidden
<ide> ctx.beginPath();
<ide> ctx.lineWidth = 2;
<del> ctx.moveTo(boxWidth + (fontSize / 2) + x, y + (fontSize / 2));
<del> ctx.lineTo(boxWidth + (fontSize / 2) + x + textWidth, y + (fontSize / 2));
<add> ctx.moveTo(xLeft, yMiddle);
<add> ctx.lineTo(xLeft + textWidth, yMiddle);
<ide> ctx.stroke();
<ide> }
<ide> }; | 1 |
Javascript | Javascript | remove redundant common.mustcall | e96e3f9eb0610168b0b06977664c0e713571b066 | <ide><path>test/parallel/test-fs-readfile-error.js
<ide> function test(env, cb) {
<ide> const filename = fixtures.path('test-fs-readfile-error.js');
<ide> const execPath = `"${process.execPath}" "${filename}"`;
<ide> const options = { env: Object.assign({}, process.env, env) };
<del> exec(execPath, options, common.mustCall((err, stdout, stderr) => {
<add> exec(execPath, options, (err, stdout, stderr) => {
<ide> assert(err);
<ide> assert.strictEqual(stdout, '');
<ide> assert.notStrictEqual(stderr, '');
<ide> cb(String(stderr));
<del> }));
<add> });
<ide> }
<ide>
<ide> test({ NODE_DEBUG: '' }, common.mustCall((data) => { | 1 |
Javascript | Javascript | add common.mustcall function | d0e6c3f5a644e4f84e80e9081d28570bf7477391 | <ide><path>test/common.js
<ide> process.on('exit', function() {
<ide> });
<ide>
<ide>
<del>// This function allows one two run an HTTP test agaist both HTTPS and
<del>// normal HTTP modules. This ensures they fit the same API.
<del>exports.httpTest = function httpTest(cb) {
<del>};
<add>var mustCallChecks = [];
<add>
<add>
<add>function runCallChecks() {
<add> var failed = mustCallChecks.filter(function(context) {
<add> return context.actual !== context.expected;
<add> });
<add>
<add> failed.forEach(function(context) {
<add> console.log('Mismatched %s function calls. Expected %d, actual %d.',
<add> context.name,
<add> context.expected,
<add> context.actual);
<add> console.log(context.stack.split('\n').slice(2).join('\n'));
<add> });
<add>
<add> if (failed.length) process.exit(1);
<add>}
<ide>
<add>
<add>exports.mustCall = function(fn, expected) {
<add> if (typeof expected !== 'number') expected = 1;
<add>
<add> var context = {
<add> expected: expected,
<add> actual: 0,
<add> stack: (new Error).stack,
<add> name: fn.name || '<anonymous>'
<add> };
<add>
<add> // add the exit listener only once to avoid listener leak warnings
<add> if (mustCallChecks.length === 0) process.on('exit', runCallChecks);
<add>
<add> mustCallChecks.push(context);
<add>
<add> return function() {
<add> context.actual++;
<add> return fn.apply(this, arguments);
<add> };
<add>}; | 1 |
Javascript | Javascript | fix typo in component lookup assert | 82843abdb5820378fec5501dee280b4d4d0554ea | <ide><path>packages/ember-htmlbars/tests/integration/component_lookup_test.js
<ide> QUnit.test('dashless components should not be found', function() {
<ide>
<ide> expectAssertion(function() {
<ide> runAppend(view);
<del> }, /You canot use 'dashless' as a component name. Component names must contain a hyphen./);
<add> }, /You cannot use 'dashless' as a component name. Component names must contain a hyphen./);
<ide> });
<ide><path>packages/ember-views/lib/component_lookup.js
<ide> export default EmberObject.extend({
<ide> var invalidName = ISNT_HELPER_CACHE.get(name);
<ide>
<ide> if (invalidName) {
<del> Ember.assert(`You canot use '${name}' as a component name. Component names must contain a hyphen.`);
<add> Ember.assert(`You cannot use '${name}' as a component name. Component names must contain a hyphen.`);
<ide> }
<ide> },
<ide> | 2 |
Python | Python | add the default none when pop actions | 6434b5770877d75fba3c0c49fd808d6413367ab4 | <ide><path>airflow/www/fab_security/views.py
<ide> def class_permission_name(self, name):
<ide> def show(self, pk):
<ide> pk = self._deserialize_pk_if_composite(pk)
<ide> widgets = self._show(pk)
<del> widgets['show'].template_args['actions'].pop('userinfoedit')
<add> widgets['show'].template_args['actions'].pop('userinfoedit', None)
<ide> return self.render_template(
<ide> self.show_template,
<ide> pk=pk, | 1 |
PHP | PHP | prevent infinite loop caused when argv not set | d62e5e1b00bea33df3240d40a06143018724cf22 | <ide><path>lib/Cake/Console/ShellDispatcher.php
<ide> public function parseParams($args) {
<ide> protected function _parsePaths($args) {
<ide> $parsed = array();
<ide> $keys = array('-working', '--working', '-app', '--app', '-root', '--root');
<add> $args = (array)$args;
<ide> foreach ($keys as $key) {
<ide> while (($index = array_search($key, $args)) !== false) {
<ide> $keyname = str_replace('-', '', $key); | 1 |
Ruby | Ruby | improve matching of sparkle strategy | 605c33c70ce5e57d6a7762afc0c52faf70d4a692 | <ide><path>Library/Homebrew/livecheck/strategy.rb
<ide> def from_url(url, livecheck_strategy: nil, url_provided: nil, regex_provided: ni
<ide> # Only treat the `PageMatch` strategy as usable if a regex is
<ide> # present in the `livecheck` block
<ide> next unless regex_provided || block_provided
<del> elsif strategy == Sparkle && (from_symbol(livecheck_strategy) != Sparkle || !url_provided)
<del> # Skip the `Sparkle` strategy if a strategy is specified explicitly
<add> elsif strategy == Sparkle
<add> # Skip the `Sparkle` strategy if another strategy is specified explicitly
<ide> # or if the URL is not specified explicitly.
<del> next
<add> next unless url_provided
<add> next if livecheck_strategy && from_symbol(livecheck_strategy) != strategy
<ide> elsif strategy.const_defined?(:PRIORITY) &&
<ide> !strategy::PRIORITY.positive? &&
<ide> from_symbol(livecheck_strategy) != strategy | 1 |
PHP | PHP | convert frame guard to middleware | 4492b52ca5b8d2e5220b82de0630a147e9ad1357 | <ide><path>src/Illuminate/Http/FrameGuard.php
<del><?php namespace Illuminate\Http;
<add><?php namespace Illuminate\Http\Middleware;
<ide>
<del>use Symfony\Component\HttpKernel\HttpKernelInterface;
<del>use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
<add>use Closure;
<add>use Illuminate\Contracts\Routing\Middleware;
<ide>
<del>class FrameGuard implements HttpKernelInterface {
<del>
<del> /**
<del> * The wrapped kernel implementation.
<del> *
<del> * @var \Symfony\Component\HttpKernel\HttpKernelInterface
<del> */
<del> protected $app;
<del>
<del> /**
<del> * Create a new FrameGuard instance.
<del> *
<del> * @param \Symfony\Component\HttpKernel\HttpKernelInterface $app
<del> * @return void
<del> */
<del> public function __construct(HttpKernelInterface $app)
<del> {
<del> $this->app = $app;
<del> }
<add>class FrameGuard implements Middleware {
<ide>
<ide> /**
<ide> * Handle the given request and get the response.
<ide> *
<del> * @implements HttpKernelInterface::handle
<del> *
<del> * @param \Symfony\Component\HttpFoundation\Request $request
<del> * @param int $type
<del> * @param bool $catch
<del> * @return \Symfony\Component\HttpFoundation\Response
<add> * @param \Illuminate\Http\Request $request
<add> * @param \Closure $next
<add> * @return \Illuminate\Http\Response
<ide> */
<del> public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
<add> public function handle($request, Closure $next)
<ide> {
<del> $response = $this->app->handle($request, $type, $catch);
<add> $response = $next($request);
<ide>
<ide> $response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);
<ide> | 1 |
PHP | PHP | fix problem with bundle assets | 9e690c8af6ad14617f81850a898cfc21c590a30f | <ide><path>laravel/bundle.php
<ide> public static function path($bundle)
<ide> */
<ide> public static function assets($bundle)
<ide> {
<del> return ($bundle != DEFAULT_BUNDLE) ? URL::base()."/bundles/{$bundle}/" : PUBLIC_PATH;
<add> return ($bundle != DEFAULT_BUNDLE) ? URL::base()."/bundles/{$bundle}/" : URL::base().'/';
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | fix url generation bug | cedc9d443c66f467a44edf7dbd291ae36cc5a4f9 | <ide><path>src/Illuminate/Routing/RouteCollection.php
<ide> protected function addLookups($route)
<ide> // is used by the route. This will let us reverse route to controllers while
<ide> // processing a request and easily generate URLs to the given controllers.
<ide> if (isset($action['controller']))
<add> {
<add> $this->addToActionList($action, $route);
<add> }
<add> }
<add>
<add> /**
<add> * Add a route to the controller action dictionary.
<add> *
<add> * @param array $action
<add> * @param \Illuminate\Routing\Route $route
<add> * @return void
<add> */
<add> protected function addToActionList($action, $route)
<add> {
<add> if ( ! isset($this->actionList[$action['controller']]))
<ide> {
<ide> $this->actionList[$action['controller']] = $route;
<ide> } | 1 |
Python | Python | address comments on | 4b1d5cbf24174b1ed96824e706f74c84841633bc | <ide><path>numpy/lib/tests/test_type_check.py
<ide> def test_generic(self):
<ide> assert_(vals[1] == 0)
<ide> assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
<ide> assert_equal(type(vals), np.ndarray)
<add>
<add> # perform the same tests but with nan, posinf and neginf keywords
<add> with np.errstate(divide='ignore', invalid='ignore'):
<add> vals = nan_to_num(np.array((-1., 0, 1))/0.,
<add> nan=10, posinf=20, neginf=30)
<add> assert_all(vals[0] == 30) and assert_all(np.isfinite(vals[0]))
<add> assert_(vals[1] == 10)
<add> assert_all(vals[2] == 20) and assert_all(np.isfinite(vals[2]))
<add> assert_equal(type(vals), np.ndarray)
<ide>
<ide> # perform the same test but in-place
<ide> with np.errstate(divide='ignore', invalid='ignore'):
<ide> def test_generic(self):
<ide> assert_(vals[1] == 0)
<ide> assert_all(vals[2] > 1e10) and assert_all(np.isfinite(vals[2]))
<ide> assert_equal(type(vals), np.ndarray)
<add>
<add> # perform the same test but in-place
<add> with np.errstate(divide='ignore', invalid='ignore'):
<add> vals = np.array((-1., 0, 1))/0.
<add> result = nan_to_num(vals, copy=False, nan=10, posinf=20, neginf=30)
<add>
<add> assert_(result is vals)
<add> assert_all(vals[0] == 30) and assert_all(np.isfinite(vals[0]))
<add> assert_(vals[1] == 10)
<add> assert_all(vals[2] == 20) and assert_all(np.isfinite(vals[2]))
<add> assert_equal(type(vals), np.ndarray)
<ide>
<ide> def test_array(self):
<ide> vals = nan_to_num([1])
<ide> assert_array_equal(vals, np.array([1], int))
<ide> assert_equal(type(vals), np.ndarray)
<add> vals = nan_to_num([1], nan=10, posinf=20, neginf=30)
<add> assert_array_equal(vals, np.array([1], int))
<add> assert_equal(type(vals), np.ndarray)
<ide>
<ide> def test_integer(self):
<ide> vals = nan_to_num(1)
<ide> assert_all(vals == 1)
<ide> assert_equal(type(vals), np.int_)
<add> vals = nan_to_num(1, nan=10, posinf=20, neginf=30)
<add> assert_all(vals == 1)
<add> assert_equal(type(vals), np.int_)
<ide>
<ide> def test_float(self):
<ide> vals = nan_to_num(1.0)
<ide> assert_all(vals == 1.0)
<ide> assert_equal(type(vals), np.float_)
<add> vals = nan_to_num(1.1, nan=10, posinf=20, neginf=30)
<add> assert_all(vals == 1.1)
<add> assert_equal(type(vals), np.float_)
<ide>
<ide> def test_complex_good(self):
<ide> vals = nan_to_num(1+1j)
<ide> assert_all(vals == 1+1j)
<ide> assert_equal(type(vals), np.complex_)
<add> vals = nan_to_num(1+1j, nan=10, posinf=20, neginf=30)
<add> assert_all(vals == 1+1j)
<add> assert_equal(type(vals), np.complex_)
<ide>
<ide> def test_complex_bad(self):
<ide> with np.errstate(divide='ignore', invalid='ignore'):
<ide> def test_complex_bad2(self):
<ide> # !! inf. Comment out for now, and see if it
<ide> # !! changes
<ide> #assert_all(vals.real < -1e10) and assert_all(np.isfinite(vals))
<add>
<add> def test_do_not_rewrite__previous_keyword(self):
<add> # This is done to test that when, for instance, nan=np.inf then these
<add> # values are not rewritten by posinf keyword to the posinf value.
<add> with np.errstate(divide='ignore', invalid='ignore'):
<add> vals = nan_to_num(np.array((-1., 0, 1))/0., nan=np.inf, posinf=999)
<add> assert_all(vals[0] < -1e10) and assert_all(np.isfinite(vals[0]))
<add> assert_(vals[1] == np.inf)
<add> assert_all(vals[2] == 999) and assert_all(np.isfinite(vals[2]))
<add> assert_equal(type(vals), np.ndarray)
<ide>
<ide>
<ide> class TestRealIfClose(object):
<ide><path>numpy/lib/type_check.py
<ide> def _getmaxmin(t):
<ide> return f.max, f.min
<ide>
<ide>
<del>def _nan_to_num_dispatcher(x, copy=None):
<add>def _nan_to_num_dispatcher(x, copy=None, nan=None, posinf=None, neginf=None):
<ide> return (x,)
<ide>
<ide>
<ide> @array_function_dispatch(_nan_to_num_dispatcher)
<del>def nan_to_num(x, copy=True):
<add>def nan_to_num(x, copy=True, nan=0.0, posinf=None, neginf=None):
<ide> """
<del> Replace NaN with zero and infinity with large finite numbers.
<add> Replace NaN with zero and infinity with large finite numbers (default
<add> behaviour) or with the numbers defined by the user using the `nan`,
<add> `posinf` and/or `neginf` keywords.
<ide>
<del> If `x` is inexact, NaN is replaced by zero, and infinity and -infinity
<del> replaced by the respectively largest and most negative finite floating
<del> point values representable by ``x.dtype``.
<add> If `x` is inexact, NaN is replaced by zero or by the user defined value in
<add> `nan` keyword, infinity is replaced by the largest finite floating point
<add> values representable by ``x.dtype`` or by the user defined value in
<add> `posinf` keyword and -infinity is replaced by the most negative finite
<add> floating point values representable by ``x.dtype`` or by the user defined
<add> value in `neginf` keyword.
<ide>
<ide> For complex dtypes, the above is applied to each of the real and
<ide> imaginary components of `x` separately.
<ide> def nan_to_num(x, copy=True):
<ide> in-place (False). The in-place operation only occurs if
<ide> casting to an array does not require a copy.
<ide> Default is True.
<add> nan : int, float, optional
<add> Value to be used to fill NaN values. If no value is passed
<add> then NaN values will be replaced with 0.0.
<add> posinf : int, float, optional
<add> Value to be used to fill positive infinity values. If no value is
<add> passed then positive infinity values will be replaced with a very
<add> large number.
<add> neginf : int, float, optional
<add> Value to be used to fill negative infinity values. If no value is
<add> passed then negative infinity values will be replaced with a very
<add> small (or negative) number.
<ide>
<ide> .. versionadded:: 1.13
<ide>
<ide> def nan_to_num(x, copy=True):
<ide> >>> np.nan_to_num(x)
<ide> array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary
<ide> -1.28000000e+002, 1.28000000e+002])
<add> >>> np.nan_to_num(x, nan=-9999, posinf=33333333, neginf=33333333)
<add> array([ 3.3333333e+07, 3.3333333e+07, -9.9990000e+03,
<add> -1.2800000e+02, 1.2800000e+02])
<ide> >>> y = np.array([complex(np.inf, np.nan), np.nan, complex(np.nan, np.inf)])
<ide> array([ 1.79769313e+308, -1.79769313e+308, 0.00000000e+000, # may vary
<ide> -1.28000000e+002, 1.28000000e+002])
<ide> >>> np.nan_to_num(y)
<ide> array([ 1.79769313e+308 +0.00000000e+000j, # may vary
<ide> 0.00000000e+000 +0.00000000e+000j,
<ide> 0.00000000e+000 +1.79769313e+308j])
<add> >>> np.nan_to_num(y, nan=111111, posinf=222222)
<add> array([222222.+111111.j, 111111. +0.j, 111111.+222222.j])
<ide> """
<ide> x = _nx.array(x, subok=True, copy=copy)
<ide> xtype = x.dtype.type
<ide> def nan_to_num(x, copy=True):
<ide>
<ide> dest = (x.real, x.imag) if iscomplex else (x,)
<ide> maxf, minf = _getmaxmin(x.real.dtype)
<add> if posinf is not None:
<add> maxf = posinf
<add> if neginf is not None:
<add> minf = neginf
<ide> for d in dest:
<del> _nx.copyto(d, 0.0, where=isnan(d))
<del> _nx.copyto(d, maxf, where=isposinf(d))
<del> _nx.copyto(d, minf, where=isneginf(d))
<add> idx_nan = isnan(d)
<add> idx_posinf = isposinf(d)
<add> idx_neginf = isneginf(d)
<add> _nx.copyto(d, nan, where=idx_nan)
<add> _nx.copyto(d, maxf, where=idx_posinf)
<add> _nx.copyto(d, minf, where=idx_neginf)
<ide> return x[()] if isscalar else x
<ide>
<ide> #----------------------------------------------------------------------------- | 2 |
Text | Text | prepare changelog for 0.69.0 | d27c8cf02d57110d2f45ccd9ab74ea6d774b69b5 | <ide><path>CHANGELOG.md
<ide> # Changelog
<ide>
<add>## v0.69.0
<add>
<add>### Breaking
<add>
<add>- Support for `console.disableYellowBox` [has been dropped](https://github.com/facebook/react-native/commit/b633cc130533f0731b2577123282c4530e4f0abe)
<add>- Already deprecated prop types have been removed ([cdfddb4dad](https://github.com/facebook/react-native/commit/cdfddb4dad7c69904850d7e5f089a32a1d3445d1), [3e229f27bc](https://github.com/facebook/react-native/commit/3e229f27bc9c7556876ff776abf70147289d544b), [10199b1581](https://github.com/facebook/react-native/commit/10199b158138b8645550b5579df87e654213fe42))
<add>- `removeListener`, deprecated since RN0.65, [was removed](https://github.com/facebook/react-native/commit/8dfbed786b40082a7a222e00dc0a621c0695697d) from Appearance
<add>- If you were using `SegmentedComponentIOS`, you will now need to move to the [segmented-control](https://github.com/react-native-segmented-control/segmented-control) library ([235f168574](https://github.com/facebook/react-native/commit/235f1685748442553e53f8ec6d904bc0314a8ae6))
<add>
<add>### Added
<add>
<add>- Add Hermes scripts to package ([004b8609d9](https://github.com/facebook/react-native/commit/004b8609d97b14a6d5cb8c9e63afdbe343c500da) by [@hramos](https://github.com/hramos))
<add>- Expose scheduler through FabricUIManager ([1730949e94](https://github.com/facebook/react-native/commit/1730949e94aa23927a90d2a64d91977b7e2904d6) by [@cortinico](https://github.com/cortinico))
<add>- Add event listeners to Scheduler ([e51e19ecc1](https://github.com/facebook/react-native/commit/e51e19ecc1d1b8ac5c860eac55338ef13471844f) by [@cortinico](https://github.com/cortinico))
<add>- C++ TurboModule methods can return functions ([c7380ba113](https://github.com/facebook/react-native/commit/c7380ba1131b26b487ecae87239a4cf82afefd15) by [@appden](https://github.com/appden))
<add>- Add support for devtools' profiler ([fefa7b6ac8](https://github.com/facebook/react-native/commit/fefa7b6ac8a1e0e33fa7a1070936c5c83c873c0a) by [@jpporto](https://github.com/jpporto))
<add>- Add getAll function to FormData class for getting all parts containing that key. This is also available in web API. ([d05a5d1551](https://github.com/facebook/react-native/commit/d05a5d15512ab794ef80b31ef91090d5d88b3fcd) by [@matinzd](https://github.com/matinzd))
<add>- Automatic type conversions for C++ TurboModules ([31f0796237](https://github.com/facebook/react-native/commit/31f079623732fb017b1fa38d56abe855d7738ece) by [@appden](https://github.com/appden))
<add>- New bridging API for JSI <-> C++ ([30cb78e709](https://github.com/facebook/react-native/commit/30cb78e709bccb4f7bf7aab3f6b0f1ba4261f577) by [@appden](https://github.com/appden))
<add>- Add asBool() method to JSI ([603620b739](https://github.com/facebook/react-native/commit/603620b7394da5855e2255790bfea9ad7d80ddf9) by [@appden](https://github.com/appden))
<add>- CustomEvent and Event polyfills for React Native ([6abbef1200](https://github.com/facebook/react-native/commit/6abbef1200af9adab1848de17955d77fbe0ad5da) by [@JoshuaGross](https://github.com/JoshuaGross))
<add>- Implement Runtime.getHeapUsage for hermes chrome inspector ([cff9590864](https://github.com/facebook/react-native/commit/cff9590864c4be153a4eb49757b7cac8b3f23f66) by [@janicduplessis](https://github.com/janicduplessis))
<add>- Introduce ReactNativeFeatureFlags file to control FeatureFlags in React Native ([33aba77456](https://github.com/facebook/react-native/commit/33aba774564acdec216e02e28f17ad08ad7bc26b) by [@mdvacca](https://github.com/mdvacca))
<add>- Added fail-safe check to catch MissingWebViewPackage Exception ([8c573d9336](https://github.com/facebook/react-native/commit/8c573d933652ae4da1008502c53fce93057101c0) by [@Kunal-Airtel2022](https://github.com/Kunal-Airtel2022))
<add>- Add ability to access properties with symbol keys through JSI ([9010bfe457](https://github.com/facebook/react-native/commit/9010bfe457b77862024214ce6210504ff1786ef5) by [@neildhar](https://github.com/neildhar))
<add>- Allow color styles to be animated using native driver ([201f355479](https://github.com/facebook/react-native/commit/201f355479cafbcece3d9eb40a52bae003da3e5c) by [@genkikondo](https://github.com/genkikondo))
<add>- Make react-native depend on react-native-gradle-plugin ([3346efb7d4](https://github.com/facebook/react-native/commit/3346efb7d422bd8eb7f48650b454071f9981fa0b) by [@cortinico](https://github.com/cortinico))
<add>- Add RawEventTelemetryEventEmitter interface to ReactNativePrivateInterface ([1f15a64028](https://github.com/facebook/react-native/commit/1f15a6402869b001cae049facc17126924b97197) by [@JoshuaGross](https://github.com/JoshuaGross))
<add>- Implement Runtime.getHeapUsage for hermes chrome inspector ([3568a72987](https://github.com/facebook/react-native/commit/3568a7298738a651d76c70763362c297ab601ee8) by [@janicduplessis](https://github.com/janicduplessis))
<add>- Add support for C++17 in OSS ([c2e4ae39b8](https://github.com/facebook/react-native/commit/c2e4ae39b8a5c6534a3fa4dae4130166eda15169) by [@sammy-SC](https://github.com/sammy-SC))
<add>
<add>#### Android specific
<add>
<add>- Generate `Nullable` for optional objects and arrays in module codegen. ([ffaa5d69bc](https://github.com/facebook/react-native/commit/ffaa5d69bc268918891121e2d60e7ca08ee82530))
<add>- Expose an API to enable Concurrent Root on Android ([d7b64b8d4b](https://github.com/facebook/react-native/commit/d7b64b8d4b2f403ce00b27c5df89ffb3a64dc6de) by [@cortinico](https://github.com/cortinico))
<add>- Add scrollEventThrottle prop support in Android ([cf55fd587e](https://github.com/facebook/react-native/commit/cf55fd587e6cc82a73079be6076d244ab72fa359) by [@ryancat](https://github.com/ryancat))
<add>- Accessibility announcement for list and grid in FlatList ([dd6325bafe](https://github.com/facebook/react-native/commit/dd6325bafe1a539d348f3710e717a6344576b859) by [@fabriziobertoglio1987](https://github.com/fabriziobertoglio1987))
<add>- Introduce ModuleDataCleaner.cleanDataFromModules(ReactContext) ([184dfb8f8b](https://github.com/facebook/react-native/commit/184dfb8f8bd4dfbb8d1575e9554e3f3361793015) by [@RSNara](https://github.com/RSNara))
<add>- Introduce ReactContext.getNativeModules() ([b978308519](https://github.com/facebook/react-native/commit/b978308519f71c6c7fda4b38a842aa219a349275) by [@RSNara](https://github.com/RSNara))
<add>- MapBuffer implementation for JVM -> C++ communication ([cf6f3b680b](https://github.com/facebook/react-native/commit/cf6f3b680b43fae31e97b14af681293503025a0c))
<add>- Make links independently focusable by Talkback ([7b5b114d57](https://github.com/facebook/react-native/commit/7b5b114d578142d18bf4a7a5279b179a9ac8d958) by [@fabriziobertoglio1987](https://github.com/fabriziobertoglio1987))
<add>- Support animating text color with native driver ([87cdb607e4](https://github.com/facebook/react-native/commit/87cdb607e4792156d433c44b89932e7dae3371da) by [@genkikondo](https://github.com/genkikondo))
<add>- Added an experimental prop serialization path based on MapBuffer ([cbcdaae2b5](https://github.com/facebook/react-native/commit/cbcdaae2b5dda2a44c95d83dcb5b5aa0f43bc6f9))
<add>- Allow to setup a Gradle Enterprise instance via an external script ([f11dcfaea1](https://github.com/facebook/react-native/commit/f11dcfaea14249b059aea2474ce36a0665140d4f) by [@cortinico](https://github.com/cortinico))
<add>- Support platform color with AnimatedColor ([cb42049e0a](https://github.com/facebook/react-native/commit/cb42049e0ae262afe907ace1099414836ab0018d) by [@genkikondo](https://github.com/genkikondo))
<add>- Support running animations with AnimatedColor with native driver ([3f49e6763e](https://github.com/facebook/react-native/commit/3f49e6763e66447f6ae17dc2f032e27330b7b74a) by [@genkikondo](https://github.com/genkikondo))
<add>- Add public API to ReactRootView to control if JS touch events are dispatched ([0a517ae438](https://github.com/facebook/react-native/commit/0a517ae43892fb764d829f8bae56c1ac58356b1b) by [@ryancat](https://github.com/ryancat))
<add>
<add>#### iOS specific
<add>
<add>- Prepare a method in the AppDelegate to control the concurrentRoot. ([8ac8439e0d](https://github.com/facebook/react-native/commit/8ac8439e0dcc0cc4a9c0cc99f614a5e19bae56eb) by [@cipolleschi](https://github.com/cipolleschi))
<add>- `hotkeysEnabled` property is added to `RCTDevMenu` which allows enabling/disabling hotkeys that triggers developer menu popup ([1a1a304ed2](https://github.com/facebook/react-native/commit/1a1a304ed2023d60547aef65b1a7bf56467edf08))
<add>- Allow modifying iOS image cache limits ([61b013e7ad](https://github.com/facebook/react-native/commit/61b013e7ad8a1cc28ee39434d2fd96b74b96cf5f) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Add dismissActionSheet method to ActionSheetIOS ([64ebe5bbdd](https://github.com/facebook/react-native/commit/64ebe5bbdd32fc3b3a243a8a81a6f724d8f81267) by [@gabrieldonadel](https://github.com/gabrieldonadel))
<add>- Integrated the `accessibilityLanguage` prop to all the available components. The prop is available for any platform but it will work only on iOS. ([7b05b091fd](https://github.com/facebook/react-native/commit/7b05b091fd97f95b778369277ac2147730abc7b8) by [@dgopsq](https://github.com/dgopsq))
<add>- Support running animations with AnimatedColor with native driver ([49f3f47b1e](https://github.com/facebook/react-native/commit/49f3f47b1e9b840e4374d46b105604f4d2c22dd5) by [@genkikondo](https://github.com/genkikondo))
<add>
<add>### Changed
<add>
<add>- Update direct Metro dependencies to 0.70.1 ([b74e964e70](https://github.com/facebook/react-native/commit/b74e964e705c40834acad7020562e870cdad9db1), ([c92b64b16a](https://github.com/facebook/react-native/commit/c92b64b16a5710c1dfaea9af4c271931e4669636) by [@arushikesarwani94](https://github.com/arushikesarwani94)), ([f89a0b765c](https://github.com/facebook/react-native/commit/f89a0b765c09c9aba573f03777cc76673989628f) by [@robhogan](https://github.com/robhogan))
<add>- Upgrade RN CLI to v8.0.0 ([0605880c9e](https://github.com/facebook/react-native/commit/0605880c9ed0aec812f3198eb5075db64fba969a), [1e0226f933](https://github.com/facebook/react-native/commit/1e0226f933814bf9ada87eaa14348bfff863ead1), [24bb7f7380](https://github.com/facebook/react-native/commit/24bb7f7380662925f078d78a03fbc954af2da3d6), [7dceb9b63c](https://github.com/facebook/react-native/commit/7dceb9b63c0bfd5b13bf6d26f9530729506e9097) by [@thymikee](https://github.com/thymikee))
<add>- Replace use-subscripton with use-sync-external-store ([93b50be8c2](https://github.com/facebook/react-native/commit/93b50be8c2341a0daf41f6fdc656896c4907c4dc) by [@rickhanlonii](https://github.com/rickhanlonii))
<add>- Expose UIManager from Scheduler ([54db5f2012](https://github.com/facebook/react-native/commit/54db5f201292ebf267800d92b7dd5bfa22431963) by [@cortinico](https://github.com/cortinico))
<add>- Optimized VirtualizedList context when used with nested lists ([ceb0a54608](https://github.com/facebook/react-native/commit/ceb0a546083509192c059cdd93d6aa379e38ef4e) by [@javache](https://github.com/javache))
<add>- Remove usage of std::string in EarlyJsErrorHandler. ([30051b2c41](https://github.com/facebook/react-native/commit/30051b2c4185bff015c72069488b5f6ba3391ad7) by [@sshic](https://github.com/sshic))
<add>- `eslint-config`: add support for ESLint 8 ([864a8c11b2](https://github.com/facebook/react-native/commit/864a8c11b2a7540f607ebc0e084edd7393169359) by [@wcandillon](https://github.com/wcandillon))
<add>- `eslint-config`: add support for TypeScript 4.5+ ([199ac680c7](https://github.com/facebook/react-native/commit/199ac680c7867a982e25620219bffa18f85f5404) by [@rnike](https://github.com/rnike))
<add>- Upgraded react-devtools-core dependency to 4.24.0 ([a7a781ff4a](https://github.com/facebook/react-native/commit/a7a781ff4a13e744f4eb3007ef0657740b277a72))
<add>- Avoid flattening nodes with event props ([980c52de41](https://github.com/facebook/react-native/commit/980c52de41258f6cf2d2360144ea7ca16a19c9f8))
<add>- Type the argument of Animated.interpolate as read-only ([6584304c10](https://github.com/facebook/react-native/commit/6584304c100ce4d51a5c4d606170a6ad0dc00875) by [@motiz88](https://github.com/motiz88))
<add>- Update gradle-download-task to 5.0.1 to support concurrent downloads ([a86cae7aac](https://github.com/facebook/react-native/commit/a86cae7aacc9837536e7d679870a57dcd0f45475) by [@michel-kraemer](https://github.com/michel-kraemer))
<add>- Logging a soft error when ReactRootView has an id other than -1 instead of crashing the app in hybrid apps ([1ca2c24930](https://github.com/facebook/react-native/commit/1ca2c2493027c1b027146cd41e17dd8a4fc33a41) by [@Kunal-Airtel2022](https://github.com/Kunal-Airtel2022))
<add>
<add>#### Android specific
<add>
<add>- Gradle: extend the algoritm to find hermesc paths ([aeac6ab677](https://github.com/facebook/react-native/commit/aeac6ab6773cd2c0ca7abe9e5aa3f22fa81683e5) by [@cortinico](https://github.com/cortinico))
<add>- Bump boost for Android to 1.76 to align with iOS ([5cd6367f0b](https://github.com/facebook/react-native/commit/5cd6367f0b86543274a15bb6d0e53a8545fed845) by [@kelset](https://github.com/kelset))
<add>- Adopt `MapBuffer` interface for `ReadableMapBuffer` ([81e4249315](https://github.com/facebook/react-native/commit/81e42493158edd5e7b88f98c19c87e9d61ba4aba))
<add>- Mark intent as nullable ([5ffa0b0aa6](https://github.com/facebook/react-native/commit/5ffa0b0aa6c523234c634167be1f94b0d9edb0f7) by [@sshic](https://github.com/sshic))
<add>- Use CMake to build ReactAndroid module ([e3830ddffd](https://github.com/facebook/react-native/commit/e3830ddffd9260fe071e0c9f9df40b379d54cf26))
<add>- Update template/android and RN Tester to use `hermes-engine` from the `react-native` NPM package. ([4d91f40fbd](https://github.com/facebook/react-native/commit/4d91f40fbdf0012689b04084113299676342c0dc) by [@cortinico](https://github.com/cortinico))
<add>- Build Hermes from Source ([a3d9892ed9](https://github.com/facebook/react-native/commit/a3d9892ed9c993d16fa36fa6b713e2ead43fcc77) by [@cortinico](https://github.com/cortinico))
<add>- Rename field with default values for ReactConfig to DEFAULT_CONFIG ([964e816752](https://github.com/facebook/react-native/commit/964e81675286c80a8e322127aa7c052f62621098))
<add>- Moved `com/react/facebook/uimanager/interfaces` files into `com/react/facebook/uimanager` to enable Kotlin build ([b1a779392d](https://github.com/facebook/react-native/commit/b1a779392d483c649d428debfe4a6405247b8c0e))
<add>- Bump AGP to 7.1.0 and fix bundle inclusion in release mode ([200488e87c](https://github.com/facebook/react-native/commit/200488e87cf4bc355e03c78cd814b97b23452117) by [@gabrieldonadel](https://github.com/gabrieldonadel))
<add>- Release react-native-gradle-plugin 0.0.5 ([42272211e4](https://github.com/facebook/react-native/commit/42272211e4a1b7cff7770b59cf1bcf649cbdd6fc) by [@cortinico](https://github.com/cortinico))
<add>- ViewPagerAndroid recommendation link. ([7e8cce3d2d](https://github.com/facebook/react-native/commit/7e8cce3d2ddffbe36bcb3c9ec2f006f7e1b42a79) by [@maaxg](https://github.com/maaxg))
<add>- Bump android Appcompat to 1.4.1 ([6b61995647](https://github.com/facebook/react-native/commit/6b61995647c789a567845521fed7b0cc1e0cddb7) by [@gabrieldonadel](https://github.com/gabrieldonadel))
<add>- Remove `react-native-gradle-plugin` as a dependency from template's package.json ([cd79317672](https://github.com/facebook/react-native/commit/cd79317672e5c99636346f2abb641a688a4ceb82) by [@cortinico](https://github.com/cortinico))
<add>- Use 2g as a default heap size for gradle builds ([09e418ef8e](https://github.com/facebook/react-native/commit/09e418ef8e98fd026cf828696ff2475993b76ac2))
<add>- Use new StatusBar API on Android 11 (API 30)+ ([50c8e973f0](https://github.com/facebook/react-native/commit/50c8e973f067d4ef1fc3c2eddd360a0709828968) by [@ieatfood](https://github.com/ieatfood))
<add>- Change static string to public ([ab45138394](https://github.com/facebook/react-native/commit/ab45138394f41aeb13370882837968636de04c24) by [@sshic](https://github.com/sshic))
<add>
<add>#### iOS specific
<add>
<add>- Use pre-built HermesC if available in current React Native release ([644fe430fd](https://github.com/facebook/react-native/commit/644fe430fdecc0bf1fa098d1c2d52178da6c987c) by [@hramos](https://github.com/hramos))
<add>- When building Hermes from source, the filesystem will now be prepared using the new hermes-utils.js scripts, outside of CocoaPods ([aaa01f7710](https://github.com/facebook/react-native/commit/aaa01f77106f891696d9ec508e2ee71111a6af2a) by [@hramos](https://github.com/hramos))
<add>- Expose scheduler through RCTSurfacePresenter ([614aa86916](https://github.com/facebook/react-native/commit/614aa86916394d8ee2ecb236f38de6bb7e161ca2) by [@cortinico](https://github.com/cortinico))
<add>- Adopt UIGraphicsImageRenderer API ([d70d7fd0b3](https://github.com/facebook/react-native/commit/d70d7fd0b3984ee54622afc4692a6c945618c345) by [@matrush](https://github.com/matrush))
<add>- Build Hermes from source when Hermes is used ([bb01b75637](https://github.com/facebook/react-native/commit/bb01b75637edc1159a3bdb3af86936e1c92f39c1) by [@hramos](https://github.com/hramos))
<add>- Update CodeGen scripts to accept custom node executable ([323db75c36](https://github.com/facebook/react-native/commit/323db75c36d26d771f6b231c8eabc5afc0da74d3) by [@cipolleschi](https://github.com/cipolleschi))
<add>- Fixed the fallback behavior when the `.xcode.env` file is missing, actually using the old `find-node-for-xcode.sh` script ([705c6f57d6](https://github.com/facebook/react-native/commit/705c6f57d66b4499f43489292183a58413402a74) by [@cipolleschi](https://github.com/cipolleschi))
<add>- Adding a link in a message for the users. ([2c52131f5e](https://github.com/facebook/react-native/commit/2c52131f5e0eb4668681242fcdd8150afe3c5827) by [@cipolleschi](https://github.com/cipolleschi))
<add>- Bump ruby to 2.7.5 ([2c87b7466e](https://github.com/facebook/react-native/commit/2c87b7466e098c5cd230e02b279fc7bc7a357615) by [@danilobuerger](https://github.com/danilobuerger))
<add>- This PR removes the `find-node.sh` scripts and replaces it with an `.xcode.env` file that is sourced by the script phases that needs it. The `.xcode.env` file is versioned: to customize a local environment, an unversioned `.xcode.local.env` can be used. ([0480f56c5b](https://github.com/facebook/react-native/commit/0480f56c5b5478b6ebe5ad88e347cad2810bfb17) by [@cipolleschi](https://github.com/cipolleschi))
<add>- Update `PushNotificationIOS.checkPermissions` to include iOS 10+ notification settings. ([17ecd2fb5b](https://github.com/facebook/react-native/commit/17ecd2fb5b3cfb8aa0282ed406b16dc3b9777018))
<add>- Enable SonarKit in React-Core when the configuration is `'Debug'` ([b5343a6b0d](https://github.com/facebook/react-native/commit/b5343a6b0dd07c1b4ef9dac549df67a4d68ebd1e) by [@cipolleschi](https://github.com/cipolleschi))
<add>- When Hermes is enabled, the Hermes Engine will be built from source instead of using the pre-built `hermes-engine` CocoaPod. ([12ad1fffe8](https://github.com/facebook/react-native/commit/12ad1fffe87c0c5ab2e001f318ff4f8d3eda7479) by [@hramos](https://github.com/hramos))
<add>- Replaced folly::Optional with std::optional from C++17 in Objc module generator. ([45e2941367](https://github.com/facebook/react-native/commit/45e2941367fbf13584193bbda598173802289167) by [@philIip](https://github.com/philIip))
<add>- Removed methodName parameter that was used only for a warning message and moved the warning parameter to be calculated inline. ([cfb11ca2f6](https://github.com/facebook/react-native/commit/cfb11ca2f67c59c090b8a58b2b7bdaacef0e19df))
<add>- Fix the crash caused by nil partialLoadHandler ([46bc521513](https://github.com/facebook/react-native/commit/46bc521513c9c78e5ffc49cf3e571757e1a91cef))
<add>- Synchronously render cached images ([189c2c8958](https://github.com/facebook/react-native/commit/189c2c8958442541c6b4f42860b2943ece612da2))
<add>- Updated Flipper-Glog to 0.5.0.4 ([cd60ffdb62](https://github.com/facebook/react-native/commit/cd60ffdb62b2183cd24baef3075d56f758cea24a))
<add>- Add function to report early js errors ([1804951595](https://github.com/facebook/react-native/commit/180495159517dc0bfa103621e5ff62fc04cb3c8b) by [@sshic](https://github.com/sshic))
<add>
<add>### Deprecated
<add>
<add>- Deprecate the use of `react-native/jest/preprocessor.js` by external projects ([c1e9aa9a27](https://github.com/facebook/react-native/commit/c1e9aa9a272aed3cba60c4aeff783eeb8bffce68) by [@motiz88](https://github.com/motiz88))
<add>- Deprecate the Promise.prototype.done method and log a warning when it's called in development. ([35800962c1](https://github.com/facebook/react-native/commit/35800962c16a33eb8e9ff1adfd428cf00bb670d3) by [@motiz88](https://github.com/motiz88))
<add>
<add>#### iOS specific
<add>
<add>- Deprecating support for iOS/tvOS SDK 11.0, 12.4+ is now required ([5f2835b14d](https://github.com/facebook/react-native/commit/5f2835b14d35681c268dd64d6ec284ea5f053be3), ([c71e6efbcd](https://github.com/facebook/react-native/commit/c71e6efbcd2b95faee327d9763d321488120bc5e), ([982ca30de0](https://github.com/facebook/react-native/commit/982ca30de079d7e80bd0b50365d58b9048fb628f) by [@philIip](https://github.com/philIip))
<add>
<add>#### iOS specific
<add>
<add>- Removed lint restricting `DynamicColorIOS` to only two properties ([13b0b06522](https://github.com/facebook/react-native/commit/13b0b0652259ada468cc044b0b604edb666b2eb9))
<add>
<add>### Fixed
<add>
<add>- Remove unactionable warning about `codegenNativeComponent` when on 'Paper' ([494b73cb33](https://github.com/facebook/react-native/commit/494b73cb33197fa865e9ead8fdca11bce6822917) by [@tido64](https://github.com/tido64))
<add>- Fix typo in Value's constructor with a Symbol ([a7a0f86a73](https://github.com/facebook/react-native/commit/a7a0f86a73ab51be31fb2c3205612d7ff1fb5384) by [@jpporto](https://github.com/jpporto))
<add>- Avoid full copy of large folly::dynamic objects by switching to std::move semantics ([3f98c8e4c2](https://github.com/facebook/react-native/commit/3f98c8e4c2c8f40b81c1a90aa65c1bdc9327faed) by [@NikoAri](https://github.com/NikoAri))
<add>- Fix performance issue on Animated.interpolate with big input range ([f503b21203](https://github.com/facebook/react-native/commit/f503b212039f79f00ea56b65ecf3cd150b82f087) by [@Almouro](https://github.com/Almouro))
<add>- Update function spacing linting rules ([8650220cf9](https://github.com/facebook/react-native/commit/8650220cf99739c4b904a37ce4f19ce7dfd3bdbb) by [@joeframbach](https://github.com/joeframbach))
<add>- Add supportsFromJs and supportsToJs template variables ([087624ccaf](https://github.com/facebook/react-native/commit/087624ccaf2e484c0b6425e57edf9afd62a06e9a) by [@appden](https://github.com/appden))
<add>- The Array appended to FormData is transmitted as a string ([d2e8e7d58e](https://github.com/facebook/react-native/commit/d2e8e7d58e680e0bb3b4da1f820dd4dd840639f5) by [@bang9](https://github.com/bang9))
<add>- AppState.removeEventListener correctly removes listener for blur and focus events ([9aab25ec53](https://github.com/facebook/react-native/commit/9aab25ec536473ffe6d22c5efeae8fea6bd769be) by [@AntoineDoubovetzky](https://github.com/AntoineDoubovetzky))
<add>- `focus()` on TextInput to respect its `editable` state ([8a5460ce80](https://github.com/facebook/react-native/commit/8a5460ce80e69c11a007121d4278d55642f6b10e) by [@vonovak](https://github.com/vonovak))
<add>- Restore Windows build with RawPropsParser.cpp ([2d64d1d693](https://github.com/facebook/react-native/commit/2d64d1d69360161c047c86a026403d8074ba28bb) by [@TatianaKapos](https://github.com/TatianaKapos))
<add>- Fix babel-plugin-codegen crash when export init is null ([ae756647c9](https://github.com/facebook/react-native/commit/ae756647c9b8a88ba615fd30185f621825a33427) by [@janicduplessis](https://github.com/janicduplessis))
<add>- Fixed compilation warning due to `using namespace` being used as part of header ([009d80bf5a](https://github.com/facebook/react-native/commit/009d80bf5a55dd74be448960b1344ac7599c6bae) by [@arhelmus](https://github.com/arhelmus))
<add>- Allow including TurboModule.h in mixed rtti/no-rtti environment, even if TurboModule.h/cpp is compiled without RTTI. ([1f87729697](https://github.com/facebook/react-native/commit/1f87729697370a4ab31e2bb9ab1780438d9e146f) by [@nlutsenko](https://github.com/nlutsenko))
<add>- Remove prettier from dependencies in eslint-config ([2db1bca952](https://github.com/facebook/react-native/commit/2db1bca95224ce39484c3f27508aec9a21ce126a) by [@Kerumen](https://github.com/Kerumen))
<add>- Switch Component doesn't disable click functionality when disabled ([b2e625a517](https://github.com/facebook/react-native/commit/b2e625a51723becea4cef0433448fbec679669ee) by [@fabriziobertoglio1987](https://github.com/fabriziobertoglio1987))
<add>- Support numeric color values in StyleSheet's Flow types ([83b1975b90](https://github.com/facebook/react-native/commit/83b1975b90569a36020da33156615a13fcc7ba92) by [@motiz88](https://github.com/motiz88))
<add>- Fix build break on Windows with ReactCommon ([42b391775f](https://github.com/facebook/react-native/commit/42b391775f663df335f6f2553104fc2fa35b1bee) by [@chiaramooney](https://github.com/chiaramooney))
<add>- Fixed opacity value in TouchableOpacity ([3eddc9abb7](https://github.com/facebook/react-native/commit/3eddc9abb70eb54209c68aab7dbd69e363cc7b29) by [@hetanthakkar1](https://github.com/hetanthakkar1))
<add>- Remove illegal private property access in VirtualizedSectionList.scrollToLocation ([b2f871a6fa](https://github.com/facebook/react-native/commit/b2f871a6fa9c92dd0712055384b9eca6d828e37d) by [@motiz88](https://github.com/motiz88))
<add>- JS animated node value updates properly when listener is attached ([1f778014a7](https://github.com/facebook/react-native/commit/1f778014a7e95c5c473898c38d5b1e0725cd373c) by [@genkikondo](https://github.com/genkikondo))
<add>- Working around Long paths limitation on Windows ([7b76abc0d3](https://github.com/facebook/react-native/commit/7b76abc0d3a0a5bec37f314c80954e412fc5f5ec) by [@mganandraj](https://github.com/mganandraj))
<add>- Fix VirtualizedList with initialScrollIndex not rendering all elements when data is updated ([c5c17985da](https://github.com/facebook/react-native/commit/c5c17985dae402725abb8a3a94ccedc515428711) by [@AntoineDoubovetzky](https://github.com/AntoineDoubovetzky))
<add>
<add>#### Android specific
<add>
<add>- Add back hermes inspector support ([6b6adcc111](https://github.com/facebook/react-native/commit/6b6adcc111123bec2c4c110070b2506385e74664) by [@Kudo](https://github.com/Kudo))
<add>- Fixed issue where any node with an AccessibilityDelegate set (which was any node with any accessibility propoerty), was using ExploreByTouchHelper's built in AccessibilityNodeProvider, and not properly populating their AccessibilityNodeInfo's, leading to focus issues and issues with automated test services like UIAutomator. ([70fcab76a4](https://github.com/facebook/react-native/commit/70fcab76a4dcf65e628ac897620fe050758574e3) by [@blavalla](https://github.com/blavalla))
<add>- Fix Extras usage in Android implementation of Linking.sendIntent() ([86f8d0bb52](https://github.com/facebook/react-native/commit/86f8d0bb528a75777c357ae214643ed58c326ca9))
<add>- Fix typo in gradle plugin deprecation message ([41cfd2f976](https://github.com/facebook/react-native/commit/41cfd2f9768e4742eedd299ab467d316d016705e) by [@mikehardy](https://github.com/mikehardy))
<add>- Fixed `TimingModule` related functions for headless JS tasks, eg. `setTimeout` ([dac56ce077](https://github.com/facebook/react-native/commit/dac56ce0776e0e4d23ed4f8b324f2e2432aefa6a) by [@marcesengel](https://github.com/marcesengel))
<add>- Improve support for Android users on M1 machine ([c5babd993a](https://github.com/facebook/react-native/commit/c5babd993a2bed2994ecc4710fa9e424b3e6cfc2) by [@cortinico](https://github.com/cortinico))
<add>- Do not use `rootProject` directly in Gradle scripts ([b2bc5aa5c9](https://github.com/facebook/react-native/commit/b2bc5aa5c903ad057a53d4caa82b0fe74e01c07c) by [@cortinico](https://github.com/cortinico))
<add>- Adding null check for context in redbox surface delegate ([9527ab1584](https://github.com/facebook/react-native/commit/9527ab1584869d7966c562e8aa7cbf48788156a3) by [@ryancat](https://github.com/ryancat))
<add>- Fix crash on empty snapToOffsets array ([145fd041c7](https://github.com/facebook/react-native/commit/145fd041c7afe9a18f08f461487bb515ab2f516a) by [@ryancat](https://github.com/ryancat))
<add>- Fix StatusBar not updating to use translucent values when set to the same value across different activities ([d34a75e9e5](https://github.com/facebook/react-native/commit/d34a75e9e5932adcac4a16f5b815bb909c3aa0dd))
<add>- Fix underlineColorAndroid transparent not working on API 21 ([52aee50a70](https://github.com/facebook/react-native/commit/52aee50a704bbeab91f5fa05fe3220dee304422f) by [@fabriziobertoglio1987](https://github.com/fabriziobertoglio1987))
<add>- Fixed regression on content in scroll view not responding to touch when fling got interrupted ([bb8ff9260f](https://github.com/facebook/react-native/commit/bb8ff9260fe6a783171f35ce1a459927d8179d08) by [@ryancat](https://github.com/ryancat))
<add>- Fixes android build error when compiling as library ([c34ef5841c](https://github.com/facebook/react-native/commit/c34ef5841cf3a63a9cc96add577d6bf6d52e4397) by [@nickfujita](https://github.com/nickfujita))
<add>- Cancel post touch process when new touch is received ([0368081858](https://github.com/facebook/react-native/commit/0368081858193d7c2537acd9080d11bb701ee98b) by [@ryancat](https://github.com/ryancat))
<add>- Improve rendering of images when resampled and corner radius applied ([f743bed657](https://github.com/facebook/react-native/commit/f743bed657591b078300a6519e3d68db542fd757) by [@javache](https://github.com/javache))
<add>- Fix transform when calculate overflowInset ([0975e96d53](https://github.com/facebook/react-native/commit/0975e96d53546ac05b2154352fe56e5d82e2a1f8) by [@ryancat](https://github.com/ryancat))
<add>- Fix ReactHorizontalScrollView contentOffset ([9f6f97151c](https://github.com/facebook/react-native/commit/9f6f97151c44a0f727c9dd938222be1860ecf3f9) by [@genkikondo](https://github.com/genkikondo))
<add>- Text Component does not announce disabled and disables click functionality when disabled ([7b2d8178b1](https://github.com/facebook/react-native/commit/7b2d8178b155f5f1b247614c46e5e20f31bbd438) by [@fabriziobertoglio1987](https://github.com/fabriziobertoglio1987))
<add>- Fix StatusBar on Android API 30 ([9ed2df628d](https://github.com/facebook/react-native/commit/9ed2df628ddd410cc3383e68b0386471432445c0) by [@ieatfood](https://github.com/ieatfood))
<add>- Use root locale when converting string case. ([5341ad8962](https://github.com/facebook/react-native/commit/5341ad896245c40a00b6faead1b90d01aac58f8c) by [@halaei](https://github.com/halaei))
<add>- Fix DarkMode on Calendar DateTimePicker ([97064ae1fb](https://github.com/facebook/react-native/commit/97064ae1fbf84a8a6b653c02c5872191b7d2d622) by [@mdvacca](https://github.com/mdvacca))
<add>- Fix ScrollView contentOffset ([be260b9f47](https://github.com/facebook/react-native/commit/be260b9f479a3b55ee43d2959d2c49fd3c1eb4ac) by [@genkikondo](https://github.com/genkikondo))
<add>- Do not bundle libhermes.so or libjsc.so inside the React Native Android AAR ([fa85417179](https://github.com/facebook/react-native/commit/fa854171798e67b8a10820f77d7198315e1784ed) by [@cortinico](https://github.com/cortinico))
<add>- Enable hitSlop to be set using a single number. ([d682753244](https://github.com/facebook/react-native/commit/d682753244feba28c6a15c31966a3da075a090e6) by [@javache](https://github.com/javache))
<add>- Fix crash caused by Image.queryCache parsing null ([ae3d4f7008](https://github.com/facebook/react-native/commit/ae3d4f700843ae4cbb6927ee620095136d1abc3f) by [@skychx](https://github.com/skychx))
<add>- Fix NullPointerException when disaptching events ([fbeb51ef51](https://github.com/facebook/react-native/commit/fbeb51ef5133303a5cb71569507d44403ded3447) by [@mdvacca](https://github.com/mdvacca))
<add>
<add>#### iOS specific
<add>
<add>- ScrollView's contentInsetAdjustmentBehavior is reset to Never at every reuse to avoid layout artifacts. ([28a65f4387](https://github.com/facebook/react-native/commit/28a65f438789c29309d6e7c58063a73ca721ef43))
<add>- Prevent Nullptr segfault in TurboModule init path ([7f3cc256b5](https://github.com/facebook/react-native/commit/7f3cc256b5bcbf2e64540ca69401f62ec6869f0e) by [@RSNara](https://github.com/RSNara))
<add>- Expose the extraData dict attached to JavaScript errors to the native ExceptionManager on iOS, similar to Android ([a65ae8eff6](https://github.com/facebook/react-native/commit/a65ae8eff6ec6f9ad283ac8e96f00802421a14da) by [@GijsWeterings](https://github.com/GijsWeterings))
<add>- `RCTLocalizationProvider` Fall back to input when no localization is available ([18196512db](https://github.com/facebook/react-native/commit/18196512db6b8b4469a5e1b098d8892ae72d743a) by [@robhogan](https://github.com/robhogan))
<add>- Update iOS LogBox to render its UIWindow with the key window's UIWindowScene ([d31d83f410](https://github.com/facebook/react-native/commit/d31d83f4109c167ec612058c805fd65f69b82476) by [@vincentriemer](https://github.com/vincentriemer))
<add>- Remove Gemfile.lock from template ([1907bd31f0](https://github.com/facebook/react-native/commit/1907bd31f066865aa1c5fe4ec88e98ee46448771) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Fix `pod install` when `RCT-Folly` version has been updated. ([b2517c3bdc](https://github.com/facebook/react-native/commit/b2517c3bdccc3f9d935f4ee06f959d6ce8f27bbe) by [@fortmarek](https://github.com/fortmarek))
<add>- Fix usage of cocoapods with --project-directory flag and new arch ([2f813f873a](https://github.com/facebook/react-native/commit/2f813f873a1692044ea3461e59ca732a4d952300) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Ensure LogBoxView is sized relative to the key window instead of the full screen ([84f8c9ad55](https://github.com/facebook/react-native/commit/84f8c9ad550f98295d2e718b4b1d6b1ac724b898) by [@vincentriemer](https://github.com/vincentriemer))
<add>- Improved template fastlane gitignore ([f43f05d292](https://github.com/facebook/react-native/commit/f43f05d292fd2fbdf3d5fdfd194ed81b0e346657) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Set RCTView borderColor to UIColor ([267d36d0af](https://github.com/facebook/react-native/commit/267d36d0afb4b3713df9b679c2019c44ac6bcc3f) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Fix action sheet callback invoked more than once on iPad ([8935d6e697](https://github.com/facebook/react-native/commit/8935d6e697dffb0971f5a8ee1dfbc580080de3e0) by [@janicduplessis](https://github.com/janicduplessis))
<add>- Resolve border platform color based on current trait collection ([9a35818797](https://github.com/facebook/react-native/commit/9a3581879764f3f1b2743905e3e54611e96bb618) by [@danilobuerger](https://github.com/danilobuerger))
<add>- Enable custom sound for local push notifications. ([eb19499484](https://github.com/facebook/react-native/commit/eb1949948406195c4c02c6041d07cba074ae820c))
<add>- Invoke registerForRemoteNotifications on main UI thread. ([3633a05299](https://github.com/facebook/react-native/commit/3633a05299d99b12acc5c3c056b977463df1924e))
<add>- Bump flipper pods to get arm64 catalyst slice ([f811da7cc2](https://github.com/facebook/react-native/commit/f811da7cc20cc49ca5c8d4e023d6c61e36e15dd1) by [@fortmarek](https://github.com/fortmarek))
<add>- Fix `pod install --project-directory=ios` failing when Hermes is enabled ([1b22e8a039](https://github.com/facebook/react-native/commit/1b22e8a039081887ffd450596d822bff975d6900), ([eb7cc85a91](https://github.com/facebook/react-native/commit/eb7cc85a9146d058694247178f03d57cc125c97a) by [@tido64](https://github.com/tido64))
<add>- Fix compilation warning in yoga ([52d8a797e7](https://github.com/facebook/react-native/commit/52d8a797e7a6be3fa472f323ceca4814a28ef596) by [@cuva](https://github.com/cuva))
<add>- Prevent deadlock when dispatching events from observers on the same thread. ([68fd1e5508](https://github.com/facebook/react-native/commit/68fd1e55085e871a854563721ee29ca698239607) by [@Pickleboyonline](https://github.com/Pickleboyonline))
<add>- In RCTSurfaceHostingComponent, access ckComponent from main queue to pass assertion ([1874c81003](https://github.com/facebook/react-native/commit/1874c81003b468554c227541fec5e29c4adfb82f) by [@p-sun](https://github.com/p-sun))
<add>- Fix modal redbox for onDismiss ([46f68aceb2](https://github.com/facebook/react-native/commit/46f68aceb20a10c95c92b5ffeb90f289b015a559) by [@HeyImChris](https://github.com/HeyImChris))
<add>- Attempt to fix crash during app termination ([9cd43340a7](https://github.com/facebook/react-native/commit/9cd43340a7e2443564c2ff5e8e85d37f6e1e47ef) by [@sammy-SC](https://github.com/sammy-SC))
<add>
<add>### Security
<add>
<add>- Encode URL params in URLSearchParams.toString() ([1042a8012f](https://github.com/facebook/react-native/commit/1042a8012fb472bd5c882b469fe507dd6279d562) by [@sshic](https://github.com/sshic))
<add>
<add>
<ide> ## v0.68.2
<ide>
<ide> ### Changed | 1 |
PHP | PHP | remove separator element | ec360c88de943d486a7d537481ef606f6b5c97e6 | <ide><path>Cake/Test/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testPassedArgsMergingWithUrlOptions() {
<ide> $result = $this->Paginator->numbers();
<ide> $expected = array(
<ide> array('li' => array('class' => 'active')), '<span', '1', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/articles/index/2?page=2&foo=bar&x=y')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/articles/index/2?page=3&foo=bar&x=y')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/articles/index/2?page=4&foo=bar&x=y')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/articles/index/2?page=5&foo=bar&x=y')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/articles/index/2?page=6&foo=bar&x=y')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/articles/index/2?page=7&foo=bar&x=y')), '7', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> $result = $this->Paginator->numbers();
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '8', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=10')), '10', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=11')), '11', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=12')), '12', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> array('li' => array('class' => 'first')), array('a' => array('href' => '/index', 'rel' => 'first')), 'first', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '8', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=10')), '10', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=11')), '11', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=12')), '12', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array('class' => 'last')), array('a' => array('href' => '/index?page=15', 'rel' => 'last')), 'last', '/a', '/li',
<ide> public function testNumbers() {
<ide> $result = $this->Paginator->numbers();
<ide> $expected = array(
<ide> array('li' => array('class' => 'active')), '<span', '1', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> $result = $this->Paginator->numbers();
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=10')), '10', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=11')), '11', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=12')), '12', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=13')), '13', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '14', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=15')), '15', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> $result = $this->Paginator->numbers(array('first' => 1));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '2', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Paginator->numbers(array('last' => 1));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '2', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=10')), '10', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=11')), '11', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=12')), '12', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=13')), '13', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=14')), '14', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '15', '/span', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '10', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=11')), '11', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=12')), '12', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=13')), '13', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=14')), '14', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=15')), '15', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbers() {
<ide> $result = $this->Paginator->numbers(array('first' => 1, 'last' => 1));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '6', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=8')), '8', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=9')), '9', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=10')), '10', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=42')), '42', '/a', '/li',
<ide> public function testNumbers() {
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=33')), '33', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=34')), '34', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=35')), '35', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=36')), '36', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '37', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=38')), '38', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=39')), '39', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=40')), '40', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=41')), '41', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=42')), '42', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers($options);
<ide> $expected = array(
<ide> array('li' => array('class' => 'active')), '<span', '1', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Paginator->numbers(array('modulus' => 3));
<ide> $expected = array(
<ide> array('li' => array('class' => 'active')), '<span', '1', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4894')), '4894', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '4895', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '3', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '3', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide>
<ide> $result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 5, 'last' => 5));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '3', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4893')), '4893', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4894')), '4894', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4895')), '4895', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4891')), '4891', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4892')), '4892', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '4893', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4894')), '4894', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4895')), '4895', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=5')), '5', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=56')), '56', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=57')), '57', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '58', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=59')), '59', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=60')), '60', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4893')), '4893', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4894')), '4894', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4895')), '4895', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers(array('first' => 5, 'modulus' => 4, 'last' => 5));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=3')), '3', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '5', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=6')), '6', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=7')), '7', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4893')), '4893', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4894')), '4894', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4895')), '4895', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersModulus() {
<ide> $result = $this->Paginator->numbers(array('first' => 2, 'modulus' => 2, 'last' => 2));
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=2')), '2', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '3', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4')), '4', '/a', '/li',
<ide> array('li' => array('class' => 'ellipsis')), '...', '/li',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4896')), '4896', '/a', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/index?page=4897')), '4897', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testNumbersRouting() {
<ide> $result = $this->Paginator->numbers();
<ide> $expected = array(
<ide> array('li' => array()), array('a' => array('href' => '/clients/index')), '1', '/a', '/li',
<del> ' | ',
<ide> array('li' => array('class' => 'active')), '<span', '2', '/span', '/li',
<del> ' | ',
<ide> array('li' => array()), array('a' => array('href' => '/clients/index?page=3')), '3', '/a', '/li',
<ide> );
<ide> $this->assertTags($result, $expected);
<ide> public function testFirstAndLastTag() {
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=6')), '6', '/a',
<ide> '/li',
<del> ' | ',
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=7')), '7', '/a',
<ide> '/li',
<ide> public function testFirstBoundaries() {
<ide> '<li',
<ide> array('a' => array('href' => '/index')), '1', '/a',
<ide> '/li',
<del> ' | ',
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=2')), '2', '/a',
<ide> '/li'
<ide> public function testLast() {
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=6')), '6', '/a',
<ide> '/li',
<del> ' | ',
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=7')), '7', '/a',
<ide> '/li',
<ide> public function testLastOptions() {
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=14&sort=Client.name&direction=DESC')), '14', '/a',
<ide> '/li',
<del> ' | ',
<ide> '<li',
<ide> array('a' => array('href' => '/index?page=15&sort=Client.name&direction=DESC')), '15', '/a',
<ide> '/li',
<ide><path>Cake/View/Helper/PaginatorHelper.php
<ide> class PaginatorHelper extends Helper {
<ide> * and custom (default). In the default mode the supplied string is parsed and constants are replaced
<ide> * by their actual values.
<ide> * placeholders: %page%, %pages%, %current%, %count%, %start%, %end% .
<del> * - `separator` The separator of the actual page and number of pages (default: ' of ').
<ide> * - `url` Url of the action. See Router::url()
<ide> * - `url['sort']` the key that the recordset is sorted.
<ide> * - `url['direction']` Direction of the sorting (default: 'asc').
<ide> class PaginatorHelper extends Helper {
<ide> 'number' => '<li><a href="{{url}}">{{text}}</a></li>',
<ide> 'current' => '<li class="active"><span>{{text}}</span></li>',
<ide> 'ellipsis' => '<li class="ellipsis">...</li>',
<del> 'separator' => ' | ',
<ide> 'sort' => '<a href="{{url}}">{{text}}</a>',
<ide> 'sortAsc' => '<a class="asc" href="{{url}}">{{text}}</a>',
<ide> 'sortDesc' => '<a class="desc" href="{{url}}">{{text}}</a>',
<ide> public function numbers($options = array()) {
<ide> }
<ide>
<ide> $out = '';
<del> $separator = $this->_templater->format('separator', []);
<ide> $ellipsis = $this->_templater->format('ellipsis', []);
<ide>
<ide> if ($options['modulus'] && $params['pageCount'] > $options['modulus']) {
<ide> public function numbers($options = array()) {
<ide> $out .= $this->first($offset);
<ide> if ($offset < $start - 1) {
<ide> $out .= $ellipsis;
<del> } else {
<del> $out .= $separator;
<ide> }
<ide> }
<ide>
<ide> public function numbers($options = array()) {
<ide> 'text' => $i,
<ide> 'url' => $this->url(['page' => $i]),
<ide> ];
<del> $out .= $this->_templater->format('number', $vars) . $separator;
<add> $out .= $this->_templater->format('number', $vars);
<ide> }
<ide>
<ide> $out .= $this->_templater->format('current', [
<ide> 'text' => $params['page'],
<ide> 'url' => $this->url(['page' => $params['page']]),
<ide> ]);
<ide>
<del> if ($i != $params['pageCount']) {
<del> $out .= $separator;
<del> }
<del>
<ide> $start = $params['page'] + 1;
<ide> for ($i = $start; $i < $end; $i++) {
<ide> $vars = [
<ide> 'text' => $i,
<ide> 'url' => $this->url(['page' => $i]),
<ide> ];
<del> $out .= $this->_templater->format('number', $vars) . $separator;
<add> $out .= $this->_templater->format('number', $vars);
<ide> }
<ide>
<ide> if ($end != $params['page']) {
<ide> public function numbers($options = array()) {
<ide> $offset = ($params['pageCount'] < $end + (int)$options['last']) ? $params['pageCount'] - $end : $options['last'];
<ide> if ($offset <= $options['last'] && $params['pageCount'] - $end > $offset) {
<ide> $out .= $ellipsis;
<del> } else {
<del> $out .= $separator;
<ide> }
<ide> $out .= $this->last($offset);
<ide> }
<ide> public function numbers($options = array()) {
<ide> ];
<ide> $out .= $this->_templater->format('number', $vars);
<ide> }
<del> if ($i != $params['pageCount']) {
<del> $out .= $separator;
<del> }
<ide> }
<ide>
<ide> $out .= $options['after'];
<ide> public function first($first = '<< first', $options = []) {
<ide> $out = '';
<ide>
<ide> if (is_int($first) && $params['page'] >= $first) {
<del> $separator = $this->_templater->format('separator', []);
<ide> for ($i = 1; $i <= $first; $i++) {
<ide> $out .= $this->_templater->format('number', [
<ide> 'url' => $this->url(['page' => $i]),
<ide> 'text' => $i
<ide> ]);
<del> if ($i != $first) {
<del> $out .= $separator;
<del> }
<ide> }
<ide> } elseif ($params['page'] > 1 && is_string($first)) {
<ide> $first = $options['escape'] ? h($first) : $first;
<ide> public function last($last = 'last >>', $options = array()) {
<ide> $lower = $params['pageCount'] - $last + 1;
<ide>
<ide> if (is_int($last) && $params['page'] <= $lower) {
<del> $separator = $this->_templater->format('separator', []);
<ide> for ($i = $lower; $i <= $params['pageCount']; $i++) {
<ide> $out .= $this->_templater->format('number', [
<ide> 'url' => $this->url(['page' => $i]),
<ide> 'text' => $i
<ide> ]);
<del> if ($i != $params['pageCount']) {
<del> $out .= $separator;
<del> }
<ide> }
<ide> } elseif ($params['page'] < $params['pageCount'] && is_string($last)) {
<ide> $last = $options['escape'] ? h($last) : $last; | 2 |
Javascript | Javascript | remove a flag for style collision warning | 31734540dc1b507982cae839536f757de964dcd5 | <ide><path>packages/react-dom/src/shared/CSSPropertyOperations.js
<ide> import dangerousStyleValue from './dangerousStyleValue';
<ide> import hyphenateStyleName from './hyphenateStyleName';
<ide> import warnValidStyle from './warnValidStyle';
<ide>
<del>import {warnAboutShorthandPropertyCollision} from 'shared/ReactFeatureFlags';
<del>
<ide> /**
<ide> * Operations for dealing with CSS properties.
<ide> */
<ide> export function validateShorthandPropertyCollisionInDev(
<ide> nextStyles,
<ide> ) {
<ide> if (__DEV__) {
<del> if (!warnAboutShorthandPropertyCollision) {
<del> return;
<del> }
<del>
<ide> if (!nextStyles) {
<ide> return;
<ide> }
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const enableSchedulerDebugging = false;
<ide> // Disable javascript: URL strings in href for XSS protection.
<ide> export const disableJavaScriptURLs = false;
<ide>
<del>// Warns when a combination of updates on a dom can cause a style declaration
<del>// that clashes with a previous one https://github.com/facebook/react/pull/14181
<del>export const warnAboutShorthandPropertyCollision = true;
<del>
<ide> // Experimental React Flare event system and event components support.
<ide> export const enableDeprecatedFlareAPI = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> export const enableSchedulerTracing = __PROFILE__;
<ide> export const enableSuspenseServerRenderer = false;
<ide> export const enableSelectiveHydration = false;
<ide> export const enableBlocksAPI = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const enableSchedulerDebugging = false;
<ide> export const debugRenderPhaseSideEffectsForStrictMode = true;
<ide> export const disableJavaScriptURLs = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> export const enableSelectiveHydration = false;
<ide> export const enableBlocksAPI = false;
<ide> export const disableJavaScriptURLs = false;
<ide> export const disableInputAttributeSyncing = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const enableSchedulerDebugging = false;
<ide> export const enableDeprecatedFlareAPI = false;
<ide> export const enableFundamentalAPI = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> export const enableSelectiveHydration = false;
<ide> export const enableBlocksAPI = false;
<ide> export const disableJavaScriptURLs = false;
<ide> export const disableInputAttributeSyncing = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const enableSchedulerDebugging = false;
<ide> export const enableDeprecatedFlareAPI = false;
<ide> export const enableFundamentalAPI = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> export const enableSchedulerTracing = __PROFILE__;
<ide> export const enableSuspenseServerRenderer = false;
<ide> export const enableSelectiveHydration = false;
<ide> export const enableBlocksAPI = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const enableSchedulerDebugging = false;
<ide> export const disableJavaScriptURLs = false;
<ide> export const disableInputAttributeSyncing = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.js
<ide> export const enableSelectiveHydration = false;
<ide> export const enableBlocksAPI = false;
<ide> export const disableJavaScriptURLs = false;
<ide> export const disableInputAttributeSyncing = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const enableSchedulerDebugging = false;
<ide> export const enableDeprecatedFlareAPI = false;
<ide> export const enableFundamentalAPI = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js
<ide> export const enableSelectiveHydration = true;
<ide> export const enableBlocksAPI = true;
<ide> export const disableJavaScriptURLs = true;
<ide> export const disableInputAttributeSyncing = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const enableSchedulerDebugging = false;
<ide> export const enableDeprecatedFlareAPI = true;
<ide> export const enableFundamentalAPI = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js
<ide> export const replayFailedUnitOfWorkWithInvokeGuardedCallback = __DEV__;
<ide> // Update the tests so that they pass in either mode, then set these
<ide> // to __VARIANT__.
<ide> export const enableTrustedTypesIntegration = false;
<del>export const warnAboutShorthandPropertyCollision = true;
<ide> export const disableInputAttributeSyncing = false;
<ide> export const disableSchedulerTimeoutBasedOnReactExpirationTime = false;
<ide> export const enableModernEventSystem = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const {
<ide> disableModulePatternComponents,
<ide> disableInputAttributeSyncing,
<ide> enableTrustedTypesIntegration,
<del> warnAboutShorthandPropertyCollision,
<ide> disableSchedulerTimeoutBasedOnReactExpirationTime,
<ide> warnAboutSpreadingKeyToJSX,
<ide> replayFailedUnitOfWorkWithInvokeGuardedCallback, | 10 |
Python | Python | wrap long lines in cyg2win32 docstring | c804775b973b7de803eb279c1dcf5c15f1b74ad3 | <ide><path>numpy/distutils/misc_util.py
<ide> def blue_text(s):
<ide> def cyg2win32(path: str) -> str:
<ide> """Convert a path from Cygwin-native to Windows-native.
<ide>
<del> Uses the cygpath utility (part of the Base install) to do the actual
<del> conversion. Falls back to returning the original path if this fails.
<del>
<del> Handles the default ``/cygdrive`` mount prefix as well as the ``/proc/cygdrive``
<del> portable prefix, custom cygdrive prefixes such as ``/`` or ``/mnt``, and
<del> absolute paths such as ``/usr/src/`` or ``/home/username``
<add> Uses the cygpath utility (part of the Base install) to do the
<add> actual conversion. Falls back to returning the original path if
<add> this fails.
<add>
<add> Handles the default ``/cygdrive`` mount prefix as well as the
<add> ``/proc/cygdrive`` portable prefix, custom cygdrive prefixes such
<add> as ``/`` or ``/mnt``, and absolute paths such as ``/usr/src/`` or
<add> ``/home/username``
<ide>
<ide> Parameters
<ide> ---------- | 1 |
Javascript | Javascript | change abstract equal to strict equal | 0f841208d2d89d91395536a3227c4b11e1bf2425 | <ide><path>lib/console.js
<ide> Console.prototype.table = function(tabularData, properties) {
<ide> if (properties !== undefined && !ArrayIsArray(properties))
<ide> throw new ERR_INVALID_ARG_TYPE('properties', 'Array', properties);
<ide>
<del> if (tabularData == null || typeof tabularData !== 'object')
<add> if (tabularData === null || typeof tabularData !== 'object')
<ide> return this.log(tabularData);
<ide>
<ide> if (cliTable === undefined) cliTable = require('internal/cli_table'); | 1 |
Javascript | Javascript | fix linter violations | cab8824aaedee5ab54333633b05b389402490d32 | <ide><path>src/project.js
<ide> * DS207: Consider shorter variations of null checks
<ide> * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
<ide> */
<del>let Project
<ide> const path = require('path')
<ide>
<ide> let _ = require('underscore-plus')
<ide> const GitRepositoryProvider = require('./git-repository-provider')
<ide> //
<ide> // An instance of this class is always available as the `atom.project` global.
<ide> module.exports =
<del>(Project = class Project extends Model {
<add>class Project extends Model {
<ide> /*
<ide> Section: Construction and Destruction
<ide> */
<ide> module.exports =
<ide> }
<ide> for (let watcher = 0; watcher < this.watcherPromisesByPath.length; watcher++) { _ = this.watcherPromisesByPath[watcher]; watcher.dispose() }
<ide> this.rootDirectories = []
<del> return this.repositories = []
<add> this.repositories = []
<ide> }
<ide>
<ide> reset (packageManager) {
<ide> module.exports =
<ide> // TextBuffers backed by files that have been deleted from being saved.
<ide> bufferState.mustExist = bufferState.digestWhenLastPersisted !== false
<ide>
<del> return TextBuffer.deserialize(bufferState).catch(err => {
<add> return TextBuffer.deserialize(bufferState).catch((_) => {
<ide> this.retiredBufferIDs.add(bufferState.id)
<ide> this.retiredBufferPaths.add(bufferState.filePath)
<ide> return null
<ide> module.exports =
<ide>
<ide> let repo = null
<ide> for (let provider of this.repositoryProviders) {
<del> if (repo = typeof provider.repositoryForDirectorySync === 'function' ? provider.repositoryForDirectorySync(directory) : undefined) { break }
<add> if (provider.repositoryForDirectorySync) {
<add> repo = provider.repositoryForDirectorySync(directory)
<add> }
<add> if (repo) { break }
<ide> }
<ide> this.repositories.push(repo != null ? repo : null)
<ide>
<ide> module.exports =
<ide> getDirectoryForProjectPath (projectPath) {
<ide> let directory = null
<ide> for (let provider of this.directoryProviders) {
<del> if (directory = typeof provider.directoryForURISync === 'function' ? provider.directoryForURISync(projectPath) : undefined) { break }
<add> if (typeof provider.directoryForURISync === 'function') {
<add> directory = provider.directoryForURISync(projectPath)
<add> if (directory) break
<add> }
<add> }
<add> if (directory == null) {
<add> directory = this.defaultDirectoryProvider.directoryForURISync(projectPath)
<ide> }
<del> if (directory == null) { directory = this.defaultDirectoryProvider.directoryForURISync(projectPath) }
<ide> return directory
<ide> }
<ide>
<ide> module.exports =
<ide> }
<ide>
<ide> if (indexToRemove != null) {
<del> const [removedDirectory] = Array.from(this.rootDirectories.splice(indexToRemove, 1))
<add> this.rootDirectories.splice(indexToRemove, 1)
<ide> const [removedRepository] = Array.from(this.repositories.splice(indexToRemove, 1))
<ide> if (!this.repositories.includes(removedRepository)) {
<ide> if (removedRepository != null) {
<ide> Make sure you have permission to access \`${buffer.getPath()}\`.\
<ide> )
<ide> })
<ide> }
<del>})
<add>}
<ide>
<ide> function __guardMethod__ (obj, methodName, transform) {
<ide> if (typeof obj !== 'undefined' && obj !== null && typeof obj[methodName] === 'function') { | 1 |
Javascript | Javascript | remove controlid inclusion from mustache | d45ad5a3dd5cce1b6bdcf9cca863f95bbed17c4e | <ide><path>packages/ember-handlebars-compiler/lib/main.js
<ide> Ember.Handlebars.JavaScriptCompiler.prototype.ambiguousBlockValue = function() {
<ide> stringifyBlockHelperMissing(this.source);
<ide> };
<ide>
<del>var prefix = "ember" + (+new Date()), incr = 1;
<del>
<ide> /**
<ide> Rewrite simple mustaches from `{{foo}}` to `{{bind "foo"}}`. This means that
<ide> all simple mustaches in Ember's Handlebars will also set up an observer to
<ide> var prefix = "ember" + (+new Date()), incr = 1;
<ide> @param mustache
<ide> */
<ide> Ember.Handlebars.Compiler.prototype.mustache = function(mustache) {
<del> if (mustache.isHelper && mustache.id.string === 'control') {
<del> mustache.hash = mustache.hash || new Handlebars.AST.HashNode([]);
<del> mustache.hash.pairs.push(["controlID", new Handlebars.AST.StringNode(prefix + incr++)]);
<del> } else if (mustache.params.length || mustache.hash) {
<del> // no changes required
<del> } else {
<add> if (!(mustache.params.length || mustache.hash)) {
<ide> var id = new Handlebars.AST.IdNode([{ part: '_triageMustache' }]);
<ide>
<ide> // Update the mustache node to include a hash value indicating whether the original node | 1 |
Javascript | Javascript | remove unused movedtopluginwarningplugin | 6051cb146ed1856d13e2e996d5f5cc6796f3b9d1 | <ide><path>lib/MovedToPluginWarningPlugin.js
<del>/*
<del> MIT License http://www.opensource.org/licenses/mit-license.php
<del> Author Tobias Koppers @sokra
<del>*/
<del>"use strict";
<del>module.exports = class MovedToPluginWarningPlugin {
<del> constructor(optionName, pluginName) {
<del> this.optionName = optionName;
<del> this.pluginName = pluginName;
<del> }
<del> apply(compiler) {
<del> const optionName = this.optionName;
<del> const pluginName = this.pluginName;
<del> compiler.plugin("compilation", (compilation) => {
<del> compilation.warnings.push(new Error `webpack options:
<del> DEPRECATED option ${optionName} will be moved to the ${pluginName}.
<del> Use this instead.
<del> For more info about the usage of the ${pluginName} see https://webpack.js.org/plugins/`);
<del> });
<del> }
<del>}; | 1 |
Javascript | Javascript | remove polymorphic types from stylesheettypes | b98bf1e09739860d82e37225f1635bba3bc817b3 | <ide><path>Libraries/StyleSheet/StyleSheetTypes.js
<ide> export opaque type StyleSheetStyle: number = number;
<ide> export type ColorValue = null | string;
<ide> export type DimensionValue = null | number | string | AnimatedNode;
<ide>
<del>export type LayoutStyle<+Dimension = DimensionValue> = {
<add>export type LayoutStyle = {
<ide> +display?: 'none' | 'flex',
<del> +width?: Dimension,
<del> +height?: Dimension,
<del> +bottom?: Dimension,
<del> +end?: Dimension,
<del> +left?: Dimension,
<del> +right?: Dimension,
<del> +start?: Dimension,
<del> +top?: Dimension,
<del> +minWidth?: Dimension,
<del> +maxWidth?: Dimension,
<del> +minHeight?: Dimension,
<del> +maxHeight?: Dimension,
<del> +margin?: Dimension,
<del> +marginBottom?: Dimension,
<del> +marginEnd?: Dimension,
<del> +marginHorizontal?: Dimension,
<del> +marginLeft?: Dimension,
<del> +marginRight?: Dimension,
<del> +marginStart?: Dimension,
<del> +marginTop?: Dimension,
<del> +marginVertical?: Dimension,
<del> +padding?: Dimension,
<del> +paddingBottom?: Dimension,
<del> +paddingEnd?: Dimension,
<del> +paddingHorizontal?: Dimension,
<del> +paddingLeft?: Dimension,
<del> +paddingRight?: Dimension,
<del> +paddingStart?: Dimension,
<del> +paddingTop?: Dimension,
<del> +paddingVertical?: Dimension,
<add> +width?: DimensionValue,
<add> +height?: DimensionValue,
<add> +bottom?: DimensionValue,
<add> +end?: DimensionValue,
<add> +left?: DimensionValue,
<add> +right?: DimensionValue,
<add> +start?: DimensionValue,
<add> +top?: DimensionValue,
<add> +minWidth?: DimensionValue,
<add> +maxWidth?: DimensionValue,
<add> +minHeight?: DimensionValue,
<add> +maxHeight?: DimensionValue,
<add> +margin?: DimensionValue,
<add> +marginBottom?: DimensionValue,
<add> +marginEnd?: DimensionValue,
<add> +marginHorizontal?: DimensionValue,
<add> +marginLeft?: DimensionValue,
<add> +marginRight?: DimensionValue,
<add> +marginStart?: DimensionValue,
<add> +marginTop?: DimensionValue,
<add> +marginVertical?: DimensionValue,
<add> +padding?: DimensionValue,
<add> +paddingBottom?: DimensionValue,
<add> +paddingEnd?: DimensionValue,
<add> +paddingHorizontal?: DimensionValue,
<add> +paddingLeft?: DimensionValue,
<add> +paddingRight?: DimensionValue,
<add> +paddingStart?: DimensionValue,
<add> +paddingTop?: DimensionValue,
<add> +paddingVertical?: DimensionValue,
<ide> +borderWidth?: number,
<ide> +borderBottomWidth?: number,
<ide> +borderEndWidth?: number,
<ide> export type TransformStyle = {
<ide> >,
<ide> };
<ide>
<del>export type ShadowStyle<+Color = ColorValue> = {
<del> +shadowColor?: Color,
<add>export type ShadowStyle = {
<add> +shadowColor?: ColorValue,
<ide> +shadowOffset?: {
<ide> +width?: number,
<ide> +height?: number,
<ide> export type ShadowStyle<+Color = ColorValue> = {
<ide> +shadowRadius?: number,
<ide> };
<ide>
<del>export type ViewStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<del> ...$Exact<LayoutStyle<Dimension>>,
<del> ...$Exact<ShadowStyle<Color>>,
<add>export type ViewStyle = {
<add> ...$Exact<LayoutStyle>,
<add> ...$Exact<ShadowStyle>,
<ide> ...$Exact<TransformStyle>,
<ide> +backfaceVisibility?: 'visible' | 'hidden',
<del> +backgroundColor?: Color,
<del> +borderColor?: Color,
<del> +borderBottomColor?: Color,
<del> +borderEndColor?: Color,
<del> +borderLeftColor?: Color,
<del> +borderRightColor?: Color,
<del> +borderStartColor?: Color,
<del> +borderTopColor?: Color,
<add> +backgroundColor?: ColorValue,
<add> +borderColor?: ColorValue,
<add> +borderBottomColor?: ColorValue,
<add> +borderEndColor?: ColorValue,
<add> +borderLeftColor?: ColorValue,
<add> +borderRightColor?: ColorValue,
<add> +borderStartColor?: ColorValue,
<add> +borderTopColor?: ColorValue,
<ide> +borderRadius?: number,
<ide> +borderBottomEndRadius?: number,
<ide> +borderBottomLeftRadius?: number,
<ide> export type ViewStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<ide> +elevation?: number,
<ide> };
<ide>
<del>export type TextStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<del> ...$Exact<ViewStyle<Dimension, Color>>,
<del> +color?: Color,
<add>export type TextStyle = {
<add> ...$Exact<ViewStyle>,
<add> +color?: ColorValue,
<ide> +fontFamily?: string,
<ide> +fontSize?: number,
<ide> +fontStyle?: 'normal' | 'italic',
<ide> export type TextStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<ide> >,
<ide> +textShadowOffset?: {+width?: number, +height?: number},
<ide> +textShadowRadius?: number,
<del> +textShadowColor?: Color,
<add> +textShadowColor?: ColorValue,
<ide> +letterSpacing?: number,
<ide> +lineHeight?: number,
<ide> +textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify',
<ide> export type TextStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<ide> | 'line-through'
<ide> | 'underline line-through',
<ide> +textDecorationStyle?: 'solid' | 'double' | 'dotted' | 'dashed',
<del> +textDecorationColor?: Color,
<add> +textDecorationColor?: ColorValue,
<ide> +writingDirection?: 'auto' | 'ltr' | 'rtl',
<ide> };
<ide>
<del>export type ImageStyle<+Dimension = DimensionValue, +Color = ColorValue> = {
<del> ...$Exact<ViewStyle<Dimension, Color>>,
<add>export type ImageStyle = {
<add> ...$Exact<ViewStyle>,
<ide> +resizeMode?: 'contain' | 'cover' | 'stretch' | 'center' | 'repeat',
<del> +tintColor?: Color,
<add> +tintColor?: ColorValue,
<ide> +overlayColor?: string,
<ide> };
<ide>
<del>export type Style<+Dimension = DimensionValue, +Color = ColorValue> = {
<del> ...$Exact<TextStyle<Dimension, Color>>,
<add>export type Style = {
<add> ...$Exact<TextStyle>,
<ide> +resizeMode?: 'contain' | 'cover' | 'stretch' | 'center' | 'repeat',
<del> +tintColor?: Color,
<add> +tintColor?: ColorValue,
<ide> +overlayColor?: string,
<ide> };
<ide>
<ide> export type StyleProp<+T> =
<ide> // $Shape<ImageStyle<DimensionValue, ColorValue>>,
<ide> // >;
<ide>
<del>export type StyleObj = StyleProp<$Shape<Style<DimensionValue, ColorValue>>>;
<add>export type StyleObj = StyleProp<$Shape<Style>>;
<ide> export type StyleValue = StyleObj;
<ide>
<ide> export type ViewStyleProp = StyleObj;
<ide> export type TextStyleProp = StyleObj;
<ide> export type ImageStyleProp = StyleObj;
<ide>
<ide> export type Styles = {
<del> +[key: string]: $Shape<Style<DimensionValue, ColorValue>>,
<add> +[key: string]: $Shape<Style>,
<ide> };
<ide> export type StyleSheet<+S: Styles> = $ObjMap<S, (Object) => StyleSheetStyle>;
<ide>
<ide> type Props = {position: TypeForStyleKey<'position'>};
<ide> This will correctly give you the type 'absolute' | 'relative' instead of the
<ide> weak type of just string;
<ide> */
<del>export type TypeForStyleKey<+key: $Keys<Style<>>> = $ElementType<Style<>, key>;
<add>export type TypeForStyleKey<+key: $Keys<Style>> = $ElementType<Style, key>;
<ide><path>Libraries/StyleSheet/flattenStyle.js
<ide>
<ide> var ReactNativePropRegistry;
<ide>
<del>import type { DimensionValue, ColorValue, StyleProp, Style } from 'StyleSheetTypes';
<add>import type { StyleProp, Style } from 'StyleSheetTypes';
<ide>
<ide> function getStyle(style) {
<ide> if (ReactNativePropRegistry === undefined) {
<ide> function getStyle(style) {
<ide> return style;
<ide> }
<ide>
<del>function flattenStyle(style: ?StyleProp<Style<DimensionValue, ColorValue>>): ?Style<DimensionValue, ColorValue> {
<add>function flattenStyle(style: ?StyleProp<Style>): ?Style {
<ide> if (style == null) {
<ide> return undefined;
<ide> } | 2 |
PHP | PHP | apply fixes from styleci | 1e4b8a50d5075eb6693b908c57e75d87aadb3537 | <ide><path>tests/View/fixtures/section-exception-layout.php
<del><?php echo $__env->yieldContent('content');
<add><?php
<add>
<add>echo $__env->yieldContent('content'); | 1 |
Text | Text | add v3.18.0 to changelog | 85f2e8c314e619eab64013cab753974974260bcd | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### v3.18.0-beta.5 (April 7, 2020)
<del>
<del>- [#18857](https://github.com/emberjs/ember.js/pull/18857) [BUGFIX] Pass value through to `PROPERTY_DID_CHANGE` to avoid calling `get` when setting values for computed props
<del>- [#18861](https://github.com/emberjs/ember.js/pull/18861) [BUGFIX] Update glimmer-vm to 0.50.1 to improve dev time performance.
<del>
<del>### v3.18.0-beta.4 (March 31, 2020)
<del>
<del>- [#18837](https://github.com/emberjs/ember.js/pull/18837) [BUGFIX] Fix `willDestroy` on class helpers
<del>- [#18838](https://github.com/emberjs/ember.js/pull/18838) [BUGFIX] Ensure destructors (e.g. `will-destroy` modifier, `@ember/component`s with `willDestroyElement`, etc) fire when used within an `{{#each}}` block.
<del>
<del>### v3.18.0-beta.3 (March 23, 2020)
<del>
<del>- [#18831](https://github.com/emberjs/ember.js/pull/18831) [BUGFIX] Fix transpilation issues (e.g. `_createSuper` is not a function) when used with Babel 7.9.0+.
<del>
<del>### v3.18.0-beta.2 (March 16, 2020)
<del>
<add>### v3.18.0 (April 14, 2020)
<add>- [#18869](https://github.com/emberjs/ember.js/pull/18869) / [#18861](https://github.com/emberjs/ember.js/pull/18861) / [#18811](https://github.com/emberjs/ember.js/pull/18811) [BUGFIX] Update to glimmer-vm 0.50.2.
<ide> - [#18807](https://github.com/emberjs/ember.js/pull/18807) [BUGFIX] Do not error (RE: `elementId` changing) if `elementId` is not changed
<del>- [#18811](https://github.com/emberjs/ember.js/pull/18811) [BUGFIX] Upgrade to latest glimmer-vm
<del>
<del>### v3.18.0-beta.1 (March 5, 2020)
<del>
<ide> - [#18774](https://github.com/emberjs/ember.js/pull/18774) [BUGFIX] Suspend observer deactivation during property changes
<ide> - [#18785](https://github.com/emberjs/ember.js/pull/18785) Drop Node 8 support.
<ide> | 1 |
Text | Text | fix typo in docs | d53364c44b2fb75b59e2c98090b253c103d63c75 | <ide><path>docs/recipes/CodeSplitting.md
<ide> that to the store instance.
<ide> ```js
<ide> import { createStore } from 'redux'
<ide>
<del>// Define the Reducers that will always be present in the appication
<add>// Define the Reducers that will always be present in the application
<ide> const staticReducers = {
<ide> users: usersReducer,
<ide> posts: postsReducer | 1 |
PHP | PHP | add missing tests | 9c652e65731484b478056e283d3f9b86dca1b2e7 | <ide><path>lib/Cake/Test/Case/AllDatabaseTest.php
<ide> public static function suite() {
<ide> 'Datasource' . DS . 'Database' . DS . 'Mysql',
<ide> 'Datasource' . DS . 'Database' . DS . 'Postgres',
<ide> 'Datasource' . DS . 'Database' . DS . 'Sqlite',
<del> 'Datasource' . DS . 'Database' . DS . 'Sqlserver'
<add> 'Datasource' . DS . 'Database' . DS . 'Sqlserver',
<add> 'Datasource' . DS . 'CakeSession',
<add> 'Datasource' . DS . 'Session' . DS . 'CacheSession',
<add> 'Datasource' . DS . 'Session' . DS . 'DatabaseSession',
<ide> );
<ide> foreach ($tasks as $task) {
<ide> $suite->addTestFile($path . $task . 'Test.php');
<ide><path>lib/Cake/Test/Case/AllEventTest.php
<add><?php
<add>/**
<add> * AllEventTest file
<add> *
<add> * PHP 5
<add> *
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @package Cake.Test.Case
<add> * @since CakePHP(tm) v 2.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>
<add>/**
<add> * AllEventTest class
<add> *
<add> * This test group will run Event tests.
<add> *
<add> * @package Cake.Test.Case
<add> */
<add>class AllEventTest extends PHPUnit_Framework_TestSuite {
<add>
<add>/**
<add> * suite method, defines tests for this suite.
<add> *
<add> * @return void
<add> */
<add> public static function suite() {
<add> $suite = new CakeTestSuite('All Event related class tests');
<add> $suite->addTestDirectory(CORE_TEST_CASES . DS . 'Event');
<add> return $suite;
<add> }
<add>}
<add>
<ide><path>lib/Cake/Test/Case/AllTestsTest.php
<ide> public static function suite() {
<ide> $suite->addTestFile($path . 'AllControllerTest.php');
<ide> $suite->addTestFile($path . 'AllDatabaseTest.php');
<ide> $suite->addTestFile($path . 'AllErrorTest.php');
<add> $suite->addTestFile($path . 'AllEventTest.php');
<ide> $suite->addTestFile($path . 'AllHelpersTest.php');
<ide> $suite->addTestFile($path . 'AllLogTest.php');
<ide> $suite->addTestFile($path . 'AllI18nTest.php'); | 3 |
Python | Python | fix syntax error | f555f7e48d63fb37a1d1ecaab0fed6ba3ea7c7c3 | <ide><path>celery/contrib/coroutine.py
<ide> class CoroutineTask(Task):
<ide> def body(self):
<ide> while True:
<ide> args, kwargs = (yield)
<del> yield self.run(*args, *kwargs)
<add> yield self.run(*args, **kwargs)
<ide>
<ide> def run(self, *args, **kwargs):
<ide> try:
<ide> class Aggregate(CoroutineTask):
<ide> abstract = True
<ide> proxied = None
<ide> minlen = 100
<del> time_max = 60
<add> time_max = None
<ide> _time_since = None
<ide>
<ide> def body(self):
<ide> def process(self, jobs):
<ide> "Subclasses of Aggregate needs to implement process()")
<ide>
<ide> def _expired(self):
<add> if not self.time_max:
<add> return False
<ide> if not self._time_since:
<ide> self._time_since = time.time()
<ide> return False | 1 |
Javascript | Javascript | replace concatenation with template literals | d112f5982c9bdb03c4e94262d7d64f67f58d87b2 | <ide><path>test/parallel/test-http-extra-response.js
<ide> const net = require('net');
<ide> const body = 'hello world\r\n';
<ide> const fullResponse =
<ide> 'HTTP/1.1 500 Internal Server Error\r\n' +
<del> 'Content-Length: ' + body.length + '\r\n' +
<add> `Content-Length: ${body.length}\r\n` +
<ide> 'Content-Type: text/plain\r\n' +
<ide> 'Date: Fri + 18 Feb 2011 06:22:45 GMT\r\n' +
<ide> 'Host: 10.20.149.2\r\n' + | 1 |
Javascript | Javascript | fix calls to jasmine fail() | 0985a37376314616ac2b777bddd8bc07e1be7af7 | <ide><path>test/ng/browserSpecs.js
<ide> describe('browser', function() {
<ide> browser.cookies('x', longVal + longVal + longVal); //should be too long for all browsers
<ide>
<ide> if (document.cookie !== cookieStr) {
<del> fail("browser didn't drop long cookie when it was expected. make the cookie in this " +
<del> "test longer");
<add> this.fail(new Error("browser didn't drop long cookie when it was expected. make the " +
<add> "cookie in this test longer"));
<ide> }
<ide>
<ide> expect(browser.cookies().x).toEqual('shortVal');
<ide><path>test/ng/compileSpec.js
<ide> describe('$compile', function() {
<ide>
<ide> it('should prevent multiple templates per element', inject(function($compile) {
<ide> try {
<del> $compile('<div><span replace class="replace"></span></div>')
<del> fail();
<add> $compile('<div><span replace class="replace"></span></div>');
<add> this.fail(new Error('should have thrown Multiple directives error'));
<ide> } catch(e) {
<ide> expect(e.message).toMatch(/Multiple directives .* asking for template/);
<ide> } | 2 |
Javascript | Javascript | add renderer id to react-devtools injection | ec77740ac3332024fcee71e2885cf8114a3ec457 | <ide><path>src/renderers/dom/ReactDOMStackEntry.js
<ide> if (
<ide> },
<ide> Mount: ReactMount,
<ide> Reconciler: ReactReconciler,
<add> rendererPackageName: 'react-dom',
<ide> });
<ide> }
<ide>
<ide><path>src/renderers/dom/fiber/ReactDOMFiberEntry.js
<ide> const foundDevTools = injectInternals({
<ide> // This is an enum because we may add more (e.g. profiler build)
<ide> bundleType: __DEV__ ? 1 : 0,
<ide> version: ReactVersion,
<add> rendererPackageName: 'react-dom',
<ide> });
<ide>
<ide> if (__DEV__) {
<ide><path>src/renderers/native/ReactNativeFiberEntry.js
<ide> injectInternals({
<ide> // This is an enum because we may add more (e.g. profiler build)
<ide> bundleType: __DEV__ ? 1 : 0,
<ide> version: ReactVersion,
<add> rendererPackageName: 'react-native',
<ide> });
<ide>
<ide> module.exports = ReactNativeFiber;
<ide><path>src/renderers/native/ReactNativeStackEntry.js
<ide> if (
<ide> Mount: ReactNativeMount,
<ide> Reconciler: require('ReactReconciler'),
<ide> getInspectorDataForViewTag: ReactNativeStackInspector.getInspectorDataForViewTag,
<add> rendererPackageName: 'react-native',
<ide> });
<ide> }
<ide> | 4 |
Javascript | Javascript | change callbacks to arrow function | 0f18a403741ff4cca80d7b6b5937e06fd50c3900 | <ide><path>lib/internal/bootstrap/node.js
<ide> // To allow people to extend Node in different ways, this hook allows
<ide> // one to drop a file lib/_third_party_main.js into the build
<ide> // directory which will be executed instead of Node's normal loading.
<del> process.nextTick(function() {
<add> process.nextTick(() => {
<ide> NativeModule.require('_third_party_main');
<ide> });
<ide> } else if (process.argv[1] === 'inspect' || process.argv[1] === 'debug') {
<ide> }
<ide>
<ide> // Start the debugger agent.
<del> process.nextTick(function() {
<add> process.nextTick(() => {
<ide> NativeModule.require('internal/deps/node-inspect/lib/_inspect').start();
<ide> });
<ide>
<ide> if (process._forceRepl || NativeModule.require('tty').isatty(0)) {
<ide> // REPL
<ide> const cliRepl = NativeModule.require('internal/repl');
<del> cliRepl.createInternalRepl(process.env, function(err, repl) {
<add> cliRepl.createInternalRepl(process.env, (err, repl) => {
<ide> if (err) {
<ide> throw err;
<ide> }
<del> repl.on('exit', function() {
<add> repl.on('exit', () => {
<ide> if (repl._flushing) {
<ide> repl.pause();
<del> return repl.once('flushHistory', function() {
<add> return repl.once('flushHistory', () => {
<ide> process.exit();
<ide> });
<ide> }
<ide> process.stdin.setEncoding('utf8');
<ide>
<ide> let code = '';
<del> process.stdin.on('data', function(d) {
<add> process.stdin.on('data', (d) => {
<ide> code += d;
<ide> });
<ide>
<ide> emitAfter
<ide> } = NativeModule.require('internal/async_hooks');
<ide>
<del> process._fatalException = function(er) {
<add> process._fatalException = (er) => {
<ide> // It's possible that defaultTriggerAsyncId was set for a constructor
<ide> // call that threw and was never cleared. So clear it now.
<ide> clearDefaultTriggerAsyncId(); | 1 |
Python | Python | fix device in longformer onnx path | 993a187c6ff03cd971c71ad234d1ddfb3beb020a | <ide><path>src/transformers/models/led/modeling_led.py
<ide> def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
<ide> hidden_states.size(2),
<ide> ]
<ide>
<del> overlapping_chunks = torch.empty(chunk_size)
<add> overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
<ide> for chunk in range(chunk_size[1]):
<ide> overlapping_chunks[:, chunk, :, :] = hidden_states[
<ide> :, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, :
<ide><path>src/transformers/models/longformer/modeling_longformer.py
<ide> def _chunk(hidden_states, window_overlap, onnx_export: bool = False):
<ide> hidden_states.size(2),
<ide> ]
<ide>
<del> overlapping_chunks = torch.empty(chunk_size)
<add> overlapping_chunks = torch.empty(chunk_size, device=hidden_states.device)
<ide> for chunk in range(chunk_size[1]):
<ide> overlapping_chunks[:, chunk, :, :] = hidden_states[
<ide> :, chunk * window_overlap : chunk * window_overlap + 2 * window_overlap, : | 2 |
Mixed | Ruby | generate secret_key_base for all new credentials | 915776ad04427044526ae9a2f9d12611d01d3675 | <ide><path>railties/CHANGELOG.md
<add>* Newly generated per-environment credentials files (e.g.
<add> `config/credentials/production.yml.enc`) now include a `secret_key_base` for
<add> convenience, just as `config/credentials.yml.enc` does.
<add>
<add> *Jonathan Hefner*
<add>
<ide> * `--no-*` options now work with the app generator's `--minimal` option, and
<ide> are both comprehensive and precise. For example:
<ide>
<ide><path>railties/lib/rails/commands/credentials/credentials_command.rb
<ide> def ensure_encryption_key_has_been_added
<ide> end
<ide>
<ide> def ensure_credentials_have_been_added
<del> if options[:environment]
<del> encrypted_file_generator.add_encrypted_file_silently(content_path, key_path)
<del> else
<del> credentials_generator.add_credentials_file_silently
<del> end
<add> credentials_generator.add_credentials_file
<ide> end
<ide>
<ide> def change_credentials_in_system_editor
<ide> def encryption_key_file_generator
<ide> Rails::Generators::EncryptionKeyFileGenerator.new
<ide> end
<ide>
<del> def encrypted_file_generator
<del> require "rails/generators"
<del> require "rails/generators/rails/encrypted_file/encrypted_file_generator"
<del>
<del> Rails::Generators::EncryptedFileGenerator.new
<del> end
<del>
<ide> def credentials_generator
<ide> require "rails/generators"
<ide> require "rails/generators/rails/credentials/credentials_generator"
<ide>
<del> Rails::Generators::CredentialsGenerator.new
<add> Rails::Generators::CredentialsGenerator.new([content_path, key_path], quiet: true)
<ide> end
<ide> end
<ide> end
<ide><path>railties/lib/rails/generators/rails/app/app_generator.rb
<ide> def credentials
<ide> return if options[:pretend] || options[:dummy_app]
<ide>
<ide> require "rails/generators/rails/credentials/credentials_generator"
<del> Rails::Generators::CredentialsGenerator.new([], quiet: options[:quiet]).add_credentials_file_silently
<add> Rails::Generators::CredentialsGenerator.new([], quiet: options[:quiet]).add_credentials_file
<ide> end
<ide>
<ide> def credentials_diff_enroll
<ide><path>railties/lib/rails/generators/rails/credentials/credentials_generator.rb
<ide> module Rails
<ide> module Generators
<ide> class CredentialsGenerator < Base # :nodoc:
<add> argument :content_path, default: "config/credentials.yml.enc"
<add> argument :key_path, default: "config/master.key"
<add>
<ide> def add_credentials_file
<del> unless credentials.content_path.exist?
<del> template = credentials_template
<add> in_root do
<add> return if File.exist?(content_path)
<ide>
<del> say "Adding #{credentials.content_path} to store encrypted credentials."
<add> say "Adding #{content_path} to store encrypted credentials."
<ide> say ""
<add>
<add> encrypted_file.write(content)
<add>
<ide> say "The following content has been encrypted with the Rails master key:"
<ide> say ""
<del> say template, :on_green
<add> say content, :on_green
<ide> say ""
<del>
<del> add_credentials_file_silently(template)
<del>
<ide> say "You can edit encrypted credentials with `bin/rails credentials:edit`."
<ide> say ""
<ide> end
<ide> end
<ide>
<del> def add_credentials_file_silently(template = nil)
<del> unless credentials.content_path.exist?
<del> credentials.write(credentials_template)
<del> end
<del> end
<del>
<ide> private
<del> def credentials
<add> def encrypted_file
<ide> ActiveSupport::EncryptedConfiguration.new(
<del> config_path: "config/credentials.yml.enc",
<del> key_path: "config/master.key",
<add> config_path: content_path,
<add> key_path: key_path,
<ide> env_key: "RAILS_MASTER_KEY",
<ide> raise_if_missing_key: true
<ide> )
<ide> end
<ide>
<del> def credentials_template
<del> <<~YAML
<add> def content
<add> @content ||= <<~YAML
<ide> # aws:
<ide> # access_key_id: 123
<ide> # secret_access_key: 345
<ide><path>railties/test/commands/credentials_test.rb
<ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
<ide> test "edit credentials" do
<ide> # Run twice to ensure credentials can be reread after first edit pass.
<ide> 2.times do
<del> assert_match(/access_key_id: 123/, run_edit_command)
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_edit_command
<ide> end
<ide> end
<ide>
<ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "edit command does not overwrite by default if credentials already exists" do
<del> run_edit_command(editor: 'ruby -e "File.write ARGV[0], %(api_key: abc)"')
<del> assert_match(/api_key: abc/, run_show_command)
<add> write_credentials "foo: bar"
<add> output = run_edit_command
<ide>
<del> run_edit_command
<del> assert_match(/api_key: abc/, run_show_command)
<add> assert_match %r/foo: bar/, output
<add> assert_no_match DEFAULT_CREDENTIALS_PATTERN, output
<ide> end
<ide>
<ide> test "edit command does not add master key when `RAILS_MASTER_KEY` env specified" do
<ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
<ide> FileUtils.rm("config/master.key")
<ide>
<ide> switch_env("RAILS_MASTER_KEY", key) do
<del> assert_match(/access_key_id: 123/, run_edit_command)
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_edit_command
<ide> assert_not File.exist?("config/master.key")
<ide> end
<ide> end
<ide> end
<ide>
<ide> test "edit command modifies file specified by environment option" do
<del> assert_match(/access_key_id: 123/, run_edit_command(environment: "production"))
<del> Dir.chdir(app_path) do
<del> assert File.exist?("config/credentials/production.key")
<del> assert File.exist?("config/credentials/production.yml.enc")
<del> end
<add> remove_file "config/credentials.yml.enc"
<add>
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_edit_command(environment: "production")
<add>
<add> assert_no_file "config/credentials.yml.enc"
<add> assert_file "config/credentials/production.key"
<add> assert_file "config/credentials/production.yml.enc"
<ide> end
<ide>
<ide> test "edit command properly expands environment option" do
<del> assert_match(/access_key_id: 123/, run_edit_command(environment: "prod"))
<del> Dir.chdir(app_path) do
<del> assert File.exist?("config/credentials/production.key")
<del> assert File.exist?("config/credentials/production.yml.enc")
<del> end
<add> remove_file "config/credentials.yml.enc"
<add>
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_edit_command(environment: "prod")
<add>
<add> assert_no_file "config/credentials.yml.enc"
<add> assert_file "config/credentials/production.key"
<add> assert_file "config/credentials/production.yml.enc"
<ide> end
<ide>
<ide> test "edit command does not raise when an initializer tries to access non-existent credentials" do
<ide> app_file "config/initializers/raise_when_loaded.rb", <<-RUBY
<ide> Rails.application.credentials.missing_key!
<ide> RUBY
<ide>
<del> assert_match(/access_key_id: 123/, run_edit_command(environment: "qa"))
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_edit_command(environment: "qa")
<ide> end
<ide>
<del> test "edit command generates template file when the file does not exist" do
<del> FileUtils.rm("#{app_path}/config/credentials.yml.enc")
<del> run_edit_command
<add> test "edit command generates credentials file when it does not exist" do
<add> remove_file "config/credentials.yml.enc"
<ide>
<del> output = run_show_command
<del> assert_match(/access_key_id: 123/, output)
<del> assert_match(/secret_key_base/, output)
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_edit_command
<add>
<add> assert_file "config/credentials.yml.enc"
<ide> end
<ide>
<ide>
<ide> test "show credentials" do
<del> assert_match(/access_key_id: 123/, run_show_command)
<add> assert_match DEFAULT_CREDENTIALS_PATTERN, run_show_command
<ide> end
<ide>
<ide> test "show command raises error when require_master_key is specified and key does not exist" do
<ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> test "show command displays content specified by environment option" do
<del> run_edit_command(environment: "production")
<add> write_credentials "foo: bar", environment: "production"
<ide>
<del> assert_match(/access_key_id: 123/, run_show_command(environment: "production"))
<add> assert_match %r/foo: bar/, run_show_command(environment: "production")
<ide> end
<ide>
<ide> test "show command properly expands environment option" do
<del> run_edit_command(environment: "production")
<add> write_credentials "foo: bar", environment: "production"
<ide>
<del> output = run_show_command(environment: "prod")
<del> assert_match(/access_key_id: 123/, output)
<del> assert_no_match(/secret_key_base/, output)
<add> assert_match %r/foo: bar/, run_show_command(environment: "prod")
<ide> end
<ide>
<ide>
<ide> class Rails::Command::CredentialsCommandTest < ActiveSupport::TestCase
<ide> end
<ide>
<ide> private
<add> DEFAULT_CREDENTIALS_PATTERN = /access_key_id: 123\n.*secret_key_base: \h{128}\n/m
<add>
<ide> def run_edit_command(editor: "cat", environment: nil, **options)
<ide> switch_env("EDITOR", editor) do
<ide> args = environment ? ["--environment", environment] : []
<ide> def run_diff_command(path = nil, enroll: nil, disenroll: nil, **options)
<ide> args = [path, ("--enroll" if enroll), ("--disenroll" if disenroll)].compact
<ide> rails "credentials:diff", args, **options
<ide> end
<add>
<add> def write_credentials(content, **options)
<add> switch_env("CONTENT", content) do
<add> run_edit_command(editor: %(ruby -e "File.write ARGV[0], ENV['CONTENT']"), **options)
<add> end
<add> end
<add>
<add> def assert_file(relative)
<add> assert File.exist?(app_path(relative)), "Expected file #{relative.inspect} to exist, but it does not"
<add> end
<add>
<add> def assert_no_file(relative)
<add> assert_not File.exist?(app_path(relative)), "Expected file #{relative.inspect} to not exist, but it does"
<add> end
<ide> end | 5 |
Mixed | Javascript | add perf_hooks detail for http request and client | d96a2ea615b4090bb8cd53a9bc7fcba231479e12 | <ide><path>doc/api/perf_hooks.md
<ide> property will be an {Object} with two properties:
<ide> * `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY`
<ide> * `perf_hooks.constants.NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE`
<ide>
<add>### HTTP ('http') Details
<add>
<add>When `performanceEntry.type` is equal to `'http'`, the `performanceEntry.detail`
<add>property will be an {Object} containing additional information.
<add>
<add>If `performanceEntry.name` is equal to `HttpClient`, the `detail`
<add>will contain the following properties: `req`, `res`. And the `req` property
<add>will be an {Object} containing `method`, `url`, `headers`, the `res` property
<add>will be an {Object} containing `statusCode`, `statusMessage`, `headers`.
<add>
<add>If `performanceEntry.name` is equal to `HttpRequest`, the `detail`
<add>will contain the following properties: `req`, `res`. And the `req` property
<add>will be an {Object} containing `method`, `url`, `headers`, the `res` property
<add>will be an {Object} containing `statusCode`, `statusMessage`, `headers`.
<add>
<add>This could add additional memory overhead and should only be used for
<add>diagnostic purposes, not left turned on in production by default.
<add>
<ide> ### HTTP/2 ('http2') Details
<ide>
<ide> When `performanceEntry.type` is equal to `'http2'`, the
<ide><path>lib/_http_client.js
<ide> const Agent = require('_http_agent');
<ide> const { Buffer } = require('buffer');
<ide> const { defaultTriggerAsyncIdScope } = require('internal/async_hooks');
<ide> const { URL, urlToHttpOptions, searchParamsSymbol } = require('internal/url');
<del>const { kOutHeaders, kNeedDrain, emitStatistics } = require('internal/http');
<add>const { kOutHeaders, kNeedDrain } = require('internal/http');
<ide> const { connResetException, codes } = require('internal/errors');
<ide> const {
<ide> ERR_HTTP_HEADERS_SENT,
<ide> const {
<ide>
<ide> const {
<ide> hasObserver,
<add> startPerf,
<add> stopPerf,
<ide> } = require('internal/perf/observe');
<ide>
<del>const { now } = require('internal/perf/utils');
<del>
<ide> const kClientRequestStatistics = Symbol('ClientRequestStatistics');
<ide>
<ide> const { addAbortSignal, finished } = require('stream');
<ide> ClientRequest.prototype._finish = function _finish() {
<ide> DTRACE_HTTP_CLIENT_REQUEST(this, this.socket);
<ide> FunctionPrototypeCall(OutgoingMessage.prototype._finish, this);
<ide> if (hasObserver('http')) {
<del> this[kClientRequestStatistics] = {
<del> startTime: now(),
<del> type: 'HttpClient',
<del> };
<add> startPerf(this, kClientRequestStatistics, {
<add> type: 'http',
<add> name: 'HttpClient',
<add> detail: {
<add> req: {
<add> method: this.method,
<add> url: `${this.protocol}//${this.host}${this.path}`,
<add> headers: typeof this.getHeaders === 'function' ? this.getHeaders() : {},
<add> },
<add> },
<add> });
<ide> }
<ide> };
<ide>
<ide> function parserOnIncomingClient(res, shouldKeepAlive) {
<ide> }
<ide>
<ide> DTRACE_HTTP_CLIENT_RESPONSE(socket, req);
<del> emitStatistics(req[kClientRequestStatistics]);
<add> if (req[kClientRequestStatistics] && hasObserver('http')) {
<add> stopPerf(req, kClientRequestStatistics, {
<add> detail: {
<add> res: {
<add> statusCode: res.statusCode,
<add> statusMessage: res.statusMessage,
<add> headers: res.headers,
<add> },
<add> },
<add> });
<add> }
<ide> req.res = res;
<ide> res.req = req;
<ide>
<ide><path>lib/_http_server.js
<ide> const {
<ide> const {
<ide> kOutHeaders,
<ide> kNeedDrain,
<del> emitStatistics
<ide> } = require('internal/http');
<ide> const {
<ide> defaultTriggerAsyncIdScope,
<ide> const kServerResponseStatistics = Symbol('ServerResponseStatistics');
<ide>
<ide> const {
<ide> hasObserver,
<add> startPerf,
<add> stopPerf,
<ide> } = require('internal/perf/observe');
<ide>
<del>const { now } = require('internal/perf/utils');
<del>
<ide> const STATUS_CODES = {
<ide> 100: 'Continue', // RFC 7231 6.2.1
<ide> 101: 'Switching Protocols', // RFC 7231 6.2.2
<ide> function ServerResponse(req) {
<ide> }
<ide>
<ide> if (hasObserver('http')) {
<del> this[kServerResponseStatistics] = {
<del> startTime: now(),
<del> type: 'HttpRequest',
<del> };
<add> startPerf(this, kServerResponseStatistics, {
<add> type: 'http',
<add> name: 'HttpRequest',
<add> detail: {
<add> req: {
<add> method: req.method,
<add> url: req.url,
<add> headers: req.headers,
<add> },
<add> },
<add> });
<ide> }
<ide> }
<ide> ObjectSetPrototypeOf(ServerResponse.prototype, OutgoingMessage.prototype);
<ide> ObjectSetPrototypeOf(ServerResponse, OutgoingMessage);
<ide>
<ide> ServerResponse.prototype._finish = function _finish() {
<ide> DTRACE_HTTP_SERVER_RESPONSE(this.socket);
<del> emitStatistics(this[kServerResponseStatistics]);
<add> if (this[kServerResponseStatistics] && hasObserver('http')) {
<add> stopPerf(this, kServerResponseStatistics, {
<add> detail: {
<add> res: {
<add> statusCode: this.statusCode,
<add> statusMessage: this.statusMessage,
<add> headers: typeof this.getHeaders === 'function' ? this.getHeaders() : {},
<add> },
<add> },
<add> });
<add> }
<ide> OutgoingMessage.prototype._finish.call(this);
<ide> };
<ide>
<ide><path>lib/internal/http.js
<ide> const {
<ide>
<ide> const { setUnrefTimeout } = require('internal/timers');
<ide>
<del>const { InternalPerformanceEntry } = require('internal/perf/performance_entry');
<del>
<del>const {
<del> enqueue,
<del> hasObserver,
<del>} = require('internal/perf/observe');
<del>
<del>const { now } = require('internal/perf/utils');
<del>
<ide> let utcCache;
<ide>
<ide> function utcDate() {
<ide> function resetCache() {
<ide> utcCache = undefined;
<ide> }
<ide>
<del>function emitStatistics(statistics) {
<del> if (!hasObserver('http') || statistics == null) return;
<del> const startTime = statistics.startTime;
<del> const entry = new InternalPerformanceEntry(
<del> statistics.type,
<del> 'http',
<del> startTime,
<del> now() - startTime,
<del> undefined,
<del> );
<del> enqueue(entry);
<del>}
<del>
<ide> module.exports = {
<ide> kOutHeaders: Symbol('kOutHeaders'),
<ide> kNeedDrain: Symbol('kNeedDrain'),
<ide> utcDate,
<del> emitStatistics,
<ide> };
<ide><path>test/parallel/test-http-perf_hooks.js
<ide> process.on('exit', () => {
<ide> } else if (entry.name === 'HttpRequest') {
<ide> numberOfHttpRequests++;
<ide> }
<add> assert.strictEqual(typeof entry.detail.req.method, 'string');
<add> assert.strictEqual(typeof entry.detail.req.url, 'string');
<add> assert.strictEqual(typeof entry.detail.req.headers, 'object');
<add> assert.strictEqual(typeof entry.detail.res.statusCode, 'number');
<add> assert.strictEqual(typeof entry.detail.res.statusMessage, 'string');
<add> assert.strictEqual(typeof entry.detail.res.headers, 'object');
<ide> });
<ide> assert.strictEqual(numberOfHttpClients, 2);
<ide> assert.strictEqual(numberOfHttpRequests, 2); | 5 |
Python | Python | add authentication for stable api | 422e3f1d5d66b9094e5a1c5412e66dd8c2202712 | <ide><path>airflow/api_connexion/endpoints/config_endpoint.py
<ide>
<ide> from flask import Response, request
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.schemas.config_schema import Config, ConfigOption, ConfigSection, config_schema
<ide> from airflow.configuration import conf
<ide> from airflow.settings import json
<ide> def _config_to_json(config: Config) -> str:
<ide> return json.dumps(config_schema.dump(config), indent=4)
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_config() -> Response:
<ide> """
<ide> Get current configuration.
<ide><path>airflow/api_connexion/endpoints/connection_endpoint.py
<ide> from marshmallow import ValidationError
<ide> from sqlalchemy import func
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import AlreadyExists, BadRequest, NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.connection_schema import (
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def delete_connection(connection_id, session):
<ide> """
<ide> def delete_connection(connection_id, session):
<ide> return NoContent, 204
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_connection(connection_id, session):
<ide> """
<ide> def get_connection(connection_id, session):
<ide> return connection_collection_item_schema.dump(connection)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide> def get_connections(session, limit, offset=0):
<ide> total_entries=total_entries))
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def patch_connection(connection_id, session, update_mask=None):
<ide> """
<ide> def patch_connection(connection_id, session, update_mask=None):
<ide> return connection_schema.dump(connection)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def post_connection(session):
<ide> """
<ide><path>airflow/api_connexion/endpoints/dag_endpoint.py
<ide> from sqlalchemy import func
<ide>
<ide> from airflow import DAG
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.dag_schema import (
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_dag(dag_id, session):
<ide> """
<ide> def get_dag(dag_id, session):
<ide> return dag_schema.dump(dag)
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_dag_details(dag_id):
<ide> """
<ide> Get details of DAG.
<ide> def get_dag_details(dag_id):
<ide> return dag_detail_schema.dump(dag)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide> def get_dags(session, limit, offset=0):
<ide> return dags_collection_schema.dump(DAGCollection(dags=dags, total_entries=total_entries))
<ide>
<ide>
<add>@security.requires_authentication
<ide> def patch_dag():
<ide> """
<ide> Update the specific DAG
<ide><path>airflow/api_connexion/endpoints/dag_run_endpoint.py
<ide> from marshmallow import ValidationError
<ide> from sqlalchemy import func
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import AlreadyExists, BadRequest, NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_datetime, format_parameters
<ide> from airflow.api_connexion.schemas.dag_run_schema import (
<ide> from airflow.utils.types import DagRunType
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def delete_dag_run(dag_id, dag_run_id, session):
<ide> """
<ide> def delete_dag_run(dag_id, dag_run_id, session):
<ide> return NoContent, 204
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_dag_run(dag_id, dag_run_id, session):
<ide> """
<ide> def get_dag_run(dag_id, dag_run_id, session):
<ide> return dagrun_schema.dump(dag_run)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'start_date_gte': format_datetime,
<ide> 'start_date_lte': format_datetime,
<ide> def _apply_date_filters_to_query(query, end_date_gte, end_date_lte, execution_da
<ide> return query
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_dag_runs_batch(session):
<ide> """
<ide> def get_dag_runs_batch(session):
<ide> total_entries=total_entries))
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def post_dag_run(dag_id, session):
<ide> """
<ide><path>airflow/api_connexion/endpoints/dag_source_endpoint.py
<ide> from flask import Response, current_app, request
<ide> from itsdangerous import BadSignature, URLSafeSerializer
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.api_connexion.schemas.dag_source_schema import dag_source_schema
<ide> from airflow.models.dagcode import DagCode
<ide>
<ide> log = logging.getLogger(__name__)
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_dag_source(file_token: str):
<ide> """
<ide> Get source code using file token
<ide><path>airflow/api_connexion/endpoints/event_log_endpoint.py
<ide>
<ide> from sqlalchemy import func
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.event_log_schema import (
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_event_log(event_log_id, session):
<ide> """
<ide> def get_event_log(event_log_id, session):
<ide> return event_log_schema.dump(event_log)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide><path>airflow/api_connexion/endpoints/extra_link_endpoint.py
<ide> from flask import current_app
<ide>
<ide> from airflow import DAG
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.exceptions import TaskNotFound
<ide> from airflow.models.dagbag import DagBag
<ide> from airflow.models.dagrun import DagRun as DR
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_extra_links(dag_id: str, dag_run_id: str, task_id: str, session):
<ide> """
<ide><path>airflow/api_connexion/endpoints/import_error_endpoint.py
<ide>
<ide> from sqlalchemy import func
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.error_schema import (
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_import_error(import_error_id, session):
<ide> """
<ide> def get_import_error(import_error_id, session):
<ide> return import_error_schema.dump(error)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide><path>airflow/api_connexion/endpoints/log_endpoint.py
<ide> from itsdangerous.exc import BadSignature
<ide> from itsdangerous.url_safe import URLSafeSerializer
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import BadRequest, NotFound
<ide> from airflow.api_connexion.schemas.log_schema import LogResponseObject, logs_schema
<ide> from airflow.models import DagRun
<ide> from airflow.utils.log.log_reader import TaskLogReader
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_log(session, dag_id, dag_run_id, task_id, task_try_number,
<ide> full_content=False, token=None):
<ide><path>airflow/api_connexion/endpoints/pool_endpoint.py
<ide> from sqlalchemy import func
<ide> from sqlalchemy.exc import IntegrityError
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import AlreadyExists, BadRequest, NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.pool_schema import PoolCollection, pool_collection_schema, pool_schema
<ide> from airflow.models.pool import Pool
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def delete_pool(pool_name: str, session):
<ide> """
<ide> def delete_pool(pool_name: str, session):
<ide> return Response(status=204)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_pool(pool_name, session):
<ide> """
<ide> def get_pool(pool_name, session):
<ide> return pool_schema.dump(obj)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide> def get_pools(session, limit, offset=None):
<ide> )
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def patch_pool(pool_name, session, update_mask=None):
<ide> """
<ide> def patch_pool(pool_name, session, update_mask=None):
<ide> return pool_schema.dump(pool)
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def post_pool(session):
<ide> """
<ide><path>airflow/api_connexion/endpoints/task_endpoint.py
<ide> from flask import current_app
<ide>
<ide> from airflow import DAG
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.api_connexion.schemas.task_schema import TaskCollection, task_collection_schema, task_schema
<ide> from airflow.exceptions import TaskNotFound
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_task(dag_id, task_id):
<ide> """
<ide> Get simplified representation of a task.
<ide> def get_task(dag_id, task_id):
<ide> return task_schema.dump(task)
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_tasks(dag_id):
<ide> """
<ide> Get tasks for DAG
<ide><path>airflow/api_connexion/endpoints/task_instance_endpoint.py
<ide>
<ide> # TODO(mik-laj): We have to implement it.
<ide> # Do you want to help? Please look at: https://github.com/apache/airflow/issues/8132
<add>from airflow.api_connexion import security
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_task_instance():
<ide> """
<ide> Get a task instance
<ide> """
<ide> raise NotImplementedError("Not implemented yet.")
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_task_instances():
<ide> """
<ide> Get list of task instances of DAG.
<ide> """
<ide> raise NotImplementedError("Not implemented yet.")
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_task_instances_batch():
<ide> """
<ide> Get list of task instances.
<ide> """
<ide> raise NotImplementedError("Not implemented yet.")
<ide>
<ide>
<add>@security.requires_authentication
<ide> def post_clear_task_instances():
<ide> """
<ide> Clear task instances.
<ide><path>airflow/api_connexion/endpoints/variable_endpoint.py
<ide> from marshmallow import ValidationError
<ide> from sqlalchemy import func
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import BadRequest, NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.variable_schema import variable_collection_schema, variable_schema
<ide> from airflow.models import Variable
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> def delete_variable(variable_key: str) -> Response:
<ide> """
<ide> Delete variable
<ide> def delete_variable(variable_key: str) -> Response:
<ide> return Response(status=204)
<ide>
<ide>
<add>@security.requires_authentication
<ide> def get_variable(variable_key: str) -> Response:
<ide> """
<ide> Get a variables by key
<ide> def get_variable(variable_key: str) -> Response:
<ide> return variable_schema.dump({"key": variable_key, "val": var})
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide> def get_variables(session, limit: Optional[int], offset: Optional[int] = None) -
<ide> })
<ide>
<ide>
<add>@security.requires_authentication
<ide> def patch_variable(variable_key: str, update_mask: Optional[List[str]] = None) -> Response:
<ide> """
<ide> Update a variable by key
<ide> def patch_variable(variable_key: str, update_mask: Optional[List[str]] = None) -
<ide> return Response(status=204)
<ide>
<ide>
<add>@security.requires_authentication
<ide> def post_variables() -> Response:
<ide> """
<ide> Create a variable
<ide><path>airflow/api_connexion/endpoints/xcom_endpoint.py
<ide> from sqlalchemy import and_, func
<ide> from sqlalchemy.orm.session import Session
<ide>
<add>from airflow.api_connexion import security
<ide> from airflow.api_connexion.exceptions import NotFound
<ide> from airflow.api_connexion.parameters import check_limit, format_parameters
<ide> from airflow.api_connexion.schemas.xcom_schema import (
<ide> from airflow.utils.session import provide_session
<ide>
<ide>
<add>@security.requires_authentication
<ide> @format_parameters({
<ide> 'limit': check_limit
<ide> })
<ide> def get_xcom_entries(
<ide> return xcom_collection_schema.dump(XComCollection(xcom_entries=query.all(), total_entries=total_entries))
<ide>
<ide>
<add>@security.requires_authentication
<ide> @provide_session
<ide> def get_xcom_entry(
<ide> dag_id: str,
<ide><path>airflow/api_connexion/security.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>from functools import wraps
<add>from typing import Callable, TypeVar, cast
<add>
<add>from flask import Response, current_app
<add>
<add>from airflow.api_connexion.exceptions import Unauthenticated
<add>
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def requires_authentication(function: T):
<add> """Decorator for functions that require authentication"""
<add> @wraps(function)
<add> def decorated(*args, **kwargs):
<add> response = current_app.api_auth.requires_authentication(lambda: Response(status=200))()
<add> if response.status_code != 200:
<add> raise Unauthenticated()
<add> return function(*args, **kwargs)
<add>
<add> return cast(T, decorated)
<ide><path>tests/api_connexion/endpoints/test_config_endpoint.py
<ide> from mock import patch
<ide>
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<add>from tests.test_utils.config import conf_vars
<ide>
<ide> MOCK_CONF = {
<ide> 'core': {
<ide> class TestGetConfig:
<ide> @classmethod
<ide> def setup_class(cls) -> None:
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<ide> cls.client = None
<ide>
<add> @classmethod
<add> def teardown_class(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<add>
<ide> def setup_method(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide>
<ide> def test_should_response_200_text_plain(self, mock_as_dict):
<del> response = self.client.get("/api/v1/config", headers={'Accept': 'text/plain'})
<add> response = self.client.get(
<add> "/api/v1/config", headers={'Accept': 'text/plain'}, environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> expected = textwrap.dedent("""\
<ide> [core]
<ide> def test_should_response_200_text_plain(self, mock_as_dict):
<ide> assert expected == response.data.decode()
<ide>
<ide> def test_should_response_200_application_json(self, mock_as_dict):
<del> response = self.client.get("/api/v1/config", headers={'Accept': 'application/json'})
<add> response = self.client.get(
<add> "/api/v1/config",
<add> headers={'Accept': 'application/json'},
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> expected = {
<ide> 'sections': [
<ide> def test_should_response_200_application_json(self, mock_as_dict):
<ide> assert expected == response.json
<ide>
<ide> def test_should_response_406(self, mock_as_dict):
<del> response = self.client.get("/api/v1/config", headers={'Accept': 'application/octet-stream'})
<add> response = self.client.get(
<add> "/api/v1/config",
<add> headers={'Accept': 'application/octet-stream'},
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 406
<add>
<add> def test_should_raises_401_unauthenticated(self, mock_as_dict):
<add> response = self.client.get(
<add> "/api/v1/config",
<add> headers={'Accept': 'application/json'}
<add> )
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_connection_endpoint.py
<ide> from airflow.models import Connection
<ide> from airflow.utils.session import provide_session
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_connections
<ide>
<ide> class TestConnectionEndpoint(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> def test_delete_should_response_204(self, session):
<ide> session.commit()
<ide> conn = session.query(Connection).all()
<ide> assert len(conn) == 1
<del> response = self.client.delete("/api/v1/connections/test-connection")
<add> response = self.client.delete(
<add> "/api/v1/connections/test-connection", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 204
<ide> connection = session.query(Connection).all()
<ide> assert len(connection) == 0
<ide>
<ide> def test_delete_should_response_404(self):
<del> response = self.client.delete("/api/v1/connections/test-connection")
<add> response = self.client.delete(
<add> "/api/v1/connections/test-connection", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_delete_should_response_404(self):
<ide> }
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.delete("/api/v1/connections/test-connection")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetConnection(TestConnectionEndpoint):
<ide>
<ide> def test_should_response_200(self, session):
<ide> session.commit()
<ide> result = session.query(Connection).all()
<ide> assert len(result) == 1
<del> response = self.client.get("/api/v1/connections/test-connection-id")
<add> response = self.client.get(
<add> "/api/v1/connections/test-connection-id", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_should_response_200(self, session):
<ide> )
<ide>
<ide> def test_should_response_404(self):
<del> response = self.client.get("/api/v1/connections/invalid-connection")
<add> response = self.client.get(
<add> "/api/v1/connections/invalid-connection", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide> self.assertEqual(
<ide> {
<ide> def test_should_response_404(self):
<ide> response.json
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get("/api/v1/connections/test-connection-id")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetConnections(TestConnectionEndpoint):
<ide>
<ide> def test_should_response_200(self, session):
<ide> session.commit()
<ide> result = session.query(Connection).all()
<ide> assert len(result) == 2
<del> response = self.client.get("/api/v1/connections")
<add> response = self.client.get(
<add> "/api/v1/connections", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_should_response_200(self, session):
<ide> }
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get("/api/v1/connections")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetConnectionsPagination(TestConnectionEndpoint):
<ide>
<ide> def test_handle_limit_offset(self, url, expected_conn_ids, session):
<ide> connections = self._create_connections(10)
<ide> session.add_all(connections)
<ide> session.commit()
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(response.json["total_entries"], 10)
<ide> conn_ids = [conn["connection_id"] for conn in response.json["connections"] if conn]
<ide> def test_should_respect_page_size_limit_default(self, session):
<ide> session.add_all(connection_models)
<ide> session.commit()
<ide>
<del> response = self.client.get("/api/v1/connections")
<add> response = self.client.get("/api/v1/connections", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide>
<ide> self.assertEqual(response.json["total_entries"], 200)
<ide> def test_limit_of_zero_should_return_default(self, session):
<ide> session.add_all(connection_models)
<ide> session.commit()
<ide>
<del> response = self.client.get("/api/v1/connections?limit=0")
<add> response = self.client.get("/api/v1/connections?limit=0", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide>
<ide> self.assertEqual(response.json["total_entries"], 200)
<ide> def test_should_return_conf_max_if_req_max_above_conf(self, session):
<ide> session.add_all(connection_models)
<ide> session.commit()
<ide>
<del> response = self.client.get("/api/v1/connections?limit=180")
<add> response = self.client.get("/api/v1/connections?limit=180", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['connections']), 150)
<ide>
<ide> class TestPatchConnection(TestConnectionEndpoint):
<ide> def test_patch_should_response_200(self, payload, session):
<ide> self._create_connection(session)
<ide>
<del> response = self.client.patch("/api/v1/connections/test-connection-id",
<del> json=payload)
<add> response = self.client.patch(
<add> "/api/v1/connections/test-connection-id",
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<ide> @provide_session
<ide> def test_patch_should_response_200_with_update_mask(self, session):
<ide> }
<ide> response = self.client.patch(
<ide> "/api/v1/connections/test-connection-id?update_mask=port,login",
<del> json=payload
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 200
<ide> connection = session.query(Connection).filter_by(conn_id=test_connection).first()
<ide> def test_patch_should_response_400_for_invalid_fields_in_update_mask(
<ide> self._create_connection(session)
<ide> response = self.client.patch(
<ide> f"/api/v1/connections/test-connection-id?{update_mask}",
<del> json=payload
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 400
<ide> self.assertEqual(response.json['title'], error_message)
<ide> def test_patch_should_response_400_for_invalid_update(
<ide> self._create_connection(session)
<ide> response = self.client.patch(
<ide> "/api/v1/connections/test-connection-id",
<del> json=payload
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 400
<ide> self.assertIn(error_message, response.json['detail'])
<ide> def test_patch_should_response_404_not_found(self):
<ide> }
<ide> response = self.client.patch(
<ide> "/api/v1/connections/test-connection-id",
<del> json=payload
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 404
<ide> self.assertEqual(
<ide> def test_patch_should_response_404_not_found(self):
<ide> response.json
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> self._create_connection(session)
<add>
<add> response = self.client.patch(
<add> "/api/v1/connections/test-connection-id",
<add> json={
<add> "connection_id": "test-connection-id",
<add> "conn_type": 'test_type',
<add> "extra": "{'key': 'var'}"
<add> }
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestPostConnection(TestConnectionEndpoint):
<ide>
<ide> def test_post_should_response_200(self, session):
<ide> "connection_id": "test-connection-id",
<ide> "conn_type": 'test_type'
<ide> }
<del> response = self.client.post("/api/v1/connections", json=payload)
<add> response = self.client.post(
<add> "/api/v1/connections",
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> connection = session.query(Connection).all()
<ide> assert len(connection) == 1
<ide> def test_post_should_response_400_for_invalid_payload(self):
<ide> payload = {
<ide> "connection_id": "test-connection-id",
<ide> } # conn_type missing
<del> response = self.client.post("/api/v1/connections", json=payload)
<add> response = self.client.post(
<add> "/api/v1/connections",
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 400
<ide> self.assertEqual(response.json,
<ide> {'detail': "{'conn_type': ['Missing data for required field.']}",
<ide> def test_post_should_response_409_already_exist(self):
<ide> "connection_id": "test-connection-id",
<ide> "conn_type": 'test_type'
<ide> }
<del> response = self.client.post("/api/v1/connections", json=payload)
<add> response = self.client.post(
<add> "/api/v1/connections", json=payload, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> # Another request
<del> response = self.client.post("/api/v1/connections", json=payload)
<add> response = self.client.post(
<add> "/api/v1/connections", json=payload, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 409
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_post_should_response_409_already_exist(self):
<ide> 'type': 'about:blank'
<ide> }
<ide> )
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.post(
<add> "/api/v1/connections",
<add> json={
<add> "connection_id": "test-connection-id",
<add> "conn_type": 'test_type'
<add> }
<add> )
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_dag_endpoint.py
<ide> from airflow.operators.dummy_operator import DummyOperator
<ide> from airflow.utils.session import provide_session
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<add>from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_dags, clear_db_runs, clear_db_serialized_dags
<ide>
<ide>
<ide> def clean_db():
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<ide>
<ide> with DAG(cls.dag_id, start_date=datetime(2020, 6, 15), doc_md="details") as dag:
<ide> DummyOperator(task_id=cls.task_id)
<ide> def setUpClass(cls) -> None:
<ide> dag_bag.dags = {dag.dag_id: dag}
<ide> cls.app.dag_bag = dag_bag # type:ignore
<ide>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<add>
<ide> def setUp(self) -> None:
<ide> self.clean_db()
<ide> self.client = self.app.test_client() # type:ignore
<ide> def _create_dag_models(self, count, session=None):
<ide> class TestGetDag(TestDagEndpoint):
<ide> def test_should_response_200(self):
<ide> self._create_dag_models(1)
<del> response = self.client.get("/api/v1/dags/TEST_DAG_1")
<add> response = self.client.get("/api/v1/dags/TEST_DAG_1", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide>
<ide> current_response = response.json
<ide> def test_should_response_200(self):
<ide> }, current_response)
<ide>
<ide> def test_should_response_404(self):
<del> response = self.client.get("/api/v1/dags/INVALID_DAG")
<add> response = self.client.get("/api/v1/dags/INVALID_DAG", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 404
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> self._create_dag_models(1)
<add>
<add> response = self.client.get("/api/v1/dags/TEST_DAG_1")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetDagDetails(TestDagEndpoint):
<ide> def test_should_response_200(self):
<del> response = self.client.get(f"/api/v1/dags/{self.dag_id}/details")
<add> response = self.client.get(
<add> f"/api/v1/dags/{self.dag_id}/details", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> expected = {
<ide> 'catchup': True,
<ide> def test_should_response_200_serialized(self):
<ide> 'tags': None,
<ide> 'timezone': "Timezone('UTC')"
<ide> }
<del> response = client.get(f"/api/v1/dags/{self.dag_id}/details")
<add> response = client.get(
<add> f"/api/v1/dags/{self.dag_id}/details", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == expected
<ide>
<add> response = self.client.get(
<add> f"/api/v1/dags/{self.dag_id}/details", environ_overrides={'REMOTE_USER': "test"}
<add> )
<add> assert response.status_code == 200
<add> expected = {
<add> 'catchup': True,
<add> 'concurrency': 16,
<add> 'dag_id': 'test_dag',
<add> 'dag_run_timeout': None,
<add> 'default_view': 'tree',
<add> 'description': None,
<add> 'doc_md': 'details',
<add> 'fileloc': __file__,
<add> 'is_paused': None,
<add> 'is_subdag': False,
<add> 'orientation': 'LR',
<add> 'owners': [],
<add> 'schedule_interval': {
<add> '__type': 'TimeDelta',
<add> 'days': 1,
<add> 'microseconds': 0,
<add> 'seconds': 0
<add> },
<add> 'start_date': '2020-06-15T00:00:00+00:00',
<add> 'tags': None,
<add> 'timezone': "Timezone('UTC')"
<add> }
<add> assert response.json == expected
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get(f"/api/v1/dags/{self.dag_id}/details")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetDags(TestDagEndpoint):
<ide>
<ide> def test_should_response_200(self):
<ide> self._create_dag_models(2)
<ide>
<del> response = self.client.get("api/v1/dags")
<add> response = self.client.get("api/v1/dags", environ_overrides={'REMOTE_USER': "test"})
<ide>
<ide> assert response.status_code == 200
<ide>
<ide> def test_should_response_200(self):
<ide> def test_should_response_200_and_handle_pagination(self, url, expected_dag_ids):
<ide> self._create_dag_models(10)
<ide>
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide>
<ide> assert response.status_code == 200
<ide>
<ide> def test_should_response_200_and_handle_pagination(self, url, expected_dag_ids):
<ide> def test_should_response_200_default_limit(self):
<ide> self._create_dag_models(101)
<ide>
<del> response = self.client.get("api/v1/dags")
<add> response = self.client.get("api/v1/dags", environ_overrides={'REMOTE_USER': "test"})
<ide>
<ide> assert response.status_code == 200
<ide>
<ide> self.assertEqual(100, len(response.json['dags']))
<ide> self.assertEqual(101, response.json['total_entries'])
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get("api/v1/dags")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestPatchDag(TestDagEndpoint):
<ide> @pytest.mark.skip(reason="Not implemented yet")
<ide> def test_should_response_200(self):
<del> response = self.client.patch("/api/v1/dags/1")
<add> response = self.client.patch("/api/v1/dags/1", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<add>
<add> @pytest.mark.skip(reason="Not implemented yet")
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.patch("/api/v1/dags/1")
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_dag_run_endpoint.py
<ide> from airflow.utils.session import create_session, provide_session
<ide> from airflow.utils.types import DagRunType
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_dags, clear_db_runs
<ide>
<ide> class TestDagRunEndpoint(unittest.TestCase):
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<ide>
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> def test_should_response_204(self, session):
<ide> session.add_all(self._create_test_dag_run())
<ide> session.commit()
<ide> response = self.client.delete(
<del> "api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID_1"
<add> "api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID_1",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 204)
<ide> # Check if the Dag Run is deleted from the database
<del> response = self.client.get("api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID_1")
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID_1", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> self.assertEqual(response.status_code, 404)
<ide>
<ide> def test_should_response_404(self):
<ide> response = self.client.delete(
<del> "api/v1/dags/INVALID_DAG_RUN/dagRuns/INVALID_DAG_RUN"
<add> "api/v1/dags/INVALID_DAG_RUN/dagRuns/INVALID_DAG_RUN", environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 404)
<ide> self.assertEqual(
<ide> def test_should_response_404(self):
<ide> },
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> session.add_all(self._create_test_dag_run())
<add> session.commit()
<add>
<add> response = self.client.delete(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID_1",
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetDagRun(TestDagRunEndpoint):
<ide> @provide_session
<ide> def test_should_response_200(self, session):
<ide> session.commit()
<ide> result = session.query(DagRun).all()
<ide> assert len(result) == 1
<del> response = self.client.get("api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID")
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID",
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> expected_response = {
<ide> 'dag_id': 'TEST_DAG_ID',
<ide> def test_should_response_200(self, session):
<ide> assert response.json == expected_response
<ide>
<ide> def test_should_response_404(self):
<del> response = self.client.get("api/v1/dags/invalid-id/dagRuns/invalid-id")
<add> response = self.client.get(
<add> "api/v1/dags/invalid-id/dagRuns/invalid-id", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide> expected_resp = {
<ide> 'detail': None,
<ide> def test_should_response_404(self):
<ide> }
<ide> assert expected_resp == response.json
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> dagrun_model = DagRun(
<add> dag_id="TEST_DAG_ID",
<add> run_id="TEST_DAG_RUN_ID",
<add> run_type=DagRunType.MANUAL.value,
<add> execution_date=timezone.parse(self.default_time),
<add> start_date=timezone.parse(self.default_time),
<add> external_trigger=True,
<add> )
<add> session.add(dagrun_model)
<add> session.commit()
<add>
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID"
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetDagRuns(TestDagRunEndpoint):
<ide> @provide_session
<ide> def test_should_response_200(self, session):
<ide> self._create_test_dag_run()
<ide> result = session.query(DagRun).all()
<ide> assert len(result) == 2
<del> response = self.client.get("api/v1/dags/TEST_DAG_ID/dagRuns")
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == {
<ide> "dag_runs": [
<ide> def test_should_return_all_with_tilde_as_dag_id(self, session):
<ide> "TEST_DAG_ID_3", "TEST_DAG_ID_4"]
<ide> result = session.query(DagRun).all()
<ide> assert len(result) == 4
<del> response = self.client.get("api/v1/dags/~/dagRuns")
<add> response = self.client.get("api/v1/dags/~/dagRuns", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> dag_run_ids = [dag_run["dag_id"] for dag_run in response.json["dag_runs"]]
<ide> assert dag_run_ids == expected_dag_run_ids
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> self._create_test_dag_run()
<add>
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns"
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetDagRunsPagination(TestDagRunEndpoint):
<ide> @parameterized.expand(
<ide> class TestGetDagRunsPagination(TestDagRunEndpoint):
<ide> )
<ide> def test_handle_limit_and_offset(self, url, expected_dag_run_ids):
<ide> self._create_dag_runs(10)
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide>
<ide> assert response.json["total_entries"] == 10
<ide> def test_handle_limit_and_offset(self, url, expected_dag_run_ids):
<ide>
<ide> def test_should_respect_page_size_limit(self):
<ide> self._create_dag_runs(200)
<del> response = self.client.get("api/v1/dags/TEST_DAG_ID/dagRuns") # default is 100
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<ide> assert response.json["total_entries"] == 200
<ide> def test_should_respect_page_size_limit(self):
<ide> @conf_vars({("api", "maximum_page_limit"): "150"})
<ide> def test_should_return_conf_max_if_req_max_above_conf(self):
<ide> self._create_dag_runs(200)
<del> response = self.client.get("api/v1/dags/TEST_DAG_ID/dagRuns?limit=180")
<add> response = self.client.get(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns?limit=180", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json["dag_runs"]), 150)
<ide>
<ide> def test_date_filters_gte_and_lte(self, url, expected_dag_run_ids, session):
<ide> session.add_all(dagrun_models)
<ide> session.commit()
<ide>
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> assert response.json["total_entries"] == 10
<ide> dag_run_ids = [dag_run["dag_run_id"] for dag_run in response.json["dag_runs"]]
<ide> class TestGetDagRunsEndDateFilters(TestDagRunEndpoint):
<ide> )
<ide> def test_end_date_gte_lte(self, url, expected_dag_run_ids):
<ide> self._create_test_dag_run('success') # state==success, then end date is today
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> assert response.json["total_entries"] == 2
<ide> dag_run_ids = [
<ide> def test_end_date_gte_lte(self, url, expected_dag_run_ids):
<ide> class TestGetDagRunBatch(TestDagRunEndpoint):
<ide> def test_should_respond_200(self):
<ide> self._create_test_dag_run()
<del> payload = {
<del> "dag_ids": ["TEST_DAG_ID"]
<del> }
<del> response = self.client.post("api/v1/dags/~/dagRuns/list", json=payload)
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list",
<add> json={
<add> "dag_ids": ["TEST_DAG_ID"]
<add> },
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == {
<ide> "dag_runs": [
<ide> def test_should_respond_200(self):
<ide> )
<ide> def test_payload_validation(self, payload, error):
<ide> self._create_test_dag_run()
<del> response = self.client.post("api/v1/dags/~/dagRuns/list", json=payload)
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list", json=payload, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 400
<ide> assert error == response.json.get("detail")
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> self._create_test_dag_run()
<add>
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list",
<add> json={
<add> "dag_ids": ["TEST_DAG_ID"]
<add> }
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetDagRunBatchPagination(TestDagRunEndpoint):
<ide> @parameterized.expand(
<ide> class TestGetDagRunBatchPagination(TestDagRunEndpoint):
<ide> )
<ide> def test_handle_limit_and_offset(self, payload, expected_dag_run_ids):
<ide> self._create_dag_runs(10)
<del> response = self.client.post("api/v1/dags/~/dagRuns/list", json=payload)
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list", json=payload, environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<ide> assert response.json["total_entries"] == 10
<ide> def test_handle_limit_and_offset(self, payload, expected_dag_run_ids):
<ide>
<ide> def test_should_respect_page_size_limit(self):
<ide> self._create_dag_runs(200)
<del> response = self.client.post("api/v1/dags/~/dagRuns/list", json={}) # default is 100
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list", json={}, environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<ide> assert response.json["total_entries"] == 200
<ide> def test_date_filters_gte_and_lte(self, payload, expected_dag_run_ids, session):
<ide> session.add_all(dag_runs)
<ide> session.commit()
<ide>
<del> response = self.client.post("api/v1/dags/~/dagRuns/list", json=payload)
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list", json=payload, environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json["total_entries"] == 10
<ide> dag_run_ids = [dag_run["dag_run_id"] for dag_run in response.json["dag_runs"]]
<ide> def _create_dag_runs(self):
<ide> )
<ide> def test_end_date_gte_lte(self, payload, expected_dag_run_ids):
<ide> self._create_test_dag_run('success') # state==success, then end date is today
<del> response = self.client.post("api/v1/dags/~/dagRuns/list", json=payload)
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list",
<add> json=payload,
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json["total_entries"] == 2
<ide> dag_run_ids = [dag_run["dag_run_id"] for dag_run in response.json["dag_runs"] if dag_run]
<ide> def test_should_response_200(self, name, request_json, session):
<ide> session.add(dag_instance)
<ide> session.commit()
<ide> response = self.client.post(
<del> "api/v1/dags/TEST_DAG_ID/dagRuns", json=request_json
<add> "api/v1/dags/TEST_DAG_ID/dagRuns", json=request_json, environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 200)
<ide> self.assertEqual(
<ide> def test_response_404(self):
<ide> response = self.client.post(
<ide> "api/v1/dags/TEST_DAG_ID/dagRuns",
<ide> json={"dag_run_id": "TEST_DAG_RUN", "execution_date": self.default_time},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 404)
<ide> self.assertEqual(
<ide> def test_response_400(self, name, url, request_json, expected_response, session)
<ide> dag_instance = DagModel(dag_id="TEST_DAG_ID")
<ide> session.add(dag_instance)
<ide> session.commit()
<del> response = self.client.post(url, json=request_json)
<add> response = self.client.post(url, json=request_json, environ_overrides={'REMOTE_USER': "test"})
<ide> self.assertEqual(response.status_code, 400, response.data)
<ide> self.assertEqual(expected_response, response.json)
<ide>
<ide> def test_response_409(self, session):
<ide> "dag_run_id": "TEST_DAG_RUN_ID_1",
<ide> "execution_date": self.default_time,
<ide> },
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 409, response.data)
<ide> self.assertEqual(
<ide> def test_response_409(self, session):
<ide> "type": "about:blank",
<ide> },
<ide> )
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.post(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns",
<add> json={
<add> "dag_run_id": "TEST_DAG_RUN_ID_1",
<add> "execution_date": self.default_time,
<add> },
<add> )
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_dag_source_endpoint.py
<ide> from airflow.configuration import conf
<ide> from airflow.models import DagBag
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<add>from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_dag_code, clear_db_dags, clear_db_serialized_dags
<ide>
<ide> ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))
<ide> class TestGetSource(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> def test_should_response_200_text(self, store_dag_code):
<ide> dag_docstring = self._get_dag_file_docstring(first_dag.fileloc)
<ide>
<ide> url = f"/api/v1/dagSources/{serializer.dumps(first_dag.fileloc)}"
<del> response = self.client.get(url, headers={
<del> "Accept": "text/plain"
<del> })
<add> response = self.client.get(
<add> url,
<add> headers={"Accept": "text/plain"},
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide>
<ide> self.assertEqual(200, response.status_code)
<ide> self.assertIn(dag_docstring, response.data.decode())
<ide> def test_should_response_200_json(self, store_dag_code):
<ide> dag_docstring = self._get_dag_file_docstring(first_dag.fileloc)
<ide>
<ide> url = f"/api/v1/dagSources/{serializer.dumps(first_dag.fileloc)}"
<del> response = self.client.get(url, headers={
<del> "Accept": 'application/json'
<del> })
<add> response = self.client.get(
<add> url,
<add> headers={"Accept": 'application/json'},
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide>
<ide> self.assertEqual(200, response.status_code)
<ide> self.assertIn(
<ide> def test_should_response_406(self, store_dag_code):
<ide> first_dag: DAG = next(iter(dagbag.dags.values()))
<ide>
<ide> url = f"/api/v1/dagSources/{serializer.dumps(first_dag.fileloc)}"
<del> response = self.client.get(url, headers={
<del> "Accept": 'image/webp'
<del> })
<add> response = self.client.get(
<add> url,
<add> headers={"Accept": 'image/webp'},
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide>
<ide> self.assertEqual(406, response.status_code)
<ide>
<ide> def test_should_response_404(self, store_dag_code):
<ide> ), mock.patch("airflow.models.dagcode.STORE_DAG_CODE", store_dag_code):
<ide> wrong_fileloc = "abcd1234"
<ide> url = f"/api/v1/dagSources/{wrong_fileloc}"
<del> response = self.client.get(url, headers={
<del> "Accept": 'application/json'
<del> })
<add> response = self.client.get(
<add> url,
<add> headers={"Accept": 'application/json'},
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide>
<ide> self.assertEqual(404, response.status_code)
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> serializer = URLSafeSerializer(conf.get('webserver', 'SECRET_KEY'))
<add> dagbag = DagBag(dag_folder=EXAMPLE_DAG_FILE)
<add> dagbag.sync_to_db()
<add> first_dag: DAG = next(iter(dagbag.dags.values()))
<add>
<add> response = self.client.get(
<add> f"/api/v1/dagSources/{serializer.dumps(first_dag.fileloc)}",
<add> headers={"Accept": "text/plain"},
<add> )
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_event_log_endpoint.py
<ide> from airflow.utils import timezone
<ide> from airflow.utils.session import provide_session
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_logs
<ide>
<ide> class TestEventLogEndpoint(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> def test_should_response_200(self, session):
<ide> session.add(log_model)
<ide> session.commit()
<ide> event_log_id = log_model.id
<del> response = self.client.get(f"/api/v1/eventLogs/{event_log_id}")
<add> response = self.client.get(
<add> f"/api/v1/eventLogs/{event_log_id}", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_should_response_200(self, session):
<ide> )
<ide>
<ide> def test_should_response_404(self):
<del> response = self.client.get("/api/v1/eventLogs/1")
<add> response = self.client.get(
<add> "/api/v1/eventLogs/1", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide> self.assertEqual(
<ide> {'detail': None, 'status': 404, 'title': 'Event Log not found', 'type': 'about:blank'},
<ide> response.json
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> log_model = Log(
<add> event='TEST_EVENT',
<add> task_instance=self._create_task_instance(),
<add> )
<add> log_model.dttm = timezone.parse(self.default_time)
<add> session.add(log_model)
<add> session.commit()
<add> event_log_id = log_model.id
<add>
<add> response = self.client.get(f"/api/v1/eventLogs/{event_log_id}")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetEventLogs(TestEventLogEndpoint):
<ide>
<ide> def test_should_response_200(self, session):
<ide> log_model_2.dttm = timezone.parse(self.default_time_2)
<ide> session.add_all([log_model_1, log_model_2])
<ide> session.commit()
<del> response = self.client.get("/api/v1/eventLogs")
<add> response = self.client.get("/api/v1/eventLogs", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_should_response_200(self, session):
<ide> }
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> log_model_1 = Log(
<add> event='TEST_EVENT_1',
<add> task_instance=self._create_task_instance(),
<add> )
<add> log_model_2 = Log(
<add> event='TEST_EVENT_2',
<add> task_instance=self._create_task_instance(),
<add> )
<add> log_model_1.dttm = timezone.parse(self.default_time)
<add> log_model_2.dttm = timezone.parse(self.default_time_2)
<add> session.add_all([log_model_1, log_model_2])
<add> session.commit()
<add>
<add> response = self.client.get("/api/v1/eventLogs")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetEventLogPagination(TestEventLogEndpoint):
<ide> @parameterized.expand(
<ide> def test_handle_limit_and_offset(self, url, expected_events, session):
<ide> session.add_all(log_models)
<ide> session.commit()
<ide>
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide>
<ide> self.assertEqual(response.json["total_entries"], 10)
<ide> def test_should_respect_page_size_limit_default(self, session):
<ide> session.add_all(log_models)
<ide> session.commit()
<ide>
<del> response = self.client.get("/api/v1/eventLogs") # default should be 100
<add> response = self.client.get("/api/v1/eventLogs", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide>
<ide> self.assertEqual(response.json["total_entries"], 200)
<ide> def test_should_return_conf_max_if_req_max_above_conf(self, session):
<ide> session.add_all(log_models)
<ide> session.commit()
<ide>
<del> response = self.client.get("/api/v1/eventLogs?limit=180")
<add> response = self.client.get("/api/v1/eventLogs?limit=180", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['event_logs']), 150)
<ide>
<ide><path>tests/api_connexion/endpoints/test_extra_link_endpoint.py
<ide> from airflow.utils.timezone import datetime
<ide> from airflow.utils.types import DagRunType
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import create_user, delete_user
<add>from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_runs, clear_db_xcom
<ide> from tests.test_utils.mock_plugins import mock_plugin_manager
<ide>
<ide> class TestGetExtraLinks(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> with mock.patch.dict("os.environ", SKIP_DAGS_PARSING="True"):
<add> with mock.patch.dict("os.environ", SKIP_DAGS_PARSING="True"), conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<ide> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> @provide_session
<ide> def setUp(self, session) -> None:
<ide> def _create_dag():
<ide> )
<ide> def test_should_response_404(self, name, url, expected_title, expected_detail):
<ide> del name
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide>
<ide> self.assertEqual(404, response.status_code)
<ide> self.assertEqual(
<ide> def test_should_response_200(self):
<ide> dag_id=self.dag.dag_id,
<ide> )
<ide> response = self.client.get(
<del> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links"
<add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide>
<ide> self.assertEqual(200, response.status_code, response.data)
<ide> def test_should_response_200(self):
<ide> @mock_plugin_manager(plugins=[])
<ide> def test_should_response_200_missing_xcom(self):
<ide> response = self.client.get(
<del> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links"
<add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide>
<ide> self.assertEqual(200, response.status_code, response.data)
<ide> def test_should_response_200_multiple_links(self):
<ide> dag_id=self.dag.dag_id,
<ide> )
<ide> response = self.client.get(
<del> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_MULTIPLE_QUERY/links"
<add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_MULTIPLE_QUERY/links",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide>
<ide> self.assertEqual(200, response.status_code, response.data)
<ide> def test_should_response_200_multiple_links(self):
<ide> @mock_plugin_manager(plugins=[])
<ide> def test_should_response_200_multiple_links_missing_xcom(self):
<ide> response = self.client.get(
<del> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_MULTIPLE_QUERY/links"
<add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_MULTIPLE_QUERY/links",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide>
<ide> self.assertEqual(200, response.status_code, response.data)
<ide> class AirflowTestPlugin(AirflowPlugin):
<ide>
<ide> with mock_plugin_manager(plugins=[AirflowTestPlugin]):
<ide> response = self.client.get(
<del> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links"
<add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide>
<ide> self.assertEqual(200, response.status_code, response.data)
<ide><path>tests/api_connexion/endpoints/test_import_error_endpoint.py
<ide> from airflow.utils import timezone
<ide> from airflow.utils.session import provide_session
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_import_errors
<ide>
<ide> class TestBaseImportError(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> super().setUp()
<ide> def test_response_200(self, session):
<ide> session.add(import_error)
<ide> session.commit()
<ide>
<del> response = self.client.get(f"/api/v1/importErrors/{import_error.id}")
<add> response = self.client.get(
<add> f"/api/v1/importErrors/{import_error.id}", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide>
<ide> assert response.status_code == 200
<ide> response_data = response.json
<ide> def test_response_200(self, session):
<ide> )
<ide>
<ide> def test_response_404(self):
<del> response = self.client.get("/api/v1/importErrors/2")
<add> response = self.client.get("/api/v1/importErrors/2", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 404
<ide> self.assertEqual(
<ide> {
<ide> def test_response_404(self):
<ide> response.json,
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> import_error = ImportError(
<add> filename="Lorem_ipsum.py",
<add> stacktrace="Lorem ipsum",
<add> timestamp=timezone.parse(self.timestamp, timezone="UTC"),
<add> )
<add> session.add(import_error)
<add> session.commit()
<add>
<add> response = self.client.get(
<add> f"/api/v1/importErrors/{import_error.id}"
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetImportErrorsEndpoint(TestBaseImportError):
<ide> @provide_session
<ide> def test_get_import_errors(self, session):
<ide> session.add_all(import_error)
<ide> session.commit()
<ide>
<del> response = self.client.get("/api/v1/importErrors")
<add> response = self.client.get("/api/v1/importErrors", environ_overrides={'REMOTE_USER': "test"})
<ide>
<ide> assert response.status_code == 200
<ide> response_data = response.json
<ide> def test_get_import_errors(self, session):
<ide> response_data,
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> import_error = [
<add> ImportError(
<add> filename="Lorem_ipsum.py",
<add> stacktrace="Lorem ipsum",
<add> timestamp=timezone.parse(self.timestamp, timezone="UTC"),
<add> )
<add> for _ in range(2)
<add> ]
<add> session.add_all(import_error)
<add> session.commit()
<add>
<add> response = self.client.get("/api/v1/importErrors")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetImportErrorsEndpointPagination(TestBaseImportError):
<ide> @parameterized.expand(
<ide> def test_limit_and_offset(self, url, expected_import_error_ids, session):
<ide> session.add_all(import_errors)
<ide> session.commit()
<ide>
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide>
<ide> assert response.status_code == 200
<ide> import_ids = [
<ide> def test_should_respect_page_size_limit_default(self, session):
<ide> ]
<ide> session.add_all(import_errors)
<ide> session.commit()
<del> response = self.client.get("/api/v1/importErrors")
<add> response = self.client.get("/api/v1/importErrors", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['import_errors']), 100)
<ide>
<ide> def test_should_return_conf_max_if_req_max_above_conf(self, session):
<ide> ]
<ide> session.add_all(import_errors)
<ide> session.commit()
<del> response = self.client.get("/api/v1/importErrors?limit=180")
<add> response = self.client.get(
<add> "/api/v1/importErrors?limit=180", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['import_errors']), 150)
<ide><path>tests/api_connexion/endpoints/test_log_endpoint.py
<ide> from airflow.utils.session import create_session, provide_session
<ide> from airflow.utils.types import DagRunType
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_runs
<ide>
<ide> class TestGetLog(unittest.TestCase):
<ide> def setUpClass(cls):
<ide> settings.configure_orm()
<ide> cls.session = settings.Session
<del> cls.app = app.create_app(testing=True)
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True)
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin")
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test")
<ide>
<ide> def setUp(self) -> None:
<ide> self.default_time = "2020-06-10T20:00:00+00:00"
<ide> def _configure_loggers(self):
<ide> handle.writelines(new_logging_file)
<ide> sys.path.append(self.settings_folder)
<ide>
<del> with conf_vars({('logging', 'logging_config_class'): 'airflow_local_settings.LOGGING_CONFIG'}):
<add> with conf_vars({
<add> ('logging', 'logging_config_class'): 'airflow_local_settings.LOGGING_CONFIG',
<add> ("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"
<add> }):
<ide> self.app = app.create_app(testing=True)
<ide> self.client = self.app.test_client()
<ide> settings.configure_logging()
<ide> def test_should_response_200_json(self, session):
<ide> key = self.app.config["SECRET_KEY"]
<ide> serializer = URLSafeSerializer(key)
<ide> token = serializer.dumps({"download_logs": False})
<del> headers = {'Accept': 'application/json'}
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<ide> f"taskInstances/{self.TASK_ID}/logs/1?token={token}",
<del> headers=headers
<add> headers={'Accept': 'application/json'},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> expected_filename = "{}/{}/{}/{}/1.log".format(
<ide> self.log_dir,
<ide> def test_should_response_200_text_plain(self, session):
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<ide> f"taskInstances/{self.TASK_ID}/logs/1?token={token}",
<del> headers={'Accept': 'text/plain'}
<add> headers={'Accept': 'text/plain'},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> expected_filename = "{}/{}/{}/{}/1.log".format(
<ide> self.log_dir,
<ide> def test_get_logs_response_with_ti_equal_to_none(self, session):
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<ide> f"taskInstances/Invalid-Task-ID/logs/1?token={token}",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 400)
<ide> self.assertEqual(response.json['detail'], "Task instance did not exist in the DB")
<ide> def test_get_logs_with_metadata_as_download_large_file(self, session):
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<ide> f"taskInstances/{self.TASK_ID}/logs/1?full_content=True",
<del> headers={"Accept": 'text/plain'}
<add> headers={"Accept": 'text/plain'},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide>
<ide> self.assertIn('1st line', response.data.decode('utf-8'))
<ide> def test_get_logs_for_handler_without_read_method(self, mock_log_reader):
<ide> key = self.app.config["SECRET_KEY"]
<ide> serializer = URLSafeSerializer(key)
<ide> token = serializer.dumps({"download_logs": False})
<del> headers = {'Content-Type': 'application/jso'} # check guessing
<add>
<add> # check guessing
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<ide> f"taskInstances/{self.TASK_ID}/logs/1?token={token}",
<del> headers=headers
<add> headers={'Content-Type': 'application/jso'},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(400, response.status_code)
<ide> self.assertIn(
<ide> def test_get_logs_for_handler_without_read_method(self, mock_log_reader):
<ide> def test_bad_signature_raises(self, session):
<ide> self._create_dagrun(session)
<ide> token = {"download_logs": False}
<del> headers = {'Accept': 'application/json'}
<add>
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<ide> f"taskInstances/{self.TASK_ID}/logs/1?token={token}",
<del> headers=headers
<add> headers={'Accept': 'application/json'},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_bad_signature_raises(self, session):
<ide> )
<ide>
<ide> def test_raises_404_for_invalid_dag_run_id(self):
<del> headers = {'Accept': 'application/json'}
<ide> response = self.client.get(
<ide> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN/" # invalid dagrun_id
<ide> f"taskInstances/{self.TASK_ID}/logs/1?",
<del> headers=headers
<add> headers={'Accept': 'application/json'},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(
<ide> response.json,
<ide> def test_raises_404_for_invalid_dag_run_id(self):
<ide> 'type': 'about:blank'
<ide> }
<ide> )
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> key = self.app.config["SECRET_KEY"]
<add> serializer = URLSafeSerializer(key)
<add> token = serializer.dumps({"download_logs": False})
<add>
<add> response = self.client.get(
<add> f"api/v1/dags/{self.DAG_ID}/dagRuns/TEST_DAG_RUN_ID/"
<add> f"taskInstances/{self.TASK_ID}/logs/1?token={token}",
<add> headers={'Accept': 'application/json'},
<add> )
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_pool_endpoint.py
<ide> from airflow.models.pool import Pool
<ide> from airflow.utils.session import provide_session
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_pools
<ide>
<ide> class TestBasePoolEndpoints(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> def test_response_200(self, session):
<ide> session.commit()
<ide> result = session.query(Pool).all()
<ide> assert len(result) == 2 # accounts for the default pool as well
<del> response = self.client.get("/api/v1/pools")
<add> response = self.client.get("/api/v1/pools", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> {
<ide> def test_response_200(self, session):
<ide> response.json,
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get("/api/v1/pools")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetPoolsPagination(TestBasePoolEndpoints):
<ide> @parameterized.expand(
<ide> def test_limit_and_offset(self, url, expected_pool_ids, session):
<ide> session.commit()
<ide> result = session.query(Pool).count()
<ide> self.assertEqual(result, 121) # accounts for default pool as well
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> pool_ids = [pool["name"] for pool in response.json["pools"]]
<ide> self.assertEqual(pool_ids, expected_pool_ids)
<ide> def test_should_respect_page_size_limit_default(self, session):
<ide> session.commit()
<ide> result = session.query(Pool).count()
<ide> self.assertEqual(result, 121)
<del> response = self.client.get("/api/v1/pools")
<add> response = self.client.get("/api/v1/pools", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['pools']), 100)
<ide>
<ide> def test_should_return_conf_max_if_req_max_above_conf(self, session):
<ide> session.commit()
<ide> result = session.query(Pool).count()
<ide> self.assertEqual(result, 200)
<del> response = self.client.get("/api/v1/pools?limit=180")
<add> response = self.client.get("/api/v1/pools?limit=180", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['pools']), 150)
<ide>
<ide> def test_response_200(self, session):
<ide> pool_model = Pool(pool="test_pool_a", slots=3)
<ide> session.add(pool_model)
<ide> session.commit()
<del> response = self.client.get("/api/v1/pools/test_pool_a")
<add> response = self.client.get(
<add> "/api/v1/pools/test_pool_a", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> {
<ide> def test_response_200(self, session):
<ide> )
<ide>
<ide> def test_response_404(self):
<del> response = self.client.get("/api/v1/pools/invalid_pool")
<add> response = self.client.get(
<add> "/api/v1/pools/invalid_pool", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide> self.assertEqual(
<ide> {
<ide> def test_response_404(self):
<ide> response.json,
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get("/api/v1/pools/default_pool")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestDeletePool(TestBasePoolEndpoints):
<ide> @provide_session
<ide> def test_response_204(self, session):
<ide> session.add(pool_instance)
<ide> session.commit()
<ide>
<del> response = self.client.delete(f"api/v1/pools/{pool_name}")
<add> response = self.client.delete(f"api/v1/pools/{pool_name}", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 204
<ide> # Check if the pool is deleted from the db
<del> response = self.client.get(f"api/v1/pools/{pool_name}")
<add> response = self.client.get(f"api/v1/pools/{pool_name}", environ_overrides={'REMOTE_USER': "test"})
<ide> self.assertEqual(response.status_code, 404)
<ide>
<ide> def test_response_404(self):
<del> response = self.client.delete("api/v1/pools/invalid_pool")
<add> response = self.client.delete("api/v1/pools/invalid_pool", environ_overrides={'REMOTE_USER': "test"})
<ide> self.assertEqual(response.status_code, 404)
<ide> self.assertEqual(
<ide> {
<ide> def test_response_404(self):
<ide> response.json,
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> pool_name = "test_pool"
<add> pool_instance = Pool(pool=pool_name, slots=3)
<add> session.add(pool_instance)
<add> session.commit()
<add>
<add> response = self.client.delete(f"api/v1/pools/{pool_name}")
<add>
<add> assert_401(response)
<add>
<add> # Should still exists
<add> response = self.client.get(
<add> f"/api/v1/pools/{pool_name}", environ_overrides={'REMOTE_USER': "test"}
<add> )
<add> assert response.status_code == 200
<add>
<ide>
<ide> class TestPostPool(TestBasePoolEndpoints):
<ide> def test_response_200(self):
<ide> response = self.client.post(
<del> "api/v1/pools", json={"name": "test_pool_a", "slots": 3}
<add> "api/v1/pools",
<add> json={"name": "test_pool_a", "slots": 3},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> def test_response_409(self, session):
<ide> session.add(pool_instance)
<ide> session.commit()
<ide> response = self.client.post(
<del> "api/v1/pools", json={"name": "test_pool_a", "slots": 3}
<add> "api/v1/pools",
<add> json={"name": "test_pool_a", "slots": 3},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 409
<ide> self.assertEqual(
<ide> def test_response_409(self, session):
<ide> )
<ide> def test_response_400(self, name, request_json, error_detail):
<ide> del name
<del> response = self.client.post("api/v1/pools", json=request_json)
<add> response = self.client.post(
<add> "api/v1/pools",
<add> json=request_json,
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 400
<ide> self.assertDictEqual(
<ide> {
<ide> def test_response_400(self, name, request_json, error_detail):
<ide> response.json,
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.post(
<add> "api/v1/pools",
<add> json={"name": "test_pool_a", "slots": 3}
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestPatchPool(TestBasePoolEndpoints):
<ide> @provide_session
<ide> def test_response_200(self, session):
<ide> session.add(pool)
<ide> session.commit()
<ide> response = self.client.patch(
<del> "api/v1/pools/test_pool", json={"name": "test_pool_a", "slots": 3}
<add> "api/v1/pools/test_pool",
<add> json={"name": "test_pool_a", "slots": 3},
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(response.status_code, 200)
<ide> self.assertEqual(
<ide> def test_response_400(self, error_detail, request_json, session):
<ide> pool = Pool(pool="test_pool", slots=2)
<ide> session.add(pool)
<ide> session.commit()
<del> response = self.client.patch("api/v1/pools/test_pool", json=request_json)
<add> response = self.client.patch(
<add> "api/v1/pools/test_pool", json=request_json, environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 400
<ide> self.assertEqual(
<ide> {
<ide> def test_response_400(self, error_detail, request_json, session):
<ide> response.json,
<ide> )
<ide>
<add> @provide_session
<add> def test_should_raises_401_unauthenticated(self, session):
<add> pool = Pool(pool="test_pool", slots=2)
<add> session.add(pool)
<add> session.commit()
<add>
<add> response = self.client.patch(
<add> "api/v1/pools/test_pool", json={"name": "test_pool_a", "slots": 3},
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestModifyDefaultPool(TestBasePoolEndpoints):
<ide> def test_delete_400(self):
<del> response = self.client.delete("api/v1/pools/default_pool")
<add> response = self.client.delete("api/v1/pools/default_pool", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 400
<ide> self.assertEqual(
<ide> {
<ide> def test_delete_400(self):
<ide> )
<ide> def test_patch(self, name, status_code, url, json, expected_response):
<ide> del name
<del> response = self.client.patch(url, json=json)
<add> response = self.client.patch(url, json=json, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == status_code
<ide> self.assertEqual(response.json, expected_response)
<ide>
<ide> def test_response_200(
<ide> pool = Pool(pool="test_pool", slots=3)
<ide> session.add(pool)
<ide> session.commit()
<del> response = self.client.patch(url, json=patch_json)
<add> response = self.client.patch(url, json=patch_json, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(
<ide> {
<ide> def test_response_400(self, name, error_detail, url, patch_json, session):
<ide> pool = Pool(pool="test_pool", slots=3)
<ide> session.add(pool)
<ide> session.commit()
<del> response = self.client.patch(url, json=patch_json)
<add> response = self.client.patch(url, json=patch_json, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 400
<ide> self.assertEqual
<ide> (
<ide><path>tests/api_connexion/endpoints/test_task_endpoint.py
<ide> from airflow.models.serialized_dag import SerializedDagModel
<ide> from airflow.operators.dummy_operator import DummyOperator
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_dags, clear_db_runs, clear_db_serialized_dags
<ide>
<ide> def clean_db():
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<ide>
<ide> with DAG(cls.dag_id, start_date=datetime(2020, 6, 15), doc_md="details") as dag:
<ide> DummyOperator(task_id=cls.task_id)
<ide> def setUpClass(cls) -> None:
<ide> dag_bag.dags = {dag.dag_id: dag}
<ide> cls.app.dag_bag = dag_bag # type:ignore
<ide>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<add>
<ide> def setUp(self) -> None:
<ide> self.clean_db()
<ide> self.client = self.app.test_client() # type:ignore
<ide> def test_should_response_200(self):
<ide> "wait_for_downstream": False,
<ide> "weight_rule": "downstream",
<ide> }
<del> response = self.client.get(f"/api/v1/dags/{self.dag_id}/tasks/{self.task_id}")
<add> response = self.client.get(
<add> f"/api/v1/dags/{self.dag_id}/tasks/{self.task_id}", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == expected
<ide>
<ide> def test_should_response_200_serialized(self):
<ide> "wait_for_downstream": False,
<ide> "weight_rule": "downstream",
<ide> }
<del> response = client.get(f"/api/v1/dags/{self.dag_id}/tasks/{self.task_id}")
<add> response = client.get(
<add> f"/api/v1/dags/{self.dag_id}/tasks/{self.task_id}", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == expected
<ide>
<ide> def test_should_response_404(self):
<ide> task_id = "xxxx_not_existing"
<del> response = self.client.get(f"/api/v1/dags/{self.dag_id}/tasks/{task_id}")
<add> response = self.client.get(
<add> f"/api/v1/dags/{self.dag_id}/tasks/{task_id}", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get(f"/api/v1/dags/{self.dag_id}/tasks/{self.task_id}")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetTasks(TestTaskEndpoint):
<ide> def test_should_response_200(self):
<ide> def test_should_response_200(self):
<ide> ],
<ide> "total_entries": 1,
<ide> }
<del> response = self.client.get(f"/api/v1/dags/{self.dag_id}/tasks")
<add> response = self.client.get(
<add> f"/api/v1/dags/{self.dag_id}/tasks", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == expected
<ide>
<ide> def test_should_response_404(self):
<ide> dag_id = "xxxx_not_existing"
<del> response = self.client.get(f"/api/v1/dags/{dag_id}/tasks")
<add> response = self.client.get(
<add> f"/api/v1/dags/{dag_id}/tasks", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.get(f"/api/v1/dags/{self.dag_id}/tasks")
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_task_instance_endpoint.py
<ide> import pytest
<ide>
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import create_user, delete_user
<add>from tests.test_utils.config import conf_vars
<ide>
<ide>
<ide> class TestTaskInstanceEndpoint(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> class TestGetTaskInstance(TestTaskInstanceEndpoint):
<ide> @pytest.mark.skip(reason="Not implemented yet")
<ide> def test_should_response_200(self):
<ide> response = self.client.get(
<del> "/api/v1/dags/TEST_DG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_TASK_ID"
<add> "/api/v1/dags/TEST_DG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_TASK_ID",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> assert response.status_code == 200
<ide>
<ide>
<ide> class TestGetTaskInstances(TestTaskInstanceEndpoint):
<ide> @pytest.mark.skip(reason="Not implemented yet")
<ide> def test_should_response_200(self):
<del> response = self.client.get("/api/v1/dags/TEST_DAG_ID/taskInstances")
<add> response = self.client.get(
<add> "/api/v1/dags/TEST_DAG_ID/taskInstances", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<ide>
<ide> class TestGetTaskInstancesBatch(TestTaskInstanceEndpoint):
<ide> @pytest.mark.skip(reason="Not implemented yet")
<ide> def test_should_response_200(self):
<del> response = self.client.post("/api/v1/dags/~/taskInstances/list")
<add> response = self.client.post(
<add> "/api/v1/dags/~/taskInstances/list", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<ide>
<ide> class TestPostClearTaskInstances(TestTaskInstanceEndpoint):
<ide> @pytest.mark.skip(reason="Not implemented yet")
<ide> def test_should_response_200(self):
<del> response = self.client.post("/api/v1/dags/clearTaskInstances")
<add> response = self.client.post(
<add> "/api/v1/dags/clearTaskInstances", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide><path>tests/api_connexion/endpoints/test_variable_endpoint.py
<ide>
<ide> from airflow.models import Variable
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<ide> from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_variables
<ide>
<ide> class TestVariableEndpoint(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide> class TestDeleteVariable(TestVariableEndpoint):
<ide> def test_should_delete_variable(self):
<ide> Variable.set("delete_var1", 1)
<ide> # make sure variable is added
<del> response = self.client.get("/api/v1/variables/delete_var1")
<add> response = self.client.get(
<add> "/api/v1/variables/delete_var1", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide>
<del> response = self.client.delete("/api/v1/variables/delete_var1")
<add> response = self.client.delete(
<add> "/api/v1/variables/delete_var1", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 204
<ide>
<ide> # make sure variable is deleted
<del> response = self.client.get("/api/v1/variables/delete_var1")
<add> response = self.client.get(
<add> "/api/v1/variables/delete_var1", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide>
<ide> def test_should_response_404_if_key_does_not_exist(self):
<del> response = self.client.delete("/api/v1/variables/NONEXIST_VARIABLE_KEY")
<add> response = self.client.delete(
<add> "/api/v1/variables/NONEXIST_VARIABLE_KEY", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> Variable.set("delete_var1", 1)
<add> # make sure variable is added
<add> response = self.client.delete(
<add> "/api/v1/variables/delete_var1"
<add> )
<add>
<add> assert_401(response)
<add>
<add> # make sure variable is not deleted
<add> response = self.client.get(
<add> "/api/v1/variables/delete_var1", environ_overrides={'REMOTE_USER': "test"}
<add> )
<add> assert response.status_code == 200
<add>
<ide>
<ide> class TestGetVariable(TestVariableEndpoint):
<ide>
<ide> def test_should_response_200(self):
<ide> expected_value = '{"foo": 1}'
<ide> Variable.set("TEST_VARIABLE_KEY", expected_value)
<del> response = self.client.get("/api/v1/variables/TEST_VARIABLE_KEY")
<add> response = self.client.get(
<add> "/api/v1/variables/TEST_VARIABLE_KEY", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> assert response.json == {"key": "TEST_VARIABLE_KEY", "value": expected_value}
<ide>
<ide> def test_should_response_404_if_not_found(self):
<del> response = self.client.get("/api/v1/variables/NONEXIST_VARIABLE_KEY")
<add> response = self.client.get(
<add> "/api/v1/variables/NONEXIST_VARIABLE_KEY", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 404
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> Variable.set("TEST_VARIABLE_KEY", '{"foo": 1}')
<add>
<add> response = self.client.get(
<add> "/api/v1/variables/TEST_VARIABLE_KEY"
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestGetVariables(TestVariableEndpoint):
<ide> @parameterized.expand([
<ide> def test_should_get_list_variables(self, query, expected):
<ide> Variable.set("var1", 1)
<ide> Variable.set("var2", "foo")
<ide> Variable.set("var3", "[100, 101]")
<del> response = self.client.get(query)
<add> response = self.client.get(query, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> assert response.json == expected
<ide>
<ide> def test_should_respect_page_size_limit_default(self):
<ide> for i in range(101):
<ide> Variable.set(f"var{i}", i)
<del> response = self.client.get("/api/v1/variables")
<add> response = self.client.get("/api/v1/variables", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> assert response.json["total_entries"] == 101
<ide> assert len(response.json["variables"]) == 100
<ide> def test_should_respect_page_size_limit_default(self):
<ide> def test_should_return_conf_max_if_req_max_above_conf(self):
<ide> for i in range(200):
<ide> Variable.set(f"var{i}", i)
<del> response = self.client.get("/api/v1/variables?limit=180")
<add> response = self.client.get(
<add> "/api/v1/variables?limit=180", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<ide> self.assertEqual(len(response.json['variables']), 150)
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> Variable.set("var1", 1)
<add>
<add> response = self.client.get("/api/v1/variables?limit=2&offset=0")
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestPatchVariable(TestVariableEndpoint):
<ide> def test_should_update_variable(self):
<ide> Variable.set("var1", "foo")
<del> response = self.client.patch("/api/v1/variables/var1", json={
<del> "key": "var1",
<del> "value": "updated",
<del> })
<add> response = self.client.patch(
<add> "/api/v1/variables/var1",
<add> json={
<add> "key": "var1",
<add> "value": "updated",
<add> },
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 204
<del> response = self.client.get("/api/v1/variables/var1")
<add> response = self.client.get("/api/v1/variables/var1", environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.json == {
<ide> "key": "var1",
<ide> "value": "updated",
<ide> }
<ide>
<ide> def test_should_reject_invalid_update(self):
<ide> Variable.set("var1", "foo")
<del> response = self.client.patch("/api/v1/variables/var1", json={
<del> "key": "var2",
<del> "value": "updated",
<del> })
<add> response = self.client.patch(
<add> "/api/v1/variables/var1",
<add> json={
<add> "key": "var2",
<add> "value": "updated",
<add> },
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 400
<ide> assert response.json == {
<ide> "title": "Invalid post body",
<ide> def test_should_reject_invalid_update(self):
<ide> "detail": "key from request body doesn't match uri parameter",
<ide> }
<ide>
<del> response = self.client.patch("/api/v1/variables/var1", json={
<del> "key": "var2",
<del> })
<add> response = self.client.patch(
<add> "/api/v1/variables/var1",
<add> json={
<add> "key": "var2",
<add> },
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.json == {
<ide> "title": "Invalid Variable schema",
<ide> "status": 400,
<ide> "type": "about:blank",
<ide> "detail": "{'value': ['Missing data for required field.']}",
<ide> }
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> Variable.set("var1", "foo")
<add>
<add> response = self.client.patch(
<add> "/api/v1/variables/var1",
<add> json={
<add> "key": "var1",
<add> "value": "updated",
<add> },
<add> )
<add>
<add> assert_401(response)
<add>
<ide>
<ide> class TestPostVariables(TestVariableEndpoint):
<ide> def test_should_create_variable(self):
<del> response = self.client.post("/api/v1/variables", json={
<del> "key": "var_create",
<del> "value": "{}",
<del> })
<add> response = self.client.post(
<add> "/api/v1/variables",
<add> json={
<add> "key": "var_create",
<add> "value": "{}",
<add> },
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 200
<del> response = self.client.get("/api/v1/variables/var_create")
<add> response = self.client.get(
<add> "/api/v1/variables/var_create", environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.json == {
<ide> "key": "var_create",
<ide> "value": "{}",
<ide> }
<ide>
<ide> def test_should_reject_invalid_request(self):
<del> response = self.client.post("/api/v1/variables", json={
<del> "key": "var_create",
<del> "v": "{}",
<del> })
<add> response = self.client.post(
<add> "/api/v1/variables",
<add> json={
<add> "key": "var_create",
<add> "v": "{}",
<add> },
<add> environ_overrides={'REMOTE_USER': "test"}
<add> )
<ide> assert response.status_code == 400
<ide> assert response.json == {
<ide> "title": "Invalid Variable schema",
<ide> "status": 400,
<ide> "type": "about:blank",
<ide> "detail": "{'value': ['Missing data for required field.'], 'v': ['Unknown field.']}",
<ide> }
<add>
<add> def test_should_raises_401_unauthenticated(self):
<add> response = self.client.post(
<add> "/api/v1/variables",
<add> json={
<add> "key": "var_create",
<add> "value": "{}",
<add> },
<add> )
<add>
<add> assert_401(response)
<ide><path>tests/api_connexion/endpoints/test_version_endpoint.py
<ide> from unittest import mock
<ide>
<ide> from airflow.www import app
<add>from tests.test_utils.config import conf_vars
<ide>
<ide>
<ide> class TestGetHealthTest(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<ide>
<ide> def setUp(self) -> None:
<ide> self.client = self.app.test_client() # type:ignore
<ide><path>tests/api_connexion/endpoints/test_xcom_endpoint.py
<ide> from airflow.utils.session import provide_session
<ide> from airflow.utils.types import DagRunType
<ide> from airflow.www import app
<add>from tests.test_utils.api_connexion_utils import assert_401, create_user, delete_user
<add>from tests.test_utils.config import conf_vars
<ide> from tests.test_utils.db import clear_db_runs, clear_db_xcom
<ide>
<ide>
<ide> class TestXComEndpoint(unittest.TestCase):
<ide> @classmethod
<ide> def setUpClass(cls) -> None:
<ide> super().setUpClass()
<del> cls.app = app.create_app(testing=True) # type:ignore
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ):
<add> cls.app = app.create_app(testing=True) # type:ignore
<add> # TODO: Add new role for each view to test permission.
<add> create_user(cls.app, username="test", role="Admin") # type: ignore
<add>
<add> @classmethod
<add> def tearDownClass(cls) -> None:
<add> delete_user(cls.app, username="test") # type: ignore
<ide>
<ide> @staticmethod
<ide> def clean_db():
<ide> def tearDown(self) -> None:
<ide>
<ide> class TestGetXComEntry(TestXComEndpoint):
<ide>
<del> @provide_session
<del> def test_should_response_200(self, session):
<add> def test_should_response_200(self):
<ide> dag_id = 'test-dag-id'
<ide> task_id = 'test-task-id'
<ide> execution_date = '2005-04-02T00:00:00+00:00'
<ide> xcom_key = 'test-xcom-key'
<ide> execution_date_parsed = parse_execution_date(execution_date)
<del> xcom_model = XCom(key=xcom_key,
<del> execution_date=execution_date_parsed,
<del> task_id=task_id,
<del> dag_id=dag_id,
<del> timestamp=execution_date_parsed)
<ide> dag_run_id = DR.generate_run_id(DagRunType.MANUAL, execution_date_parsed)
<del> dagrun = DR(dag_id=dag_id,
<del> run_id=dag_run_id,
<del> execution_date=execution_date_parsed,
<del> start_date=execution_date_parsed,
<del> run_type=DagRunType.MANUAL.value)
<del> session.add(xcom_model)
<del> session.add(dagrun)
<del> session.commit()
<add> self._create_xcom_entry(dag_id, dag_run_id, execution_date_parsed, task_id, xcom_key)
<ide> response = self.client.get(
<del> f"/api/v1/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries/{xcom_key}"
<add> f"/api/v1/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries/{xcom_key}",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<ide> self.assertEqual(200, response.status_code)
<add>
<add> current_data = response.json
<add> current_data['timestamp'] = 'TIMESTAMP'
<ide> self.assertEqual(
<del> response.json,
<add> current_data,
<ide> {
<ide> 'dag_id': dag_id,
<ide> 'execution_date': execution_date,
<ide> 'key': xcom_key,
<ide> 'task_id': task_id,
<del> 'timestamp': execution_date
<add> 'timestamp': 'TIMESTAMP'
<ide> }
<ide> )
<ide>
<del>
<del>class TestGetXComEntries(TestXComEndpoint):
<del> @provide_session
<del> def test_should_response_200(self, session):
<add> def test_should_raises_401_unauthenticated(self):
<ide> dag_id = 'test-dag-id'
<ide> task_id = 'test-task-id'
<ide> execution_date = '2005-04-02T00:00:00+00:00'
<add> xcom_key = 'test-xcom-key'
<ide> execution_date_parsed = parse_execution_date(execution_date)
<del> xcom_model_1 = XCom(key='test-xcom-key-1',
<del> execution_date=execution_date_parsed,
<del> task_id=task_id,
<del> dag_id=dag_id,
<del> timestamp=execution_date_parsed)
<del> xcom_model_2 = XCom(key='test-xcom-key-2',
<del> execution_date=execution_date_parsed,
<del> task_id=task_id,
<del> dag_id=dag_id,
<del> timestamp=execution_date_parsed)
<ide> dag_run_id = DR.generate_run_id(DagRunType.MANUAL, execution_date_parsed)
<add> self._create_xcom_entry(dag_id, dag_run_id, execution_date_parsed, task_id, xcom_key)
<add>
<add> response = self.client.get(
<add> f"/api/v1/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries/{xcom_key}"
<add> )
<add>
<add> assert_401(response)
<add>
<add> @provide_session
<add> def _create_xcom_entry(self, dag_id, dag_run_id, execution_date, task_id, xcom_key, session=None):
<add> XCom.set(key=xcom_key,
<add> value="TEST_VALUE",
<add> execution_date=execution_date,
<add> task_id=task_id,
<add> dag_id=dag_id,)
<ide> dagrun = DR(dag_id=dag_id,
<ide> run_id=dag_run_id,
<del> execution_date=execution_date_parsed,
<del> start_date=execution_date_parsed,
<add> execution_date=execution_date,
<add> start_date=execution_date,
<ide> run_type=DagRunType.MANUAL.value)
<del> xcom_models = [xcom_model_1, xcom_model_2]
<del> session.add_all(xcom_models)
<ide> session.add(dagrun)
<del> session.commit()
<add>
<add>
<add>class TestGetXComEntries(TestXComEndpoint):
<add> def test_should_response_200(self):
<add> dag_id = 'test-dag-id'
<add> task_id = 'test-task-id'
<add> execution_date = '2005-04-02T00:00:00+00:00'
<add> execution_date_parsed = parse_execution_date(execution_date)
<add> dag_run_id = DR.generate_run_id(DagRunType.MANUAL, execution_date_parsed)
<add>
<add> self._create_xcom_entries(dag_id, dag_run_id, execution_date_parsed, task_id)
<ide> response = self.client.get(
<del> f"/api/v1/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries"
<add> f"/api/v1/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries",
<add> environ_overrides={'REMOTE_USER': "test"}
<ide> )
<add>
<ide> self.assertEqual(200, response.status_code)
<add> response_data = response.json
<add> for xcom_entry in response_data['xcom_entries']:
<add> xcom_entry['timestamp'] = "TIMESTAMP"
<ide> self.assertEqual(
<ide> response.json,
<ide> {
<ide> def test_should_response_200(self, session):
<ide> 'execution_date': execution_date,
<ide> 'key': 'test-xcom-key-1',
<ide> 'task_id': task_id,
<del> 'timestamp': execution_date
<add> 'timestamp': "TIMESTAMP"
<ide> },
<ide> {
<ide> 'dag_id': dag_id,
<ide> 'execution_date': execution_date,
<ide> 'key': 'test-xcom-key-2',
<ide> 'task_id': task_id,
<del> 'timestamp': execution_date
<add> 'timestamp': "TIMESTAMP"
<ide> }
<ide> ],
<ide> 'total_entries': 2,
<ide> }
<ide> )
<ide>
<add> def test_should_raises_401_unauthenticated(self):
<add> dag_id = 'test-dag-id'
<add> task_id = 'test-task-id'
<add> execution_date = '2005-04-02T00:00:00+00:00'
<add> execution_date_parsed = parse_execution_date(execution_date)
<add> dag_run_id = DR.generate_run_id(DagRunType.MANUAL, execution_date_parsed)
<add> self._create_xcom_entries(dag_id, dag_run_id, execution_date_parsed, task_id)
<add>
<add> response = self.client.get(
<add> f"/api/v1/dags/{dag_id}/dagRuns/{dag_run_id}/taskInstances/{task_id}/xcomEntries"
<add> )
<add>
<add> assert_401(response)
<add>
<add> @provide_session
<add> def _create_xcom_entries(self, dag_id, dag_run_id, execution_date, task_id, session=None):
<add> for i in [1, 2]:
<add> XCom.set(
<add> key=f'test-xcom-key-{i}',
<add> value="TEST",
<add> execution_date=execution_date,
<add> task_id=task_id,
<add> dag_id=dag_id,
<add> )
<add> dagrun = DR(dag_id=dag_id,
<add> run_id=dag_run_id,
<add> execution_date=execution_date,
<add> start_date=execution_date,
<add> run_type=DagRunType.MANUAL.value)
<add> session.add(dagrun)
<add>
<ide>
<ide> class TestPaginationGetXComEntries(TestXComEndpoint):
<ide>
<ide> def test_handle_limit_offset(self, query_params, expected_xcom_ids, session):
<ide> session.add_all(xcom_models)
<ide> session.add(dagrun)
<ide> session.commit()
<del> response = self.client.get(url)
<add> response = self.client.get(url, environ_overrides={'REMOTE_USER': "test"})
<ide> assert response.status_code == 200
<ide> self.assertEqual(response.json["total_entries"], 10)
<ide> conn_ids = [conn["key"] for conn in response.json["xcom_entries"] if conn]
<ide><path>tests/test_utils/api_connexion_utils.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>def create_user(app, username, role):
<add> appbuilder = app.appbuilder
<add> role_admin = appbuilder.sm.find_role(role)
<add> tester = appbuilder.sm.find_user(username=username)
<add> if not tester:
<add> appbuilder.sm.add_user(
<add> username=username,
<add> first_name=username,
<add> last_name=username,
<add> email=f"{username}@fab.org",
<add> role=role_admin,
<add> password=username,
<add> )
<add>
<add>
<add>def delete_user(app, username):
<add> appbuilder = app.appbuilder
<add> user = next(u for u in appbuilder.sm.get_all_users() if u.username == username)
<add>
<add> appbuilder.sm.del_register_user(user)
<add>
<add>
<add>def assert_401(response):
<add> assert response.status_code == 401
<add> assert response.json == {
<add> 'detail': None,
<add> 'status': 401,
<add> 'title': 'Unauthorized',
<add> 'type': 'about:blank'
<add> }
<ide><path>tests/test_utils/remote_user_api_auth_backend.py
<add>#
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>"""Default authentication backend - everything is allowed"""
<add>import logging
<add>from functools import wraps
<add>from typing import Callable, Optional, Tuple, TypeVar, Union, cast
<add>
<add>from flask import Response, current_app, request
<add>from flask_login import login_user
<add>from requests.auth import AuthBase
<add>
<add>log = logging.getLogger(__name__)
<add>
<add>CLIENT_AUTH: Optional[Union[Tuple[str, str], AuthBase]] = None
<add>
<add>
<add>def init_app(_):
<add> """Initializes authentication backend"""
<add>
<add>
<add>T = TypeVar("T", bound=Callable) # pylint: disable=invalid-name
<add>
<add>
<add>def _lookup_user(user_email_or_username: str):
<add> security_manager = current_app.appbuilder.sm
<add> user = (
<add> security_manager.find_user(email=user_email_or_username)
<add> or security_manager.find_user(username=user_email_or_username)
<add> )
<add> if not user:
<add> return None
<add>
<add> if not user.is_active:
<add> return None
<add>
<add> return user
<add>
<add>
<add>def requires_authentication(function: T):
<add> """Decorator for functions that require authentication"""
<add> @wraps(function)
<add> def decorated(*args, **kwargs):
<add> user_id = request.remote_user
<add> if not user_id:
<add> log.debug("Missing REMOTE_USER.")
<add> return Response("Forbidden", 403)
<add>
<add> log.debug("Looking for user: %s", user_id)
<add>
<add> user = _lookup_user(user_id)
<add> if not user:
<add> return Response("Forbidden", 403)
<add>
<add> log.debug("Found user: %s", user)
<add>
<add> login_user(user, remember=False)
<add> return function(*args, **kwargs)
<add>
<add> return cast(T, decorated)
<ide><path>tests/test_utils/test_remote_user_api_auth_backend.py
<add># Licensed to the Apache Software Foundation (ASF) under one
<add># or more contributor license agreements. See the NOTICE file
<add># distributed with this work for additional information
<add># regarding copyright ownership. The ASF licenses this file
<add># to you under the Apache License, Version 2.0 (the
<add># "License"); you may not use this file except in compliance
<add># with the License. You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing,
<add># software distributed under the License is distributed on an
<add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
<add># KIND, either express or implied. See the License for the
<add># specific language governing permissions and limitations
<add># under the License.
<add>
<add>import unittest
<add>from unittest import mock
<add>
<add>from flask_login import current_user
<add>
<add>from airflow.www.app import create_app
<add>from tests.test_utils.config import conf_vars
<add>from tests.test_utils.db import clear_db_pools
<add>
<add>
<add>class TestGoogleOpenID(unittest.TestCase):
<add> def setUp(self) -> None:
<add> with conf_vars(
<add> {("api", "auth_backend"): "tests.test_utils.remote_user_api_auth_backend"}
<add> ), mock.patch.dict('os.environ', SKIP_DAGS_PARSING='True'):
<add> self.app = create_app(testing=True)
<add>
<add> self.appbuilder = self.app.appbuilder # pylint: disable=no-member
<add> role_admin = self.appbuilder.sm.find_role("Admin")
<add> tester = self.appbuilder.sm.find_user(username="test")
<add> if not tester:
<add> self.appbuilder.sm.add_user(
<add> username="test",
<add> first_name="test",
<add> last_name="test",
<add> email="test@fab.org",
<add> role=role_admin,
<add> password="test",
<add> )
<add>
<add> def test_success_using_username(self):
<add> clear_db_pools()
<add>
<add> with self.app.test_client() as test_client:
<add> response = test_client.get(
<add> "/api/experimental/pools", environ_overrides={'REMOTE_USER': "test"}
<add> )
<add> self.assertEqual("test@fab.org", current_user.email)
<add>
<add> self.assertEqual(200, response.status_code)
<add> self.assertIn("Default pool", str(response.json))
<add>
<add> def test_success_using_email(self):
<add> clear_db_pools()
<add>
<add> with self.app.test_client() as test_client:
<add> response = test_client.get(
<add> "/api/experimental/pools", environ_overrides={'REMOTE_USER': "test@fab.org"}
<add> )
<add> self.assertEqual("test@fab.org", current_user.email)
<add>
<add> self.assertEqual(200, response.status_code)
<add> self.assertIn("Default pool", str(response.json))
<add>
<add> def test_user_not_exists(self):
<add> with self.app.test_client() as test_client:
<add> response = test_client.get(
<add> "/api/experimental/pools", environ_overrides={'REMOTE_USER': "INVALID"}
<add> )
<add>
<add> self.assertEqual(403, response.status_code)
<add> self.assertEqual("Forbidden", response.data.decode())
<add>
<add> def test_missing_remote_user(self):
<add> with self.app.test_client() as test_client:
<add> response = test_client.get("/api/experimental/pools")
<add>
<add> self.assertEqual(403, response.status_code)
<add> self.assertEqual("Forbidden", response.data.decode())
<add>
<add> def test_user_should_be_logged_temporary(self):
<add> with self.app.test_client() as test_client:
<add> response = test_client.get(
<add> "/api/experimental/pools", environ_overrides={'REMOTE_USER': "INVALID"}
<add> )
<add>
<add> self.assertEqual(403, response.status_code)
<add> self.assertEqual("Forbidden", response.data.decode()) | 33 |
PHP | PHP | fix testapp parma typehints | 60a0b2fd62e6c71347d76972be181b3c4f0ec57c | <ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> public static function httpMethodProvider()
<ide> * @dataProvider httpMethodProvider
<ide> * @return void
<ide> */
<del> public function testHttpMethods($method)
<add> public function testHttpMethods(string $method)
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/', [], ['namePrefix' => 'app:']);
<ide> $route = $routes->{strtolower($method)}(
<ide> public function testHttpMethods($method)
<ide> * @dataProvider httpMethodProvider
<ide> * @return void
<ide> */
<del> public function testHttpMethodsStringTarget($method)
<add> public function testHttpMethodsStringTarget(string $method)
<ide> {
<ide> $routes = new RouteBuilder($this->collection, '/', [], ['namePrefix' => 'app:']);
<ide> $route = $routes->{strtolower($method)}(
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> public static function hostProvider()
<ide> *
<ide> * @dataProvider hostProvider
<ide> */
<del> public function testParseRequestCheckHostConditionFail($host)
<add> public function testParseRequestCheckHostConditionFail(string $host)
<ide> {
<ide> $this->expectException(\Cake\Routing\Exception\MissingRouteException::class);
<ide> $this->expectExceptionMessage('A route matching "/fallback" could not be found');
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> public function testParseError()
<ide> * @return void
<ide> * @dataProvider parseReverseSymmetryData
<ide> */
<del> public function testParseReverseSymmetry($url)
<add> public function testParseReverseSymmetry(string $url)
<ide> {
<ide> $this->_connectDefaultRoutes();
<ide> $this->assertSame($url, Router::reverse(Router::parseRequest($this->makeRequest($url, 'GET')) + ['url' => []]));
<ide><path>tests/TestCase/TestSuite/FixtureManagerTest.php
<ide> public function testExceptionOnLoad()
<ide> * @dataProvider loadErrorMessageProvider
<ide> * @return void
<ide> */
<del> public function testExceptionOnLoadFixture($method, $expectedMessage)
<add> public function testExceptionOnLoadFixture(string $method, string $expectedMessage)
<ide> {
<ide> $fixture = $this->getMockBuilder('Cake\Test\Fixture\ProductsFixture')
<ide> ->onlyMethods(['drop', 'create', $method])
<ide><path>tests/TestCase/TestSuite/IntegrationTestTraitTest.php
<ide> public function testEventManagerReset1()
<ide> * @depends testEventManagerReset1
<ide> * @return void
<ide> */
<del> public function testEventManagerReset2($prevEventManager)
<add> public function testEventManagerReset2(EventManager $prevEventManager)
<ide> {
<ide> $this->assertInstanceOf('Cake\Event\EventManager', $prevEventManager);
<ide> $this->assertNotSame($prevEventManager, EventManager::instance());
<ide> public function testDisableErrorHandlerMiddleware()
<ide> * @return void
<ide> * @dataProvider methodsProvider
<ide> */
<del> public function testSecureWithQueryString($method)
<add> public function testSecureWithQueryString(string $method)
<ide> {
<ide> $this->enableSecurityToken();
<ide> $this->{$method}('/posts/securePost/?ids[]=1&ids[]=2');
<ide> public function testAssertResponseRegExpVerbose()
<ide> * Test the assertion generates a verbose message for session related checks.
<ide> *
<ide> * @dataProvider assertionFailureSessionVerboseProvider
<add> * @param mixed ...$rest
<ide> * @return void
<ide> */
<del> public function testAssertSessionRelatedVerboseMessages($assertMethod, ...$rest)
<add> public function testAssertSessionRelatedVerboseMessages(string $assertMethod, ...$rest)
<ide> {
<ide> $this->expectException(AssertionFailedError::class);
<ide> $this->expectExceptionMessage('Possibly related to OutOfBoundsException: "oh no!"');
<ide><path>tests/TestCase/Utility/HashTest.php
<ide> public function testExtractInvalidArgument()
<ide> * Test the extraction of a single value filtered by another field.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractSingleValueWithFilteringByAnotherField($data)
<ide> public function testExtractSingleValueWithFilteringByAnotherField($data)
<ide> * Test simple paths.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractBasic($data)
<ide> public function testExtractBasic($data)
<ide> * Test the {n} selector
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractNumericKey($data)
<ide> public function testExtractNumericNonZero()
<ide> * Test the {s} selector.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractStringKey($data)
<ide> public function testExtractWildcard()
<ide> * Test the attribute presence selector.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractAttributePresence($data)
<ide> public function testExtractAttributePresence($data)
<ide> * Test = and != operators.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractAttributeEquality($data)
<ide> public function testExtractAttributeEqualityOnScalarValue()
<ide> * Test comparison operators.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractAttributeComparison($data)
<ide> public function testExtractAttributeComparison($data)
<ide> * Test multiple attributes with conditions.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractAttributeMultiple($data)
<ide> public function testExtractAttributeMultiple($data)
<ide> * Test attribute pattern matching.
<ide> *
<ide> * @dataProvider articleDataSets
<add> * @param \ArrayAccess|array $data
<ide> * @return void
<ide> */
<ide> public function testExtractAttributePattern($data)
<ide><path>tests/TestCase/Utility/InflectorTest.php
<ide> public function tearDown(): void
<ide> * @dataProvider singularizeProvider
<ide> * @return void
<ide> */
<del> public function testInflectingSingulars($singular, $plural)
<add> public function testInflectingSingulars(string $singular, string $plural)
<ide> {
<ide> $this->assertSame($singular, Inflector::singularize($plural));
<ide> }
<ide> public function testSingularizeMultiWordIrregular()
<ide> * @dataProvider pluralizeProvider
<ide> * @return void
<ide> */
<del> public function testInflectingPlurals($plural, $singular)
<add> public function testInflectingPlurals(string $plural, string $singular)
<ide> {
<ide> $this->assertSame($plural, Inflector::pluralize($singular));
<ide> }
<ide><path>tests/TestCase/Utility/TextTest.php
<ide> public function testReplaceWithQuestionMarkInString()
<ide> * @dataProvider wordWrapProvider
<ide> * @return void
<ide> */
<del> public function testWordWrap($text, $width, $break = "\n", $cut = false)
<add> public function testWordWrap(string $text, int $width, string $break = "\n", bool $cut = false)
<ide> {
<ide> $result = Text::wordWrap($text, $width, $break, $cut);
<ide> $expected = wordwrap($text, $width, $break, $cut);
<ide> public function testAscii()
<ide> * testparseFileSize
<ide> *
<ide> * @dataProvider filesizes
<add> * @param mixed $expected
<ide> * @return void
<ide> */
<del> public function testParseFileSize($params, $expected)
<add> public function testParseFileSize(array $params, $expected)
<ide> {
<ide> $result = Text::parseFileSize($params['size'], $params['default']);
<ide> $this->assertSame($expected, $result);
<ide><path>tests/TestCase/Utility/XmlTest.php
<ide> public static function invalidDataProvider()
<ide> * testBuildInvalidData
<ide> *
<ide> * @dataProvider invalidDataProvider
<add> * @param mixed $value
<ide> * @return void
<ide> */
<ide> public function testBuildInvalidData($value)
<ide> public static function invalidArrayDataProvider()
<ide> * testFromArrayFail method
<ide> *
<ide> * @dataProvider invalidArrayDataProvider
<add> * @param mixed $value
<ide> * @return void
<ide> */
<ide> public function testFromArrayFail($value)
<ide> public static function invalidToArrayDataProvider()
<ide> * testToArrayFail method
<ide> *
<ide> * @dataProvider invalidToArrayDataProvider
<add> * @param mixed $value
<ide> * @return void
<ide> */
<ide> public function testToArrayFail($value)
<ide><path>tests/TestCase/Validation/ValidationTest.php
<ide> public function testUploadedFileErrorCode()
<ide> * @dataProvider uploadedFileProvider
<ide> * @return void
<ide> */
<del> public function testUploadedFileArray($expected, $options)
<add> public function testUploadedFileArray(bool $expected, array $options)
<ide> {
<ide> $file = [
<ide> 'name' => 'cake.power.gif',
<ide> public function uploadedFileProvider()
<ide> * @dataProvider uploadedFileProvider
<ide> * @return void
<ide> */
<del> public function testUploadedFilePsr7($expected, $options)
<add> public function testUploadedFilePsr7(bool $expected, array $options)
<ide> {
<ide> $image = TEST_APP . 'webroot/img/cake.power.gif';
<ide> $file = new UploadedFile($image, 1000, UPLOAD_ERR_OK, 'cake.power.gif', 'image/gif');
<ide><path>tests/TestCase/View/Form/EntityContextTest.php
<ide> public function testIsCreateSingle()
<ide> * Test isCreate on a collection.
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testIsCreateCollection($collection)
<ide> public function testOperationsNoTableArg()
<ide> * Test collection operations that lack a table argument.
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testCollectionOperationsNoTableArg($collection)
<ide> public static function collectionProvider()
<ide> * Test operations on a collection of entities.
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testValOnCollections($collection)
<ide> public function testValOnCollections($collection)
<ide> * table name
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testValOnCollectionsWithRootName($collection)
<ide> public function testValOnCollectionsWithRootName($collection)
<ide> * Test error operations on a collection of entities.
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testErrorsOnCollections($collection)
<ide> public function testErrorsOnCollections($collection)
<ide> * Test schema operations on a collection of entities.
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testSchemaOnCollections($collection)
<ide> public function testSchemaOnCollections($collection)
<ide> * Test validation operations on a collection of entities.
<ide> *
<ide> * @dataProvider collectionProvider
<add> * @param mixed $collection
<ide> * @return void
<ide> */
<ide> public function testValidatorsOnCollections($collection)
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function contextSelectionProvider()
<ide> * Test default context selection in create()
<ide> *
<ide> * @dataProvider contextSelectionProvider
<add> * @param mixed $data
<ide> * @return void
<ide> */
<del> public function testCreateContextSelectionBuiltIn($data, $class)
<add> public function testCreateContextSelectionBuiltIn($data, string $class)
<ide> {
<ide> $this->loadFixtures('Articles');
<ide> $this->Form->create($data);
<ide> public function testSubmitTemplateVars()
<ide> * @dataProvider requestTypeProvider
<ide> * @return void
<ide> */
<del> public function testCreateTypeOptions($type, $method, $override)
<add> public function testCreateTypeOptions(string $type, string $method, string $override)
<ide> {
<ide> $encoding = strtolower(Configure::read('App.encoding'));
<ide> $result = $this->Form->create(null, ['type' => $type]);
<ide><path>tests/TestCase/View/Helper/NumberHelperTest.php
<ide> public function methodProvider()
<ide> * @dataProvider methodProvider
<ide> * @return void
<ide> */
<del> public function testNumberHelperProxyMethodCalls($method)
<add> public function testNumberHelperProxyMethodCalls(string $method)
<ide> {
<ide> $number = $this->getMockBuilder(NumberMock::class)
<ide> ->addMethods([$method])
<ide> public function testNumberHelperProxyMethodCalls($method)
<ide> * @dataProvider methodProvider
<ide> * @return void
<ide> */
<del> public function testParameterCountMatch($method)
<add> public function testParameterCountMatch(string $method)
<ide> {
<ide> $numberMethod = new ReflectionMethod(Number::class, $method);
<ide> $helperMethod = new ReflectionMethod(NumberHelper::class, $method);
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testMethodsWhenThereIsNoPageCount()
<ide> $this->assertSame(0, $result);
<ide> }
<ide>
<add> /**
<add> * @param mixed $params
<add> */
<ide> protected function setPagingParams($params, bool $merge = true)
<ide> {
<ide> if ($merge) {
<ide><path>tests/TestCase/View/Helper/TextHelperTest.php
<ide> public static function autoLinkProvider()
<ide> * @dataProvider autoLinkProvider
<ide> * @return void
<ide> */
<del> public function testAutoLinkUrls($text, $expected)
<add> public function testAutoLinkUrls(string $text, string $expected)
<ide> {
<ide> $result = $this->Text->autoLinkUrls($text);
<ide> $this->assertEquals($expected, $result);
<ide> public function autoLinkEmailProvider()
<ide> * @dataProvider autoLinkEmailProvider
<ide> * @return void
<ide> */
<del> public function testAutoLinkEmails($text, $expected, $attrs = [])
<add> public function testAutoLinkEmails(string $text, string $expected, array $attrs = [])
<ide> {
<ide> $result = $this->Text->autoLinkEmails($text, $attrs);
<ide> $this->assertSame($expected, $result);
<ide><path>tests/TestCase/View/ViewBuilderTest.php
<ide> public function arrayPropertyProvider()
<ide> * @dataProvider stringPropertyProvider
<ide> * @return void
<ide> */
<del> public function testStringProperties($property, $value)
<add> public function testStringProperties(string $property, string $value)
<ide> {
<ide> $get = 'get' . ucfirst($property);
<ide> $set = 'set' . ucfirst($property);
<ide> public function testStringProperties($property, $value)
<ide> * @dataProvider boolPropertyProvider
<ide> * @return void
<ide> */
<del> public function testBoolProperties($property, $default, $value)
<add> public function testBoolProperties(string $property, bool $default, bool $value)
<ide> {
<ide> $set = 'enable' . ucfirst($property);
<ide> $get = 'is' . ucfirst($property) . 'Enabled';
<ide> public function testBoolProperties($property, $default, $value)
<ide> * @dataProvider arrayPropertyProvider
<ide> * @return void
<ide> */
<del> public function testArrayProperties($property, $value)
<add> public function testArrayProperties(string $property, array $value)
<ide> {
<ide> $get = 'get' . ucfirst($property);
<ide> $set = 'set' . ucfirst($property);
<ide> public function testArrayProperties($property, $value)
<ide> * @dataProvider arrayPropertyProvider
<ide> * @return void
<ide> */
<del> public function testArrayPropertyMerge($property, $value)
<add> public function testArrayPropertyMerge(string $property, array $value)
<ide> {
<ide> $get = 'get' . ucfirst($property);
<ide> $set = 'set' . ucfirst($property);
<ide><path>tests/TestCase/View/ViewTest.php
<ide> public function testGetNamePlugin()
<ide> $this->assertSame('TestPlugin', $this->View->getPlugin());
<ide> }
<ide>
<del> protected function checkException($message)
<add> protected function checkException(string $message)
<ide> {
<ide> if (version_compare(PHP_VERSION, '7.4', '>=')) {
<ide> $this->expectException(\Error::class);
<ide><path>tests/TestCase/View/Widget/CheckboxWidgetTest.php
<ide> public static function checkedProvider()
<ide> * Test rendering checked checkboxes with value.
<ide> *
<ide> * @dataProvider checkedProvider
<add> * @param mixed $checked
<ide> * @return void
<ide> */
<ide> public function testRenderCheckedValue($checked)
<ide> public static function uncheckedProvider()
<ide> * Test rendering unchecked checkboxes
<ide> *
<ide> * @dataProvider uncheckedProvider
<add> * @param mixed $checked
<ide> * @return void
<ide> */
<ide> public function testRenderUnCheckedValue($checked)
<ide><path>tests/TestCase/View/Widget/DateTimeWidgetTest.php
<ide> public static function invalidSelectedValuesProvider()
<ide> * test rendering selected values.
<ide> *
<ide> * @dataProvider invalidSelectedValuesProvider
<add> * @param mixed $selected
<ide> * @return void
<ide> */
<ide> public function testRenderInvalid($selected)
<ide> public static function selectedValuesProvider()
<ide> * test rendering selected values.
<ide> *
<ide> * @dataProvider selectedValuesProvider
<add> * @param mixed $selected
<ide> * @return void
<ide> */
<ide> public function testRenderValid($selected)
<ide><path>tests/test_app/Plugin/TestPlugin/src/Cache/Engine/TestPluginCacheEngine.php
<ide>
<ide> class TestPluginCacheEngine extends CacheEngine
<ide> {
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function set($key, $value, $ttl = null): bool
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function get($key, $default = null)
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function increment(string $key, int $offset = 1)
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function decrement(string $key, int $offset = 1)
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function delete($key): bool
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function clear(): bool
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function clearGroup(string $group): bool
<ide> {
<ide> }
<ide><path>tests/test_app/Plugin/TestPlugin/src/Http/Session/TestPluginSession.php
<ide> */
<ide> class TestPluginSession implements SessionHandlerInterface
<ide> {
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function open($path, $name): bool
<ide> {
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function close(): bool
<ide> {
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> #[ReturnTypeWillChange]
<ide> public function read($id)
<ide> {
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function write($id, $data): bool
<ide> {
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function destroy($id): bool
<ide> {
<ide> return true;
<ide> }
<ide>
<add> /**
<add> * @inheritDoc
<add> */
<ide> #[ReturnTypeWillChange]
<ide> public function gc($maxlifetime)
<ide> {
<ide><path>tests/test_app/Plugin/TestPlugin/src/Log/Engine/TestPluginLog.php
<ide> */
<ide> class TestPluginLog extends AbstractLogger
<ide> {
<add> /**
<add> * @inheritDoc
<add> */
<ide> public function log($level, $message, array $context = [])
<ide> {
<ide> } | 22 |
PHP | PHP | extract a trait for generating id values | d4e69440468d5e3fed8e600e802730a11889f03a | <ide><path>src/View/Widget/IdGeneratorTrait.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) v3.0
<add> * @license http://www.opensource.org/licenses/mit-license.php MIT License
<add> */
<add>namespace Cake\View\Widget;
<add>
<add>use Cake\Utility\Inflector;
<add>
<add>/**
<add> * A trait that provides id generating methods to be
<add> * used in various widget classes.
<add> */
<add>trait IdGeneratorTrait {
<add>
<add>/**
<add> * A list of id suffixes used in the current rendering.
<add> *
<add> * @var array
<add> */
<add> protected $_idSuffixes = [];
<add>
<add>/**
<add> * Clear the stored ID suffixes.
<add> *
<add> * @return void
<add> */
<add> protected function _clearIds() {
<add> $this->_idSuffixes = [];
<add> }
<add>
<add>/**
<add> * Generate an ID attribute for a radio button.
<add> *
<add> * Ensures that id's for a given set of fields are unique.
<add> *
<add> * @param array $radio The radio properties.
<add> * @return string Generated id.
<add> */
<add> protected function _id($name, $val) {
<add> $name = mb_strtolower(Inflector::slug($name, '-'));
<add> $idSuffix = mb_strtolower(str_replace(array('@', '<', '>', ' ', '"', '\''), '-', $val));
<add> $count = 1;
<add> $check = $idSuffix;
<add> while (in_array($check, $this->_idSuffixes)) {
<add> $check = $idSuffix . $count++;
<add> }
<add> $this->_idSuffixes[] = $check;
<add> return trim($name . '-' . $check, '-');
<add> }
<add>}
<ide><path>src/View/Widget/Radio.php
<ide> */
<ide> namespace Cake\View\Widget;
<ide>
<del>use Cake\Utility\Inflector;
<add>use Cake\View\Widget\IdGeneratorTrait;
<ide> use Cake\View\Widget\WidgetInterface;
<ide> use Traversable;
<ide>
<ide> */
<ide> class Radio implements WidgetInterface {
<ide>
<add> use IdGeneratorTrait;
<add>
<ide> /**
<ide> * Template instance.
<ide> *
<ide> class Radio implements WidgetInterface {
<ide> */
<ide> protected $_label;
<ide>
<del>/**
<del> * A list of id suffixes used in the current rendering.
<del> *
<del> * @var array
<del> */
<del> protected $_idSuffixes = [];
<del>
<ide> /**
<ide> * Constructor
<ide> *
<ide> public function render(array $data) {
<ide> }
<ide> unset($data['empty']);
<ide>
<del> $this->_idSuffixes = [];
<add> $this->_clearIds();
<ide> $opts = [];
<ide> foreach ($options as $val => $text) {
<ide> $opts[] = $this->_renderInput($val, $text, $data);
<ide> protected function _renderInput($val, $text, $data) {
<ide> $radio['name'] = $data['name'];
<ide>
<ide> if (empty($radio['id'])) {
<del> $radio['id'] = $this->_id($radio);
<add> $radio['id'] = $this->_id($radio['name'], $radio['value']);
<ide> }
<ide>
<ide> if (isset($data['val']) && is_bool($data['val'])) {
<ide> protected function _renderLabel($radio, $label, $input, $escape) {
<ide> return $this->_label->render($labelAttrs);
<ide> }
<ide>
<del>/**
<del> * Generate an ID attribute for a radio button.
<del> *
<del> * Ensures that id's for a given set of fields are unique.
<del> *
<del> * @param array $radio The radio properties.
<del> * @return string Generated id.
<del> */
<del> protected function _id($radio) {
<del> $value = mb_strtolower(Inflector::slug($radio['name'], '-'));
<del> $idSuffix = mb_strtolower(str_replace(array('@', '<', '>', ' ', '"', '\''), '-', $radio['value']));
<del> $count = 1;
<del> $check = $idSuffix;
<del> while (in_array($check, $this->_idSuffixes)) {
<del> $check = $idSuffix . $count++;
<del> }
<del> $this->_idSuffixes[] = $check;
<del> return trim($value . '-' . $check, '-');
<del> }
<del>
<ide> } | 2 |
Ruby | Ruby | remove deprecation comment | c7f8ce83d44f6f4b0133c35a1b7a64a91e133900 | <ide><path>Library/Homebrew/cmd/tap.rb
<ide> def tap_args
<ide> assumptions, so taps can be cloned from places other than GitHub and
<ide> using protocols other than HTTPS, e.g. SSH, git, HTTP, FTP(S), rsync.
<ide> EOS
<del> # odeprecated "brew tap --full"
<ide> switch "--full",
<ide> description: "Convert a shallow clone to a full clone without untapping. Taps are only cloned as "\
<ide> "shallow clones if `--shallow` was originally passed." | 1 |
Go | Go | remove unused imports | e7ee2f443ad93803e8312bc224da618d555aebdc | <ide><path>term/term.go
<ide> package term
<ide>
<ide> import (
<del> "fmt"
<del> "io"
<ide> "os"
<ide> "os/signal"
<ide> "syscall" | 1 |
Java | Java | fix typo in javadoc | 0705454ce012b6390ba50744f59a98223c0464a6 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/PathMatchConfigurer.java
<ide> public PathMatchConfigurer addPathPrefix(String prefix, Predicate<Class<?>> pred
<ide> /**
<ide> * Whether to use suffix pattern match (".*") when matching patterns to
<ide> * requests. If enabled a method mapped to "/users" also matches to "/users.*".
<del> * <p>By default this is set to {@code true}.
<add> * <p>By default this is set to {@code false}.
<ide> * <p><strong>Note:</strong> This property is mutually exclusive with and
<ide> * ignored when {@link #setPatternParser(PathPatternParser)} is set.
<ide> * @deprecated as of 5.2.4. See class-level note in | 1 |
Python | Python | fix mixture weights in fine_tune | 62594903478a5be5b8c9c0a77624cd83ef8efc2d | <ide><path>spacy/_ml.py
<ide> def fine_tune_fwd(docs_tokvecs, drop=0.):
<ide> vecs, bp_vecs = embedding.begin_update(docs, drop=drop)
<ide> flat_tokvecs = embedding.ops.flatten(tokvecs)
<ide> flat_vecs = embedding.ops.flatten(vecs)
<add> alpha = model.mix
<add> minus = 1-model.mix
<ide> output = embedding.ops.unflatten(
<del> (model.mix[0] * flat_vecs + model.mix[1] * flat_tokvecs),
<del> lengths)
<add> (alpha * flat_tokvecs + minus * flat_vecs), lengths)
<ide>
<ide> def fine_tune_bwd(d_output, sgd=None):
<del> bp_vecs([d_o * model.d_mix[0] for d_o in d_output], sgd=sgd)
<ide> flat_grad = model.ops.flatten(d_output)
<del> model.d_mix[1] += flat_tokvecs.dot(flat_grad.T).sum()
<del> model.d_mix[0] += flat_vecs.dot(flat_grad.T).sum()
<add> model.d_mix += flat_tokvecs.dot(flat_grad.T).sum()
<add> model.d_mix += 1-flat_vecs.dot(flat_grad.T).sum()
<add>
<add> bp_vecs([d_o * minus for d_o in d_output], sgd=sgd)
<add> d_output = [d_o * alpha for d_o in d_output]
<ide> sgd(model._mem.weights, model._mem.gradient, key=model.id)
<del> return [d_o * model.d_mix[1] for d_o in d_output]
<add> model.mix = model.ops.xp.minimum(model.mix, 1.0)
<add> return d_output
<ide> return output, fine_tune_bwd
<ide> model = wrap(fine_tune_fwd, embedding)
<del> model.mix = model._mem.add((model.id, 'mix'), (2,))
<del> model.mix.fill(0.5)
<add> model.mix = model._mem.add((model.id, 'mix'), (1,))
<add> model.mix.fill(0.0)
<ide> model.d_mix = model._mem.add_gradient((model.id, 'd_mix'), (model.id, 'mix'))
<ide> return model
<ide> | 1 |
Javascript | Javascript | add ordinal test | b60d42bd1c1fdbe84a456d644c9e82440f23b8af | <ide><path>test/lang/km.js
<ide> exports["lang:km"] = {
<ide> test.done();
<ide> },
<ide>
<add> "format ordinal": function (test) {
<add> test.expect(31);
<add> test.equal(moment([2011, 0, 1]).format('DDDo'), '1', '1st');
<add> test.equal(moment([2011, 0, 2]).format('DDDo'), '2', '2nd');
<add> test.equal(moment([2011, 0, 3]).format('DDDo'), '3', '3rd');
<add> test.equal(moment([2011, 0, 4]).format('DDDo'), '4', '4th');
<add> test.equal(moment([2011, 0, 5]).format('DDDo'), '5', '5th');
<add> test.equal(moment([2011, 0, 6]).format('DDDo'), '6', '6th');
<add> test.equal(moment([2011, 0, 7]).format('DDDo'), '7', '7th');
<add> test.equal(moment([2011, 0, 8]).format('DDDo'), '8', '8th');
<add> test.equal(moment([2011, 0, 9]).format('DDDo'), '9', '9th');
<add> test.equal(moment([2011, 0, 10]).format('DDDo'), '10', '10th');
<add>
<add> test.equal(moment([2011, 0, 11]).format('DDDo'), '11', '11th');
<add> test.equal(moment([2011, 0, 12]).format('DDDo'), '12', '12th');
<add> test.equal(moment([2011, 0, 13]).format('DDDo'), '13', '13th');
<add> test.equal(moment([2011, 0, 14]).format('DDDo'), '14', '14th');
<add> test.equal(moment([2011, 0, 15]).format('DDDo'), '15', '15th');
<add> test.equal(moment([2011, 0, 16]).format('DDDo'), '16', '16th');
<add> test.equal(moment([2011, 0, 17]).format('DDDo'), '17', '17th');
<add> test.equal(moment([2011, 0, 18]).format('DDDo'), '18', '18th');
<add> test.equal(moment([2011, 0, 19]).format('DDDo'), '19', '19th');
<add> test.equal(moment([2011, 0, 20]).format('DDDo'), '20', '20th');
<add>
<add> test.equal(moment([2011, 0, 21]).format('DDDo'), '21', '21st');
<add> test.equal(moment([2011, 0, 22]).format('DDDo'), '22', '22nd');
<add> test.equal(moment([2011, 0, 23]).format('DDDo'), '23', '23rd');
<add> test.equal(moment([2011, 0, 24]).format('DDDo'), '24', '24th');
<add> test.equal(moment([2011, 0, 25]).format('DDDo'), '25', '25th');
<add> test.equal(moment([2011, 0, 26]).format('DDDo'), '26', '26th');
<add> test.equal(moment([2011, 0, 27]).format('DDDo'), '27', '27th');
<add> test.equal(moment([2011, 0, 28]).format('DDDo'), '28', '28th');
<add> test.equal(moment([2011, 0, 29]).format('DDDo'), '29', '29th');
<add> test.equal(moment([2011, 0, 30]).format('DDDo'), '30', '30th');
<add>
<add> test.equal(moment([2011, 0, 31]).format('DDDo'), '31', '31st');
<add> test.done();
<add> },
<add>
<ide> "format month": function (test) {
<ide> test.expect(12);
<ide> var expected = 'មករា មករា_កុម្ភៈ កុម្ភៈ_មិនា មិនា_មេសា មេសា_ឧសភា ឧសភា_មិថុនា មិថុនា_កក្កដា កក្កដា_សីហា សីហា_កញ្ញា កញ្ញា_តុលា តុលា_វិច្ឆិកា វិច្ឆិកា_ធ្នូ ធ្នូ'.split("_"), | 1 |
Javascript | Javascript | remove unused local variable 'child' in bone.js | c8cfa5d6344aa0e097ad45e1fffe2bba8ebe3c2e | <ide><path>src/objects/Bone.js
<ide> THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
<ide>
<ide> // update children
<ide>
<del> var child, i, l = this.children.length;
<add> var i, l = this.children.length;
<ide>
<ide> for ( i = 0; i < l; i ++ ) {
<ide> | 1 |
Ruby | Ruby | remove tags_only_debian logic | 64a7c1f8213558f9aeaaa751492297e75463f656 | <ide><path>Library/Homebrew/livecheck/strategy/git.rb
<ide> def self.versions_from_tags(tags, regex = nil, &block)
<ide> return Strategy.handle_block_return(block_return_value)
<ide> end
<ide>
<del> tags_only_debian = tags.all? { |tag| tag.start_with?("debian/") }
<del>
<ide> tags.map do |tag|
<del> # Skip tag if it has a 'debian/' prefix and upstream does not do
<del> # only 'debian/' prefixed tags
<del> next if tag =~ %r{^debian/} && !tags_only_debian
<del>
<ide> if regex
<ide> # Use the first capture group (the version)
<ide> tag.scan(regex).first&.first | 1 |
Java | Java | use try-with-resource in scriptutils | b4cf88499c36c5120da9596e2785895a3d2a512d | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/ScriptUtils.java
<ide> static String readScript(EncodedResource resource) throws IOException {
<ide> private static String readScript(EncodedResource resource, @Nullable String[] commentPrefixes,
<ide> @Nullable String separator, @Nullable String blockCommentEndDelimiter) throws IOException {
<ide>
<del> LineNumberReader lnr = new LineNumberReader(resource.getReader());
<del> try {
<add> try (LineNumberReader lnr = new LineNumberReader(resource.getReader())) {
<ide> return readScript(lnr, commentPrefixes, separator, blockCommentEndDelimiter);
<ide> }
<del> finally {
<del> lnr.close();
<del> }
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | fix grammatical errors in readme.md | 23716d448757254fc6c9c4451ea189b17e0ac17e | <ide><path>readme.md
<ide> The second `as` parameter for `push` and `replace` is an optional _decoration_ o
<ide> _Note: in order to programmatically change the route without triggering navigation and component-fetching, use `props.url.push` and `props.url.replace` within a component_
<ide>
<ide> ##### With URL object
<del>You can use an URL object the same way you use it in a `<Link>` component to `push` and `replace` an url.
<add>You can use an URL object the same way you use it in a `<Link>` component to `push` and `replace` an URL.
<ide>
<ide> ```jsx
<ide> import Router from 'next/router'
<ide> export default () =>
<ide> </div>
<ide> ```
<ide>
<del>This uses of the same exact parameters as in the `<Link>` component.
<add>This uses the same exact parameters as in the `<Link>` component.
<ide>
<ide> ##### Router Events
<ide> | 1 |
Ruby | Ruby | change function name | 7be216fcbec3021df87fb37b17bbbd91202af6f5 | <ide><path>Library/Homebrew/cli/args.rb
<ide> def context
<ide> Context::ContextStruct.new(debug: debug?, quiet: quiet?, verbose: verbose?)
<ide> end
<ide>
<del> def only_path_formula_or_cask
<add> def only_formula_or_cask
<ide> return :formula if formula? && !cask?
<ide> return :cask if cask? && !formula?
<ide> end
<ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def fetch
<ide> end
<ide> end
<ide> else
<del> args.named.to_formulae_and_casks(only: args.only_path_formula_or_cask)
<add> args.named.to_formulae_and_casks(only: args.only_formula_or_cask)
<ide> end.uniq
<ide>
<ide> puts "Fetching: #{bucket * ", "}" if bucket.size > 1
<ide><path>Library/Homebrew/cmd/home.rb
<ide> def home
<ide> return
<ide> end
<ide>
<del> homepages = args.named.to_formulae_and_casks(only: args.only_path_formula_or_cask).map do |formula_or_cask|
<add> homepages = args.named.to_formulae_and_casks(only: args.only_formula_or_cask).map do |formula_or_cask|
<ide> puts "Opening homepage for #{name_of(formula_or_cask)}"
<ide> formula_or_cask.homepage
<ide> end
<ide><path>Library/Homebrew/cmd/info.rb
<ide> def info
<ide> end
<ide> end
<ide>
<del> print_analytics(args: args, only: args.only_path_formula_or_cask)
<add> print_analytics(args: args, only: args.only_formula_or_cask)
<ide> elsif args.json
<del> print_json(args: args, only: args.only_path_formula_or_cask)
<add> print_json(args: args, only: args.only_formula_or_cask)
<ide> elsif args.github?
<ide> raise FormulaOrCaskUnspecifiedError if args.no_named?
<ide>
<del> exec_browser(*args.named.to_formulae_and_casks(only: args.only_path_formula_or_cask).map { |f| github_info(f) })
<add> exec_browser(*args.named.to_formulae_and_casks(only: args.only_formula_or_cask).map { |f| github_info(f) })
<ide> elsif args.no_named?
<ide> print_statistics
<ide> else
<del> print_info(args: args, only: args.only_path_formula_or_cask)
<add> print_info(args: args, only: args.only_formula_or_cask)
<ide> end
<ide> end
<ide>
<ide> def print_analytics(args:, only: nil)
<ide> return
<ide> end
<ide>
<del> args.named.to_formulae_and_casks_and_unavailable(only: args.only_path_formula_or_cask).each_with_index do |obj, i|
<add> args.named.to_formulae_and_casks_and_unavailable(only: args.only_formula_or_cask).each_with_index do |obj, i|
<ide> puts unless i.zero?
<ide>
<ide> case obj
<ide> def print_analytics(args:, only: nil)
<ide>
<ide> sig { params(args: CLI::Args, only: T.nilable(Symbol)).void }
<ide> def print_info(args:, only: nil)
<del> args.named.to_formulae_and_casks_and_unavailable(only: args.only_path_formula_or_cask).each_with_index do |obj, i|
<add> args.named.to_formulae_and_casks_and_unavailable(only: args.only_formula_or_cask).each_with_index do |obj, i|
<ide> puts unless i.zero?
<ide>
<ide> case obj
<ide> def print_json(args:, only: nil)
<ide> elsif args.installed?
<ide> [Formula.installed.sort, Cask::Caskroom.casks.sort_by(&:full_name)]
<ide> else
<del> args.named.to_formulae_to_casks(only: args.only_path_formula_or_cask)
<add> args.named.to_formulae_to_casks(only: args.only_formula_or_cask)
<ide> end
<ide>
<ide> {
<ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> EOS
<ide> end
<ide>
<del> formulae, casks = args.named.to_formulae_and_casks(only: args.only_path_formula_or_cask)
<add> formulae, casks = args.named.to_formulae_and_casks(only: args.only_formula_or_cask)
<ide> .partition { |formula_or_cask| formula_or_cask.is_a?(Formula) }
<ide>
<ide> if casks.any?
<ide><path>Library/Homebrew/cmd/uninstall.rb
<ide> def uninstall
<ide> args = uninstall_args.parse
<ide>
<ide> all_kegs, casks = args.named.to_kegs_to_casks(
<del> only: args.only_path_formula_or_cask,
<add> only: args.only_formula_or_cask,
<ide> ignore_unavailable: args.force?,
<ide> all_kegs: args.force?,
<ide> )
<ide><path>Library/Homebrew/cmd/upgrade.rb
<ide> def upgrade_args
<ide> def upgrade
<ide> args = upgrade_args.parse
<ide>
<del> formulae, casks = args.named.to_resolved_formulae_to_casks(only: args.only_path_formula_or_cask)
<add> formulae, casks = args.named.to_resolved_formulae_to_casks(only: args.only_formula_or_cask)
<ide> # If one or more formulae are specified, but no casks were
<ide> # specified, we want to make note of that so we don't
<ide> # try to upgrade all outdated casks.
<ide><path>Library/Homebrew/dev-cmd/audit.rb
<ide> def audit
<ide> elsif args.no_named?
<ide> [Formula, Cask::Cask.to_a]
<ide> else
<del> args.named.to_formulae_and_casks(only: args.only_path_formula_or_cask)
<add> args.named.to_formulae_and_casks(only: args.only_formula_or_cask)
<ide> .partition { |formula_or_cask| formula_or_cask.is_a?(Formula) }
<ide> end
<ide> style_files = args.named.to_paths unless skip_style
<ide><path>Library/Homebrew/dev-cmd/cat.rb
<ide> def cat
<ide> "cat"
<ide> end
<ide>
<del> safe_system pager, args.named.to_paths(only: args.only_path_formula_or_cask).first
<add> safe_system pager, args.named.to_paths(only: args.only_formula_or_cask).first
<ide> end
<ide> end
<ide><path>Library/Homebrew/dev-cmd/edit.rb
<ide> def edit
<ide> EOS
<ide> end
<ide>
<del> paths = args.named.to_paths(only: args.only_path_formula_or_cask).select do |path|
<add> paths = args.named.to_paths(only: args.only_formula_or_cask).select do |path|
<ide> next path if path.exist?
<ide>
<ide> raise UsageError, "#{path} doesn't exist on disk. " \ | 10 |
Go | Go | add docker import test with a tag. fixes | 7e72ed70f9cac871b845bebef0f96178c0f1a25c | <ide><path>integration-cli/docker_cli_export_import_test.go
<ide> func TestExportContainerAndImportImage(t *testing.T) {
<ide> out, _, err = runCommandWithOutput(exportCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to export container: %v %v", out, err))
<ide>
<del> importCmdFinal := `cat /tmp/testexp.tar | docker import - testexp`
<add> importCmdFinal := `cat /tmp/testexp.tar | docker import - repo/testexp:v1`
<ide> importCmd := exec.Command("bash", "-c", importCmdFinal)
<ide> out, _, err = runCommandWithOutput(importCmd)
<ide> errorOut(err, t, fmt.Sprintf("failed to import image: %v %v", out, err))
<ide> func TestExportContainerAndImportImage(t *testing.T) {
<ide> errorOut(err, t, fmt.Sprintf("output should've been an image id: %v %v", out, err))
<ide>
<ide> deleteContainer(cleanedContainerID)
<del> deleteImages("testexp")
<add> deleteImages("repo/testexp:v1")
<ide>
<ide> os.Remove("/tmp/testexp.tar")
<ide> | 1 |
Javascript | Javascript | add stub for the last piece of the puzzle | 315071ca28ab1bdba6f1a27558f507f41a48d962 | <ide><path>src/core.js
<ide> function getPdf(arg, callback) {
<ide> params = { url: arg };
<ide>
<ide> var xhr = new XMLHttpRequest();
<add>
<add> if(params.headers){
<add> //TODO: Code this, use xhr.setRequestHeader(key, value);
<add> }
<add>
<ide> xhr.open('GET', params.url);
<ide> xhr.mozResponseType = xhr.responseType = 'arraybuffer';
<ide> var protocol = params.url.indexOf(':') < 0 ? window.location.protocol : | 1 |
PHP | PHP | fix bug in ioc | 9d1d48fb4fd87d48b4da7905a152b12a7e5af05b | <ide><path>laravel/ioc.php
<ide> class IoC {
<ide> * @param bool $singleton
<ide> * @return void
<ide> */
<del> public static function register($name, $resolver, $singleton = false)
<add> public static function register($name, $resolver = null, $singleton = false)
<ide> {
<add> if (is_null($resolver)) $resolver = $name;
<add>
<ide> static::$registry[$name] = compact('resolver', 'singleton');
<ide> }
<ide>
<ide> public static function registered($name)
<ide> * @param Closure $resolver
<ide> * @return void
<ide> */
<del> public static function singleton($name, $resolver)
<add> public static function singleton($name, $resolver = null)
<ide> {
<ide> static::register($name, $resolver, true);
<ide> } | 1 |
Text | Text | add branding to style guide | 7b09f5b14f11d4e362e8e84560e483d6b29d73d2 | <ide><path>doc/STYLE_GUIDE.md
<ide> <!--lint disable prohibited-strings remark-lint-->
<ide> * NOT OK: Javascript, Google's v8
<ide> <!-- lint enable prohibited-strings remark-lint-->
<add>* Use _Node.js_ and not _Node_, _NodeJS_, or similar variants.
<add> * When referring to the executable, _`node`_ is acceptable.
<ide>
<ide> See also API documentation structure overview in [doctools README][].
<ide> | 1 |
Javascript | Javascript | add new&old val to the infinite $digest log | b00da987a9e0e4378d8252add8e15ad2e508901d | <ide><path>src/service/scope.js
<ide> function $RootScopeProvider(){
<ide> length,
<ide> dirty, ttl = 100,
<ide> next, current, target = this,
<del> watchLog = [];
<add> watchLog = [],
<add> logIdx, logMsg;
<ide>
<ide> if (target.$$phase) {
<ide> throw Error(target.$$phase + ' already in progress');
<ide> function $RootScopeProvider(){
<ide> watch.last = copy(value);
<ide> watch.fn(current, value, ((last === initWatchVal) ? value : last));
<ide> if (ttl < 5) {
<del> if (!watchLog[4-ttl]) watchLog[4-ttl] = [];
<del> if (isFunction(watch.exp)) {
<del> watchLog[4-ttl].push('fn: ' + (watch.exp.name || watch.exp.toString()));
<del> } else {
<del> watchLog[4-ttl].push(watch.exp);
<del> }
<add> logIdx = 4-ttl;
<add> if (!watchLog[logIdx]) watchLog[logIdx] = [];
<add> logMsg = (isFunction(watch.exp))
<add> ? 'fn: ' + (watch.exp.name || watch.exp.toString())
<add> : watch.exp;
<add> logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
<add> watchLog[logIdx].push(logMsg);
<ide> }
<ide> }
<ide> } catch (e) {
<ide><path>test/service/scopeSpec.js
<ide> describe('Scope', function() {
<ide> $rootScope.$digest();
<ide> }).toThrow('100 $digest() iterations reached. Aborting!\n'+
<ide> 'Watchers fired in the last 5 iterations: ' +
<del> '[["a","b"],["a","b"],["a","b"],["a","b"],["a","b"]]');
<add> '[["a; newVal: 96; oldVal: 95","b; newVal: 97; oldVal: 96"],' +
<add> '["a; newVal: 97; oldVal: 96","b; newVal: 98; oldVal: 97"],' +
<add> '["a; newVal: 98; oldVal: 97","b; newVal: 99; oldVal: 98"],' +
<add> '["a; newVal: 99; oldVal: 98","b; newVal: 100; oldVal: 99"],' +
<add> '["a; newVal: 100; oldVal: 99","b; newVal: 101; oldVal: 100"]]');
<ide> }));
<ide>
<ide> | 2 |
Python | Python | add checkpoint links in a few config classes | 803475fb69097e802985eb4f85b52199c66a52de | <ide><path>src/transformers/models/clip/configuration_clip.py
<ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike],
<ide> class CLIPConfig(PretrainedConfig):
<ide> r"""
<ide> [`CLIPConfig`] is the configuration class to store the configuration of a [`CLIPModel`]. It is used to instantiate
<del> CLIP model according to the specified arguments, defining the text model and vision model configs.
<add> CLIP model according to the specified arguments, defining the text model and vision model configs. Instantiating a
<add> configuration with the defaults will yield a similar configuration to that of the CLIP
<add> [openai/clip-vit-base-patch32](https://huggingface.co/openai/clip-vit-base-patch32) architecture.
<ide>
<ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
<ide> documentation from [`PretrainedConfig`] for more information.
<ide><path>src/transformers/models/groupvit/configuration_groupvit.py
<ide> class GroupViTConfig(PretrainedConfig):
<ide> r"""
<ide> [`GroupViTConfig`] is the configuration class to store the configuration of a [`GroupViTModel`]. It is used to
<ide> instantiate a GroupViT model according to the specified arguments, defining the text model and vision model
<del> configs.
<add> configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the GroupViT
<add> [nvidia/groupvit-gcc-yfcc](https://huggingface.co/nvidia/groupvit-gcc-yfcc) architecture.
<ide>
<ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
<ide> documentation from [`PretrainedConfig`] for more information.
<ide><path>src/transformers/models/owlvit/configuration_owlvit.py
<ide> class OwlViTConfig(PretrainedConfig):
<ide> r"""
<ide> [`OwlViTConfig`] is the configuration class to store the configuration of an [`OwlViTModel`]. It is used to
<ide> instantiate an OWL-ViT model according to the specified arguments, defining the text model and vision model
<del> configs.
<add> configs. Instantiating a configuration with the defaults will yield a similar configuration to that of the OWL-ViT
<add> [google/owlvit-base-patch32](https://huggingface.co/google/owlvit-base-patch32) architecture.
<ide>
<ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
<ide> documentation from [`PretrainedConfig`] for more information.
<ide><path>src/transformers/models/x_clip/configuration_x_clip.py
<ide> class XCLIPConfig(PretrainedConfig):
<ide> r"""
<ide> [`XCLIPConfig`] is the configuration class to store the configuration of a [`XCLIPModel`]. It is used to
<ide> instantiate X-CLIP model according to the specified arguments, defining the text model and vision model configs.
<add> Instantiating a configuration with the defaults will yield a similar configuration to that of the X-CLIP
<add> [microsoft/xclip-base-patch32](https://huggingface.co/microsoft/xclip-base-patch32) architecture.
<ide>
<ide> Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
<ide> documentation from [`PretrainedConfig`] for more information.
<ide><path>utils/check_config_docstrings.py
<ide>
<ide>
<ide> CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK = {
<del> "CLIPConfig",
<del> "OwlViTConfig",
<del> "GroupViTConfig",
<ide> "DecisionTransformerConfig",
<ide> "EncoderDecoderConfig",
<ide> "RagConfig",
<ide> "SpeechEncoderDecoderConfig",
<ide> "VisionEncoderDecoderConfig",
<ide> "VisionTextDualEncoderConfig",
<del> "XCLIPConfig",
<ide> }
<ide>
<ide> | 5 |
Python | Python | update serving_output for some tf models | 258480864d3b5771ab07800912515bc1e859b7a3 | <ide><path>src/transformers/models/led/modeling_tf_led.py
<ide> def serving_output(self, output):
<ide> pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
<ide> dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
<ide> dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
<add> cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
<ide> enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
<ide> enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
<ide> enc_g_attns = tf.convert_to_tensor(output.encoder_global_attentions) if self.config.output_attentions else None
<ide> def serving_output(self, output):
<ide> past_key_values=pkv,
<ide> decoder_hidden_states=dec_hs,
<ide> decoder_attentions=dec_attns,
<add> cross_attentions=cross_attns,
<ide> encoder_last_hidden_state=output.encoder_last_hidden_state,
<ide> encoder_hidden_states=enc_hs,
<ide> encoder_attentions=enc_attns,
<ide> def call(
<ide> past_key_values=outputs.past_key_values, # index 1 of d outputs
<ide> decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
<ide> decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
<del> cross_attentions=outputs.cross_attentions,
<add> cross_attentions=outputs.cross_attentions, # index 4 of d outputs
<ide> encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
<ide> encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
<ide> encoder_attentions=outputs.encoder_attentions, # 2 of e out
<ide> def serving_output(self, output):
<ide> pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
<ide> dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
<ide> dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
<add> cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
<ide> enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
<ide> enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
<ide> enc_g_attns = tf.convert_to_tensor(output.encoder_global_attentions) if self.config.output_attentions else None
<ide> def serving_output(self, output):
<ide> past_key_values=pkv,
<ide> decoder_hidden_states=dec_hs,
<ide> decoder_attentions=dec_attns,
<add> cross_attentions=cross_attns,
<ide> encoder_last_hidden_state=output.encoder_last_hidden_state,
<ide> encoder_hidden_states=enc_hs,
<ide> encoder_attentions=enc_attns,
<ide><path>src/transformers/models/t5/modeling_tf_t5.py
<ide> def serving_output(self, output):
<ide> pkv = tf.convert_to_tensor(output.past_key_values[1:]) if self.config.use_cache else None
<ide> dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
<ide> dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
<add> cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
<ide> enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
<ide> enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
<ide>
<ide> def serving_output(self, output):
<ide> decoder_hidden_states=dec_hs,
<ide> decoder_attentions=dec_attns,
<ide> encoder_last_hidden_state=output.encoder_last_hidden_state,
<add> cross_attentions=cross_attns,
<ide> encoder_hidden_states=enc_hs,
<ide> encoder_attentions=enc_attns,
<ide> )
<ide> def serving_output(self, output):
<ide> pkv = tf.convert_to_tensor(output.past_key_values[1:]) if self.config.use_cache else None
<ide> dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
<ide> dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
<add> cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
<ide> enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
<ide> enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
<ide>
<ide> def serving_output(self, output):
<ide> past_key_values=pkv,
<ide> decoder_hidden_states=dec_hs,
<ide> decoder_attentions=dec_attns,
<add> cross_attentions=cross_attns,
<ide> encoder_last_hidden_state=output.encoder_last_hidden_state,
<ide> encoder_hidden_states=enc_hs,
<ide> encoder_attentions=enc_attns,
<ide><path>src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py
<ide> def serving_output(self, output):
<ide> hs = tf.convert_to_tensor(output.hidden_states) if self.config.output_hidden_states else None
<ide> attns = tf.convert_to_tensor(output.attentions) if self.config.output_attentions else None
<ide>
<del> return TFBaseModelOutput(last_hidden_state=output.last_hidden_state, hidden_states=hs, attentions=attns)
<add> return TFWav2Vec2BaseModelOutput(
<add> last_hidden_state=output.last_hidden_state,
<add> extract_features=output.extract_features,
<add> hidden_states=hs,
<add> attentions=attns,
<add> )
<ide>
<ide>
<ide> @add_start_docstrings( | 3 |
Javascript | Javascript | fix typo in player.js | 9ca2e8764a2cced1efdad730b8c66c4b42a33f7f | <ide><path>src/js/player.js
<ide> class Player extends Component {
<ide> /**
<ide> * The player's language code.
<ide> *
<del> * Changing the langauge will trigger
<add> * Changing the language will trigger
<ide> * [languagechange]{@link Player#event:languagechange}
<ide> * which Components can use to update control text.
<ide> * ClickableComponent will update its control text by default on | 1 |
Ruby | Ruby | fix syntax error on ruby 2.0 | 9a43816928f07c4ed988fb47545d219eff55e28a | <ide><path>activesupport/lib/active_support/json/encoding.rb
<add>#encoding: us-ascii
<add>
<ide> require 'active_support/core_ext/object/to_json'
<ide> require 'active_support/core_ext/module/delegation'
<ide> require 'active_support/json/variable'
<ide> class << self
<ide> def escape_html_entities_in_json=(value)
<ide> self.escape_regex = \
<ide> if @escape_html_entities_in_json = value
<del> /\xe2\x80(\xa8|\xa9)|[\x00-\x1F"\\><&]/
<add> /\xe2\x80\xa8|\xe2\x80\xa9|[\x00-\x1F"\\><&]/
<ide> else
<del> /\xe2\x80(\xa8|\xa9)|[\x00-\x1F"\\]/
<add> /\xe2\x80\xa8|\xe2\x80\xa9|[\x00-\x1F"\\]/
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | fix use order | b6b0f15da52d3075b2c873bc3a38f102c2541fca | <ide><path>Cake/Test/TestCase/View/Helper/StringTemplateTraitTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\View\Helper;
<ide>
<del>use Cake\View\Helper\StringTemplateTrait;
<ide> use Cake\View\Helper\StringTemplate;
<add>use Cake\View\Helper\StringTemplateTrait;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> /** | 1 |
PHP | PHP | add stringable support for isuuid | bc1188d74d434ea2b8e9e7f60642cbc67f85956a | <ide><path>src/Illuminate/Support/Stringable.php
<ide> public function isAscii()
<ide> return Str::isAscii($this->value);
<ide> }
<ide>
<add> /**
<add> * Determine if a given string is a valid UUID.
<add> *
<add> * @return bool
<add> */
<add> public function isUuid()
<add> {
<add> return Str::isUuid($this->value);
<add> }
<add>
<ide> /**
<ide> * Determine if the given string is empty.
<ide> *
<ide><path>tests/Support/SupportStringableTest.php
<ide> public function testIsAscii()
<ide> $this->assertFalse($this->stringable('ù')->isAscii());
<ide> }
<ide>
<add> public function testIsUuid()
<add> {
<add> $this->assertTrue($this->stringable('2cdc7039-65a6-4ac7-8e5d-d554a98e7b15')->isUuid());
<add> $this->assertFalse($this->stringable('2cdc7039-65a6-4ac7-8e5d-d554a98')->isUuid());
<add> }
<add>
<ide> public function testIsEmpty()
<ide> {
<ide> $this->assertTrue($this->stringable('')->isEmpty()); | 2 |
Text | Text | add tip to detect wrong hook imports with eslint | 4335097c22bf741af0b5826253499765ba77cb79 | <ide><path>docs/usage/UsageWithTypescript.md
<ide> export function Counter() {
<ide> }
<ide> ```
<ide>
<add>:::tip Warn about wrong imports
<add>
<add>ESLint can help your team import the right hooks easily. The [typescript-eslint/no-restricted-imports](https://github.com/typescript-eslint/typescript-eslint/blob/main/packages/eslint-plugin/docs/rules/no-restricted-imports.md) rule can show a warning when the wrong import is used accidentally.
<add>
<add>You could add this to your ESLint config as an example:
<add>
<add>```json
<add>"no-restricted-imports": "off",
<add>"@typescript-eslint/no-restricted-imports": [
<add> "warn",
<add> {
<add> "name": "react-redux",
<add> "importNames": ["useSelector", "useDispatch"],
<add> "message": "Use typed hooks `useAppDispatch` and `useAppSelector` instead."
<add> }
<add>],
<add>```
<add>
<add>:::
<add>
<ide> ## Typing Additional Redux Logic
<ide>
<ide> ### Type Checking Reducers | 1 |
Javascript | Javascript | hoist the deprecate function | ba90a1d20e0567ed1e956a334a6c5f3b397fa973 | <ide><path>lib/ExternalModuleFactoryPlugin.js
<ide> const util = require("util");
<ide> const ExternalModule = require("./ExternalModule");
<ide> const UNSPECIFIED_EXTERNAL_TYPE_REGEXP = /^[a-z0-9]+ /;
<ide>
<add>// TODO webpack 6 remove this
<add>const callDeprecatedExternals = util.deprecate(
<add> (externalsFunction, context, request, cb) => {
<add> externalsFunction.call(null, context, request, cb);
<add> },
<add> "The externals-function should be defined like ({context, request}, cb) => { ... }",
<add> "DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS"
<add>);
<add>
<ide> class ExternalModuleFactoryPlugin {
<ide> constructor(type, externals) {
<ide> this.type = type;
<ide> class ExternalModuleFactoryPlugin {
<ide> };
<ide> if (externals.length === 3) {
<ide> // TODO webpack 6 remove this
<del> util
<del> .deprecate(
<del> (context, request, cb) => {
<del> externals.call(null, context, dependency.request, cb);
<del> },
<del> "The externals-function should be defined like ({context, request}, cb) => { ... }",
<del> "DEP_WEBPACK_EXTERNALS_FUNCTION_PARAMETERS"
<del> )
<del> .call(null, context, dependency.request, cb);
<add> callDeprecatedExternals(
<add> externals,
<add> context,
<add> dependency.request,
<add> cb
<add> );
<ide> } else {
<ide> externals(
<ide> { | 1 |
Javascript | Javascript | add tests for namespacing and property removal | 2fb6d98ef158d8942c7df4683a927e2a3069731c | <ide><path>test/core/selection-attr-test.js
<ide> suite.addBatch({
<ide> body.attr("bgcolor", function(d, i) { return "orange-" + i; });
<ide> assert.equal(document.body.getAttribute("bgcolor"), "orange-0");
<ide> },
<add> "sets a namespaced attribute as a string": function(body) {
<add> body.attr("xlink:href", "url");
<add> assert.equal(document.body.getAttributeNS("http://www.w3.org/1999/xlink", "href"), "url");
<add> },
<add> "sets a namespaced attribute as a function": function(body) {
<add> body.data(["orange"]).attr("xlink:href", function(d, i) { return d + "-" + i; });
<add> assert.equal(document.body.getAttributeNS("http://www.w3.org/1999/xlink", "href"), "orange-0");
<add> },
<ide> "gets an attribute value": function(body) {
<ide> document.body.setAttribute("bgcolor", "yellow");
<ide> assert.equal(body.attr("bgcolor"), "yellow");
<add> },
<add> "gets a namespaced attribute value": function(body) {
<add> document.body.setAttributeNS("http://www.w3.org/1999/xlink", "foo", "bar");
<add> assert.equal(body.attr("xlink:foo"), "bar");
<add> },
<add> "removes an attribute as null": function(body) {
<add> body.attr("bgcolor", "red").attr("bgcolor", null);
<add> assert.equal(body.attr("bgcolor"), "");
<add> },
<add> "removes an attribute as a function": function(body) {
<add> body.attr("bgcolor", "red").attr("bgcolor", function() { return null; });
<add> assert.equal(body.attr("bgcolor"), "");
<add> },
<add> "removes a namespaced attribute as null": function(body) {
<add> body.attr("xlink:href", "url").attr("xlink:href", null);
<add> assert.equal(body.attr("bgcolor"), "");
<add> },
<add> "removes a namespaced attribute as a function": function(body) {
<add> body.attr("xlink:href", "url").attr("xlink:href", function() { return null; });
<add> assert.equal(body.attr("xlink:href"), "");
<ide> }
<ide> }
<ide> });
<ide> suite.addBatch({
<ide> assert.equal(div[0][0].getAttribute("bgcolor"), "color-0");
<ide> assert.equal(div[0][1].getAttribute("bgcolor"), "color-1");
<ide> },
<add> "sets a namespaced attribute as a string": function(div) {
<add> div.attr("xlink:href", "url");
<add> assert.equal(div[0][0].getAttributeNS("http://www.w3.org/1999/xlink", "href"), "url");
<add> assert.equal(div[0][1].getAttributeNS("http://www.w3.org/1999/xlink", "href"), "url");
<add> },
<add> "sets a namespaced attribute as a function": function(div) {
<add> div.data(["red", "blue"]).attr("xlink:href", function(d, i) { return d + "-" + i; });
<add> assert.equal(div[0][0].getAttributeNS("http://www.w3.org/1999/xlink", "href"), "red-0");
<add> assert.equal(div[0][1].getAttributeNS("http://www.w3.org/1999/xlink", "href"), "blue-1");
<add> },
<ide> "gets an attribute value": function(div) {
<ide> div[0][0].setAttribute("bgcolor", "purple");
<ide> assert.equal(div.attr("bgcolor"), "purple");
<add> },
<add> "gets a namespaced attribute value": function(div) {
<add> div[0][0].setAttributeNS("http://www.w3.org/1999/xlink", "foo", "bar");
<add> assert.equal(div.attr("xlink:foo"), "bar");
<add> },
<add> "removes an attribute as null": function(div) {
<add> div.attr("href", "url").attr("href", null);
<add> assert.equal(div[0][0].getAttribute("href"), "");
<add> assert.equal(div[0][1].getAttribute("href"), "");
<add> },
<add> "removes an attribute as a function": function(div) {
<add> div.attr("href", "url").attr("href", function() { return null; });
<add> assert.equal(div[0][0].getAttribute("href"), "");
<add> assert.equal(div[0][1].getAttribute("href"), "");
<add> },
<add> "removes a namespaced attribute as null": function(div) {
<add> div.attr("xlink:foo", "bar").attr("xlink:foo", null);
<add> assert.equal(div[0][0].getAttributeNS("http://www.w3.org/1999/xlink", "foo"), "");
<add> assert.equal(div[0][1].getAttributeNS("http://www.w3.org/1999/xlink", "foo"), "");
<add> },
<add> "removes a namespaced attribute as a function": function(div) {
<add> div.attr("xlink:foo", "bar").attr("xlink:foo", function() { return null; });
<add> assert.equal(div[0][0].getAttributeNS("http://www.w3.org/1999/xlink", "foo"), "");
<add> assert.equal(div[0][1].getAttributeNS("http://www.w3.org/1999/xlink", "foo"), "");
<ide> }
<ide> }
<ide> });
<ide><path>test/core/selection-property-test.js
<ide> suite.addBatch({
<ide> "gets a property value": function(body) {
<ide> document.body.bgcolor = "yellow";
<ide> assert.equal(body.property("bgcolor"), "yellow");
<add> },
<add> "removes a property as null": function(body) {
<add> body.property("bgcolor", "yellow").property("bgcolor", null);
<add> assert.isFalse("bgcolor" in document.body);
<add> },
<add> "removes a property as a function": function(body) {
<add> body.property("bgcolor", "yellow").property("bgcolor", function() { return null });
<add> assert.isFalse("bgcolor" in document.body);
<ide> }
<ide> }
<ide> });
<ide> suite.addBatch({
<ide> "gets a property value": function(div) {
<ide> div[0][0].bgcolor = "purple";
<ide> assert.equal(div.property("bgcolor"), "purple");
<add> },
<add> "removes a property as null": function(div) {
<add> div.property("bgcolor", "yellow").property("bgcolor", null);
<add> assert.isFalse("bgcolor" in div[0][0]);
<add> assert.isFalse("bgcolor" in div[0][1]);
<add> },
<add> "removes a property as a function": function(div) {
<add> div.property("bgcolor", "yellow").property("bgcolor", function() { return null });
<add> assert.isFalse("bgcolor" in div[0][0]);
<add> assert.isFalse("bgcolor" in div[0][1]);
<ide> }
<ide> }
<ide> });
<ide><path>test/core/selection-style-test.js
<ide> suite.addBatch({
<ide> "observes the specified priority": function(body) {
<ide> body.style("background-color", "green", "important");
<ide> assert.equal(document.body.style.getPropertyPriority("background-color"), "important");
<add> },
<add> "removes a property as null": function(body) {
<add> body.style("background-color", "green").style("background-color", null);
<add> assert.equal(body.style("background-color"), "");
<add> },
<add> "removes a property as a function": function(body) {
<add> body.style("background-color", "green").style("background-color", function() { return null; });
<add> assert.equal(body.style("background-color"), "");
<ide> }
<ide> }
<ide> });
<ide> suite.addBatch({
<ide> div.style("background-color", "blue", "important");
<ide> assert.equal(div[0][0].style.getPropertyPriority("background-color"), "important");
<ide> assert.equal(div[0][1].style.getPropertyPriority("background-color"), "important");
<add> },
<add> "removes a property as null": function(div) {
<add> div.style("background-color", "red").style("background-color", null);
<add> assert.equal(div[0][0].style["background-color"], "");
<add> assert.equal(div[0][1].style["background-color"], "");
<add> },
<add> "removes a property as a function": function(div) {
<add> div.style("background-color", "red").style("background-color", function() { return null; });
<add> assert.equal(div[0][0].style["background-color"], "");
<add> assert.equal(div[0][1].style["background-color"], "");
<ide> }
<ide> }
<ide> }); | 3 |
Go | Go | remove errant "runtime.goarch" from debug message | 3d71555a4785cfe28f621caf5edf6e729300bc40 | <ide><path>distribution/pull_v2.go
<ide> func (p *puller) pullManifestList(ctx context.Context, ref reference.Named, mfst
<ide> if pp != nil {
<ide> platform = *pp
<ide> }
<del> logrus.Debugf("%s resolved to a manifestList object with %d entries; looking for a %s/%s match", ref, len(mfstList.Manifests), platforms.Format(platform), runtime.GOARCH)
<add> logrus.Debugf("%s resolved to a manifestList object with %d entries; looking for a %s match", ref, len(mfstList.Manifests), platforms.Format(platform))
<ide>
<ide> manifestMatches := filterManifests(mfstList.Manifests, platform)
<ide> | 1 |
Ruby | Ruby | ignore false rubocop positive | 71a79e7e040202c543e54198bc91539c0b7abc01 | <ide><path>Library/Homebrew/utils/formatter.rb
<ide> def pluralize(count, singular, plural = nil, show_count: true)
<ide> end
<ide>
<ide> def comma_and(*items)
<del> *items, last = items.map(&:to_s)
<add> *items, last = items.map(&:to_s) # rubocop:disable Lint/ShadowedArgument, TODO: Remove when RuboCop 0.57.3 is released.
<ide> return last if items.empty?
<ide>
<ide> "#{items.join(", ")} and #{last}" | 1 |
PHP | PHP | fix psalm errors | 285e0ebb941a224f0fdd95af3eb2b9120a925c04 | <ide><path>src/Http/Uri.php
<ide> public function getFragment()
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param string $scheme Scheme value.
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withScheme($scheme)
<ide> {
<del> return $this->uri->withScheme($scheme);
<add> return new static($this->uri->withScheme($scheme), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param string $user User value
<del> * @param string|null $password Password value.
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withUserInfo($user, $password = null)
<ide> {
<del> return $this->uri->withUserInfo($user, $password);
<add> return new static($this->uri->withUserInfo($user, $password), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param string $host Host value.
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withHost($host)
<ide> {
<del> return $this->uri->withHost($host);
<add> return new static($this->uri->withHost($host), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param int $port Port value
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withPort($port)
<ide> {
<del> return $this->uri->withPort($port);
<add> return new static($this->uri->withPort($port), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param string $path Path value
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withPath($path)
<ide> {
<del> return $this->uri->withPath($path);
<add> return new static($this->uri->withPath($path), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param string $query Query value
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withQuery($query)
<ide> {
<del> return $this->uri->withQuery($query);
<add> return new static($this->uri->withQuery($query), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<del> * {@inheritDoc}
<del> *
<del> * @param string $fragment Fragment value
<del> * @return \Psr\Http\Message\UriInterface
<add> * @inheritDoc
<ide> */
<ide> public function withFragment($fragment)
<ide> {
<del> return $this->uri->withFragment($fragment);
<add> return new static($this->uri->withFragment($fragment), $this->base, $this->webroot);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Http/UriTest.php
<ide> public function testWrappedWithMethods()
<ide> $new = $uri->{$method}('value');
<ide> $this->assertNotSame($new, $uri);
<ide> $this->assertNotSame($new, $inner);
<add> $this->assertInstanceOf(Uri::class, $new);
<ide> }
<ide> }
<ide> } | 2 |
PHP | PHP | fix return errors | 276f4f2992cdae6a67fab70a0922d5c1411ae917 | <ide><path>src/Event/Event.php
<ide> public function subject() {
<ide> * @return void
<ide> */
<ide> public function stopPropagation() {
<del> return $this->_stopped = true;
<add> $this->_stopped = true;
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | fix crash in mixed precision stateful rnns | f8add5472995229aaf2f21f8aa1644e72b6a0bda | <ide><path>keras/layers/recurrent.py
<ide> def step(inputs, states):
<ide>
<ide> if self.stateful:
<ide> updates = [
<del> tf.compat.v1.assign(self_state, state) for self_state, state in zip(
<add> tf.compat.v1.assign(self_state, tf.cast(state, self_state.dtype))
<add> for self_state, state in zip(
<ide> tf.nest.flatten(self.states), tf.nest.flatten(states))
<ide> ]
<ide> self.add_update(updates)
<ide> def _process_inputs(self, inputs, initial_state, constants):
<ide> strict=True)
<ide> else:
<ide> initial_state = self.states
<add> initial_state = tf.nest.map_structure(
<add> lambda v: tf.cast(v, self.compute_dtype), initial_state
<add> )
<ide> elif initial_state is None:
<ide> initial_state = self.get_initial_state(inputs)
<ide>
<ide> def reset_states(self, states=None):
<ide> if getattr(self.cell, 'get_initial_state', None):
<ide> flat_init_state_values = tf.nest.flatten(self.cell.get_initial_state(
<ide> inputs=None, batch_size=batch_size,
<del> dtype=self.dtype or backend.floatx()))
<add> # Use variable_dtype instead of compute_dtype, since the state is
<add> # stored in a variable
<add> dtype=self.variable_dtype or backend.floatx()))
<ide> else:
<ide> flat_init_state_values = tf.nest.flatten(_generate_zero_filled_state(
<del> batch_size, self.cell.state_size, self.dtype or backend.floatx()))
<add> batch_size, self.cell.state_size,
<add> self.variable_dtype or backend.floatx()))
<ide> flat_states_variables = tf.nest.map_structure(
<ide> backend.variable, flat_init_state_values)
<ide> self.states = tf.nest.pack_sequence_as(self.cell.state_size,
<ide><path>keras/layers/recurrent_v2.py
<ide> def step(cell_inputs, cell_states):
<ide> inputs, initial_state, training, mask, row_lengths)
<ide>
<ide> if self.stateful:
<del> updates = [tf.compat.v1.assign(self.states[0], states[0])]
<add> updates = [tf.compat.v1.assign(self.states[0],
<add> tf.cast(states[0], self.states[0].dtype))]
<ide> self.add_update(updates)
<ide>
<ide> if self.return_sequences:
<ide> def step(inputs, states):
<ide>
<ide> if self.stateful:
<ide> updates = [
<del> tf.compat.v1.assign(self_state, state)
<add> tf.compat.v1.assign(self_state, tf.cast(state, self_state.dtype))
<ide> for self_state, state in zip(self.states, states)
<ide> ]
<ide> self.add_update(updates)
<ide><path>keras/mixed_precision/layer_correctness_test.py
<ide> def _create_model_from_layer(self, layer, input_shapes):
<ide> ('GlobalAveragePooling2D', pooling.GlobalAveragePooling2D, (2, 2, 2, 1)),
<ide> ('SimpleRNN', lambda: recurrent.SimpleRNN(units=4),
<ide> (4, 4, 4), 1e-2, 1e-2),
<add> ('SimpleRNN_stateful',
<add> lambda: recurrent.SimpleRNN(units=4, stateful=True),
<add> (4, 4, 4), 1e-2, 1e-2),
<ide> ('GRU', lambda: recurrent.GRU(units=4), (4, 4, 4)),
<ide> ('LSTM', lambda: recurrent.LSTM(units=4), (4, 4, 4)),
<ide> ('GRUV2', lambda: recurrent_v2.GRU(units=4), (4, 4, 4)),
<add> ('GRUV2_stateful', lambda: recurrent_v2.GRU(units=4, stateful=True),
<add> (4, 4, 4)),
<ide> ('LSTMV2', lambda: recurrent_v2.LSTM(units=4), (4, 4, 4)),
<add> ('LSTMV2_stateful', lambda: recurrent_v2.LSTM(units=4, stateful=True),
<add> (4, 4, 4)),
<ide> ('TimeDistributed', lambda: wrappers.TimeDistributed(core.Dense(2)),
<ide> (2, 2, 2)),
<ide> ('Bidirectional', | 3 |
Text | Text | update my email address | 91272bce7a5c98829f4a2736def1d684c8f8eb1b | <ide><path>README.md
<ide> For information about the governance of the Node.js project, see
<ide> * [mcollina](https://github.com/mcollina) -
<ide> **Matteo Collina** <matteo.collina@gmail.com> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<del>**Michael Dawson** <michael_dawson@ca.ibm.com> (he/him)
<add>**Michael Dawson** <midawson@redhat.com> (he/him)
<ide> * [mmarchini](https://github.com/mmarchini) -
<ide> **Mary Marchini** <oss@mmarchini.me> (she/her)
<ide> * [MylesBorins](https://github.com/MylesBorins) -
<ide> For information about the governance of the Node.js project, see
<ide> * [mcollina](https://github.com/mcollina) -
<ide> **Matteo Collina** <matteo.collina@gmail.com> (he/him)
<ide> * [mhdawson](https://github.com/mhdawson) -
<del>**Michael Dawson** <michael_dawson@ca.ibm.com> (he/him)
<add>**Michael Dawson** <midawson@redhat.com> (he/him)
<ide> * [mildsunrise](https://github.com/mildsunrise) -
<ide> **Alba Mendez** <me@alba.sh> (she/her)
<ide> * [misterdjules](https://github.com/misterdjules) - | 1 |
Text | Text | add readme files 2/8 | 6314195bb1e6001ddd0a11a59c41f1d0b9eeb722 | <ide><path>cellular_automata/README.md
<ide> # Cellular Automata
<ide>
<del>* https://en.wikipedia.org/wiki/Cellular_automaton
<del>* https://mathworld.wolfram.com/ElementaryCellularAutomaton.html
<add>Cellular automata are a way to simulate the behavior of "life", no matter if it is a robot or cell.
<add>They usually follow simple rules but can lead to the creation of complex forms.
<add>The most popular cellular automaton is Conway's [Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life).
<add>
<add>* <https://en.wikipedia.org/wiki/Cellular_automaton>
<add>* <https://mathworld.wolfram.com/ElementaryCellularAutomaton.html>
<ide><path>ciphers/README.md
<add># Ciphers
<add>
<add>Ciphers are used to protect data from people that are not allowed to have it. They are everywhere on the internet to protect your connections.
<add>
<add>* <https://en.wikipedia.org/wiki/Cipher>
<add>* <http://practicalcryptography.com/ciphers/>
<add>* <https://practicalcryptography.com/ciphers/classical-era/>
<ide><path>compression/README.md
<add># Compression
<add>
<add>Data compression is everywhere, you need it to store data without taking too much space.
<add>Either the compression lose some data (then we talk about lossy compression, such as .jpg) or it does not (and then it is lossless compression, such as .png)
<add>
<add>Lossless compression is mainly used for archive purpose as it allow storing data without losing information about the file archived. On the other hand, lossy compression is used for transfer of file where quality isn't necessarily what is required (i.e: images on Twitter).
<add>
<add>* <https://www.sciencedirect.com/topics/computer-science/compression-algorithm>
<add>* <https://en.wikipedia.org/wiki/Data_compression>
<add>* <https://en.wikipedia.org/wiki/Pigeonhole_principle>
<ide><path>computer_vision/README.md
<del>### Computer Vision
<add># Computer Vision
<add>
<add>Computer vision is a field of computer science that works on enabling computers to see, identify and process images in the same way that human does, and provide appropriate output.
<ide>
<del>Computer vision is a field of computer science that works on enabling computers to see,
<del>identify and process images in the same way that human vision does, and then provide appropriate output.
<ide> It is like imparting human intelligence and instincts to a computer.
<ide> Image processing and computer vision are a little different from each other. Image processing means applying some algorithms for transforming image from one form to the other like smoothing, contrasting, stretching, etc.
<add>
<ide> While computer vision comes from modelling image processing using the techniques of machine learning, computer vision applies machine learning to recognize patterns for interpretation of images (much like the process of visual reasoning of human vision).
<add>
<add>* <https://en.wikipedia.org/wiki/Computer_vision>
<add>* <https://www.algorithmia.com/blog/introduction-to-computer-vision>
<ide><path>conversions/README.md
<add># Conversion
<add>
<add>Conversion programs convert a type of data, a number from a numerical base or unit into one of another type, base or unit, e.g. binary to decimal, integer to string or foot to meters.
<add>
<add>* <https://en.wikipedia.org/wiki/Data_conversion>
<add>* <https://en.wikipedia.org/wiki/Transcoding> | 5 |
PHP | PHP | fix improper use of mb_substr() | 810311e3309ab0c1672af94a3ead1aab9200f330 | <ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> public function to($path, $extra = [], $secure = null)
<ide> $root = $this->getRootUrl($scheme);
<ide>
<ide> if (($queryPosition = strpos($path, '?')) !== false) {
<del> $query = mb_substr($path, $queryPosition);
<del> $path = mb_substr($path, 0, $queryPosition);
<add> $query = substr($path, $queryPosition);
<add> $path = substr($path, 0, $queryPosition);
<ide> } else {
<ide> $query = '';
<ide> } | 1 |
Mixed | Ruby | add has_secure_token to active record | 5a58ba3366ec6092fcd0e69340acd93f347d2576 | <ide><path>activerecord/CHANGELOG.md
<add>* Added ActiveRecord::SecureToken in order to encapsulate generation of
<add> unique tokens for attributes in a model using SecureRandom
<add>
<add> *Roberto Miranda*
<add>
<ide> * Change the behavior of boolean columns to be closer to Ruby's semantics.
<ide>
<ide> Before this change we had a small set of "truthy", and all others are "falsy".
<ide><path>activerecord/lib/active_record.rb
<ide> module ActiveRecord
<ide> autoload :Transactions
<ide> autoload :Translation
<ide> autoload :Validations
<add> autoload :SecureToken
<ide>
<ide> eager_autoload do
<ide> autoload :ActiveRecordError, 'active_record/errors'
<ide><path>activerecord/lib/active_record/base.rb
<ide> class Base
<ide> include Reflection
<ide> include Serialization
<ide> include Store
<add> include SecureToken
<ide> end
<ide>
<ide> ActiveSupport.run_load_hooks(:active_record, Base)
<ide><path>activerecord/lib/active_record/secure_token.rb
<add>module ActiveRecord
<add> module SecureToken
<add> extend ActiveSupport::Concern
<add>
<add> module ClassMethods
<add> # Example using has_secure_token
<add> #
<add> # # Schema: User(toke:string, auth_token:string)
<add> # class User < ActiveRecord::Base
<add> # has_secure_token
<add> # has_secure_token :auth_token
<add> # end
<add> #
<add> # user = User.new
<add> # user.save
<add> # user.token # => "44539a6a59835a4ee9d7b112"
<add> # user.auth_token # => "e2426a93718d1817a43abbaa"
<add> # user.regenerate_token # => true
<add> # user.regenerate_auth_token # => true
<add> #
<add> # SecureRandom is used to generate the 24-character unique token, so collisions are highly unlikely.
<add> # We'll check to see if the generated token has been used already using #exists?, and retry up to 10
<add> # times to find another unused token. After that a RuntimeError is raised if the problem persists.
<add> #
<add> # Note that it's still possible to generate a race condition in the database in the same way that
<add> # validates_presence_of can. You're encouraged to add a unique index in the database to deal with
<add> # this even more unlikely scenario.
<add> def has_secure_token(attribute = :token)
<add> # Load securerandom only when has_secure_key is used.
<add> require 'securerandom'
<add> define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_unique_secure_token(attribute) }
<add> before_create { self.send("#{attribute}=", self.class.generate_unique_secure_token(attribute)) }
<add> end
<add>
<add> def generate_unique_secure_token(attribute)
<add> 10.times do |i|
<add> SecureRandom.hex(12).tap do |token|
<add> if exists?(attribute => token)
<add> raise "Couldn't generate a unique token in 10 attempts!" if i == 9
<add> else
<add> return token
<add> end
<add> end
<add> end
<add> end
<add> end
<add> end
<add>end
<add>
<ide><path>activerecord/test/cases/secure_token_test.rb
<add>require 'cases/helper'
<add>require 'models/user'
<add>
<add>class SecureTokenTest < ActiveRecord::TestCase
<add> setup do
<add> @user = User.new
<add> end
<add>
<add> test "assing unique token values" do
<add> @user.save
<add> assert_not_nil @user.token
<add> assert_not_nil @user.auth_token
<add> end
<add>
<add> test "regenerate the secure key for the attribute" do
<add> @user.save
<add> old_token = @user.token
<add> old_auth_token = @user.auth_token
<add> @user.regenerate_token
<add> @user.regenerate_auth_token
<add>
<add> assert_not_equal @user.token, old_token
<add> assert_not_equal @user.auth_token, old_auth_token
<add> end
<add>
<add> test "raise and exception when with 10 attemps is reached" do
<add> User.stubs(:exists?).returns(*Array.new(10, true))
<add> assert_raises(RuntimeError) do
<add> @user.save
<add> end
<add> end
<add>
<add> test "assing unique token after 9 attemps reached" do
<add> User.stubs(:exists?).returns(*Array.new(10){ |i| i == 9 ? false : true})
<add> @user.save
<add> assert_not_nil @user.token
<add> assert_not_nil @user.auth_token
<add> end
<add>end
<ide><path>activerecord/test/models/user.rb
<add>class User < ActiveRecord::Base
<add> has_secure_token
<add> has_secure_token :auth_token
<add>end
<ide><path>activerecord/test/schema/schema.rb
<ide> def except(adapter_names_to_exclude)
<ide> t.string :overloaded_string_with_limit, limit: 255
<ide> t.string :string_with_default, default: 'the original default'
<ide> end
<add>
<add> create_table :users, force: true do |t|
<add> t.string :token
<add> t.string :auth_token
<add> end
<ide> end
<ide>
<ide> Course.connection.create_table :courses, force: true do |t| | 7 |
Ruby | Ruby | remove should_pop variable | d94cd869c82bc52388b670553ee08ad34679fc42 | <ide><path>actionpack/lib/action_dispatch/routing/polymorphic_routes.rb
<ide> def polymorphic_url(record_or_hash_or_array, options = {})
<ide> end
<ide>
<ide> inflection = lambda { |name| name.singular_route_key }
<del> should_pop = true
<ide>
<ide> if options[:action] == 'new'
<ide> elsif record.try(:persisted?)
<del> should_pop = false
<ide> else
<ide> inflection = lambda { |name| name.route_key }
<ide> end
<ide> def polymorphic_url(record_or_hash_or_array, options = {})
<ide> when Symbol, String
<ide> record.to_s
<ide> when Class
<del> args << record unless should_pop
<ide> inflection.call record.model_name
<ide> else
<del> args << record.to_model unless should_pop
<add> args << record.to_model if record.persisted?
<ide> inflection.call record.to_model.class.model_name
<ide> end
<ide> | 1 |
Javascript | Javascript | add hascrypto check to async-wrap-gh13045 | 485be99e684f5e296c2aba28a401d5ef42fc3cb4 | <ide><path>test/parallel/test-async-wrap-GH13045.js
<ide> 'use strict';
<ide> const common = require('../common');
<add>if (!common.hasCrypto) {
<add> common.skip('missing crypto');
<add> return;
<add>}
<ide>
<ide> // Refs: https://github.com/nodejs/node/issues/13045
<ide> // An HTTP Agent reuses a TLSSocket, and makes a failed call to `asyncReset`. | 1 |
Python | Python | fix repetition penalty error in modeling_utils.py | 18e5bdbec5b12ad395bfb2a30223c78d74a9c158 | <ide><path>src/transformers/modeling_utils.py
<ide> def _generate_no_beam_search(
<ide> if repetition_penalty != 1.0:
<ide> for i in range(batch_size):
<ide> for previous_tokens in set(input_ids[i].tolist()):
<del> next_token_logits[i, previous_tokens] /= repetition_penalty
<add> # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
<add> if next_token_logits[i, previous_tokens] < 0:
<add> next_token_logits[i, previous_tokens] *= repetition_penalty
<add> else:
<add> next_token_logits[i, previous_tokens] /= repetition_penalty
<ide>
<ide> if do_sample:
<ide> # Temperature (higher temperature => more likely to sample low probability tokens)
<ide> def _generate_beam_search(
<ide> if repetition_penalty != 1.0:
<ide> for i in range(batch_size * num_beams):
<ide> for previous_tokens in set(input_ids[i].tolist()):
<del> scores[i, previous_tokens] /= repetition_penalty
<add> # if score < 0 then repetition penalty has to multiplied to reduce the previous token probability
<add> if scores[i, previous_tokens] < 0:
<add> scores[i, previous_tokens] *= repetition_penalty
<add> else:
<add> scores[i, previous_tokens] /= repetition_penalty
<ide>
<ide> if do_sample:
<ide> # Temperature (higher temperature => more likely to sample low probability tokens) | 1 |
Python | Python | remove unnecessary space | 76406dd0c286da809b63f628c38cd37ecaae20eb | <ide><path>keras/backend/tensorflow_backend.py
<ide> def shape(x):
<ide> def int_shape(x):
<ide> '''Returns the shape of a tensor as a tuple of
<ide> integers or None entries.
<del> Note that this function only works with TensorFlow.
<add> Note that this function only works with TensorFlow.
<ide> '''
<ide> shape = x.get_shape()
<ide> return tuple([i.__int__() for i in shape]) | 1 |
Java | Java | remove javadoc warnings | ffbfb6713df6c9c2731038963c01590e182f026f | <ide><path>rxjava-core/src/main/java/rx/observables/BlockingObservable.java
<ide> public Subscription call(Observer<T> observer) {
<ide> /**
<ide> * Returns an iterator that iterates all values of the observable.
<ide> *
<del> * @param that
<add> * @param source
<ide> * an observable sequence to get an iterator for.
<ide> * @param <T>
<ide> * the type of source.
<ide> public static <T> Iterator<T> toIterator(Observable<T> source) {
<ide> /**
<ide> * Returns the last element of an observable sequence with a specified source.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @return the last element in the observable sequence.
<ide> */
<ide> public static <T> T last(final Observable<T> source) {
<ide> /**
<ide> * Returns the last element of an observable sequence that matches the predicate.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param predicate
<ide> * a predicate function to evaluate for elements in the sequence.
<ide> public static <T> T last(final Observable<T> source, final Func1<T, Boolean> pre
<ide> /**
<ide> * Returns the last element of an observable sequence that matches the predicate.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param predicate
<ide> * a predicate function to evaluate for elements in the sequence.
<ide> private static <T> T _singleOrDefault(BlockingObservable<T> source, boolean hasD
<ide> /**
<ide> * Returns the only element of an observable sequence and throws an exception if there is not exactly one element in the observable sequence.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @return The single element in the observable sequence.
<ide> * @throws IllegalStateException
<ide> public static <T> T single(Observable<T> source) {
<ide> /**
<ide> * Returns the only element of an observable sequence that matches the predicate and throws an exception if there is not exactly one element in the observable sequence.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param predicate
<ide> * A predicate function to evaluate for elements in the sequence.
<ide> public static <T> T single(Observable<T> source, Func1<T, Boolean> predicate) {
<ide> /**
<ide> * Returns the only element of an observable sequence that matches the predicate and throws an exception if there is not exactly one element in the observable sequence.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param predicate
<ide> * A predicate function to evaluate for elements in the sequence.
<ide> public static <T> T single(Observable<T> source, Object predicate) {
<ide> /**
<ide> * Returns the only element of an observable sequence, or a default value if the observable sequence is empty.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param defaultValue
<ide> * default value for a sequence.
<ide> public static <T> T singleOrDefault(Observable<T> source, T defaultValue) {
<ide> /**
<ide> * Returns the only element of an observable sequence that matches the predicate, or a default value if no value is found.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param defaultValue
<ide> * default value for a sequence.
<ide> public static <T> T singleOrDefault(Observable<T> source, T defaultValue, Func1<
<ide> /**
<ide> * Returns the only element of an observable sequence that matches the predicate, or a default value if no value is found.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @param defaultValue
<ide> * default value for a sequence.
<ide> public static <T> T singleOrDefault(Observable<T> source, T defaultValue, Object
<ide> * <p>
<ide> * This will throw an exception if the Observable emits more than 1 value. If more than 1 are expected then use <code>toList().toFuture()</code>.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @return a Future that expects a single item emitted by the source Observable
<ide> */
<ide> public static <T> Future<T> toFuture(final Observable<T> source) {
<ide> /**
<ide> * Converts an observable sequence to an Iterable.
<ide> *
<del> * @param that
<add> * @param source
<ide> * the source Observable
<ide> * @return Observable converted to Iterable.
<ide> */ | 1 |
PHP | PHP | fix a few bugs | 242f52f83567ae0d3351744cc98e5a2fbab68592 | <ide><path>src/Illuminate/Database/Eloquent/Factory.php
<ide> public function define($class, callable $attributes, $name = 'default')
<ide> */
<ide> public function state($class, $state, callable $attributes)
<ide> {
<del> $this->modifiers[$class][$state] = $attributes;
<add> $this->states[$class][$state] = $attributes;
<ide> }
<ide>
<ide> /**
<ide> public function raw($class, array $attributes = [], $name = 'default')
<ide> */
<ide> public function of($class, $name = 'default')
<ide> {
<del> return new FactoryBuilder($class, $name, $this->definitions, $this->faker, $this->states);
<add> return new FactoryBuilder($class, $name, $this->definitions, $this->states, $this->faker);
<ide> }
<ide>
<ide> /** | 1 |
Text | Text | add ali ijaz sheikh to the ctc | 97dc810d46d647186911555808d29d016a62085f | <ide><path>README.md
<ide> information about the governance of the Node.js project, see
<ide> * [jasnell](https://github.com/jasnell) - **James M Snell** <jasnell@gmail.com>
<ide> * [misterdjules](https://github.com/misterdjules) - **Julien Gilli** <jgilli@nodejs.org>
<ide> * [mscdex](https://github.com/mscdex) - **Brian White** <mscdex@mscdex.net>
<add>* [ofrobots](https://github.com/ofrobots) - **Ali Ijaz Sheikh** <ofrobots@google.com>
<ide> * [orangemocha](https://github.com/orangemocha) - **Alexis Campailla** <orangemocha@nodejs.org>
<ide> * [piscisaureus](https://github.com/piscisaureus) - **Bert Belder** <bertbelder@gmail.com>
<ide> * [rvagg](https://github.com/rvagg) - **Rod Vagg** <rod@vagg.org>
<ide> information about the governance of the Node.js project, see
<ide> * [micnic](https://github.com/micnic) - **Nicu Micleușanu** <micnic90@gmail.com>
<ide> * [mikeal](https://github.com/mikeal) - **Mikeal Rogers** <mikeal.rogers@gmail.com>
<ide> * [monsanto](https://github.com/monsanto) - **Christopher Monsanto** <chris@monsan.to>
<del>* [ofrobots](https://github.com/ofrobots) - **Ali Ijaz Sheikh** <ofrobots@google.com>
<ide> * [Olegas](https://github.com/Olegas) - **Oleg Elifantiev** <oleg@elifantiev.ru>
<ide> * [petkaantonov](https://github.com/petkaantonov) - **Petka Antonov** <petka_antonov@hotmail.com>
<ide> * [qard](https://github.com/qard) - **Stephen Belanger** <admin@stephenbelanger.com> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.