content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Python | Python | add regression tests for pickleable record arrays | 64d5832d0b675436a52e10a06d5386611c8eb889 | <ide><path>numpy/core/tests/test_records.py
<ide>
<ide> import warnings
<ide> import collections
<add>import pickle
<ide>
<ide>
<ide> class TestFromrecords(TestCase):
<ide> def test_out_of_order_fields(self):
<ide> y = self.data[['col2', 'col1']]
<ide> assert_equal(x[0][0], y[0][1])
<ide>
<add> def test_pickle_1(self):
<add> # Issue #1529
<add> a = np.array([(1, [])], dtype=[('a', np.int32), ('b', np.int32, 0)])
<add> assert_equal(a, pickle.loads(pickle.dumps(a)))
<add> assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
<add>
<add> def test_pickle_2(self):
<add> a = self.data
<add> assert_equal(a, pickle.loads(pickle.dumps(a)))
<add> assert_equal(a[0], pickle.loads(pickle.dumps(a[0])))
<add>
<ide>
<ide> def test_find_duplicate():
<ide> l1 = [1, 2, 3, 4, 5, 6] | 1 |
Go | Go | add ipv4forwarding check | 05418df539dfed118da099aacfe4250f2f6ad5e0 | <ide><path>pkg/sysinfo/sysinfo.go
<ide> import (
<ide> "io/ioutil"
<ide> "os"
<ide> "path"
<add> "strconv"
<add> "strings"
<ide>
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/libcontainer/cgroups"
<ide> func New(quiet bool) *SysInfo {
<ide> }
<ide> }
<ide>
<add> // Checek if ipv4_forward is disabled.
<add> if data, err := ioutil.ReadFile("/proc/sys/net/ipv4/ip_forward"); os.IsNotExist(err) {
<add> sysInfo.IPv4ForwardingDisabled = true
<add> } else {
<add> if enabled, _ := strconv.Atoi(strings.TrimSpace(string(data))); enabled == 0 {
<add> sysInfo.IPv4ForwardingDisabled = true
<add> } else {
<add> sysInfo.IPv4ForwardingDisabled = false
<add> }
<add> }
<add>
<ide> // Check if AppArmor is supported.
<ide> if _, err := os.Stat("/sys/kernel/security/apparmor"); os.IsNotExist(err) {
<ide> sysInfo.AppArmor = false | 1 |
Javascript | Javascript | eliminate need for render() method | 0bcfd33c38c64c6a38470764e613566a4cfea430 | <ide><path>examples/with-react-jss/pages/_document.js
<ide> import React from 'react'
<del>import Document, { Head, Main, NextScript } from 'next/document'
<add>import Document from 'next/document'
<ide> import { SheetsRegistry, JssProvider, createGenerateId } from 'react-jss'
<ide>
<ide> export default class JssDocument extends Document {
<ide> export default class JssDocument extends Document {
<ide>
<ide> return {
<ide> ...initialProps,
<del> registry
<add> styles: <>
<add> {initialProps.styles},
<add> <style id='server-side-styles'>
<add> {registry.toString()}
<add> </style>
<add> </>
<ide> }
<ide> }
<del>
<del> render () {
<del> return (
<del> <html>
<del> <Head>
<del> <style id='server-side-styles'>
<del> {this.props.registry.toString()}
<del> </style>
<del> </Head>
<del>
<del> <body>
<del> <Main />
<del> <NextScript />
<del> </body>
<del> </html>
<del> )
<del> }
<ide> } | 1 |
Java | Java | fix checkstyle violation | f47481749bb9d00a9e8b88c46c787c209856e01d | <ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java
<ide> public void readAndSplitScriptContainingCommentsWithWindowsLineEnding() throws E
<ide> String script = readScript("test-data-with-comments.sql").replaceAll("\n", "\r\n");
<ide> splitScriptContainingComments(script);
<ide> }
<del>
<add>
<ide> private void splitScriptContainingComments(String script) throws Exception {
<ide> List<String> statements = new ArrayList<>();
<ide> splitSqlScript(script, ';', statements); | 1 |
Javascript | Javascript | fix a few more flow warnings | e0202e459fd0181db551d0025ef562d7998186b0 | <ide><path>Libraries/Alert/Alert.js
<ide> const Platform = require('Platform');
<ide>
<ide> import type { AlertType, AlertButtonStyle } from 'AlertIOS';
<ide>
<del>type Buttons = Array<{
<add>export type Buttons = Array<{
<ide> text?: string,
<ide> onPress?: ?Function,
<ide> style?: AlertButtonStyle, | 1 |
PHP | PHP | add assertpushedtimes and assertsenttimes methods | 55b9ee34dfbb83576c09b4bb7d1ac286dfa7bd7e | <ide><path>src/Illuminate/Support/Testing/Fakes/MailFake.php
<ide> public function assertSent($mailable, $callback = null)
<ide> );
<ide> }
<ide>
<add> /**
<add> * Assert if a mailable was sent a number of times based on a truth-test callback.
<add> *
<add> * @param string $mailable
<add> * @param integer $times
<add> * @param callable|null $callback
<add> * @return void
<add> */
<add> public function assertSentTimes($mailable, $times = 1, $callback = null)
<add> {
<add> PHPUnit::assertTrue(
<add> ($count = $this->sent($mailable, $callback)->count()) === $times,
<add> "The expected [{$mailable}] mailable was sent {$count} times instead of {$times} times."
<add> );
<add> }
<add>
<ide> /**
<ide> * Determine if a mailable was not sent based on a truth-test callback.
<ide> *
<ide><path>src/Illuminate/Support/Testing/Fakes/QueueFake.php
<ide> public function assertPushed($job, $callback = null)
<ide> );
<ide> }
<ide>
<add> /**
<add> * Assert if a job was pushed a number of times based on a truth-test callback.
<add> *
<add> * @param string $job
<add> * @param integer $times
<add> * @param callable|null $callback
<add> * @return void
<add> */
<add> public function assertPushed($job, $times, $callback = null)
<add> {
<add> PHPUnit::assertTrue(
<add> ($count = $this->pushed($job, $callback)->count()) === $times,
<add> "The expected [{$job}] job was pushed {$count} times instead of {$times} times."
<add> );
<add> }
<add>
<ide> /**
<ide> * Assert if a job was pushed based on a truth-test callback.
<ide> * | 2 |
Javascript | Javascript | remove unused isdescriptortrap | 3db7357a47731a448f7b51d23cfb16c75b9a3e59 | <ide><path>packages/ember-metal/lib/meta.js
<ide> if (DEBUG) {
<ide> meta._counters = counters;
<ide> }
<ide>
<del>// Using `symbol()` here causes some node test to fail, presumably
<del>// because we define the CP with one copy of Ember and boot the app
<del>// with a different copy, so the random key we generate do not line
<del>// up. Is that testing a legit scenario?
<del>export const DESCRIPTOR = '__DESCRIPTOR__';
<del>
<ide> /**
<ide> Returns the CP descriptor assocaited with `obj` and `keyName`, if any.
<ide>
<ide> export function descriptorFor(obj, keyName, _meta) {
<ide> }
<ide> }
<ide>
<del>export let isDescriptorTrap;
<del>
<del>if (DEBUG) {
<del> isDescriptorTrap = function isDescriptorTrap(possibleDesc) {
<del> return (
<del> possibleDesc !== null &&
<del> typeof possibleDesc === 'object' &&
<del> possibleDesc[DESCRIPTOR] !== undefined
<del> );
<del> };
<del>}
<del>
<ide> /**
<ide> Check whether a value is a CP descriptor.
<ide> | 1 |
Javascript | Javascript | reset elements for polar area chart | c2d6e4c31f027fc2bbba0a594ab41d156523bd71 | <ide><path>src/Chart.PolarArea.js
<ide> _options: this.options,
<ide> }, this);
<ide>
<add> // Fit the scale before we animate
<add> this.updateScaleRange();
<add> this.scale.calculateRange();
<add> Chart.scaleService.fitScalesForChart(this, this.chart.width, this.chart.height);
<add>
<add> // so that we animate nicely
<add> this.resetElements();
<add>
<ide> // Update the chart with the latest data.
<ide> this.update();
<ide>
<ide> yCenter: this.chart.height / 2
<ide> });
<ide> },
<add> resetElements: function() {
<add> var circumference = 1 / this.data.datasets[0].data.length * 2;
<add>
<add> // Map new data to data points
<add> helpers.each(this.data.datasets[0].metaData, function(slice, index) {
<add>
<add> var value = this.data.datasets[0].data[index];
<add>
<add> var startAngle = Math.PI * 1.5 + (Math.PI * circumference) * index;
<add> var endAngle = startAngle + (circumference * Math.PI);
<add>
<add> helpers.extend(slice, {
<add> _index: index,
<add> _model: {
<add> x: this.chart.width / 2,
<add> y: this.chart.height / 2,
<add> innerRadius: 0,
<add> outerRadius: 0,
<add> startAngle: Math.PI * 1.5,
<add> endAngle: Math.PI * 1.5,
<add>
<add> backgroundColor: slice.custom && slice.custom.backgroundColor ? slice.custom.backgroundColor : helpers.getValueAtIndexOrDefault(this.data.datasets[0].backgroundColor, index, this.options.elements.slice.backgroundColor),
<add> hoverBackgroundColor: slice.custom && slice.custom.hoverBackgroundColor ? slice.custom.hoverBackgroundColor : helpers.getValueAtIndexOrDefault(this.data.datasets[0].hoverBackgroundColor, index, this.options.elements.slice.hoverBackgroundColor),
<add> borderWidth: slice.custom && slice.custom.borderWidth ? slice.custom.borderWidth : helpers.getValueAtIndexOrDefault(this.data.datasets[0].borderWidth, index, this.options.elements.slice.borderWidth),
<add> borderColor: slice.custom && slice.custom.borderColor ? slice.custom.borderColor : helpers.getValueAtIndexOrDefault(this.data.datasets[0].borderColor, index, this.options.elements.slice.borderColor),
<add>
<add> label: helpers.getValueAtIndexOrDefault(this.data.datasets[0].labels, index, this.data.datasets[0].labels[index])
<add> },
<add> });
<add>
<add> slice.pivot();
<add> }, this);
<add> },
<ide> update: function() {
<ide>
<ide> this.updateScaleRange(); | 1 |
Ruby | Ruby | make bazel write to .brew_home | 65f52806f6e04f2013838d5c9ecc70eb1b91ab82 | <ide><path>Library/Homebrew/formula.rb
<ide> def setup_home(home)
<ide> import site; site.addsitedir("#{HOMEBREW_PREFIX}/lib/python2.7/site-packages")
<ide> import sys, os; sys.path = (os.environ["PYTHONPATH"].split(os.pathsep) if "PYTHONPATH" in os.environ else []) + ["#{HOMEBREW_PREFIX}/lib/python2.7/site-packages"] + sys.path
<ide> PYTHON
<add>
<add> # Don't let bazel write to tmp directories we don't control or clean.
<add> (home/".bazelrc").write "startup --output_user_root=#{home}/_bazel"
<ide> end
<ide>
<ide> # Returns a list of Dependency objects that are declared in the formula. | 1 |
Javascript | Javascript | expand the test fixture | d6257d382d6f9910fb36ad1b4707bfa23ac965d2 | <ide><path>shells/dev/app/SuspenseTree/index.js
<ide> function SuspenseTree() {
<ide> return (
<ide> <>
<ide> <h1>Suspense</h1>
<del> <Suspense fallback={<Fallback>Loading outer</Fallback>}>
<add> <PrimaryFallbackTest />
<add> <NestedSuspenseTest />
<add> </>
<add> );
<add>}
<add>
<add>function PrimaryFallbackTest() {
<add> const [suspend, setSuspend] = useState(false);
<add> const fallbackStep = useTestSequence('fallback', Fallback1, Fallback2);
<add> const primaryStep = useTestSequence('primary', Primary1, Primary2);
<add> return (
<add> <>
<add> <h3>Suspense Primary / Fallback</h3>
<add> <label>
<add> <input
<add> checked={suspend}
<add> onChange={e => setSuspend(e.target.checked)}
<add> type="checkbox"
<add> />
<add> Suspend
<add> </label>
<add> <br />
<add> <Suspense fallback={fallbackStep}>
<add> {suspend ? <Never /> : primaryStep}
<add> </Suspense>
<add> </>
<add> );
<add>}
<add>
<add>function useTestSequence(label, T1, T2) {
<add> let [step, setStep] = useState(0);
<add> let next = (
<add> <button onClick={() => setStep(s => (s + 1) % allSteps.length)}>
<add> next {label} content
<add> </button>
<add> );
<add> let allSteps = [
<add> <>{next}</>,
<add> <>
<add> {next} <T1 prop={step}>mount</T1>
<add> </>,
<add> <>
<add> {next} <T1 prop={step}>update</T1>
<add> </>,
<add> <>
<add> {next} <T2 prop={step}>several</T2> <T1 prop={step}>different</T1>{' '}
<add> <T2 prop={step}>children</T2>
<add> </>,
<add> <>
<add> {next} <T2 prop={step}>goodbye</T2>
<add> </>,
<add> ];
<add> return allSteps[step];
<add>}
<add>
<add>function NestedSuspenseTest() {
<add> return (
<add> <>
<add> <h3>Nested Suspense</h3>
<add> <Suspense fallback={<Fallback1>Loading outer</Fallback1>}>
<ide> <Parent />
<ide> </Suspense>
<ide> </>
<ide> function SuspenseTree() {
<ide> function Parent() {
<ide> return (
<ide> <div>
<del> <Suspense fallback={<Fallback>Loading inner 1</Fallback>}>
<del> <Child>Hello</Child>
<del> </Suspense>
<del> <Suspense fallback={<Fallback>Loading inner 2</Fallback>}>
<del> <Child>World</Child>
<add> <Suspense fallback={<Fallback1>Loading inner 1</Fallback1>}>
<add> <Primary1>Hello</Primary1>
<add> </Suspense>{' '}
<add> <Suspense fallback={<Fallback2>Loading inner 2</Fallback2>}>
<add> <Primary2>World</Primary2>
<ide> </Suspense>
<del> <Suspense fallback={<Fallback>This will never load</Fallback>}>
<add> <br />
<add> <Suspense fallback={<Fallback1>This will never load</Fallback1>}>
<ide> <Never />
<ide> </Suspense>
<del> <LoadLater />
<add> <br />
<add> <b>
<add> <LoadLater />
<add> </b>
<ide> </div>
<ide> );
<ide> }
<ide> function LoadLater() {
<ide> return (
<ide> <Suspense
<ide> fallback={
<del> <Fallback onClick={() => setLoadChild(true)}>Click to load</Fallback>
<add> <Fallback1 onClick={() => setLoadChild(true)}>Click to load</Fallback1>
<ide> }
<ide> >
<ide> {loadChild ? (
<del> <Child onClick={() => setLoadChild(false)}>
<add> <Primary1 onClick={() => setLoadChild(false)}>
<ide> Loaded! Click to suspend again.
<del> </Child>
<add> </Primary1>
<ide> ) : (
<ide> <Never />
<ide> )}
<ide> </Suspense>
<ide> );
<ide> }
<ide>
<del>function Child(props) {
<del> return <p {...props} />;
<add>function Never() {
<add> throw new Promise(resolve => {});
<add>}
<add>
<add>function Fallback1({ prop, ...rest }) {
<add> return <span {...rest} />;
<ide> }
<ide>
<del>function Fallback(props) {
<del> return <h3 {...props}>{props.children}</h3>;
<add>function Fallback2({ prop, ...rest }) {
<add> return <span {...rest} />;
<ide> }
<ide>
<del>function Never() {
<del> throw new Promise(resolve => {});
<add>function Primary1({ prop, ...rest }) {
<add> return <span {...rest} />;
<add>}
<add>
<add>function Primary2({ prop, ...rest }) {
<add> return <span {...rest} />;
<ide> }
<ide>
<ide> export default SuspenseTree; | 1 |
Ruby | Ruby | simplify array#in_groups_of code | 50e11e989727b6886b25d61333ce40060514c3e2 | <ide><path>activesupport/lib/active_support/core_ext/array/grouping.rb
<ide> def in_groups_of(number, fill_with = nil)
<ide> if block_given?
<ide> collection.each_slice(number) { |slice| yield(slice) }
<ide> else
<del> groups = []
<del> collection.each_slice(number) { |group| groups << group }
<del> groups
<add> collection.each_slice(number).to_a
<ide> end
<ide> end
<ide> | 1 |
PHP | PHP | use array<> type annotation | 118341bcc85972b2675141e74e68650e5db7dec1 | <ide><path>src/Http/ContentTypeNegotiation.php
<ide> protected function parseQualifiers(string $header): array
<ide> * You can expect null when the request has no Accept header.
<ide> *
<ide> * @param \Psr\Http\Message\RequestInterface $request The request to use.
<del> * @param string[] $choices The supported content type choices.
<add> * @param array<string> $choices The supported content type choices.
<ide> * @return string|null The prefered type or null if there is no match with choices or if the
<ide> * request had no Accept header.
<ide> */ | 1 |
PHP | PHP | add missing property. | e6a81b6d3617b6de3baa87afbc1bd68ae91ea1ba | <ide><path>src/Illuminate/Session/CookieSessionHandler.php
<ide> class CookieSessionHandler implements SessionHandlerInterface
<ide> */
<ide> protected $request;
<ide>
<add> /*
<add> * The number of minutes the session should be valid.
<add> *
<add> * @var int
<add> */
<add> protected $minutes;
<add>
<ide> /**
<ide> * Create a new cookie driven handler instance.
<ide> * | 1 |
Python | Python | add transparency for unsupported connection type | d05900b233d03849a4d9650bfc80840a466ef99a | <ide><path>airflow/sensors/sql.py
<ide> def _get_hook(self):
<ide> }
<ide> if conn.conn_type not in allowed_conn_type:
<ide> raise AirflowException(
<del> "The connection type is not supported by SqlSensor. "
<add> f"Connection type ({conn.conn_type}) is not supported by SqlSensor. "
<ide> + f"Supported connection types: {list(allowed_conn_type)}"
<ide> )
<ide> return conn.get_hook() | 1 |
Mixed | Javascript | add option to disable line drawing | 24e4a924c4b6adcb787e13eb417b3e1845e9cf11 | <ide><path>docs/02-Line-Chart.md
<ide> The default options for line chart are defined in `Chart.defaults.Line`.
<ide>
<ide> Name | Type | Default | Description
<ide> --- | --- | --- | ---
<add>showLines | Boolean | true | If false, the lines between points are not drawn
<ide> stacked | Boolean | false | If true, lines stack on top of each other along the y axis.
<ide> *hover*.mode | String | "label" | Label's hover mode. "label" is used since the x axis displays data by the index in the dataset.
<ide> scales | - | - | -
<ide><path>src/controllers/controller.line.js
<ide> helpers = Chart.helpers;
<ide>
<ide> Chart.defaults.line = {
<add> showLines: true,
<add>
<ide> hover: {
<ide> mode: "label"
<ide> },
<ide> this.getDataset().metaData.splice(index, 0, point);
<ide>
<ide> // Make sure bezier control points are updated
<del> this.updateBezierControlPoints();
<add> if (this.chart.options.showLines)
<add> this.updateBezierControlPoints();
<ide> },
<ide>
<ide> update: function update(reset) {
<ide> }
<ide>
<ide> // Update Line
<del> helpers.extend(line, {
<del> // Utility
<del> _scale: yScale,
<del> _datasetIndex: this.index,
<del> // Data
<del> _children: points,
<del> // Model
<del> _model: {
<del> // Appearance
<del> tension: line.custom && line.custom.tension ? line.custom.tension : helpers.getValueOrDefault(this.getDataset().tension, this.chart.options.elements.line.tension),
<del> backgroundColor: line.custom && line.custom.backgroundColor ? line.custom.backgroundColor : (this.getDataset().backgroundColor || this.chart.options.elements.line.backgroundColor),
<del> borderWidth: line.custom && line.custom.borderWidth ? line.custom.borderWidth : (this.getDataset().borderWidth || this.chart.options.elements.line.borderWidth),
<del> borderColor: line.custom && line.custom.borderColor ? line.custom.borderColor : (this.getDataset().borderColor || this.chart.options.elements.line.borderColor),
<del> borderCapStyle: line.custom && line.custom.borderCapStyle ? line.custom.borderCapStyle : (this.getDataset().borderCapStyle || this.chart.options.elements.line.borderCapStyle),
<del> borderDash: line.custom && line.custom.borderDash ? line.custom.borderDash : (this.getDataset().borderDash || this.chart.options.elements.line.borderDash),
<del> borderDashOffset: line.custom && line.custom.borderDashOffset ? line.custom.borderDashOffset : (this.getDataset().borderDashOffset || this.chart.options.elements.line.borderDashOffset),
<del> borderJoinStyle: line.custom && line.custom.borderJoinStyle ? line.custom.borderJoinStyle : (this.getDataset().borderJoinStyle || this.chart.options.elements.line.borderJoinStyle),
<del> fill: line.custom && line.custom.fill ? line.custom.fill : (this.getDataset().fill !== undefined ? this.getDataset().fill : this.chart.options.elements.line.fill),
<del> // Scale
<del> scaleTop: yScale.top,
<del> scaleBottom: yScale.bottom,
<del> scaleZero: scaleBase,
<del> },
<del> });
<del> line.pivot();
<add> if (this.chart.options.showLines) {
<add> helpers.extend(line, {
<add> // Utility
<add> _scale: yScale,
<add> _datasetIndex: this.index,
<add> // Data
<add> _children: points,
<add> // Model
<add> _model: {
<add> // Appearance
<add> tension: line.custom && line.custom.tension ? line.custom.tension : helpers.getValueOrDefault(this.getDataset().tension, this.chart.options.elements.line.tension),
<add> backgroundColor: line.custom && line.custom.backgroundColor ? line.custom.backgroundColor : (this.getDataset().backgroundColor || this.chart.options.elements.line.backgroundColor),
<add> borderWidth: line.custom && line.custom.borderWidth ? line.custom.borderWidth : (this.getDataset().borderWidth || this.chart.options.elements.line.borderWidth),
<add> borderColor: line.custom && line.custom.borderColor ? line.custom.borderColor : (this.getDataset().borderColor || this.chart.options.elements.line.borderColor),
<add> borderCapStyle: line.custom && line.custom.borderCapStyle ? line.custom.borderCapStyle : (this.getDataset().borderCapStyle || this.chart.options.elements.line.borderCapStyle),
<add> borderDash: line.custom && line.custom.borderDash ? line.custom.borderDash : (this.getDataset().borderDash || this.chart.options.elements.line.borderDash),
<add> borderDashOffset: line.custom && line.custom.borderDashOffset ? line.custom.borderDashOffset : (this.getDataset().borderDashOffset || this.chart.options.elements.line.borderDashOffset),
<add> borderJoinStyle: line.custom && line.custom.borderJoinStyle ? line.custom.borderJoinStyle : (this.getDataset().borderJoinStyle || this.chart.options.elements.line.borderJoinStyle),
<add> fill: line.custom && line.custom.fill ? line.custom.fill : (this.getDataset().fill !== undefined ? this.getDataset().fill : this.chart.options.elements.line.fill),
<add> // Scale
<add> scaleTop: yScale.top,
<add> scaleBottom: yScale.bottom,
<add> scaleZero: scaleBase,
<add> },
<add> });
<add> line.pivot();
<add> }
<ide>
<ide> // Update Points
<ide> helpers.each(points, function(point, index) {
<ide> this.updateElement(point, index, reset);
<ide> }, this);
<ide>
<del> this.updateBezierControlPoints();
<add> if (this.chart.options.showLines)
<add> this.updateBezierControlPoints();
<ide> },
<ide>
<ide> getPointBackgroundColor: function(point, index) {
<ide> }, this);
<ide>
<ide> // Transition and Draw the line
<del> this.getDataset().metaDataset.transition(easingDecimal).draw();
<add> if (this.chart.options.showLines)
<add> this.getDataset().metaDataset.transition(easingDecimal).draw();
<ide>
<ide> // Draw the points
<ide> helpers.each(this.getDataset().metaData, function(point) {
<ide><path>test/controller.line.tests.js
<ide> describe('Line controller tests', function() {
<ide> type: 'line'
<ide> },
<ide> options: {
<add> showLines: true,
<ide> scales: {
<ide> xAxes: [{
<ide> id: 'firstXScaleID'
<ide> describe('Line controller tests', function() {
<ide> expect(chart.data.datasets[0].metaData[3].draw.calls.count()).toBe(1);
<ide> });
<ide>
<add> it('should draw all elements except lines', function() {
<add> var chart = {
<add> data: {
<add> datasets: [{
<add> data: [10, 15, 0, -4]
<add> }]
<add> },
<add> config: {
<add> type: 'line'
<add> },
<add> options: {
<add> showLines: false,
<add> scales: {
<add> xAxes: [{
<add> id: 'firstXScaleID'
<add> }],
<add> yAxes: [{
<add> id: 'firstYScaleID'
<add> }]
<add> }
<add> }
<add> };
<add>
<add> var controller = new Chart.controllers.line(chart, 0);
<add>
<add> spyOn(chart.data.datasets[0].metaDataset, 'draw');
<add> spyOn(chart.data.datasets[0].metaData[0], 'draw');
<add> spyOn(chart.data.datasets[0].metaData[1], 'draw');
<add> spyOn(chart.data.datasets[0].metaData[2], 'draw');
<add> spyOn(chart.data.datasets[0].metaData[3], 'draw');
<add>
<add> controller.draw();
<add>
<add> expect(chart.data.datasets[0].metaDataset.draw.calls.count()).toBe(0);
<add> expect(chart.data.datasets[0].metaData[0].draw.calls.count()).toBe(1);
<add> expect(chart.data.datasets[0].metaData[2].draw.calls.count()).toBe(1);
<add> expect(chart.data.datasets[0].metaData[3].draw.calls.count()).toBe(1);
<add> });
<add>
<ide> it('should update elements', function() {
<ide> var data = {
<ide> datasets: [{
<ide> describe('Line controller tests', function() {
<ide> type: 'line'
<ide> },
<ide> options: {
<add> showLines: true,
<ide> elements: {
<ide> line: {
<ide> backgroundColor: 'rgb(255, 0, 0)', | 3 |
Go | Go | fix typos in daemon | b00a67be6e3d3f241879110bd342abaa8e23cbac | <ide><path>daemon/cluster/controllers/plugin/controller.go
<ide> import (
<ide> // We'll also end up with many tasks all pointing to the same plugin ID.
<ide> //
<ide> // TODO(@cpuguy83): registry auth is intentionally not supported until we work out
<del>// the right way to pass registry crednetials via secrets.
<add>// the right way to pass registry credentials via secrets.
<ide> type Controller struct {
<ide> backend Backend
<ide> spec runtime.PluginSpec
<ide><path>daemon/graphdriver/lcow/lcow.go
<ide> func (d *Driver) terminateServiceVM(id, context string, force bool) (err error)
<ide> svm.signalStopFinished(err)
<ide> }()
<ide>
<del> // Now it's possible that the serivce VM failed to start and now we are trying to termiante it.
<add> // Now it's possible that the serivce VM failed to start and now we are trying to terminate it.
<ide> // In this case, we will relay the error to the goroutines waiting for this vm to stop.
<ide> if err := svm.getStartError(); err != nil {
<ide> logrus.Debugf("lcowdriver: terminateservicevm: %s had failed to start up: %s", id, err)
<ide><path>daemon/logger/logger.go
<ide> func PutMessage(msg *Message) {
<ide> messagePool.Put(msg)
<ide> }
<ide>
<del>// Message is datastructure that represents piece of output produced by some
<add>// Message is data structure that represents piece of output produced by some
<ide> // container. The Line member is a slice of an array whose contents can be
<ide> // changed after a log driver's Log() method returns.
<ide> //
<ide> func (w *LogWatcher) WatchClose() <-chan struct{} {
<ide> return w.closeNotifier
<ide> }
<ide>
<del>// Capability defines the list of capabilties that a driver can implement
<add>// Capability defines the list of capabilities that a driver can implement
<ide> // These capabilities are not required to be a logging driver, however do
<ide> // determine how a logging driver can be used
<ide> type Capability struct { | 3 |
Javascript | Javascript | add deprecation warning for v8breakiterator | 105e628f84ad03cfd32ffac112746285be28c872 | <ide><path>lib/internal/process.js
<ide> function setupConfig(_source) {
<ide> return value;
<ide> });
<ide> const processConfig = process.binding('config');
<del> // Intl.v8BreakIterator() would crash w/ fatal error, so throw instead.
<del> if (processConfig.hasIntl &&
<del> processConfig.hasSmallICU &&
<del> Intl.hasOwnProperty('v8BreakIterator') &&
<del> !process.icu_data_dir) {
<add> if (typeof Intl !== 'undefined' && Intl.hasOwnProperty('v8BreakIterator')) {
<add> const oldV8BreakIterator = Intl.v8BreakIterator;
<ide> const des = Object.getOwnPropertyDescriptor(Intl, 'v8BreakIterator');
<del> des.value = function v8BreakIterator() {
<del> throw new Error('v8BreakIterator: full ICU data not installed. ' +
<del> 'See https://github.com/nodejs/node/wiki/Intl');
<del> };
<add> des.value = require('internal/util').deprecate(function v8BreakIterator() {
<add> if (processConfig.hasSmallICU && !process.icu_data_dir) {
<add> // Intl.v8BreakIterator() would crash w/ fatal error, so throw instead.
<add> throw new Error('v8BreakIterator: full ICU data not installed. ' +
<add> 'See https://github.com/nodejs/node/wiki/Intl');
<add> }
<add> return Reflect.construct(oldV8BreakIterator, arguments);
<add> }, 'Intl.v8BreakIterator is deprecated and will be removed soon.');
<ide> Object.defineProperty(Intl, 'v8BreakIterator', des);
<ide> }
<ide> // Don’t let icu_data_dir leak through.
<ide><path>test/parallel/test-intl-v8BreakIterator.js
<ide> if (global.Intl === undefined || Intl.v8BreakIterator === undefined) {
<ide> return common.skip('no Intl');
<ide> }
<ide>
<add>const warning = 'Intl.v8BreakIterator is deprecated and will be removed soon.';
<add>common.expectWarning('DeprecationWarning', warning);
<add>
<ide> try {
<ide> new Intl.v8BreakIterator();
<ide> // May succeed if data is available - OK | 2 |
Python | Python | fix transformer width in textcatensemble | 3983bc6b1e8355eb0fa17e7787e94074c1eb4a63 | <ide><path>spacy/ml/models/textcat.py
<ide> from thinc.api import SparseLinear, Softmax, softmax_activation, Maxout, reduce_sum
<ide> from thinc.api import HashEmbed, with_array, with_cpu, uniqued
<ide> from thinc.api import Relu, residual, expand_window
<add>from thinc.layers.chain import init as init_chain
<ide>
<ide> from ...attrs import ID, ORTH, PREFIX, SUFFIX, SHAPE, LOWER
<ide> from ...util import registry
<ide> from ..extract_ngrams import extract_ngrams
<ide> from ..staticvectors import StaticVectors
<ide> from ..featureextractor import FeatureExtractor
<ide> from ...tokens import Doc
<add>from .tok2vec import get_tok2vec_width
<ide>
<ide>
<ide> @registry.architectures.register("spacy.TextCatCNN.v1")
<ide> def build_text_classifier_v2(
<ide> exclusive_classes = not linear_model.attrs["multi_label"]
<ide> with Model.define_operators({">>": chain, "|": concatenate}):
<ide> width = tok2vec.maybe_get_dim("nO")
<add> attention_layer = ParametricAttention(width) # TODO: benchmark performance difference of this layer
<add> maxout_layer = Maxout(nO=width, nI=width)
<add> linear_layer = Linear(nO=nO, nI=width)
<ide> cnn_model = (
<del> tok2vec
<del> >> list2ragged()
<del> >> ParametricAttention(
<del> width
<del> ) # TODO: benchmark performance difference of this layer
<del> >> reduce_sum()
<del> >> residual(Maxout(nO=width, nI=width))
<del> >> Linear(nO=nO, nI=width)
<del> >> Dropout(0.0)
<add> tok2vec
<add> >> list2ragged()
<add> >> attention_layer
<add> >> reduce_sum()
<add> >> residual(maxout_layer)
<add> >> linear_layer
<add> >> Dropout(0.0)
<ide> )
<ide>
<ide> nO_double = nO * 2 if nO else None
<ide> def build_text_classifier_v2(
<ide> if model.has_dim("nO") is not False:
<ide> model.set_dim("nO", nO)
<ide> model.set_ref("output_layer", linear_model.get_ref("output_layer"))
<add> model.set_ref("attention_layer", attention_layer)
<add> model.set_ref("maxout_layer", maxout_layer)
<add> model.set_ref("linear_layer", linear_layer)
<ide> model.attrs["multi_label"] = not exclusive_classes
<add>
<add> model.init = init_ensemble_textcat
<add> return model
<add>
<add>
<add>def init_ensemble_textcat(model, X, Y) -> Model:
<add> tok2vec_width = get_tok2vec_width(model)
<add> model.get_ref("attention_layer").set_dim("nO", tok2vec_width)
<add> model.get_ref("maxout_layer").set_dim("nO", tok2vec_width)
<add> model.get_ref("maxout_layer").set_dim("nI", tok2vec_width)
<add> model.get_ref("linear_layer").set_dim("nI", tok2vec_width)
<add> init_chain(model, X, Y)
<ide> return model
<ide>
<ide>
<ide><path>spacy/ml/models/tok2vec.py
<ide> def tok2vec_listener_v1(width: int, upstream: str = "*"):
<ide> return tok2vec
<ide>
<ide>
<add>def get_tok2vec_width(model: Model):
<add> nO = None
<add> if model.has_ref("tok2vec"):
<add> tok2vec = model.get_ref("tok2vec")
<add> if tok2vec.has_dim("nO"):
<add> nO = tok2vec.get_dim("nO")
<add> elif tok2vec.has_ref("listener"):
<add> nO = tok2vec.get_ref("listener").get_dim("nO")
<add> return nO
<add>
<add>
<ide> @registry.architectures.register("spacy.HashEmbedCNN.v1")
<ide> def build_hash_embed_cnn_tok2vec(
<ide> *, | 2 |
PHP | PHP | remove unneeded method arguments | 9796669a6d6bf6c3ba2aa1e1cd22e202412a6bb5 | <ide><path>src/ORM/Behavior/Translate/EavStrategy.php
<ide> public function __construct(Table $table, array $config = [])
<ide> $this->table = $table;
<ide> $this->translationTable = $this->getTableLocator()->get($this->_config['translationTable']);
<ide>
<del> $this->setupFieldAssociations(
<del> $this->_config['fields'],
<del> $this->_config['translationTable'],
<del> $this->_config['referenceName'],
<del> $this->_config['strategy']
<del> );
<add> $this->setupAssociations();
<ide> }
<ide>
<ide> /**
<ide> public function __construct(Table $table, array $config = [])
<ide> * Additionally it creates a `i18n` HasMany association that will be
<ide> * used for fetching all translations for each record in the bound table.
<ide> *
<del> * @param array $fields List of fields to create associations for.
<del> * @param string $table The table name to use for storing each field translation.
<del> * @param string $model The model field value.
<del> * @param string $strategy The strategy used in the _i18n association.
<del> *
<ide> * @return void
<ide> */
<del> protected function setupFieldAssociations($fields, $table, $model, $strategy)
<add> protected function setupAssociations()
<ide> {
<add> $fields = $this->_config['fields'];
<add> $table = $this->_config['translationTable'];
<add> $model = $this->_config['referenceName'];
<add> $strategy = $this->_config['strategy'];
<add> $filter = $this->_config['onlyTranslated'];
<add>
<ide> $targetAlias = $this->translationTable->getAlias();
<ide> $alias = $this->table->getAlias();
<del> $filter = $this->_config['onlyTranslated'];
<ide> $tableLocator = $this->getTableLocator();
<ide>
<ide> foreach ($fields as $field) {
<ide><path>src/ORM/Behavior/Translate/ShadowTableStrategy.php
<ide> public function __construct(Table $table, array $config = [])
<ide> $this->table = $table;
<ide> $this->translationTable = $this->getTableLocator()->get($this->_config['translationTable']);
<ide>
<del> $this->setupFieldAssociations(
<del> $this->_config['fields'],
<del> $this->_config['translationTable'],
<del> $this->_config['referenceName'],
<del> $this->_config['strategy']
<del> );
<add> $this->setupAssociations();
<ide> }
<ide>
<ide> /**
<ide> public function __construct(Table $table, array $config = [])
<ide> * Don't create a hasOne association here as the join conditions are modified
<ide> * in before find - so create/modify it there.
<ide> *
<del> * @param array $fields Unused.
<del> * @param string $table Unused.
<del> * @param string $fieldConditions Unused.
<del> * @param string $strategy The strategy used in the shadow table association.
<del> *
<ide> * @return void
<ide> */
<del> public function setupFieldAssociations($fields, $table, $fieldConditions, $strategy)
<add> protected function setupAssociations()
<ide> {
<ide> $config = $this->getConfig();
<ide>
<ide> $this->table->hasMany($config['translationTable'], [
<ide> 'className' => $config['translationTable'],
<ide> 'foreignKey' => 'id',
<del> 'strategy' => $strategy,
<add> 'strategy' => $config['strategy'],
<ide> 'propertyName' => '_i18n',
<ide> 'dependent' => true,
<ide> ]); | 2 |
Javascript | Javascript | remove supports in webglcapabilities | d4f5a1f4456da6efef4e106f0e9ea305a491f4f8 | <ide><path>src/renderers/webgl/WebGLCapabilities.js
<ide> THREE.WebGLCapabilities = function( gl, extensions, parameters ) {
<ide>
<ide> this.vertexTextures = this.maxVertexTextures > 0;
<ide> this.floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
<del> this.floatVertexTextures = this.supportsVertexTextures && this.supportsFloatFragmentTextures;
<add> this.floatVertexTextures = this.vertexTextures && this.floatFragmentTextures;
<ide>
<ide> var _maxPrecision = this.getMaxPrecision( this.precision );
<ide> | 1 |
Ruby | Ruby | add test for window + partition + order | 4a72415555de19ca33c8ea16ee9ba26d1b73b078 | <ide><path>test/test_select_manager.rb
<ide> def test_manager_stores_bind_values
<ide> }
<ide> end
<ide>
<add> it 'takes a partition and an order' do
<add> table = Table.new :users
<add> manager = Arel::SelectManager.new Table.engine
<add> manager.from table
<add> manager.window('a_window').partition(table['foo']).order(table['foo'].asc)
<add> manager.to_sql.must_be_like %{
<add> SELECT FROM "users" WINDOW "a_window" AS (PARTITION BY "users"."foo"
<add> ORDER BY "users"."foo" ASC)
<add> }
<add> end
<add>
<ide> it 'takes a partition with multiple columns' do
<ide> table = Table.new :users
<ide> manager = Arel::SelectManager.new Table.engine | 1 |
Ruby | Ruby | add home-assistant to github_prerelease_allowlist | 41fe6b5e7c83e7934fd08ec958b315247ae87dce | <ide><path>Library/Homebrew/utils/shared_audits.rb
<ide> def github_release_data(user, repo, tag)
<ide> "elm-format" => "0.8.3",
<ide> "freetube" => :all,
<ide> "gitless" => "0.8.8",
<add> "home-assistant" => :all,
<ide> "infrakit" => "0.5",
<ide> "pock" => :all,
<ide> "riff" => "0.5.0", | 1 |
Text | Text | recommend gdm for go resources | 30455d0fb5fce2652ca8cadd5941aecccc611e5b | <ide><path>share/doc/homebrew/Formula-Cookbook.md
<ide> end
<ide>
<ide> [jrnl](https://github.com/Homebrew/homebrew/blob/master/Library/Formula/jrnl.rb) is an example of a formula that does this well. The end result means the user doesn't have use `pip` or Python and can just run `jrnl`.
<ide>
<del>[homebrew-pypi-poet](https://github.com/tdsmith/homebrew-pypi-poet) can help you generate resource stanzas for the dependencies of your Python application and [homebrew-go-resources](https://github.com/samertm/homebrew-go-resources) can help you generate go\_resource stanzas for the dependencies of your go application.
<add>[homebrew-pypi-poet](https://github.com/tdsmith/homebrew-pypi-poet) can help you generate resource stanzas for the dependencies of your Python application and [gdm](https://github.com/sparrc/gdm#homebrew) can help you generate go\_resource stanzas for the dependencies of your go application.
<ide>
<ide> ## Install the formula
<ide> | 1 |
Ruby | Ruby | fix dummy_app configuration | 8967170164186f2408776ff5b193878f1c82a541 | <ide><path>railties/lib/rails/generators/rails/plugin/templates/rails/application.rb
<ide> <% if include_all_railties? -%>
<ide> require 'rails/all'
<ide> <% else -%>
<add>require "rails"
<ide> # Pick the frameworks you want:
<add>require "active_model/railtie"
<add>require "active_job/railtie"
<ide> <%= comment_if :skip_active_record %>require "active_record/railtie"
<ide> require "action_controller/railtie"
<del>require "action_view/railtie"
<ide> <%= comment_if :skip_action_mailer %>require "action_mailer/railtie"
<del>require "active_job/railtie"
<add>require "action_view/railtie"
<ide> require "active_storage/engine"
<ide> <%= comment_if :skip_action_cable %>require "action_cable/engine"
<del><%= comment_if :skip_test %>require "rails/test_unit/railtie"
<ide> <%= comment_if :skip_sprockets %>require "sprockets/railtie"
<add><%= comment_if :skip_test %>require "rails/test_unit/railtie"
<ide> <% end -%>
<ide>
<ide> Bundler.require(*Rails.groups) | 1 |
Python | Python | fix linting errors | 291ffceb877595ef00f1e9ad53fb10f2e48185db | <ide><path>libcloud/compute/drivers/dimensiondata.py
<ide> def _to_firewall_address(self, element):
<ide> port_list = element.find(fixxpath('portList', TYPES_URN))
<ide> address_list = element.find(fixxpath('ipAddressList', TYPES_URN))
<ide> if address_list is None:
<del> return DimensionDataFirewallAddress (
<add> return DimensionDataFirewallAddress(
<ide> any_ip=ip.get('address') == 'ANY',
<ide> ip_address=ip.get('address'),
<ide> ip_prefix_size=ip.get('prefixSize'),
<ide> def _to_firewall_address(self, element):
<ide> )
<ide> else:
<ide> return DimensionDataFirewallAddress(
<del> any_ip = False,
<del> ip_address= None,
<del> ip_prefix_size = None,
<del> port_begin = None,
<del> port_end = None,
<add> any_ip=False,
<add> ip_address=None,
<add> ip_prefix_size=None,
<add> port_begin=None,
<add> port_end=None,
<ide> port_list_id=port_list.get('id', None)
<ide> if port_list is not None else None,
<ide> address_list_id=address_list.get('id') | 1 |
Python | Python | improve type coverage in test_unique | 5a929a4875bc3e33d0333d8684d6eeaa0e4d45f4 | <ide><path>numpy/lib/tests/test_arraysetops.py
<ide> import warnings
<ide>
<ide> class TestAso(TestCase):
<del> def test_unique( self ):
<del> a = np.array( [5, 7, 1, 2, 1, 5, 7] )
<del>
<del> ec = np.array( [1, 2, 5, 7] )
<del> c = unique( a )
<del> assert_array_equal( c, ec )
<del>
<del> vals, indices = unique( a, return_index=True )
<ide>
<ide>
<del> ed = np.array( [2, 3, 0, 1] )
<del> assert_array_equal(vals, ec)
<del> assert_array_equal(indices, ed)
<del>
<del> vals, ind0, ind1 = unique( a, return_index=True,
<del> return_inverse=True )
<del>
<add> def test_unique( self ):
<ide>
<del> ee = np.array( [2, 3, 0, 1, 0, 2, 3] )
<del> assert_array_equal(vals, ec)
<del> assert_array_equal(ind0, ed)
<del> assert_array_equal(ind1, ee)
<add> def check_values(a, b, msg):
<add> v = unique(a)
<add> assert_array_equal(v, b, msg)
<add>
<add> def check_indexes(a, b, i1, i2, msg):
<add> v, j1, j2 = unique(a, 1, 1)
<add> assert_array_equal(v, b, msg)
<add> assert_array_equal(j1, i1, msg)
<add> assert_array_equal(j2, i2, msg)
<add>
<add> fmt = "Failed for type '%s'"
<add> a = [5, 7, 1, 2, 1, 5, 7]
<add> b = [1, 2, 5, 7]
<add> i1 = [2, 3, 0, 1]
<add> i2 = [2, 3, 0, 1, 0, 2, 3]
<add>
<add>
<add> types = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
<add>
<add> # test for numeric arrays
<add> for dt in types:
<add> msg = fmt % dt
<add> aa = np.array(a, dt)
<add> bb = np.array(b, dt)
<add> check_values(aa, bb, msg)
<add> check_indexes(aa, bb, i1, i2, msg)
<add>
<add> # test for object arrays
<add> msg = fmt % 'O'
<add> aa = np.empty(len(a), 'O')
<add> aa[:] = a
<add> bb = np.empty(len(b), 'O')
<add> bb[:] = b
<add> check_values(aa, bb, msg)
<add> check_indexes(aa, bb, i1, i2, msg)
<add>
<add> # test for structured arrays
<add> msg = fmt % 'V'
<add> aa = np.array(zip(a,a), [('', 'i'), ('', 'i')])
<add> bb = np.array(zip(b,b), [('', 'i'), ('', 'i')])
<add> check_values(aa, bb, msg)
<add> check_indexes(aa, bb, i1, i2, msg)
<add>
<add> # test for datetime64 arrays
<add> msg = fmt % 'M'
<add> aa = np.array(a, 'datetime64[D]')
<add> bb = np.array(b, 'datetime64[D]')
<add> check_values(aa, bb, msg)
<add> check_indexes(aa, bb, i1, i2, msg)
<add>
<add> # test for timedelta64 arrays
<add> msg = fmt % 'm'
<add> aa = np.array(a, 'timedelta64[D]')
<add> bb = np.array(b, 'timedelta64[D]')
<add> check_values(aa, bb, msg)
<add> check_indexes(aa, bb, i1, i2, msg)
<ide>
<del> assert_array_equal([], unique([]))
<ide>
<ide> def test_intersect1d( self ):
<ide> # unique inputs | 1 |
Javascript | Javascript | extract creation of async chunk | 3dc08aec2aed5df0394ebc0456d7755c0e64d25a | <ide><path>lib/optimize/CommonsChunkPlugin.js
<ide> The available options are:
<ide> });
<ide> }
<ide>
<add> createAsyncChunk(compilation, asyncOption, commonChunk) {
<add> const asyncChunk = compilation.addChunk(typeof asyncOption === "string" ? asyncOption : undefined);
<add> asyncChunk.chunkReason = "async commons chunk";
<add> asyncChunk.extraAsync = true;
<add> asyncChunk.addParent(commonChunk);
<add> return asyncChunk;
<add> }
<add>
<ide> apply(compiler) {
<ide> const filenameTemplate = this.filenameTemplate;
<ide> const minChunks = this.minChunks;
<ide> The available options are:
<ide> if(!usedChunks) {
<ide> return;
<ide> }
<add>
<ide> let asyncChunk;
<ide> if(asyncOption) {
<del> asyncChunk = compilation.addChunk(typeof asyncOption === "string" ? asyncOption : undefined);
<del> asyncChunk.chunkReason = "async commons chunk";
<del> asyncChunk.extraAsync = true;
<del> asyncChunk.addParent(commonChunk);
<add> asyncChunk = this.createAsyncChunk(compilation, this.async, commonChunk);
<ide> commonChunk.addChunk(asyncChunk);
<ide> commonChunk = asyncChunk;
<ide> } | 1 |
PHP | PHP | use new config setter in connection manager | e8baecdaadc28786f289e1c8bfafd7d0cc85c701 | <ide><path>src/Datasource/ConnectionManager.php
<ide> class ConnectionManager
<ide> {
<ide>
<ide> use StaticConfigTrait {
<del> config as protected _config;
<add> setConfig as protected _setConfig;
<ide> parseDsn as protected _parseDsn;
<ide> }
<ide>
<ide> class ConnectionManager
<ide> * @throws \Cake\Core\Exception\Exception When trying to modify an existing config.
<ide> * @see \Cake\Core\StaticConfigTrait::config()
<ide> */
<del> public static function config($key, $config = null)
<add> public static function setConfig($key, $config = null)
<ide> {
<ide> if (is_array($config)) {
<ide> $config['name'] = $key;
<ide> }
<ide>
<del> return static::_config($key, $config);
<add> return static::_setConfig($key, $config);
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | simplify check for wildcard listeners | 6aa3a468dab0f0ed93640221cc4a082176b95e7a | <ide><path>src/Illuminate/Events/Dispatcher.php
<ide> public function hasListeners($eventName)
<ide> */
<ide> public function hasWildcardListeners($eventName)
<ide> {
<del> foreach ($this->wildcards as $key => $listeners) {
<del> if (Str::is($key, $eventName)) {
<del> return true;
<del> }
<del> }
<del>
<del> return false;
<add> return Str::is(array_keys($this->wildcards), $eventName);
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | fix usage of word alternatively in docs [ci skip] | fe33c15d4d66b7a0ebd6257fb1eef21335424bba | <ide><path>actionpack/lib/action_dispatch/routing.rb
<ide> module ActionDispatch
<ide> # resources :posts, :comments
<ide> # end
<ide> #
<del> # Alternately, you can add prefixes to your path without using a separate
<add> # Alternatively, you can add prefixes to your path without using a separate
<ide> # directory by using +scope+. +scope+ takes additional options which
<ide> # apply to all enclosed routes.
<ide> #
<ide><path>actionview/lib/action_view/base.rb
<ide> module ActionView #:nodoc:
<ide> #
<ide> # Headline: <%= local_assigns[:headline] %>
<ide> #
<del> # This is useful in cases where you aren't sure if the local variable has been assigned. Alternately, you could also use
<add> # This is useful in cases where you aren't sure if the local variable has been assigned. Alternatively, you could also use
<ide> # <tt>defined? headline</tt> to first check if the variable has been assigned before using it.
<ide> #
<ide> # === Template caching | 2 |
PHP | PHP | fix html dump from artisan console | a879001ce96fae833695854b7f77a4f15b73a988 | <ide><path>src/Illuminate/Exception/ExceptionServiceProvider.php
<ide> protected function registerPlainDisplayer()
<ide> {
<ide> $this->app['exception.plain'] = $this->app->share(function($app)
<ide> {
<del> $handler = new KernelHandler($app['config']['app.debug']);
<add> // If the application is running in a console environment, we will just always
<add> // use the debug handler as there is no point in the console ever returning
<add> // out HTML. This debug handler always returns JSON from the console env.
<add> if ($app->runningInConsole())
<add> {
<add> return $app['exception.debug'];
<add> }
<add> else
<add> {
<add> $handler = new KernelHandler($app['config']['app.debug']);
<ide>
<del> return new SymfonyDisplayer($handler);
<add> return new SymfonyDisplayer($handler);
<add> }
<ide> });
<ide> }
<ide> | 1 |
Go | Go | implement docker wait with standalone client lib | 51efb1480a58b2317e1ad1833964ccad4456e6be | <ide><path>api/client/lib/wait.go
<add>package lib
<add>
<add>import (
<add> "encoding/json"
<add>
<add> "github.com/docker/docker/api/types"
<add>)
<add>
<add>// ContainerWait pauses execution util a container is exits.
<add>// It returns the API status code as response of its readiness.
<add>func (cli *Client) ContainerWait(containerID string) (int, error) {
<add> resp, err := cli.post("/containers/"+containerID+"/wait", nil, nil, nil)
<add> if err != nil {
<add> return -1, err
<add> }
<add> defer ensureReaderClosed(resp)
<add>
<add> var res types.ContainerWaitResponse
<add> if err := json.NewDecoder(resp.body).Decode(&res); err != nil {
<add> return -1, err
<add> }
<add>
<add> return res.StatusCode, nil
<add>}
<ide><path>api/client/run.go
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide> // No Autoremove: Simply retrieve the exit code
<ide> if !config.Tty {
<ide> // In non-TTY mode, we can't detach, so we must wait for container exit
<del> if status, err = waitForExit(cli, createResponse.ID); err != nil {
<add> if status, err = cli.client.ContainerWait(createResponse.ID); err != nil {
<ide> return err
<ide> }
<ide> } else {
<ide><path>api/client/utils.go
<ide> func (cli *DockerCli) resizeTty(id string, isExec bool) {
<ide> }
<ide> }
<ide>
<del>func waitForExit(cli *DockerCli, containerID string) (int, error) {
<del> serverResp, err := cli.call("POST", "/containers/"+containerID+"/wait", nil, nil)
<del> if err != nil {
<del> return -1, err
<del> }
<del>
<del> defer serverResp.body.Close()
<del>
<del> var res types.ContainerWaitResponse
<del> if err := json.NewDecoder(serverResp.body).Decode(&res); err != nil {
<del> return -1, err
<del> }
<del>
<del> return res.StatusCode, nil
<del>}
<del>
<ide> // getExitCode perform an inspect on the container. It returns
<ide> // the running state and the exit code.
<ide> func getExitCode(cli *DockerCli, containerID string) (bool, int, error) {
<ide><path>api/client/wait.go
<ide> func (cli *DockerCli) CmdWait(args ...string) error {
<ide>
<ide> var errNames []string
<ide> for _, name := range cmd.Args() {
<del> status, err := waitForExit(cli, name)
<add> status, err := cli.client.ContainerWait(name)
<ide> if err != nil {
<ide> fmt.Fprintf(cli.err, "%s\n", err)
<ide> errNames = append(errNames, name) | 4 |
Python | Python | create directory if missing in save_to_directory | d0e19267e8d14463a50f5ca24367015ca50c97d9 | <ide><path>spacy/language.py
<ide> def save_to_directory(self, path):
<ide> }
<ide>
<ide> path = util.ensure_path(path)
<add> if not path.exists():
<add> path.mkdir()
<ide> self.setup_directory(path, **configs)
<ide>
<ide> strings_loc = path / 'vocab' / 'strings.json' | 1 |
Javascript | Javascript | fix startof issues across dst with updateoffset | 3dd80ba2891a304511fb83da0ffb0ffa343b84c8 | <ide><path>moment.js
<ide> moment.fn.millisecond = moment.fn.milliseconds = makeAccessor('Milliseconds', false);
<ide> moment.fn.second = moment.fn.seconds = makeAccessor('Seconds', false);
<ide> moment.fn.minute = moment.fn.minutes = makeAccessor('Minutes', false);
<del> moment.fn.hour = moment.fn.hours = makeAccessor('Hours', false);
<add> // Setting the hour should keep the time, because the user explicitly
<add> // specified which hour he wants. So trying to maintain the same hour (in
<add> // a new timezone) makes sense. Adding/subtracting hours does not follow
<add> // this rule.
<add> moment.fn.hour = moment.fn.hours = makeAccessor('Hours', true);
<ide> // moment.fn.month is defined separately
<ide> moment.fn.date = makeAccessor('Date', true);
<ide> moment.fn.dates = deprecate("dates accessor is deprecated. Use date instead.", makeAccessor('Date', true));
<ide><path>test/moment/sod_eod.js
<ide> exports.end_start_of = {
<ide> test.equal(m.minutes(), 4, "keep the minutes");
<ide> test.equal(m.seconds(), 5, "keep the seconds");
<ide> test.equal(m.milliseconds(), 999, "set the seconds");
<add> test.done();
<add> },
<add>
<add> "startOf across DST +1" : function (test) {
<add> var oldUpdateOffset = moment.updateOffset,
<add> // Based on a real story somewhere in America/Los_Angeles
<add> dstAt = moment("2014-03-09T02:00:00-08:00").parseZone(),
<add> m;
<add>
<add> moment.updateOffset = function (mom, keepTime) {
<add> if (mom.isBefore(dstAt)) {
<add> mom.zone(8, keepTime);
<add> } else {
<add> mom.zone(7, keepTime);
<add> }
<add> }
<add>
<add> m = moment("2014-03-15T00:00:00-07:00").parseZone();
<add> m.startOf('M')
<add> test.equal(m.format(), "2014-03-01T00:00:00-08:00",
<add> "startOf('month') across +1");
<add>
<add> m = moment("2014-03-09T09:00:00-07:00").parseZone();
<add> m.startOf('d');
<add> test.equal(m.format(), "2014-03-09T00:00:00-08:00",
<add> "startOf('day') across +1");
<add>
<add> m = moment("2014-03-09T03:05:00-07:00").parseZone();
<add> m.startOf('h');
<add> test.equal(m.format(), "2014-03-09T03:00:00-07:00",
<add> "startOf('hour') after +1");
<add>
<add> m = moment("2014-03-09T01:35:00-08:00").parseZone();
<add> m.startOf('h');
<add> test.equal(m.format(), "2014-03-09T01:00:00-08:00",
<add> "startOf('hour') before +1");
<add>
<add> // There is no such time as 2:30-7 to try startOf('hour') across that
<add>
<add> moment.updateOffset = oldUpdateOffset;
<add>
<add> test.done();
<add> },
<add>
<add> "startOf across DST -1" : function (test) {
<add> var oldUpdateOffset = moment.updateOffset,
<add> // Based on a real story somewhere in America/Los_Angeles
<add> dstAt = moment("2014-11-02T02:00:00-07:00").parseZone(),
<add> m;
<add>
<add> moment.updateOffset = function (mom, keepTime) {
<add> if (mom.isBefore(dstAt)) {
<add> mom.zone(7, keepTime);
<add> } else {
<add> mom.zone(8, keepTime);
<add> }
<add> }
<add>
<add> m = moment("2014-11-15T00:00:00-08:00").parseZone();
<add> m.startOf('M')
<add> test.equal(m.format(), "2014-11-01T00:00:00-07:00",
<add> "startOf('month') across -1");
<add>
<add> m = moment("2014-11-02T09:00:00-08:00").parseZone();
<add> m.startOf('d');
<add> test.equal(m.format(), "2014-11-02T00:00:00-07:00",
<add> "startOf('day') across -1");
<add>
<add> // note that zone is -8
<add> m = moment("2014-11-02T01:30:00-08:00").parseZone();
<add> m.startOf('h');
<add> test.equal(m.format(), "2014-11-02T01:00:00-08:00",
<add> "startOf('hour') after +1");
<add>
<add> // note that zone is -7
<add> m = moment("2014-11-02T01:30:00-07:00").parseZone();
<add> m.startOf('h');
<add> test.equal(m.format(), "2014-11-02T01:00:00-07:00",
<add> "startOf('hour') before +1");
<add>
<add> moment.updateOffset = oldUpdateOffset;
<add>
<ide> test.done();
<ide> }
<ide> }; | 2 |
Ruby | Ruby | fix error if a compatible bottle was not found | 59dc0ed6521b98265230ac76e762064cedd25bcb | <ide><path>Library/Homebrew/cmd/--cache.rb
<ide> def __cache
<ide> sig { params(formula: Formula, args: CLI::Args).void }
<ide> def print_formula_cache(formula, args:)
<ide> if fetch_bottle?(formula, args: args)
<del> puts formula.bottle_for_tag(args.bottle_tag).cached_download
<add> puts formula.bottle_for_tag(args.bottle_tag&.to_sym).cached_download
<ide> elsif args.HEAD?
<ide> puts formula.head.cached_download
<ide> else
<ide><path>Library/Homebrew/cmd/fetch.rb
<ide> def fetch
<ide> begin
<ide> f.clear_cache if args.force?
<ide> f.fetch_bottle_tab
<del> fetch_formula(f.bottle_for_tag(args.bottle_tag), args: args)
<add> fetch_formula(f.bottle_for_tag(args.bottle_tag&.to_sym), args: args)
<ide> rescue Interrupt
<ide> raise
<ide> rescue => e
<ide><path>Library/Homebrew/formula.rb
<ide> def bottle
<ide>
<ide> # The Bottle object for given tag.
<ide> # @private
<del> sig { params(tag: T.nilable(String)).returns(T.nilable(Bottle)) }
<add> sig { params(tag: T.nilable(Symbol)).returns(T.nilable(Bottle)) }
<ide> def bottle_for_tag(tag = nil)
<ide> Bottle.new(self, bottle_specification, tag) if bottled?(tag)
<ide> end
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def pour_bottle?(output_warning: false)
<ide> return false
<ide> end
<ide>
<del> bottle = formula.bottle
<del> if bottle && !bottle.compatible_locations?
<add> bottle = formula.bottle_for_tag(Utils::Bottles.tag.to_sym)
<add> return false if bottle.nil?
<add>
<add> unless bottle.compatible_locations?
<ide> if output_warning
<ide> prefix = Pathname(bottle.cellar).parent
<ide> opoo <<~EOS | 4 |
PHP | PHP | simplify boolean check | 2cfdc9228dd0a227e6ecc8d90d4e6d405b05ccb3 | <ide><path>src/Database/Statement/StatementDecorator.php
<ide> public function bind(array $params, array $types): void
<ide> return;
<ide> }
<ide>
<del> $anonymousParams = is_int(key($params)) ? true : false;
<add> $anonymousParams = is_int(key($params));
<ide> $offset = 1;
<ide> foreach ($params as $index => $value) {
<ide> $type = $types[$index] ?? null; | 1 |
Javascript | Javascript | run the basic tests for each helper configuration | 5fa2a238b69e6067d3a43ca576ea268be22be4fd | <ide><path>packages/ember-glimmer/tests/integration/helpers/inline-if-test.js
<ide> moduleFor('@glimmer Helpers test: {{if}} used with another helper', class extend
<ide> return `(if ${cond} ${truthy} ${falsy})`;
<ide> }
<ide>
<del>});
<add>}, BASIC_TRUTHY_TESTS, BASIC_FALSY_TESTS);
<ide>
<ide> moduleFor('@glimmer Helpers test: {{if}} used in attribute position', class extends SharedHelperConditionalsTest {
<ide>
<ide> moduleFor('@glimmer Helpers test: {{if}} used in attribute position', class exte
<ide> return this.$('div').attr('data-foo');
<ide> }
<ide>
<del>});
<add>}, BASIC_TRUTHY_TESTS, BASIC_FALSY_TESTS); | 1 |
PHP | PHP | fix example & incorrect import | 6292fc707d5d4cf885c0a10a6a3abdb6dc263d3c | <ide><path>lib/Cake/Routing/Route/CakeRoute.php
<ide> * @since CakePHP(tm) v 1.3
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<del>
<del>App::uses('Set', 'Utility');
<add>App::uses('Hash', 'Utility');
<ide>
<ide> /**
<ide> * A single Route used by the Router to connect requests to
<ide><path>lib/Cake/Routing/Router.php
<ide> public static function resourceMap($resourceMap = null) {
<ide> * - `named` is used to configure named parameters at the route level. This key uses the same options
<ide> * as Router::connectNamed()
<ide> *
<del> * In addition to the 4 keys listed above, you can add additional conditions for matching routes.
<add> * You can also add additional conditions for matching routes to the $defaults array.
<ide> * The following conditions can be used:
<ide> *
<ide> * - `[type]` Only match requests for specific content types.
<ide> public static function resourceMap($resourceMap = null) {
<ide> *
<ide> * Example of using the `[method]` condition:
<ide> *
<del> * `Router::connect('/tasks', array('controller' => 'tasks', 'action' => 'index'), array('[method]' => 'GET'));`
<add> * `Router::connect('/tasks', array('controller' => 'tasks', 'action' => 'index', '[method]' => 'GET'));`
<ide> *
<ide> * The above route will only be matched for GET requests. POST requests will fail to match this route.
<ide> * | 2 |
Javascript | Javascript | remove iscomposite and hide toplevelwrapper | acd67c368d1ff66d80657094f136e87b36413210 | <ide><path>src/isomorphic/ReactDebugTool.js
<ide> function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) {
<ide> }
<ide> }
<ide>
<add>// This can be removed once TopLevelWrapper is gone.
<add>function isTopLevelWrapper(debugID) {
<add> return debugID === 0;
<add>}
<add>
<ide> var ReactDebugTool = {
<ide> addDevtool(devtool) {
<ide> eventHandlers.push(devtool);
<ide> var ReactDebugTool = {
<ide> onSetState() {
<ide> emitEvent('onSetState');
<ide> },
<del> onSetIsTopLevelWrapper(debugID, isTopLevelWrapper) {
<del> emitEvent('onSetIsTopLevelWrapper', debugID, isTopLevelWrapper);
<del> },
<del> onSetIsComposite(debugID, isComposite) {
<del> emitEvent('onSetIsComposite', debugID, isComposite);
<del> },
<ide> onSetDisplayName(debugID, displayName) {
<ide> emitEvent('onSetDisplayName', debugID, displayName);
<ide> },
<add> onSetIsEmpty(debugID, isEmpty) {
<add> emitEvent('onSetIsEmpty', debugID, isEmpty);
<add> },
<ide> onSetChildren(debugID, childDebugIDs) {
<del> emitEvent('onSetChildren', debugID, childDebugIDs);
<add> if (!isTopLevelWrapper(debugID)) {
<add> emitEvent('onSetChildren', debugID, childDebugIDs);
<add> }
<ide> },
<ide> onSetOwner(debugID, ownerDebugID) {
<ide> emitEvent('onSetOwner', debugID, ownerDebugID);
<ide> var ReactDebugTool = {
<ide> onMountRootComponent(debugID) {
<ide> emitEvent('onMountRootComponent', debugID);
<ide> },
<del> onMountComponent(debugID, nativeContainerDebugID) {
<del> emitEvent('onMountComponent', debugID, nativeContainerDebugID);
<add> onMountComponent(debugID) {
<add> if (!isTopLevelWrapper(debugID)) {
<add> emitEvent('onMountComponent', debugID);
<add> }
<ide> },
<ide> onUpdateComponent(debugID) {
<del> emitEvent('onUpdateComponent', debugID);
<add> if (!isTopLevelWrapper(debugID)) {
<add> emitEvent('onUpdateComponent', debugID);
<add> }
<ide> },
<ide> onUnmountComponent(debugID) {
<del> emitEvent('onUnmountComponent', debugID);
<del> },
<del> onUnmountNativeContainer(nativeContainerDebugID) {
<del> emitEvent('onUnmountNativeContainer', nativeContainerDebugID);
<add> if (!isTopLevelWrapper(debugID)) {
<add> emitEvent('onUnmountComponent', debugID);
<add> }
<ide> },
<ide> };
<ide>
<ide><path>src/isomorphic/devtools/ReactComponentTreeDevtool.js
<ide>
<ide> var invariant = require('invariant');
<ide>
<del>var unmountedContainerIDs = [];
<ide> var tree = {};
<add>var rootIDs = [];
<ide>
<ide> function updateTree(id, update) {
<ide> if (!tree[id]) {
<ide> tree[id] = {
<del> nativeContainerID: null,
<ide> parentID: null,
<ide> ownerID: null,
<ide> text: null,
<ide> childIDs: [],
<ide> displayName: 'Unknown',
<del> isTopLevelWrapper: false,
<add> isMounted: false,
<add> isEmpty: false,
<ide> };
<ide> }
<ide> update(tree[id]);
<ide> }
<ide>
<del>function purgeTree(id) {
<add>function purgeDeep(id) {
<ide> var item = tree[id];
<ide> if (item) {
<ide> var {childIDs} = item;
<ide> delete tree[id];
<del> childIDs.forEach(purgeTree);
<add> childIDs.forEach(purgeDeep);
<ide> }
<ide> }
<ide>
<ide> var ReactComponentTreeDevtool = {
<del> onSetIsTopLevelWrapper(id, isTopLevelWrapper) {
<del> updateTree(id, item => item.isTopLevelWrapper = isTopLevelWrapper);
<del> },
<del>
<del> onSetIsComposite(id, isComposite) {
<del> updateTree(id, item => item.isComposite = isComposite);
<add> onSetIsEmpty(id, isEmpty) {
<add> updateTree(id, item => item.isEmpty = isEmpty);
<ide> },
<ide>
<ide> onSetDisplayName(id, displayName) {
<ide> updateTree(id, item => item.displayName = displayName);
<ide> },
<ide>
<ide> onSetChildren(id, nextChildIDs) {
<del> if (ReactComponentTreeDevtool.isTopLevelWrapper(id)) {
<del> return;
<del> }
<del>
<ide> updateTree(id, item => {
<ide> var prevChildIDs = item.childIDs;
<ide> item.childIDs = nextChildIDs;
<ide>
<del> prevChildIDs.forEach(prevChildID => {
<del> var prevChild = tree[prevChildID];
<del> if (prevChild && nextChildIDs.indexOf(prevChildID) === -1) {
<del> prevChild.parentID = null;
<del> }
<del> });
<del>
<ide> nextChildIDs.forEach(nextChildID => {
<ide> var nextChild = tree[nextChildID];
<ide> invariant(
<ide> nextChild,
<ide> 'Expected devtool events to fire for the child ' +
<ide> 'before its parent includes it in onSetChildren().'
<ide> );
<del> invariant(
<del> nextChild.isComposite != null,
<del> 'Expected onSetIsComposite() to fire for the child ' +
<del> 'before its parent includes it in onSetChildren().'
<del> );
<ide> invariant(
<ide> nextChild.displayName != null,
<ide> 'Expected onSetDisplayName() to fire for the child ' +
<ide> 'before its parent includes it in onSetChildren().'
<ide> );
<ide> invariant(
<ide> nextChild.childIDs != null || nextChild.text != null,
<del> 'Expected either onSetChildren() or onSetText() to fire for the child ' +
<add> 'Expected onSetChildren() or onSetText() to fire for the child ' +
<add> 'before its parent includes it in onSetChildren().'
<add> );
<add> invariant(
<add> nextChild.isMounted,
<add> 'Expected onMountComponent() to fire for the child ' +
<ide> 'before its parent includes it in onSetChildren().'
<ide> );
<ide>
<ide> var ReactComponentTreeDevtool = {
<ide> updateTree(id, item => item.text = text);
<ide> },
<ide>
<del> onMountComponent(id, nativeContainerID) {
<del> updateTree(id, item => item.nativeContainerID = nativeContainerID);
<add> onMountComponent(id) {
<add> updateTree(id, item => item.isMounted = true);
<ide> },
<ide>
<del> onUnmountComponent(id) {
<del> purgeTree(id);
<add> onMountRootComponent(id) {
<add> rootIDs.push(id);
<ide> },
<ide>
<del> onUnmountNativeContainer(nativeContainerID) {
<del> unmountedContainerIDs.push(nativeContainerID);
<add> onUnmountComponent(id) {
<add> updateTree(id, item => item.isMounted = false);
<add> rootIDs = rootIDs.filter(rootID => rootID !== id);
<ide> },
<ide>
<ide> purgeUnmountedComponents() {
<del> var unmountedIDs = Object.keys(tree).filter(id =>
<del> unmountedContainerIDs.indexOf(tree[id].nativeContainerID) !== -1
<del> );
<del> unmountedContainerIDs = [];
<del> unmountedIDs.forEach(purgeTree);
<add> Object.keys(tree)
<add> .filter(id => !tree[id].isMounted)
<add> .forEach(purgeDeep);
<ide> },
<ide>
<del> isComposite(id) {
<add> isMounted(id) {
<ide> var item = tree[id];
<del> return item ? item.isComposite : false;
<del> },
<del>
<del> isTopLevelWrapper(id) {
<del> var item = tree[id];
<del> return item ? item.isTopLevelWrapper : false;
<add> return item ? item.isMounted : false;
<ide> },
<ide>
<ide> getChildIDs(id) {
<ide> var item = tree[id];
<del> return item ? item.childIDs : [];
<add> return item ? item.childIDs.filter(childID => !tree[childID].isEmpty) : [];
<ide> },
<ide>
<ide> getDisplayName(id) {
<ide> var ReactComponentTreeDevtool = {
<ide> return item ? item.text : null;
<ide> },
<ide>
<add> getRootIDs() {
<add> return rootIDs;
<add> },
<add>
<ide> getRegisteredIDs() {
<ide> return Object.keys(tree);
<ide> },
<ide><path>src/isomorphic/devtools/__tests__/ReactComponentTreeDevtool-test.js
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> ReactDebugTool.removeDevtool(ReactComponentTreeDevtool);
<ide> });
<ide>
<add> function getRootDisplayNames() {
<add> return ReactComponentTreeDevtool.getRootIDs()
<add> .map(ReactComponentTreeDevtool.getDisplayName);
<add> }
<add>
<ide> function getRegisteredDisplayNames() {
<ide> return ReactComponentTreeDevtool.getRegisteredIDs()
<del> .filter(id => !ReactComponentTreeDevtool.isTopLevelWrapper(id))
<ide> .map(ReactComponentTreeDevtool.getDisplayName);
<ide> }
<ide>
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> } = options;
<ide>
<ide> var result = {
<del> isComposite: ReactComponentTreeDevtool.isComposite(rootID),
<ide> displayName: ReactComponentTreeDevtool.getDisplayName(rootID),
<ide> };
<ide>
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> currentElement = element;
<ide> ReactDOM.render(<Wrapper />, node);
<ide> expect(getActualTree()).toEqual(expectedTree);
<add> ReactComponentTreeDevtool.purgeUnmountedComponents();
<add> expect(getActualTree()).toEqual(expectedTree);
<ide> });
<ide> ReactDOM.unmountComponentAtNode(node);
<ide>
<del> var lastExpectedTree = pairs[pairs.length - 1][1];
<del> expect(getActualTree()).toEqual(lastExpectedTree);
<del>
<ide> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toBe(undefined);
<add> expect(getRootDisplayNames()).toEqual([]);
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide>
<ide> pairs.forEach(([element, expectedTree]) => {
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> ReactComponentTreeDevtool.purgeUnmountedComponents();
<ide> expect(getActualTree()).toBe(undefined);
<add> expect(getRootDisplayNames()).toEqual([]);
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> });
<ide> }
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var element = <div><Foo /><Baz /><Qux /></div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Baz',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Unknown',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var element = <div><Foo /><Baz /><Qux /></div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Baz',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> // Note: Ideally fallback name should be consistent (e.g. "Unknown")
<ide> displayName: 'ReactComponent',
<ide> children: [],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var element = <div><Foo /><Baz /><Qux /></div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Baz',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Unknown',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var element = <div><Foo /><Baz /><Qux /></div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Baz',
<ide> children: [],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Unknown',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'p',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'span',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi!',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Wow.',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: 'hr',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var element = <Foo />;
<ide> var tree = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var element = <Baz />;
<ide> var tree = {
<del> isComposite: true,
<ide> displayName: 'Baz',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Qux',
<ide> children: [],
<ide> }],
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'h1',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'span',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi,',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Mom',
<ide> }],
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: 'a',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Click me.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> }
<ide> var element = <Foo />;
<ide> var tree = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> }
<ide> var element = <Foo />;
<ide> var tree = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('reports text nodes as children', () => {
<ide> var element = <div>{'1'}{2}</div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '1',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '2',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('reports a single text node as a child', () => {
<ide> var element = <div>{'1'}</div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '1',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('reports a single number node as a child', () => {
<ide> var element = <div>{42}</div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '42',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('reports a zero as a child', () => {
<ide> var element = <div>{0}</div>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '0',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'hi',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '42',
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('reports html content as no children', () => {
<ide> var element = <div dangerouslySetInnerHTML={{__html: 'Bye.'}} />;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates text of a single text child', () => {
<ide> var elementBefore = <div>Hi.</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div>Bye.</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from no children to a single text child', () => {
<ide> var elementBefore = <div />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div>Hi.</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from a single text child to no children', () => {
<ide> var elementBefore = <div>Hi.</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from html content to a single text child', () => {
<ide> var elementBefore = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div>Hi.</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from a single text child to html content', () => {
<ide> var elementBefore = <div>Hi.</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from no children to multiple text children', () => {
<ide> var elementBefore = <div />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from multiple text children to no children', () => {
<ide> var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from html content to multiple text children', () => {
<ide> var elementBefore = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from multiple text children to html content', () => {
<ide> var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from html content to no children', () => {
<ide> var elementBefore = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from no children to html content', () => {
<ide> var elementBefore = <div />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div dangerouslySetInnerHTML={{__html: 'Hi.'}} />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from one text child to multiple text children', () => {
<ide> var elementBefore = <div>Hi.</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates from multiple text children to one text child', () => {
<ide> var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div>Hi.</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> it('updates text nodes when reordering', () => {
<ide> var elementBefore = <div>{'Hi.'}{'Bye.'}</div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div>{'Bye.'}{'Hi.'}</div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Bye.',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <div><Foo /></div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div><Bar /></div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <div><Foo><div /></Foo></div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementAfter = <div><Foo><span /></Foo></div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'span',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <div />;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <div><Foo /></div>;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <div><Foo /></div>;
<ide> var treeBefore = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <div />;
<ide> var treeAfter = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var tree1 = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'hi',
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: '42',
<ide> }, {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var tree2 = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'hi',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> </div>
<ide> );
<ide> var tree3 = {
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><div /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo><span /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'span',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo>{null}</Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <Foo><div /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><div /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo>{null}</Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><div /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo><Bar /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><Bar /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo><div /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo>{null}</Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <Foo><Bar /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><Bar /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo>{null}</Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><div /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo><span /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'span',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo>{null}</Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <Foo><div /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><div /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo>{null}</Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><div /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo><Bar /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><Bar /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo><div /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo>{null}</Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide>
<ide> var elementAfter = <Foo><Bar /></Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide>
<ide> var elementBefore = <Foo><Bar /></Foo>;
<ide> var treeBefore = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> children: [],
<ide> }],
<ide> };
<ide>
<ide> var elementAfter = <Foo>{null}</Foo>;
<ide> var treeAfter = {
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [],
<ide> };
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> // because they are not created from real elements.
<ide> var element = <article><Foo /></article>;
<ide> var tree = {
<del> isComposite: false,
<ide> displayName: 'article',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Foo',
<ide> children: [{
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> ownerDisplayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'div',
<ide> ownerDisplayName: 'Bar',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: 'h1',
<ide> ownerDisplayName: 'Foo',
<ide> children: [{
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: 'Hi.',
<ide> }],
<ide> }, {
<del> isComposite: false,
<ide> displayName: '#text',
<ide> text: ' Mom',
<ide> }],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> assertTreeMatches([element, tree], {includeOwnerDisplayName: true});
<ide> });
<ide>
<del> it.only('preserves unmounted components until purge', () => {
<add> it('preserves unmounted components until purge', () => {
<ide> var node = document.createElement('div');
<ide> var renderBar = true;
<ide> var fooInstance;
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> expect(
<ide> getTree(barInstance._debugID, {
<ide> includeParentDisplayName: true,
<del> expectedParentID: fooInstance._debugID
<add> expectedParentID: fooInstance._debugID,
<ide> })
<ide> ).toEqual({
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> parentDisplayName: 'Foo',
<ide> children: [],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> expect(
<ide> getTree(barInstance._debugID, {
<ide> includeParentDisplayName: true,
<del> expectedParentID: fooInstance._debugID
<add> expectedParentID: fooInstance._debugID,
<ide> })
<ide> ).toEqual({
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> parentDisplayName: 'Foo',
<ide> children: [],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> expectedParentID: fooInstance._debugID,
<ide> })
<ide> ).toEqual({
<del> isComposite: true,
<ide> displayName: 'Bar',
<ide> parentDisplayName: 'Foo',
<ide> children: [],
<ide> describe('ReactComponentTreeDevtool', () => {
<ide> expect(
<ide> getTree(barInstance._debugID, {includeParentDisplayName: true})
<ide> ).toEqual({
<del> isComposite: false,
<ide> displayName: 'Unknown',
<ide> children: [],
<ide> });
<ide> });
<ide>
<del> it('ignores top-level wrapper', () => {
<add> it('does not report top-level wrapper as a root', () => {
<ide> var node = document.createElement('div');
<add>
<ide> ReactDOM.render(<div className="a" />, node);
<del> expect(getRegisteredDisplayNames()).toEqual(['div']);
<add> expect(getRootDisplayNames()).toEqual(['div']);
<add>
<ide> ReactDOM.render(<div className="b" />, node);
<del> expect(getRegisteredDisplayNames()).toEqual(['div']);
<add> expect(getRootDisplayNames()).toEqual(['div']);
<add>
<ide> ReactDOM.unmountComponentAtNode(node);
<del> expect(getRegisteredDisplayNames()).toEqual(['div']);
<add> expect(getRootDisplayNames()).toEqual([]);
<add>
<ide> ReactComponentTreeDevtool.purgeUnmountedComponents();
<add> expect(getRootDisplayNames()).toEqual([]);
<add>
<add> // This currently contains TopLevelWrapper until purge
<add> // so we only check it at the very end.
<ide> expect(getRegisteredDisplayNames()).toEqual([]);
<ide> });
<ide> });
<ide><path>src/renderers/dom/client/ReactMount.js
<ide> var ReactMount = {
<ide>
<ide> ReactBrowserEventEmitter.ensureScrollValueMonitoring();
<ide> var componentInstance = instantiateReactComponent(nextElement);
<add>
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetIsTopLevelWrapper(
<del> componentInstance._debugID,
<del> true
<del> );
<add> // Mute future events from the top level wrapper.
<add> // It is an implementation detail that devtools should not know about.
<add> componentInstance._debugID = 0;
<ide> }
<ide>
<ide> // The initial render is synchronous but any updates that happen during
<ide> var ReactMount = {
<ide> instancesByReactRootID[wrapperID] = componentInstance;
<ide>
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onMountRootComponent(componentInstance._debugID);
<add> // The instance here is TopLevelWrapper so we report mount for its child.
<add> ReactInstrumentation.debugTool.onMountRootComponent(
<add> componentInstance._renderedComponent._debugID
<add> );
<ide> }
<ide>
<ide> return componentInstance;
<ide> var ReactMount = {
<ide> container,
<ide> false
<ide> );
<del> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onUnmountNativeContainer(
<del> prevComponent._nativeContainerInfo._debugID
<del> );
<del> }
<ide> return true;
<ide> },
<ide>
<ide><path>src/renderers/dom/server/ReactServerRendering.js
<ide> function renderToStringImpl(element, makeStaticMarkup) {
<ide>
<ide> return transaction.perform(function() {
<ide> var componentInstance = instantiateReactComponent(element);
<del> var nativeContainerInfo = ReactDOMContainerInfo();
<ide> var markup = ReactReconciler.mountComponent(
<ide> componentInstance,
<ide> transaction,
<ide> null,
<del> nativeContainerInfo,
<add> ReactDOMContainerInfo(),
<ide> emptyObject
<ide> );
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onUnmountNativeContainer(
<del> nativeContainerInfo._debugID
<add> ReactInstrumentation.debugTool.onUnmountComponent(
<add> componentInstance._debugID
<ide> );
<ide> }
<ide> if (!makeStaticMarkup) {
<ide><path>src/renderers/dom/shared/ReactDOMComponent.js
<ide> var ReactInstrumentation = require('ReactInstrumentation');
<ide> var ReactMultiChild = require('ReactMultiChild');
<ide> var ReactPerf = require('ReactPerf');
<ide>
<add>var emptyFunction = require('emptyFunction');
<ide> var escapeTextContentForBrowser = require('escapeTextContentForBrowser');
<ide> var invariant = require('invariant');
<ide> var isEventSupported = require('isEventSupported');
<ide> function optionPostMount() {
<ide> ReactDOMOption.postMountWrapper(inst);
<ide> }
<ide>
<add>var setContentChildForInstrumentation = emptyFunction;
<add>if (__DEV__) {
<add> setContentChildForInstrumentation = function(contentToUse) {
<add> var debugID = this._debugID;
<add> var contentDebugID = debugID + '#text';
<add> this._contentDebugID = contentDebugID;
<add> ReactInstrumentation.debugTool.onSetIsEmpty(contentDebugID, false);
<add> ReactInstrumentation.debugTool.onSetDisplayName(contentDebugID, '#text');
<add> ReactInstrumentation.debugTool.onSetText(contentDebugID, '' + contentToUse);
<add> ReactInstrumentation.debugTool.onMountComponent(contentDebugID);
<add> ReactInstrumentation.debugTool.onSetChildren(debugID, [contentDebugID]);
<add> };
<add>}
<add>
<ide> // There are so many media events, it makes sense to just
<ide> // maintain a list rather than create a `trapBubbledEvent` for each
<ide> var mediaEvents = {
<ide> ReactDOMComponent.Mixin = {
<ide> // TODO: Validate that text is allowed as a child of this node
<ide> ret = escapeTextContentForBrowser(contentToUse);
<ide> if (__DEV__) {
<del> this._contentDebugID = this._debugID + '#text';
<del> ReactInstrumentation.debugTool.onSetIsComposite(this._contentDebugID, false);
<del> ReactInstrumentation.debugTool.onSetDisplayName(this._contentDebugID, '#text');
<del> ReactInstrumentation.debugTool.onSetText(this._contentDebugID, '' + contentToUse);
<del> ReactInstrumentation.debugTool.onSetChildren(this._debugID, [this._contentDebugID]);
<add> setContentChildForInstrumentation.call(this, contentToUse);
<ide> }
<ide> } else if (childrenToUse != null) {
<ide> var mountImages = this.mountChildren(
<ide> ReactDOMComponent.Mixin = {
<ide> if (contentToUse != null) {
<ide> // TODO: Validate that text is allowed as a child of this node
<ide> if (__DEV__) {
<del> this._contentDebugID = this._debugID + '#text';
<del> ReactInstrumentation.debugTool.onSetIsComposite(this._contentDebugID, false);
<del> ReactInstrumentation.debugTool.onSetDisplayName(this._contentDebugID, '#text');
<del> ReactInstrumentation.debugTool.onSetText(this._contentDebugID, '' + contentToUse);
<del> ReactInstrumentation.debugTool.onSetChildren(this._debugID, [this._contentDebugID]);
<add> setContentChildForInstrumentation.call(this, contentToUse);
<ide> }
<ide> DOMLazyTree.queueText(lazyTree, contentToUse);
<ide> } else if (childrenToUse != null) {
<ide> ReactDOMComponent.Mixin = {
<ide> this.updateTextContent('' + nextContent);
<ide> if (__DEV__) {
<ide> this._contentDebugID = this._debugID + '#text';
<del> ReactInstrumentation.debugTool.onSetIsComposite(this._contentDebugID, false);
<del> ReactInstrumentation.debugTool.onSetDisplayName(this._contentDebugID, '#text');
<del> ReactInstrumentation.debugTool.onSetText(this._contentDebugID, '' + nextContent);
<del> ReactInstrumentation.debugTool.onSetChildren(this._debugID, [this._contentDebugID]);
<add> setContentChildForInstrumentation.call(this, nextContent);
<ide> }
<ide> }
<ide> } else if (nextHtml != null) {
<ide><path>src/renderers/dom/shared/ReactDOMContainerInfo.js
<ide> var validateDOMNesting = require('validateDOMNesting');
<ide>
<ide> var DOC_NODE_TYPE = 9;
<del>var nextContainerDebugID = 1;
<ide>
<ide> function ReactDOMContainerInfo(topLevelWrapper, node) {
<ide> var info = {
<ide> function ReactDOMContainerInfo(topLevelWrapper, node) {
<ide> _namespaceURI: node ? node.namespaceURI : null,
<ide> };
<ide> if (__DEV__) {
<del> info._debugID = nextContainerDebugID++;
<ide> info._ancestorInfo = node ?
<ide> validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null;
<ide> }
<ide><path>src/renderers/shared/reconciler/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = {
<ide> this._renderedComponent = this._instantiateReactComponent(
<ide> renderedElement
<ide> );
<del> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetChildren(
<del> this._debugID,
<del> this._renderedNodeType === ReactNodeTypes.EMPTY ?
<del> [] :
<del> [this._renderedComponent._debugID]
<del> );
<del> }
<ide>
<ide> var markup = ReactReconciler.mountComponent(
<ide> this._renderedComponent,
<ide> var ReactCompositeComponentMixin = {
<ide> this._processChildContext(context)
<ide> );
<ide>
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onSetChildren(
<add> this._debugID,
<add> [this._renderedComponent._debugID]
<add> );
<add> }
<add>
<ide> return markup;
<ide> },
<ide>
<ide> var ReactCompositeComponentMixin = {
<ide> this._renderedComponent = this._instantiateReactComponent(
<ide> nextRenderedElement
<ide> );
<del> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetChildren(
<del> this._debugID,
<del> this._renderedNodeType === ReactNodeTypes.EMPTY ?
<del> [] :
<del> [this._renderedComponent._debugID]
<del> );
<del> }
<ide>
<ide> var nextMarkup = ReactReconciler.mountComponent(
<ide> this._renderedComponent,
<ide> var ReactCompositeComponentMixin = {
<ide> this._nativeContainerInfo,
<ide> this._processChildContext(context)
<ide> );
<add>
<add> if (__DEV__) {
<add> ReactInstrumentation.debugTool.onSetChildren(
<add> this._debugID,
<add> [this._renderedComponent._debugID]
<add> );
<add> }
<add>
<ide> this._replaceNodeWithMarkup(oldNativeNode, nextMarkup);
<ide> }
<ide> },
<ide><path>src/renderers/shared/reconciler/ReactMultiChild.js
<ide> var ReactCurrentOwner = require('ReactCurrentOwner');
<ide> var ReactReconciler = require('ReactReconciler');
<ide> var ReactChildReconciler = require('ReactChildReconciler');
<ide>
<add>var emptyFunction = require('emptyFunction');
<ide> var flattenChildren = require('flattenChildren');
<ide> var invariant = require('invariant');
<ide>
<ide> function processQueue(inst, updateQueue) {
<ide> );
<ide> }
<ide>
<add>var setChildrenForInstrumentation = emptyFunction;
<add>if (__DEV__) {
<add> setChildrenForInstrumentation = function(children) {
<add> ReactInstrumentation.debugTool.onSetChildren(
<add> this._debugID,
<add> children ? Object.keys(children).map(key => children[key]._debugID) : []
<add> );
<add> };
<add>}
<add>
<ide> /**
<ide> * ReactMultiChild are capable of reconciling multiple children.
<ide> *
<ide> var ReactMultiChild = {
<ide> }
<ide>
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetChildren(
<del> this._debugID,
<del> children ?
<del> Object.keys(children).map(key => children[key]._debugID) :
<del> []
<del> );
<add> setChildrenForInstrumentation.call(this, children);
<ide> }
<ide>
<ide> return mountImages;
<ide> var ReactMultiChild = {
<ide> this._renderedChildren = nextChildren;
<ide>
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onSetChildren(
<del> this._debugID,
<del> nextChildren ?
<del> Object.keys(nextChildren).map(key => nextChildren[key]._debugID) :
<del> []
<del> );
<add> setChildrenForInstrumentation.call(this, nextChildren);
<ide> }
<ide> },
<ide>
<ide><path>src/renderers/shared/reconciler/ReactReconciler.js
<ide> var ReactReconciler = {
<ide> transaction.getReactMountReady().enqueue(attachRefs, internalInstance);
<ide> }
<ide> if (__DEV__) {
<del> ReactInstrumentation.debugTool.onMountComponent(
<del> internalInstance._debugID,
<del> nativeContainerInfo._debugID
<del> );
<add> ReactInstrumentation.debugTool.onMountComponent(internalInstance._debugID);
<ide> }
<ide> return markup;
<ide> },
<ide><path>src/renderers/shared/reconciler/instantiateReactComponent.js
<ide> function instantiateReactComponent(node) {
<ide>
<ide> var isNative = false;
<ide> var isComposite = false;
<add> var isEmpty = false;
<ide>
<ide> if (node === null || node === false) {
<add> isEmpty = true;
<ide> instance = ReactEmptyComponent.create(instantiateReactComponent);
<ide> } else if (typeof node === 'object') {
<ide> var element = node;
<ide> function instantiateReactComponent(node) {
<ide> }
<ide>
<ide> if (__DEV__) {
<del> instance._debugID = nextDebugID++;
<add> var debugID = nextDebugID++;
<add> instance._debugID = debugID;
<add>
<ide> var displayName = getDisplayName(instance);
<del> ReactInstrumentation.debugTool.onSetIsComposite(instance._debugID, isComposite);
<del> ReactInstrumentation.debugTool.onSetDisplayName(instance._debugID, displayName);
<add> ReactInstrumentation.debugTool.onSetDisplayName(debugID, displayName);
<add> ReactInstrumentation.debugTool.onSetIsEmpty(debugID, isEmpty);
<ide> if (isNative || isComposite) {
<del> ReactInstrumentation.debugTool.onSetChildren(instance._debugID, []);
<add> ReactInstrumentation.debugTool.onSetChildren(debugID, []);
<ide> }
<ide> var owner = node && node._owner;
<ide> if (owner) {
<del> ReactInstrumentation.debugTool.onSetOwner(instance._debugID, owner._debugID);
<add> ReactInstrumentation.debugTool.onSetOwner(debugID, owner._debugID);
<ide> }
<ide> }
<ide>
<ide><path>src/test/ReactTestUtils.js
<ide> ReactShallowRenderer.prototype._render = function(element, transaction, context)
<ide> this._instance.receiveComponent(element, transaction, context);
<ide> } else {
<ide> var instance = new ShallowComponentWrapper(element);
<del> instance.mountComponent(transaction, null, {}, context);
<add> instance.mountComponent(transaction, null, null, context);
<ide> this._instance = instance;
<ide> }
<ide> }; | 12 |
Javascript | Javascript | fix haste resolution (and better warnings) | fa0da5682b17e93b4d06957b5aa27797ee5bbcd9 | <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/HasteMap.js
<ide> const chalk = require('chalk');
<ide> const path = require('path');
<ide> const getPlatformExtension = require('../../lib/getPlatformExtension');
<ide>
<add>const GENERIC_PLATFORM = 'generic';
<add>
<ide> class HasteMap {
<ide> constructor({ fastfs, moduleCache, helpers }) {
<ide> this._fastfs = fastfs;
<ide> class HasteMap {
<ide> /*eslint no-labels: 0 */
<ide> if (type === 'delete' || type === 'change') {
<ide> loop: for (let name in this._map) {
<del> let modules = this._map[name];
<del> for (var i = 0; i < modules.length; i++) {
<del> if (modules[i].path === absPath) {
<del> modules.splice(i, 1);
<del> break loop;
<add> const modulesMap = this._map[name];
<add> for (let platform in modulesMap) {
<add> const modules = modulesMap[platform];
<add> for (var i = 0; i < modules.length; i++) {
<add> if (modules[i].path === absPath) {
<add> modules.splice(i, 1);
<add> break loop;
<add> }
<ide> }
<ide> }
<ide> }
<ide> class HasteMap {
<ide> }
<ide>
<ide> getModule(name, platform = null) {
<del> if (!this._map[name]) {
<add> const modulesMap = this._map[name];
<add> if (modulesMap == null) {
<ide> return null;
<ide> }
<ide>
<del> const modules = this._map[name];
<del> if (platform != null) {
<del> for (let i = 0; i < modules.length; i++) {
<del> if (getPlatformExtension(modules[i].path) === platform) {
<del> return modules[i];
<del> }
<add> // If no platform is given we choose the generic platform module list.
<add> // If a platform is given and no modules exist we fallback
<add> // to the generic platform module list.
<add> let modules;
<add> if (platform == null) {
<add> modules = modulesMap[GENERIC_PLATFORM];
<add> } else {
<add> modules = modulesMap[platform];
<add> if (modules == null) {
<add> modules = modulesMap[GENERIC_PLATFORM];
<ide> }
<add> }
<ide>
<del> if (modules.length > 1) {
<del> if (!this._warnedAbout[name]) {
<del> this._warnedAbout[name] = true;
<del> console.warn(
<del> chalk.yellow(
<del> '\nWARNING: Found multiple haste modules or packages ' +
<del> 'with the name `%s`. Please fix this by adding it to ' +
<del> 'the blacklist or deleting the modules keeping only one.\n' +
<del> 'One of the following modules will be selected at random:\n%s\n'
<del> ),
<del> name,
<del> modules.map(m => m.path).join('\n'),
<del> );
<del> }
<add> if (modules == null) {
<add> return null;
<add> }
<ide>
<del> const randomIndex = Math.floor(Math.random() * modules.length);
<del> return modules[randomIndex];
<add> if (modules.length > 1) {
<add> if (!this._warnedAbout[name]) {
<add> this._warnedAbout[name] = true;
<add> console.warn(
<add> chalk.yellow(
<add> '\nWARNING: Found multiple haste modules or packages ' +
<add> 'with the name `%s`. Please fix this by adding it to ' +
<add> 'the blacklist or deleting the modules keeping only one.\n' +
<add> 'One of the following modules will be selected at random:\n%s\n'
<add> ),
<add> name,
<add> modules.map(m => m.path).join('\n'),
<add> );
<ide> }
<add>
<add> const randomIndex = Math.floor(Math.random() * modules.length);
<add> return modules[randomIndex];
<ide> }
<ide>
<ide> return modules[0];
<ide> class HasteMap {
<ide>
<ide> _updateHasteMap(name, mod) {
<ide> if (this._map[name] == null) {
<del> this._map[name] = [];
<add> this._map[name] = Object.create(null);
<ide> }
<ide>
<del> if (mod.type === 'Module') {
<del> // Modules takes precendence over packages.
<del> this._map[name].unshift(mod);
<del> } else {
<del> this._map[name].push(mod);
<add> const moduleMap = this._map[name];
<add> const modulePlatform = getPlatformExtension(mod.path) || GENERIC_PLATFORM;
<add>
<add> if (!moduleMap[modulePlatform]) {
<add> moduleMap[modulePlatform] = [];
<ide> }
<add>
<add> moduleMap[modulePlatform].push(mod);
<ide> }
<ide> }
<ide>
<ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/__tests__/DependencyGraph-test.js
<ide> describe('DependencyGraph', function() {
<ide> });
<ide> });
<ide>
<del> pit('providesModule wins when conflict with package', function() {
<del> var root = '/root';
<del> fs.__setMockFilesystem({
<del> 'root': {
<del> 'index.js': [
<del> '/**',
<del> ' * @providesModule index',
<del> ' */',
<del> 'require("aPackage")',
<del> ].join('\n'),
<del> 'b.js': [
<del> '/**',
<del> ' * @providesModule aPackage',
<del> ' */',
<del> ].join('\n'),
<del> 'aPackage': {
<del> 'package.json': JSON.stringify({
<del> name: 'aPackage',
<del> main: 'main.js'
<del> }),
<del> 'main.js': 'lol'
<del> }
<del> }
<del> });
<del>
<del> var dgraph = new DependencyGraph({
<del> roots: [root],
<del> fileWatcher: fileWatcher,
<del> assetExts: ['png', 'jpg'],
<del> cache: cache,
<del> });
<del> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
<del> expect(deps)
<del> .toEqual([
<del> {
<del> id: 'index',
<del> path: '/root/index.js',
<del> dependencies: ['aPackage'],
<del> isAsset: false,
<del> isAsset_DEPRECATED: false,
<del> isJSON: false,
<del> isPolyfill: false,
<del> resolution: undefined,
<del> resolveDependency: undefined,
<del> },
<del> {
<del> id: 'aPackage',
<del> path: '/root/b.js',
<del> dependencies: [],
<del> isAsset: false,
<del> isAsset_DEPRECATED: false,
<del> isJSON: false,
<del> isPolyfill: false,
<del> resolution: undefined,
<del> resolveDependency: undefined,
<del> },
<del> ]);
<del> });
<del> });
<del>
<ide> pit('should be forgiving with missing requires', function() {
<ide> var root = '/root';
<ide> fs.__setMockFilesystem({
<ide> describe('DependencyGraph', function() {
<ide> * @providesModule a
<ide> */
<ide> `,
<add> 'a.web.js': `
<add> /**
<add> * @providesModule a
<add> */
<add> `,
<ide> }
<ide> });
<ide>
<ide> describe('DependencyGraph', function() {
<ide> });
<ide> });
<ide>
<add> describe('warnings', () => {
<add> let warn = console.warn;
<add>
<add> beforeEach(() => {
<add> console.warn = jest.genMockFn();
<add> });
<add>
<add> afterEach(() => {
<add> console.warn = warn;
<add> });
<add>
<add> pit('should warn about colliding module names', function() {
<add> fs.__setMockFilesystem({
<add> 'root': {
<add> 'index.js': `
<add> /**
<add> * @providesModule index
<add> */
<add> require('a');
<add> `,
<add> 'a.js': `
<add> /**
<add> * @providesModule a
<add> */
<add> `,
<add> 'b.js': `
<add> /**
<add> * @providesModule a
<add> */
<add> `,
<add> }
<add> });
<add>
<add> var dgraph = new DependencyGraph({
<add> roots: ['/root'],
<add> fileWatcher: fileWatcher,
<add> assetExts: ['png', 'jpg'],
<add> cache: cache,
<add> });
<add>
<add> return getOrderedDependenciesAsJSON(dgraph, '/root/index.js').then(function(deps) {
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> });
<add> });
<add>
<add>
<add> pit('should warn about colliding module names within a platform', function() {
<add> var root = '/root';
<add> fs.__setMockFilesystem({
<add> 'root': {
<add> 'index.ios.js': `
<add> /**
<add> * @providesModule index
<add> */
<add> require('a');
<add> `,
<add> 'a.ios.js': `
<add> /**
<add> * @providesModule a
<add> */
<add> `,
<add> 'b.ios.js': `
<add> /**
<add> * @providesModule a
<add> */
<add> `,
<add> }
<add> });
<add>
<add> var dgraph = new DependencyGraph({
<add> roots: [root],
<add> fileWatcher: fileWatcher,
<add> assetExts: ['png', 'jpg'],
<add> cache: cache,
<add> });
<add>
<add> return getOrderedDependenciesAsJSON(dgraph, '/root/index.ios.js', 'ios').then(function(deps) {
<add> expect(console.warn.mock.calls.length).toBe(1);
<add> });
<add> });
<add> });
<add>
<ide> describe('getAsyncDependencies', () => {
<ide> pit('should get dependencies', function() {
<ide> var root = '/root'; | 2 |
Python | Python | simplify s3 ``unify_bucket_name_and_key`` | 6e101317a22bb58a9edf512bbda662c862e53c78 | <ide><path>airflow/providers/amazon/aws/hooks/s3.py
<ide> def unify_bucket_name_and_key(func: T) -> T:
<ide> def wrapper(*args, **kwargs) -> T:
<ide> bound_args = function_signature.bind(*args, **kwargs)
<ide>
<del> def get_key_name() -> Optional[str]:
<del> if 'wildcard_key' in bound_args.arguments:
<del> return 'wildcard_key'
<del> if 'key' in bound_args.arguments:
<del> return 'key'
<add> if 'wildcard_key' in bound_args.arguments:
<add> key_name = 'wildcard_key'
<add> elif 'key' in bound_args.arguments:
<add> key_name = 'key'
<add> else:
<ide> raise ValueError('Missing key parameter!')
<ide>
<del> key_name = get_key_name()
<del> if key_name and 'bucket_name' not in bound_args.arguments:
<add> if 'bucket_name' not in bound_args.arguments:
<ide> bound_args.arguments['bucket_name'], bound_args.arguments[key_name] = S3Hook.parse_s3_url(
<ide> bound_args.arguments[key_name]
<ide> ) | 1 |
Javascript | Javascript | fix crash of lint rule no-document-import-in-page | 90eae2c00fd086e61aaa2a784deef83b344b6af9 | <ide><path>packages/eslint-plugin-next/lib/rules/no-document-import-in-page.js
<ide> module.exports = {
<ide> }
<ide>
<ide> const page = context.getFilename().split('pages')[1]
<add> if (!page) {
<add> return
<add> }
<ide> const { name, dir } = path.parse(page)
<ide> if (
<del> !page ||
<ide> name.startsWith('_document') ||
<ide> (dir === '/_document' && name === 'index')
<ide> ) {
<ide><path>test/eslint-plugin-next/no-document-import-in-page.unit.test.js
<ide> ruleTester.run('no-document-import-in-page', rule, {
<ide> `,
<ide> filename: 'pages/_document/index.tsx',
<ide> },
<add> {
<add> code: `import Document from "next/document"
<add>
<add> export const Test = () => <p>Test</p>
<add> `,
<add> filename: 'components/test.js',
<add> },
<ide> ],
<ide> invalid: [
<ide> { | 2 |
Java | Java | simplify iteration over maps | aaeabc3c85befe72c6c22df9ac9b83a6c67bdef2 | <ide><path>spring-jms/src/main/java/org/springframework/jms/support/SimpleJmsHeaderMapper.java
<ide> public void fromHeaders(MessageHeaders headers, javax.jms.Message jmsMessage) {
<ide> logger.debug("Failed to set JMSType - skipping", ex);
<ide> }
<ide> }
<del> Set<String> headerNames = headers.keySet();
<del> for (String headerName : headerNames) {
<add> Set<Map.Entry<String, Object>> entries = headers.entrySet();
<add> for (Map.Entry<String, Object> entry : entries) {
<add> String headerName = entry.getKey();
<ide> if (StringUtils.hasText(headerName) && !headerName.startsWith(JmsHeaders.PREFIX)) {
<del> Object value = headers.get(headerName);
<add> Object value = entry.getValue();
<ide> if (value != null && SUPPORTED_PROPERTY_TYPES.contains(value.getClass())) {
<ide> try {
<ide> String propertyName = this.fromHeaderName(headerName);
<ide><path>spring-test/src/main/java/org/springframework/test/context/cache/DefaultContextCache.java
<ide> public void remove(MergedContextConfiguration key, @Nullable HierarchyMode hiera
<ide> }
<ide>
<ide> // Remove empty entries from the hierarchy map.
<del> for (MergedContextConfiguration currentKey : this.hierarchyMap.keySet()) {
<del> if (this.hierarchyMap.get(currentKey).isEmpty()) {
<del> this.hierarchyMap.remove(currentKey);
<add> for (Map.Entry<MergedContextConfiguration, Set<MergedContextConfiguration>> entry : this.hierarchyMap.entrySet()) {
<add> if (entry.getValue().isEmpty()) {
<add> this.hierarchyMap.remove(entry.getKey());
<ide> }
<ide> }
<ide> }
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/SessionAttributesHandler.java
<ide> public Map<String, Object> retrieveAttributes(WebSession session) {
<ide> * @param attributes candidate attributes for session storage
<ide> */
<ide> public void storeAttributes(WebSession session, Map<String, ?> attributes) {
<del> attributes.keySet().forEach(name -> {
<del> Object value = attributes.get(name);
<add> attributes.forEach((name, value) -> {
<ide> if (value != null && isHandlerSessionAttribute(name, value.getClass())) {
<ide> session.getAttributes().put(name, value);
<ide> } | 3 |
Text | Text | remove url from merge sort challenge | 0751fe2e5313bebb159ade9c3bf64c50c34056a4 | <ide><path>curriculum/challenges/russian/08-coding-interview-prep/algorithms/implement-merge-sort.russian.md
<ide> id: 587d825c367417b2b2512c8f
<ide> title: Implement Merge Sort
<ide> challengeType: 1
<del>videoUrl: 'https://www.youtube.com/watch?v=TzeBrDU-JaY'
<add>videoUrl: ''
<ide> localeTitle: Реализация Merge Sort
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Другим промежуточным алгоритмом сортировки, который очень распространен, является сортировка слияния. Подобно быстрой сортировке, сортировка слиянием также использует метод рекурсивного анализа для разделения массива. Сортировка использует тот факт, что легче сортировать два массива меньшего размера, нежели один большего. В качестве входных данных начнем с неотсортированного массива. Как мы можем перейти к двум отсортированным массивам? Мы можем рекурсивно разделить исходный ввод на два, пока не достигнем базового случая массива с одним элементом. Массив из одного элемента естественно сортируется, поэтому мы можем начать комбинировать. Эта комбинация будет раскручивать рекурсивные вызовы, разделяющие исходный массив, в конечном итоге создавая окончательный отсортированный массив всех элементов.
<add><section id="description"> Другим промежуточным алгоритмом сортировки, который очень распространен, является сортировка слияния. Подобно быстрой сортировке, сортировка слиянием также использует метод рекурсивного анализа для разделения массива. Сортировка использует тот факт, что легче сортировать два массива меньшего размера, нежели один большего. <br>В качестве входных данных начнем с неотсортированного массива. Как мы можем перейти к двум отсортированным массивам? Мы можем рекурсивно разделить исходный ввод на два, пока не достигнем базового случая массива с одним элементом. Массив из одного элемента естественно сортируется, поэтому мы можем начать комбинировать. Эта комбинация будет раскручивать рекурсивные вызовы, разделяющие исходный массив, в конечном итоге создавая окончательный отсортированный массив всех элементов.
<ide> Затем выполняются шаги сортировки слияния:
<del> <strong>1)</strong> Рекурсивно разделить входной массив пополам, пока не будет создан массив только с одним элементом. <strong>2)</strong> Объединтить каждый отсортированный подмассив вместе, чтобы получить окончательный отсортированный массив.
<del> Сортировка Merge - это эффективный метод сортировки со алгоритмически-оптимальной сложностью <i>O (nlog (n))</i> . Этот алгоритм популярен, потому что он прост в реализации. Это будет последний эффективный алгоритм сортировки, который мы рассмотрим здесь. Однако позже в разделе о структурах древовидных данных мы опишем сортировку кучи (HeapSort), еще один эффективный метод сортировки, который требует реализацию бинарной кучи.
<add> <br><strong>1)</strong> Рекурсивно разделить входной массив пополам, пока не будет создан массив только с одним элементом. <br><strong>2)</strong> Объединтить каждый отсортированный подмассив вместе, чтобы получить окончательный отсортированный массив.
<add> Сортировка Merge - это эффективный метод сортировки со алгоритмически-оптимальной сложностью <i>O (nlog (n))</i> . Этот алгоритм популярен, потому что он прост в реализации. <br>Это будет последний эффективный алгоритм сортировки, который мы рассмотрим здесь. Однако позже в разделе о структурах древовидных данных мы опишем сортировку кучи (HeapSort), еще один эффективный метод сортировки, который требует реализацию бинарной кучи.
<ide> <strong>Инструкции:</strong> Напишите функцию <code>mergeSort</code> которая принимает массив целых чисел в качестве входных данных и возвращает массив этих целых чисел в отсортированном порядке от наименьшего к наибольшему. Хороший способ реализовать это - написать одну функцию, например <code>merge</code> , которая отвечает за объединение двух отсортированных массивов и другую функцию, например, <code>mergeSort</code> , которая отвечает за слияние. Удачи!
<ide> <strong>Заметка:</strong> <br> Мы вызываем эту функцию из-за кулис; тестовый массив, который мы используем, закомментирован в редакторе. Попробуйте logging <code>array</code> чтобы увидеть ваш алгоритм сортировки в действии! </section>
<ide> | 1 |
Ruby | Ruby | add test to ar's counter_cache_test.rb | 0123c39f41e2062311b2197e6e230ef8ad67e20e | <ide><path>activerecord/test/cases/counter_cache_test.rb
<ide> class ::SpecialReply < ::Reply
<ide> end
<ide> end
<ide>
<add> test 'reset multiple association counters' do
<add> Topic.increment_counter(:replies_count, @topic.id)
<add> assert_difference '@topic.reload.replies_count', -1 do
<add> Topic.reset_counters(@topic.id, :replies, :unique_replies)
<add> end
<add>
<add> Topic.increment_counter(:unique_replies_count, @topic.id)
<add> assert_difference '@topic.reload.unique_replies_count', -1 do
<add> Topic.reset_counters(@topic.id, :replies, :unique_replies)
<add> end
<add> end
<add>
<ide> test "reset counters with string argument" do
<ide> Topic.increment_counter('replies_count', @topic.id)
<ide>
<ide><path>activerecord/test/models/reply.rb
<ide> class Reply < Topic
<ide> end
<ide>
<ide> class UniqueReply < Reply
<add> belongs_to :topic, :foreign_key => 'parent_id', :counter_cache => true
<ide> validates_uniqueness_of :content, :scope => 'parent_id'
<ide> end
<ide>
<ide><path>activerecord/test/schema/schema.rb
<ide> def create_table(*args, &block)
<ide> end
<ide> t.boolean :approved, :default => true
<ide> t.integer :replies_count, :default => 0
<add> t.integer :unique_replies_count, :default => 0
<ide> t.integer :parent_id
<ide> t.string :parent_title
<ide> t.string :type | 3 |
Ruby | Ruby | write a test for `#form_data?` | 7f546318d56b75bafb798d0c178578600fd6939e | <ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def body
<ide> end
<ide> end
<ide>
<add> # Determine whether the request body contains form-data by checking
<add> # the request Content-Type for one of the media-types:
<add> # "application/x-www-form-urlencoded" or "multipart/form-data". The
<add> # list of form-data media types can be modified through the
<add> # +FORM_DATA_MEDIA_TYPES+ array.
<add> #
<add> # A request body is not assumed to contain form-data when no
<add> # Content-Type header is provided and the request_method is POST.
<ide> def form_data?
<del> FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
<add> FORM_DATA_MEDIA_TYPES.include?(media_type)
<ide> end
<ide>
<ide> def body_stream #:nodoc:
<ide><path>actionpack/test/dispatch/request_test.rb
<ide> def setup
<ide> end
<ide> end
<ide> end
<add>
<add>class RequestFormData < BaseRequestTest
<add> test 'media_type is from the FORM_DATA_MEDIA_TYPES array' do
<add> assert stub_request('CONTENT_TYPE' => 'application/x-www-form-urlencoded').form_data?
<add> assert stub_request('CONTENT_TYPE' => 'multipart/form-data').form_data?
<add> end
<add>
<add> test 'media_type is not from the FORM_DATA_MEDIA_TYPES array' do
<add> assert !stub_request('CONTENT_TYPE' => 'application/xml').form_data?
<add> assert !stub_request('CONTENT_TYPE' => 'multipart/related').form_data?
<add> end
<add>
<add> test 'no Content-Type header is provided and the request_method is POST' do
<add> request = stub_request('REQUEST_METHOD' => 'POST')
<add>
<add> assert_equal '', request.media_type
<add> assert_equal 'POST', request.request_method
<add> assert !request.form_data?
<add> end
<add>end | 2 |
Python | Python | remove duplicated methods | 9b0512f148f36d3f53145edd2192ceba78d12109 | <ide><path>test/storage/test_cloudfiles.py
<ide> def test_create_container_already_exists(self):
<ide> self.fail(
<ide> 'Container already exists but an exception was not thrown')
<ide>
<del> def test_create_container_invalid_name(self):
<del> try:
<del> self.driver.create_container(container_name='invalid//name/')
<del> except:
<del> pass
<del> else:
<del> self.fail(
<del> 'Invalid name was provided (name contains slashes)'
<del> ', but exception was not thrown')
<del>
<ide> def test_create_container_invalid_name(self):
<ide> name = ''.join([ 'x' for x in range(0, 257)])
<ide> try:
<ide> def dummy_content_type(name):
<ide> finally:
<ide> libcloud.utils.guess_file_mime_type = old_func
<ide>
<del> def test_delete_object_success(self):
<del> container = Container(name='foo_bar_container', extra={}, driver=self)
<del> obj = Object(name='foo_bar_object', size=1000, hash=None, extra={},
<del> container=container, meta_data=None,
<del> driver=CloudFilesStorageDriver)
<del> result = self.driver.delete_object(obj=obj)
<del> self.assertTrue(result)
<del>
<ide> def test_delete_object_success(self):
<ide> CloudFilesMockHttp.type = 'NOT_FOUND'
<ide> container = Container(name='foo_bar_container', extra={}, driver=self) | 1 |
Java | Java | fix checkstyle violation | 5e561623944665f282f5549e3c21b5c1261d7359 | <ide><path>spring-tx/src/main/java/org/springframework/transaction/support/TransactionSynchronizationUtils.java
<ide> public static boolean sameResourceFactory(ResourceTransactionManager tm, Object
<ide> /**
<ide> * Unwrap the given resource handle if necessary; otherwise return
<ide> * the given handle as-is.
<del> * @see org.springframework.core.InfrastructureProxy#getWrappedObject()
<ide> * @since 5.3.4
<add> * @see org.springframework.core.InfrastructureProxy#getWrappedObject()
<ide> */
<ide> public static Object unwrapResourceIfNecessary(Object resource) {
<ide> Assert.notNull(resource, "Resource must not be null"); | 1 |
PHP | PHP | add return typehint | a5ee2b8d59baac9f548dfe480e0fc4f74226b939 | <ide><path>src/ORM/AssociationCollection.php
<ide> public function cascadeDelete(EntityInterface $entity, array $options): void
<ide> * @param array $options The options used in the delete operation.
<ide> * @return \Cake\ORM\Association[]
<ide> */
<del> protected function _getNoCascadeItems(EntityInterface $entity, array $options)
<add> protected function _getNoCascadeItems(EntityInterface $entity, array $options): array
<ide> {
<ide> $noCascade = [];
<ide> foreach ($this->_items as $assoc) { | 1 |
Javascript | Javascript | add gl_position as a keyword | e2b702c13ccd1acb1539123f369913d45164df7d | <ide><path>editor/js/libs/codemirror/mode/glsl.js
<ide> "do for while if else in out inout float int void bool true false " +
<ide> "lowp mediump highp precision invariant discard return mat2 mat3 " +
<ide> "mat4 vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 sampler2D " +
<del> "samplerCube struct gl_FragCoord gl_FragColor";
<add> "samplerCube struct gl_FragCoord gl_FragColor gl_Position";
<ide> var glslBuiltins = "radians degrees sin cos tan asin acos atan pow " +
<ide> "exp log exp2 log2 sqrt inversesqrt abs sign floor ceil fract mod " +
<ide> "min max clamp mix step smoothstep length distance dot cross " + | 1 |
PHP | PHP | fix problems with rate limiter | be225adf0c54f87f14a686141d1bf8126cfad9d1 | <ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php
<ide> trait ThrottlesLogins
<ide> protected function hasTooManyLoginAttempts(Request $request)
<ide> {
<ide> return app(RateLimiter::class)->tooManyAttempts(
<del> $request->input($this->loginUsername()).$request->ip(),
<add> $this->getThrottleKey($request),
<ide> $this->maxLoginAttempts(), $this->lockoutTime() / 60
<ide> );
<ide> }
<ide> protected function hasTooManyLoginAttempts(Request $request)
<ide> protected function incrementLoginAttempts(Request $request)
<ide> {
<ide> app(RateLimiter::class)->hit(
<del> $request->input($this->loginUsername()).$request->ip()
<add> $this->getThrottleKey($request)
<ide> );
<ide> }
<ide>
<ide> protected function incrementLoginAttempts(Request $request)
<ide> protected function retriesLeft(Request $request)
<ide> {
<ide> $attempts = app(RateLimiter::class)->attempts(
<del> $request->input($this->loginUsername()).$request->ip()
<add> $this->getThrottleKey($request)
<ide> );
<ide>
<ide> return $this->maxLoginAttempts() - $attempts + 1;
<ide> protected function retriesLeft(Request $request)
<ide> protected function sendLockoutResponse(Request $request)
<ide> {
<ide> $seconds = app(RateLimiter::class)->availableIn(
<del> $request->input($this->loginUsername()).$request->ip()
<add> $this->getThrottleKey($request)
<ide> );
<ide>
<del> return redirect($this->loginPath())
<add> return redirect()->back()
<ide> ->withInput($request->only($this->loginUsername(), 'remember'))
<ide> ->withErrors([
<ide> $this->loginUsername() => $this->getLockoutErrorMessage($seconds),
<ide> protected function getLockoutErrorMessage($seconds)
<ide> protected function clearLoginAttempts(Request $request)
<ide> {
<ide> app(RateLimiter::class)->clear(
<del> $request->input($this->loginUsername()).$request->ip()
<add> $this->getThrottleKey($request)
<ide> );
<ide> }
<ide>
<add> /**
<add> * Get the throttle key for the given request.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @return string
<add> */
<add> protected function getThrottleKey(Request $request)
<add> {
<add> return mb_strtolower($request->input($this->loginUsername())).'|'.$request->ip();
<add> }
<add>
<ide> /**
<ide> * Get the maximum number of login attempts for delaying further attempts.
<ide> * | 1 |
PHP | PHP | update the signature of allowemptystring() | d1a0cfe0fc0677d78f69cfec589acca296384720 | <ide><path>src/Validation/Validator.php
<ide> public function allowEmpty($field, $when = true, $message = null)
<ide> }
<ide>
<ide> /**
<del> * Indicate that a field can be empty.
<add> * Low-level method to indicate that a field can be empty.
<ide> *
<del> * Using an array will let you provide the following keys:
<add> * This method should generally not be used and instead you should
<add> * use:
<ide> *
<del> * - `flags` individual flags for field
<del> * - `when` individual when condition for field
<del> * - `message` individual message for field
<add> * - `allowEmptyString()`
<add> * - `allowEmptyArray()`
<add> * - `allowEmptyFile()`
<add> * - `allowEmptyDate()`
<add> * - `allowEmptyDatetime()`
<add> * - `allowEmptyTime()`
<add> *
<add> * Should be used as their APIs are simpler to operate and read.
<ide> *
<ide> * You can also set flags, when and message for all passed fields, the individual
<ide> * setting takes precedence over group settings.
<ide> public function allowEmptyFor($field, $flags, $when = true, $message = null)
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Compatibility shim for the allowEmpty* methods that enable
<add> * us to support both the `$when, $message` signature (deprecated)
<add> * and the `$message, $when` format which is preferred.
<add> *
<add> * A deprecation warning will be emitted when a deprecated form
<add> * is used.
<add> *
<add> * @param mixed $first The message or when to be sorted.
<add> * @param mixed $second The message or when to be sorted.
<add> * @param string $method The called method
<add> * @return array A list of [$message, $when]
<add> */
<add> protected function sortMessageAndWhen($first, $second, $method)
<add> {
<add> // Called with `$message, $when`. No order change necessary
<add> if (
<add> (
<add> in_array($second, [true, false, 'create', 'update'], true) ||
<add> is_callable($second)
<add> ) && (
<add> is_string($first) || $first === null
<add> )
<add> ) {
<add> return [$first, $second];
<add> }
<add> deprecationWarning(
<add> "You are using a deprecated argument order for ${method}. " .
<add> "You should reverse the order of your `when` and `message` arguments " .
<add> "so that they are `message, when`."
<add> );
<add>
<add> // Called with `$when, $message`. Reverse the
<add> // order to match the expected return value.
<add> return [$second, $first];
<add> }
<add>
<ide> /**
<ide> * Allows a field to be an empty string.
<ide> *
<ide> * This method is equivalent to calling allowEmptyFor() with EMPTY_STRING flag.
<ide> *
<ide> * @param string $field The name of the field.
<add> * @param string|null $message The message to show if the field is not
<ide> * @param bool|string|callable $when Indicates when the field is allowed to be empty
<ide> * Valid values are true, false, 'create', 'update'. If a callable is passed then
<ide> * the field will allowed to be empty only when the callback returns true.
<del> * @param string|null $message The message to show if the field is not
<ide> * @return $this
<ide> * @since 3.7.0
<ide> * @see \Cake\Validation\Validator::allowEmptyFor() For detail usage
<ide> */
<del> public function allowEmptyString($field, $when = true, $message = null)
<add> public function allowEmptyString($field, $message = null, $when = true)
<ide> {
<add> list($message, $when) = $this->sortMessageAndWhen($message, $when, __METHOD__);
<ide> return $this->allowEmptyFor($field, self::EMPTY_STRING, $when, $message);
<ide> }
<ide>
<ide><path>tests/TestCase/Validation/ValidatorTest.php
<ide> public function testAllowEmptyString()
<ide> $this->assertNotEmpty($validator->errors($data));
<ide>
<ide> $validator = new Validator();
<del> $validator->allowEmptyString('title', 'update', 'message');
<add> $validator->allowEmptyString('title', 'message', 'update');
<add> $this->assertFalse($validator->isEmptyAllowed('title', true));
<add> $this->assertTrue($validator->isEmptyAllowed('title', false));
<add>
<add> $data = [
<add> 'title' => null,
<add> ];
<add> $expected = [
<add> 'title' => ['_empty' => 'message'],
<add> ];
<add> $this->assertSame($expected, $validator->errors($data, true));
<add> $this->assertEmpty($validator->errors($data, false));
<add> }
<add>
<add> /**
<add> * Ensure that allowEmptyString() works with deprecated arguments
<add> *
<add> * @return void
<add> */
<add> public function testAllowEmptyStringDeprecatedArguments()
<add> {
<add> $validator = new Validator();
<add> $this->deprecated(function () use ($validator) {
<add> $validator->allowEmptyString('title', 'update', 'message');
<add> });
<ide> $this->assertFalse($validator->isEmptyAllowed('title', true));
<ide> $this->assertTrue($validator->isEmptyAllowed('title', false));
<ide> | 2 |
Javascript | Javascript | add missing semicolons in nodematerial | 5918295ba320ba435e37a46f3caa92da73fa8712 | <ide><path>examples/js/nodes/NodeMaterial.js
<ide> THREE.NodeMaterial.addShortcuts = function( proto, prop, list ) {
<ide> }
<ide> };
<ide>
<del> };
<add> }
<ide>
<ide> return ( function() {
<ide>
<ide> THREE.NodeMaterial.prototype.getVar = function( uuid, type, ns ) {
<ide> var index = this.vars.length,
<ide> name = ns ? ns : 'nVv' + index;
<ide>
<del> data = { name : name, type : type }
<add> data = { name : name, type : type };
<ide>
<ide> this.vars.push( data );
<ide> this.vars[ uuid ] = data; | 1 |
PHP | PHP | add link to explain mentioned problem | 4d3ee09a455c97c18fe2328854013e1726e585f0 | <ide><path>src/Database/SchemaCache.php
<ide> * can prevent thundering herd effects on the metadata cache when new
<ide> * versions of your application are deployed, or when migrations
<ide> * requiring updated metadata are required.
<add> *
<add> * @link https://en.wikipedia.org/wiki/Thundering_herd_problem About the thundering herd problem
<ide> */
<ide> class SchemaCache
<ide> { | 1 |
Python | Python | add basic unit tests for pattern | 46637369aaffc0ba0e62cec675289b8275d149c5 | <ide><path>spacy/tests/pattern/__init__.py
<add># coding: utf-8
<ide><path>spacy/tests/pattern/parser.py
<add># coding: utf-8
<add>
<add>
<add>import re
<add>from ...pattern.parser import PatternParser
<add>
<add>
<add>class TestPatternParser:
<add> def test_empty_query(self):
<add> assert PatternParser.parse('') is None
<add> assert PatternParser.parse(' ') is None
<add>
<add> def test_define_node(self):
<add> query = "fox [lemma:fox,word:fox]=alias"
<add> pattern = PatternParser.parse(query)
<add>
<add> assert pattern is not None
<add> assert pattern.number_of_nodes() == 1
<add> assert pattern.number_of_edges() == 0
<add>
<add> assert 'fox' in pattern.nodes
<add>
<add> attrs = pattern['fox']
<add> assert attrs.get('lemma') == 'fox'
<add> assert attrs.get('word') == 'fox'
<add> assert attrs.get('_name') == 'fox'
<add> assert attrs.get('_alias') == 'alias'
<add>
<add> for adj_list in pattern.adjacency.values():
<add> assert not adj_list
<add>
<add> def test_define_node_with_regex(self):
<add> query = "fox [lemma:/fo.*/]"
<add> pattern = PatternParser.parse(query)
<add>
<add> attrs = pattern['fox']
<add> assert attrs.get('lemma') == re.compile(r'fo.*', re.U)
<add>
<add> def test_define_edge(self):
<add> query = "[word:quick] >amod [word:fox]"
<add> pattern = PatternParser.parse(query)
<add>
<add> assert pattern is not None
<add> assert pattern.number_of_nodes() == 2
<add> assert pattern.number_of_edges() == 1
<add>
<add> base_node_id = list(pattern.adjacency.keys())[0]
<add> adj_map = pattern.adjacency[base_node_id]
<add>
<add> assert len(adj_map) == 1
<add> head_node_id = list(adj_map.keys())[0]
<add> dep = adj_map[head_node_id]
<add>
<add> assert dep == 'amod'
<add> assert pattern[base_node_id]['word'] == 'fox'
<add> assert pattern[head_node_id]['word'] == 'quick'
<add>
<add> def test_define_edge_with_regex(self):
<add> query = "[word:quick] >/amod|nsubj/ [word:fox]"
<add> pattern = PatternParser.parse(query)
<add>
<add> base_node_id = list(pattern.adjacency.keys())[0]
<add> adj_map = pattern.adjacency[base_node_id]
<add>
<add> assert len(adj_map) == 1
<add> head_node_id = list(adj_map.keys())[0]
<add> dep = adj_map[head_node_id]
<add> assert dep == re.compile(r'amod|nsubj', re.U)
<ide><path>spacy/tests/pattern/pattern.py
<add># coding: utf-8
<add>
<add>from ..util import get_doc
<add>from ...pattern.pattern import Tree, DependencyTree
<add>from ...pattern.parser import PatternParser
<add>
<add>import pytest
<add>
<add>import logging
<add>logger = logging.getLogger()
<add>logger.addHandler(logging.StreamHandler())
<add>logger.setLevel(logging.DEBUG)
<add>
<add>
<add>@pytest.fixture
<add>def doc(en_vocab):
<add> words = ['I', "'m", 'going', 'to', 'the', 'zoo', 'next', 'week', '.']
<add> doc = get_doc(en_vocab,
<add> words=words,
<add> deps=['nsubj', 'aux', 'ROOT', 'prep', 'det', 'pobj',
<add> 'amod', 'npadvmod', 'punct'],
<add> heads=[2, 1, 0, -1, 1, -2, 1, -5, -6])
<add> return doc
<add>
<add>
<add>class TestTree:
<add> def test_is_connected(self):
<add> tree = Tree()
<add> tree.add_node(1)
<add> tree.add_node(2)
<add> tree.add_edge(1, 2)
<add>
<add> assert tree.is_connected()
<add>
<add> tree.add_node(3)
<add> assert not tree.is_connected()
<add>
<add>
<add>class TestDependencyTree:
<add> def test_from_doc(self, doc):
<add> dep_tree = DependencyTree(doc)
<add>
<add> assert len(dep_tree) == len(doc)
<add> assert dep_tree.is_connected()
<add> assert dep_tree.number_of_edges() == len(doc) - 1
<add>
<add> def test_simple_matching(self, doc):
<add> dep_tree = DependencyTree(doc)
<add> pattern = PatternParser.parse("""root [word:going]
<add> to [word:to]
<add> [word:week]=date > root
<add> [word:/zoo|park/]=place >pobj to
<add> to >prep root
<add> """)
<add> assert pattern is not None
<add> matches = dep_tree.match(pattern)
<add> assert len(matches) == 1
<add>
<add> match = matches[0]
<add> assert match['place'] == doc[5]
<add> assert match['date'] == doc[7] | 3 |
Python | Python | fix permission issues | 367dd01a338e67c772362af62889a53a1302fb02 | <ide><path>djangorestframework/permissions.py
<ide> class IsAuthenticated(BasePermission):
<ide> """
<ide>
<ide> def check_permission(self, request, obj=None):
<del> if request.user.is_authenticated():
<add> if request.user and request.user.is_authenticated():
<ide> return True
<ide> return False
<ide>
<ide> class IsAdminUser(BasePermission):
<ide> """
<ide>
<ide> def check_permission(self, request, obj=None):
<del> if request.user.is_staff:
<add> if request.user and request.user.is_staff():
<ide> return True
<ide> return False
<ide>
<ide> class IsAuthenticatedOrReadOnly(BasePermission):
<ide> """
<ide>
<ide> def check_permission(self, request, obj=None):
<del> if (request.user.is_authenticated() or
<del> request.method in SAFE_METHODS):
<add> if (request.method in SAFE_METHODS or
<add> request.user and
<add> request.user.is_authenticated()):
<ide> return True
<ide> return False
<ide>
<ide> def check_permission(self, request, obj=None):
<ide> model_cls = self.view.model
<ide> perms = self.get_required_permissions(request.method, model_cls)
<ide>
<del> if request.user.is_authenticated() and request.user.has_perms(perms, obj):
<add> if (request.user and
<add> request.user.is_authenticated() and
<add> request.user.has_perms(perms, obj)):
<ide> return True
<ide> return False | 1 |
Text | Text | update 5.12.6 and 5.12.3 | 254683b5cd62832d4764fcd06e4650a1b4ba4c87 | <ide><path>CHANGELOG.md
<ide> <a name="5.12.6"></a>
<del>## [5.12.6](https://github.com/videojs/video.js/compare/v5.10.7...v5.12.6) (2016-10-25)
<del>
<del>### Features
<del>
<del>* **lang:** add missing translations in fr.json ([280ecd4](https://github.com/videojs/video.js/commit/280ecd4))
<del>* **lang:** add missing translations to el.json ([eb0efd4](https://github.com/videojs/video.js/commit/eb0efd4))
<add>## [5.12.6](https://github.com/videojs/video.js/compare/v5.12.5...v5.12.6) (2016-10-25)
<ide>
<ide> ### Bug Fixes
<ide>
<del>* **controls:** fix load progress bar never highlighting first buffered time range ([ca02298](https://github.com/videojs/video.js/commit/ca02298))
<del>* **css:** remove commented out css ([5fdcd46](https://github.com/videojs/video.js/commit/5fdcd46)), closes [#3587](https://github.com/videojs/video.js/issues/3587)
<del>* disable HLS hack on Firefox for Android ([#3586](https://github.com/videojs/video.js/issues/3586)) ([dd2aff0](https://github.com/videojs/video.js/commit/dd2aff0))
<del>* **html5:** disable manual timeupdate events on html5 tech ([#3656](https://github.com/videojs/video.js/issues/3656)) ([920c54a](https://github.com/videojs/video.js/commit/920c54a))
<del>* logging failing on browsers that don't always have console ([#3686](https://github.com/videojs/video.js/issues/3686)) ([e932061](https://github.com/videojs/video.js/commit/e932061))
<ide> * make sure that document.createElement exists before using ([#3706](https://github.com/videojs/video.js/issues/3706)) ([49e29ba](https://github.com/videojs/video.js/commit/49e29ba)), closes [#3665](https://github.com/videojs/video.js/issues/3665)
<del>* move html5 source handler incantation to bottom ([#3695](https://github.com/videojs/video.js/issues/3695)) ([7b9574b](https://github.com/videojs/video.js/commit/7b9574b))
<del>* proxy ios webkit events into fullscreenchange ([#3644](https://github.com/videojs/video.js/issues/3644)) ([e479f8c](https://github.com/videojs/video.js/commit/e479f8c))
<ide> * remove unnecessary comments from video.min.js ([#3709](https://github.com/videojs/video.js/issues/3709)) ([fe760a4](https://github.com/videojs/video.js/commit/fe760a4)), closes [#3707](https://github.com/videojs/video.js/issues/3707)
<del>* Restore timeupdate/loadedmetadata listeners for duration display ([#3682](https://github.com/videojs/video.js/issues/3682)) ([44ec0e4](https://github.com/videojs/video.js/commit/44ec0e4))
<del>
<del>### Chores
<del>
<del>* move metadata to hidden folder and update references ([86f0830](https://github.com/videojs/video.js/commit/86f0830))
<del>* **deps:** add the bundle-collapser browserify plugin ([816291e](https://github.com/videojs/video.js/commit/816291e))
<del>* refactor redundant code in html5 tech ([#3593](https://github.com/videojs/video.js/issues/3593)) ([6878c21](https://github.com/videojs/video.js/commit/6878c21))
<del>* refactor redundant or verbose code in player.js ([#3597](https://github.com/videojs/video.js/issues/3597)) ([ae3e277](https://github.com/videojs/video.js/commit/ae3e277))
<del>* update CHANGELOG automation to use conventional-changelog ([#3669](https://github.com/videojs/video.js/issues/3669)) ([d4e89d2](https://github.com/videojs/video.js/commit/d4e89d2))
<del>* update object.assign to ^4.0.4 ([08c7f4e](https://github.com/videojs/video.js/commit/08c7f4e))
<del>* **grunt:** fix getting changelog by switching to npm-run ([#3687](https://github.com/videojs/video.js/issues/3687)) ([8845bd3](https://github.com/videojs/video.js/commit/8845bd3)), closes [#3683](https://github.com/videojs/video.js/issues/3683)
<del>* **package:** remove es2015-loose since it's an option for es2015 ([#3629](https://github.com/videojs/video.js/issues/3629)) ([c545acd](https://github.com/videojs/video.js/commit/c545acd))
<del>* **package:** update grunt-contrib-cssmin to version 1.0.2 ([#3595](https://github.com/videojs/video.js/issues/3595)) ([54e3db5](https://github.com/videojs/video.js/commit/54e3db5))
<del>* **package:** update grunt-shell to version 2.0.0 ([#3642](https://github.com/videojs/video.js/issues/3642)) ([2032b17](https://github.com/videojs/video.js/commit/2032b17))
<del>
<del>### Documentation
<del>
<del>* fix broken links in docs index.md ([4063f96](https://github.com/videojs/video.js/commit/4063f96))
<del>* **options.md:** Remove Bad Apostrophe ([#3677](https://github.com/videojs/video.js/issues/3677)) ([16c8559](https://github.com/videojs/video.js/commit/16c8559))
<del>* **tech.md:** Add a note on Flash permissions in sandboxed environments ([#3684](https://github.com/videojs/video.js/issues/3684)) ([66922a8](https://github.com/videojs/video.js/commit/66922a8))
<del>
<del>### Tests
<del>
<del>* **a11y:** add basic accessibility testing using grunt-accessibility ([7d85f27](https://github.com/videojs/video.js/commit/7d85f27))
<ide>
<ide> <a name="5.12.5"></a>
<ide> ## [5.12.5](https://github.com/videojs/video.js/compare/v5.12.4...v5.12.5) (2016-10-19)
<ide> * **tech.md:** Add a note on Flash permissions in sandboxed environments ([#3684](https://github.com/videojs/video.js/issues/3684)) ([66922a8](https://github.com/videojs/video.js/commit/66922a8))
<ide>
<ide> <a name="5.12.3"></a>
<del>## [5.12.3](https://github.com/videojs/video.js/compare/v5.10.7...v5.12.3) (2016-10-06)
<add>## [5.12.3](https://github.com/videojs/video.js/compare/v5.12.2...v5.12.3) (2016-10-06)
<ide>
<ide> ### Features
<ide> | 1 |
Text | Text | fix set_autoload_paths and set_load_path document | 02d57b6270e82ea55574df44db64936f3904c740 | <ide><path>guides/source/configuring.md
<ide> Below is a comprehensive list of all the initializers found in Rails in the orde
<ide>
<ide> * `action_mailer.compile_config_methods` Initializes methods for the config settings specified so that they are quicker to access.
<ide>
<del>* `set_load_path` This initializer runs before `bootstrap_hook`. Adds the `vendor`, `lib`, all directories of `app` and any paths specified by `config.load_paths` to `$LOAD_PATH`.
<add>* `set_load_path` This initializer runs before `bootstrap_hook`. Adds paths specified by `config.load_paths` and all autoload paths to `$LOAD_PATH`.
<ide>
<del>* `set_autoload_paths` This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths` to `ActiveSupport::Dependencies.autoload_paths`.
<add>* `set_autoload_paths` This initializer runs before `bootstrap_hook`. Adds all sub-directories of `app` and paths specified by `config.autoload_paths`, `config.eager_load_paths` and `config.autoload_once_paths` to `ActiveSupport::Dependencies.autoload_paths`.
<ide>
<ide> * `add_routing_paths` Loads (by default) all `config/routes.rb` files (in the application and railties, including engines) and sets up the routes for the application.
<ide> | 1 |
Java | Java | add missing marble diagams to single | e6406b362994bcb4b5c2a00a6c10c6dbde4de3c4 | <ide><path>src/main/java/io/reactivex/rxjava3/core/Single.java
<ide> public static <T> Flowable<T> concatArray(SingleSource<? extends T>... sources)
<ide> /**
<ide> * Concatenates a sequence of SingleSource eagerly into a single stream of values.
<ide> * <p>
<add> * <img width="640" height="257" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.concatArrayEager.png" alt="">
<add> * <p>
<ide> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the
<ide> * source SingleSources. The operator buffers the value emitted by these SingleSources and then drains them
<ide> * in order, each one after the previous one completes.
<ide> public static <T> Flowable<T> merge(
<ide> /**
<ide> * Merges an Iterable sequence of SingleSource instances into a single Flowable sequence,
<ide> * running all SingleSources at once and delaying any error(s) until all sources succeed or fail.
<add> * <p>
<add> * <img width="640" height="469" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.i.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
<ide> public static <T> Flowable<T> mergeDelayError(Iterable<? extends SingleSource<?
<ide> /**
<ide> * Merges a Flowable sequence of SingleSource instances into a single Flowable sequence,
<ide> * running all SingleSources at once and delaying any error(s) until all sources succeed or fail.
<add> * <p>
<add> * <img width="640" height="356" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.p.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The returned {@code Flowable} honors the backpressure of the downstream consumer.</dd>
<ide> public static <T> Flowable<T> mergeDelayError(Publisher<? extends SingleSource<?
<ide> * Flattens two Singles into a single Flowable, without any transformation, delaying
<ide> * any error(s) until all sources succeed or fail.
<ide> * <p>
<del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt="">
<add> * <img width="640" height="554" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.2.png" alt="">
<ide> * <p>
<ide> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by
<ide> * using the {@code mergeDelayError} method.
<ide> public static <T> Flowable<T> mergeDelayError(
<ide> * Flattens three Singles into a single Flowable, without any transformation, delaying
<ide> * any error(s) until all sources succeed or fail.
<ide> * <p>
<del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt="">
<add> * <img width="640" height="496" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.3.png" alt="">
<ide> * <p>
<ide> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using
<ide> * the {@code mergeDelayError} method.
<ide> public static <T> Flowable<T> mergeDelayError(
<ide> * Flattens four Singles into a single Flowable, without any transformation, delaying
<ide> * any error(s) until all sources succeed or fail.
<ide> * <p>
<del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.merge.png" alt="">
<add> * <img width="640" height="509" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.mergeDelayError.4.png" alt="">
<ide> * <p>
<ide> * You can combine items emitted by multiple Singles so that they appear as a single Flowable, by using
<ide> * the {@code mergeDelayError} method.
<ide> public static <T> Single<Boolean> equals(final SingleSource<? extends T> first,
<ide> /**
<ide> * <strong>Advanced use only:</strong> creates a Single instance without
<ide> * any safeguards by using a callback that is called with a SingleObserver.
<add> * <p>
<add> * <img width="640" height="261" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.unsafeCreate.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code unsafeCreate} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public static <T> Single<T> unsafeCreate(SingleSource<T> onSubscribe) {
<ide> /**
<ide> * Allows using and disposing a resource while running a SingleSource instance generated from
<ide> * that resource (similar to a try-with-resources).
<add> * <p>
<add> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.using.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public static <T, U> Single<T> using(Supplier<U> resourceSupplier,
<ide> /**
<ide> * Allows using and disposing a resource while running a SingleSource instance generated from
<ide> * that resource (similar to a try-with-resources).
<add> * <p>
<add> * <img width="640" height="325" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.using.b.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public static <T, U> Single<T> using(
<ide> /**
<ide> * Wraps a SingleSource instance into a new Single instance if not already a Single
<ide> * instance.
<add> * <p>
<add> * <img width="640" height="350" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.wrap.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <R> Single<R> compose(SingleTransformer<? super T, ? extends R> tra
<ide> /**
<ide> * Stores the success value or exception from the current Single and replays it to late SingleObservers.
<ide> * <p>
<add> * <img width="640" height="363" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.cache.png" alt="">
<add> * <p>
<ide> * The returned Single subscribes to the current Single when the first SingleObserver subscribes.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> public final Single<T> cache() {
<ide> /**
<ide> * Casts the success value of the current Single into the target type or signals a
<ide> * ClassCastException if not compatible.
<add> * <p>
<add> * <img width="640" height="393" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.cast.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code cast} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> delay(final long time, final TimeUnit unit, final Schedul
<ide> /**
<ide> * Delays the actual subscription to the current Single until the given other CompletableSource
<ide> * completes.
<add> * <p>
<add> * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.c.png" alt="">
<ide> * <p>If the delaying source signals an error, that error is re-emitted and no subscription
<ide> * to the current Single happens.
<ide> * <dl>
<ide> public final Single<T> delaySubscription(CompletableSource other) {
<ide> /**
<ide> * Delays the actual subscription to the current Single until the given other SingleSource
<ide> * signals success.
<add> * <p>
<add> * <img width="640" height="309" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.s.png" alt="">
<ide> * <p>If the delaying source signals an error, that error is re-emitted and no subscription
<ide> * to the current Single happens.
<ide> * <dl>
<ide> public final <U> Single<T> delaySubscription(SingleSource<U> other) {
<ide> /**
<ide> * Delays the actual subscription to the current Single until the given other ObservableSource
<ide> * signals its first value or completes.
<add> * <p>
<add> * <img width="640" height="214" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.o.png" alt="">
<ide> * <p>If the delaying source signals an error, that error is re-emitted and no subscription
<ide> * to the current Single happens.
<ide> * <dl>
<ide> public final <U> Single<T> delaySubscription(ObservableSource<U> other) {
<ide> /**
<ide> * Delays the actual subscription to the current Single until the given other Publisher
<ide> * signals its first value or completes.
<add> * <p>
<add> * <img width="640" height="214" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.p.png" alt="">
<ide> * <p>If the delaying source signals an error, that error is re-emitted and no subscription
<ide> * to the current Single happens.
<ide> * <p>The other source is consumed in an unbounded manner (requesting Long.MAX_VALUE from it).
<ide> public final <U> Single<T> delaySubscription(Publisher<U> other) {
<ide>
<ide> /**
<ide> * Delays the actual subscription to the current Single until the given time delay elapsed.
<add> * <p>
<add> * <img width="640" height="472" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.t.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code delaySubscription} does by default subscribe to the current Single
<ide> public final Single<T> delaySubscription(long time, TimeUnit unit) {
<ide>
<ide> /**
<ide> * Delays the actual subscription to the current Single until the given time delay elapsed.
<add> * <p>
<add> * <img width="640" height="420" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.delaySubscription.ts.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code delaySubscription} does by default subscribe to the current Single
<ide> public final Single<T> delaySubscription(long time, TimeUnit unit, Scheduler sch
<ide> * {@code onSuccess}, {@code onError} or {@code onComplete} signals as a
<ide> * {@link Maybe} source.
<ide> * <p>
<add> * <img width="640" height="341" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.dematerialize.png" alt="">
<add> * <p>
<ide> * The intended use of the {@code selector} function is to perform a
<ide> * type-safe identity mapping (see example) on a source that is already of type
<ide> * {@code Notification<T>}. The Java language doesn't allow
<ide> public final Single<T> doOnSuccess(final Consumer<? super T> onSuccess) {
<ide> /**
<ide> * Calls the shared consumer with the error sent via onError or the value
<ide> * via onSuccess for each SingleObserver that subscribes to the current Single.
<add> * <p>
<add> * <img width="640" height="264" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.doOnEvent.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code doOnEvent} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Completable flatMapCompletable(final Function<? super T, ? extends
<ide> /**
<ide> * Waits in a blocking fashion until the current Single signals a success value (which is returned) or
<ide> * an exception (which is propagated).
<add> * <p>
<add> * <img width="640" height="429" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.blockingGet.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code blockingGet} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final T blockingGet() {
<ide> * and providing a new {@code SingleObserver}, containing the custom operator's intended business logic, that will be
<ide> * used in the subscription process going further upstream.
<ide> * <p>
<add> * <img width="640" height="304" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.lift.png" alt="">
<add> * <p>
<ide> * Generally, such a new {@code SingleObserver} will wrap the downstream's {@code SingleObserver} and forwards the
<ide> * {@code onSuccess} and {@code onError} events from the upstream directly or according to the
<ide> * emission pattern the custom operator's business logic requires. In addition, such operator can intercept the
<ide> public final Single<Notification<T>> materialize() {
<ide> /**
<ide> * Signals true if the current Single signals a success value that is Object-equals with the value
<ide> * provided.
<add> * <p>
<add> * <img width="640" height="400" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.contains.png" alt="">
<add> * <p>
<add> * <img width="640" height="401" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.contains.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<Boolean> contains(Object value) {
<ide> /**
<ide> * Signals true if the current Single signals a success value that is equal with
<ide> * the value provided by calling a bi-predicate.
<add> * <p>
<add> * <img width="640" height="401" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.contains.f.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code contains} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> onErrorReturnItem(final T value) {
<ide> * Instructs a Single to pass control to another Single rather than invoking
<ide> * {@link SingleObserver#onError(Throwable)} if it encounters an error.
<ide> * <p>
<del> * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorResumeNext.png" alt="">
<add> * <img width="640" height="451" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onErrorResumeWith.png" alt="">
<ide> * <p>
<ide> * By default, when a Single encounters an error that prevents it from emitting the expected item to
<ide> * its {@link SingleObserver}, the Single invokes its SingleObserver's {@code onError} method, and then quits
<ide> public final Single<T> onErrorResumeNext(
<ide> /**
<ide> * Nulls out references to the upstream producer and downstream SingleObserver if
<ide> * the sequence is terminated or downstream calls dispose().
<add> * <p>
<add> * <img width="640" height="346" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.onTerminateDetach.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code onTerminateDetach} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Flowable<T> repeatUntil(BooleanSupplier stop) {
<ide>
<ide> /**
<ide> * Repeatedly re-subscribes to the current Single indefinitely if it fails with an onError.
<add> * <p>
<add> * <img width="640" height="399" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> retry() {
<ide> /**
<ide> * Repeatedly re-subscribe at most the specified times to the current Single
<ide> * if it fails with an onError.
<add> * <p>
<add> * <img width="640" height="329" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.n.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> retry(long times) {
<ide> /**
<ide> * Re-subscribe to the current Single if the given predicate returns true when the Single fails
<ide> * with an onError.
<add> * <p>
<add> * <img width="640" height="230" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.f2.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> retry(BiPredicate<? super Integer, ? super Throwable> pre
<ide> /**
<ide> * Repeatedly re-subscribe at most times or until the predicate returns false, whichever happens first
<ide> * if it fails with an onError.
<add> * <p>
<add> * <img width="640" height="259" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.nf.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> retry(long times, Predicate<? super Throwable> predicate)
<ide> /**
<ide> * Re-subscribe to the current Single if the given predicate returns true when the Single fails
<ide> * with an onError.
<add> * <p>
<add> * <img width="640" height="240" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retry.f.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code retry} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> retry(Predicate<? super Throwable> predicate) {
<ide> * Re-subscribes to the current Single if and when the Publisher returned by the handler
<ide> * function signals a value.
<ide> * <p>
<add> * <img width="640" height="405" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.retryWhen.png" alt="">
<add> * <p>
<ide> * If the Publisher signals an {@code onComplete}, the resulting {@code Single} will signal a {@link NoSuchElementException}.
<ide> * <p>
<ide> * Note that the inner {@code Publisher} returned by the handler function should signal
<ide> public final Single<T> retryWhen(Function<? super Flowable<Throwable>, ? extends
<ide> /**
<ide> * Subscribes to a Single but ignore its emission or notification.
<ide> * <p>
<add> * <img width="640" height="340" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.png" alt="">
<add> * <p>
<ide> * If the Single emits an error, it is wrapped into an
<ide> * {@link io.reactivex.rxjava3.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException}
<ide> * and routed to the RxJavaPlugins.onError handler.
<ide> public final Disposable subscribe() {
<ide> /**
<ide> * Subscribes to a Single and provides a composite callback to handle the item it emits
<ide> * or any error notification it issues.
<add> * <p>
<add> * <img width="640" height="340" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.c2.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Disposable subscribe(final BiConsumer<? super T, ? super Throwable>
<ide> /**
<ide> * Subscribes to a Single and provides a callback to handle the item it emits.
<ide> * <p>
<add> * <img width="640" height="341" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.c.png" alt="">
<add> * <p>
<ide> * If the Single emits an error, it is wrapped into an
<ide> * {@link io.reactivex.rxjava3.exceptions.OnErrorNotImplementedException OnErrorNotImplementedException}
<ide> * and routed to the RxJavaPlugins.onError handler.
<ide> public final Disposable subscribe(Consumer<? super T> onSuccess) {
<ide> /**
<ide> * Subscribes to a Single and provides callbacks to handle the item it emits or any error notification it
<ide> * issues.
<add> * <p>
<add> * <img width="640" height="340" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribe.cc.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code subscribe} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final void subscribe(SingleObserver<? super T> observer) {
<ide> /**
<ide> * Subscribes a given SingleObserver (subclass) to this Single and returns the given
<ide> * SingleObserver as is.
<add> * <p>
<add> * <img width="640" height="338" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.subscribeWith.png" alt="">
<ide> * <p>Usage example:
<ide> * <pre><code>
<ide> * Single<Integer> source = Single.just(1);
<ide> public final Single<T> subscribeOn(final Scheduler scheduler) {
<ide> * termination of {@code other}, this will emit a {@link CancellationException} rather than go to
<ide> * {@link SingleObserver#onSuccess(Object)}.
<ide> * <p>
<del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt="">
<add> * <img width="640" height="333" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.takeUntil.c.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final Single<T> takeUntil(final CompletableSource other) {
<ide> * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to
<ide> * {@link SingleObserver#onSuccess(Object)}.
<ide> * <p>
<del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt="">
<add> * <img width="640" height="215" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.takeUntil.p.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The {@code other} publisher is consumed in an unbounded fashion but will be
<ide> public final <E> Single<T> takeUntil(final Publisher<E> other) {
<ide> * emission of an item from {@code other}, this will emit a {@link CancellationException} rather than go to
<ide> * {@link SingleObserver#onSuccess(Object)}.
<ide> * <p>
<del> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/takeUntil.png" alt="">
<add> * <img width="640" height="314" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.takeUntil.s.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code takeUntil} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final <E> Single<T> takeUntil(final SingleSource<? extends E> other) {
<ide> /**
<ide> * Signals a TimeoutException if the current Single doesn't signal a success value within the
<ide> * specified timeout window.
<add> * <p>
<add> * <img width="640" height="364" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code timeout} signals the TimeoutException on the {@code computation} {@link Scheduler}.</dd>
<ide> public final Single<T> timeout(long timeout, TimeUnit unit) {
<ide> /**
<ide> * Signals a TimeoutException if the current Single doesn't signal a success value within the
<ide> * specified timeout window.
<add> * <p>
<add> * <img width="640" height="334" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.s.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code timeout} signals the TimeoutException on the {@link Scheduler} you specify.</dd>
<ide> public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler)
<ide> /**
<ide> * Runs the current Single and if it doesn't signal within the specified timeout window, it is
<ide> * disposed and the other SingleSource subscribed to.
<add> * <p>
<add> * <img width="640" height="283" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.sb.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code timeout} subscribes to the other SingleSource on the {@link Scheduler} you specify.</dd>
<ide> public final Single<T> timeout(long timeout, TimeUnit unit, Scheduler scheduler,
<ide> /**
<ide> * Runs the current Single and if it doesn't signal within the specified timeout window, it is
<ide> * disposed and the other SingleSource subscribed to.
<add> * <p>
<add> * <img width="640" height="282" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.timeout.b.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code timeout} subscribes to the other SingleSource on
<ide> public final Observable<T> toObservable() {
<ide> /**
<ide> * Returns a Single which makes sure when a SingleObserver disposes the Disposable,
<ide> * that call is propagated up on the specified scheduler.
<add> * <p>
<add> * <img width="640" height="693" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.unsubscribeOn.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code unsubscribeOn} calls dispose() of the upstream on the {@link Scheduler} you specify.</dd>
<ide> public final <U, R> Single<R> zipWith(SingleSource<U> other, BiFunction<? super
<ide> /**
<ide> * Creates a TestObserver and subscribes
<ide> * it to this Single.
<add> * <p>
<add> * <img width="640" height="442" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.test.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public final TestObserver<T> test() {
<ide>
<ide> /**
<ide> * Creates a TestObserver optionally in cancelled state, then subscribes it to this Single.
<add> * <p>
<add> * <img width="640" height="482" src="https://raw.githubusercontent.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.test.b.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code test} does not operate by default on a particular {@link Scheduler}.</dd> | 1 |
Ruby | Ruby | add test for `csp_meta_tag` | 3f186e30452b700483c42c8d07f095c7b5c031b8 | <ide><path>actionview/test/template/csp_helper_test.rb
<add># frozen_string_literal: true
<add>
<add>require "abstract_unit"
<add>
<add>class CspHelperWithCspEnabledTest < ActionView::TestCase
<add> tests ActionView::Helpers::CspHelper
<add>
<add> def content_security_policy_nonce
<add> "iyhD0Yc0W+c="
<add> end
<add>
<add> def content_security_policy?
<add> true
<add> end
<add>
<add> def test_csp_meta_tag
<add> assert_equal "<meta name=\"csp-nonce\" content=\"iyhD0Yc0W+c=\" />", csp_meta_tag
<add> end
<add>end
<add>
<add>class CspHelperWithCspDisabledTest < ActionView::TestCase
<add> tests ActionView::Helpers::CspHelper
<add>
<add> def content_security_policy?
<add> false
<add> end
<add>
<add> def test_csp_meta_tag
<add> assert_nil csp_meta_tag
<add> end
<add>end | 1 |
Javascript | Javascript | make animation oncomplete callbacks async | e31104fa6c9e5efd93ac69cd70c70cffaf200843 | <ide><path>src/ngAnimate/animate.js
<ide> angular.module('ngAnimate', ['ng'])
<ide> var NG_ANIMATE_STATE = '$$ngAnimateState';
<ide> var rootAnimateState = {running:true};
<ide>
<del> $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement',
<del> function($delegate, $injector, $sniffer, $rootElement) {
<add> $provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$timeout',
<add> function($delegate, $injector, $sniffer, $rootElement, $timeout) {
<ide>
<ide> var noop = angular.noop;
<ide> var forEach = angular.forEach;
<ide> angular.module('ngAnimate', ['ng'])
<ide> if ((parent.inheritedData(NG_ANIMATE_STATE) || disabledAnimation).running) {
<ide> //avoid calling done() since there is no need to remove any
<ide> //data or className values since this happens earlier than that
<del> (onComplete || noop)();
<add> //and also use a timeout so that it won't be asynchronous
<add> $timeout(onComplete || noop, 0, false);
<ide> return;
<ide> }
<ide>
<ide><path>test/ngAnimate/animateSpec.js
<ide> describe("ngAnimate", function() {
<ide>
<ide> describe("enable / disable", function() {
<ide>
<del> beforeEach(function() {
<del> module(function($animateProvider, $provide) {
<del> $provide.value('$window', angular.mock.createMockWindow());
<del> });
<del> });
<del>
<ide> it("should disable and enable the animations", function() {
<ide> var $animate, initialState = null;
<ide>
<ide> describe("ngAnimate", function() {
<ide>
<ide> $animate.removeClass(element, 'ng-hide');
<ide> if($sniffer.transitions) {
<del> $timeout.flushNext(1);
<ide> $timeout.flushNext(0);
<add> $timeout.flushNext(1);
<ide> }
<ide> $timeout.flushNext(0);
<ide> expect(element.text()).toBe('memento');
<ide> describe("ngAnimate", function() {
<ide> }));
<ide>
<ide> it("should skip animations if disabled and run when enabled",
<del> inject(function($animate, $rootScope, $compile, $sniffer) {
<add> inject(function($animate, $rootScope, $compile, $sniffer, $timeout) {
<ide> $animate.enabled(false);
<ide> var style = 'animation: some_animation 2s linear 0s 1 alternate;' +
<ide> vendorPrefix + 'animation: some_animation 2s linear 0s 1 alternate;'
<ide> describe("ngAnimate", function() {
<ide> element.addClass('ng-hide');
<ide> expect(element).toBeHidden();
<ide> $animate.removeClass(element, 'ng-hide');
<add> $timeout.flush();
<ide> expect(element).toBeShown();
<ide> }));
<ide>
<ide> describe("ngAnimate", function() {
<ide> element.addClass('ng-hide');
<ide> expect(element).toBeHidden();
<ide> $animate.removeClass(element, 'ng-hide');
<del> expect(element).toBeShown();
<del>
<ide> $timeout.flushNext(0);
<add> $timeout.flushNext(0);
<add> expect(element).toBeShown();
<ide>
<ide> $animate.enabled(true);
<ide>
<ide> describe("ngAnimate", function() {
<ide> $timeout.flushNext(1);
<ide> $timeout.flushNext(2000);
<ide> }
<add> $timeout.flush();
<ide> expect(element).toBeShown();
<ide> }));
<ide>
<ide> describe("ngAnimate", function() {
<ide>
<ide> element.addClass('ng-hide');
<ide> $animate.removeClass(element, 'ng-hide');
<add> $timeout.flushNext(0);
<add> $timeout.flushNext(0);
<ide> expect(element).toBeShown();
<ide>
<del> $timeout.flushNext(0); //callback which is called
<del>
<ide> $animate.enabled(true);
<ide>
<ide> element.addClass('ng-hide');
<ide> describe("ngAnimate", function() {
<ide> $timeout.flushNext(1);
<ide> $timeout.flushNext(3000);
<ide> }
<del> $timeout.flushNext(0);
<add> $timeout.flush();
<ide> expect(element).toBeShown();
<ide> }));
<ide>
<ide><path>test/ngRoute/directive/ngViewSpec.js
<ide> describe('ngView', function() {
<ide> beforeEach(module('ngRoute'));
<ide>
<ide> beforeEach(module(function($provide) {
<del> $provide.value('$window', angular.mock.createMockWindow());
<ide> return function($rootScope, $compile, $animate) {
<ide> element = $compile('<div><ng:view onload="load()"></ng:view></div>')($rootScope);
<ide> };
<ide> describe('ngView animations', function() {
<ide>
<ide>
<ide> beforeEach(module(function($provide, $routeProvider) {
<del> $provide.value('$window', angular.mock.createMockWindow());
<ide> $routeProvider.when('/foo', {controller: noop, templateUrl: '/foo.html'});
<ide> $routeProvider.when('/bar', {controller: noop, templateUrl: '/bar.html'});
<ide> return function($templateCache) {
<ide> describe('ngView animations', function() {
<ide>
<ide> var window;
<ide> module(function($routeProvider, $animateProvider, $provide) {
<del> $provide.value('$window', window = angular.mock.createMockWindow());
<ide> $routeProvider.when('/foo', {template: '<div ng-repeat="i in [1,2]">{{i}}</div>'});
<ide> $routeProvider.when('/bar', {template: '<div ng-repeat="i in [3,4]">{{i}}</div>'});
<ide> $animateProvider.register('.my-animation', function() { | 3 |
Ruby | Ruby | add bottle info | 2df6ad1beda5f29f6eaf6807ec4a53f59bb20260 | <ide><path>Library/Homebrew/formula.rb
<ide> def to_hash
<ide> { "option" => opt.flag, "description" => opt.description }
<ide> end
<ide>
<add> hsh["bottle"] = {}
<add> %w[stable devel].each do |spec_sym|
<add> next unless spec = send(spec_sym)
<add> next unless (bottle_spec = spec.bottle_specification).checksums.any?
<add> bottle_info = {
<add> "revision" => bottle_spec.revision,
<add> "cellar" => (cellar = bottle_spec.cellar).is_a?(Symbol) ? \
<add> cellar.inspect : cellar,
<add> "prefix" => bottle_spec.prefix,
<add> "root_url" => bottle_spec.root_url,
<add> }
<add> bottle_info["files"] = {}
<add> bottle_spec.collector.keys.each do |os|
<add> checksum = bottle_spec.collector[os]
<add> bottle_info["files"][os] = {
<add> "url" => "#{bottle_spec.root_url}/#{Bottle::Filename.create(self, os, bottle_spec.revision)}",
<add> checksum.hash_type.to_s => checksum.hexdigest,
<add> }
<add> end
<add> hsh["bottle"][spec_sym] = bottle_info
<add> end
<add>
<ide> if rack.directory?
<ide> rack.subdirs.each do |keg_path|
<ide> keg = Keg.new keg_path | 1 |
PHP | PHP | update react preset to latest version | 29c7deb6562a09a120e63d81d53f3c5fa412b7f7 | <ide><path>src/Illuminate/Foundation/Console/Presets/React.php
<ide> protected static function updatePackageArray(array $packages)
<ide> {
<ide> return [
<ide> 'babel-preset-react' => '^6.23.0',
<del> 'react' => '^15.4.2',
<del> 'react-dom' => '^15.4.2',
<add> 'react' => '^16.2.0',
<add> 'react-dom' => '^16.2.0',
<ide> ] + Arr::except($packages, ['vue']);
<ide> }
<ide> | 1 |
Python | Python | handle json encoding of v1pod in task callback | 92389cf090f336073337517f2460c2914a9f0d4b | <ide><path>airflow/callbacks/callback_requests.py
<ide> def __init__(
<ide> self.is_failure_callback = is_failure_callback
<ide>
<ide> def to_json(self) -> str:
<del> dict_obj = self.__dict__.copy()
<del> dict_obj["simple_task_instance"] = self.simple_task_instance.as_dict()
<del> return json.dumps(dict_obj)
<add> from airflow.serialization.serialized_objects import BaseSerialization
<add>
<add> val = BaseSerialization.serialize(self.__dict__, strict=True)
<add> return json.dumps(val)
<ide>
<ide> @classmethod
<ide> def from_json(cls, json_str: str):
<del> from airflow.models.taskinstance import SimpleTaskInstance
<add> from airflow.serialization.serialized_objects import BaseSerialization
<ide>
<del> kwargs = json.loads(json_str)
<del> simple_ti = SimpleTaskInstance.from_dict(obj_dict=kwargs.pop("simple_task_instance"))
<del> return cls(simple_task_instance=simple_ti, **kwargs)
<add> val = json.loads(json_str)
<add> return cls(**BaseSerialization.deserialize(val))
<ide>
<ide>
<ide> class DagCallbackRequest(CallbackRequest):
<ide><path>airflow/exceptions.py
<ide> def __str__(self) -> str:
<ide>
<ide>
<ide> class SerializationError(AirflowException):
<del> """A problem occurred when trying to serialize a DAG."""
<add> """A problem occurred when trying to serialize something."""
<ide>
<ide>
<ide> class ParamValidationError(AirflowException):
<ide><path>airflow/models/taskinstance.py
<ide> def __eq__(self, other):
<ide> return NotImplemented
<ide>
<ide> def as_dict(self):
<add> warnings.warn(
<add> "This method is deprecated. Use BaseSerialization.serialize.",
<add> RemovedInAirflow3Warning,
<add> stacklevel=2,
<add> )
<ide> new_dict = dict(self.__dict__)
<ide> for key in new_dict:
<ide> if key in ["start_date", "end_date"]:
<ide> def from_ti(cls, ti: TaskInstance) -> SimpleTaskInstance:
<ide>
<ide> @classmethod
<ide> def from_dict(cls, obj_dict: dict) -> SimpleTaskInstance:
<add> warnings.warn(
<add> "This method is deprecated. Use BaseSerialization.deserialize.",
<add> RemovedInAirflow3Warning,
<add> stacklevel=2,
<add> )
<ide> ti_key = TaskInstanceKey(*obj_dict.pop("key"))
<ide> start_date = None
<ide> end_date = None
<ide><path>airflow/serialization/enums.py
<ide> class DagAttributeTypes(str, Enum):
<ide> PARAM = "param"
<ide> XCOM_REF = "xcomref"
<ide> DATASET = "dataset"
<add> SIMPLE_TASK_INSTANCE = "simple_task_instance"
<ide><path>airflow/serialization/serialized_objects.py
<ide> from airflow.models.mappedoperator import MappedOperator
<ide> from airflow.models.operator import Operator
<ide> from airflow.models.param import Param, ParamsDict
<add>from airflow.models.taskinstance import SimpleTaskInstance
<ide> from airflow.models.taskmixin import DAGNode
<ide> from airflow.models.xcom_arg import XComArg, deserialize_xcom_arg, serialize_xcom_arg
<ide> from airflow.providers_manager import ProvidersManager
<ide> def serialize_to_json(
<ide> return serialized_object
<ide>
<ide> @classmethod
<del> def serialize(cls, var: Any) -> Any: # Unfortunately there is no support for recursive types in mypy
<add> def serialize(
<add> cls, var: Any, *, strict: bool = False
<add> ) -> Any: # Unfortunately there is no support for recursive types in mypy
<ide> """Helper function of depth first search for serialization.
<ide>
<ide> The serialization protocol is:
<ide> def serialize(cls, var: Any) -> Any: # Unfortunately there is no support for re
<ide> return var.value
<ide> return var
<ide> elif isinstance(var, dict):
<del> return cls._encode({str(k): cls.serialize(v) for k, v in var.items()}, type_=DAT.DICT)
<add> return cls._encode(
<add> {str(k): cls.serialize(v, strict=strict) for k, v in var.items()}, type_=DAT.DICT
<add> )
<ide> elif isinstance(var, list):
<del> return [cls.serialize(v) for v in var]
<add> return [cls.serialize(v, strict=strict) for v in var]
<ide> elif var.__class__.__name__ == "V1Pod" and _has_kubernetes() and isinstance(var, k8s.V1Pod):
<ide> json_pod = PodGenerator.serialize_pod(var)
<ide> return cls._encode(json_pod, type_=DAT.POD)
<ide> def serialize(cls, var: Any) -> Any: # Unfortunately there is no support for re
<ide> elif isinstance(var, set):
<ide> # FIXME: casts set to list in customized serialization in future.
<ide> try:
<del> return cls._encode(sorted(cls.serialize(v) for v in var), type_=DAT.SET)
<add> return cls._encode(sorted(cls.serialize(v, strict=strict) for v in var), type_=DAT.SET)
<ide> except TypeError:
<del> return cls._encode([cls.serialize(v) for v in var], type_=DAT.SET)
<add> return cls._encode([cls.serialize(v, strict=strict) for v in var], type_=DAT.SET)
<ide> elif isinstance(var, tuple):
<ide> # FIXME: casts tuple to list in customized serialization in future.
<del> return cls._encode([cls.serialize(v) for v in var], type_=DAT.TUPLE)
<add> return cls._encode([cls.serialize(v, strict=strict) for v in var], type_=DAT.TUPLE)
<ide> elif isinstance(var, TaskGroup):
<ide> return TaskGroupSerialization.serialize_task_group(var)
<ide> elif isinstance(var, Param):
<ide> def serialize(cls, var: Any) -> Any: # Unfortunately there is no support for re
<ide> return cls._encode(serialize_xcom_arg(var), type_=DAT.XCOM_REF)
<ide> elif isinstance(var, Dataset):
<ide> return cls._encode(dict(uri=var.uri, extra=var.extra), type_=DAT.DATASET)
<add> elif isinstance(var, SimpleTaskInstance):
<add> return cls._encode(cls.serialize(var.__dict__, strict=strict), type_=DAT.SIMPLE_TASK_INSTANCE)
<ide> else:
<ide> log.debug("Cast type %s to str in serialization.", type(var))
<add> if strict:
<add> raise SerializationError("Encountered unexpected type")
<ide> return str(var)
<ide>
<ide> @classmethod
<ide> def deserialize(cls, encoded_var: Any) -> Any:
<ide> return _XComRef(var) # Delay deserializing XComArg objects until we have the entire DAG.
<ide> elif type_ == DAT.DATASET:
<ide> return Dataset(**var)
<add> elif type_ == DAT.SIMPLE_TASK_INSTANCE:
<add> return SimpleTaskInstance(**cls.deserialize(var))
<ide> else:
<ide> raise TypeError(f"Invalid type {type_!s} in deserialization.")
<ide>
<ide><path>tests/__init__.py
<ide> # KIND, either express or implied. See the License for the
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<add>from __future__ import annotations
<add>
<add>from pathlib import Path
<add>
<add>REPO_ROOT = Path(__file__).parent.parent
<ide><path>tests/callbacks/test_callback_requests.py
<ide> def test_taskcallback_to_json_with_start_date_and_end_date(self, session, create
<ide> json_str = input.to_json()
<ide> result = TaskCallbackRequest.from_json(json_str)
<ide> assert input == result
<add>
<add> def test_simple_ti_roundtrip_exec_config_pod(self):
<add> """A callback request including a TI with an exec config with a V1Pod should safely roundtrip."""
<add> from kubernetes.client import models as k8s
<add>
<add> from airflow.callbacks.callback_requests import TaskCallbackRequest
<add> from airflow.models import TaskInstance
<add> from airflow.models.taskinstance import SimpleTaskInstance
<add> from airflow.operators.bash import BashOperator
<add>
<add> test_pod = k8s.V1Pod(metadata=k8s.V1ObjectMeta(name="hello", namespace="ns"))
<add> op = BashOperator(task_id="hi", executor_config={"pod_override": test_pod}, bash_command="hi")
<add> ti = TaskInstance(task=op)
<add> s = SimpleTaskInstance.from_ti(ti)
<add> data = TaskCallbackRequest("hi", s).to_json()
<add> actual = TaskCallbackRequest.from_json(data).simple_task_instance.executor_config["pod_override"]
<add> assert actual == test_pod
<add>
<add> def test_simple_ti_roundtrip_dates(self):
<add> """A callback request including a TI with an exec config with a V1Pod should safely roundtrip."""
<add> from unittest.mock import MagicMock
<add>
<add> from airflow.callbacks.callback_requests import TaskCallbackRequest
<add> from airflow.models import TaskInstance
<add> from airflow.models.taskinstance import SimpleTaskInstance
<add> from airflow.operators.bash import BashOperator
<add>
<add> op = BashOperator(task_id="hi", bash_command="hi")
<add> ti = TaskInstance(task=op)
<add> ti.set_state("SUCCESS", session=MagicMock())
<add> start_date = ti.start_date
<add> end_date = ti.end_date
<add> s = SimpleTaskInstance.from_ti(ti)
<add> data = TaskCallbackRequest("hi", s).to_json()
<add> assert TaskCallbackRequest.from_json(data).simple_task_instance.start_date == start_date
<add> assert TaskCallbackRequest.from_json(data).simple_task_instance.end_date == end_date
<ide><path>tests/serialization/test_serialized_objects.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 __future__ import annotations
<add>
<add>import pytest
<add>
<add>from airflow.exceptions import SerializationError
<add>from tests import REPO_ROOT
<add>
<add>
<add>def test_recursive_serialize_calls_must_forward_kwargs():
<add> """Any time we recurse cls.serialize, we must forward all kwargs."""
<add> import ast
<add>
<add> valid_recursive_call_count = 0
<add> file = REPO_ROOT / "airflow/serialization/serialized_objects.py"
<add> content = file.read_text()
<add> tree = ast.parse(content)
<add>
<add> class_def = None
<add> for stmt in ast.walk(tree):
<add> if not isinstance(stmt, ast.ClassDef):
<add> continue
<add> if stmt.name == "BaseSerialization":
<add> class_def = stmt
<add>
<add> method_def = None
<add> for elem in ast.walk(class_def):
<add> if isinstance(elem, ast.FunctionDef):
<add> if elem.name == "serialize":
<add> method_def = elem
<add> break
<add> kwonly_args = [x.arg for x in method_def.args.kwonlyargs]
<add>
<add> for elem in ast.walk(method_def):
<add> if isinstance(elem, ast.Call):
<add> if getattr(elem.func, "attr", "") == "serialize":
<add> kwargs = {y.arg: y.value for y in elem.keywords}
<add> for name in kwonly_args:
<add> if name not in kwargs or getattr(kwargs[name], "id", "") != name:
<add> ref = f"{file}:{elem.lineno}"
<add> message = (
<add> f"Error at {ref}; recursive calls to `cls.serialize` "
<add> f"must forward the `{name}` argument"
<add> )
<add> raise Exception(message)
<add> valid_recursive_call_count += 1
<add> print(f"validated calls: {valid_recursive_call_count}")
<add> assert valid_recursive_call_count > 0
<add>
<add>
<add>def test_strict_mode():
<add> """If strict=True, serialization should fail when object is not JSON serializable."""
<add>
<add> class Test:
<add> a = 1
<add>
<add> from airflow.serialization.serialized_objects import BaseSerialization
<add>
<add> obj = [[[Test()]]] # nested to verify recursive behavior
<add> BaseSerialization.serialize(obj) # does not raise
<add> with pytest.raises(SerializationError, match="Encountered unexpected type"):
<add> BaseSerialization.serialize(obj, strict=True) # now raises | 8 |
Javascript | Javascript | fix ui explorer in android | 0b72eba8698c5d1ef014fe735c299321e6030352 | <ide><path>Examples/UIExplorer/NavigationExperimental/NavigationBasicExample.js
<ide> const NavigationBasicExample = React.createClass({
<ide> return (
<ide> <ScrollView style={styles.topView}>
<ide> <NavigationExampleRow
<del> text={`Current page: ${this.state.croutes[this.state.index].key}`}
<add> text={`Current page: ${this.state.routes[this.state.index].key}`}
<ide> />
<ide> <NavigationExampleRow
<ide> text={`Push page #${this.state.routes.length}`}
<ide><path>Examples/UIExplorer/UIExplorerApp.android.js
<ide> class UIExplorerApp extends React.Component {
<ide> />
<ide> );
<ide> }
<del> const title = UIExplorerStateTitleMap(stack.children[stack.index]);
<del> const index = stack.children.length <= 1 ? 1 : stack.index;
<add> const title = UIExplorerStateTitleMap(stack.routes[stack.index]);
<add> const index = stack.routes.length <= 1 ? 1 : stack.index;
<ide>
<del> if (stack && stack.children[index]) {
<del> const {key} = stack.children[index];
<add> if (stack && stack.routes[index]) {
<add> const {key} = stack.routes[index];
<ide> const ExampleModule = UIExplorerList.Modules[key];
<ide> const ExampleComponent = UIExplorerExampleList.makeRenderable(ExampleModule);
<ide> return (
<ide> class UIExplorerApp extends React.Component {
<ide> <UIExplorerExampleList
<ide> onNavigate={this._handleAction}
<ide> list={UIExplorerList}
<del> {...stack.children[0]}
<add> {...stack.routes[0]}
<ide> />
<ide> </View>
<ide> ); | 2 |
Javascript | Javascript | fix typos in test/parallel | 58b60c1393dd65cd228a8b0084a19acd2c1d16aa | <ide><path>test/parallel/test-event-capture-rejections.js
<ide> function globalSetting() {
<ide> }
<ide>
<ide> // We need to be able to configure this for streams, as we would
<del>// like to call destro(err) there.
<add>// like to call destroy(err) there.
<ide> function configurable() {
<ide> const ee = new EventEmitter({ captureRejections: true });
<ide> const _err = new Error('kaboom');
<ide><path>test/parallel/test-stream-writable-samecb-singletick.js
<ide> const async_hooks = require('async_hooks');
<ide> const checkTickCreated = common.mustCall();
<ide>
<ide> async_hooks.createHook({
<del> init(id, type, triggerId, resoure) {
<add> init(id, type, triggerId, resource) {
<ide> if (type === 'TickObject') checkTickCreated();
<ide> }
<ide> }).enable(); | 2 |
Python | Python | add some type hints for hive providers | f760823b4af3f0fdfacf63dae199ec4d88028f71 | <ide><path>airflow/providers/apache/hive/transfers/vertica_to_hive.py
<ide>
<ide> from collections import OrderedDict
<ide> from tempfile import NamedTemporaryFile
<add>from typing import Any, Dict, Optional
<ide>
<ide> import unicodecsv as csv
<ide>
<ide> class VerticaToHiveOperator(BaseOperator):
<ide> :param hive_cli_conn_id: Reference to the
<ide> :ref:`Hive CLI connection id <howto/connection:hive_cli>`.
<ide> :type hive_cli_conn_id: str
<del>
<ide> """
<ide>
<ide> template_fields = ('sql', 'partition', 'hive_table')
<ide> class VerticaToHiveOperator(BaseOperator):
<ide> def __init__(
<ide> self,
<ide> *,
<del> sql,
<del> hive_table,
<del> create=True,
<del> recreate=False,
<del> partition=None,
<del> delimiter=chr(1),
<del> vertica_conn_id='vertica_default',
<del> hive_cli_conn_id='hive_cli_default',
<del> **kwargs,
<del> ):
<add> sql: str,
<add> hive_table: str,
<add> create: bool = True,
<add> recreate: bool = False,
<add> partition: Optional[Dict] = None,
<add> delimiter: str = chr(1),
<add> vertica_conn_id: str = 'vertica_default',
<add> hive_cli_conn_id: str = 'hive_cli_default',
<add> **kwargs: Any,
<add> ) -> None:
<ide> super().__init__(**kwargs)
<ide> self.sql = sql
<ide> self.hive_table = hive_table | 1 |
Java | Java | remove some dead code | 115a095a6009a1d0a59b1a055077b79813b3bd9e | <ide><path>src/main/java/io/reactivex/internal/observers/InnerQueuedObserver.java
<ide>
<ide> volatile boolean done;
<ide>
<del> long produced;
<del>
<ide> int fusionMode;
<ide>
<ide> public InnerQueuedObserver(InnerQueuedObserverSupport<T> parent, int prefetch) {
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableInternalHelper.java
<ide> public static <T, U> Function<T, Publisher<U>> flatMapIntoIterable(final Functio
<ide> return new FlatMapIntoIterable<T, U>(mapper);
<ide> }
<ide>
<del> enum MapToInt implements Function<Object, Object> {
<del> INSTANCE;
<del> @Override
<del> public Object apply(Object t) throws Exception {
<del> return 0;
<del> }
<del> }
<del>
<ide> public static <T> Callable<ConnectableFlowable<T>> replayCallable(final Flowable<T> parent) {
<ide> return new Callable<ConnectableFlowable<T>>() {
<ide> @Override
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableSequenceEqual.java
<ide> public void subscribeActual(Subscriber<? super Boolean> s) {
<ide>
<ide> final BiPredicate<? super T, ? super T> comparer;
<ide>
<del> final int prefetch;
<del>
<ide> final EqualSubscriber<T> first;
<ide>
<ide> final EqualSubscriber<T> second;
<ide> public void subscribeActual(Subscriber<? super Boolean> s) {
<ide>
<ide> EqualCoordinator(Subscriber<? super Boolean> actual, int prefetch, BiPredicate<? super T, ? super T> comparer) {
<ide> super(actual);
<del> this.prefetch = prefetch;
<ide> this.comparer = comparer;
<ide> this.wip = new AtomicInteger();
<ide> this.first = new EqualSubscriber<T>(this, prefetch);
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java
<ide> public final class FlowableToList<T, U extends Collection<? super T>> extends AbstractFlowableWithUpstream<T, U> {
<ide> final Callable<U> collectionSupplier;
<ide>
<del> @SuppressWarnings("unchecked")
<del> public FlowableToList(Publisher<T> source) {
<del> this(source, (Callable<U>)ArrayListSupplier.asCallable());
<del> }
<del>
<ide> public FlowableToList(Publisher<T> source, Callable<U> collectionSupplier) {
<ide> super(source);
<ide> this.collectionSupplier = collectionSupplier;
<ide><path>src/main/java/io/reactivex/internal/schedulers/ScheduledRunnable.java
<ide> public void setFuture(Future<?> f) {
<ide> }
<ide> }
<ide>
<del> /**
<del> * Returns true if this ScheduledRunnable has been scheduled.
<del> * @return true if this ScheduledRunnable has been scheduled.
<del> */
<del> public boolean wasScheduled() {
<del> return get(FUTURE_INDEX) != null;
<del> }
<del>
<ide> @Override
<ide> public void dispose() {
<ide> for (;;) {
<ide><path>src/main/java/io/reactivex/internal/subscribers/SubscriberResourceWrapper.java
<ide>
<ide> final AtomicReference<Subscription> subscription = new AtomicReference<Subscription>();
<ide>
<del> static final Object TERMINATED = new Object();
<del>
<ide> public SubscriberResourceWrapper(Subscriber<? super T> actual) {
<ide> this.actual = actual;
<ide> } | 6 |
Go | Go | remove "quiet" argument | 9b795c3e502906bb042e207db6b7583c9bfa34e5 | <ide><path>cmd/dockerd/daemon.go
<ide> func warnOnDeprecatedConfigOptions(config *config.Config) {
<ide> func initRouter(opts routerOptions) {
<ide> decoder := runconfig.ContainerDecoder{
<ide> GetSysInfo: func() *sysinfo.SysInfo {
<del> return opts.daemon.RawSysInfo(true)
<add> return opts.daemon.RawSysInfo()
<ide> },
<ide> }
<ide>
<ide> routers := []router.Router{
<ide> // we need to add the checkpoint router before the container router or the DELETE gets masked
<ide> checkpointrouter.NewRouter(opts.daemon, decoder),
<del> container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo(true).CgroupUnified),
<add> container.NewRouter(opts.daemon, decoder, opts.daemon.RawSysInfo().CgroupUnified),
<ide> image.NewRouter(opts.daemon.ImageService()),
<ide> systemrouter.NewRouter(opts.daemon, opts.cluster, opts.buildkit, opts.features),
<ide> volume.NewRouter(opts.daemon.VolumesService()),
<ide><path>daemon/daemon.go
<ide> func NewDaemon(ctx context.Context, config *config.Config, pluginStore *plugin.S
<ide> return nil, err
<ide> }
<ide>
<del> sysInfo := d.RawSysInfo(false)
<add> sysInfo := d.RawSysInfo()
<add> for _, w := range sysInfo.Warnings {
<add> logrus.Warn(w)
<add> }
<ide> // Check if Devices cgroup is mounted, it is hard requirement for container security,
<ide> // on Linux.
<ide> if runtime.GOOS == "linux" && !sysInfo.CgroupDevicesEnabled && !userns.RunningInUserNS() {
<ide><path>daemon/daemon_unix.go
<ide> func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.
<ide> if hostConfig == nil {
<ide> return nil, nil
<ide> }
<del> sysInfo := daemon.RawSysInfo(true)
<add> sysInfo := daemon.RawSysInfo()
<ide>
<ide> w, err := verifyPlatformContainerResources(&hostConfig.Resources, sysInfo, update)
<ide>
<ide> func (daemon *Daemon) setupSeccompProfile() error {
<ide> }
<ide>
<ide> // RawSysInfo returns *sysinfo.SysInfo .
<del>func (daemon *Daemon) RawSysInfo(quiet bool) *sysinfo.SysInfo {
<add>func (daemon *Daemon) RawSysInfo() *sysinfo.SysInfo {
<ide> var siOpts []sysinfo.Opt
<ide> if daemon.getCgroupDriver() == cgroupSystemdDriver {
<ide> if euid := os.Getenv("ROOTLESSKIT_PARENT_EUID"); euid != "" {
<ide> siOpts = append(siOpts, sysinfo.WithCgroup2GroupPath("/user.slice/user-"+euid+".slice"))
<ide> }
<ide> }
<del> return sysinfo.New(quiet, siOpts...)
<add> return sysinfo.New(siOpts...)
<ide> }
<ide>
<ide> func recursiveUnmount(target string) error {
<ide><path>daemon/daemon_unsupported.go
<ide> func setupResolvConf(config *config.Config) {
<ide> }
<ide>
<ide> // RawSysInfo returns *sysinfo.SysInfo .
<del>func (daemon *Daemon) RawSysInfo(quiet bool) *sysinfo.SysInfo {
<del> return sysinfo.New(quiet)
<add>func (daemon *Daemon) RawSysInfo() *sysinfo.SysInfo {
<add> return sysinfo.New()
<ide> }
<ide><path>daemon/daemon_windows.go
<ide> func setupResolvConf(config *config.Config) {
<ide> }
<ide>
<ide> // RawSysInfo returns *sysinfo.SysInfo .
<del>func (daemon *Daemon) RawSysInfo(quiet bool) *sysinfo.SysInfo {
<del> return sysinfo.New(quiet)
<add>func (daemon *Daemon) RawSysInfo() *sysinfo.SysInfo {
<add> return sysinfo.New()
<ide> }
<ide><path>daemon/info.go
<ide> import (
<ide> func (daemon *Daemon) SystemInfo() *types.Info {
<ide> defer metrics.StartTimer(hostInfoFunctions.WithValues("system_info"))()
<ide>
<del> sysInfo := daemon.RawSysInfo(true)
<add> sysInfo := daemon.RawSysInfo()
<ide> cRunning, cPaused, cStopped := stateCtr.get()
<ide>
<ide> v := &types.Info{
<ide><path>daemon/oci_linux.go
<ide> func WithCgroups(daemon *Daemon, c *container.Container) coci.SpecOpts {
<ide> }
<ide>
<ide> // FIXME this is very expensive way to check if cpu rt is supported
<del> sysInfo := daemon.RawSysInfo(true)
<add> sysInfo := daemon.RawSysInfo()
<ide> if !sysInfo.CPURealtime {
<ide> return errors.New("daemon-scoped cpu-rt-period and cpu-rt-runtime are not supported by the kernel")
<ide> }
<ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *testing.T) {
<ide> func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *testing.T) {
<ide> testRequires(c, cgroupCpuset, testEnv.IsLocalDaemon)
<ide>
<del> sysInfo := sysinfo.New(true)
<add> sysInfo := sysinfo.New()
<ide> cpus, err := parsers.ParseUintList(sysInfo.Cpus)
<ide> assert.NilError(c, err)
<ide> var invalid int
<ide> func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *testing.T) {
<ide> func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *testing.T) {
<ide> testRequires(c, cgroupCpuset)
<ide>
<del> sysInfo := sysinfo.New(true)
<add> sysInfo := sysinfo.New()
<ide> mems, err := parsers.ParseUintList(sysInfo.Mems)
<ide> assert.NilError(c, err)
<ide> var invalid int
<ide><path>integration-cli/requirements_unix_test.go
<ide> func overlayFSSupported() bool {
<ide>
<ide> func init() {
<ide> if testEnv.IsLocalDaemon() {
<del> SysInfo = sysinfo.New(true)
<add> SysInfo = sysinfo.New()
<ide> }
<ide> }
<ide><path>pkg/sysinfo/cgroup2_linux.go
<ide> import (
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide>
<del>func newV2(quiet bool, options ...Opt) *SysInfo {
<add>func newV2(options ...Opt) *SysInfo {
<ide> sysInfo := &SysInfo{
<ide> CgroupUnified: true,
<ide> cg2GroupPath: "/",
<ide> func newV2(quiet bool, options ...Opt) *SysInfo {
<ide> for _, o := range ops {
<ide> o(sysInfo)
<ide> }
<del> if !quiet {
<del> for _, w := range sysInfo.Warnings {
<del> logrus.Warn(w)
<del> }
<del> }
<ide> return sysInfo
<ide> }
<ide>
<ide><path>pkg/sysinfo/sysinfo_linux.go
<ide> func WithCgroup2GroupPath(g string) Opt {
<ide> }
<ide>
<ide> // New returns a new SysInfo, using the filesystem to detect which features
<del>// the kernel supports. If `quiet` is `false` info.Warnings are printed in logs
<del>// whenever an error occurs or misconfigurations are present.
<del>func New(quiet bool, options ...Opt) *SysInfo {
<add>// the kernel supports.
<add>func New(options ...Opt) *SysInfo {
<ide> if cdcgroups.Mode() == cdcgroups.Unified {
<del> return newV2(quiet, options...)
<add> return newV2(options...)
<ide> }
<del> return newV1(quiet)
<add> return newV1()
<ide> }
<ide>
<del>func newV1(quiet bool) *SysInfo {
<add>func newV1() *SysInfo {
<ide> var (
<ide> err error
<ide> sysInfo = &SysInfo{}
<ide> func newV1(quiet bool) *SysInfo {
<ide> for _, o := range ops {
<ide> o(sysInfo)
<ide> }
<del> if !quiet {
<del> for _, w := range sysInfo.Warnings {
<del> logrus.Warn(w)
<del> }
<del> }
<ide> return sysInfo
<ide> }
<ide>
<ide><path>pkg/sysinfo/sysinfo_linux_test.go
<ide> func TestCgroupEnabled(t *testing.T) {
<ide> }
<ide>
<ide> func TestNew(t *testing.T) {
<del> sysInfo := New(false)
<del> assert.Assert(t, sysInfo != nil)
<del> checkSysInfo(t, sysInfo)
<del>
<del> sysInfo = New(true)
<add> sysInfo := New()
<ide> assert.Assert(t, sysInfo != nil)
<ide> checkSysInfo(t, sysInfo)
<ide> }
<ide> func TestNewAppArmorEnabled(t *testing.T) {
<ide> t.Skip("App Armor Must be Enabled")
<ide> }
<ide>
<del> sysInfo := New(true)
<add> sysInfo := New()
<ide> assert.Assert(t, sysInfo.AppArmor)
<ide> }
<ide>
<ide> func TestNewAppArmorDisabled(t *testing.T) {
<ide> t.Skip("App Armor Must be Disabled")
<ide> }
<ide>
<del> sysInfo := New(true)
<add> sysInfo := New()
<ide> assert.Assert(t, !sysInfo.AppArmor)
<ide> }
<ide>
<ide> func TestNewCgroupNamespacesEnabled(t *testing.T) {
<ide> t.Skip("cgroup namespaces must be enabled")
<ide> }
<ide>
<del> sysInfo := New(true)
<add> sysInfo := New()
<ide> assert.Assert(t, sysInfo.CgroupNamespaces)
<ide> }
<ide>
<ide> func TestNewCgroupNamespacesDisabled(t *testing.T) {
<ide> t.Skip("cgroup namespaces must be disabled")
<ide> }
<ide>
<del> sysInfo := New(true)
<add> sysInfo := New()
<ide> assert.Assert(t, !sysInfo.CgroupNamespaces)
<ide> }
<ide>
<ide><path>pkg/sysinfo/sysinfo_other.go
<ide> package sysinfo // import "github.com/docker/docker/pkg/sysinfo"
<ide>
<ide> // New returns an empty SysInfo for non linux for now.
<del>func New(quiet bool, options ...Opt) *SysInfo {
<add>func New(options ...Opt) *SysInfo {
<ide> return &SysInfo{}
<ide> }
<ide><path>runconfig/config.go
<ide> func (r ContainerDecoder) DecodeConfig(src io.Reader) (*container.Config, *conta
<ide> if r.GetSysInfo != nil {
<ide> si = r.GetSysInfo()
<ide> } else {
<del> si = sysinfo.New(true)
<add> si = sysinfo.New()
<ide> }
<ide>
<ide> return decodeContainerConfig(src, si)
<ide><path>runconfig/config_test.go
<ide> func TestDecodeContainerConfig(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<del> c, h, _, err := decodeContainerConfig(bytes.NewReader(b), sysinfo.New(true))
<add> c, h, _, err := decodeContainerConfig(bytes.NewReader(b), sysinfo.New())
<ide> if err != nil {
<ide> t.Fatal(fmt.Errorf("Error parsing %s: %v", f, err))
<ide> }
<ide> func callDecodeContainerConfigIsolation(isolation string) (*container.Config, *c
<ide> if b, err = json.Marshal(w); err != nil {
<ide> return nil, nil, nil, fmt.Errorf("Error on marshal %s", err.Error())
<ide> }
<del> return decodeContainerConfig(bytes.NewReader(b), sysinfo.New(true))
<add> return decodeContainerConfig(bytes.NewReader(b), sysinfo.New())
<ide> } | 15 |
Javascript | Javascript | adjust layoutselector for i18n | b45e78d1eedec74876b9b84496536bd9afab75b3 | <ide><path>client/utils/gatsby/layoutSelector.js
<ide> export default function layoutSelector({ element, props }) {
<ide> if (element.type === FourOhFourPage) {
<ide> return <DefaultLayout pathname={pathname}>{element}</DefaultLayout>;
<ide> }
<del> if (/^\/certification(\/.*)*/.test(pathname)) {
<add> if (/\/certification\//.test(pathname)) {
<ide> return (
<ide> <CertificationLayout pathname={pathname}>{element}</CertificationLayout>
<ide> );
<ide> }
<del> if (/^\/guide(\/.*)*/.test(pathname)) {
<add> if (/\/guide\//.test(pathname)) {
<ide> console.log('Hitting guide for some reason. Need a redirect.');
<ide> }
<ide>
<ide> const splitPath = pathname.split('/');
<del> const splitPathThree = splitPath.length > 2 ? splitPath[3] : '';
<add> const isSuperBlock =
<add> (splitPath.length === 3 && splitPath[1]) ||
<add> (splitPath.length === 4 && splitPath[2]);
<ide>
<del> const isNotSuperBlockIntro =
<del> splitPath.length > 3 && splitPathThree.length > 1;
<del>
<del> if (/^\/learn(\/.*)*/.test(pathname) && isNotSuperBlockIntro) {
<add> if (/\/learn\//.test(pathname) && !isSuperBlock) {
<ide> return (
<ide> <DefaultLayout pathname={pathname} showFooter={false}>
<ide> {element} | 1 |
PHP | PHP | apply fixes from styleci | 34af980c3e9668c98d48025634ab0d18bc964367 | <ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function renderExceptionWithWhoops(Exception $e)
<ide> $whoops->writeToOutput(false);
<ide>
<ide> $whoops->allowQuit(false);
<del> })->handleException($e);
<add> }
<add> )->handleException($e);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | modify representation for some objects | 5a0f8c95e253025229f2ed1e8e80ea4c4f142d60 | <ide><path>libcloud/common/dimensiondata.py
<ide> def __init__(self, id, name, action, location, network_domain,
<ide> self.enabled = enabled
<ide>
<ide> def __repr__(self):
<del> return (('<DimensionDataNetworkDomain: id=%s, name=%s, '
<del> 'action=%s, location=%s, status=%s>')
<add> return (('<DimensionDataFirewallRule: id=%s, name=%s, '
<add> 'action=%s, location=%s, network_domain=%s, '
<add> 'status=%s, ip_version=%s, protocol=%s, source=%s, '
<add> 'destination=%s, enabled=%s>')
<ide> % (self.id, self.name, self.action, self.location,
<del> self.status))
<add> self.network_domain, self.status, self.ip_version,
<add> self.protocol, self.source, self.destination,
<add> self.enabled))
<ide>
<ide>
<ide> class DimensionDataFirewallAddress(object):
<ide> def __init__(self, id, name, status, ip, port, node_id):
<ide> self.node_id = node_id
<ide>
<ide> def __repr__(self):
<del> return (('<DimensionDataPool: id=%s, name=%s, '
<add> return (('<DimensionDataPoolMember: id=%s, name=%s, '
<ide> 'ip=%s, status=%s, port=%s, node_id=%s>')
<ide> % (self.id, self.name,
<ide> self.ip, self.status, self.port,
<ide> def __init__(self, id, name, status, ip):
<ide> self.ip = ip
<ide>
<ide> def __repr__(self):
<del> return (('<DimensionDataPool: id=%s, name=%s, '
<add> return (('<DimensionDataVirtualListener: id=%s, name=%s, '
<ide> 'status=%s, ip=%s>')
<ide> % (self.id, self.name,
<ide> self.status, self.ip)) | 1 |
Javascript | Javascript | fix style in readline | 65f2e72d770158502eacdc0a847ca538534749b7 | <ide><path>lib/readline.js
<ide> Interface.prototype._ttyWrite = function (b) {
<ide> } else if (b[1] === 91 && b[2] === 66) { // down arrow
<ide> this._historyNext();
<ide> } else if (b[1] === 91 && b[2] === 51 && this.cursor < this.line.length) { // delete right
<del> this.line = this.line.slice(0, this.cursor)
<del> + this.line.slice(this.cursor+1, this.line.length)
<del> ;
<add> this.line = this.line.slice(0, this.cursor) +
<add> this.line.slice(this.cursor+1, this.line.length);
<ide> this._refreshLine();
<ide> }
<ide> break; | 1 |
PHP | PHP | use arr class | b310b1ec45d0097ac1cee30b26c7bdd2e139090d | <ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide>
<ide> use RuntimeException;
<ide> use Illuminate\Http\File;
<add>use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Support\Carbon;
<ide> public function __construct(FilesystemInterface $driver)
<ide> */
<ide> public function assertExists($path)
<ide> {
<del> $paths = array_wrap($path);
<add> $paths = Arr::wrap($path);
<ide>
<ide> foreach ($paths as $path) {
<ide> PHPUnit::assertTrue(
<ide> public function assertExists($path)
<ide> */
<ide> public function assertMissing($path)
<ide> {
<del> $paths = array_wrap($path);
<add> $paths = Arr::wrap($path);
<ide>
<ide> foreach ($paths as $path) {
<ide> PHPUnit::assertFalse( | 1 |
PHP | PHP | fix style violation | 3c907066923823ff8e3f6079f8f49bf4eb9a6c26 | <ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testWithoutEventDispatcher()
<ide> $model = EloquentModelSaveStub::withoutEventDispatcher(function () {
<ide> $model = new EloquentModelSaveStub;
<ide> $model->save();
<add>
<ide> return $model;
<ide> });
<ide> | 1 |
Python | Python | add benchmark for small array coercions | ad1dd9066f04f0dda10a1c991480ba506d53676a | <ide><path>benchmarks/benchmarks/bench_array_coercion.py
<add>from __future__ import absolute_import, division, print_function
<add>
<add>from .common import Benchmark
<add>
<add>import numpy as np
<add>
<add>
<add>class ArrayCoercionSmall(Benchmark):
<add> # More detailed benchmarks for array coercion,
<add> # some basic benchmarks are in `bench_core.py`.
<add> params = [[range(3), [1], 1, np.array([5], dtype=np.int64), np.int64(5)]]
<add> param_names = ['array_like']
<add> int64 = np.dtype(np.int64)
<add>
<add> def time_array_invalid_kwarg(self, array_like):
<add> try:
<add> np.array(array_like, ndmin="not-integer")
<add> except TypeError:
<add> pass
<add>
<add> def time_array(self, array_like):
<add> np.array(array_like)
<add>
<add> def time_array_dtype_not_kwargs(self, array_like):
<add> np.array(array_like, self.int64)
<add>
<add> def time_array_no_copy(self, array_like):
<add> np.array(array_like, copy=False)
<add>
<add> def time_array_subok(self, array_like):
<add> np.array(array_like, subok=True)
<add>
<add> def time_array_all_kwargs(self, array_like):
<add> np.array(array_like, dtype=self.int64, copy=False, order="F",
<add> subok=False, ndmin=2)
<add>
<add> def time_asarray(self, array_like):
<add> np.asarray(array_like)
<add>
<add> def time_asarray_dtype(self, array_like):
<add> np.array(array_like, dtype=self.int64)
<add>
<add> def time_asarray_dtype(self, array_like):
<add> np.array(array_like, dtype=self.int64, order="F")
<add>
<add> def time_asanyarray(self, array_like):
<add> np.asarray(array_like)
<add>
<add> def time_asanyarray_dtype(self, array_like):
<add> np.array(array_like, dtype=self.int64)
<add>
<add> def time_asanyarray_dtype(self, array_like):
<add> np.array(array_like, dtype=self.int64, order="F")
<add>
<add> def time_ascontiguousarray(self, array_like):
<add> np.ascontiguousarray(array_like)
<add> | 1 |
Ruby | Ruby | use rails convetions | ade741e113928b6ee4b376ee5d60e6813ecc35c4 | <ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb
<ide> def test_belongs_to_with_touch_option_on_touch
<ide> end
<ide>
<ide> def test_belongs_to_with_touch_option_on_touch_without_updated_at_attributes
<del> assert !LineItem.column_names.include?("updated_at")
<add> assert_not LineItem.column_names.include?("updated_at")
<ide>
<ide> line_item = LineItem.create!
<ide> invoice = Invoice.create!(line_items: [line_item])
<ide> initial = invoice.updated_at
<ide> line_item.touch
<ide>
<del> refute_equal initial, invoice.reload.updated_at
<add> assert_not_equal initial, invoice.reload.updated_at
<ide> end
<ide>
<ide> def test_belongs_to_with_touch_option_on_touch_and_removed_parent | 1 |
Text | Text | update coverage badge and link to coveralls | 58798d5b359e69021b299b0f601db601f41452de | <ide><path>README.md
<ide> <a href="https://travis-ci.org/cakephp/cakephp" target="_blank">
<ide> <img alt="Build Status" src="https://img.shields.io/travis/cakephp/cakephp/master.svg?style=flat-square">
<ide> </a>
<del> <a href="https://codecov.io/github/cakephp/cakephp" target="_blank">
<del> <img alt="Coverage Status" src="https://img.shields.io/codecov/c/github/cakephp/cakephp.svg?style=flat-square">
<add> <a href="https://coveralls.io/r/cakephp/cakephp?branch=master" target="_blank">
<add> <img alt="Coverage Status" src="https://img.shields.io/coveralls/cakephp/cakephp/master.svg?style=flat-square">
<ide> </a>
<ide> <a href="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/" target="_blank">
<ide> <img alt="Code Consistency" src="https://squizlabs.github.io/PHP_CodeSniffer/analysis/cakephp/cakephp/grade.svg"> | 1 |
Go | Go | change floats to ints recursively on env encoding | 1d3d1c5d2b762a32fbee348702af96f9c00fff83 | <ide><path>engine/env.go
<ide> func (env *Env) SetAuto(k string, v interface{}) {
<ide> }
<ide> }
<ide>
<add>func changeFloats(v interface{}) interface{} {
<add> switch v := v.(type) {
<add> case float64:
<add> return int(v)
<add> case map[string]interface{}:
<add> for key, val := range v {
<add> v[key] = changeFloats(val)
<add> }
<add> case []interface{}:
<add> for idx, val := range v {
<add> v[idx] = changeFloats(val)
<add> }
<add> }
<add> return v
<add>}
<add>
<ide> func (env *Env) Encode(dst io.Writer) error {
<ide> m := make(map[string]interface{})
<ide> for k, v := range env.Map() {
<ide> func (env *Env) Encode(dst io.Writer) error {
<ide> // FIXME: we fix-convert float values to int, because
<ide> // encoding/json decodes integers to float64, but cannot encode them back.
<ide> // (See http://golang.org/src/pkg/encoding/json/decode.go#L46)
<del> if fval, isFloat := val.(float64); isFloat {
<del> val = int(fval)
<del> }
<del> m[k] = val
<add> m[k] = changeFloats(val)
<ide> } else {
<ide> m[k] = v
<ide> }
<ide><path>engine/env_test.go
<ide> package engine
<ide>
<ide> import (
<ide> "bytes"
<add> "encoding/json"
<ide> "testing"
<ide>
<ide> "github.com/dotcloud/docker/pkg/testutils"
<ide> func BenchmarkDecode(b *testing.B) {
<ide> reader.Seek(0, 0)
<ide> }
<ide> }
<add>
<add>func TestLongNumbers(t *testing.T) {
<add> type T struct {
<add> TestNum int64
<add> }
<add> v := T{67108864}
<add> var buf bytes.Buffer
<add> e := &Env{}
<add> e.SetJson("Test", v)
<add> if err := e.Encode(&buf); err != nil {
<add> t.Fatal(err)
<add> }
<add> res := make(map[string]T)
<add> if err := json.Unmarshal(buf.Bytes(), &res); err != nil {
<add> t.Fatal(err)
<add> }
<add> if res["Test"].TestNum != v.TestNum {
<add> t.Fatalf("TestNum %d, expected %d", res["Test"].TestNum, v.TestNum)
<add> }
<add>}
<add>
<add>func TestLongNumbersArray(t *testing.T) {
<add> type T struct {
<add> TestNum []int64
<add> }
<add> v := T{[]int64{67108864}}
<add> var buf bytes.Buffer
<add> e := &Env{}
<add> e.SetJson("Test", v)
<add> if err := e.Encode(&buf); err != nil {
<add> t.Fatal(err)
<add> }
<add> res := make(map[string]T)
<add> if err := json.Unmarshal(buf.Bytes(), &res); err != nil {
<add> t.Fatal(err)
<add> }
<add> if res["Test"].TestNum[0] != v.TestNum[0] {
<add> t.Fatalf("TestNum %d, expected %d", res["Test"].TestNum, v.TestNum)
<add> }
<add>} | 2 |
Javascript | Javascript | remove old reference to rootresponder | 4a250b3b7062e531955bcad3d017f998e60fe75f | <ide><path>packages/ember-handlebars/tests/handlebars_test.js
<ide> test("Child views created using the view helper should have their IDs registered
<ide>
<ide> var childView = firstChild(view);
<ide> var id = childView.$()[0].id;
<del> equal(Ember.View.views[id], childView, 'childView without passed ID is registered with Ember.View.views so that it can properly receive events from RootResponder');
<add> equal(Ember.View.views[id], childView, 'childView without passed ID is registered with Ember.View.views so that it can properly receive events from EventDispatcher');
<ide>
<ide> childView = nthChild(view, 1);
<ide> id = childView.$()[0].id;
<ide> equal(id, 'templateViewTest', 'precond -- id of childView should be set correctly');
<del> equal(Ember.View.views[id], childView, 'childView with passed ID is registered with Ember.View.views so that it can properly receive events from RootResponder');
<add> equal(Ember.View.views[id], childView, 'childView with passed ID is registered with Ember.View.views so that it can properly receive events from EventDispatcher');
<ide> });
<ide>
<ide> test("Child views created using the view helper and that have a viewName should be registered as properties on their parentView", function() { | 1 |
PHP | PHP | fix failing schemacollection tests | 32be6679dac00f28885046c65f876689b30b2553 | <ide><path>Cake/Test/TestCase/Database/Schema/CollectionTest.php
<ide> class CollectionTest extends TestCase {
<ide> public function setUp() {
<ide> parent::setUp();
<ide> $this->connection = ConnectionManager::get('test');
<add> Cache::clear(false, '_cake_model_');
<add> Cache::enable();
<ide> }
<ide>
<ide> /**
<ide> public function setUp() {
<ide> public function tearDown() {
<ide> parent::tearDown();
<ide> unset($this->connection);
<del> Cache::clear(true, '_cake_model_');
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | allow serializing of objects with null prototype | 44663f8c673eb0f3a10aca7f5ca60b65381f59dd | <ide><path>lib/serialization/NullPrototypeObjectSerializer.js
<add>/*
<add> MIT License http://www.opensource.org/licenses/mit-license.php
<add>*/
<add>
<add>"use strict";
<add>
<add>class NullPrototypeObjectSerializer {
<add> serialize(obj, { write }) {
<add> const keys = Object.keys(obj);
<add> for (const key of keys) {
<add> write(key);
<add> }
<add> write(null);
<add> for (const key of keys) {
<add> write(obj[key]);
<add> }
<add> }
<add> deserialize({ read }) {
<add> const obj = Object.create(null);
<add> const keys = [];
<add> let key = read();
<add> while (key !== null) {
<add> keys.push(key);
<add> key = read();
<add> }
<add> for (const key of keys) {
<add> obj[key] = read();
<add> }
<add> return obj;
<add> }
<add>}
<add>
<add>module.exports = NullPrototypeObjectSerializer;
<ide><path>lib/serialization/ObjectMiddleware.js
<ide> const memorize = require("../util/memorize");
<ide> const ErrorObjectSerializer = require("./ErrorObjectSerializer");
<ide> const MapObjectSerializer = require("./MapObjectSerializer");
<add>const NullPrototypeObjectSerializer = require("./NullPrototypeObjectSerializer");
<ide> const PlainObjectSerializer = require("./PlainObjectSerializer");
<ide> const RegExpObjectSerializer = require("./RegExpObjectSerializer");
<ide> const SerializerMiddleware = require("./SerializerMiddleware");
<ide> const ESCAPE_ESCAPE_VALUE = null;
<ide> const ESCAPE_END_OBJECT = true;
<ide> const ESCAPE_UNDEFINED = false;
<ide>
<del>const CURRENT_VERSION = 1;
<add>const CURRENT_VERSION = 2;
<ide>
<ide> const plainObjectSerializer = new PlainObjectSerializer();
<ide>
<ide> serializers.set(Array, {
<ide> });
<ide>
<ide> const jsTypes = new Map();
<add>jsTypes.set(null, new NullPrototypeObjectSerializer());
<ide> jsTypes.set(Map, new MapObjectSerializer());
<ide> jsTypes.set(Set, new SetObjectSerializer());
<ide> jsTypes.set(RegExp, new RegExpObjectSerializer());
<ide> class ObjectMiddleware extends SerializerMiddleware {
<ide> }
<ide>
<ide> static getSerializerFor(object) {
<del> const c = object.constructor;
<add> let c = object.constructor;
<add> if (!c) {
<add> if (Object.getPrototypeOf(object) === null) {
<add> // Object created with Object.create(null)
<add> c = null;
<add> } else {
<add> throw new Error(
<add> "Serialization of objects with prototype without valid constructor property not possible"
<add> );
<add> }
<add> }
<ide> const config = serializers.get(c);
<ide>
<ide> if (!config) throw new Error(`No serializer registered for ${c.name}`);
<ide><path>test/cases/loaders/emit-file/file.js
<add>module.exports = "ok";
<ide><path>test/cases/loaders/emit-file/index.js
<add>import "./loader!./file";
<add>
<add>it("should have the file emitted", () => {
<add> const result = __non_webpack_require__("./extra-file.js");
<add> expect(result).toBe("ok");
<add>});
<ide><path>test/cases/loaders/emit-file/loader.js
<add>module.exports = function(content) {
<add> this.emitFile("extra-file.js", content);
<add> return "";
<add>} | 5 |
Text | Text | update all-langs.js link | 135d93ee6df123c1636f4fe46c5096f87e18979c | <ide><path>docs/how-to-work-on-localized-client-webapp.md
<ide> You can test the client app in any language available in the [list of languages
<ide>
<ide> If you are testing a new language, create a folder with the language name as the title next to the other languages and copy the JSON files from another language into your new folder.
<ide>
<del>Add the language to the `client` array as seen above in the [`config/i18n/all-langs.js`](https://github.com/freeCodeCamp/freeCodeCamp/blob/main/config/i18n/all-langs.js) file.
<add>Add the language to the `client` array as seen above in the [`config/i18n/all-langs.ts`](https://github.com/freeCodeCamp/freeCodeCamp/blob/main/config/i18n/all-langs.ts) file.
<ide>
<ide> Next, follow the instructions in the comments in the same file to add/update the rest of the variables as needed.
<ide> | 1 |
PHP | PHP | update docs + add tests for tableregistry | 132232294af3d70a141d082afea638a6b8012aa5 | <ide><path>Cake/ORM/TableRegistry.php
<ide> class TableRegistry {
<ide> protected static $_instances = [];
<ide>
<ide> /**
<del> * Stores a list of options to be used when instantiating an object for the table
<del> * with the same name as $table. The options that can be stored are those that
<del> * are recognized by `build()`
<add> * Stores a list of options to be used when instantiating an object
<add> * with a matching alias.
<ide> *
<del> * If second argument is omitted, it will return the current settings for $table
<add> * The options that can be stored are those that are recognized by `build()`
<add> * If second argument is omitted, it will return the current settings
<add> * for $alias.
<ide> *
<ide> * If no arguments are passed it will return the full configuration array for
<del> * all tables
<add> * all aliases
<ide> *
<del> * @param string $table name of the table
<del> * @param null|array $options list of options for the table
<del> * @return array
<add> * @param string $alias Name of the alias
<add> * @param null|array $options list of options for the alias
<add> * @return array The config data.
<ide> */
<del> public static function config($table = null, $options = null) {
<del> if ($table === null) {
<add> public static function config($alias = null, $options = null) {
<add> if ($alias === null) {
<ide> return static::$_config;
<ide> }
<del> if (!is_string($table)) {
<del> return static::$_config = $table;
<add> if (!is_string($alias)) {
<add> return static::$_config = $alias;
<ide> }
<ide> if ($options === null) {
<del> return isset(static::$_config[$table]) ? static::$_config[$table] : [];
<add> return isset(static::$_config[$alias]) ? static::$_config[$alias] : [];
<ide> }
<del> return static::$_config[$table] = $options;
<add> return static::$_config[$alias] = $options;
<ide> }
<ide>
<ide> /**
<ide><path>Cake/Test/TestCase/ORM/TableRegistryTest.php
<add><?php
<add>/**
<add> * PHP Version 5.4
<add> *
<add> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
<add> * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> *
<add> * Licensed under The MIT License
<add> * For full copyright and license information, please see the LICENSE.txt
<add> * Redistributions of files must retain the above copyright notice.
<add> *
<add> * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
<add> * @link http://cakephp.org CakePHP(tm) Project
<add> * @since CakePHP(tm) v 3.0.0
<add> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<add> */
<add>namespace Cake\Test\TestCase\ORM;
<add>
<add>use Cake\ORM\Table;
<add>use Cake\ORM\TableRegistry;
<add>use Cake\TestSuite\TestCase;
<add>
<add>/**
<add> * Test case for TableRegistry
<add> */
<add>class TableRegistryTest extends TestCase {
<add>
<add>/**
<add> * tear down
<add> *
<add> * @return void
<add> */
<add> public function tearDown() {
<add> parent::tearDown();
<add> TableRegistry::clear();
<add> }
<add>
<add>/**
<add> * Test config() method.
<add> *
<add> * @return void
<add> */
<add> public function testConfig() {
<add> $this->assertEquals([], TableRegistry::config('Test'));
<add>
<add> $data = [
<add> 'connection' => 'testing',
<add> 'entityClass' => 'TestApp\Model\Entity\Article',
<add> ];
<add> $result = TableRegistry::config('Test', $data);
<add> $this->assertEquals($data, $result, 'Returns config data.');
<add>
<add> $result = TableRegistry::config();
<add> $expected = ['Test' => $data];
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<add>/**
<add> * Test getting instances from the registry.
<add> *
<add> * @return void
<add> */
<add> public function testGet() {
<add> $result = TableRegistry::get('Article', ['table' => 'my_articles']);
<add> $this->assertInstanceOf('Cake\ORM\Table', $result);
<add> $this->assertEquals('my_articles', $result->table());
<add>
<add> $result2 = TableRegistry::get('Article', ['table' => 'herp_derp']);
<add> $this->assertSame($result, $result2);
<add> $this->assertEquals('my_articles', $result->table());
<add> }
<add>
<add>/**
<add> * Test that get() uses config data set with config()
<add> *
<add> * @return void
<add> */
<add> public function testGetWithConfig() {
<add> TableRegistry::config('Article', ['table' => 'my_articles']);
<add> $result = TableRegistry::get('Article');
<add> $this->assertEquals('my_articles', $result->table(), 'Should use config() data.');
<add> }
<add>
<add>/**
<add> * Test setting an instance.
<add> *
<add> * @return void
<add> */
<add> public function testSet() {
<add> $mock = $this->getMock('Cake\ORM\Table');
<add> $this->assertSame($mock, TableRegistry::set('Article', $mock));
<add> $this->assertSame($mock, TableRegistry::get('Article'));
<add> }
<add>
<add>} | 2 |
Javascript | Javascript | use arguments rather than an array of keys | e27f9fe458ad798bacd545c10ba3b53104b5bc9c | <ide><path>packages/sproutcore-runtime/lib/mixins/observable.js
<ide> SC.Observable = SC.Mixin.create(/** @scope SC.Observable.prototype */ {
<ide>
<ide> /**
<ide> To get multiple properties at once, call getProperties
<del> with an Array:
<add> with a list of strings:
<ide>
<del> record.getProperties(['firstName', 'lastName', 'zipCode']);
<add> record.getProperties('firstName', 'lastName', 'zipCode');
<ide>
<del> @param {Array} array of keys to get
<add> @param {String...} list of keys to get
<ide> @returns {Hash}
<ide> */
<del> getProperties: function(keyNames) {
<add> getProperties: function() {
<ide> var ret = {};
<del> for(var i = 0; i < keyNames.length; i++) {
<del> ret[keyNames[i]] = get(this, keyNames[i]);
<add> for(var i = 0; i < arguments.length; i++) {
<add> ret[arguments[i]] = get(this, arguments[i]);
<ide> }
<ide> return ret;
<ide> },
<ide><path>packages/sproutcore-runtime/tests/mixins/observable_test.js
<ide> test('should be able to use getProperties to get a POJO of provided keys', funct
<ide> var obj = SC.Object.create({
<ide> firstName: "Steve",
<ide> lastName: "Jobs",
<del> zipCode: 94301
<add> companyName: "Apple, Inc."
<ide> });
<ide>
<del> var pojo = obj.getProperties("firstName lastName".w());
<add> var pojo = obj.getProperties("firstName", "lastName");
<ide> equals("Steve", pojo.firstName);
<ide> equals("Jobs", pojo.lastName);
<ide> });
<ide>\ No newline at end of file | 2 |
Ruby | Ruby | add fuse migrations | bd5083f970e26b3978f26493300951f9be0fad75 | <ide><path>Library/Homebrew/tap_migrations.rb
<ide> TAP_MIGRATIONS = {
<ide> "adobe-air-sdk" => "homebrew/binary",
<add> "afuse" => "homebrew/fuse",
<ide> "agedu" => "homebrew/head-only",
<ide> "aimage" => "homebrew/boneyard",
<ide> "aplus" => "homebrew/boneyard",
<ide> "apple-gcc42" => "homebrew/dupes",
<ide> "appledoc" => "homebrew/boneyard",
<ide> "appswitch" => "homebrew/binary",
<add> "archivemount" => "homebrew/fuse",
<ide> "atari++" => "homebrew/x11",
<ide> "auctex" => "homebrew/tex",
<ide> "authexec" => "homebrew/boneyard",
<add> "avfs" => "homebrew/fuse",
<ide> "aws-iam-tools" => "homebrew/boneyard",
<ide> "bbcp" => "homebrew/head-only",
<ide> "bcwipe" => "homebrew/boneyard",
<add> "bindfs" => "homebrew/fuse",
<ide> "blackbox" => "homebrew/boneyard",
<ide> "bochs" => "homebrew/x11",
<ide> "boost149" => "homebrew/versions",
<ide> "ddd" => "homebrew/x11",
<ide> "denyhosts" => "homebrew/boneyard",
<ide> "dgtal" => "homebrew/science",
<add> "djmount" => "homebrew/fuse",
<ide> "dmenu" => "homebrew/x11",
<ide> "dotwrp" => "homebrew/science",
<ide> "drizzle" => "homebrew/boneyard",
<ide> "dzen2" => "homebrew/x11",
<ide> "easy-tag" => "homebrew/x11",
<ide> "electric-fence" => "homebrew/boneyard",
<add> "encfs" => "homebrew/fuse",
<add> "ext2fuse" => "homebrew/fuse",
<add> "ext4fuse" => "homebrew/fuse",
<ide> "fceux" => "homebrew/games",
<ide> "feh" => "homebrew/x11",
<ide> "figtoipe" => "homebrew/head-only",
<ide> "fox" => "homebrew/x11",
<ide> "freeglut" => "homebrew/x11",
<ide> "freerdp" => "homebrew/x11",
<ide> "fsv" => "homebrew/x11",
<add> "fuse-zip" => "homebrew/fuse",
<add> "fuse4x-kext" => "homebrew/fuse",
<add> "fuse4x" => "homebrew/fuse",
<add> "gcsfuse" => "homebrew/fuse",
<ide> "geany" => "homebrew/x11",
<ide> "geda-gaf" => "homebrew/x11",
<ide> "geeqie" => "homebrew/x11",
<ide> "ggobi" => "homebrew/x11",
<ide> "giblib" => "homebrew/x11",
<ide> "git-flow-clone" => "homebrew/boneyard",
<add> "gitfs" => "homebrew/fuse",
<ide> "git-latexdiff" => "homebrew/tex",
<ide> "gkrellm" => "homebrew/x11",
<ide> "glade" => "homebrew/x11",
<ide> "hllib" => "homebrew/boneyard",
<ide> "hugs98" => "homebrew/boneyard",
<ide> "hwloc" => "homebrew/science",
<add> "ifuse" => "homebrew/fuse",
<ide> "imake" => "homebrew/x11",
<ide> "inkscape" => "homebrew/x11",
<ide> "ipopt" => "homebrew/science",
<ide> "mlkit" => "homebrew/boneyard",
<ide> "mlton" => "homebrew/boneyard",
<ide> "morse" => "homebrew/x11",
<add> "mp3fs" => "homebrew/fuse",
<ide> "mpio" => "homebrew/boneyard",
<ide> "mscgen" => "homebrew/x11",
<ide> "msgpack-rpc" => "homebrew/boneyard",
<ide> "mysqlreport" => "homebrew/boneyard",
<ide> "newick-utils" => "homebrew/science",
<ide> "nlopt" => "homebrew/science",
<add> "ntfs-3g" => "homebrew/fuse",
<ide> "octave" => "homebrew/science",
<ide> "opencv" => "homebrew/science",
<ide> "openfst" => "homebrew/science",
<ide> "opengrm-ngram" => "homebrew/science",
<add> "ori" => "homebrew/fuse",
<ide> "pan" => "homebrew/boneyard",
<ide> "pari" => "homebrew/x11",
<ide> "pathfinder" => "homebrew/boneyard",
<ide> "qfits" => "homebrew/boneyard",
<ide> "qrupdate" => "homebrew/science",
<ide> "rdesktop" => "homebrew/x11",
<add> "rofs-filtered" => "homebrew/fuse",
<ide> "rxvt-unicode" => "homebrew/x11",
<add> "s3-backer" => "homebrew/fuse",
<add> "s3fs" => "homebrew/fuse",
<ide> "salt" => "homebrew/science",
<ide> "scantailor" => "homebrew/x11",
<ide> "shark" => "homebrew/boneyard",
<ide> "shell.fm" => "homebrew/boneyard",
<add> "simple-mtpfs" => "homebrew/fuse",
<ide> "sitecopy" => "homebrew/boneyard",
<ide> "slicot" => "homebrew/science",
<ide> "smartsim" => "homebrew/x11",
<ide> "solfege" => "homebrew/boneyard",
<ide> "sptk" => "homebrew/x11",
<add> "sshfs" => "homebrew/fuse",
<add> "stormfs" => "homebrew/fuse",
<ide> "sundials" => "homebrew/science",
<ide> "swi-prolog" => "homebrew/x11",
<ide> "sxiv" => "homebrew/x11",
<ide> "timbl" => "homebrew/science",
<ide> "tmap" => "homebrew/boneyard",
<ide> "transmission-remote-gtk" => "homebrew/x11",
<add> "tup" => "homebrew/fuse",
<ide> "ume" => "homebrew/games",
<ide> "upnp-router-control" => "homebrew/x11",
<ide> "urweb" => "homebrew/boneyard",
<ide> "ushare" => "homebrew/boneyard",
<ide> "viewglob" => "homebrew/x11",
<add> "wdfs" => "homebrew/fuse",
<ide> "wkhtmltopdf" => "homebrew/boneyard",
<ide> "wmctrl" => "homebrew/x11",
<ide> "wopr" => "homebrew/science",
<ide> "xdotool" => "homebrew/x11",
<ide> "xdu" => "homebrew/x11",
<ide> "xournal" => "homebrew/x11",
<add> "xmount" => "homebrew/fuse",
<ide> "xpa" => "homebrew/x11",
<ide> "xpdf" => "homebrew/x11",
<ide> "xplot" => "homebrew/x11", | 1 |
Ruby | Ruby | remove some warning with ruby 2.2 | 156c6577313ca4183c72423bab5ffd24c1b9353d | <ide><path>railties/test/generators/actions_test.rb
<ide> def test_environment_with_block_should_include_block_contents_in_environment_ini
<ide> run_generator
<ide>
<ide> action :environment do
<del> '# This wont be added'
<add> _ = '# This wont be added'# assignment to silence parse-time warning "unused literal ignored"
<ide> '# This will be added'
<ide> end
<ide> | 1 |
Javascript | Javascript | fix paths of module system and polyfills | 7eb005b4df541ecc5940175b945f82523281d831 | <ide><path>packager/src/ModuleGraph/types.flow.js
<ide> export type TransformedSourceFile =
<ide> export type LibraryOptions = {|
<ide> dependencies?: Array<string>,
<ide> platform?: string,
<del> root: string,
<add> rebasePath: string => string,
<ide> |};
<ide>
<ide> export type Base64Content = string; | 1 |
Text | Text | improve russian translation in challenge | 3a66452896fb3728999c6bb2c5b44d46ce66af6f | <ide><path>curriculum/challenges/russian/01-responsive-web-design/applied-accessibility/add-a-text-alternative-to-images-for-visually-impaired-accessibility.russian.md
<ide> localeTitle: Добавить текстовую альтернативу изо
<ide> ## Description
<ide>
<ide>
<add>
<ide> <section id="description"> Вероятно, вы видели атрибут <code>alt</code> в теге <code>img</code> в других задачах. Текст <code>Alt</code> описывает содержимое изображения и предоставляет текстовую альтернативу. Это помогает в случае, если изображение не загружается или не может быть замечено пользователем. Он также используется поисковыми системами, чтобы понять, что изображение содержит, чтобы включить его в результаты поиска. Вот пример: <code><img src="importantLogo.jpeg" alt="Company logo"></code> Люди с нарушениями зрения полагаются на устройства чтения с экрана для преобразования веб-контента в аудиоинтерфейс. Они не получат информацию, если они представлены только визуально. Для изображений экранные программы могут получить доступ к атрибуту <code>alt</code> и прочитать его содержимое для сообщения ключевой информации. Хороший <code>alt</code> представляет из себя короткий текст, который передает основной смысл изоражения. Вы всегда должны использовать атрибут <code>alt</code> на своих изображениях. По спецификации HTML5 это считается обязательным. </section>
<ide>
<add>
<ide> ## Instructions
<del><section id="instructions"> Camper Cat оказался как ниндзя кодирования, так и настоящим ниндзя, и создает веб-сайт, чтобы поделиться своими знаниями. Изображение профиля, которое он хочет использовать, показывает его навыки и должно быть оценено всеми посетителями сайта. Добавьте атрибут <code>alt</code> в тег <code>img</code> , который объясняет, что Camper Cat делает каратэ. (Изображение <code>src</code> не ссылается на фактический файл, поэтому вы должны увидеть текст <code>alt</code> на дисплее.) </section>
<add><section id="instructions"> Camper Cat будучи не только ниндзей кодирования, но и настояющим ниндзя, создает веб-сайт, чтобы поделиться своими знаниями. Изображение профиля, которое он хочет использовать, показывает его навыки и должно быть оценено всеми посетителями сайта. Добавьте атрибут <code>alt</code> в тег <code>img</code>, который объясняет, что Camper Cat занимается каратэ. (Изображение <code>src</code> не ссылается на фактический файл, поэтому вы должны увидеть текст <code>alt</code> на дисплее.) </section>
<add>
<ide>
<ide>
<ide> | 1 |
Ruby | Ruby | handle optional build-time deps correctly | 93af660c7fd043d1dce809a7bfb5017252f28990 | <ide><path>Library/Homebrew/build.rb
<ide> def expand_reqs
<ide>
<ide> def expand_deps
<ide> f.recursive_dependencies do |dependent, dep|
<del> if dep.optional? || dep.recommended?
<del> Dependency.prune unless dependent.build.with?(dep.name)
<del> elsif dep.build?
<del> Dependency.prune unless dependent == f
<add> if (dep.optional? || dep.recommended?) && dependent.build.without?(dep.name)
<add> Dependency.prune
<add> elsif dep.build? && dependent != f
<add> Dependency.prune
<ide> end
<ide> end
<ide> end | 1 |
Javascript | Javascript | add test for responses to http connect req | 0ecc430894f087e69518dc34e57d66cbae5a39d9 | <ide><path>test/parallel/test-http-connect-req-res.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const http = require('http');
<add>
<add>const server = http.createServer(function(req, res) {
<add> assert(false);
<add>});
<add>server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) {
<add> assert.equal(req.method, 'CONNECT');
<add> assert.equal(req.url, 'example.com:443');
<add> console.error('Server got CONNECT request');
<add>
<add> // It is legal for the server to send some data intended for the client
<add> // along with the CONNECT response
<add> socket.write(
<add> 'HTTP/1.1 200 Connection established\r\n' +
<add> 'Date: Tue, 15 Nov 1994 08:12:31 GMT\r\n' +
<add> '\r\n' +
<add> 'Head'
<add> );
<add>
<add> var data = firstBodyChunk.toString();
<add> socket.on('data', function(buf) {
<add> data += buf.toString();
<add> });
<add> socket.on('end', function() {
<add> socket.end(data);
<add> });
<add>}));
<add>server.listen(common.PORT, common.mustCall(function() {
<add> const req = http.request({
<add> port: common.PORT,
<add> method: 'CONNECT',
<add> path: 'example.com:443'
<add> }, function(res) {
<add> assert(false);
<add> });
<add>
<add> req.on('close', common.mustCall(function() { }));
<add>
<add> req.on('connect', common.mustCall(function(res, socket, firstBodyChunk) {
<add> console.error('Client got CONNECT request');
<add>
<add> // Make sure this request got removed from the pool.
<add> const name = 'localhost:' + common.PORT;
<add> assert(!http.globalAgent.sockets.hasOwnProperty(name));
<add> assert(!http.globalAgent.requests.hasOwnProperty(name));
<add>
<add> // Make sure this socket has detached.
<add> assert(!socket.ondata);
<add> assert(!socket.onend);
<add> assert.equal(socket.listeners('connect').length, 0);
<add> assert.equal(socket.listeners('data').length, 0);
<add>
<add> var data = firstBodyChunk.toString();
<add>
<add> // test that the firstBodyChunk was not parsed as HTTP
<add> assert.equal(data, 'Head');
<add>
<add> socket.on('data', function(buf) {
<add> data += buf.toString();
<add> });
<add> socket.on('end', function() {
<add> assert.equal(data, 'HeadRequestEnd');
<add> server.close();
<add> });
<add> socket.end('End');
<add> }));
<add>
<add> req.end('Request');
<add>})); | 1 |
Python | Python | fix blenderbot tok | 2aa9c2f20445312955078d3d46cc699ea8de33cf | <ide><path>src/transformers/models/blenderbot/tokenization_blenderbot.py
<ide> class BlenderbotTokenizer(RobertaTokenizer):
<ide> "tokenizer_config_file": "tokenizer_config.json",
<ide> }
<ide> pretrained_vocab_files_map = {
<del> "vocab_file": {CKPT_3B: "https://cdn.huggingface.co/facebook/blenderbot-3B/vocab.json"},
<del> "merges_file": {CKPT_3B: "https://cdn.huggingface.co/facebook/blenderbot-3B/merges.txt"},
<del> "tokenizer_config_file": {CKPT_3B: "https://cdn.huggingface.co/facebook/blenderbot-3B/tokenizer_config.json"},
<add> "vocab_file": {CKPT_3B: "https://huggingface.co/facebook/blenderbot-3B/resolve/main/vocab.json"},
<add> "merges_file": {CKPT_3B: "https://huggingface.co/facebook/blenderbot-3B/resolve/main/merges.txt"},
<add> "tokenizer_config_file": {
<add> CKPT_3B: "https://huggingface.co/facebook/blenderbot-3B/resolve/main/tokenizer_config.json"
<add> },
<ide> }
<ide> max_model_input_sizes = {"facebook/blenderbot-3B": 128}
<ide>
<ide><path>src/transformers/models/blenderbot_small/tokenization_blenderbot_small.py
<ide> class BlenderbotSmallTokenizer(PreTrainedTokenizer):
<ide> }
<ide> pretrained_vocab_files_map = {
<ide> "vocab_file": {
<del> "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/blob/main/vocab.json"
<add> "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json"
<ide> },
<ide> "merges_file": {
<del> "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/blob/main/merges.txt"
<add> "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt"
<ide> },
<ide> "tokenizer_config_file": {
<del> "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/blob/main/tokenizer.json"
<add> "facebook/blenderbot_small-90M": "https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer.json"
<ide> },
<ide> }
<ide> max_model_input_sizes = {"facebook/blenderbot_small-90M": 512} | 2 |
Javascript | Javascript | remove unused comments | a65979d02897e924ca54d80270315f5814f55ff1 | <ide><path>test/cases/parsing/issue-11353/index.js
<ide> it('should correctly build the correct function string', () => {
<ide> });
<ide>
<ide> it('should correctly provide the generator function interface', () => {
<del> var gen = generator(); // "Generator { }"
<del> expect(gen.next().value).toBe(0); // 0
<del> expect(gen.next().value).toBe(1); // 0
<del> expect(gen.next().value).toBe(2); // 0
<add> var gen = generator();
<add> expect(gen.next().value).toBe(0);
<add> expect(gen.next().value).toBe(1);
<add> expect(gen.next().value).toBe(2);
<ide> });
<ide>
<ide> it('should correctly import async generator function', () => {
<ide> expect(typeof asyncGenerator).toBe("function");
<ide> });
<ide>
<ide> it('should correctly build the correct async function string', () => {
<del> expect(asyncGenerator.toString().indexOf('async function* ')).toBe(0); // 0
<add> expect(asyncGenerator.toString().indexOf('async function* ')).toBe(0);
<ide> });
<ide>
<ide> it('should correctly provide the async generator function interface', async () => { | 1 |
Python | Python | fix linter issue | 78c6713b4ee06bec1fa579f94b466cbe5fe4e8f3 | <ide><path>numpy/distutils/ccompiler_opt.py
<ide> class _Config:
<ide> ## Power9/ISA 3.00
<ide> VSX3 = dict(interest=3, implies="VSX2", implies_detect=False),
<ide> ## Power10/ISA 3.1
<del> VSX4 = dict(interest=4, implies="VSX3", extra_checks="VSX4_MMA", implies_detect=False),
<add> VSX4 = dict(interest=4, implies="VSX3", implies_detect=False,
<add> extra_checks="VSX4_MMA"),
<ide> # IBM/Z
<ide> ## VX(z13) support
<ide> VX = dict(interest=1, headers="vecintrin.h"), | 1 |
Ruby | Ruby | add documentation for create_with | 97350762da7c723eb49e30f827ee2e4eb5997fd8 | <ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def offset!(value)
<ide> end
<ide>
<ide> # Specifies locking settings (default to +true+). For more information
<del> # on locking, please see +ActiveRecord::Locking+.
<add> # on locking, please see +ActiveRecord::Lockin+g.
<ide> def lock(locks = true)
<ide> spawn.lock!(locks)
<ide> end
<ide> def readonly!(value = true)
<ide> self
<ide> end
<ide>
<add> # Sets attributes to be used when creating new records from a
<add> # relation object.
<add> #
<add> # users = User.where(name: 'Oscar')
<add> # users.new.name # => 'Oscar'
<add> #
<add> # users = users.create_with(name: 'DHH')
<add> # users.new.name # => 'DHH'
<add> #
<add> # You can pass +nil+ to +create_with+ to reset attributes:
<add> #
<add> # users = users.create_with(nil)
<add> # users.new.name # => 'Oscar'
<ide> def create_with(value)
<ide> spawn.create_with!(value)
<ide> end
<ide>
<add> # Like #create_with but modifies the relation in place. Raises
<add> # +ImmutableRelation+ if the relation has already been loaded.
<add> #
<add> # users = User.scoped.create_with!(name: 'Oscar')
<add> # users.name # => 'Oscar'
<ide> def create_with!(value)
<ide> self.create_with_value = value ? create_with_value.merge(value) : {}
<ide> self | 1 |
Javascript | Javascript | remove reference to `.controller` on components | 13afe72bd37cdf5db007bda269eca0d18e7f1ac7 | <ide><path>packages/ember-glimmer/lib/renderer.js
<ide> import { RootReference } from './utils/references';
<ide> import run from 'ember-metal/run_loop';
<ide> import { setHasViews } from 'ember-metal/tags';
<del>import { CURRENT_TAG } from 'glimmer-reference';
<add>import { CURRENT_TAG, UNDEFINED_REFERENCE } from 'glimmer-reference';
<ide>
<ide> const { backburner } = run;
<ide>
<ide> class DynamicScope {
<del> constructor({ view, controller, outletState, isTopLevel }) {
<add> constructor({ view, controller, outletState, isTopLevel, targetObject }) {
<ide> this.view = view;
<ide> this.controller = controller;
<ide> this.outletState = outletState;
<ide> this.isTopLevel = isTopLevel;
<add> this.targetObject = targetObject;
<ide> }
<ide>
<ide> child() {
<ide> class Renderer {
<ide>
<ide> let env = this._env;
<ide> let self = new RootReference(view);
<add> let controller = view.outletState.render.controller;
<ide> let dynamicScope = new DynamicScope({
<ide> view,
<del> controller: view.outletState.render.controller,
<add> controller,
<add> targetObject: controller,
<ide> outletState: view.toReference(),
<ide> isTopLevel: true
<ide> });
<ide> class Renderer {
<ide> appendTo(view, target) {
<ide> let env = this._env;
<ide> let self = new RootReference(view);
<del> let dynamicScope = new DynamicScope({ view, controller: view.controller });
<add> let dynamicScope = new DynamicScope({
<add> view,
<add> controller: undefined,
<add> targetObject: undefined,
<add> outletState: UNDEFINED_REFERENCE,
<add> isTopLevel: true
<add> });
<ide>
<ide> env.begin();
<ide> let result = view.template.asEntryPoint().render(self, env, { appendTo: target, dynamicScope });
<ide><path>packages/ember-glimmer/lib/syntax/curly-component.js
<ide> class CurlyComponentManager {
<ide>
<ide> props.renderer = parentView.renderer;
<ide> props[HAS_BLOCK] = hasBlock;
<del> // parentView.controller represents any parent components
<del> // dynamicScope.controller represents the outlet controller
<del> props._targetObject = parentView.controller || dynamicScope.controller;
<add>
<add> // dynamicScope here is inherited from the parent dynamicScope,
<add> // but is set shortly below to the new target
<add> props._targetObject = dynamicScope.targetObject;
<ide>
<ide> let component = klass.create(props);
<ide>
<ide> dynamicScope.view = component;
<add> dynamicScope.targetObject = component;
<add>
<ide> parentView.appendChild(component);
<ide>
<ide> component.trigger('didInitAttrs', { attrs });
<ide><path>packages/ember-glimmer/lib/syntax/outlet.js
<ide> class OutletComponentManager extends AbstractOutletComponentManager {
<ide> create(definition, args, dynamicScope) {
<ide> let outletStateReference = dynamicScope.outletState = dynamicScope.outletState.get(definition.outletName);
<ide> let outletState = outletStateReference.value();
<del> dynamicScope.controller = outletState.render.controller;
<add> dynamicScope.targetObject = dynamicScope.controller = outletState.render.controller;
<ide> return outletState;
<ide> }
<ide> } | 3 |
Text | Text | add url to a missing link | 56021117899497d0e2098874c10e9ee2b6523ef4 | <ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who/index.md
<ide> Uses the operator `typeof` to check if the variable is a boolean. If it is, it w
<ide>
<ide> #### Relevant Links
<ide>
<del>* <a>Using typeof</a>
<ide> * <a href='https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof' target='_blank' rel='nofollow'>typeof</a>
<ide>
<ide> ##  NOTES FOR CONTRIBUTIONS: | 1 |
Javascript | Javascript | fix timing sensitivity in debugger test | 21b05cd6cd66afb86145bc0a22e571dd5842112e | <ide><path>test/parallel/test-debugger-util-regression.js
<ide> const path = require('path');
<ide> const spawn = require('child_process').spawn;
<ide> const assert = require('assert');
<ide>
<add>const DELAY = common.platformTimeout(200);
<add>
<ide> const fixture = path.join(
<ide> common.fixturesDir,
<ide> 'debugger-util-regression-fixture.js'
<ide> proc.stderr.setEncoding('utf8');
<ide>
<ide> let stdout = '';
<ide> let stderr = '';
<add>proc.stdout.on('data', (data) => stdout += data);
<add>proc.stderr.on('data', (data) => stderr += data);
<ide>
<ide> let nextCount = 0;
<ide> let exit = false;
<ide>
<del>proc.stdout.on('data', (data) => {
<del> stdout += data;
<add>// We look at output periodically. We don't do this in the on('data') as we
<add>// may end up processing partial output. Processing periodically ensures that
<add>// the debugger is in a stable state before we take the next step.
<add>const timer = setInterval(() => {
<ide> if (stdout.includes('> 1') && nextCount < 1 ||
<ide> stdout.includes('> 2') && nextCount < 2 ||
<ide> stdout.includes('> 3') && nextCount < 3 ||
<ide> proc.stdout.on('data', (data) => {
<ide> } else if (!exit && (stdout.includes('< { a: \'b\' }'))) {
<ide> exit = true;
<ide> proc.stdin.write('.exit\n');
<add> // We can cancel the timer and terminate normally.
<add> clearInterval(timer);
<ide> } else if (stdout.includes('program terminated')) {
<ide> // Catch edge case present in v4.x
<ide> // process will terminate after call to util.inspect
<ide> common.fail('the program should not terminate');
<ide> }
<del>});
<del>
<del>proc.stderr.on('data', (data) => stderr += data);
<add>}, DELAY);
<ide>
<ide> process.on('exit', (code) => {
<ide> assert.strictEqual(code, 0, 'the program should exit cleanly'); | 1 |
Text | Text | add link to code of conduct in contributing | 16630ecb5107b75dfa4cf1104f0bc8baee01413c | <ide><path>.github/CONTRIBUTING.md
<ide> Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
<ide> disclosure of security bugs. In those cases, please go through the process
<ide> outlined on that page and do not file a public issue.
<ide>
<add>## Code of Conduct
<add>
<add>Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please [read the full text](https://code.facebook.com/pages/876921332402685/open-source-code-of-conduct) so that you can understand what actions will and will not be tolerated.
<add>
<ide> # Pull Requests
<ide>
<ide> All active development of Immutable JS happens on GitHub. We actively welcome | 1 |
Mixed | Javascript | add hijackstdout and hijackstderr | d00e5f1a04fa4bcf15bbeb6c0f1f6de1e8f8afd4 | <ide><path>test/common/README.md
<ide> Checks whether `IPv6` is supported on this platform.
<ide>
<ide> Checks if there are multiple localhosts available.
<ide>
<add>### hijackStderr(listener)
<add>* `listener` [<Function>][MDN-Function]: a listener with a single parameter called `data`.
<add>
<add>Eavesdrop to `process.stderr.write` calls. Once `process.stderr.write` is
<add>called, `listener` will also be called and the `data` of `write` function will
<add>be passed to `listener`. What's more, `process.stderr.writeTimes` is a count of
<add>the number of calls.
<add>
<add>### hijackStdout(listener)
<add>* `listener` [<Function>][MDN-Function]: a listener with a single parameter called `data`.
<add>
<add>Eavesdrop to `process.stdout.write` calls. Once `process.stdout.write` is
<add>called, `listener` will also be called and the `data` of `write` function will
<add>be passed to `listener`. What's more, `process.stdout.writeTimes` is a count of
<add>the number of calls.
<add>
<ide> ### inFreeBSDJail
<ide> * return [<Boolean>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type)
<ide>
<ide> Port tests are running on.
<ide>
<ide> Deletes the 'tmp' dir and recreates it
<ide>
<add>### restoreStderr()
<add>
<add>Restore the original `process.stderr.write`.
<add>
<add>### restoreStdout()
<add>
<add>Restore the original `process.stdout.write`.
<add>
<ide> ### rootDir
<ide> * return [<String>](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type)
<ide>
<ide> Node.js
<ide> [WHATWG URL API](https://nodejs.org/api/url.html#url_the_whatwg_url_api)
<ide> implementation with tests from
<ide> [W3C Web Platform Tests](https://github.com/w3c/web-platform-tests).
<add>
<add>[MDN-Function]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Normal_objects_and_functions
<ide><path>test/common/index.js
<ide> exports.getTTYfd = function getTTYfd() {
<ide> }
<ide> return tty_fd;
<ide> };
<add>
<add>// Hijack stdout and stderr
<add>const stdWrite = {};
<add>function hijackStdWritable(name, listener) {
<add> const stream = process[name];
<add> const _write = stdWrite[name] = stream.write;
<add>
<add> stream.writeTimes = 0;
<add> stream.write = function(data, callback) {
<add> listener(data);
<add> _write.call(stream, data, callback);
<add> stream.writeTimes++;
<add> };
<add>}
<add>
<add>function restoreWritable(name) {
<add> process[name].write = stdWrite[name];
<add> delete process[name].writeTimes;
<add>}
<add>
<add>exports.hijackStdout = hijackStdWritable.bind(null, 'stdout');
<add>exports.hijackStderr = hijackStdWritable.bind(null, 'stderr');
<add>exports.restoreStdout = restoreWritable.bind(null, 'stdout');
<add>exports.restoreStderr = restoreWritable.bind(null, 'stderr');
<ide><path>test/fixtures/echo-close-check.js
<ide> const fs = require('fs');
<ide>
<ide> process.stdout.write('hello world\r\n');
<ide>
<del>var stdin = process.openStdin();
<add>const stdin = process.openStdin();
<ide>
<ide> stdin.on('data', function(data) {
<ide> process.stdout.write(data.toString());
<ide><path>test/parallel/test-common.js
<ide> for (const p of failFixtures) {
<ide> assert.strictEqual(firstLine, expected);
<ide> }));
<ide> }
<add>
<add>// hijackStderr and hijackStdout
<add>const HIJACK_TEST_ARRAY = [ 'foo\n', 'bar\n', 'baz\n' ];
<add>[ 'err', 'out' ].forEach((txt) => {
<add> const stream = process[`std${txt}`];
<add> const originalWrite = stream.write;
<add>
<add> common[`hijackStd${txt}`](common.mustCall(function(data) {
<add> assert.strictEqual(data, HIJACK_TEST_ARRAY[stream.writeTimes]);
<add> }, HIJACK_TEST_ARRAY.length));
<add> assert.notStrictEqual(originalWrite, stream.write);
<add>
<add> HIJACK_TEST_ARRAY.forEach((val) => {
<add> stream.write(val, common.mustCall(common.noop));
<add> });
<add>
<add> assert.strictEqual(HIJACK_TEST_ARRAY.length, stream.writeTimes);
<add> common[`restoreStd${txt}`]();
<add> assert.strictEqual(originalWrite, stream.write);
<add>});
<ide><path>test/parallel/test-console.js
<ide> assert.doesNotThrow(function() {
<ide> // an Object with a custom .inspect() function
<ide> const custom_inspect = { foo: 'bar', inspect: () => 'inspect' };
<ide>
<del>const stdout_write = global.process.stdout.write;
<del>const stderr_write = global.process.stderr.write;
<ide> const strings = [];
<ide> const errStrings = [];
<del>global.process.stdout.write = function(string) {
<del> strings.push(string);
<del>};
<del>global.process.stderr.write = function(string) {
<del> errStrings.push(string);
<del>};
<add>common.hijackStdout(function(data) {
<add> strings.push(data);
<add>});
<add>common.hijackStderr(function(data) {
<add> errStrings.push(data);
<add>});
<ide>
<ide> // test console.log() goes to stdout
<ide> console.log('foo');
<ide> console.timeEnd('constructor');
<ide> console.time('hasOwnProperty');
<ide> console.timeEnd('hasOwnProperty');
<ide>
<del>global.process.stdout.write = stdout_write;
<del>global.process.stderr.write = stderr_write;
<add>assert.strictEqual(strings.length, process.stdout.writeTimes);
<add>assert.strictEqual(errStrings.length, process.stderr.writeTimes);
<add>common.restoreStdout();
<add>common.restoreStderr();
<ide>
<ide> // verify that console.timeEnd() doesn't leave dead links
<ide> const timesMapSize = console._times.size;
<ide> assert.ok(/^hasOwnProperty: \d+\.\d{3}ms$/.test(strings.shift().trim()));
<ide> assert.strictEqual('Trace: This is a {"formatted":"trace"} 10 foo',
<ide> errStrings.shift().split('\n').shift());
<ide>
<del>assert.strictEqual(strings.length, 0);
<del>assert.strictEqual(errStrings.length, 0);
<del>
<ide> assert.throws(() => {
<ide> console.assert(false, 'should throw');
<ide> }, common.expectsError({
<ide> assert.throws(() => {
<ide> assert.doesNotThrow(() => {
<ide> console.assert(true, 'this should not throw');
<ide> });
<add>
<add>// hijack stderr to catch `process.emitWarning` which is using
<add>// `process.nextTick`
<add>common.hijackStderr(common.mustCall(function(data) {
<add> common.restoreStderr();
<add>
<add> // stderr.write will catch sync error, so use `process.nextTick` here
<add> process.nextTick(function() {
<add> assert.strictEqual(data.includes('no such label'), true);
<add> });
<add>}));
<ide><path>test/parallel/test-global-console-exists.js
<ide> const common = require('../common');
<ide> const assert = require('assert');
<ide> const EventEmitter = require('events');
<del>const leak_warning = /EventEmitter memory leak detected\. 2 hello listeners/;
<add>const leakWarning = /EventEmitter memory leak detected\. 2 hello listeners/;
<ide>
<del>let write_calls = 0;
<add>common.hijackStderr(common.mustCall(function(data) {
<add> if (process.stderr.writeTimes === 0) {
<add> assert.ok(data.match(leakWarning));
<add> } else {
<add> assert.fail('stderr.write should be called only once');
<add> }
<add>}));
<ide>
<del>process.on('warning', (warning) => {
<add>process.on('warning', function(warning) {
<ide> // This will be called after the default internal
<ide> // process warning handler is called. The default
<ide> // process warning writes to the console, which will
<ide> // invoke the monkeypatched process.stderr.write
<ide> // below.
<del> assert.strictEqual(write_calls, 1);
<del> EventEmitter.defaultMaxListeners = old_default;
<add> assert.strictEqual(process.stderr.writeTimes, 1);
<add> EventEmitter.defaultMaxListeners = oldDefault;
<ide> // when we get here, we should be done
<ide> });
<ide>
<del>process.stderr.write = (data) => {
<del> if (write_calls === 0)
<del> assert.ok(data.match(leak_warning));
<del> else
<del> assert.fail('stderr.write should be called only once');
<del>
<del> write_calls++;
<del>};
<del>
<del>const old_default = EventEmitter.defaultMaxListeners;
<add>const oldDefault = EventEmitter.defaultMaxListeners;
<ide> EventEmitter.defaultMaxListeners = 1;
<ide>
<ide> const e = new EventEmitter();
<ide><path>test/parallel/test-process-raw-debug.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const os = require('os');
<ide>
<ide> function child() {
<ide> throw new Error('No ticking!');
<ide> };
<ide>
<del> const stderr = process.stderr;
<del> stderr.write = function() {
<del> throw new Error('No writing to stderr!');
<del> };
<add> common.hijackStderr(common.mustNotCall('stderr.write must not be called.'));
<ide>
<ide> process._rawDebug('I can still %s!', 'debug');
<ide> }
<ide><path>test/parallel/test-util-log.js
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<ide> 'use strict';
<del>require('../common');
<add>const common = require('../common');
<ide> const assert = require('assert');
<ide> const util = require('util');
<ide>
<ide> assert.ok(process.stdout.writable);
<ide> assert.ok(process.stderr.writable);
<ide>
<del>const stdout_write = global.process.stdout.write;
<ide> const strings = [];
<del>global.process.stdout.write = function(string) {
<del> strings.push(string);
<del>};
<del>console._stderr = process.stdout;
<add>common.hijackStdout(function(data) {
<add> strings.push(data);
<add>});
<add>common.hijackStderr(common.mustNotCall('stderr.write must not be called'));
<ide>
<ide> const tests = [
<ide> {input: 'foo', output: 'foo'},
<ide> tests.forEach(function(test) {
<ide> assert.strictEqual(match[1], test.output);
<ide> });
<ide>
<del>global.process.stdout.write = stdout_write;
<add>assert.strictEqual(process.stdout.writeTimes, tests.length);
<add>
<add>common.restoreStdout(); | 8 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.