content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
PHP | PHP | move boolean value handling logic into radiowidget | 0a0bff0e11ca7a26065829a826e3624d1330691a | <ide><path>src/View/Widget/Radio.php
<ide> public function __construct($templates, $label) {
<ide> * - `val` - A string of the option to mark as selected.
<ide> * - `label` - Either false to disable label generation, or
<ide> * an array of attributes for all labels.
<add> * - `required` - Set to true to add the required attribute
<add> * on all generated radios.
<ide> *
<ide> * @param array $data The data to build radio buttons with.
<ide> * @return string
<ide> protected function _renderInput($val, $text, $data) {
<ide> $radio['id'] = $this->_id($radio);
<ide> }
<ide>
<add> if (isset($data['val']) && is_bool($data['val'])) {
<add> $data['val'] = $data['val'] ? 1 : 0;
<add> }
<add>
<ide> if (isset($data['val']) && strval($data['val']) === strval($radio['value'])) {
<ide> $radio['checked'] = true;
<ide> }
<ide>
<ide> if ($this->_isDisabled($radio, $data['disabled'])) {
<ide> $radio['disabled'] = true;
<ide> }
<add> if (!empty($data['required'])) {
<add> $radio['required'] = true;
<add> }
<ide>
<ide> $input = $this->_templates->format('radio', [
<ide> 'name' => $radio['name'],
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php
<ide> public function testRadio() {
<ide>
<ide> $result = $this->Form->radio('Model.field', array('option A', 'option B'), array('name' => 'Model[custom]'));
<ide> $expected = array(
<del> 'input' => array('type' => 'hidden', 'name' => 'Model[custom]', 'value' => ''),
<del> array('input' => array('type' => 'radio', 'name' => 'Model[custom]', 'value' => '0', 'id' => 'model-field-0')),
<del> array('label' => array('for' => 'model-field-0')),
<add> array('input' => array('type' => 'hidden', 'name' => 'Model[custom]', 'value' => '')),
<add> array('input' => array('type' => 'radio', 'name' => 'Model[custom]', 'value' => '0', 'id' => 'model-custom-0')),
<add> array('label' => array('for' => 'model-custom-0')),
<ide> 'option A',
<ide> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'Model[custom]', 'value' => '1', 'id' => 'model-field-1')),
<del> array('label' => array('for' => 'model-field-1')),
<add> array('input' => array('type' => 'radio', 'name' => 'Model[custom]', 'value' => '1', 'id' => 'model-custom-1')),
<add> array('label' => array('for' => 'model-custom-1')),
<ide> 'option B',
<ide> '/label',
<ide> );
<ide> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio(
<del> 'Model.field',
<del> array('a>b' => 'first', 'a<b' => 'second', 'a"b' => 'third')
<del> );
<del> $expected = array(
<del> 'input' => array(
<del> 'type' => 'hidden', 'name' => 'data[Model][field]',
<del> 'value' => '',
<del> ),
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]',
<del> 'id' => 'model-field-a-b', 'value' => 'a>b')),
<del> array('label' => array('for' => 'model-field-a-b')),
<del> 'first',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]',
<del> 'id' => 'ModelFieldAB1', 'value' => 'a<b')),
<del> array('label' => array('for' => 'model-field-ab2')),
<del> 'second',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'data[Model][field]',
<del> 'id' => 'model-field-ab2', 'value' => 'a"b')),
<del> array('label' => array('for' => 'model-field-ab2')),
<del> 'third',
<del> '/label',
<del> );
<del> $this->assertTags($result, $expected);
<del> }
<del>
<del>/**
<del> * Test marking radio buttons as required.
<del> *
<del> * @return void
<del> */
<del> public function testRadioRequired() {
<del> $this->article['required'] = [
<del> 'published' => true,
<del> ];
<del> $this->Form->create($this->article);
<del>
<del> $result = $this->Form->radio('published', array('option A', 'optionB'));
<del> $expected = array(
<del> 'input' => array('type' => 'hidden', 'name' => 'published', 'value' => ''),
<del> array('input' => array('type' => 'radio', 'name' => 'published', 'value' => '0', 'id' => 'published-0', 'required' => 'required')),
<del> 'label' => array('for' => 'published-0'),
<del> 'option A',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'published', 'value' => '1', 'id' => 'published-1', 'required' => 'required')),
<del> 'label' => array('for' => 'published-1'),
<del> 'option B',
<del> '/label',
<del> );
<del> $this->assertTags($result, $expected);
<del> }
<del>
<del>/**
<del> * Test that radios with a 0 value are selected under the correct conditions.
<del> * Also ensure that values that are booleanish are handled correctly.
<del> *
<del> * @return void
<del> */
<del> public function testRadioOptionWithBooleanishValues() {
<del> $expected = array(
<del> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'model-field-1')),
<del> array('label' => array('for' => 'model-field-1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'model-field-0', 'checked' => 'checked')),
<del> array('label' => array('for' => 'model-field-0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => '0'));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => 0));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => false));
<del> $this->assertTags($result, $expected);
<del>
<del> $expected = array(
<del> 'input' => array('type' => 'hidden', 'name' => 'Model[field]', 'value' => ''),
<del> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'model-field-1')),
<del> array('label' => array('for' => 'model-field-1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'model-field-0')),
<del> array('label' => array('for' => 'ModelField0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => null));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => ''));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'));
<del> $this->assertTags($result, $expected);
<del>
<del> $expected = array(
<del> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'checked' => 'checked', 'value' => '1', 'id' => 'model-field-1')),
<del> array('label' => array('for' => 'model-field-1')),
<del> 'Yes',
<del> '/label',
<del> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'model-field-0')),
<del> array('label' => array('for' => 'model-field-0')),
<del> 'No',
<del> '/label',
<del> '/fieldset'
<del> );
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => 1));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => '1'));
<del> $this->assertTags($result, $expected);
<del>
<del> $result = $this->Form->radio('Model.field', array('1' => 'Yes', '0' => 'No'), array('value' => true));
<del> $this->assertTags($result, $expected);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/View/Widget/RadioTest.php
<ide> public function testRenderIdSuffixGeneration() {
<ide> 'type' => 'radio',
<ide> 'name' => 'Thing[value]',
<ide> 'value' => 'a<b',
<del> 'id' => 'thing-value-a-b2',
<add> 'id' => 'thing-value-a-b1',
<ide> ]],
<del> ['label' => ['for' => 'thing-value-a-b2']],
<add> ['label' => ['for' => 'thing-value-a-b1']],
<ide> 'Second',
<ide> '/label',
<ide> ];
<ide> $this->assertTags($result, $expected);
<ide> }
<ide>
<add>/**
<add> * Test rendering checks the right option with booleanish values.
<add> *
<add> * @return void
<add> */
<add> public function testRenderBooleanishValues() {
<add> $label = new Label($this->templates);
<add> $radio = new Radio($this->templates, $label);
<add> $data = [
<add> 'name' => 'Model[field]',
<add> 'options' => ['1' => 'Yes', '0' => 'No'],
<add> 'val' => '0'
<add> ];
<add> $result = $radio->render($data);
<add> $expected = array(
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'model-field-1')),
<add> array('label' => array('for' => 'model-field-1')),
<add> 'Yes',
<add> '/label',
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'model-field-0', 'checked' => 'checked')),
<add> array('label' => array('for' => 'model-field-0')),
<add> 'No',
<add> '/label',
<add> );
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = 0;
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = false;
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $expected = array(
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'model-field-1')),
<add> array('label' => array('for' => 'model-field-1')),
<add> 'Yes',
<add> '/label',
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'model-field-0')),
<add> array('label' => array('for' => 'model-field-0')),
<add> 'No',
<add> '/label',
<add> );
<add> $data['val'] = null;
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = '';
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $expected = array(
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '1', 'id' => 'model-field-1', 'checked' => 'checked')),
<add> array('label' => array('for' => 'model-field-1')),
<add> 'Yes',
<add> '/label',
<add> array('input' => array('type' => 'radio', 'name' => 'Model[field]', 'value' => '0', 'id' => 'model-field-0')),
<add> array('label' => array('for' => 'model-field-0')),
<add> 'No',
<add> '/label',
<add> );
<add> $data['val'] = '1';
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = 1;
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add>
<add> $data['val'] = true;
<add> $result = $radio->render($data);
<add> $this->assertTags($result, $expected);
<add> }
<add>
<add>/**
<add> * Test that render() works with the required attribute.
<add> *
<add> * @return void
<add> */
<add> public function testRenderRequired() {
<add> $label = new Label($this->templates);
<add> $radio = new Radio($this->templates, $label);
<add> $data = [
<add> 'name' => 'published',
<add> 'options' => ['option A', 'option B'],
<add> 'required' => true
<add> ];
<add> $result = $radio->render($data);
<add> $expected = [
<add> ['input' => ['type' => 'radio', 'name' => 'published', 'value' => '0', 'id' => 'published-0', 'required' => 'required']],
<add> ['label' => ['for' => 'published-0']],
<add> 'option A',
<add> '/label',
<add> ['input' => ['type' => 'radio', 'name' => 'published', 'value' => '1', 'id' => 'published-1', 'required' => 'required']],
<add> ['label' => ['for' => 'published-1']],
<add> 'option B',
<add> '/label',
<add> ];
<add> $this->assertTags($result, $expected);
<add> }
<add>
<ide> /**
<ide> * Test rendering the empty option.
<ide> * | 3 |
Text | Text | update example render for react v18 | e912da964dbf5f84bf8c4e78e0ac218362bc074e | <ide><path>README.md
<ide> You can improve it by sending pull requests to [this repository](https://github.
<ide> We have several examples [on the website](https://reactjs.org/). Here is the first one to get you started:
<ide>
<ide> ```jsx
<add>import { createRoot } from 'react-dom/client';
<add>
<ide> function HelloMessage({ name }) {
<ide> return <div>Hello {name}</div>;
<ide> }
<ide>
<del>ReactDOM.render(
<del> <HelloMessage name="Taylor" />,
<del> document.getElementById('container')
<del>);
<add>const root = createRoot(document.getElementById('container'));
<add>root.render(<HelloMessage name="Taylor" />);
<ide> ```
<ide>
<ide> This example will render "Hello Taylor" into a container on the page. | 1 |
Javascript | Javascript | use collision detection for dorling cartogram | bb5d7873a772c63f33e899f14be64df51428e2fd | <ide><path>examples/cartogram/dorling.js
<ide> var data = [
<ide> ];
<ide>
<ide> var force = d3.layout.force()
<del> .gravity(.015)
<add> .gravity(0)
<add> .charge(0)
<ide> .distance(function(l) {
<ide> return l.length;
<ide> })
<ide> .size([960, 500]);
<ide>
<del>var svg = d3.select("#chart")
<del> .append("svg:svg");
<add>var svg = d3.select("#chart").append("svg:svg");
<ide>
<del>d3.json("../data/us-borders.json", function(borders) {
<del> d3.json("../data/us-state-centroids.json", function(states) {
<del> var project = d3.geo.albersUsa(),
<del> idToNode = {},
<del> links = [],
<del> nodes = states.features.map(function(d) {
<del> var xy = project(d.geometry.coordinates);
<del> return idToNode[d.id] = {x: xy[0], y: xy[1], r: Math.sqrt(data[+d.id] * 5000)};
<del> });
<add>d3.json("../data/us-state-centroids.json", function(states) {
<add> var project = d3.geo.albersUsa(),
<add> idToNode = {},
<add> links = [],
<add> nodes = states.features.map(function(d) {
<add> var xy = project(d.geometry.coordinates);
<add> return idToNode[d.id] = {x: xy[0], y: xy[1], r: Math.sqrt(data[+d.id] * 5000)};
<add> });
<ide>
<del> states.features.forEach(function(d) {
<del> var stateBorders = borders[d.id];
<del> if (!stateBorders) return;
<del> stateBorders.forEach(function(b) {
<del> if (idToNode[d.id] && idToNode[b] && d.id < b) {
<del> var nodeA = idToNode[d.id],
<del> nodeB = idToNode[b],
<del> dx = nodeA.x - nodeB.x,
<del> dy = nodeA.y - nodeB.y,
<del> dist = Math.sqrt(dx * dx + dy * dy);
<del> links.push({source: nodeA, target: nodeB, length: dist});
<add> force
<add> .nodes(nodes)
<add> .links(links)
<add> .start()
<add> .on("tick", function(e) {
<add> var k = .1 * e.alpha;
<add> nodes.forEach(function(a, i) {
<add> nodes.forEach(function(b, i) {
<add> // Check for collision
<add> var dx = a.x - b.x,
<add> dy = a.y - b.y,
<add> dr = a.r + b.r;
<add> if (dx * dx + dy * dy < dr * dr) {
<add> a.x += dx * k;
<add> a.y += dy * k;
<ide> }
<ide> });
<ide> });
<ide>
<del> force
<del> .nodes(nodes)
<del> .links(links)
<del> .start();
<del>
<ide> svg.selectAll("circle")
<del> .data(nodes)
<del> .enter().append("svg:circle")
<ide> .attr("cx", function(d) { return d.x; })
<del> .attr("cy", function(d) { return d.y; })
<del> .attr("r", function(d, i) { return d.r; });
<add> .attr("cy", function(d) { return d.y; });
<ide> });
<del>});
<ide>
<del>force.on("tick", function(e) {
<ide> svg.selectAll("circle")
<add> .data(nodes)
<add> .enter().append("svg:circle")
<ide> .attr("cx", function(d) { return d.x; })
<del> .attr("cy", function(d) { return d.y; });
<add> .attr("cy", function(d) { return d.y; })
<add> .attr("r", function(d, i) { return d.r; });
<ide> }); | 1 |
Ruby | Ruby | remove consts if loading failed | 90e9d177894f76b5f5081d3be2a92245b2aafeda | <ide><path>Library/Homebrew/formulary.rb
<ide> def self.load_formula(name, path, contents, namespace, flags:)
<ide> mod.const_set(:BUILD_FLAGS, flags)
<ide> mod.module_eval(contents, path)
<ide> rescue NameError, ArgumentError, ScriptError, MethodDeprecatedError => e
<add> remove_const(namespace)
<ide> raise FormulaUnreadableError.new(name, e)
<ide> end
<ide> class_name = class_s(name)
<ide> def self.load_formula(name, path, contents, namespace, flags:)
<ide> .map { |const_name| mod.const_get(const_name) }
<ide> .select { |const| const.is_a?(Class) }
<ide> new_exception = FormulaClassUnavailableError.new(name, path, class_name, class_list)
<add> remove_const(namespace)
<ide> raise new_exception, "", e.backtrace
<ide> end
<ide> end | 1 |
Python | Python | introduce weighting of labels | 11e961fdf848808bb63489bd698908d80119910e | <ide><path>keras/models.py
<ide> def standardize_y(y):
<ide> if not hasattr(y, 'shape'):
<ide> y = np.asarray(y)
<ide> if len(y.shape) == 1:
<del> y = np.reshape(y, (len(y), 1))
<add> y = np.expand_dims(y, 1)
<ide> return y
<ide>
<ide> def make_batches(size, batch_size):
<ide> def slice_X(X, start=None, stop=None):
<ide> else:
<ide> return X[start:stop]
<ide>
<del>def calculate_loss_weights(Y, sample_weight=None, class_weight=None):
<del> if sample_weight is not None:
<del> if isinstance(sample_weight, list):
<del> w = np.array(sample_weight)
<del> else:
<del> w = sample_weight
<del> elif isinstance(class_weight, dict):
<del> if Y.shape[1] > 1:
<del> y_classes = Y.argmax(axis=1)
<del> elif Y.shape[1] == 1:
<del> y_classes = np.reshape(Y, Y.shape[0])
<del> else:
<del> y_classes = Y
<del> w = np.array(list(map(lambda x: class_weight[x], y_classes)))
<del> else:
<del> w = np.ones((Y.shape[0]))
<del> return w
<del>
<ide> class Model(object):
<ide>
<ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None):
<ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None):
<ide> # target of model
<ide> self.y = T.zeros_like(self.y_train)
<ide>
<del> train_loss = self.loss(self.y, self.y_train)
<del> test_score = self.loss(self.y, self.y_test)
<add> self.weights = T.ones_like(self.y_train)
<ide>
<add> train_loss = self.loss(self.y, self.y_train, self.weights)
<add> test_score = self.loss(self.y, self.y_test, self.weights)
<add>
<add>
<ide> if class_mode == "categorical":
<ide> train_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_train, axis=-1)))
<ide> test_accuracy = T.mean(T.eq(T.argmax(self.y, axis=-1), T.argmax(self.y_test, axis=-1)))
<ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None):
<ide> updates = self.optimizer.get_updates(self.params, self.regularizers, self.constraints, train_loss)
<ide>
<ide> if type(self.X_train) == list:
<del> train_ins = self.X_train + [self.y]
<del> test_ins = self.X_test + [self.y]
<add> train_ins = self.X_train + [self.y, self.weights]
<add> test_ins = self.X_test + [self.y, self.weights]
<ide> predict_ins = self.X_test
<ide> else:
<del> train_ins = [self.X_train, self.y]
<del> test_ins = [self.X_test, self.y]
<add> train_ins = [self.X_train, self.y, self.weights]
<add> test_ins = [self.X_test, self.y, self.weights]
<ide> predict_ins = [self.X_test]
<ide>
<ide> self._train = theano.function(train_ins, train_loss,
<ide> def compile(self, optimizer, loss, class_mode="categorical", theano_mode=None):
<ide> allow_input_downcast=True, mode=theano_mode)
<ide>
<ide>
<del> def train(self, X, y, accuracy=False):
<add> def train(self, X, y, accuracy=False, weights=None):
<ide> X = standardize_X(X)
<ide> y = standardize_y(y)
<ide>
<del> ins = X + [y]
<add> if weights is None:
<add> weights = np.ones(list(y.shape[0:-1]) + [1])
<add> else:
<add> weights = standardize_y(weights)
<add>
<add> ins = X + [y, weights]
<ide> if accuracy:
<ide> return self._train_with_acc(*ins)
<ide> else:
<ide> def test(self, X, y, accuracy=False):
<ide>
<ide>
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<del> validation_split=0., validation_data=None, shuffle=True, show_accuracy=False):
<add> validation_split=0., validation_data=None, shuffle=True, show_accuracy=False, weights=None):
<ide>
<ide> X = standardize_X(X)
<ide> y = standardize_y(y)
<add> if weights is not None:
<add> weights = standardize_y(weights)
<ide>
<ide> do_validation = False
<ide> if validation_data:
<add> weight_val = None
<ide> try:
<ide> X_val, y_val = validation_data
<ide> except:
<del> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val). \
<del> X_val may be a numpy array or a list of numpy arrays depending on your model input.")
<add> try:
<add> X_val, y_val, weight_val = validation_data
<add> except:
<add> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val, [weight_val]). \
<add> X_val may be a numpy array or a list of numpy arrays depending on your model input.")
<ide> do_validation = True
<ide> X_val = standardize_X(X_val)
<ide> y_val = standardize_y(y_val)
<add> if weight_val is not None:
<add> weight_val = standardize_y(weight_val)
<add>
<ide> if verbose:
<ide> print("Train on %d samples, validate on %d samples" % (len(y), len(y_val)))
<ide> else:
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> do_validation = True
<ide> split_at = int(len(y) * (1 - validation_split))
<ide> (X, X_val) = (slice_X(X, 0, split_at), slice_X(X, split_at))
<del> (y, y_val) = (y[0:split_at], y[split_at:])
<add> (y, y_val) = (y[:split_at], y[split_at:])
<add> if weights is not None:
<add> (weights, weight_val) = (weights[:split_at], weights[split_at:])
<add>
<ide> if verbose:
<ide> print("Train on %d samples, validate on %d samples" % (len(y), len(y_val)))
<ide>
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> batch_ids = index_array[batch_start:batch_end]
<ide> X_batch = slice_X(X, batch_ids)
<ide> y_batch = y[batch_ids]
<add> if weights is not None:
<add> weight_batch = weights[batch_ids]
<add> else:
<add> weight_batch = np.ones(list(y_batch.shape[:-1]) + [1])
<ide>
<ide> batch_logs = {}
<ide> batch_logs['batch'] = batch_index
<ide> batch_logs['size'] = len(batch_ids)
<ide> callbacks.on_batch_begin(batch_index, batch_logs)
<ide>
<del> ins = X_batch + [y_batch]
<add> ins = X_batch + [y_batch, weight_batch]
<ide> if show_accuracy:
<ide> loss, acc = self._train_with_acc(*ins)
<ide> batch_logs['accuracy'] = acc
<ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[],
<ide> epoch_logs = {}
<ide> if do_validation:
<ide> if show_accuracy:
<del> val_loss, val_acc = self.evaluate(X_val, y_val, batch_size=batch_size, \
<add> val_loss, val_acc = self.evaluate(X_val, y_val, weights=weight_val, batch_size=batch_size, \
<ide> verbose=0, show_accuracy=True)
<ide> epoch_logs['val_accuracy'] = val_acc
<ide> else:
<del> val_loss = self.evaluate(X_val, y_val, batch_size=batch_size, verbose=0)
<add> val_loss = self.evaluate(X_val, y_val, weights=weight_val, batch_size=batch_size, verbose=0)
<ide> epoch_logs['val_loss'] = val_loss
<ide>
<ide> callbacks.on_epoch_end(epoch, epoch_logs)
<ide> def predict_classes(self, X, batch_size=128, verbose=1):
<ide> return (proba > 0.5).astype('int32')
<ide>
<ide>
<del> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<add> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1, weights=None):
<ide> X = standardize_X(X)
<ide> y = standardize_y(y)
<ide>
<add> if weights is not None:
<add> weights = standardize_y(weights)
<add>
<ide> if show_accuracy:
<ide> tot_acc = 0.
<ide> tot_score = 0.
<ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, verbose=1):
<ide> for batch_index, (batch_start, batch_end) in enumerate(batches):
<ide> X_batch = slice_X(X, batch_start, batch_end)
<ide> y_batch = y[batch_start:batch_end]
<add> if weights is None:
<add> weight_batch = np.ones(list(y_batch.shape[:-1]) + [1])
<add> else:
<add> weight_batch = weights[batch_start:batch_end]
<add>
<ide>
<del> ins = X_batch + [y_batch]
<add> ins = X_batch + [y_batch, weight_batch]
<ide> if show_accuracy:
<ide> loss, acc = self._test_with_acc(*ins)
<ide> tot_acc += acc * len(y_batch)
<ide> def load_weights(self, filepath):
<ide> g = f['layer_{}'.format(k)]
<ide> weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])]
<ide> self.layers[k].set_weights(weights)
<del> f.close()
<ide>\ No newline at end of file
<add> f.close()
<ide><path>keras/objectives.py
<ide> epsilon = 1.0e-9
<ide>
<ide> def mean_squared_error(y_true, y_pred):
<del> return T.sqr(y_pred - y_true).mean()
<add> return T.sqr(y_pred - y_true).mean(axis=-1)
<ide>
<ide> def mean_absolute_error(y_true, y_pred):
<del> return T.abs_(y_pred - y_true).mean()
<add> return T.abs_(y_pred - y_true).mean(axis=-1)
<ide>
<ide> def squared_hinge(y_true, y_pred):
<del> return T.sqr(T.maximum(1. - y_true * y_pred, 0.)).mean()
<add> return T.sqr(T.maximum(1. - y_true * y_pred, 0.)).mean(axis=-1)
<ide>
<ide> def hinge(y_true, y_pred):
<del> return T.maximum(1. - y_true * y_pred, 0.).mean()
<add> return T.maximum(1. - y_true * y_pred, 0.).mean(axis=-1)
<ide>
<ide> def categorical_crossentropy(y_true, y_pred):
<ide> '''Expects a binary class matrix instead of a vector of scalar classes
<ide> '''
<ide> y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
<ide> # scale preds so that the class probas of each sample sum to 1
<del> y_pred /= y_pred.sum(axis=1, keepdims=True)
<add> y_pred /= y_pred.sum(axis=-1, keepdims=True)
<ide> cce = T.nnet.categorical_crossentropy(y_pred, y_true)
<del> return cce.mean()
<add> return cce
<ide>
<ide> def binary_crossentropy(y_true, y_pred):
<ide> y_pred = T.clip(y_pred, epsilon, 1.0 - epsilon)
<ide> bce = T.nnet.binary_crossentropy(y_pred, y_true)
<del> return bce.mean()
<add> return bce
<ide>
<ide> # aliases
<ide> mse = MSE = mean_squared_error
<ide> mae = MAE = mean_absolute_error
<ide>
<ide> from .utils.generic_utils import get_from_module
<ide> def get(identifier):
<del> return get_from_module(identifier, globals(), 'objective')
<ide>\ No newline at end of file
<add> obj_fn = get_from_module(identifier, globals(), 'objective')
<add> def weighted_obj_fun(y_true, y_pred, weights):
<add> # it's important that 0 * Inf == 0, not NaN, so I need to mask first
<add> masked_y_true = y_true[weights.nonzero()[:-1]]
<add> masked_y_pred = y_pred[weights.nonzero()[:-1]]
<add> masked_weights = weights[weights.nonzero()]
<add> return (masked_weights * obj_fn(masked_y_true, masked_y_pred)).mean()
<add> return weighted_obj_fun
<ide><path>tests/manual/check_masked_recurrent.py
<ide> model2.add(Activation('tanh'))
<ide> model2.add(GRU(4,4, activation='softmax', return_sequences=True))
<ide> model2.add(SimpleDeepRNN(4,4, depth=2, activation='relu', return_sequences=True))
<del>model2.add(SimpleRNN(4,4, activation='relu', return_sequences=False))
<add>model2.add(SimpleRNN(4,4, activation='relu', return_sequences=True))
<ide> model2.compile(loss='categorical_crossentropy',
<del> optimizer='rmsprop', theano_mode=theano.compile.mode.FAST_COMPILE)
<add> optimizer='rmsprop', theano_mode=theano.compile.mode.FAST_RUN)
<ide> print("Compiled model2")
<ide>
<ide> X2 = np.random.random_integers(1, 4, size=(2,5))
<add>y2 = np.random.random((X2.shape[0],X2.shape[1],4))
<add>
<ide> ref = model2.predict(X2)
<add>ref_eval = model2.evaluate(X2, y2)
<add>mask = np.ones((y2.shape[0], y2.shape[1], 1))
<add>
<ide> for pre_zeros in range(1,10):
<del> padded = np.concatenate((np.zeros((2, pre_zeros)), X2), axis=1)
<del> pred = model2.predict(padded)
<del> if not np.allclose(ref, pred):
<add> padded_X2 = np.concatenate((np.zeros((X2.shape[0], pre_zeros)), X2), axis=1)
<add> padded_mask = np.concatenate((np.zeros((mask.shape[0], pre_zeros, mask.shape[2])), mask), axis=1)
<add> padded_y2 = np.concatenate((np.zeros((y2.shape[0], pre_zeros, y2.shape[2])), y2), axis=1)
<add>
<add> pred = model2.predict(padded_X2)
<add> if not np.allclose(ref[:,-1,:], pred[:,-1,:]):
<ide> raise Exception("Different result after left-padding %d zeros. Ref: %s, Pred: %s" % (pre_zeros, ref, pred))
<add>
<add> pad_eval = model2.evaluate(padded_X2, padded_y2, weights=padded_mask)
<add> if not np.allclose([pad_eval], [ref_eval]):
<add> raise Exception("Got dissimilar categorical_crossentropy after left-padding %d zeros. Ref: %f, Pred %f" %\
<add> (pref_eval, pred_val))
<add>
<ide> | 3 |
Python | Python | add another randomness into the password generator | 4b43a2f50740bbeab95f64137eb8993ed8ac4617 | <ide><path>other/password_generator.py
<ide> import string
<del>from random import *
<add>import random
<ide>
<del>letters = string.ascii_letters
<del>digits = string.digits
<del>symbols = string.punctuation
<add>letters = [letter for letter in string.ascii_letters]
<add>digits = [digit for digit in string.digits]
<add>symbols = [symbol for symbol in string.punctuation]
<ide> chars = letters + digits + symbols
<add>random.shuffle(chars)
<ide>
<ide> min_length = 8
<ide> max_length = 16
<del>password = ''.join(choice(chars) for x in range(randint(min_length, max_length)))
<del>print('Password: %s' % password)
<add>password = ''.join(random.choice(chars) for x in range(random.randint(min_length, max_length)))
<add>print('Password: ' + password)
<ide> print('[ If you are thinking of using this passsword, You better save it. ]') | 1 |
PHP | PHP | hastable | 0a26661949db13fb3f3c878177f77d8d3a8fa987 | <ide><path>src/Illuminate/Database/PostgresConnection.php
<ide>
<ide> namespace Illuminate\Database;
<ide>
<add>use Illuminate\Database\Schema\PostgresBuilder;
<ide> use Doctrine\DBAL\Driver\PDOPgSql\Driver as DoctrineDriver;
<ide> use Illuminate\Database\Query\Processors\PostgresProcessor;
<ide> use Illuminate\Database\Query\Grammars\PostgresGrammar as QueryGrammar;
<ide> use Illuminate\Database\Schema\Grammars\PostgresGrammar as SchemaGrammar;
<ide>
<ide> class PostgresConnection extends Connection
<ide> {
<add> /**
<add> * Get a schema builder instance for the connection.
<add> *
<add> * @return \Illuminate\Database\Schema\PostgresBuilder
<add> */
<add> public function getSchemaBuilder()
<add> {
<add> if (is_null($this->schemaGrammar)) {
<add> $this->useDefaultSchemaGrammar();
<add> }
<add>
<add> return new PostgresBuilder($this);
<add> }
<add>
<ide> /**
<ide> * Get the default query grammar instance.
<ide> *
<ide><path>src/Illuminate/Database/Schema/Grammars/PostgresGrammar.php
<ide> class PostgresGrammar extends Grammar
<ide> */
<ide> public function compileTableExists()
<ide> {
<del> return 'select * from information_schema.tables where table_name = ?';
<add> return 'select * from information_schema.tables where table_schema = ? and table_name = ?';
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Schema/PostgresBuilder.php
<add><?php
<add>
<add>namespace Illuminate\Database\Schema;
<add>
<add>class PostgresBuilder extends Builder
<add>{
<add> /**
<add> * Determine if the given table exists.
<add> *
<add> * @param string $table
<add> * @return bool
<add> */
<add> public function hasTable($table)
<add> {
<add> $sql = $this->grammar->compileTableExists();
<add>
<add> $schema = $this->connection->getConfig('schema');
<add>
<add> $table = $this->connection->getTablePrefix().$table;
<add>
<add> return count($this->connection->select($sql, [$schema, $table])) > 0;
<add> }
<add>} | 3 |
Javascript | Javascript | remove license header from third-party code | 5fae86fb962e024582f24502bb39c4a87ada4430 | <ide><path>flow-typed/npm/base64-js_v1.x.x.js
<ide> /**
<del> * (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
<del> *
<ide> * @flow strict
<ide> * @format
<ide> */
<ide><path>flow-typed/npm/pretty-format_v26.x.x.js
<ide> /**
<del> * (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
<del> *
<ide> * @flow strict
<ide> * @format
<ide> */
<ide><path>flow-typed/npm/promise_v8.x.x.js
<ide> /**
<del> * (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
<del> *
<ide> * @flow strict
<ide> * @format
<ide> */
<ide><path>flow-typed/npm/prop-types_v15.x.x.js
<ide> /**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<ide> * @flow strict
<ide> * @nolint
<ide> * @format
<ide><path>flow-typed/npm/react-dom_v16.x.x.js
<ide> /**
<del> * Copyright (c) 2013-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<ide> * react-dom v16.x.x libdefs from flow-typed
<ide> *
<ide> * @noformat
<ide><path>flow-typed/npm/stacktrace-parser_v0.1.x.js
<ide> /**
<del> * (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
<del> *
<ide> * @flow strict
<ide> * @format
<ide> */ | 6 |
PHP | PHP | remove some spacial overkill | ec619eec04397df8ad2b780baaa46cabbfad548a | <ide><path>lib/Cake/Console/Command/Task/DbConfigTask.php
<ide> protected function _verify($config) {
<ide> $this->out(__d('cake_console', 'The following database configuration will be created:'));
<ide> $this->hr();
<ide> $this->out(__d('cake_console', "Name: %s", $name));
<del> $this->out(__d('cake_console', "Datasource: %s", $datasource));
<add> $this->out(__d('cake_console', "Datasource: %s", $datasource));
<ide> $this->out(__d('cake_console', "Persistent: %s", $persistent));
<ide> $this->out(__d('cake_console', "Host: %s", $host));
<ide> | 1 |
Javascript | Javascript | remove donation message for unauthorized users | 99a30d4b6552eda134892e2311d19faeb13c5cd9 | <ide><path>client/src/client-only-routes/ShowCertification.js
<ide> class ShowCertification extends Component {
<ide> if (
<ide> !isDonationDisplayed &&
<ide> userComplete &&
<add> signedInUserName &&
<ide> signedInUserName === username &&
<ide> !isDonating
<ide> ) { | 1 |
Go | Go | fix cleanup for tests | 4508bd94b0efd07a0ef48cd090786615e6b8cbb7 | <ide><path>pkg/symlink/fs_test.go
<ide> func TestFollowSymLinkUnderLinkedDir(t *testing.T) {
<ide> if err != nil {
<ide> t.Fatal(err)
<ide> }
<add> defer os.RemoveAll(dir)
<ide>
<ide> os.Mkdir(filepath.Join(dir, "realdir"), 0700)
<ide> os.Symlink("realdir", filepath.Join(dir, "linkdir")) | 1 |
Javascript | Javascript | fix indentation of inline snapshots in tests | ee01be3462a142fd8d75efee5b1855111817f9ab | <ide><path>Libraries/Lists/__tests__/VirtualizedList-test.js
<ide> describe('VirtualizedList', () => {
<ide> Array [
<ide> Array [
<ide> "A VirtualizedList contains a cell which itself contains more than one VirtualizedList of the same orientation as the parent list. You must pass a unique listKey prop to each sibling list.
<del>
<add>
<ide> VirtualizedList trace:
<ide> Child (horizontal):
<ide> listKey: level2 | 1 |
Go | Go | fix breakouts from git root during build | 7f7ebeffe81760e2e0a711eb480dd0e0e8cf24dc | <ide><path>utils/git.go
<ide> import (
<ide> "path/filepath"
<ide> "strings"
<ide>
<add> "github.com/docker/docker/pkg/symlink"
<ide> "github.com/docker/docker/pkg/urlutil"
<ide> )
<ide>
<ide> func checkoutGit(fragment, root string) (string, error) {
<ide> }
<ide>
<ide> if len(refAndDir) > 1 && len(refAndDir[1]) != 0 {
<del> newCtx := filepath.Join(root, refAndDir[1])
<add> newCtx, err := symlink.FollowSymlinkInScope(filepath.Join(root, refAndDir[1]), root)
<add> if err != nil {
<add> return "", fmt.Errorf("Error setting git context, %q not within git root: %s", refAndDir[1], err)
<add> }
<add>
<ide> fi, err := os.Stat(newCtx)
<ide> if err != nil {
<ide> return "", err
<ide><path>utils/git_test.go
<ide> func TestCheckoutGit(t *testing.T) {
<ide> t.Fatal(err)
<ide> }
<ide>
<add> if err = os.Symlink("../subdir", filepath.Join(gitDir, "parentlink")); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err = os.Symlink("/subdir", filepath.Join(gitDir, "absolutelink")); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<ide> if _, err = gitWithinDir(gitDir, "add", "-A"); err != nil {
<ide> t.Fatal(err)
<ide> }
<ide> func TestCheckoutGit(t *testing.T) {
<ide> {":Dockerfile", "", true}, // not a directory error
<ide> {"master:nosubdir", "", true},
<ide> {"master:subdir", "FROM scratch\nEXPOSE 5000", false},
<add> {"master:parentlink", "FROM scratch\nEXPOSE 5000", false},
<add> {"master:absolutelink", "FROM scratch\nEXPOSE 5000", false},
<add> {"master:../subdir", "", true},
<ide> {"test", "FROM scratch\nEXPOSE 3000", false},
<ide> {"test:", "FROM scratch\nEXPOSE 3000", false},
<ide> {"test:subdir", "FROM busybox\nEXPOSE 5000", false}, | 2 |
Text | Text | add r2curl in ecosystem | 299e827c577c2f1461e17678282f4d19a753e6f2 | <ide><path>ECOSYSTEM.md
<ide> This is a list of axios related libraries and resources. If you have a suggestio
<ide> * [axios-curlirize](https://www.npmjs.com/package/axios-curlirize) - Logs axios requests as curl commands, also adds a property to the response object with the curl command as value.
<ide> * [axios-actions](https://github.com/davestewart/axios-actions) - Bundle endpoints as callable, reusable services
<ide> * [axios-api-versioning](https://weffe.github.io/axios-api-versioning) - Add easy to manage api versioning to axios
<add>* [r2curl](https://github.com/uyu423/r2curl) - Extracts the cURL command string from the Axios object. (AxiosResponse, AxiosRequestConfig) | 1 |
Ruby | Ruby | tell the user when build logs are copied | aef580261b2452eda2ebad666f27692e94cbf7ef | <ide><path>Library/Homebrew/formula.rb
<ide> def brew
<ide> yield self
<ide> rescue Interrupt, RuntimeError, SystemCallError => e
<ide> unless ARGV.debug?
<del> logs = File.expand_path '~/Library/Logs/Homebrew/'
<del> if File.exist? 'config.log'
<del> mkdir_p logs
<del> mv 'config.log', logs
<del> end
<del> if File.exist? 'CMakeCache.txt'
<del> mkdir_p logs
<del> mv 'CMakeCache.txt', logs
<add> %w(config.log CMakeCache.txt).select{|f| File.exist? f}.each do |f|
<add> HOMEBREW_LOGS.install f
<add> ohai "#{f} was copied to #{HOMEBREW_LOGS}"
<ide> end
<ide> raise
<ide> end
<ide><path>Library/Homebrew/global.rb
<ide> def cache
<ide> HOMEBREW_REPOSITORY+"Cellar"
<ide> end
<ide>
<add>HOMEBREW_LOGS = Pathname.new('~/Library/Logs/Homebrew/').expand_path
<add>
<add>
<ide> MACOS_FULL_VERSION = `/usr/bin/sw_vers -productVersion`.chomp
<ide> MACOS_VERSION = /(10\.\d+)(\.\d+)?/.match(MACOS_FULL_VERSION).captures.first.to_f
<ide> | 2 |
Javascript | Javascript | use less container trickery | 6a71ff26042f2e6f9516f9616d88159a2acd8bec | <ide><path>packages/ember-application/lib/system/application.js
<ide> var Application = Namespace.extend(DeferredMixin, {
<ide>
<ide> // For the default instance only, set the view registry to the global
<ide> // Ember.View.views hash for backwards-compatibility.
<del> var registry = instance.applicationRegistry;
<del> registry.unregister('-view-registry:main');
<del> registry.register('-view-registry:main', EmberView.views);
<del> registry.optionsForType('-view-registry', { instantiate: false });
<add> EmberView.views = instance.container.lookup('-view-registry:main');
<ide>
<ide> // TODO2.0: Legacy support for App.__container__
<ide> // and global methods on App that rely on a single, | 1 |
Ruby | Ruby | remove time calculatiosn extension | ff9b38a7b556d103f94ab84aab237406a72dd61a | <ide><path>activesupport/lib/active_support/file_update_checker.rb
<add>require 'active_support/core_ext/time/calculations'
<add>
<ide> module ActiveSupport
<ide> # FileUpdateChecker specifies the API used by Rails to watch files
<ide> # and control reloading. The API depends on four methods: | 1 |
PHP | PHP | remove tests which are not expected to pass | 8ac036a078d1a8263432f0f102971ca6e324709a | <ide><path>tests/TestCase/ORM/Behavior/TranslateBehaviorTest.php
<ide> public function testCustomTableLocator()
<ide> $this->assertNotSame($this->getTableLocator(), $behaviorLocator);
<ide> }
<ide>
<del> /**
<del> * Tests that using matching doesn't cause an association property to be created.
<del> *
<del> * @return void
<del> */
<del> public function testMatchingDoesNotCreateAssociationProperty()
<del> {
<del> $table = $this->getTableLocator()->get('Articles');
<del> $table->hasMany('Comments');
<del>
<del> $table->Comments->addBehavior('Translate', ['fields' => ['comment']]);
<del> $table->Comments->setLocale('abc');
<del>
<del> $this->assertNotEquals($table->Comments->getLocale(), I18n::getLocale());
<del>
<del> $result = $table
<del> ->find()
<del> ->matching('Comments')
<del> ->first();
<del>
<del> $this->assertArrayNotHasKey('comments', $result->toArray());
<del> }
<del>
<ide> /**
<ide> * Tests that using deep matching doesn't cause an association property to be created.
<ide> *
<ide> public function testDeepMatchingDoesNotCreateAssociationProperty()
<ide> $this->assertArrayNotHasKey('author', $result->comments);
<ide> }
<ide>
<del> /**
<del> * Tests that using contained matching doesn't cause an association property to be created.
<del> *
<del> * @return void
<del> */
<del> public function testContainedMatchingDoesNotCreateAssociationProperty()
<del> {
<del> $table = $this->getTableLocator()->get('Authors');
<del> $table->hasMany('Comments')->setForeignKey('user_id');
<del> $table->Comments->belongsTo('Articles');
<del>
<del> $table->Comments->Articles->addBehavior('Translate', ['fields' => ['title', 'body']]);
<del> $table->Comments->Articles->setLocale('xyz');
<del>
<del> $this->assertNotEquals($table->Comments->Articles->getLocale(), I18n::getLocale());
<del>
<del> $result = $table
<del> ->find()
<del> ->contain([
<del> 'Comments' => function ($query) {
<del> return $query->matching('Articles');
<del> },
<del> ])
<del> ->first();
<del>
<del> $this->assertArrayNotHasKey('article', $result->comments[0]->toArray());
<del> }
<del>
<ide> /**
<ide> * Tests that the _locale property is set on the entity in the _matchingData property.
<ide> * | 1 |
PHP | PHP | use strict typing for routing package | ee78231c2feab109cafac8e116db8d8bdd515650 | <ide><path>src/Controller/Component/AuthComponent.php
<ide> public function redirectUrl($url = null): string
<ide> if ($url !== null) {
<ide> $redirectUrl = $url;
<ide> } elseif ($redirectUrl) {
<del> if (Router::normalize($redirectUrl) === Router::normalize($this->_config['loginAction'])) {
<add> if ($this->_config['loginAction']
<add> && Router::normalize($redirectUrl) === Router::normalize($this->_config['loginAction'])
<add> ) {
<ide> $redirectUrl = $this->_config['loginRedirect'];
<ide> }
<ide> } elseif ($this->_config['loginRedirect']) {
<ide><path>src/Routing/Exception/DuplicateNamedRouteException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Exception/MissingControllerException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Exception/MissingDispatcherFilterException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Exception/MissingRouteException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Exception/RedirectException.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Middleware/AssetMiddleware.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function __construct(array $options = [])
<ide> * @param callable $next Callback to invoke the next middleware.
<ide> * @return \Psr\Http\Message\ResponseInterface A response
<ide> */
<del> public function __invoke($request, $response, $next)
<add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
<ide> {
<ide> $url = $request->getUri()->getPath();
<ide> if (strpos($url, '..') !== false || strpos($url, '.') === false) {
<ide> public function __invoke($request, $response, $next)
<ide> * @param \Cake\Filesystem\File $file The file object to compare.
<ide> * @return bool
<ide> */
<del> protected function isNotModified($request, $file)
<add> protected function isNotModified(ServerRequestInterface $request, File $file): bool
<ide> {
<ide> $modifiedSince = $request->getHeaderLine('If-Modified-Since');
<ide> if (!$modifiedSince) {
<ide> protected function isNotModified($request, $file)
<ide> * @param string $url Asset URL
<ide> * @return string|null Absolute path for asset file, null on failure
<ide> */
<del> protected function _getAssetFile($url)
<add> protected function _getAssetFile(string $url): ?string
<ide> {
<ide> $parts = explode('/', ltrim($url, '/'));
<ide> $pluginPart = [];
<ide> protected function _getAssetFile($url)
<ide> * @param \Cake\Filesystem\File $file The file wrapper for the file.
<ide> * @return \Psr\Http\Message\ResponseInterface The response with the file & headers.
<ide> */
<del> protected function deliverAsset(ServerRequestInterface $request, ResponseInterface $response, $file)
<add> protected function deliverAsset(ServerRequestInterface $request, ResponseInterface $response, File $file): ResponseInterface
<ide> {
<ide> $contentType = $this->getType($file);
<ide> $modified = $file->lastChange();
<ide> protected function deliverAsset(ServerRequestInterface $request, ResponseInterfa
<ide> * @param File $file The file from which you get the type
<ide> * @return string
<ide> */
<del> protected function getType($file)
<add> protected function getType(File $file): string
<ide> {
<ide> $extension = $file->ext();
<ide> if (isset($this->typeMap[$extension])) {
<ide><path>src/Routing/Middleware/RoutingMiddleware.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> use Cake\Http\MiddlewareQueue;
<ide> use Cake\Http\Runner;
<ide> use Cake\Routing\Exception\RedirectException;
<add>use Cake\Routing\RouteCollection;
<ide> use Cake\Routing\Router;
<ide> use Psr\Http\Message\ResponseInterface;
<ide> use Psr\Http\Message\ServerRequestInterface;
<ide> class RoutingMiddleware
<ide> /**
<ide> * Constructor
<ide> *
<del> * @param \Cake\Http\BaseApplication $app The application instance that routes are defined on.
<add> * @param \Cake\Http\BaseApplication|null $app The application instance that routes are defined on.
<ide> * @param string|null $cacheConfig The cache config name to use or null to disable routes cache
<ide> */
<del> public function __construct(?BaseApplication $app = null, $cacheConfig = null)
<add> public function __construct(?BaseApplication $app = null, ?string $cacheConfig = null)
<ide> {
<ide> $this->app = $app;
<ide> $this->cacheConfig = $cacheConfig;
<ide> public function __construct(?BaseApplication $app = null, $cacheConfig = null)
<ide> *
<ide> * @return void
<ide> */
<del> protected function loadRoutes()
<add> protected function loadRoutes(): void
<ide> {
<ide> if (!$this->app) {
<ide> return;
<ide> protected function loadRoutes()
<ide> *
<ide> * @return \Cake\Routing\RouteCollection
<ide> */
<del> protected function buildRouteCollection()
<add> protected function buildRouteCollection(): RouteCollection
<ide> {
<ide> if (Cache::enabled() && $this->cacheConfig !== null) {
<ide> return Cache::remember(static::ROUTE_COLLECTION_CACHE_KEY, function () {
<ide> protected function buildRouteCollection()
<ide> *
<ide> * @return \Cake\Routing\RouteCollection
<ide> */
<del> protected function prepareRouteCollection()
<add> protected function prepareRouteCollection(): RouteCollection
<ide> {
<ide> $builder = Router::createRouteBuilder('/');
<ide> $this->app->routes($builder);
<ide> protected function prepareRouteCollection()
<ide> * @return \Psr\Http\Message\ResponseInterface A response.
<ide> * @throws \Cake\Routing\InvalidArgumentException
<ide> */
<del> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, $next)
<add> public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next): ResponseInterface
<ide> {
<ide> $this->loadRoutes();
<ide> try {
<ide><path>src/Routing/Route/DashedRoute.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Route/EntityRoute.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Route/InflectedRoute.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function match(array $url, array $context = []): ?string
<ide> * @param array $url An array of URL keys.
<ide> * @return array
<ide> */
<del> protected function _underscore($url)
<add> protected function _underscore(array $url): array
<ide> {
<ide> if (!empty($url['controller'])) {
<ide> $url['controller'] = Inflector::underscore($url['controller']);
<ide><path>src/Routing/Route/PluginShortRoute.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Route/RedirectRoute.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>src/Routing/Route/Route.php
<ide> public function hostMatches(string $host): bool
<ide> * @param string $url The url to parse.
<ide> * @return array containing url, extension
<ide> */
<del> protected function _parseExtension($url)
<add> protected function _parseExtension(string $url): array
<ide> {
<ide> if (count($this->_extensions) && strpos($url, '.') !== false) {
<ide> foreach ($this->_extensions as $ext) {
<ide> protected function _parseExtension($url)
<ide> * Currently implemented rule types are controller, action and match that can be combined with each other.
<ide> *
<ide> * @param string $args A string with the passed params. eg. /1/foo
<del> * @param string $context The current route context, which should contain controller/action keys.
<add> * @param array $context The current route context, which should contain controller/action keys.
<ide> * @return array Array of passed args.
<ide> */
<del> protected function _parseArgs($args, $context)
<add> protected function _parseArgs(string $args, array $context): array
<ide> {
<ide> $pass = [];
<ide> $args = explode('/', $args);
<ide> protected function _parseArgs($args, $context)
<ide> * @param array $params An array of persistent values to replace persistent ones.
<ide> * @return array An array with persistent parameters applied.
<ide> */
<del> protected function _persistParams(array $url, array $params)
<add> protected function _persistParams(array $url, array $params): array
<ide> {
<ide> foreach ($this->options['persist'] as $persistKey) {
<ide> if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
<ide> public function match(array $url, array $context = []): ?string
<ide> * @param array $url The array for the URL being generated.
<ide> * @return bool
<ide> */
<del> protected function _matchMethod($url)
<add> protected function _matchMethod(array $url): bool
<ide> {
<ide> if (empty($this->defaults['_method'])) {
<ide> return true;
<ide> protected function _matchMethod($url)
<ide> * @param array $query An array of parameters
<ide> * @return string Composed route string.
<ide> */
<del> protected function _writeUrl($params, $pass = [], $query = [])
<add> protected function _writeUrl(array $params, array $pass = [], array $query = []): string
<ide> {
<ide> $pass = implode('/', array_map('rawurlencode', $pass));
<ide> $out = $this->template;
<ide> public function setMiddleware(array $middleware)
<ide> *
<ide> * @return array
<ide> */
<del> public function getMiddleware()
<add> public function getMiddleware(): array
<ide> {
<ide> return $this->middleware;
<ide> }
<ide><path>src/Routing/RouteBuilder.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class RouteBuilder
<ide> * @param array $params The scope's routing parameters.
<ide> * @param array $options Options list.
<ide> */
<del> public function __construct(RouteCollection $collection, $path, array $params = [], array $options = [])
<add> public function __construct(RouteCollection $collection, string $path, array $params = [], array $options = [])
<ide> {
<ide> $this->_collection = $collection;
<ide> $this->_path = $path;
<ide> public function __construct(RouteCollection $collection, $path, array $params =
<ide> * @param string $routeClass Class name.
<ide> * @return $this
<ide> */
<del> public function setRouteClass($routeClass)
<add> public function setRouteClass(string $routeClass): self
<ide> {
<ide> $this->_routeClass = $routeClass;
<ide>
<ide> public function setRouteClass($routeClass)
<ide> *
<ide> * @return string
<ide> */
<del> public function getRouteClass()
<add> public function getRouteClass(): string
<ide> {
<ide> return $this->_routeClass;
<ide> }
<ide> public function getRouteClass()
<ide> * @param string|array $extensions The extensions to set.
<ide> * @return $this
<ide> */
<del> public function setExtensions($extensions)
<add> public function setExtensions($extensions): self
<ide> {
<ide> $this->_extensions = (array)$extensions;
<ide>
<ide> public function setExtensions($extensions)
<ide> *
<ide> * @return array
<ide> */
<del> public function getExtensions()
<add> public function getExtensions(): array
<ide> {
<ide> return $this->_extensions;
<ide> }
<ide> public function getExtensions()
<ide> * @param string|array $extensions One or more extensions to add
<ide> * @return void
<ide> */
<del> public function addExtensions($extensions)
<add> public function addExtensions($extensions): void
<ide> {
<ide> $extensions = array_merge($this->_extensions, (array)$extensions);
<ide> $this->_extensions = array_unique($extensions);
<ide> public function addExtensions($extensions)
<ide> *
<ide> * @return string
<ide> */
<del> public function path()
<add> public function path(): string
<ide> {
<ide> $routeKey = strpos($this->_path, ':');
<ide> if ($routeKey !== false) {
<ide> public function path()
<ide> *
<ide> * @return array
<ide> */
<del> public function params()
<add> public function params(): array
<ide> {
<ide> return $this->_params;
<ide> }
<ide> public function params()
<ide> * @param string $name Name.
<ide> * @return bool
<ide> */
<del> public function nameExists($name)
<add> public function nameExists(string $name): bool
<ide> {
<ide> return array_key_exists($name, $this->_collection->named());
<ide> }
<ide> public function nameExists($name)
<ide> * @param string|null $value Either the value to set or null.
<ide> * @return string
<ide> */
<del> public function namePrefix($value = null)
<add> public function namePrefix(?string $value = null): string
<ide> {
<ide> if ($value !== null) {
<ide> $this->_namePrefix = $value;
<ide> public function namePrefix($value = null)
<ide> * scopes inherit the existing path and 'id' parameter.
<ide> * @return void
<ide> */
<del> public function resources($name, $options = [], $callback = null)
<add> public function resources(string $name, $options = [], $callback = null): void
<ide> {
<ide> if (is_callable($options) && $callback === null) {
<ide> $callback = $options;
<ide> public function resources($name, $options = [], $callback = null)
<ide> * Create a route that only responds to GET requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function get($template, $target, $name = null)
<add> public function get(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('GET', $template, $target, $name);
<ide> }
<ide> public function get($template, $target, $name = null)
<ide> * Create a route that only responds to POST requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function post($template, $target, $name = null)
<add> public function post(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('POST', $template, $target, $name);
<ide> }
<ide> public function post($template, $target, $name = null)
<ide> * Create a route that only responds to PUT requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function put($template, $target, $name = null)
<add> public function put(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('PUT', $template, $target, $name);
<ide> }
<ide> public function put($template, $target, $name = null)
<ide> * Create a route that only responds to PATCH requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function patch($template, $target, $name = null)
<add> public function patch(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('PATCH', $template, $target, $name);
<ide> }
<ide> public function patch($template, $target, $name = null)
<ide> * Create a route that only responds to DELETE requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function delete($template, $target, $name = null)
<add> public function delete(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('DELETE', $template, $target, $name);
<ide> }
<ide> public function delete($template, $target, $name = null)
<ide> * Create a route that only responds to HEAD requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function head($template, $target, $name = null)
<add> public function head(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('HEAD', $template, $target, $name);
<ide> }
<ide> public function head($template, $target, $name = null)
<ide> * Create a route that only responds to OPTIONS requests.
<ide> *
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<del> * @param string $name The name of the route.
<add> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> public function options($template, $target, $name = null)
<add> public function options(string $template, $target, ?string $name = null): Route
<ide> {
<ide> return $this->_methodRoute('OPTIONS', $template, $target, $name);
<ide> }
<ide> public function options($template, $target, $name = null)
<ide> *
<ide> * @param string $method The HTTP method name to match.
<ide> * @param string $template The URL template to use.
<del> * @param array $target An array describing the target route parameters. These parameters
<add> * @param array|string $target An array describing the target route parameters. These parameters
<ide> * should indicate the plugin, prefix, controller, and action that this route points to.
<ide> * @param string|null $name The name of the route.
<ide> * @return \Cake\Routing\Route\Route
<ide> */
<del> protected function _methodRoute($method, $template, $target, $name)
<add> protected function _methodRoute(string $method, string $template, $target, ?string $name): Route
<ide> {
<ide> if ($name !== null) {
<ide> $name = $this->_namePrefix . $name;
<ide> protected function _methodRoute($method, $template, $target, $name)
<ide> * @throws \Cake\Core\Exception\MissingPluginException When the plugin has not been loaded.
<ide> * @throws \InvalidArgumentException When the plugin does not have a routes file.
<ide> */
<del> public function loadPlugin($name)
<add> public function loadPlugin(string $name): void
<ide> {
<ide> $plugins = Plugin::getCollection();
<ide> if (!$plugins->has($name)) {
<ide> public function loadPlugin($name)
<ide> *
<ide> * The above route will only be matched for GET requests. POST requests will fail to match this route.
<ide> *
<del> * @param string $route A string describing the template of the route
<add> * @param string|\Cake\Routing\Route\Route $route A string describing the template of the route
<ide> * @param array|string $defaults An array describing the default route parameters. These parameters will be used by default
<ide> * and can supply routing parameters that are not dynamic. See above.
<ide> * @param array $options An array matching the named elements in the route to regular expressions which that
<ide> public function loadPlugin($name)
<ide> * @throws \InvalidArgumentException
<ide> * @throws \BadMethodCallException
<ide> */
<del> public function connect($route, $defaults = [], array $options = [])
<add> public function connect($route, $defaults = [], array $options = []): Route
<ide> {
<ide> $defaults = $this->parseDefaults($defaults);
<ide> if (!isset($options['action']) && !isset($defaults['action'])) {
<ide> public function connect($route, $defaults = [], array $options = [])
<ide> * @param string|array $defaults Defaults array from the connect() method.
<ide> * @return array
<ide> */
<del> protected static function parseDefaults($defaults)
<add> protected static function parseDefaults($defaults): array
<ide> {
<ide> if (!is_string($defaults)) {
<ide> return $defaults;
<ide> protected static function parseDefaults($defaults)
<ide> * @throws \InvalidArgumentException when route class or route object is invalid.
<ide> * @throws \BadMethodCallException when the route to make conflicts with the current scope
<ide> */
<del> protected function _makeRoute($route, $defaults, $options)
<add> protected function _makeRoute($route, $defaults, $options): Route
<ide> {
<ide> if (is_string($route)) {
<ide> $routeClass = App::className($options['routeClass'], 'Routing/Route');
<ide> protected function _makeRoute($route, $defaults, $options)
<ide> * shifted into the passed arguments. As well as supplying patterns for routing parameters.
<ide> * @return void
<ide> */
<del> public function redirect($route, $url, array $options = [])
<add> public function redirect(string $route, $url, array $options = []): void
<ide> {
<ide> if (!isset($options['routeClass'])) {
<ide> $options['routeClass'] = 'Cake\Routing\Route\RedirectRoute';
<ide> public function redirect($route, $url, array $options = [])
<ide> * @return void
<ide> * @throws \InvalidArgumentException If a valid callback is not passed
<ide> */
<del> public function prefix($name, $params = [], ?callable $callback = null)
<add> public function prefix(string $name, $params = [], ?callable $callback = null): void
<ide> {
<ide> if ($callback === null) {
<ide> if (!is_callable($params)) {
<ide> public function prefix($name, $params = [], ?callable $callback = null)
<ide> * Only required when $options is defined.
<ide> * @return void
<ide> */
<del> public function plugin($name, $options = [], $callback = null)
<add> public function plugin(string $name, $options = [], $callback = null): void
<ide> {
<ide> if ($callback === null) {
<ide> /** @var callable $callback */
<ide> public function plugin($name, $options = [], $callback = null)
<ide> * @return void
<ide> * @throws \InvalidArgumentException when there is no callable parameter.
<ide> */
<del> public function scope($path, $params, $callback = null)
<add> public function scope(string $path, $params, $callback = null): void
<ide> {
<ide> if ($callback === null) {
<ide> $callback = $params;
<ide> public function scope($path, $params, $callback = null)
<ide> * if not specified
<ide> * @return void
<ide> */
<del> public function fallbacks($routeClass = null)
<add> public function fallbacks(?string $routeClass = null): void
<ide> {
<ide> $routeClass = $routeClass ?: $this->_routeClass;
<ide> $this->connect('/:controller', ['action' => 'index'], compact('routeClass'));
<ide> public function fallbacks($routeClass = null)
<ide> * @return $this
<ide> * @see \Cake\Routing\RouteCollection
<ide> */
<del> public function registerMiddleware($name, $middleware)
<add> public function registerMiddleware(string $name, $middleware): self
<ide> {
<ide> $this->_collection->registerMiddleware($name, $middleware);
<ide>
<ide> public function registerMiddleware($name, $middleware)
<ide> * @return $this
<ide> * @see \Cake\Routing\RouteCollection::addMiddlewareToScope()
<ide> */
<del> public function applyMiddleware(...$names)
<add> public function applyMiddleware(string ...$names): self
<ide> {
<ide> foreach ($names as $name) {
<ide> if (!$this->_collection->middlewareExists($name)) {
<ide> public function applyMiddleware(...$names)
<ide> * @param array $middlewareNames Names of the middleware
<ide> * @return $this
<ide> */
<del> public function middlewareGroup($name, array $middlewareNames)
<add> public function middlewareGroup(string $name, array $middlewareNames)
<ide> {
<ide> $this->_collection->middlewareGroup($name, $middlewareNames);
<ide>
<ide><path>src/Routing/RouteCollection.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class RouteCollection
<ide> * `_name` option, which enables named routes.
<ide> * @return void
<ide> */
<del> public function add(Route $route, array $options = [])
<add> public function add(Route $route, array $options = []): void
<ide> {
<ide> $this->_routes[] = $route;
<ide>
<ide> public function parse(string $url, string $method = ''): array
<ide> * @return array An array of request parameters parsed from the URL.
<ide> * @throws \Cake\Routing\Exception\MissingRouteException When a URL has no matching route.
<ide> */
<del> public function parseRequest(ServerRequestInterface $request)
<add> public function parseRequest(ServerRequestInterface $request): array
<ide> {
<ide> $uri = $request->getUri();
<ide> $urlPath = urldecode($uri->getPath());
<ide> public function parseRequest(ServerRequestInterface $request)
<ide> * @param array $url The url to match.
<ide> * @return array The set of names of the url
<ide> */
<del> protected function _getNames($url)
<add> protected function _getNames(array $url): array
<ide> {
<ide> $plugin = false;
<ide> if (isset($url['plugin']) && $url['plugin'] !== false) {
<ide> protected function _getNames($url)
<ide> if (isset($url['prefix']) && $url['prefix'] !== false) {
<ide> $prefix = strtolower($url['prefix']);
<ide> }
<del> $controller = strtolower($url['controller']);
<add> $controller = isset($url['controller']) ? strtolower($url['controller']) : null;
<ide> $action = strtolower($url['action']);
<ide>
<ide> $names = [
<ide> protected function _getNames($url)
<ide> * @return string The URL string on match.
<ide> * @throws \Cake\Routing\Exception\MissingRouteException When no route could be matched.
<ide> */
<del> public function match($url, $context)
<add> public function match(array $url, array $context): string
<ide> {
<ide> // Named routes support optimization.
<ide> if (isset($url['_name'])) {
<ide> public function match($url, $context)
<ide> *
<ide> * @return \Cake\Routing\Route\Route[]
<ide> */
<del> public function routes()
<add> public function routes(): array
<ide> {
<ide> return $this->_routes;
<ide> }
<ide> public function routes()
<ide> *
<ide> * @return \Cake\Routing\Route\Route[]
<ide> */
<del> public function named()
<add> public function named(): array
<ide> {
<ide> return $this->_named;
<ide> }
<ide> public function named()
<ide> *
<ide> * @return array The valid extensions.
<ide> */
<del> public function getExtensions()
<add> public function getExtensions(): array
<ide> {
<ide> return $this->_extensions;
<ide> }
<ide> public function getExtensions()
<ide> * Defaults to `true`.
<ide> * @return $this
<ide> */
<del> public function setExtensions(array $extensions, $merge = true)
<add> public function setExtensions(array $extensions, bool $merge = true): self
<ide> {
<ide> if ($merge) {
<ide> $extensions = array_unique(array_merge(
<ide> public function setExtensions(array $extensions, $merge = true)
<ide> * @param callable|string $middleware The middleware callable or class name to register.
<ide> * @return $this
<ide> */
<del> public function registerMiddleware($name, $middleware)
<add> public function registerMiddleware(string $name, $middleware): self
<ide> {
<ide> $this->_middleware[$name] = $middleware;
<ide>
<ide> public function registerMiddleware($name, $middleware)
<ide> * @param array $middlewareNames Names of the middleware
<ide> * @return $this
<ide> */
<del> public function middlewareGroup($name, array $middlewareNames)
<add> public function middlewareGroup(string $name, array $middlewareNames): self
<ide> {
<ide> if ($this->hasMiddleware($name)) {
<ide> $message = "Cannot add middleware group '$name'. A middleware by this name has already been registered.";
<ide> public function middlewareGroup($name, array $middlewareNames)
<ide> * @param string $name The name of the middleware group to check.
<ide> * @return bool
<ide> */
<del> public function hasMiddlewareGroup($name)
<add> public function hasMiddlewareGroup(string $name): bool
<ide> {
<ide> return array_key_exists($name, $this->_middlewareGroups);
<ide> }
<ide> public function hasMiddlewareGroup($name)
<ide> * @param string $name The name of the middleware to check.
<ide> * @return bool
<ide> */
<del> public function hasMiddleware($name)
<add> public function hasMiddleware(string $name): bool
<ide> {
<ide> return isset($this->_middleware[$name]);
<ide> }
<ide> public function hasMiddleware($name)
<ide> * @param string $name The name of the middleware to check.
<ide> * @return bool
<ide> */
<del> public function middlewareExists($name)
<add> public function middlewareExists(string $name): bool
<ide> {
<ide> return $this->hasMiddleware($name) || $this->hasMiddlewareGroup($name);
<ide> }
<ide> public function middlewareExists($name)
<ide> * @param string[] $middleware The middleware names to add for the path.
<ide> * @return $this
<ide> */
<del> public function applyMiddleware($path, array $middleware)
<add> public function applyMiddleware(string $path, array $middleware): self
<ide> {
<ide> foreach ($middleware as $name) {
<ide> if (!$this->hasMiddleware($name) && !$this->hasMiddlewareGroup($name)) {
<ide> public function applyMiddleware($path, array $middleware)
<ide> * the groups middleware will be flattened into the returned list.
<ide> * @throws \RuntimeException when a requested middleware does not exist.
<ide> */
<del> public function getMiddleware(array $names)
<add> public function getMiddleware(array $names): array
<ide> {
<ide> $out = [];
<ide> foreach ($names as $name) {
<ide><path>src/Routing/Router.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> class Router
<ide> * @param string|null $routeClass Class name.
<ide> * @return string|null
<ide> */
<del> public static function defaultRouteClass($routeClass = null)
<add> public static function defaultRouteClass(?string $routeClass = null): ?string
<ide> {
<ide> if ($routeClass === null) {
<ide> return static::$_defaultRouteClass;
<ide> }
<ide> static::$_defaultRouteClass = $routeClass;
<add>
<add> return null;
<ide> }
<ide>
<ide> /**
<ide> public static function defaultRouteClass($routeClass = null)
<ide> * @return array Named route elements
<ide> * @see \Cake\Routing\Router::$_namedExpressions
<ide> */
<del> public static function getNamedExpressions()
<add> public static function getNamedExpressions(): array
<ide> {
<ide> return static::$_namedExpressions;
<ide> }
<ide> public static function getNamedExpressions()
<ide> *
<ide> * Compatibility proxy to \Cake\Routing\RouteBuilder::connect() in the `/` scope.
<ide> *
<del> * @param string $route A string describing the template of the route
<add> * @param string|\Cake\Routing\Route\Route $route A string describing the template of the route
<ide> * @param array|string $defaults An array describing the default route parameters. These parameters will be used by default
<ide> * and can supply routing parameters that are not dynamic. See above.
<ide> * @param array $options An array matching the named elements in the route to regular expressions which that
<ide> public static function getNamedExpressions()
<ide> * @see \Cake\Routing\RouteBuilder::connect()
<ide> * @see \Cake\Routing\Router::scope()
<ide> */
<del> public static function connect($route, $defaults = [], $options = [])
<add> public static function connect($route, $defaults = [], $options = []): void
<ide> {
<del> static::scope('/', function ($routes) use ($route, $defaults, $options) {
<add> static::scope('/', function ($routes) use ($route, $defaults, $options): void {
<ide> $routes->connect($route, $defaults, $options);
<ide> });
<ide> }
<ide> public static function connect($route, $defaults = [], $options = [])
<ide> * @return array Parsed elements from URL.
<ide> * @throws \Cake\Routing\Exception\MissingRouteException When a route cannot be handled
<ide> */
<del> public static function parseRequest(ServerRequestInterface $request)
<add> public static function parseRequest(ServerRequestInterface $request): array
<ide> {
<ide> return static::$_collection->parseRequest($request);
<ide> }
<ide> public static function parseRequest(ServerRequestInterface $request)
<ide> * @param \Psr\Http\Message\ServerRequestInterface $request request object.
<ide> * @return void
<ide> */
<del> public static function setRequestInfo(ServerRequestInterface $request)
<add> public static function setRequestInfo(ServerRequestInterface $request): void
<ide> {
<ide> static::pushRequest($request);
<ide> }
<ide> public static function setRequestInfo(ServerRequestInterface $request)
<ide> * @param \Cake\Http\ServerRequest $request Request instance.
<ide> * @return void
<ide> */
<del> public static function pushRequest(ServerRequest $request)
<add> public static function pushRequest(ServerRequest $request): void
<ide> {
<ide> static::$_requests[] = $request;
<ide> static::setRequestContext($request);
<ide> public static function pushRequest(ServerRequest $request)
<ide> * @return void
<ide> * @throws \InvalidArgumentException When parameter is an incorrect type.
<ide> */
<del> public static function setRequestContext(ServerRequestInterface $request)
<add> public static function setRequestContext(ServerRequestInterface $request): void
<ide> {
<ide> $uri = $request->getUri();
<ide> static::$_requestContext = [
<ide> public static function setRequestContext(ServerRequestInterface $request)
<ide> * @return \Cake\Http\ServerRequest The request removed from the stack.
<ide> * @see \Cake\Routing\Router::pushRequest()
<ide> */
<del> public static function popRequest()
<add> public static function popRequest(): ServerRequest
<ide> {
<ide> $removed = array_pop(static::$_requests);
<ide> $last = end(static::$_requests);
<ide> public static function popRequest()
<ide> * @param bool $current True to get the current request, or false to get the first one.
<ide> * @return \Cake\Http\ServerRequest|null
<ide> */
<del> public static function getRequest($current = false)
<add> public static function getRequest(bool $current = false): ?ServerRequest
<ide> {
<ide> if ($current) {
<ide> $request = end(static::$_requests);
<ide> public static function getRequest($current = false)
<ide> *
<ide> * @return void
<ide> */
<del> public static function reload()
<add> public static function reload(): void
<ide> {
<ide> if (empty(static::$_initialState)) {
<ide> static::$_collection = new RouteCollection();
<ide> public static function reload()
<ide> * @param callable $function The function to add
<ide> * @return void
<ide> */
<del> public static function addUrlFilter(callable $function)
<add> public static function addUrlFilter(callable $function): void
<ide> {
<ide> static::$_urlFilters[] = $function;
<ide> }
<ide> public static function addUrlFilter(callable $function)
<ide> * @see \Cake\Routing\Router::url()
<ide> * @see \Cake\Routing\Router::addUrlFilter()
<ide> */
<del> protected static function _applyUrlFilters($url)
<add> protected static function _applyUrlFilters(array $url): array
<ide> {
<ide> $request = static::getRequest(true);
<ide> foreach (static::$_urlFilters as $filter) {
<ide> protected static function _applyUrlFilters($url)
<ide> * @return string Full translated URL with base path.
<ide> * @throws \Cake\Core\Exception\Exception When the route name is not found
<ide> */
<del> public static function url($url = null, $full = false)
<add> public static function url($url = null, $full = false): string
<ide> {
<ide> $params = [
<ide> 'plugin' => null,
<ide> public static function url($url = null, $full = false)
<ide> * Default is false.
<ide> * @return bool
<ide> */
<del> public static function routeExists($url = null, $full = false)
<add> public static function routeExists($url = null, $full = false): bool
<ide> {
<ide> try {
<ide> $route = static::url($url, $full);
<ide> public static function routeExists($url = null, $full = false)
<ide> * For example: `http://example.com`
<ide> * @return string
<ide> */
<del> public static function fullBaseUrl($base = null)
<add> public static function fullBaseUrl(?string $base = null): string
<ide> {
<ide> if ($base !== null) {
<ide> static::$_fullBaseUrl = $base;
<ide> public static function fullBaseUrl($base = null)
<ide> * Cake\Http\ServerRequest object that needs to be reversed.
<ide> * @return array The URL array ready to be used for redirect or HTML link.
<ide> */
<del> public static function reverseToArray($params)
<add> public static function reverseToArray($params): array
<ide> {
<ide> $url = [];
<ide> if ($params instanceof ServerRequest) {
<ide> public static function reverseToArray($params)
<ide> * protocol when reversing the URL.
<ide> * @return string The string that is the reversed result of the array
<ide> */
<del> public static function reverse($params, $full = false)
<add> public static function reverse($params, $full = false): string
<ide> {
<ide> $params = static::reverseToArray($params);
<ide>
<ide> public static function reverse($params, $full = false)
<ide> * @param array|string $url URL to normalize Either an array or a string URL.
<ide> * @return string Normalized URL
<ide> */
<del> public static function normalize($url = '/')
<add> public static function normalize($url = '/'): string
<ide> {
<ide> if (is_array($url)) {
<ide> $url = static::url($url);
<ide> public static function normalize($url = '/')
<ide> * Defaults to `true`.
<ide> * @return array Array of extensions Router is configured to parse.
<ide> */
<del> public static function extensions($extensions = null, $merge = true)
<add> public static function extensions($extensions = null, $merge = true): array
<ide> {
<ide> $collection = static::$_collection;
<ide> if ($extensions === null) {
<ide> public static function extensions($extensions = null, $merge = true)
<ide> * @param array $options The options for the builder
<ide> * @return \Cake\Routing\RouteBuilder
<ide> */
<del> public static function createRouteBuilder($path, array $options = [])
<add> public static function createRouteBuilder(string $path, array $options = []): RouteBuilder
<ide> {
<ide> $defaults = [
<ide> 'routeClass' => static::defaultRouteClass(),
<ide> public static function createRouteBuilder($path, array $options = [])
<ide> * @throws \InvalidArgumentException When an invalid callable is provided.
<ide> * @return void
<ide> */
<del> public static function scope($path, $params = [], $callback = null)
<add> public static function scope(string $path, $params = [], $callback = null): void
<ide> {
<ide> $options = [];
<ide> if (is_array($params)) {
<ide> public static function scope($path, $params = [], $callback = null)
<ide> * @param callable|null $callback The callback to invoke that builds the prefixed routes.
<ide> * @return void
<ide> */
<del> public static function prefix($name, $params = [], $callback = null)
<add> public static function prefix(string $name, $params = [], $callback = null): void
<ide> {
<ide> if ($callback === null) {
<ide> /** @var callable $callback */
<ide> public static function prefix($name, $params = [], $callback = null)
<ide> * Only required when $options is defined
<ide> * @return void
<ide> */
<del> public static function plugin($name, $options = [], $callback = null)
<add> public static function plugin(string $name, $options = [], $callback = null): void
<ide> {
<ide> if ($callback === null) {
<ide> /** @var callable $callback */
<ide> public static function plugin($name, $options = [], $callback = null)
<ide> *
<ide> * @return \Cake\Routing\Route\Route[]
<ide> */
<del> public static function routes()
<add> public static function routes(): array
<ide> {
<ide> return static::$_collection->routes();
<ide> }
<ide> public static function routes()
<ide> *
<ide> * @return \Cake\Routing\RouteCollection
<ide> */
<del> public static function getRouteCollection()
<add> public static function getRouteCollection(): RouteCollection
<ide> {
<ide> return static::$_collection;
<ide> }
<ide> public static function getRouteCollection()
<ide> * @param RouteCollection $routeCollection route collection
<ide> * @return void
<ide> */
<del> public static function setRouteCollection($routeCollection)
<add> public static function setRouteCollection(RouteCollection $routeCollection): void
<ide> {
<ide> static::$_collection = $routeCollection;
<ide> }
<ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php
<ide> public function testLoginRedirectDifferentBaseUrl(): void
<ide> 'webroot' => 'webroot',
<ide> 'base' => false,
<ide> 'baseUrl' => '/cake/index.php',
<add> 'fullBaseUrl' => '',
<ide> ]);
<ide>
<ide> $this->Auth->getController()->getRequest()->getSession()->delete('Auth');
<ide><path>tests/TestCase/Routing/Middleware/AssetMiddlewareTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/Middleware/RoutingMiddlewareTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testRouterSetParams()
<ide> '_matchedRoute' => '/articles',
<ide> ];
<ide> $this->assertEquals($expected, $req->getAttribute('params'));
<add>
<add> return $res;
<ide> };
<ide> $middleware = new RoutingMiddleware();
<ide> $middleware($request, $response, $next);
<ide> public function testPreservingExistingParams()
<ide> '_csrfToken' => 'i-am-groot',
<ide> ];
<ide> $this->assertEquals($expected, $req->getAttribute('params'));
<add>
<add> return $res;
<ide> };
<ide> $middleware = new RoutingMiddleware();
<ide> $middleware($request, $response, $next);
<ide> public function testRoutesHookInvokedOnApp()
<ide> $this->assertEquals($expected, $req->getAttribute('params'));
<ide> $this->assertNotEmpty(Router::routes());
<ide> $this->assertEquals('/app/articles', Router::routes()[0]->template);
<add>
<add> return $res;
<ide> };
<ide> $app = new Application(CONFIG);
<ide> $middleware = new RoutingMiddleware($app);
<ide> public function testRouterNoopOnController()
<ide> $response = new Response();
<ide> $next = function ($req, $res) {
<ide> $this->assertEquals(['controller' => 'Articles'], $req->getAttribute('params'));
<add>
<add> return $res;
<ide> };
<ide> $middleware = new RoutingMiddleware();
<ide> $middleware($request, $response, $next);
<ide> public function testMissingRouteNotCaught()
<ide> $request = ServerRequestFactory::fromGlobals(['REQUEST_URI' => '/missing']);
<ide> $response = new Response();
<ide> $next = function ($req, $res) {
<add> return $res;
<ide> };
<ide> $middleware = new RoutingMiddleware();
<ide> $middleware($request, $response, $next);
<ide> public function testFakedRequestMethodParsed()
<ide> ];
<ide> $this->assertEquals($expected, $req->getAttribute('params'));
<ide> $this->assertEquals('PATCH', $req->getMethod());
<add>
<add> return $res;
<ide> };
<ide> $middleware = new RoutingMiddleware();
<ide> $middleware($request, $response, $next);
<ide><path>tests/TestCase/Routing/Route/DashedRouteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/Route/EntityRouteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/Route/InflectedRouteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/Route/PluginShortRouteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/Route/RedirectRouteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/Route/RouteTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/RouteBuilderTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide><path>tests/TestCase/Routing/RouterTest.php
<ide> <?php
<add>declare(strict_types=1);
<ide> /**
<ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
<ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
<ide> public function testRouteParamDefaults()
<ide> {
<ide> Router::connect('/cache/*', ['prefix' => false, 'plugin' => true, 'controller' => 0, 'action' => 1]);
<ide>
<del> $url = Router::url(['prefix' => 0, 'plugin' => 1, 'controller' => 0, 'action' => 1, 'test']);
<add> $url = Router::url(['prefix' => '0', 'plugin' => '1', 'controller' => '0', 'action' => '1', 'test']);
<ide> $expected = '/cache/test';
<ide> $this->assertEquals($expected, $url);
<ide>
<ide> try {
<del> Router::url(['controller' => 0, 'action' => 1, 'test']);
<add> Router::url(['controller' => '0', 'action' => '1', 'test']);
<ide> $this->fail('No exception raised');
<ide> } catch (\Exception $e) {
<ide> $this->assertTrue(true, 'Exception was raised');
<ide> }
<ide>
<ide> try {
<del> Router::url(['prefix' => 1, 'controller' => 0, 'action' => 1, 'test']);
<add> Router::url(['prefix' => '1', 'controller' => '0', 'action' => '1', 'test']);
<ide> $this->fail('No exception raised');
<ide> } catch (\Exception $e) {
<ide> $this->assertTrue(true, 'Exception was raised');
<ide><path>tests/test_app/TestApp/Routing/Route/DashedRoute.php
<ide>
<ide> class DashedRoute extends InflectedRoute
<ide> {
<del> protected function _underscore($url)
<add> protected function _underscore(array $url): array
<ide> {
<ide> $url = parent::_underscore($url);
<ide> | 30 |
Python | Python | add exceptions for `batch_dot` | 918c5991faa21cbb48de07566124c57cf16c0cf0 | <ide><path>keras/backend/cntk_backend.py
<ide> def batch_dot(x, y, axes=None):
<ide> if axes is None:
<ide> # behaves like tf.batch_matmul as default
<ide> axes = [len(x_shape) - 1, len(y_shape) - 2]
<add> if b_any([isinstance(a, (list, tuple)) for a in axes]):
<add> raise ValueError('Multiple target dimensions are not supported. ' +
<add> 'Expected: None, int, (int, int), ' +
<add> 'Provided: ' + str(axes))
<ide>
<ide> if len(x_shape) == 2 and len(y_shape) == 2:
<ide> if axes[0] == axes[1]:
<ide><path>keras/backend/tensorflow_backend.py
<ide> from .common import image_dim_ordering
<ide>
<ide> py_all = all
<add>py_any = any
<ide> py_sum = sum
<ide>
<ide> # INTERNAL UTILS
<ide> def batch_dot(x, y, axes=None):
<ide> if axes is None:
<ide> # behaves like tf.batch_matmul as default
<ide> axes = [x_ndim - 1, y_ndim - 2]
<add> if py_any([isinstance(a, (list, tuple)) for a in axes]):
<add> raise ValueError('Multiple target dimensions are not supported. ' +
<add> 'Expected: None, int, (int, int), ' +
<add> 'Provided: ' + str(axes))
<ide> if x_ndim > y_ndim:
<ide> diff = x_ndim - y_ndim
<ide> y = tf.reshape(y, tf.concat([tf.shape(y), [1] * (diff)], axis=0))
<ide><path>keras/backend/theano_backend.py
<ide> from .common import set_image_dim_ordering, image_dim_ordering
<ide>
<ide> py_all = all
<add>py_any = any
<ide> py_sum = sum
<ide>
<ide>
<ide> def batch_dot(x, y, axes=None):
<ide> if axes is None:
<ide> # behaves like tf.batch_matmul as default
<ide> axes = [x.ndim - 1, y.ndim - 2]
<add> if py_any([isinstance(a, (list, tuple)) for a in axes]):
<add> raise ValueError('Multiple target dimensions are not supported. ' +
<add> 'Expected: None, int, (int, int), ' +
<add> 'Provided: ' + str(axes))
<ide> if isinstance(axes, tuple):
<ide> axes = list(axes)
<ide> | 3 |
Text | Text | add document describing the rn ecosystem. | a1250da64625c1da581fe600f805fd321cd12d4f | <ide><path>ECOSYSTEM.md
<add># The React Native Ecosystem
<add>
<add>We aim to build a vibrant and inclusive ecosystem of partners, core contributors, and community that goes beyond the main React Native GitHub repository. This document explains the roles and responsibilities of various stakeholders and provides guidelines for the community organization. The structure outlined in this document has been in place for a while but hadn't been written down before.
<add>
<add>There are three types of stakeholders:
<add>
<add>* **Partners:** Companies that are significantly invested in React Native and have been for years.
<add>* **Core Contributors:** Individual people who contribute to the React Native project.
<add>* **Community Contributors:** Individuals who support projects in the [react-native-community](https://github.com/react-native-community) organization.
<add>
<add>## Partners
<add>
<add>Partners are companies that are significantly invested in React Native and have been for years. Informed by their use of React Native, they push for improvements of the core and/or the ecosystem around it. Facebook's partners think of React Native as a product: they understand the trade offs that the project makes as well as future plans and goals. Together we shape the vision for React Native to make it the best way to build applications.
<add>
<add>Our current set of partners include Callstack, Expo, Infinite Red, Microsoft and Software Mansion. Many engineers from these companies are core contributors, and their partner responsibilities also include:
<add>
<add>* **[Callstack](https://callstack.com/):** Manages releases, maintains the [React Native CLI](https://github.com/react-native-community/react-native-cli) and organizes [React Native EU](https://react-native.eu/)
<add>* **[Expo](https://expo.io/):** Builds [expo](https://github.com/expo/expo) on top of React Native to simplify app development
<add>* **[Infinite Red](https://infinite.red/):** Maintains the [ignite cli/boilerplate](https://github.com/infinitered/ignite), organizes [Chain React Conf](https://infinite.red/ChainReactConf)
<add>* **[Microsoft](https://www.microsoft.com/en-gb/):** Develops [React Native Windows](https://github.com/Microsoft/react-native-windows) for the Universal Windows Platform (UWP)
<add>* **[Software Mansion](https://swmansion.com/):** Maintain core infrastructure including JSC, Animated, and other popular third-party plugins.
<add>
<add>In terms of open source work, pull requests from partners are commonly prioritized. When you are contributing to React Native, you'll most likely meet somebody who works at one of the partner companies and who is a core contributor:
<add>
<add>## Core Contributors
<add>
<add>Core contributors are individuals who contribute to the React Native project. A core contributor is somebody who displayed a lasting commitment to the evolution and maintenance of React Native. The work done by core contributors includes responsibilities mentioned in the “Partners” section above, and concretely means that they:
<add>
<add>* Consistently contribute high quality changes, fixes and improvements
<add>* Actively review changes and provide quality feedback to contributors
<add>* Manage the release process of React Native by maintaining release branches, communicating changes to users and publishing releases
<add>* Love to help out other users with issues on GitHub
<add>* Mentor and encourage first time contributors
<add>* Identify React Native community members who could be effective core contributors
<add>* Help build an inclusive community with people from all backgrounds
<add>* Are great at communicating with other contributors and the community in general
<add>
<add>These are behaviors we have observed in our existing core contributors. They aren't strict rules but rather outline their usual responsibilities. We do not expect every core contributor to do all of the above things all the time. Most importantly, we want to create a supportive and friendly environment that fosters collaboration. Above all else, **we are always polite and friendly.**
<add>
<add>Core contributor status is attained after consistently contributing and taking on the responsibilities outlined above and granted by other core contributors. Similarly, after a long period of inactivity, a core contributor may be removed.
<add>
<add>We aim to make contributing to React Native as easy and transparent as possible. All important topics are handled through a [discussion or RFC process on GitHub](https://github.com/react-native-community/discussions-and-proposals). We are always looking for active, enthusiastic members of the React Native community to become core contributors.
<add>
<add>## Community Contributors
<add>
<add>Community contributors are individuals who support projects in the [react-native-community](https://github.com/react-native-community) organization. This organization exists as an incubator for high quality components that extend the capabilities of React Native with functionality that many but not all applications require. Facebook engineers will provide guidance to help build a vibrant community of people and components that make React Native better.
<add>
<add>This structure has multiple benefits:
<add>
<add>* Keep the core of React Native small, which improves performance and reduces the surface area
<add>* Provide visibility to projects through shared representation, for example on the React Native website or on Twitter
<add>* Ensure a consistent and high standard for code, documentation, user experience, stability and contributions for third-party components
<add>* Upgrade the most important components right away when we make breaking changes and move the ecosystem forward at a fast pace
<add>* Find new maintainers for projects that are important but were abandoned by previous owners
<add>
<add>Additionally, some companies may choose to sponsor the development of one or many of the packages that are part of the community organization. They will commit to maintain projects, triage issues, fix bugs and develop features. In turn, they will be able to gain visibility for their work, for example through a mention of active maintainers in the README of individual projects after a consistent period of contributions. Such a mention may be removed if maintainers abandon the project.
<add>
<add>If you are working on a popular component and would like to move it to the React Native community, please create an issue on the [discussions-and-proposals repository](https://github.com/react-native-community/discussions-and-proposals).
<ide><path>README.md
<ide> React Native brings [**React**'s][r] declarative UI framework to iOS and Android
<ide> - **Developer Velocity.** See local changes in seconds. Changes to JavaScript code can be live reloaded without rebuilding the native app.
<ide> - **Portability.** Reuse code across iOS, Android, and [other platforms][p].
<ide>
<add>React Native is developed and supported by many companies and individual core contributors. Find out more in our [ecosystem overview][e].
<add>
<ide> [r]: https://reactjs.org/
<ide> [p]: https://facebook.github.io/react-native/docs/out-of-tree-platforms
<add>[e]: https://github.com/facebook/react-native/blob/master/ECOSYSTEM.md
<ide>
<ide> ## Contents
<ide> | 2 |
Go | Go | move the kernel detection to arch specific files | 16aeb77d5155cf33d1637073b9ca56728d472b49 | <ide><path>getKernelVersion_darwin.go
<add>package docker
<add>
<add>func getKernelVersion() (*KernelVersionInfo, error) {
<add> return nil, fmt.Errorf("Kernel version detection is not available on darwin")
<add>}
<ide><path>getKernelVersion_linux.go
<add>package docker
<add>
<add>import (
<add> "strconv"
<add> "strings"
<add> "syscall"
<add>)
<add>
<add>func getKernelVersion() (*KernelVersionInfo, error) {
<add> var (
<add> uts syscall.Utsname
<add> flavor string
<add> kernel, major, minor int
<add> err error
<add> )
<add>
<add> if err := syscall.Uname(&uts); err != nil {
<add> return nil, err
<add> }
<add>
<add> release := make([]byte, len(uts.Release))
<add>
<add> i := 0
<add> for _, c := range uts.Release {
<add> release[i] = byte(c)
<add> i++
<add> }
<add>
<add> tmp := strings.SplitN(string(release), "-", 2)
<add> tmp2 := strings.SplitN(tmp[0], ".", 3)
<add>
<add> if len(tmp2) > 0 {
<add> kernel, err = strconv.Atoi(tmp2[0])
<add> if err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> if len(tmp2) > 1 {
<add> major, err = strconv.Atoi(tmp2[1])
<add> if err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> if len(tmp2) > 2 {
<add> minor, err = strconv.Atoi(tmp2[2])
<add> if err != nil {
<add> return nil, err
<add> }
<add> }
<add>
<add> if len(tmp) == 2 {
<add> flavor = tmp[1]
<add> } else {
<add> flavor = ""
<add> }
<add>
<add> return &KernelVersionInfo{
<add> Kernel: kernel,
<add> Major: major,
<add> Minor: minor,
<add> Flavor: flavor,
<add> }, nil
<add>}
<ide><path>utils.go
<ide> import (
<ide> "path/filepath"
<ide> "regexp"
<ide> "runtime"
<del> "strconv"
<ide> "strings"
<ide> "sync"
<del> "syscall"
<ide> "time"
<ide> )
<ide>
<ide> type KernelVersionInfo struct {
<ide>
<ide> // FIXME: this doens't build on Darwin
<ide> func GetKernelVersion() (*KernelVersionInfo, error) {
<del> var (
<del> uts syscall.Utsname
<del> flavor string
<del> kernel, major, minor int
<del> err error
<del> )
<del>
<del> if err := syscall.Uname(&uts); err != nil {
<del> return nil, err
<del> }
<del>
<del> release := make([]byte, len(uts.Release))
<del>
<del> i := 0
<del> for _, c := range uts.Release {
<del> release[i] = byte(c)
<del> i++
<del> }
<del>
<del> tmp := strings.SplitN(string(release), "-", 2)
<del> tmp2 := strings.SplitN(tmp[0], ".", 3)
<del>
<del> if len(tmp2) > 0 {
<del> kernel, err = strconv.Atoi(tmp2[0])
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<del>
<del> if len(tmp2) > 1 {
<del> major, err = strconv.Atoi(tmp2[1])
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<del>
<del> if len(tmp2) > 2 {
<del> minor, err = strconv.Atoi(tmp2[2])
<del> if err != nil {
<del> return nil, err
<del> }
<del> }
<del>
<del> if len(tmp) == 2 {
<del> flavor = tmp[1]
<del> } else {
<del> flavor = ""
<del> }
<del>
<del> return &KernelVersionInfo{
<del> Kernel: kernel,
<del> Major: major,
<del> Minor: minor,
<del> Flavor: flavor,
<del> }, nil
<add> return getKernelVersion()
<ide> }
<ide>
<ide> func (k *KernelVersionInfo) String() string { | 3 |
Ruby | Ruby | remove stray space | 5561d3d09c760effce6621628a6612df16f5ec66 | <ide><path>Library/Homebrew/requirements/python_dependency.rb
<ide> def minor
<ide> end
<ide> end
<ide>
<del> def initialize(default_version="2.6", tags=[] )
<add> def initialize(default_version="2.6", tags=[])
<ide> tags = [tags].flatten
<ide> # Extract the min_version if given. Default to default_version else
<ide> if /(\d+\.)*\d+/ === tags.first.to_s | 1 |
Ruby | Ruby | handle multiple results | 2056e24a12a48b9776e78992cfe77494d64ca3f8 | <ide><path>Library/Homebrew/macos.rb
<ide> def app_with_bundle_id id
<ide> end
<ide>
<ide> def mdfind attribute, id
<del> path = `mdfind "#{attribute} == '#{id}'"`.strip
<add> path = `mdfind "#{attribute} == '#{id}'"`.split("\n").first.strip
<ide> Pathname.new(path) unless path.empty?
<ide> end
<ide> | 1 |
Javascript | Javascript | favor arrow function in callback | 21522cb713250cb353d8fb43a70f936e32b88eaf | <ide><path>test/parallel/test-zlib-close-after-write.js
<ide> const common = require('../common');
<ide> const zlib = require('zlib');
<ide>
<del>zlib.gzip('hello', common.mustCall(function(err, out) {
<add>zlib.gzip('hello', common.mustCall((err, out) => {
<ide> const unzip = zlib.createGunzip();
<ide> unzip.write(out);
<ide> unzip.close(common.mustCall()); | 1 |
Python | Python | write failing test | 0ad41a09ae7d4d48cd3ba402296ee7d3022b7fa2 | <ide><path>t/unit/tasks/test_canvas.py
<ide> def test_app_when_app_in_task(self):
<ide> x = chord([t1], body=t2)
<ide> assert x.app is t2._app
<ide>
<add> def test_app_when_header_is_empty(self):
<add> x = chord([], self.add.s(4, 4))
<add> assert x.app is self.add.app
<add>
<ide> @pytest.mark.usefixtures('depends_on_current_app')
<ide> def test_app_fallback_to_current(self):
<ide> from celery._state import current_app | 1 |
PHP | PHP | fix failing tests | 389415f628b6881d587b5498d3df3de7871b7bcf | <ide><path>tests/TestCase/Core/PluginTest.php
<ide> public function testUnload()
<ide> */
<ide> public function testLoadSingleWithAutoload()
<ide> {
<del> $this->assertFalse(class_exists('Company\TestPluginThree\Utility\Hello'));
<del> Plugin::load('Company/TestPluginThree', [
<add> $this->assertFalse(class_exists('Company\TestPluginFive\Utility\Hello'));
<add> Plugin::load('Company/TestPluginFive', [
<ide> 'autoload' => true,
<ide> ]);
<ide> $this->assertTrue(
<del> class_exists('Company\TestPluginThree\Utility\Hello'),
<add> class_exists('Company\TestPluginFive\Utility\Hello'),
<ide> 'Class should be loaded'
<ide> );
<ide> }
<ide> class_exists('Company\TestPluginThree\Utility\Hello'),
<ide> */
<ide> public function testLoadSingleWithAutoloadAndBootstrap()
<ide> {
<del> $this->assertFalse(class_exists('Company\TestPluginFive\Utility\Hello'));
<ide> Plugin::load(
<ide> 'Company/TestPluginFive',
<ide> [ | 1 |
Ruby | Ruby | fix printing of unexpected bin/lib files | 5f6b10f39adbf6fc256eaf58945f5c95db0cbd14 | <ide><path>Library/Homebrew/formula_cellar_checks.rb
<ide> def check_jars
<ide> Installing JARs to "lib" can cause conflicts between packages.
<ide> For Java software, it is typically better for the formula to
<ide> install to "libexec" and then symlink or wrap binaries into "bin".
<del> "See "activemq", "jruby", etc. for examples."
<del> "The offending files are:"
<del> #{jars}
<add> See "activemq", "jruby", etc. for examples.
<add> The offending files are:
<add> #{jars * "\n"}
<ide> EOS
<ide> ]
<ide> end
<ide> def check_non_libraries
<ide> <<-EOS.undent
<ide> Installing non-libraries to "lib" is bad practice.
<ide> The offending files are:
<del> #{non_libraries}
<add> #{non_libraries * "\n"}
<ide> EOS
<ide> ]
<ide> end
<ide> def check_non_executables bin
<ide> ["Non-executables were installed to \"#{bin}\".",
<ide> <<-EOS.undent
<ide> The offending files are:
<del> #{non_exes}
<add> #{non_exes * "\n"}
<ide> EOS
<ide> ]
<ide> end | 1 |
Text | Text | add clarification to question and escape backslash | da166363eb5dadd15a298a74088f3ab68a28e01e | <ide><path>curriculum/challenges/english/07-scientific-computing-with-python/python-for-everybody/regular-expressions.english.md
<ide> videoId: Yud_COr6pZo
<ide> ```yml
<ide> question:
<ide> text: |
<del> Which regex only matches a white space character?
<add> Which regex matches only a white space character?
<ide>
<ide> answers:
<ide> - | | 1 |
Java | Java | refine precomputefieldfeature logging | bfe37c290e033aa1684faf61941bbbceb1d3324d | <ide><path>spring-core/src/main/java/org/springframework/aot/nativex/feature/PreComputeFieldFeature.java
<ide> private void iterateFields(DuringAnalysisAccess access, Class<?> subtype) {
<ide> System.out.println("Field " + fieldIdentifier + " set to " + fieldValue + " at build time");
<ide> }
<ide> catch (Throwable ex) {
<del> System.out.println("Processing of field " + fieldIdentifier + " skipped due the following error : " + ex.getMessage());
<add> System.out.println("Field " + fieldIdentifier + " will be evaluated at runtime due to this error during build time evaluation: " + ex.getMessage());
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | implement platform specific protocolforurl | 6591d689689e3c1203fc3dc94d1ba234433328a1 | <ide><path>packages/ember-glimmer/lib/environment.js
<ide> import { default as normalizeClassHelper } from './helpers/-normalize-class';
<ide> import { default as htmlSafeHelper } from './helpers/-html-safe';
<ide> import { OWNER } from 'container';
<ide>
<add>import installPlatformSpecificProtocolForURL from './protocol-for-url';
<add>
<ide> const builtInComponents = {
<ide> textarea: '-text-area'
<ide> };
<ide> export default class Environment extends GlimmerEnvironment {
<ide> super(...arguments);
<ide> this.owner = owner;
<ide>
<del> this.uselessAnchor = this.getAppendOperations().createElement('a');
<add> installPlatformSpecificProtocolForURL(this);
<ide>
<ide> this._definitionCache = new Cache(2000, ({ name, source, owner }) => {
<ide> let { component: ComponentClass, layout } = lookupComponent(owner, name, { source });
<ide> export default class Environment extends GlimmerEnvironment {
<ide> };
<ide> }
<ide>
<del> protocolForURL(url) {
<del> this.uselessAnchor.href = url;
<del> return this.uselessAnchor.protocol;
<del> }
<del>
<ide> // Hello future traveler, welcome to the world of syntax refinement.
<ide> // The method below is called by Glimmer's runtime compiler to allow
<ide> // us to take generic statement syntax and refine it to more meaniful
<ide><path>packages/ember-glimmer/lib/protocol-for-url.js
<add>/* globals module, URL */
<add>
<add>import { environment as emberEnvironment } from 'ember-environment';
<add>
<add>let nodeURL;
<add>let parsingNode;
<add>
<add>export default function installProtocolForURL(environment) {
<add> let protocol;
<add>
<add> if (emberEnvironment.hasDOM) {
<add> protocol = browserProtocolForURL.call(environment, 'foobar:baz');
<add> }
<add>
<add> // Test to see if our DOM implementation parses
<add> // and normalizes URLs.
<add> if (protocol === 'foobar:') {
<add> // Swap in the method that doesn't do this test now that
<add> // we know it works.
<add> environment.protocolForURL = browserProtocolForURL;
<add> } else if (typeof URL === 'object') {
<add> // URL globally provided, likely from FastBoot's sandbox
<add> nodeURL = URL;
<add> environment.protocolForURL = nodeProtocolForURL;
<add> } else if (typeof module === 'object' && typeof module.require === 'function') {
<add> // Otherwise, we need to fall back to our own URL parsing.
<add> // Global `require` is shadowed by Ember's loader so we have to use the fully
<add> // qualified `module.require`.
<add> nodeURL = module.require('url');
<add> environment.protocolForURL = nodeProtocolForURL;
<add> } else {
<add> throw new Error("Could not find valid URL parsing mechanism for URL Sanitization");
<add> }
<add>}
<add>
<add>function browserProtocolForURL(url) {
<add> if (!parsingNode) {
<add> parsingNode = document.createElement('a');
<add> }
<add>
<add> parsingNode.href = url;
<add> return parsingNode.protocol;
<add>}
<add>
<add>function nodeProtocolForURL(url) {
<add> let protocol = null;
<add> if (typeof url === 'string') {
<add> protocol = nodeURL.parse(url).protocol;
<add> }
<add> return (protocol === null) ? ':' : protocol;
<add>} | 2 |
Text | Text | improve write style consistency | 86454cbd139d21b5646bb704971b6a27a32b379d | <ide><path>CHANGELOG.md
<ide> repository and therefore can be seen as an extension to v0.11.
<ide>
<ide> - The V8 JavaScript engine bundled with io.js was upgraded dramatically, from version 3.14.5.9 in Node.js v0.10.35 and 3.26.33 in Node.js v0.11.14 to 3.31.74.1 for io.js v1.0.0. This brings along many fixes and performance improvements, as well as additional support for new ES6 language features! For more information on this, check out [the io.js ES6 page](https://iojs.org/es6.html).
<ide> - Other bundled technologies were upgraded:
<del> - libuv: 0.10.30 to 1.2.0
<add> - c-ares: 1.9.0-DEV to 1.10.0-DEV
<ide> - http_parser: 1.0 to 2.3
<del> - openssl: 1.0.1j to 1.0.1k
<add> - libuv: 0.10.30 to 1.2.0
<ide> - npm: 1.4.28 to 2.1.18
<del> - c-ares: 1.9.0-DEV to 1.10.0-DEV
<add> - openssl: 1.0.1j to 1.0.1k
<ide> - punycode: 1.2.0 to 1.3.2.
<ide> - Performance and stability improvements on all platforms.
<ide>
<ide> ### buffer
<ide>
<ide> https://iojs.org/api/buffer.html
<ide>
<del>- Added `new Buffer(otherBuffer)` constructor.
<del>- Changed the output of `buffer.toJSON()` to not be the same as an array. Instead it is an object specifically tagged as a buffer, which can be recovered by passing it to (a new overload of) the `Buffer` constructor.
<add>- Added `buf.writeUIntLE`, `buf.writeUIntBE`, `buf.writeIntLE`, `buf.writeIntBE`, `buf.readUIntLE`, `buf.readUIntBE`, `buf.readIntLE` and `buf.readIntBE` methods that read and write value up to 6 bytes.
<ide> - Added `Buffer.compare()` which does a `memcmp()` on two Buffer instances. Instances themselves also have a `compare()`.
<ide> - Added `buffer.equals()` that checks equality of Buffers by their contents.
<del>- `SlowBuffer`'s semantics were tweaked.
<del>- Added `buf.writeUIntLE`, `buf.writeUIntBE`, `buf.writeIntLE`, `buf.writeIntBE`, `buf.readUIntLE`, `buf.readUIntBE`, `buf.readIntLE` and `buf.readIntBE` that read and write value up to 6 bytes.
<add>- Added `new Buffer(otherBuffer)` constructor.
<add>- Tweaked `SlowBuffer`'s semantics.
<add>- Updated the output of `buffer.toJSON()` to not be the same as an array. Instead it is an object specifically tagged as a buffer, which can be recovered by passing it to (a new overload of) the `Buffer` constructor.
<ide>
<ide> ### child_process
<ide>
<ide> https://iojs.org/api/child_process.html
<ide>
<del>- Added synchronous counterparts for the child process functions: `child_process.spawnSync`, `child_process.execSync`, and `child_process.execFileSync`.
<ide> - Added a `shell` option to `child_process.exec`.
<add>- Added synchronous counterparts for the child process functions: `child_process.spawnSync`, `child_process.execSync`, and `child_process.execFileSync`.
<ide> - Added the path to any `ENOENT` errors, for easier debugging.
<ide>
<ide> ### console
<ide>
<ide> https://iojs.org/api/console.html
<ide>
<del>- Added an options parameter to `console.dir`.
<add>- Added an `options` parameter to `console.dir`.
<ide>
<ide> ### cluster
<ide>
<ide> https://iojs.org/api/cluster.html
<ide>
<ide> (**DETAILS TO BE ADDED HERE**)
<ide>
<del>- Cluster now uses round-robin load balancing by default on non-Windows platforms. The scheduling policy is configurable however.
<add>- Updated `cluster` to use round-robin load balancing by default on non-Windows platforms. The scheduling policy is configurable however.
<ide>
<ide> ### crypto
<ide>
<ide> https://iojs.org/api/crypto.html
<ide>
<del>- Setting and getting of authentication tags and setting additional authentication data is now possible for use with ciphers such as AES-GCM.
<del>- `Sign.sign()` now allows you to pass in a passphrase for decrypting the signing key.
<del>- `DiffieHellman` now supports custom generator values (defaulting to 2 for backwards compatibility).
<add>- Added support for custom generator values to `DiffieHellman` (defaulting to 2 for backwards compatibility).
<add>- Added support for custom pbkdf2 digest methods.
<ide> - Added support for elliptic curve-based Diffie-Hellman.
<del>- Added support for RSA public encryption and private decryption {rephrase this maybe}
<del>- Custom pbkdf2 digest methods
<del>- OpenSSL engine support
<del>- Support for private key passphrase in every method that accepts it
<add>- Added support for loading and setting the engine for some/all OpenSSL functions.
<add>- Added support for passing in a passphrase for decrypting the signing key to `Sign.sign()`.
<add>- Added support for private key passphrase in every method that accepts it.
<add>- Added support for RSA public/private encryption/decryption functionality.
<add>- Added support for setting and getting of authentication tags and setting additional authentication data when using ciphers such as AES-GCM.
<ide>
<ide> ### dgram
<ide>
<ide> https://iojs.org/api/dgram.html
<ide>
<del>- Made it possible to receive empty UDP packets.
<add>- Added support for receiving empty UDP packets.
<ide>
<ide> ### dns
<ide>
<ide> https://iojs.org/api/dns.html
<ide>
<del>- Added `dns.resolveSoa`, `dns.getServers`, and `dns.setServers`.
<del>- Error messages include the hostname when available.
<del>- More consistent error handling.
<add>- Added `dns.resolveSoa`, `dns.getServers`, and `dns.setServers` methods.
<add>- Added `hostname` on error messages when available.
<add>- Improved error handling consistency.
<ide>
<ide> ### events
<ide>
<ide> https://iojs.org/api/events.html
<ide>
<del>- `require("events")` now returns the `EventEmitter` constructor. Which means the module could also be used like this `var EventEmitter = require('events')` instead of `var EventEmitter = require('events').EventEmitter`.
<del>- `ee.setMaxListeners` now returns `this` to support chaining.
<add>- Added chaining support to `EventEmitter.setMaxListeners`.
<add>- Updated `require('events')` to return the `EventEmitter` constructor, allowing the module to be used like `var EventEmitter = require('events')` instead of `var EventEmitter = require('events').EventEmitter`.
<ide>
<ide> ### fs
<ide>
<ide> https://iojs.org/api/fs.html
<ide>
<del>- Missing callbacks will now cause errors to be thrown, instead of just printed.
<ide> - Added `fs.access`, and deprecated `fs.exists`. Please read the documentation carefully.
<del>- Added option to `fs.watch` for recursive sub-directory support, on OS X only.
<del>- Setting the `NODE_DEBUG` environment variable will give more informative errors that show the call site of the `fs` call.
<add>- Added more informative errors and method call site details when the `NODE_DEBUG` environment is set to ease debugging.
<add>- Added option to `fs.watch` for recursive sub-directory support (OS X only).
<add>- Fixed missing callbacks errors just being printed instead of thrown.
<ide>
<ide> ### http
<ide>
<ide> https://iojs.org/api/http.html
<ide>
<del>- Proper Keep-Alive behavior (**DETAILS TO BE ADDED**)
<del>- Added 308 status code; see RFC 7238.
<del>- Stopped defaulting `DELETE` and `OPTIONS` to chunked encoding.
<add>- Added support for `response.write` and `response.end` to receive a callback to know when the operation completes.
<add>- Added support for 308 status code (see RFC 7238).
<add>- Added `http.METHODS` array, listing the HTTP methods supported by the parser.
<add>- Added `request.flush` method.
<add>- Added `response.getHeader('header')` method that may be used before headers are flushed.
<ide> - Added `response.statusMessage` property.
<del>- Added `http.METHODS` array, listing the HTTP methods suported by the parser.
<del>- Added `response.getHeader("header")` method that may be used before headers are flushed.
<del>- `response.write` and `response.end` now take a callback to know when the operation completes.
<del>- Added `request.flush()`.
<add>- Fixed Keep-Alive behavior (**DETAILS TO BE ADDED**)
<add>- Removed default chunked encoding on `DELETE` and `OPTIONS`.
<ide>
<ide> ### os
<ide>
<ide> https://iojs.org/api/os.html
<ide>
<del>- `os.networkInterfaces()` now includes MAC addresses and netmasks as well as scope IDs for IPv6 addresses in its output.
<del>- On Windows, `os.tmpdir()` now uses the `%SystemRoot%` or `%WINDIR%` environment variables instead of the hardcoded value of `c:\windows` when determining the temporary directory location.
<add>- Added MAC addresses, netmasks and scope IDs for IPv6 addresses to `os.networkInterfaces` method output.
<add>- Updated `os.tmpdir` on Windows to use the `%SystemRoot%` or `%WINDIR%` environment variables instead of the hard-coded value of `c:\windows` when determining the temporary directory location.
<ide>
<ide> ### path
<ide>
<ide> https://iojs.org/api/path.html
<ide>
<del>- Added `path.isAbsolute` and `path.parse`.
<add>- Added `path.isAbsolute` and `path.parse` methods.
<ide> - Added `path.win32` and `path.posix` objects that contain platform-specific versions of the various `path` functions.
<del>- `path.join` is now faster.
<add>- Improved `path.join` performance.
<ide>
<ide> ### process
<ide>
<ide> https://iojs.org/api/process.html
<ide>
<del>- Added `process.mainModule` and `process.exitCode`.
<ide> - Added `beforeExit` event.
<add>- Added `process.mainModule` and `process.exitCode`.
<ide>
<ide> ### querystring
<ide>
<ide> https://iojs.org/api/querystring.html
<ide>
<ide> - Added the ability to pass custom versions of `encodeURIComponent` and `decodeURIComponent` when stringifying or parsing a querystring.
<del>- Several bug-fixes to the formatting of query strings in edge cases.
<add>- Fixed several issues with the formatting of query strings in edge cases.
<ide>
<ide> ### smalloc
<ide>
<ide> unnoticed by the majority of stream consumers and implementers.
<ide>
<ide> #### Readable streams
<ide>
<del>The distinction between "flowing" and "non-flowing" modes has been refined. Entering "flowing" mode is
<del>no longer an irreversible operation—it is possible to return to "non-flowing" mode from "flowing" mode.
<del>Additionally, the two modes now flow through the same machinery instead of replacing methods. Any time
<add>The distinction between "flowing" and "non-flowing" modes has been refined. Entering "flowing" mode is
<add>no longer an irreversible operation—it is possible to return to "non-flowing" mode from "flowing" mode.
<add>Additionally, the two modes now flow through the same machinery instead of replacing methods. Any time
<ide> data is returned as a result of a `.read` call that data will *also* be emitted on the `"data"` event.
<ide>
<ide> As before, adding a listener for the `"readable"` or `"data"` event will start flowing the stream; as
<ide> For a detailed overview of how streams3 interact, [see this diagram](https://clo
<ide>
<ide> https://iojs.org/api/timers.html
<ide>
<del>- `process.maxTickDepth` has been removed, allowing `process.nextTick` to be used recursively without limit.
<del>- `setImmediate` now processes the full queue each turn of the event loop, instead of one per queue.
<add>- Removed `process.maxTickDepth`, allowing `process.nextTick` to be used recursively without limit.
<add>- Updated `setImmediate` to process the full queue each turn of the event loop, instead of one per queue.
<ide>
<ide> ### tls
<ide>
<ide> https://iojs.org/api/tls.html
<ide>
<del>- Removed SSLv2 and SSLv3 support.
<del>- Implemented TLS streams in C++, boosting their performance.
<del>- ECDSA/ECDHE cipher support.
<add>- Added `detailed` boolean flag to `getPeerCertificate` to return detailed certificate information (with raw DER bytes).
<add>- Added `renegotiate(options, callback)` method for session renegotiation.
<add>- Added `setMaxSendFragment` method for varying TLS fragment size.
<ide> - Added a `dhparam` option for DH ciphers.
<ide> - Added a `ticketKeys` option for TLS ticket AES encryption keys setup.
<del>- Multi-key server support (for example, ECDSA+RSA server).
<del>- Async SNI callback
<del>- Async OCSP-stapling callback
<del>- Async session storage events
<del>- Optional `checkServerIdentity` callback for manual certificate validation in user-land
<del>- `.getPeerCertificate(true)` - to return detailed certificate information (with raw DER bytes)
<add>- Added async OCSP-stapling callback.
<add>- Added async session storage events.
<add>- Added async SNI callback.
<add>- Added multi-key server support (for example, ECDSA+RSA server).
<add>- Added optional callback to `checkServerIdentity` for manual certificate validation in user-land.
<add>- Added support for ECDSA/ECDHE cipher.
<add>- Implemented TLS streams in C++, boosting their performance.
<ide> - Moved `createCredentials` to `tls` and renamed it to `createSecureContext`.
<del>- `.setMaxSendFragment()` method for varying TLS fragment size
<del>- `.renegotiate(options, callback)` method for session renegotiation
<add>- Removed SSLv2 and SSLv3 support.
<ide>
<ide> ### url
<ide>
<ide> https://iojs.org/api/url.html
<ide>
<del>- Improved parsing speed.
<ide> - Added support for `path` option in `url.format`, which encompasses `pathname`, `query`, and `search`.
<del>- Better escaping of certain characters.
<add>- Improved escaping of certain characters.
<add>- Improved parsing speed.
<ide>
<ide> ### util
<ide>
<ide> https://iojs.org/api/util.html
<ide>
<del>- `util.format` received several changes:
<add>- Added `util.debuglog`.
<add>- Added a plethora of new type-testing methods. See [the docs](https://iojs.org/api/util.html).
<add>- Updated `util.format` to receive several changes:
<ide> - `-0` is now displayed as such, instead of as `0`.
<ide> - Anything that is `instanceof Error` is now formatted as an error.
<add> - Circular references in JavaScript objects are now handled for the `%j` specifier.
<ide> - Custom `inspect` functions are now allowed to return an object.
<ide> - Custom `inspect` functions now receive any arguments passed to `util.inspect`.
<del> - Circular references in JavaScript objects are now handled for the `%j` specifier.
<del>- A plethora of new type-testing methods were added. See [the docs](https://iojs.org/api/util.html).
<del>- Added `util.debuglog`.
<ide>
<ide> ## v8
<ide>
<ide> https://iojs.org/api/v8.html
<ide>
<ide> https://iojs.org/api/vm.html
<ide>
<del>The vm module has been rewritten to work better, based on the excellent [Contextify](https://github.com/brianmcd/contextify) native module. All of the functionality of Contextify is now in core, with improvements!
<add>The `vm` module has been rewritten to work better, based on the excellent [Contextify](https://github.com/brianmcd/contextify) native module. All of the functionality of Contextify is now in core, with improvements!
<ide>
<del>- There is no longer any error-prone copying of properties back and forth between the supplied sandbox object and the global that appears inside the scripts run by the `vm` module. Instead, the supplied sandbox object is used directly as the global.
<del>- `vm.createContext(sandbox)` now "contextifies" sandbox, making it suitable for use as a global for `vm` scripts, and then returns it. It no longer creates a separate context object.
<del>- The new `vm.isContext(obj)` method determines whether `obj` has been contextified.
<del>- The new `vm.runInDebugContext(code)` method compiles and executes `code` inside the V8 debug context.
<del>- Most of the `vm` and `vm.Script` methods now take an options object, allowing you to configure a timeout for the script, the error display behavior, and sometimes the filename (for stack traces).
<add>- Added `vm.isContext(object)` method to determine whether `object` has been contextified.
<add>- Added `vm.runInDebugContext(code)` method to compile and execute `code` inside the V8 debug context.
<add>- Updated `vm.createContext(sandbox)` to "contextify" the sandbox, making it suitable for use as a global for `vm` scripts, and then return it. It no longer creates a separate context object.
<add>- Updated most `vm` and `vm.Script` methods to accept an `options` object, allowing you to configure a timeout for the script, the error display behavior, and sometimes the filename (for stack traces).
<add>- Updated the supplied sandbox object to be used directly as the global, remove error-prone copying of properties back and forth between the supplied sandbox object and the global that appears inside the scripts run by the `vm` module.
<ide>
<del>For more information, see the vm documentation linked above.
<add>For more information, see the `vm` documentation linked above.
<ide>
<ide> ### zlib
<ide>
<ide> https://iojs.org/api/zlib.html
<ide>
<del>- `zlib.params` allows for dynamically updating the compression level and strategy when deflating.
<del>- `zlib.flush` allows specifying a particular flush method (defaulting to `Z_FULL_FLUSH`).
<add>- Added support for `zlib.flush` to specify a particular flush method (defaulting to `Z_FULL_FLUSH`).
<add>- Added support for `zlib.params` to dynamically update the compression level and strategy when deflating.
<ide> - Added synchronous versions of the zlib methods.
<ide>
<ide> ### C++ API Changes
<ide> In general it is recommended that you use [NAN](https://github.com/rvagg/nan) as
<ide>
<ide> #### V8 highlights
<ide>
<del>- Exposed method signature has changed from `Handle<Value> Method(const Arguments& args)` to `void Method(const v8::FunctionCallbackInfo<Value>& args)` with the newly introduced `FunctionCallbackInfo` also taking the return value via `args.GetReturnValue().Set(value)` instead of `scope.Close(value)`, `Arguments` has been removed
<del>- Exposed setter signature has changed from `void Setter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<void>& args)`
<del>- Exposed getter signature has changed from `void Getter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<Value>& args)`
<del>- Exposed property setter signature has changed from `Handle<Value> Setter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<Value>& args)`
<del>- Exposed property getter signature has changed from `Handle<Value> Getter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<Value>& args)`
<del>- Similar changes have been made to property enumerators, property deleters, property query, index getter, index setter, index enumerator, index deleter, index query
<del>- V8 objects instantiated in C++ now require an `Isolate*` argument as the first argument. In most cases it is OK to simply pass `v8::Isolate::GetCurrent()`, e.g. `Date::New(Isolate::GetCurrent(), time)`, or `String::NewFromUtf8(Isolate::GetCurrent(), "foobar")`
<del>- `HandleScope scope` now requires an `Isolate*` argument, i.e. `HandleScope scope(isolate)`, in most cases `v8::Isolate::GetCurrent()` is OK
<del>- Similar changes have been made to `Locker` and `Unlocker`
<del>- V8 objects that need to "escape" a scope should be enclosed in a `EscapableHandleScope` rather than a `HandleScope` and should be returned with `scope.Escape(value)`
<del>- Exceptions are now thrown from isolates with `isolate->ThrowException(ExceptionObject)`
<del>- `Context::GetCurrent()` must now be done on an isolate, e.g. `Isolate::GetCurrent()->GetCurrentContext()`
<del>- `String::NewSymbol()` has been removed, use plain strings instead
<del>- `String::New()` has been removed, use `String::NewFromUtf8()` instead
<del>- `Persistent` objects no longer inherit from `Handle` and cannot be instantiated with another object. Instead, the `Persistent` should simply be declared, e.g. `Persistent<Type> handle` and then have a `Local` assigned to it with `handle.Reset(isolate, value)`. To get a `Local` from a `Persistent` you must instantiate it w as the argument, i.e. `Local::New(Isolate*, Persistent)`.
<add>- Exposed method signature has changed from `Handle<Value> Method(const Arguments& args)` to `void Method(const v8::FunctionCallbackInfo<Value>& args)` with the newly introduced `FunctionCallbackInfo` also taking the return value via `args.GetReturnValue().Set(value)` instead of `scope.Close(value)`, `Arguments` has been removed.
<add>- Exposed setter signature has changed from `void Setter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<void>& args)`.
<add>- Exposed getter signature has changed from `void Getter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<Value>& args)`.
<add>- Exposed property setter signature has changed from `Handle<Value> Setter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<Value>& args)`.
<add>- Exposed property getter signature has changed from `Handle<Value> Getter(Local<String> property, Local<Value> value, const v8::AccessorInfo& args)` `void Setter(Local<String> property, Local<Value> value, const v8::PropertyCallbackInfo<Value>& args)`.
<add>- Similar changes have been made to property enumerators, property deleters, property query, index getter, index setter, index enumerator, index deleter, index query.
<add>- V8 objects instantiated in C++ now require an `Isolate*` argument as the first argument. In most cases it is OK to simply pass `v8::Isolate::GetCurrent()`, e.g. `Date::New(Isolate::GetCurrent(), time)`, or `String::NewFromUtf8(Isolate::GetCurrent(), "foobar")`.
<add>- `HandleScope scope` now requires an `Isolate*` argument, i.e. `HandleScope scope(isolate)`, in most cases `v8::Isolate::GetCurrent()` is OK.
<add>- Similar changes have been made to `Locker` and `Unlocker`.
<add>- V8 objects that need to "escape" a scope should be enclosed in a `EscapableHandleScope` rather than a `HandleScope` and should be returned with `scope.Escape(value)`.
<add>- Exceptions are now thrown from isolates with `isolate->ThrowException(ExceptionObject)`.
<add>- `Context::GetCurrent()` must now be done on an isolate, e.g. `Isolate::GetCurrent()->GetCurrentContext()`.
<add>- `String::NewSymbol()` has been removed, use plain strings instead.
<add>- `String::New()` has been removed, use `String::NewFromUtf8()` instead.
<add>- `Persistent` objects no longer inherit from `Handle` and cannot be instantiated with another object. Instead, the `Persistent` should simply be declared, e.g. `Persistent<Type> handle` and then have a `Local` assigned to it with `handle.Reset(isolate, value)`. To get a `Local` from a `Persistent` you must instantiate it as the argument, i.e. `Local::New(Isolate*, Persistent)`.
<ide>
<ide> #### Node / io.js
<ide>
<del>- `node::Buffer::New()` now returns a `Handle` directly so you no longer need to fetch the `handle_` property.
<del>- `node::MakeCallback()` now requires an `Isolate*` as the first argument. Generally `Isolate::GetCurrent()` will be OK for this.
<add>- Updated `node::Buffer::New()` to return a `Handle` directly so you no longer need to fetch the `handle_` property.
<add>- Updated `node::MakeCallback()` to require an `Isolate*` as the first argument. Generally `Isolate::GetCurrent()` will be OK for this.
<ide>
<ide>
<ide> --------------------------------------
<ide>
<del>**The ChangeLog below was inherited from joyent/node prior to the io.js fork.**
<add>**The changelog below was inherited from joyent/node prior to the io.js fork.**
<ide>
<ide>
<ide> ## 2014.09.24, Version 0.11.14 (Unstable)
<ide> https://github.com/iojs/io.js/commit/f711d5343b29d1e72e87107315708e40951a7826
<ide> ## 2010.04.29, Version 0.1.93
<ide>
<ide> https://github.com/iojs/io.js/commit/557ba6bd97bad3afe0f9bd3ac07efac0a39978c1
<del>
<add>
<ide> * Fixed no 'end' event on long chunked HTTP messages
<ide> https://github.com/joyent/node/issues/77
<del>
<add>
<ide> * Remove legacy modules http_old and tcp_old
<ide> * Support DNS MX queries (Jérémy Lal)
<del>
<add>
<ide> * Fix large socket write (tlb@tlb.org)
<ide> * Fix child process exit codes (Felix Geisendörfer)
<del>
<add>
<ide> * Allow callers to disable PHP/Rails style parameter munging in
<ide> querystring.stringify (Thomas Lee)
<del>
<add>
<ide> * Upgrade V8 to 2.2.6
<ide>
<ide> ## 2010.04.23, Version 0.1.92
<ide>
<ide> https://github.com/iojs/io.js/commit/caa828a242f39b6158084ef4376355161c14fe34
<del>
<add>
<ide> * OpenSSL support. Still undocumented (see tests). (Rhys Jones)
<ide> * API: Unhandled 'error' events throw.
<del>
<add>
<ide> * Script class with eval-function-family in binding('evals') plus tests.
<ide> (Herbert Vojcik)
<del>
<add>
<ide> * stream.setKeepAlive (Julian Lamb)
<ide> * Bugfix: Force no body on http 204 and 304
<del>
<add>
<ide> * Upgrade Waf to 1.5.16, V8 to 2.2.4.2
<ide>
<ide> ## 2010.04.15, Version 0.1.91
<ide>
<ide> https://github.com/iojs/io.js/commit/311d7dee19034ff1c6bc9098c36973b8d687eaba
<del>
<add>
<ide> * Add incoming.httpVersion
<ide> * Object.prototype problem with C-Ares binding
<del>
<add>
<ide> * REPL can be run from multiple different streams. (Matt Ranney)
<ide> * After V8 heap is compact, don't use a timer every 2 seconds.
<del>
<add>
<ide> * Improve nextTick implementation.
<ide> * Add primative support for Upgrading HTTP connections.
<ide> (See commit log for docs 760bba5)
<del>
<add>
<ide> * Add timeout and maxBuffer options to child_process.exec
<ide> * Fix bugs.
<del>
<add>
<ide> * Upgrade V8 to 2.2.3.1
<ide>
<ide> ## 2010.04.09, Version 0.1.90
<ide>
<ide> https://github.com/iojs/io.js/commit/07e64d45ffa1856e824c4fa6afd0442ba61d6fd8
<del>
<add>
<ide> * Merge writing of networking system (net2)
<ide> - New Buffer object for binary data.
<ide> - Support UNIX sockets, Pipes
<ide> - Uniform stream API
<ide> - Currently no SSL
<ide> - Legacy modules can be accessed at 'http_old' and 'tcp_old'
<del>
<add>
<ide> * Replace udns with c-ares. (Krishna Rajendran)
<ide> * New documentation system using Markdown and Ronn
<ide> (Tim Caswell, Micheil Smith)
<del>
<add>
<ide> * Better idle-time GC
<ide> * Countless small bug fixes.
<del>
<add>
<ide> * Upgrade V8 to 2.2.X, WAF 1.5.15
<ide>
<ide> ## 2010.03.19, Version 0.1.33
<ide>
<ide> https://github.com/iojs/io.js/commit/618296ef571e873976f608d91a3d6b9e65fe8284
<del>
<add>
<ide> * Include lib/ directory in node executable. Compile on demand.
<ide> * evalcx clean ups (Isaac Z. Schlueter, Tim-Smart)
<del>
<add>
<ide> * Various fixes, clean ups
<ide> * V8 upgraded to 2.1.5
<ide>
<ide> ## 2010.03.12, Version 0.1.32
<ide>
<ide> https://github.com/iojs/io.js/commit/61c801413544a50000faa7f58376e9b33ba6254f
<del>
<add>
<ide> * Optimize event emitter for single listener
<ide> * Add process.evalcx, require.registerExtension (Tim Smart)
<del>
<add>
<ide> * Replace --cflags with --vars
<ide> * Fix bugs in fs.create*Stream (Felix Geisendörfer)
<del>
<add>
<ide> * Deprecate process.mixin, process.unloop
<ide> * Remove the 'Error: (no message)' exceptions, print stack
<ide> trace instead
<del>
<add>
<ide> * INI parser bug fixes (Isaac Schlueter)
<ide> * FreeBSD fixes (Vanilla Hsu)
<del>
<add>
<ide> * Upgrade to V8 2.1.3, WAF 1.5.14a, libev
<ide>
<ide> ## 2010.03.05, Version 0.1.31
<ide>
<ide> https://github.com/iojs/io.js/commit/39b63dfe1737d46a8c8818c92773ef181fd174b3
<del>
<add>
<ide> * API: - Move process.watchFile into fs module
<ide> - Move process.inherits to sys
<del>
<add>
<ide> * Improve Solaris port
<ide> * tcp.Connection.prototype.write now returns boolean to indicate if
<ide> argument was flushed to the kernel buffer.
<del>
<add>
<ide> * Added fs.link, fs.symlink, fs.readlink, fs.realpath
<ide> (Rasmus Andersson)
<del>
<add>
<ide> * Add setgid,getgid (James Duncan)
<ide> * Improve sys.inspect (Benjamin Thomas)
<del>
<add>
<ide> * Allow passing env to child process (Isaac Schlueter)
<ide> * fs.createWriteStream, fs.createReadStream (Felix Geisendörfer)
<del>
<add>
<ide> * Add INI parser (Rob Ellis)
<ide> * Bugfix: fs.readFile handling encoding (Jacek Becela)
<del>
<add>
<ide> * Upgrade V8 to 2.1.2
<ide>
<ide> ## 2010.02.22, Version 0.1.30
<ide>
<ide> https://github.com/iojs/io.js/commit/bb0d1e65e1671aaeb21fac186b066701da0bc33b
<del>
<add>
<ide> * Major API Changes
<ide> - Promises removed. See
<ide> http://groups.google.com/group/nodejs/msg/426f3071f3eec16b
<ide> https://github.com/iojs/io.js/commit/bb0d1e65e1671aaeb21fac186b066701da0bc33b
<ide> renamed to pause() and resume()
<ide> - http.ServerResponse.prototype.sendHeader() renamed to
<ide> writeHeader(). Now accepts reasonPhrase.
<del>
<add>
<ide> * Compact garbage on idle.
<ide> * Configurable debug ports, and --debug-brk (Zoran Tomicic)
<del>
<add>
<ide> * Better command line option parsing (Jeremy Ashkenas)
<ide> * Add fs.chmod (Micheil Smith), fs.lstat (Isaac Z. Schlueter)
<del>
<add>
<ide> * Fixes to process.mixin (Rasmus Andersson, Benjamin Thomas)
<ide> * Upgrade V8 to 2.1.1
<ide>
<ide> ## 2010.02.17, Version 0.1.29
<ide>
<ide> https://github.com/iojs/io.js/commit/87d5e5b316a4276bcf881f176971c1a237dcdc7a
<del>
<add>
<ide> * Major API Changes
<ide> - Remove 'file' module
<ide> - require('posix') -----------------> require('fs')
<ide> https://github.com/iojs/io.js/commit/87d5e5b316a4276bcf881f176971c1a237dcdc7a
<ide> takes an argument. Add the 'response' listener manually.
<ide> - Allow strings for the flag argument to fs.open
<ide> ("r", "r+", "w", "w+", "a", "a+")
<del>
<add>
<ide> * Added multiple arg support for sys.puts(), print(), etc.
<ide> (tj@vision-media.ca)
<del>
<add>
<ide> * sys.inspect(Date) now shows the date value (Mark Hansen)
<ide> * Calculate page size with getpagesize for armel (Jérémy Lal)
<del>
<add>
<ide> * Bugfix: stderr flushing.
<ide> * Bugfix: Promise late chain (Yuichiro MASUI)
<del>
<add>
<ide> * Bugfix: wait() on fired promises
<ide> (Felix Geisendörfer, Jonas Pfenniger)
<del>
<add>
<ide> * Bugfix: Use InstanceTemplate() instead of PrototypeTemplate() for
<ide> accessor methods. Was causing a crash with Eclipse debugger.
<ide> (Zoran Tomicic)
<del>
<add>
<ide> * Bugfix: Throw from connection.connect if resolving.
<ide> (Reported by James Golick)
<ide>
<ide> ## 2010.02.09, Version 0.1.28
<ide>
<ide> https://github.com/iojs/io.js/commit/49de41ef463292988ddacfb01a20543b963d9669
<del>
<add>
<ide> * Use Google's jsmin.py which can be used for evil.
<ide> * Add posix.truncate()
<del>
<add>
<ide> * Throw errors from server.listen()
<ide> * stdio bugfix (test by Mikeal Rogers)
<del>
<add>
<ide> * Module system refactor (Felix Geisendörfer, Blaine Cook)
<ide> * Add process.setuid(), getuid() (Michael Carter)
<del>
<add>
<ide> * sys.inspect refactor (Tim Caswell)
<ide> * Multipart library rewrite (isaacs)
<ide>
<ide> ## 2010.02.03, Version 0.1.27
<ide>
<ide> https://github.com/iojs/io.js/commit/0cfa789cc530848725a8cb5595224e78ae7b9dd0
<del>
<add>
<ide> * Implemented __dirname (Felix Geisendörfer)
<ide> * Downcase process.ARGV, process.ENV, GLOBAL
<ide> (now process.argv, process.env, global)
<del>
<add>
<ide> * Bug Fix: Late promise promise callbacks firing
<ide> (Felix Geisendörfer, Jonas Pfenniger)
<del>
<add>
<ide> * Make assert.AssertionError instance of Error
<ide> * Removed inline require call for querystring
<ide> (self@cloudhead.net)
<del>
<add>
<ide> * Add support for MX, TXT, and SRV records in DNS module.
<ide> (Blaine Cook)
<del>
<add>
<ide> * Bugfix: HTTP client automatically reconnecting
<ide> * Adding OS X .dmg build scripts. (Standa Opichal)
<del>
<add>
<ide> * Bugfix: ObjectWrap memory leak
<ide> * Bugfix: Multipart handle Content-Type headers with charset
<ide> (Felix Geisendörfer)
<del>
<add>
<ide> * Upgrade http-parser to fix header overflow attack.
<ide> * Upgrade V8 to 2.1.0
<del>
<add>
<ide> * Various other bug fixes, performance improvements.
<ide>
<ide> ## 2010.01.20, Version 0.1.26
<ide>
<ide> https://github.com/iojs/io.js/commit/da00413196e432247346d9e587f8c78ce5ceb087
<del>
<add>
<ide> * Bugfix, HTTP eof causing crash (Ben Williamson)
<ide> * Better error message on SyntaxError
<del>
<add>
<ide> * API: Move Promise and EventEmitter into 'events' module
<ide> * API: Add process.nextTick()
<del>
<add>
<ide> * Allow optional params to setTimeout, setInterval
<ide> (Micheil Smith)
<del>
<add>
<ide> * API: change some Promise behavior (Felix Geisendörfer)
<ide> - Removed Promise.cancel()
<ide> - Support late callback binding
<ide> - Make unhandled Promise errors throw an exception
<del>
<add>
<ide> * Upgrade V8 to 2.0.6.1
<ide> * Solaris port (Erich Ocean)
<ide>
<ide> ## 2010.01.09, Version 0.1.25
<ide>
<ide> https://github.com/iojs/io.js/commit/39ca93549af91575ca9d4cbafd1e170fbcef3dfa
<del>
<add>
<ide> * sys.inspect() improvements (Tim Caswell)
<ide> * path module improvements (isaacs, Benjamin Thomas)
<del>
<add>
<ide> * API: request.uri -> request.url
<ide> It is no longer an object, but a string. The 'url' module
<ide> was addded to parse that string. That is, node no longer
<ide> parses the request URL automatically.
<ide> require('url').parse(request.url)
<ide> is roughly equivlent to the old request.uri object.
<ide> (isaacs)
<del>
<add>
<ide> * Bugfix: Several libeio related race conditions.
<ide> * Better errors for multipart library (Felix Geisendörfer)
<del>
<add>
<ide> * Bugfix: Update node-waf version to 1.5.10
<ide> * getmem for freebsd (Vanilla Hsu)
<ide>
<ide> ## 2009.12.31, Version 0.1.24
<ide>
<ide> https://github.com/iojs/io.js/commit/642c2773a7eb2034f597af1cd404b9e086b59632
<del>
<add>
<ide> * Bugfix: don't chunk responses to HTTP/1.0 clients, even if
<ide> they send Connection: Keep-Alive (e.g. wget)
<del>
<add>
<ide> * Bugfix: libeio race condition
<ide> * Bugfix: Don't segfault on unknown http method
<del>
<add>
<ide> * Simplify exception reporting
<ide> * Upgrade V8 to 2.0.5.4
<ide>
<ide> ## 2009.12.22, Version 0.1.23
<ide>
<ide> https://github.com/iojs/io.js/commit/f91e347eeeeac1a8bd6a7b462df0321b60f3affc
<del>
<add>
<ide> * Bugfix: require("../blah") issues (isaacs)
<ide> * Bugfix: posix.cat (Jonas Pfenniger)
<del>
<add>
<ide> * Do not pause request for multipart parsing (Felix Geisendörfer)
<ide>
<ide> ## 2009.12.19, Version 0.1.22
<ide>
<ide> https://github.com/iojs/io.js/commit/a2d809fe902f6c4102dba8f2e3e9551aad137c0f
<del>
<add>
<ide> * Bugfix: child modules get wrong id with "index.js" (isaacs)
<ide> * Bugfix: require("../foo") cycles (isaacs)
<del>
<add>
<ide> * Bugfix: require() should throw error if module does.
<ide> * New URI parser stolen from Narwhal (isaacs)
<del>
<add>
<ide> * Bugfix: correctly check kqueue and epoll. (Rasmus Andersson)
<ide> * Upgrade WAF to 1.5.10
<del>
<add>
<ide> * Bugfix: posix.statSync() was crashing
<ide> * Statically define string symbols for performance improvement
<del>
<add>
<ide> * Bugfix: ARGV[0] weirdness
<ide> * Added superCtor to ctor.super_ instead superCtor.prototype.
<ide> (Johan Dahlberg)
<del>
<add>
<ide> * http-parser supports webdav methods
<ide> * API: http.Client.prototype.request() (Christopher Lenz)
<ide>
<ide> ## 2009.12.06, Version 0.1.21
<ide>
<ide> https://github.com/iojs/io.js/commit/c6affb64f96a403a14d20035e7fbd6d0ce089db5
<del>
<add>
<ide> * Feature: Add HTTP client TLS support (Rhys Jones)
<ide> * Bugfix: use --jobs=1 with WAF
<del>
<add>
<ide> * Bugfix: Don't use chunked encoding for 1.0 requests
<ide> * Bugfix: Duplicated header weren't handled correctly
<del>
<add>
<ide> * Improve sys.inspect (Xavier Shay)
<ide> * Upgrade v8 to 2.0.3
<del>
<add>
<ide> * Use CommonJS assert API (Felix Geisendörfer, Karl Guertin)
<ide>
<ide> ## 2009.11.28, Version 0.1.20
<ide>
<ide> https://github.com/iojs/io.js/commit/aa42c6790da8ed2cd2b72051c07f6251fe1724d8
<del>
<add>
<ide> * Add gnutls version to configure script
<ide> * Add V8 heap info to process.memoryUsage()
<del>
<add>
<ide> * process.watchFile callback has 2 arguments with the stat object
<ide> (choonkeat@gmail.com)
<ide>
<ide> ## 2009.11.28, Version 0.1.19
<ide>
<ide> https://github.com/iojs/io.js/commit/633d6be328708055897b72327b88ac88e158935f
<del>
<add>
<ide> * Feature: Initial TLS support for TCP servers and clients.
<ide> (Rhys Jones)
<del>
<add>
<ide> * Add options to process.watchFile()
<ide> * Add process.umask() (Friedemann Altrock)
<del>
<add>
<ide> * Bugfix: only detach timers when active.
<ide> * Bugfix: lib/file.js write(), shouldn't always emit errors or success
<ide> (onne@onnlucky.com)
<del>
<add>
<ide> * Bugfix: Memory leak in fs.write
<ide> (Reported by onne@onnlucky.com)
<del>
<add>
<ide> * Bugfix: Fix regular expressions detecting outgoing message headers.
<ide> (Reported by Elliott Cable)
<del>
<add>
<ide> * Improvements to Multipart parser (Felix Geisendörfer)
<ide> * New HTTP parser
<del>
<add>
<ide> * Upgrade v8 to 2.0.2
<ide>
<ide> ## 2009.11.17, Version 0.1.18
<ide>
<ide> https://github.com/iojs/io.js/commit/027829d2853a14490e6de9fc5f7094652d045ab8
<del>
<add>
<ide> * Feature: process.watchFile() process.unwatchFile()
<ide> * Feature: "uncaughtException" event on process
<ide> (Felix Geisendörfer)
<del>
<add>
<ide> * Feature: 'drain' event to tcp.Connection
<ide> * Bugfix: Promise.timeout() blocked the event loop
<ide> (Felix Geisendörfer)
<del>
<add>
<ide> * Bugfix: sendBody() and chunked utf8 strings
<ide> (Felix Geisendörfer)
<del>
<add>
<ide> * Supply the strerror as a second arg to the tcp.Connection close
<ide> event (Johan Sørensen)
<del>
<add>
<ide> * Add EventEmitter.removeListener (frodenius@gmail.com)
<ide> * Format JSON for inspecting objects (Felix Geisendörfer)
<del>
<add>
<ide> * Upgrade libev to latest CVS
<ide>
<ide> ## 2009.11.07, Version 0.1.17
<ide>
<ide> https://github.com/iojs/io.js/commit/d1f69ef35dac810530df8249d523add168e09f03
<del>
<add>
<ide> * Feature: process.chdir() (Brandon Beacher)
<ide> * Revert http parser upgrade. (b893859c34f05db5c45f416949ebc0eee665cca6)
<ide> Broke keep-alive.
<del>
<add>
<ide> * API: rename process.inherits to sys.inherits
<ide>
<ide> ## 2009.11.03, Version 0.1.16
<ide>
<ide> https://github.com/iojs/io.js/commit/726865af7bbafe58435986f4a193ff11c84e4bfe
<del>
<add>
<ide> * API: Use CommonJS-style module requiring
<ide> - require("/sys.js") becomes require("sys")
<ide> - require("circle.js") becomes require("./circle")
<ide> - process.path.join() becomes require("path").join()
<ide> - __module becomes module
<del>
<add>
<ide> * API: Many namespacing changes
<ide> - Move node.* into process.*
<ide> - Move node.dns into module "dns"
<ide> https://github.com/iojs/io.js/commit/726865af7bbafe58435986f4a193ff11c84e4bfe
<ide> For more information on the API changes see:
<ide> http://thread.gmane.org/gmane.comp.lang.javascript.nodejs/6
<ide> http://thread.gmane.org/gmane.comp.lang.javascript.nodejs/14
<del>
<add>
<ide> * Feature: process.platform, process.memoryUsage()
<ide> * Feature: promise.cancel() (Felix Geisendörfer)
<del>
<add>
<ide> * Upgrade V8 to 1.3.18
<ide>
<ide> ## 2009.10.28, Version 0.1.15
<ide>
<ide> https://github.com/iojs/io.js/commit/eca2de73ed786b935507fd1c6faccd8df9938fd3
<del>
<add>
<ide> * Many build system fixes (esp. for OSX users)
<ide> * Feature: promise.timeout() (Felix Geisendörfer)
<del>
<add>
<ide> * Feature: Added external interface for signal handlers, process.pid, and
<ide> process.kill() (Brandon Beacher)
<del>
<add>
<ide> * API: Rename node.libraryPaths to require.paths
<ide> * Bugfix: 'data' event for stdio should emit a string
<del>
<add>
<ide> * Large file support
<ide> * Upgrade http_parser
<del>
<add>
<ide> * Upgrade v8 to 1.3.16
<ide>
<ide> ## 2009.10.09, Version 0.1.14
<ide>
<ide> https://github.com/iojs/io.js/commit/b12c809bb84d1265b6a4d970a5b54ee8a4890513
<del>
<add>
<ide> * Feature: Improved addon builds with node-waf
<ide> * Feature: node.SignalHandler (Brandon Beacher)
<del>
<add>
<ide> * Feature: Enable V8 debugging (but still need to make a debugger)
<ide> * API: Rename library /utils.js to /sys.js
<del>
<add>
<ide> * Clean up Node's build system
<ide> * Don't use parseUri for HTTP server
<del>
<add>
<ide> * Remove node.pc
<ide> * Don't use /bin/sh to create child process except with exec()
<del>
<add>
<ide> * API: Add __module to reference current module
<ide> * API: Remove include() add node.mixin()
<del>
<add>
<ide> * Normalize http headers; "Content-Length" becomes "content-length"
<ide> * Upgrade V8 to 1.3.15
<ide>
<ide> ## 2009.09.30, Version 0.1.13
<ide>
<ide> https://github.com/iojs/io.js/commit/58493bb05b3da3dc8051fabc0bdea9e575c1a107
<del>
<add>
<ide> * Feature: Multipart stream parser (Felix Geisendörfer)
<ide> * API: Move node.puts(), node.exec() and others to /utils.js
<del>
<add>
<ide> * API: Move http, tcp libraries to /http.js and /tcp.js
<ide> * API: Rename node.exit() to process.exit()
<del>
<add>
<ide> * Bugfix: require() and include() should work in callbacks.
<ide> * Pass the Host header in http.cat calls
<del>
<add>
<ide> * Add warning when coroutine stack size grows too large.
<ide> * Enhance repl library (Ray Morgan)
<del>
<add>
<ide> * Bugfix: build script for
<ide> GCC 4.4 (removed -Werror in V8),
<ide> on Linux 2.4,
<ide> and with Python 2.4.4.
<del>
<add>
<ide> * Add read() and write() to /file.js to read and write
<ide> whole files at once.
<ide>
<ide> ## 2009.09.24, Version 0.1.12
<ide>
<ide> https://github.com/iojs/io.js/commit/2f56ccb45e87510de712f56705598b3b4e3548ec
<del>
<add>
<ide> * Feature: System modules, node.libraryPaths
<ide> * API: Remove "raw" encoding, rename "raws" to "binary".
<del>
<add>
<ide> * API: Added connection.setNoDElay() to disable Nagle algo.
<ide> * Decrease default TCP server backlog to 128
<del>
<add>
<ide> * Bugfix: memory leak involving node.fs.* methods.
<ide> * Upgrade v8 to 1.3.13
<ide>
<ide> ## 2009.09.18, Version 0.1.11
<ide>
<ide> https://github.com/iojs/io.js/commit/5ddc4f5d0c002bac0ae3d62fc0dc58f0d2d83ec4
<del>
<add>
<ide> * API: default to utf8 encoding for node.fs.cat()
<ide> * API: add node.exec()
<del>
<add>
<ide> * API: node.fs.read() takes a normal encoding parameter.
<ide> * API: Change arguments of emit(), emitSuccess(), emitError()
<del>
<add>
<ide> * Bugfix: node.fs.write() was stack allocating buffer.
<ide> * Bugfix: ReportException shouldn't forget the top frame.
<del>
<add>
<ide> * Improve buffering for HTTP outgoing messages
<ide> * Fix and reenable x64 macintosh build.
<del>
<add>
<ide> * Upgrade v8 to 1.3.11
<ide>
<ide> ## 2009.09.11, Version 0.1.10
<ide>
<ide> https://github.com/iojs/io.js/commit/12bb0d46ce761e3d00a27170e63b40408c15b558
<del>
<add>
<ide> * Feature: raw string encoding "raws"
<ide> * Feature: access to environ through "ENV"
<del>
<add>
<ide> * Feature: add isDirectory, isFile, isSocket, ... methods
<ide> to stats object.
<del>
<add>
<ide> * Bugfix: Internally use full paths when loading modules
<ide> this fixes a shebang loading problem.
<del>
<add>
<ide> * Bugfix: Add '--' command line argument for seperating v8
<ide> args from program args.
<del>
<add>
<ide> * Add man page.
<ide> * Add node-repl
<del>
<add>
<ide> * Upgrade v8 to 1.3.10
<ide>
<ide> ## 2009.09.05, Version 0.1.9
<ide>
<ide> https://github.com/iojs/io.js/commit/d029764bb32058389ecb31ed54a5d24d2915ad4c
<del>
<add>
<ide> * Bugfix: Compile on Snow Leopard.
<ide> * Bugfix: Malformed URIs raising exceptions.
<ide> ## 2009.09.04, Version 0.1.8
<ide>
<ide> https://github.com/iojs/io.js/commit/e6d712a937b61567e81b15085edba863be16ba96
<del>
<add>
<ide> * Feature: External modules
<ide> * Feature: setTimeout() for node.tcp.Connection
<del>
<add>
<ide> * Feature: add node.cwd(), node.fs.readdir(), node.fs.mkdir()
<ide> * Bugfix: promise.wait() releasing out of order.
<del>
<add>
<ide> * Bugfix: Asyncly do getaddrinfo() on Apple.
<ide> * Disable useless evcom error messages.
<del>
<add>
<ide> * Better stack traces.
<ide> * Built natively on x64.
<del>
<add>
<ide> * Upgrade v8 to 1.3.9
<ide> ## 2009.08.27, Version 0.1.7
<ide>
<ide> https://github.com/iojs/io.js/commit/f7acef9acf8ba8433d697ad5ed99d2e857387e4b
<del>
<add>
<ide> * Feature: global 'process' object. Emits "exit".
<ide> * Feature: promise.wait()
<del>
<add>
<ide> * Feature: node.stdio
<ide> * Feature: EventEmitters emit "newListener" when listeners are
<ide> added
<del>
<add>
<ide> * API: Use flat object instead of array-of-arrays for HTTP
<ide> headers.
<del>
<add>
<ide> * API: Remove buffered file object (node.File)
<ide> * API: require(), include() are synchronous. (Uses
<ide> continuations.)
<del>
<add>
<ide> * API: Deprecate onLoad and onExit.
<ide> * API: Rename node.Process to node.ChildProcess
<del>
<add>
<ide> * Refactor node.Process to take advantage of evcom_reader/writer.
<ide> * Upgrade v8 to 1.3.7
<ide> ## 2009.08.22, Version 0.1.6
<ide>
<ide> https://github.com/iojs/io.js/commit/9c97b1db3099d61cd292aa59ec2227a619f3a7ab
<del>
<add>
<ide> * Bugfix: Ignore SIGPIPE.
<ide> ## 2009.08.21, Version 0.1.5
<ide>
<ide> https://github.com/iojs/io.js/commit/b0fd3e281cb5f7cd8d3a26bd2b89e1b59998e5ed
<del>
<add>
<ide> * Bugfix: Buggy connections could crash node.js. Now check
<ide> connection before sending data every time (Kevin van Zonneveld)
<del>
<add>
<ide> * Bugfix: stdin fd (0) being ignored by node.File. (Abe Fettig)
<ide> * API: Remove connnection.fullClose()
<del>
<add>
<ide> * API: Return the EventEmitter from addListener for chaining.
<ide> * API: tcp.Connection "disconnect" event renamed to "close"
<del>
<add>
<ide> * Upgrade evcom
<ide> Upgrade v8 to 1.3.6
<ide> ## 2009.08.13, Version 0.1.4
<ide>
<ide> https://github.com/iojs/io.js/commit/0f888ed6de153f68c17005211d7e0f960a5e34f3
<del>
<add>
<ide> * Major refactor to evcom.
<ide> * Enable test-tcp-many-clients.
<del>
<add>
<ide> * Add -m32 gcc flag to udns.
<ide> * Add connection.readPause() and connection.readResume()
<ide> Add IncomingMessage.prototype.pause() and resume().
<del>
<add>
<ide> * Fix http benchmark. Wasn't correctly dispatching.
<ide> * Bugfix: response.setBodyEncoding("ascii") not working.
<del>
<add>
<ide> * Bugfix: Negative ints in HTTP's on_body and node.fs.read()
<ide> * Upgrade v8 to 1.3.4
<ide> Upgrade libev to 3.8
<ide> Upgrade http_parser to v0.2
<ide> ## 2009.08.06, Version 0.1.3
<ide>
<ide> https://github.com/iojs/io.js/commit/695f0296e35b30cf8322fd1bd934810403cca9f3
<del>
<add>
<ide> * Upgrade v8 to 1.3.2
<ide> * Bugfix: node.http.ServerRequest.setBodyEncoding('ascii') not
<ide> working
<del>
<add>
<ide> * Bugfix: node.encodeUtf8 was broken. (Connor Dunn)
<ide> * Add ranlib to udns Makefile.
<del>
<add>
<ide> * Upgrade evcom - fix accepting too many connections issue.
<ide> * Initial support for shebang
<del>
<add>
<ide> * Add simple command line switches
<ide> * Add node.version API
<ide>
<ide> ## 2009.08.01, Version 0.1.2
<ide>
<ide> https://github.com/iojs/io.js/commit/025a34244d1cea94d6d40ad7bf92671cb909a96c
<del>
<add>
<ide> * Add DNS API
<ide> * node.tcp.Server's backlog option is now an argument to listen()
<del>
<add>
<ide> * Upgrade V8 to 1.3.1
<ide> * Bugfix: Default to chunked for client requests without
<ide> Content-Length.
<del>
<add>
<ide> * Bugfix: Line numbers in stack traces.
<ide> * Bugfix: negative integers in raw encoding stream
<del>
<add>
<ide> * Bugfix: node.fs.File was not passing args to promise callbacks.
<ide>
<ide> ## 2009.07.27, Version 0.1.1
<ide>
<ide> https://github.com/iojs/io.js/commit/77d407df2826b20e9177c26c0d2bb4481e497937
<del>
<add>
<ide> * Simplify and clean up ObjectWrap.
<ide> * Upgrade liboi (which is now called evcom)
<ide> Upgrade libev to 3.7
<ide> Upgrade V8 to 1.2.14
<del>
<add>
<ide> * Array.prototype.encodeUtf8 renamed to node.encodeUtf8(array)
<ide> * Move EventEmitter.prototype.emit() completely into C++.
<del>
<add>
<ide> * Bugfix: Fix memory leak in event emitters.
<ide> http://groups.google.com/group/nodejs/browse_thread/thread/a8d1dfc2fd57a6d1
<del>
<add>
<ide> * Bugfix: Had problems reading scripts with non-ascii characters.
<ide> * Bugfix: Fix Detach() in node::Server
<del>
<add>
<ide> * Bugfix: Sockets not properly reattached if reconnected during
<ide> disconnect event.
<del>
<add>
<ide> * Bugfix: Server-side clients not attached between creation and
<ide> on_connect.
<del>
<add>
<ide> * Add 'close' event to node.tcp.Server
<ide> * Simplify and clean up http.js. (Takes more advantage of event
<ide> infrastructure.)
<del>
<add>
<ide> * Add benchmark scripts. Run with "make benchmark".
<ide>
<ide> ## 2009.06.30, Version 0.1.0
<ide>
<ide> https://github.com/iojs/io.js/commit/0fe44d52fe75f151bceb59534394658aae6ac328
<del>
<add>
<ide> * Update documentation, use asciidoc.
<ide> * EventEmitter and Promise interfaces. (Breaks previous API.)
<del>
<add>
<ide> * Remove node.Process constructor in favor of node.createProcess
<ide> * Add -m32 flags for compiling on x64 platforms.
<ide> (Thanks to András Bártházi)
<del>
<add>
<ide> * Upgrade v8 to 1.2.10 and libev to 3.6
<ide> * Bugfix: Timer::RepeatSetter wasn't working.
<del>
<add>
<ide> * Bugfix: Spawning many processes in a loop
<ide> (reported by Felix Geisendörfer)
<ide>
<ide> ## 2009.06.24, Version 0.0.6
<ide>
<ide> https://github.com/iojs/io.js/commit/fbe0be19ebfb422d8fa20ea5204c1713e9214d5f
<del>
<add>
<ide> * Load modules via HTTP URLs (Urban Hafner)
<ide> * Bugfix: Add HTTPConnection->size() and HTTPServer->size()
<del>
<add>
<ide> * New node.Process API
<ide> * Clean up build tools, use v8's test runner.
<del>
<add>
<ide> * Use ev_unref() instead of starting/stopping the eio thread
<ide> pool watcher.
<ide>
<ide> ## 2009.06.18, Version 0.0.5
<ide>
<ide> https://github.com/iojs/io.js/commit/3a2b41de74b6c343b8464a68eff04c4bfd9aebea
<del>
<add>
<ide> * Support for IPv6
<ide> * Remove namespace node.constants
<del>
<add>
<ide> * Upgrade v8 to 1.2.8.1
<ide> * Accept ports as strings in the TCP client and server.
<del>
<add>
<ide> * Bugfix: HTTP Client race
<ide> * Bugfix: freeaddrinfo() wasn't getting called after
<ide> getaddrinfo() for TCP servers
<del>
<add>
<ide> * Add "opening" to TCP client readyState
<ide> * Add remoteAddress to TCP client
<del>
<add>
<ide> * Add global print() function.
<ide>
<ide> ## 2009.06.13, Version 0.0.4
<ide>
<ide> https://github.com/iojs/io.js/commit/916b9ca715b229b0703f0ed6c2fc065410fb189c
<del>
<add>
<ide> * Add interrupt() method to server-side HTTP requests.
<ide> * Bugfix: onBodyComplete was not getting called on server-side
<ide> HTTP
<ide>
<ide> ## 2009.06.11, Version 0.0.3
<ide>
<ide> https://github.com/iojs/io.js/commit/6e0dfe50006ae4f5dac987f055e0c9338662f40a
<del>
<add>
<ide> * Many bug fixes including the problem with http.Client on
<ide> macintosh
<del>
<add>
<ide> * Upgrades v8 to 1.2.7
<ide> * Adds onExit hook
<del>
<add>
<ide> * Guard against buffer overflow in http parser
<ide> * require() and include() now need the ".js" extension
<del>
<add>
<ide> * http.Client uses identity transfer encoding by default. | 1 |
Ruby | Ruby | add audit check for url schema | e363889d27bb7fddaea513fb733c3c050d3af144 | <ide><path>Library/Homebrew/cask/lib/hbc/audit.rb
<ide> def run!
<ide> check_url
<ide> check_generic_artifacts
<ide> check_token_conflicts
<add> check_https_availability
<ide> check_download
<ide> check_single_pre_postflight
<ide> check_single_uninstall_zap
<ide> def core_formula_url
<ide> "#{core_tap.default_remote}/blob/master/Formula/#{cask.token}.rb"
<ide> end
<ide>
<add> def check_https_availability
<add> check_url_for_https_availability(cask.homepage) unless cask.url.to_s.empty?
<add> check_url_for_https_availability(cask.appcast) unless cask.appcast.to_s.empty?
<add> check_url_for_https_availability(cask.homepage) unless cask.homepage.to_s.empty?
<add> end
<add>
<add> def check_url_for_https_availability(url_to_check)
<add> if schema_http?(url_to_check)
<add> result, effective_url = access_url(url_to_check.sub(/^http:/, 'https:'))
<add> if schema_https?(effective_url) && result == 1
<add> add_error "Change #{url_to_check} to #{url_to_check.sub(/^http:/, 'https:')}"
<add> else
<add> result, effective_url = access_url(url_to_check)
<add>
<add> if result == 0
<add> add_error "URL is not reachable #{url_to_check}"
<add> end
<add> end
<add> else
<add> result, effective_url = access_url(url_to_check)
<add> if result == 1 && schema_https?(effective_url)
<add> return
<add> else
<add> result, effective_url = access_url(url_to_check.sub(/^https:/, 'http:'))
<add> if result == 1 && schema_http?(effective_url)
<add> add_error "Change #{url_to_check} to #{url_to_check.sub(/^https:/, 'http:')}"
<add> else
<add> add_error "URL is not reachable #{url_to_check}"
<add> end
<add> end
<add> end
<add> end
<add>
<add> def access_url(url_to_access)
<add> # return values:
<add> # 1, effective URL : URL reachable, no schema change
<add> # 0, nil : URL unreachable
<add> # -1, effective URL : URL reachable, but schema changed
<add>
<add> curl_executable, *args = curl_args(
<add> "--compressed", "--location", "--fail",
<add> "--write-out", "%{http_code} %{url_effective}",
<add> "--output", "/dev/null",
<add> url_to_access,
<add> user_agent: :fake
<add> )
<add> result = @command.run(curl_executable, args: args, print_stderr: false)
<add> if result.success?
<add> http_code, url_effective = result.stdout.chomp.split(' ')
<add> odebug "input: #{url_to_access} effective: #{url_effective} code: #{http_code}"
<add>
<add> # Fail if return code not 2XX or 3XX
<add> return 0, nil if http_code.to_i < 200 && http_code.to_i > 300
<add>
<add> # Fail if URL schema changed
<add> # ([4] is either http[s]:// or http[:]// )
<add> return -1, url_effective if url_to_access[4] != url_effective[4]
<add>
<add> return 1, url_effective
<add> else
<add> return 0, nil
<add> end
<add> end
<add>
<add> def schema_http?(url)
<add> url[/^http:/] ? 1 : nil
<add> end
<add>
<add> def schema_https?(url)
<add> url[/^https:/] ? 1 : nil
<add> end
<add>
<ide> def check_download
<ide> return unless download && cask.url
<ide> odebug "Auditing download" | 1 |
Javascript | Javascript | fix breaking test in chrome | 659773348f1fca0fb609f92271013f2a087f3247 | <ide><path>src/effects.js
<ide> jQuery.fn.extend({
<ide>
<ide> if ( parts ) {
<ide> var end = parseFloat( parts[2] ),
<del> unit = parts[3] || jQuery.cssNumber[ name ] ? "" : "px";
<add> unit = parts[3] || ( jQuery.cssNumber[ name ] ? "" : "px" );
<ide>
<ide> // We need to compute starting value
<ide> if ( unit !== "px" ) {
<ide> jQuery.fx.prototype = {
<ide> this.startTime = jQuery.now();
<ide> this.start = from;
<ide> this.end = to;
<del> this.unit = unit || this.unit || jQuery.cssNumber[ this.prop ] ? "" : "px";
<add> this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
<ide> this.now = this.start;
<ide> this.pos = this.state = 0;
<ide>
<ide><path>test/unit/effects.js
<ide> test("hide hidden elements, with animation (bug #7141)", function() {
<ide>
<ide> test("animate unit-less properties (#4966)", 2, function() {
<ide> stop();
<del> var div = jQuery( "<div style='z-index: 0'></div>" ).appendTo( "body" );
<add> var div = jQuery( "<div style='z-index: 0; position: absolute;'></div>" ).appendTo( "#main" );
<ide> equal( div.css( "z-index" ), "0", "z-index is 0" );
<ide> div.animate({ zIndex: 2 }, function() {
<ide> equal( div.css( "z-index" ), "2", "z-index is 2" ); | 2 |
Ruby | Ruby | add actioncable.server singleton | c811bed8e1fd67869452acb4818c3264e82d627c | <ide><path>lib/action_cable.rb
<ide> module ActionCable
<ide> autoload :RemoteConnection, 'action_cable/remote_connection'
<ide> autoload :RemoteConnections, 'action_cable/remote_connections'
<ide> autoload :Broadcaster, 'action_cable/broadcaster'
<add>
<add> # Singleton instance of the server
<add> module_function def server
<add> ActionCable::Server::Base.new
<add> end
<ide> end | 1 |
Javascript | Javascript | fix printing regression from | c9f23905675a16251fe688fcbd05847acad8c9a4 | <ide><path>web/viewer.js
<ide> var PDFView = {
<ide> bindOnAfterDraw(pageView, thumbnailView);
<ide> pages.push(pageView);
<ide> thumbnails.push(thumbnailView);
<add> if (!PDFJS.disableAutoFetch) {
<add> pagePromises.push(pdfDocument.getPage(pageNum).then(
<add> function (pageView, pdfPage) {
<add> pageView.setPdfPage(pdfPage);
<add> }.bind(this, pageView)
<add> ));
<add> }
<ide> }
<ide>
<ide> var event = document.createEvent('CustomEvent'); | 1 |
Javascript | Javascript | rewrite the suspense logic | 0f536bba5c4354838d4dc1f3fdf226d1b0e67ee9 | <ide><path>src/backend/renderer.js
<ide> import {
<ide> TREE_OPERATION_ADD,
<ide> TREE_OPERATION_REMOVE,
<ide> TREE_OPERATION_RESET_CHILDREN,
<add> TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN,
<ide> TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
<ide> } from '../constants';
<ide> import { getUID } from '../utils';
<ide> export function attach(
<ide> pendingOperations = new Uint32Array(0);
<ide> }
<ide>
<del> function enqueueMount(fiber: Fiber, parentFiber: Fiber | null) {
<add> function recordMount(fiber: Fiber, parentFiber: Fiber | null) {
<ide> const isRoot = fiber.tag === HostRoot;
<ide> const id = getFiberID(getPrimaryFiber(fiber));
<ide>
<ide> export function attach(
<ide> }
<ide> }
<ide>
<del> function enqueueUnmount(fiber) {
<add> function recordUnmount(fiber) {
<ide> const isRoot = fiber.tag === HostRoot;
<ide> const primaryFiber = getPrimaryFiber(fiber);
<ide> if (!fiberToIDMap.has(primaryFiber)) {
<ide> export function attach(
<ide> }
<ide> }
<ide>
<del> function mountFiber(
<add> function recordRecursiveRemoveChildren(fiber) {
<add> const primaryFiber = getPrimaryFiber(fiber);
<add> const id = getFiberID(primaryFiber);
<add> const operation = new Uint32Array(2);
<add> operation[0] = TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN;
<add> operation[1] = id;
<add> addOperation(operation, false);
<add> }
<add>
<add> function mountFiberRecursively(
<ide> fiber: Fiber,
<ide> parentFiber: Fiber | null,
<ide> traverseSiblings = false
<ide> ) {
<ide> if (__DEBUG__) {
<del> debug('mountFiber()', fiber, parentFiber);
<add> debug('mountFiberRecursively()', fiber, parentFiber);
<ide> }
<ide>
<del> const shouldEnqueueMount = !shouldFilterFiber(fiber);
<del> if (shouldEnqueueMount) {
<del> enqueueMount(fiber, parentFiber);
<add> const shouldInclude = !shouldFilterFiber(fiber);
<add> if (shouldInclude) {
<add> recordMount(fiber, parentFiber);
<ide> }
<ide>
<ide> const isTimedOutSuspense =
<ide> export function attach(
<ide> const fallbackChildFragment = primaryChildFragment.sibling;
<ide> const fallbackChild = fallbackChildFragment.child;
<ide> if (fallbackChild !== null) {
<del> mountFiber(fallbackChild, shouldEnqueueMount ? fiber : parentFiber, true);
<add> mountFiberRecursively(
<add> fallbackChild,
<add> shouldInclude ? fiber : parentFiber,
<add> true
<add> );
<ide> }
<ide> } else {
<ide> if (fiber.child !== null) {
<del> mountFiber(fiber.child, shouldEnqueueMount ? fiber : parentFiber, true);
<add> mountFiberRecursively(
<add> fiber.child,
<add> shouldInclude ? fiber : parentFiber,
<add> true
<add> );
<ide> }
<ide> }
<ide>
<ide> if (traverseSiblings && fiber.sibling !== null) {
<del> mountFiber(fiber.sibling, parentFiber, true);
<add> mountFiberRecursively(fiber.sibling, parentFiber, true);
<ide> }
<ide> }
<ide>
<del> function enqueueUpdateIfNecessary(
<del> fiber: Fiber,
<del> hasChildOrderChanged: boolean
<del> ) {
<add> function unmountFiberRecursively(fiber, traverseSiblings = false) {
<ide> if (__DEBUG__) {
<del> debug('enqueueUpdateIfNecessary()', fiber);
<add> debug('unmountFiberRecursively()', fiber, traverseSiblings);
<add> }
<add> if (!shouldFilterFiber(fiber)) {
<add> recordUnmount(fiber);
<add> }
<add> if (fiber.child !== null) {
<add> unmountFiberRecursively(fiber.child, true);
<add> }
<add> if (traverseSiblings && fiber.sibling !== null) {
<add> unmountFiberRecursively(fiber.sibling, true);
<add> }
<add> }
<add>
<add> function maybeRecordUpdate(fiber: Fiber, hasChildOrderChanged: boolean) {
<add> if (__DEBUG__) {
<add> debug('maybeRecordUpdate()', fiber);
<ide> }
<ide>
<ide> const isProfilingSupported = fiber.hasOwnProperty('treeBaseDuration');
<ide> export function attach(
<ide> // We might want to revisit this if it proves to be too inefficient.
<ide> let child = fiber.child;
<ide> while (child !== null) {
<del> findReorderedChildren(child, nextChildren);
<add> findReorderedChildrenRecursively(child, nextChildren);
<ide> child = child.sibling;
<ide> }
<ide>
<ide> export function attach(
<ide> }
<ide> }
<ide>
<del> function findReorderedChildren(fiber: Fiber, nextChildren: Array<number>) {
<add> function findReorderedChildrenRecursively(
<add> fiber: Fiber,
<add> nextChildren: Array<number>
<add> ) {
<ide> if (!shouldFilterFiber(fiber)) {
<ide> nextChildren.push(getFiberID(getPrimaryFiber(fiber)));
<ide> } else {
<ide> let child = fiber.child;
<ide> while (child !== null) {
<del> findReorderedChildren(child, nextChildren);
<add> findReorderedChildrenRecursively(child, nextChildren);
<ide> child = child.sibling;
<ide> }
<ide> }
<ide> }
<ide>
<del> function updateFiber(
<add> function updateFiberRecursively(
<ide> nextFiber: Fiber,
<ide> prevFiber: Fiber,
<ide> parentFiber: Fiber | null
<ide> ) {
<ide> if (__DEBUG__) {
<del> debug('enqueueUpdateIfNecessary()', nextFiber, parentFiber);
<add> debug('updateFiberRecursively()', nextFiber, parentFiber);
<ide> }
<ide>
<del> const shouldEnqueueUpdate = !shouldFilterFiber(nextFiber);
<del>
<del> // Suspense components only have a non-null memoizedState if they're timed-out.
<del> const isTimedOutSuspense =
<del> nextFiber.tag === SuspenseComponent && nextFiber.memoizedState !== null;
<del>
<del> if (isTimedOutSuspense) {
<del> // The behavior of timed-out Suspense trees is unique.
<del> // Rather than unmount the timed out content (and possibly lose important state),
<del> // React re-parents this content within a hidden Fragment while the fallback is showing.
<del> // This behavior doesn't need to be observable in the DevTools though.
<del> // It might even result in a bad user experience for e.g. node selection in the Elements panel.
<del> // The easiest fix is to strip out the intermediate Fragment fibers,
<del> // so the Elements panel and Profiler don't need to special case them.
<del> const primaryChildFragment = nextFiber.child;
<del> const fallbackChildFragment = primaryChildFragment.sibling;
<del> const fallbackChild = fallbackChildFragment.child;
<del>
<del> // The primary, hidden child is never actually updated in this case,
<del> // so we can skip any updates to its tree.
<del> // We only need to track updates to the Fallback UI for now.
<del> if (fallbackChild.alternate) {
<del> updateFiber(fallbackChild, fallbackChild.alternate, nextFiber);
<add> // The behavior of timed-out Suspense trees is unique.
<add> // Rather than unmount the timed out content (and possibly lose important state),
<add> // React re-parents this content within a hidden Fragment while the fallback is showing.
<add> // This behavior doesn't need to be observable in the DevTools though.
<add> // It might even result in a bad user experience for e.g. node selection in the Elements panel.
<add> // The easiest fix is to strip out the intermediate Fragment fibers,
<add> // so the Elements panel and Profiler don't need to special case them.
<add> if (nextFiber.tag === SuspenseComponent) {
<add> // Suspense components only have a non-null memoizedState if they're timed-out.
<add> const prevDidTimeout = prevFiber.memoizedState !== null;
<add> const nextDidTimeOut = nextFiber.memoizedState !== null;
<add>
<add> // The logic below is inspired by the codepaths in updateSuspenseComponent()
<add> // inside ReactFiberBeginWork in the React source code.
<add> if (prevDidTimeout) {
<add> if (nextDidTimeOut) {
<add> // Fallback -> Fallback:
<add> // 1. Reconcile fallback set.
<add> const nextFallbackChildSet = nextFiber.child.sibling;
<add> // Note: We can't use nextFiber.child.sibling.alternate
<add> // because the set is special and alternate may not exist.
<add> const prevFallbackChildSet = prevFiber.child.sibling;
<add> updateFiberRecursively(
<add> nextFallbackChildSet,
<add> prevFallbackChildSet,
<add> nextFiber
<add> );
<add> return;
<add> } else {
<add> // Fallback -> Primary:
<add> // 1. Unmount fallback set
<add> // Note: don't emulate fallback unmount because React actually did it.
<add> // 2. Mount primary set
<add> const nextPrimaryChildSet = nextFiber.child;
<add> mountFiberRecursively(nextPrimaryChildSet, nextFiber, true);
<add> return;
<add> }
<ide> } else {
<del> mountFiber(fallbackChild, nextFiber);
<add> if (nextDidTimeOut) {
<add> // Primary -> Fallback:
<add> // 1. Hide primary set
<add> // This is not a real unmount, so it won't get reported by React.
<add> // By this point it's *too late* to find the previous primary child set
<add> // so we'll just tell the store to "forget" about those children.
<add> // They might "resurface" later when we switch to primary content,
<add> // but from the store's point of view they will be a new tree.
<add> recordRecursiveRemoveChildren(nextFiber);
<add> // 2. Mount fallback set
<add> const nextFallbackChildSet = nextFiber.child.sibling;
<add> mountFiberRecursively(nextFallbackChildSet, nextFiber, true);
<add> return;
<add> } else {
<add> // Primary -> Primary:
<add> // 1. Reconcile primary set.
<add> // Note: no return so we can passthrough to the logic below.
<add> }
<ide> }
<add> }
<ide>
<del> if (shouldEnqueueUpdate) {
<del> enqueueUpdateIfNecessary(nextFiber, false);
<del> }
<del> } else {
<del> let hasChildOrderChanged = false;
<del> if (nextFiber.child !== prevFiber.child) {
<del> // If the first child is different, we need to traverse them.
<del> // Each next child will be either a new child (mount) or an alternate (update).
<del> let nextChild = nextFiber.child;
<del> let prevChildAtSameIndex = prevFiber.child;
<del> while (nextChild) {
<del> // We already know children will be referentially different because
<del> // they are either new mounts or alternates of previous children.
<del> // Schedule updates and mounts depending on whether alternates exist.
<del> // We don't track deletions here because they are reported separately.
<del> if (nextChild.alternate) {
<del> const prevChild = nextChild.alternate;
<del> updateFiber(
<del> nextChild,
<del> prevChild,
<del> shouldEnqueueUpdate ? nextFiber : parentFiber
<del> );
<del> // However we also keep track if the order of the children matches
<del> // the previous order. They are always different referentially, but
<del> // if the instances line up conceptually we'll want to know that.
<del> if (!hasChildOrderChanged && prevChild !== prevChildAtSameIndex) {
<del> hasChildOrderChanged = true;
<del> }
<del> } else {
<del> mountFiber(
<del> nextChild,
<del> shouldEnqueueUpdate ? nextFiber : parentFiber
<del> );
<del> if (!hasChildOrderChanged) {
<del> hasChildOrderChanged = true;
<del> }
<add> const shouldInclude = !shouldFilterFiber(nextFiber);
<add> let hasChildOrderChanged = false;
<add> if (nextFiber.child !== prevFiber.child) {
<add> // If the first child is different, we need to traverse them.
<add> // Each next child will be either a new child (mount) or an alternate (update).
<add> let nextChild = nextFiber.child;
<add> let prevChildAtSameIndex = prevFiber.child;
<add> while (nextChild) {
<add> // We already know children will be referentially different because
<add> // they are either new mounts or alternates of previous children.
<add> // Schedule updates and mounts depending on whether alternates exist.
<add> // We don't track deletions here because they are reported separately.
<add> if (nextChild.alternate) {
<add> const prevChild = nextChild.alternate;
<add> updateFiberRecursively(
<add> nextChild,
<add> prevChild,
<add> shouldInclude ? nextFiber : parentFiber
<add> );
<add> // However we also keep track if the order of the children matches
<add> // the previous order. They are always different referentially, but
<add> // if the instances line up conceptually we'll want to know that.
<add> if (!hasChildOrderChanged && prevChild !== prevChildAtSameIndex) {
<add> hasChildOrderChanged = true;
<ide> }
<del> // Try the next child.
<del> nextChild = nextChild.sibling;
<del> // Advance the pointer in the previous list so that we can
<del> // keep comparing if they line up.
<del> if (!hasChildOrderChanged && prevChildAtSameIndex != null) {
<del> prevChildAtSameIndex = prevChildAtSameIndex.sibling;
<add> } else {
<add> mountFiberRecursively(
<add> nextChild,
<add> shouldInclude ? nextFiber : parentFiber
<add> );
<add> if (!hasChildOrderChanged) {
<add> hasChildOrderChanged = true;
<ide> }
<ide> }
<del> // If we have no more children, but used to, they don't line up.
<add> // Try the next child.
<add> nextChild = nextChild.sibling;
<add> // Advance the pointer in the previous list so that we can
<add> // keep comparing if they line up.
<ide> if (!hasChildOrderChanged && prevChildAtSameIndex != null) {
<del> hasChildOrderChanged = true;
<add> prevChildAtSameIndex = prevChildAtSameIndex.sibling;
<ide> }
<ide> }
<del>
<del> if (shouldEnqueueUpdate) {
<del> enqueueUpdateIfNecessary(nextFiber, hasChildOrderChanged);
<add> // If we have no more children, but used to, they don't line up.
<add> if (!hasChildOrderChanged && prevChildAtSameIndex != null) {
<add> hasChildOrderChanged = true;
<ide> }
<ide> }
<add>
<add> if (shouldInclude) {
<add> maybeRecordUpdate(nextFiber, hasChildOrderChanged);
<add> }
<ide> }
<ide>
<ide> function cleanup() {
<ide> export function attach(
<ide> };
<ide> }
<ide>
<del> mountFiber(root.current, null);
<add> mountFiberRecursively(root.current, null);
<ide> flushPendingEvents(root);
<ide> currentRootID = -1;
<ide> });
<ide> export function attach(
<ide> // This is not recursive.
<ide> // We can't traverse fibers after unmounting so instead
<ide> // we rely on React telling us about each unmount.
<del> enqueueUnmount(fiber);
<add> recordUnmount(fiber);
<ide> }
<ide>
<ide> function handleCommitFiberRoot(root) {
<ide> export function attach(
<ide> current.memoizedState != null && current.memoizedState.element != null;
<ide> if (!wasMounted && isMounted) {
<ide> // Mount a new root.
<del> mountFiber(current, null);
<add> mountFiberRecursively(current, null);
<ide> } else if (wasMounted && isMounted) {
<ide> // Update an existing root.
<del> updateFiber(current, alternate, null);
<add> updateFiberRecursively(current, alternate, null);
<ide> } else if (wasMounted && !isMounted) {
<ide> // Unmount an existing root.
<del> enqueueUnmount(current);
<add> recordUnmount(current);
<ide> }
<ide> } else {
<ide> // Mount a new root.
<del> mountFiber(current, null);
<add> mountFiberRecursively(current, null);
<ide> }
<ide>
<ide> if (isProfiling) {
<ide><path>src/constants.js
<ide> export const TREE_OPERATION_ADD = 1;
<ide> export const TREE_OPERATION_REMOVE = 2;
<ide> export const TREE_OPERATION_RESET_CHILDREN = 3;
<ide> export const TREE_OPERATION_UPDATE_TREE_BASE_DURATION = 4;
<add>export const TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN = 5;
<ide>
<ide> export const LOCAL_STORAGE_RELOAD_AND_PROFILE_KEY =
<ide> 'React::DevTools::reloadAndProfile';
<ide><path>src/devtools/store.js
<ide> import EventEmitter from 'events';
<ide> import {
<ide> TREE_OPERATION_ADD,
<add> TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN,
<ide> TREE_OPERATION_REMOVE,
<ide> TREE_OPERATION_RESET_CHILDREN,
<ide> TREE_OPERATION_UPDATE_TREE_BASE_DURATION,
<ide> export default class Store extends EventEmitter {
<ide> weightDelta = 1;
<ide> }
<ide> break;
<del> case TREE_OPERATION_REMOVE:
<add> case TREE_OPERATION_RECURSIVE_REMOVE_CHILDREN: {
<add> id = ((operations[i + 1]: any): number);
<add>
<add> if (!this._idToElement.has(id)) {
<add> throw new Error(
<add> 'Store does not contain fiber ' +
<add> id +
<add> '. This is a bug in React DevTools.'
<add> );
<add> }
<add>
<add> i = i + 2;
<add>
<add> let justRemovedIDs = [];
<add> const recursivelyRemove = childID => {
<add> justRemovedIDs.push(childID);
<add> const child = this._idToElement.get(childID);
<add> if (!child) {
<add> throw new Error(
<add> 'Store does not contain fiber ' +
<add> childID +
<add> '. This is a bug in React DevTools.'
<add> );
<add> }
<add> this._idToElement.delete(childID);
<add> child.children.forEach(recursivelyRemove);
<add> };
<add>
<add> // Track removed items so search results can be updated
<add> const oldRemovedElementIDs = removedElementIDs;
<add> removedElementIDs = new Uint32Array(
<add> removedElementIDs.length + justRemovedIDs.length
<add> );
<add> removedElementIDs.set(oldRemovedElementIDs);
<add> let startIndex = oldRemovedElementIDs.length;
<add> for (let j = 0; j < justRemovedIDs.length; j++) {
<add> removedElementIDs[startIndex + j] = oldRemovedElementIDs[j];
<add> }
<add>
<add> parentElement = ((this._idToElement.get(id): any): Element);
<add> parentElement.children.forEach(recursivelyRemove);
<add> parentElement.children = [];
<add> weightDelta = -parentElement.weight + 1;
<add> break;
<add> }
<add> case TREE_OPERATION_REMOVE: {
<ide> id = ((operations[i + 1]: any): number);
<ide>
<ide> if (!this._idToElement.has(id)) {
<ide> export default class Store extends EventEmitter {
<ide> }
<ide>
<ide> // Track removed items so search results can be updated
<del> const oldRemovededElementIDs = removedElementIDs;
<add> const oldRemovedElementIDs = removedElementIDs;
<ide> removedElementIDs = new Uint32Array(removedElementIDs.length + 1);
<del> removedElementIDs.set(oldRemovededElementIDs);
<del> removedElementIDs[oldRemovededElementIDs.length] = id;
<add> removedElementIDs.set(oldRemovedElementIDs);
<add> removedElementIDs[oldRemovedElementIDs.length] = id;
<ide> break;
<add> }
<ide> case TREE_OPERATION_RESET_CHILDREN:
<ide> id = ((operations[i + 1]: any): number);
<ide> const numChildren = ((operations[i + 2]: any): number); | 3 |
Go | Go | add missing comments to runtime.go | 6a9f4ecf9bc4263baef8e9a1d86f1474f9c66d31 | <ide><path>runtime.go
<ide> func init() {
<ide> sysInitPath = utils.SelfPath()
<ide> }
<ide>
<add>// List returns an array of all containers registered in the runtime.
<ide> func (runtime *Runtime) List() []*Container {
<ide> containers := new(History)
<ide> for e := runtime.containers.Front(); e != nil; e = e.Next() {
<ide> func (runtime *Runtime) getContainerElement(id string) *list.Element {
<ide> return nil
<ide> }
<ide>
<add>// Get looks for a container by the specified ID or name, and returns it.
<add>// If the container is not found, or if an error occurs, nil is returned.
<ide> func (runtime *Runtime) Get(name string) *Container {
<ide> id, err := runtime.idIndex.Get(name)
<ide> if err != nil {
<ide> func (runtime *Runtime) Get(name string) *Container {
<ide> return e.Value.(*Container)
<ide> }
<ide>
<add>// Exists returns a true if a container of the specified ID or name exists,
<add>// false otherwise.
<ide> func (runtime *Runtime) Exists(id string) bool {
<ide> return runtime.Get(id) != nil
<ide> }
<ide> func (runtime *Runtime) containerRoot(id string) string {
<ide> return path.Join(runtime.repository, id)
<ide> }
<ide>
<add>// Load reads the contents of a container from disk and registers
<add>// it with Register.
<add>// This is typically done at startup.
<ide> func (runtime *Runtime) Load(id string) (*Container, error) {
<ide> container := &Container{root: runtime.containerRoot(id)}
<ide> if err := container.FromDisk(); err != nil {
<ide> func (runtime *Runtime) LogToDisk(src *utils.WriteBroadcaster, dst, stream strin
<ide> return nil
<ide> }
<ide>
<add>// Destroy unregisters a container from the runtime and cleanly removes its contents from the filesystem.
<ide> func (runtime *Runtime) Destroy(container *Container) error {
<ide> if container == nil {
<ide> return fmt.Errorf("The given container is <nil>")
<ide> func (runtime *Runtime) restore() error {
<ide> return nil
<ide> }
<ide>
<del>// FIXME: comment please
<add>// FIXME: comment please!
<ide> func (runtime *Runtime) UpdateCapabilities(quiet bool) {
<ide> if cgroupMemoryMountpoint, err := utils.FindCgroupMountpoint("memory"); err != nil {
<ide> if !quiet {
<ide> func NewRuntimeFromDirectory(root string, autoRestart bool) (*Runtime, error) {
<ide> return runtime, nil
<ide> }
<ide>
<add>// History is a convenience type for storing a list of containers,
<add>// ordered by creation date.
<ide> type History []*Container
<ide>
<ide> func (history *History) Len() int { | 1 |
Text | Text | update euler-50 solution with prime sieve | 4be4bf36242a6406e10594e5b53575eea2c819d0 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/project-euler/problem-50-consecutive-prime-sum.md
<ide> consecutivePrimeSum(1000000);
<ide> # --solutions--
<ide>
<ide> ```js
<del>function consecutivePrimeSum(limit) {
<del> function isPrime(num) {
<del> if (num < 2) {
<del> return false;
<del> } else if (num === 2) {
<del> return true;
<del> }
<del> const sqrtOfNum = Math.floor(num ** 0.5);
<del> for (let i = 2; i <= sqrtOfNum + 1; i++) {
<del> if (num % i === 0) {
<del> return false;
<del> }
<add>// Initalize prime number list with sieve
<add>const NUM_PRIMES = 1000000;
<add>const PRIMES = [2];
<add>const PRIME_SIEVE = Array(Math.floor((NUM_PRIMES-1)/2)).fill(true);
<add>(function initPrimes(num) {
<add> const upper = Math.floor((num - 1) / 2);
<add> const sqrtUpper = Math.floor((Math.sqrt(num) - 1) / 2);
<add> for (let i = 0; i <= sqrtUpper; i++) {
<add> if (PRIME_SIEVE[i]) {
<add> // Mark value in PRIMES array
<add> const prime = 2 * i + 3;
<add> PRIMES.push(prime);
<add> // Mark all multiples of this number as false (not prime)
<add> const primeSqaredIndex = 2 * i ** 2 + 6 * i + 3;
<add> for (let j = primeSqaredIndex; j < upper; j += prime)
<add> PRIME_SIEVE[j] = false;
<ide> }
<del> return true;
<ide> }
<del> function getPrimes(limit) {
<del> const primes = [];
<del> for (let i = 0; i <= limit; i++) {
<del> if (isPrime(i)) primes.push(i);
<del> }
<del> return primes;
<add> for (let i = sqrtUpper + 1; i < upper; i++) {
<add> if (PRIME_SIEVE[i])
<add> PRIMES.push(2 * i + 3);
<ide> }
<add>})(NUM_PRIMES);
<ide>
<del> const primes = getPrimes(limit);
<del> let primeSum = [...primes];
<del> primeSum.reduce((acc, n, i) => {
<del> primeSum[i] += acc;
<del> return acc += n;
<del> }, 0);
<del>
<del> for (let j = primeSum.length - 1; j >= 0; j--) {
<del> for (let i = 0; i < j; i++) {
<del> const sum = primeSum[j] - primeSum[i];
<del> if (sum > limit) break;
<del> if (isPrime(sum) && primes.indexOf(sum) > -1) return sum;
<add>function isPrime(num) {
<add> if (num === 2)
<add> return true;
<add> else if (num % 2 === 0)
<add> return false
<add> else
<add> return PRIME_SIEVE[(num - 3) / 2];
<add>}
<add>
<add>function consecutivePrimeSum(limit) {
<add> // Initalize for longest sum < 100
<add> let bestPrime = 41;
<add> let bestI = 0;
<add> let bestJ = 5;
<add>
<add> // Find longest sum < limit
<add> let sumOfCurrRange = 41;
<add> let i = 0, j = 5;
<add> // -- Loop while current some starting at i is < limit
<add> while (sumOfCurrRange < limit) {
<add> let currSum = sumOfCurrRange;
<add> // -- Loop while pushing j towards end of PRIMES list
<add> // keeping sum under limit
<add> while (currSum < limit) {
<add> if (isPrime(currSum)) {
<add> bestPrime = sumOfCurrRange = currSum;
<add> bestI = i;
<add> bestJ = j;
<add> }
<add> // -- Increment inner loop
<add> j++;
<add> currSum += PRIMES[j];
<ide> }
<add> // -- Increment outer loop
<add> i++;
<add> j = i + (bestJ - bestI);
<add> sumOfCurrRange -= PRIMES[i - 1];
<add> sumOfCurrRange += PRIMES[j];
<ide> }
<add> // Return
<add> return bestPrime;
<ide> }
<ide> ``` | 1 |
Javascript | Javascript | enlarge clickable area of tutorial nav buttons | d3491083a54b6d653687a4d96720cd8fc3efaac5 | <ide><path>docs/src/templates/js/docs.js
<ide> docsApp.directive.docTutorialNav = function(templateMerge) {
<ide> element.addClass('btn-group');
<ide> element.addClass('tutorial-nav');
<ide> element.append(templateMerge(
<del> '<li class="btn btn-primary"><a href="tutorial/{{prev}}"><i class="icon-step-backward"></i> Previous</a></li>\n' +
<del> '<li class="btn btn-primary"><a href="http://angular.github.com/angular-phonecat/step-{{seq}}/app"><i class="icon-play"></i> Live Demo</a></li>\n' +
<del> '<li class="btn btn-primary"><a href="https://github.com/angular/angular-phonecat/compare/step-{{diffLo}}...step-{{diffHi}}"><i class="icon-search"></i> Code Diff</a></li>\n' +
<del> '<li class="btn btn-primary"><a href="tutorial/{{next}}">Next <i class="icon-step-forward"></i></a></li>', props));
<add> '<a href="tutorial/{{prev}}"><li class="btn btn-primary"><i class="icon-step-backward"></i> Previous</li></a>\n' +
<add> '<a href="http://angular.github.com/angular-phonecat/step-{{seq}}/app"><li class="btn btn-primary"><i class="icon-play"></i> Live Demo</li></a>\n' +
<add> '<a href="https://github.com/angular/angular-phonecat/compare/step-{{diffLo}}...step-{{diffHi}}"><li class="btn btn-primary"><i class="icon-search"></i> Code Diff</li></a>\n' +
<add> '<a href="tutorial/{{next}}"><li class="btn btn-primary">Next <i class="icon-step-forward"></i></li></a>', props));
<ide> }
<ide> };
<ide> }; | 1 |
Javascript | Javascript | update code style | cc96ff069288d5979e9a056b82ff141a59827f32 | <ide><path>editor/js/Sidebar.Material.js
<ide> Sidebar.Material = function ( editor ) {
<ide>
<ide> }
<ide>
<del> if ( material.depthPacking !== undefined) {
<add> if ( material.depthPacking !== undefined ) {
<add>
<add> var depthPacking = parseInt( materialDepthPacking.getValue() );
<add> if ( material.depthPacking !== depthPacking ) {
<ide>
<del> var depthPacking = parseInt(materialDepthPacking.getValue());
<del> if(material.depthPacking !== depthPacking)
<del> {
<ide> editor.execute( new SetMaterialValueCommand( currentObject, 'depthPacking', depthPacking, currentMaterialSlot ) );
<add>
<ide> }
<ide>
<ide> } | 1 |
Javascript | Javascript | fix isdict when type is missing in dictionary | a79f0055276a04671711686e137a8739543a21bc | <ide><path>src/util.js
<ide> function isCmd(v, cmd) {
<ide> }
<ide>
<ide> function isDict(v, type) {
<del> return v instanceof Dict && (!type || v.get('Type').name == type);
<add> if (!(v instanceof Dict)) {
<add> return false;
<add> }
<add> if (!type) {
<add> return true;
<add> }
<add> var dictType = v.get('Type');
<add> return isName(dictType) && dictType.name == type;
<ide> }
<ide>
<ide> function isArray(v) {
<ide><path>test/unit/util_spec.js
<ide> describe('util', function() {
<ide> });
<ide> });
<ide>
<add> describe('isDict', function() {
<add> it('handles empty dictionaries with type check', function() {
<add> var dict = new Dict();
<add> expect(isDict(dict, 'Page')).toEqual(false);
<add> });
<add>
<add> it('handles dictionaries with type check', function() {
<add> var dict = new Dict();
<add> dict.set('Type', new Name('Page'));
<add> expect(isDict(dict, 'Page')).toEqual(true);
<add> });
<add> });
<add>
<ide> });
<ide> | 2 |
Java | Java | fix definition of nativeanimated.isempty | bf405d70837e1319cfa83e4c5cbb7c9a69abd820 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/animated/NativeAnimatedModule.java
<ide> private class ConcurrentOperationQueue {
<ide>
<ide> @AnyThread
<ide> boolean isEmpty() {
<del> return mQueue.isEmpty();
<add> return mQueue.isEmpty() && mPeekedOperation != null;
<ide> }
<ide>
<ide> void setSynchronizedAccess(boolean isSynchronizedAccess) {
<ide> void executeBatch(long maxBatchNumber, NativeAnimatedNodesManager nodesManager)
<ide>
<ide> @UiThread
<ide> private @Nullable List<UIThreadOperation> drainQueueIntoList(long maxBatchNumber) {
<del> if (mQueue.isEmpty() && mPeekedOperation == null) {
<add> if (isEmpty()) {
<ide> return null;
<ide> }
<ide> | 1 |
Text | Text | add olegas as collaborator | 11ed5f31abc6fc58e6f4b57a6088c7ea0043cdd2 | <ide><path>README.md
<ide> information about the governance of the io.js project, see
<ide> * **Alex Kocharin** ([@rlidwka](https://github.com/rlidwka)) <alex@kocharin.ru>
<ide> * **Christopher Monsanto** ([@monsanto](https://github.com/monsanto)) <chris@monsan.to>
<ide> * **Ali Ijaz Sheikh** ([@ofrobots](https://github.com/ofrobots)) <ofrobots@google.com>
<add>* **Oleg Elifantiev** ([@Olegas](https://github.com/Olegas)) <oleg@elifantiev.ru>
<ide>
<ide> Collaborators follow the [COLLABORATOR_GUIDE.md](./COLLABORATOR_GUIDE.md) in
<ide> maintaining the io.js project. | 1 |
Ruby | Ruby | fix bug in any_bottle_tag | f70a2c67da7dfb4abf7c6ae0044abb248d518781 | <ide><path>Library/Homebrew/dev-cmd/pull.rb
<ide> def bottle_info_any
<ide> end
<ide>
<ide> def any_bottle_tag
<del> tag = Utils::Bottles.tag
<add> tag = Utils::Bottles.tag.to_s
<ide> # Prefer native bottles as a convenience for download caching
<ide> bottle_tags.include?(tag) ? tag : bottle_tags.first
<ide> end
<ide> def verify_bintray_published(formulae_names)
<ide> opoo "Cannot publish bottle: Failed reading info for formula #{f.full_name}"
<ide> next
<ide> end
<del> bottle_info = jinfo.bottle_info(jinfo.bottle_tags.first)
<add> bottle_info = jinfo.bottle_info_any
<ide> unless bottle_info
<ide> opoo "No bottle defined in formula #{f.full_name}"
<ide> next | 1 |
Python | Python | add flags for adam hyperparameters | f3be93a730ed41e2dea5c593e0f8c1cf7186290c | <ide><path>official/recommendation/ncf_main.py
<ide> def run_ncf(_):
<ide> "tpu": FLAGS.tpu,
<ide> "tpu_zone": FLAGS.tpu_zone,
<ide> "tpu_gcp_project": FLAGS.tpu_gcp_project,
<add> "beta1": FLAGS.beta1,
<add> "beta2": FLAGS.beta2,
<add> "epsilon": FLAGS.epsilon,
<ide> }, batch_size=flags.FLAGS.batch_size, eval_batch_size=eval_batch_size)
<ide>
<ide> # Create hooks that log information about the training and metric values
<ide> def define_ncf_flags():
<ide> name="learning_rate", default=0.001,
<ide> help=flags_core.help_wrap("The learning rate."))
<ide>
<add> flags.DEFINE_float(
<add> name="beta1", default=0.9,
<add> help=flags_core.help_wrap("beta1 hyperparameter for the Adam optimizer."))
<add>
<add> flags.DEFINE_float(
<add> name="beta2", default=0.999,
<add> help=flags_core.help_wrap("beta2 hyperparameter for the Adam optimizer."))
<add>
<add> flags.DEFINE_float(
<add> name="epsilon", default=1e-8,
<add> help=flags_core.help_wrap("epsilon hyperparameter for the Adam "
<add> "optimizer."))
<add>
<ide> flags.DEFINE_float(
<ide> name="hr_threshold", default=None,
<ide> help=flags_core.help_wrap(
<ide><path>official/recommendation/neumf_model.py
<ide> def neumf_model_fn(features, labels, mode, params):
<ide>
<ide> elif mode == tf.estimator.ModeKeys.TRAIN:
<ide> labels = tf.cast(labels, tf.int32)
<del> optimizer = tf.train.AdamOptimizer(learning_rate=params["learning_rate"])
<add> optimizer = tf.train.AdamOptimizer(
<add> learning_rate=params["learning_rate"], beta1=params["beta1"],
<add> beta2=params["beta2"], epsilon=params["epsilon"])
<ide> if params["use_tpu"]:
<ide> optimizer = tf.contrib.tpu.CrossShardOptimizer(optimizer)
<ide> | 2 |
Python | Python | use sparse meshgrid instead of indices().tolist() | 39fbc1b1e7aee9220c62d8aeaa47eb885a4fde96 | <ide><path>numpy/ma/core.py
<ide> def sort(self, axis= -1, kind='quicksort', order=None,
<ide> filler = maximum_fill_value(self)
<ide> else:
<ide> filler = fill_value
<del> idx = np.indices(self.shape)
<add> idx = np.meshgrid(*[np.arange(x) for x in self.shape], sparse=True,
<add> indexing='ij')
<ide> idx[axis] = self.filled(filler).argsort(axis=axis, kind=kind,
<ide> order=order)
<del> idx_l = idx.tolist()
<del> tmp_mask = self._mask[idx_l].flat
<del> tmp_data = self._data[idx_l].flat
<add> tmp_mask = self._mask[idx].flat
<add> tmp_data = self._data[idx].flat
<ide> self._data.flat = tmp_data
<ide> self._mask.flat = tmp_mask
<ide> return
<ide> def sort(a, axis= -1, kind='quicksort', order=None, endwith=True, fill_value=Non
<ide> else:
<ide> filler = fill_value
<ide> # return
<del> indx = np.indices(a.shape).tolist()
<add> indx = np.meshgrid(*[np.arange(x) for x in a.shape], sparse=True,
<add> indexing='ij')
<ide> indx[axis] = filled(a, filler).argsort(axis=axis, kind=kind, order=order)
<ide> return a[indx]
<ide> sort.__doc__ = MaskedArray.sort.__doc__ | 1 |
Javascript | Javascript | fix uniforms to support fog | 10710ebf2cbaee16d742094bf41d74a7c2304c91 | <ide><path>examples/jsm/loaders/LDrawLoader.js
<ide> import {
<ide> MeshPhongMaterial,
<ide> MeshStandardMaterial,
<ide> ShaderMaterial,
<add> UniformsLib,
<add> UniformsUtils,
<ide> Vector3
<ide> } from '../../../build/three.module.js';
<ide>
<ide> var LDrawLoader = ( function () {
<ide> edgeMaterial.userData.conditionalEdgeMaterial = new ShaderMaterial( {
<ide> vertexShader: conditionalLineVertShader,
<ide> fragmentShader: conditionalLineFragShader,
<del> uniforms: {
<del> diffuse: {
<del> value: new Color( edgeColour )
<del> },
<del> opacity: {
<del> value: alpha
<add> uniforms: UniformsUtils.merge( [
<add> UniformsLib.fog,
<add> {
<add> diffuse: {
<add> value: new Color( edgeColour )
<add> },
<add> opacity: {
<add> value: alpha
<add> }
<ide> }
<del> },
<add> ] ),
<add> fog: true,
<ide> transparent: isTransparent,
<ide> depthWrite: ! isTransparent
<ide> } ); | 1 |
Text | Text | fix typo in buffer.md | fb93b713075caa302b617a6cdb495f649bc45622 | <ide><path>doc/api/buffer.md
<ide> added: v15.7.0
<ide> * `type` {string} The content-type for the new `Blob`
<ide>
<ide> Creates and returns a new `Blob` containing a subset of this `Blob` objects
<del>data. The original `Blob` is not alterered.
<add>data. The original `Blob` is not altered.
<ide>
<ide> ### `blob.text()`
<ide> <!-- YAML | 1 |
Javascript | Javascript | replace _binding with _handle | 5344d0c1034b28f9e6de914430d8c8436ad85105 | <ide><path>lib/crypto.js
<ide> exports.createHash = exports.Hash = Hash;
<ide> function Hash(algorithm, options) {
<ide> if (!(this instanceof Hash))
<ide> return new Hash(algorithm, options);
<del> this._binding = new binding.Hash(algorithm);
<add> this._handle = new binding.Hash(algorithm);
<ide> LazyTransform.call(this, options);
<ide> }
<ide>
<ide> util.inherits(Hash, LazyTransform);
<ide>
<ide> Hash.prototype._transform = function(chunk, encoding, callback) {
<del> this._binding.update(chunk, encoding);
<add> this._handle.update(chunk, encoding);
<ide> callback();
<ide> };
<ide>
<ide> Hash.prototype._flush = function(callback) {
<ide> var encoding = this._readableState.encoding || 'buffer';
<del> this.push(this._binding.digest(encoding), encoding);
<add> this.push(this._handle.digest(encoding), encoding);
<ide> callback();
<ide> };
<ide>
<ide> Hash.prototype.update = function(data, encoding) {
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding === 'buffer' && util.isString(data))
<ide> encoding = 'binary';
<del> this._binding.update(data, encoding);
<add> this._handle.update(data, encoding);
<ide> return this;
<ide> };
<ide>
<ide>
<ide> Hash.prototype.digest = function(outputEncoding) {
<ide> outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
<del> return this._binding.digest(outputEncoding);
<add> return this._handle.digest(outputEncoding);
<ide> };
<ide>
<ide>
<ide> exports.createHmac = exports.Hmac = Hmac;
<ide> function Hmac(hmac, key, options) {
<ide> if (!(this instanceof Hmac))
<ide> return new Hmac(hmac, key, options);
<del> this._binding = new binding.Hmac();
<del> this._binding.init(hmac, toBuf(key));
<add> this._handle = new binding.Hmac();
<add> this._handle.init(hmac, toBuf(key));
<ide> LazyTransform.call(this, options);
<ide> }
<ide>
<ide> exports.createCipher = exports.Cipher = Cipher;
<ide> function Cipher(cipher, password, options) {
<ide> if (!(this instanceof Cipher))
<ide> return new Cipher(cipher, password, options);
<del> this._binding = new binding.CipherBase(true);
<add> this._handle = new binding.CipherBase(true);
<ide>
<del> this._binding.init(cipher, toBuf(password));
<add> this._handle.init(cipher, toBuf(password));
<ide> this._decoder = null;
<ide>
<ide> LazyTransform.call(this, options);
<ide> function Cipher(cipher, password, options) {
<ide> util.inherits(Cipher, LazyTransform);
<ide>
<ide> Cipher.prototype._transform = function(chunk, encoding, callback) {
<del> this.push(this._binding.update(chunk, encoding));
<add> this.push(this._handle.update(chunk, encoding));
<ide> callback();
<ide> };
<ide>
<ide> Cipher.prototype._flush = function(callback) {
<ide> try {
<del> this.push(this._binding.final());
<add> this.push(this._handle.final());
<ide> } catch (e) {
<ide> callback(e);
<ide> return;
<ide> Cipher.prototype.update = function(data, inputEncoding, outputEncoding) {
<ide> inputEncoding = inputEncoding || exports.DEFAULT_ENCODING;
<ide> outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
<ide>
<del> var ret = this._binding.update(data, inputEncoding);
<add> var ret = this._handle.update(data, inputEncoding);
<ide>
<ide> if (outputEncoding && outputEncoding !== 'buffer') {
<ide> this._decoder = getDecoder(this._decoder, outputEncoding);
<ide> Cipher.prototype.update = function(data, inputEncoding, outputEncoding) {
<ide>
<ide> Cipher.prototype.final = function(outputEncoding) {
<ide> outputEncoding = outputEncoding || exports.DEFAULT_ENCODING;
<del> var ret = this._binding.final();
<add> var ret = this._handle.final();
<ide>
<ide> if (outputEncoding && outputEncoding !== 'buffer') {
<ide> this._decoder = getDecoder(this._decoder, outputEncoding);
<ide> Cipher.prototype.final = function(outputEncoding) {
<ide>
<ide>
<ide> Cipher.prototype.setAutoPadding = function(ap) {
<del> this._binding.setAutoPadding(ap);
<add> this._handle.setAutoPadding(ap);
<ide> return this;
<ide> };
<ide>
<ide> exports.createCipheriv = exports.Cipheriv = Cipheriv;
<ide> function Cipheriv(cipher, key, iv, options) {
<ide> if (!(this instanceof Cipheriv))
<ide> return new Cipheriv(cipher, key, iv, options);
<del> this._binding = new binding.CipherBase(true);
<del> this._binding.initiv(cipher, toBuf(key), toBuf(iv));
<add> this._handle = new binding.CipherBase(true);
<add> this._handle.initiv(cipher, toBuf(key), toBuf(iv));
<ide> this._decoder = null;
<ide>
<ide> LazyTransform.call(this, options);
<ide> Cipheriv.prototype.final = Cipher.prototype.final;
<ide> Cipheriv.prototype.setAutoPadding = Cipher.prototype.setAutoPadding;
<ide>
<ide> Cipheriv.prototype.getAuthTag = function() {
<del> return this._binding.getAuthTag();
<add> return this._handle.getAuthTag();
<ide> };
<ide>
<ide>
<ide> Cipheriv.prototype.setAuthTag = function(tagbuf) {
<del> this._binding.setAuthTag(tagbuf);
<add> this._handle.setAuthTag(tagbuf);
<ide> };
<ide>
<ide> Cipheriv.prototype.setAAD = function(aadbuf) {
<del> this._binding.setAAD(aadbuf);
<add> this._handle.setAAD(aadbuf);
<ide> };
<ide>
<ide>
<ide> function Decipher(cipher, password, options) {
<ide> if (!(this instanceof Decipher))
<ide> return new Decipher(cipher, password, options);
<ide>
<del> this._binding = new binding.CipherBase(false);
<del> this._binding.init(cipher, toBuf(password));
<add> this._handle = new binding.CipherBase(false);
<add> this._handle.init(cipher, toBuf(password));
<ide> this._decoder = null;
<ide>
<ide> LazyTransform.call(this, options);
<ide> function Decipheriv(cipher, key, iv, options) {
<ide> if (!(this instanceof Decipheriv))
<ide> return new Decipheriv(cipher, key, iv, options);
<ide>
<del> this._binding = new binding.CipherBase(false);
<del> this._binding.initiv(cipher, toBuf(key), toBuf(iv));
<add> this._handle = new binding.CipherBase(false);
<add> this._handle.initiv(cipher, toBuf(key), toBuf(iv));
<ide> this._decoder = null;
<ide>
<ide> LazyTransform.call(this, options);
<ide> exports.createSign = exports.Sign = Sign;
<ide> function Sign(algorithm, options) {
<ide> if (!(this instanceof Sign))
<ide> return new Sign(algorithm, options);
<del> this._binding = new binding.Sign();
<del> this._binding.init(algorithm);
<add> this._handle = new binding.Sign();
<add> this._handle.init(algorithm);
<ide>
<ide> stream.Writable.call(this, options);
<ide> }
<ide>
<ide> util.inherits(Sign, stream.Writable);
<ide>
<ide> Sign.prototype._write = function(chunk, encoding, callback) {
<del> this._binding.update(chunk, encoding);
<add> this._handle.update(chunk, encoding);
<ide> callback();
<ide> };
<ide>
<ide> Sign.prototype.sign = function(options, encoding) {
<ide>
<ide> var key = options.key || options;
<ide> var passphrase = options.passphrase || null;
<del> var ret = this._binding.sign(toBuf(key), null, passphrase);
<add> var ret = this._handle.sign(toBuf(key), null, passphrase);
<ide>
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding && encoding !== 'buffer')
<ide> function Verify(algorithm, options) {
<ide> if (!(this instanceof Verify))
<ide> return new Verify(algorithm, options);
<ide>
<del> this._binding = new binding.Verify;
<del> this._binding.init(algorithm);
<add> this._handle = new binding.Verify;
<add> this._handle.init(algorithm);
<ide>
<ide> stream.Writable.call(this, options);
<ide> }
<ide> Verify.prototype.update = Sign.prototype.update;
<ide>
<ide> Verify.prototype.verify = function(object, signature, sigEncoding) {
<ide> sigEncoding = sigEncoding || exports.DEFAULT_ENCODING;
<del> return this._binding.verify(toBuf(object), toBuf(signature, sigEncoding));
<add> return this._handle.verify(toBuf(object), toBuf(signature, sigEncoding));
<ide> };
<ide>
<ide>
<ide> function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) {
<ide> else if (typeof generator !== 'number')
<ide> generator = toBuf(generator, genEncoding);
<ide>
<del> this._binding = new binding.DiffieHellman(sizeOrKey, generator);
<add> this._handle = new binding.DiffieHellman(sizeOrKey, generator);
<ide> Object.defineProperty(this, 'verifyError', {
<ide> enumerable: true,
<del> value: this._binding.verifyError,
<add> value: this._handle.verifyError,
<ide> writable: false
<ide> });
<ide> }
<ide> exports.DiffieHellmanGroup =
<ide> function DiffieHellmanGroup(name) {
<ide> if (!(this instanceof DiffieHellmanGroup))
<ide> return new DiffieHellmanGroup(name);
<del> this._binding = new binding.DiffieHellmanGroup(name);
<add> this._handle = new binding.DiffieHellmanGroup(name);
<ide> Object.defineProperty(this, 'verifyError', {
<ide> enumerable: true,
<del> value: this._binding.verifyError,
<add> value: this._handle.verifyError,
<ide> writable: false
<ide> });
<ide> }
<ide> DiffieHellmanGroup.prototype.generateKeys =
<ide> dhGenerateKeys;
<ide>
<ide> function dhGenerateKeys(encoding) {
<del> var keys = this._binding.generateKeys();
<add> var keys = this._handle.generateKeys();
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding && encoding !== 'buffer')
<ide> keys = keys.toString(encoding);
<ide> DiffieHellmanGroup.prototype.computeSecret =
<ide> function dhComputeSecret(key, inEnc, outEnc) {
<ide> inEnc = inEnc || exports.DEFAULT_ENCODING;
<ide> outEnc = outEnc || exports.DEFAULT_ENCODING;
<del> var ret = this._binding.computeSecret(toBuf(key, inEnc));
<add> var ret = this._handle.computeSecret(toBuf(key, inEnc));
<ide> if (outEnc && outEnc !== 'buffer')
<ide> ret = ret.toString(outEnc);
<ide> return ret;
<ide> DiffieHellmanGroup.prototype.getPrime =
<ide> dhGetPrime;
<ide>
<ide> function dhGetPrime(encoding) {
<del> var prime = this._binding.getPrime();
<add> var prime = this._handle.getPrime();
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding && encoding !== 'buffer')
<ide> prime = prime.toString(encoding);
<ide> DiffieHellmanGroup.prototype.getGenerator =
<ide> dhGetGenerator;
<ide>
<ide> function dhGetGenerator(encoding) {
<del> var generator = this._binding.getGenerator();
<add> var generator = this._handle.getGenerator();
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding && encoding !== 'buffer')
<ide> generator = generator.toString(encoding);
<ide> DiffieHellmanGroup.prototype.getPublicKey =
<ide> dhGetPublicKey;
<ide>
<ide> function dhGetPublicKey(encoding) {
<del> var key = this._binding.getPublicKey();
<add> var key = this._handle.getPublicKey();
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding && encoding !== 'buffer')
<ide> key = key.toString(encoding);
<ide> DiffieHellmanGroup.prototype.getPrivateKey =
<ide> dhGetPrivateKey;
<ide>
<ide> function dhGetPrivateKey(encoding) {
<del> var key = this._binding.getPrivateKey();
<add> var key = this._handle.getPrivateKey();
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<ide> if (encoding && encoding !== 'buffer')
<ide> key = key.toString(encoding);
<ide> function dhGetPrivateKey(encoding) {
<ide>
<ide> DiffieHellman.prototype.setPublicKey = function(key, encoding) {
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<del> this._binding.setPublicKey(toBuf(key, encoding));
<add> this._handle.setPublicKey(toBuf(key, encoding));
<ide> return this;
<ide> };
<ide>
<ide>
<ide> DiffieHellman.prototype.setPrivateKey = function(key, encoding) {
<ide> encoding = encoding || exports.DEFAULT_ENCODING;
<del> this._binding.setPrivateKey(toBuf(key, encoding));
<add> this._handle.setPrivateKey(toBuf(key, encoding));
<ide> return this;
<ide> };
<ide>
<ide> function Certificate() {
<ide> if (!(this instanceof Certificate))
<ide> return new Certificate();
<ide>
<del> this._binding = new binding.Certificate();
<add> this._handle = new binding.Certificate();
<ide> }
<ide>
<ide>
<ide> Certificate.prototype.verifySpkac = function(object) {
<del> return this._binding.verifySpkac(object);
<add> return this._handle.verifySpkac(object);
<ide> };
<ide>
<ide>
<ide> Certificate.prototype.exportPublicKey = function(object, encoding) {
<del> return this._binding.exportPublicKey(toBuf(object, encoding));
<add> return this._handle.exportPublicKey(toBuf(object, encoding));
<ide> };
<ide>
<ide>
<ide> Certificate.prototype.exportChallenge = function(object, encoding) {
<del> return this._binding.exportChallenge(toBuf(object, encoding));
<add> return this._handle.exportChallenge(toBuf(object, encoding));
<ide> };
<ide>
<ide>
<ide><path>lib/zlib.js
<ide> function Zlib(opts, mode) {
<ide> }
<ide> }
<ide>
<del> this._binding = new binding.Zlib(mode);
<add> this._handle = new binding.Zlib(mode);
<ide>
<ide> var self = this;
<ide> this._hadError = false;
<del> this._binding.onerror = function(message, errno) {
<add> this._handle.onerror = function(message, errno) {
<ide> // there is no way to cleanly recover.
<ide> // continuing only obscures problems.
<del> self._binding = null;
<add> self._handle = null;
<ide> self._hadError = true;
<ide>
<ide> var error = new Error(message);
<ide> function Zlib(opts, mode) {
<ide> var strategy = exports.Z_DEFAULT_STRATEGY;
<ide> if (util.isNumber(opts.strategy)) strategy = opts.strategy;
<ide>
<del> this._binding.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
<del> level,
<del> opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
<del> strategy,
<del> opts.dictionary);
<add> this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS,
<add> level,
<add> opts.memLevel || exports.Z_DEFAULT_MEMLEVEL,
<add> strategy,
<add> opts.dictionary);
<ide>
<ide> this._buffer = new Buffer(this._chunkSize);
<ide> this._offset = 0;
<ide> Zlib.prototype.params = function(level, strategy, callback) {
<ide> if (this._level !== level || this._strategy !== strategy) {
<ide> var self = this;
<ide> this.flush(binding.Z_SYNC_FLUSH, function() {
<del> self._binding.params(level, strategy);
<add> self._handle.params(level, strategy);
<ide> if (!self._hadError) {
<ide> self._level = level;
<ide> self._strategy = strategy;
<ide> Zlib.prototype.params = function(level, strategy, callback) {
<ide> };
<ide>
<ide> Zlib.prototype.reset = function() {
<del> return this._binding.reset();
<add> return this._handle.reset();
<ide> };
<ide>
<ide> // This is the _flush function called by the transform class,
<ide> Zlib.prototype.close = function(callback) {
<ide>
<ide> this._closed = true;
<ide>
<del> this._binding.close();
<add> this._handle.close();
<ide>
<ide> var self = this;
<ide> process.nextTick(function() {
<ide> Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
<ide> });
<ide>
<ide> do {
<del> var res = this._binding.writeSync(flushFlag,
<del> chunk, // in
<del> inOff, // in_off
<del> availInBefore, // in_len
<del> this._buffer, // out
<del> this._offset, //out_off
<del> availOutBefore); // out_len
<add> var res = this._handle.writeSync(flushFlag,
<add> chunk, // in
<add> inOff, // in_off
<add> availInBefore, // in_len
<add> this._buffer, // out
<add> this._offset, //out_off
<add> availOutBefore); // out_len
<ide> } while (!this._hadError && callback(res[0], res[1]));
<ide>
<ide> if (this._hadError) {
<ide> Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
<ide> return buf;
<ide> }
<ide>
<del> var req = this._binding.write(flushFlag,
<del> chunk, // in
<del> inOff, // in_off
<del> availInBefore, // in_len
<del> this._buffer, // out
<del> this._offset, //out_off
<del> availOutBefore); // out_len
<add> var req = this._handle.write(flushFlag,
<add> chunk, // in
<add> inOff, // in_off
<add> availInBefore, // in_len
<add> this._buffer, // out
<add> this._offset, //out_off
<add> availOutBefore); // out_len
<ide>
<ide> req.buffer = chunk;
<ide> req.callback = callback;
<ide> Zlib.prototype._processChunk = function(chunk, flushFlag, cb) {
<ide> if (!async)
<ide> return true;
<ide>
<del> var newReq = self._binding.write(flushFlag,
<del> chunk,
<del> inOff,
<del> availInBefore,
<del> self._buffer,
<del> self._offset,
<del> self._chunkSize);
<add> var newReq = self._handle.write(flushFlag,
<add> chunk,
<add> inOff,
<add> availInBefore,
<add> self._buffer,
<add> self._offset,
<add> self._chunkSize);
<ide> newReq.callback = callback; // this same function
<ide> newReq.buffer = chunk;
<ide> return; | 2 |
Text | Text | update hasfipscrypto in test/common/readme | 2111207f445f591a412a9420464d451ef748975a | <ide><path>test/common/README.md
<ide> Indicates whether OpenSSL is available.
<ide> ### hasFipsCrypto
<ide> * [<boolean>]
<ide>
<del>Indicates `hasCrypto` and `crypto` with fips.
<add>Indicates that Node.js has been linked with a FIPS compatible OpenSSL library,
<add>and that FIPS as been enabled using `--enable-fips`.
<add>
<add>To only detect if the OpenSSL library is FIPS compatible, regardless if it has
<add>been enabled or not, then `process.config.variables.openssl_is_fips` can be
<add>used to determine that situation.
<ide>
<ide> ### hasIntl
<ide> * [<boolean>] | 1 |
Text | Text | fix typo for rewrites to rewrite. | 5646e43f8347db00a94f5deb103ec45a9a50236f | <ide><path>docs/api-reference/next/server.md
<ide> export function middleware(request: NextRequest) {
<ide> const { device } = userAgent(request)
<ide> const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
<ide> url.searchParams.set('viewport', viewport)
<del> return NextResponse.rewrites(url)
<add> return NextResponse.rewrite(url)
<ide> }
<ide> ```
<ide>
<ide><path>errors/middleware-upgrade-guide.md
<ide> export function middleware(request: NextRequest) {
<ide> const url = request.nextUrl
<ide> const viewport = request.ua.device.type === 'mobile' ? 'mobile' : 'desktop'
<ide> url.searchParams.set('viewport', viewport)
<del> return NextResponse.rewrites(url)
<add> return NextResponse.rewrite(url)
<ide> }
<ide> ```
<ide>
<ide> export function middleware(request: NextRequest) {
<ide> const { device } = userAgent(request)
<ide> const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
<ide> url.searchParams.set('viewport', viewport)
<del> return NextResponse.rewrites(url)
<add> return NextResponse.rewrite(url)
<ide> }
<ide> ```
<ide>
<ide><path>errors/middleware-user-agent.md
<ide> export function middleware(request: NextRequest) {
<ide> const url = request.nextUrl
<ide> const viewport = request.ua.device.type === 'mobile' ? 'mobile' : 'desktop'
<ide> url.searchParams.set('viewport', viewport)
<del> return NextResponse.rewrites(url)
<add> return NextResponse.rewrite(url)
<ide> }
<ide> ```
<ide>
<ide> export function middleware(request: NextRequest) {
<ide> const { device } = userAgent(request)
<ide> const viewport = device.type === 'mobile' ? 'mobile' : 'desktop'
<ide> url.searchParams.set('viewport', viewport)
<del> return NextResponse.rewrites(url)
<add> return NextResponse.rewrite(url)
<ide> }
<ide> ``` | 3 |
PHP | PHP | add autoloaders for testapp and test plugins | 44b31a0b2c51fe954af9753820704d0dd0ab4f02 | <ide><path>lib/Cake/Test/init.php
<ide> define('WWW_ROOT', APP . WEBROOT_DIR . DS);
<ide> define('TESTS', APP . 'Test' . DS);
<ide>
<add>define('TEST_APP', ROOT . '/lib/Cake/Test/TestApp/');
<add>
<ide> //@codingStandardsIgnoreStart
<ide> @mkdir(LOGS);
<ide> @mkdir(CACHE);
<ide>
<ide> (new Cake\Core\ClassLoader('Cake', dirname(dirname(__DIR__)) ))->register();
<ide> (new Cake\Core\ClassLoader('TestApp', dirname(__DIR__) . '/Test'))->register();
<add>(new Cake\Core\ClassLoader('TestPlugin', CAKE . '/Test/TestApp/Plugin/'))->register();
<add>(new Cake\Core\ClassLoader('TestPluginTwo', CAKE . '/Test/TestApp/Plugin/'))->register();
<add>(new Cake\Core\ClassLoader('PluginJs', CAKE . '/Test/TestApp/Plugin/'))->register();
<ide>
<ide> require CORE_PATH . 'Cake/bootstrap.php';
<ide>
<ide> 'imageBaseUrl' => 'img/',
<ide> 'jsBaseUrl' => 'js/',
<ide> 'cssBaseUrl' => 'css/',
<add> 'pluginPath' => TEST_APP . 'Plugin/',
<ide> ]);
<ide>
<ide> Cache::config([ | 1 |
PHP | PHP | add early return | 05bb2b83df8f4c6dfd94b52c50e66b71e8f46729 | <ide><path>src/Illuminate/Translation/Translator.php
<ide> public function get($key, array $replace = [], $locale = null, $fallback = true)
<ide> if (! is_null($line = $this->getLine(
<ide> $namespace, $group, $locale, $item, $replace
<ide> ))) {
<del> break;
<add> return $line ?? $key;
<ide> }
<ide> }
<ide> } | 1 |
Javascript | Javascript | improve the usage of typeerror[invalid_arg_type] | e22b8d0c46728ebdaf64176191ffa2bdd0f56be9 | <ide><path>lib/_http_client.js
<ide> function ClientRequest(options, cb) {
<ide> // when createConnection is provided.
<ide> } else if (typeof agent.addRequest !== 'function') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'Agent option',
<del> ['Agent-like object', 'undefined', 'false']);
<add> ['Agent-like Object', 'undefined', 'false']);
<ide> }
<ide> this.agent = agent;
<ide>
<ide><path>lib/_http_outgoing.js
<ide> function write_(msg, chunk, encoding, callback, fromEnd) {
<ide>
<ide> if (!fromEnd && typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
<del> ['string', 'buffer']);
<add> ['string', 'Buffer']);
<ide> }
<ide>
<ide>
<ide> OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
<ide> if (chunk) {
<ide> if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
<del> ['string', 'buffer']);
<add> ['string', 'Buffer']);
<ide> }
<ide> if (!this._header) {
<ide> if (typeof chunk === 'string')
<ide><path>lib/_tls_wrap.js
<ide> function Server(options, listener) {
<ide> } else if (options == null || typeof options === 'object') {
<ide> options = options || {};
<ide> } else {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide> }
<ide>
<ide>
<ide><path>lib/assert.js
<ide> function innerThrows(shouldThrow, block, expected, message) {
<ide> var details = '';
<ide>
<ide> if (typeof block !== 'function') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'block', 'function',
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'block', 'Function',
<ide> block);
<ide> }
<ide>
<ide><path>lib/buffer.js
<ide> Buffer.from = function from(value, encodingOrOffset, length) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE',
<ide> 'first argument',
<del> ['string', 'buffer', 'arrayBuffer', 'array', 'array-like object'],
<add> ['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'],
<ide> value
<ide> );
<ide> }
<ide> Buffer.from = function from(value, encodingOrOffset, length) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE',
<ide> 'first argument',
<del> ['string', 'buffer', 'arrayBuffer', 'array', 'array-like object'],
<add> ['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'],
<ide> value
<ide> );
<ide> };
<ide> Buffer.isBuffer = function isBuffer(b) {
<ide> Buffer.compare = function compare(a, b) {
<ide> if (!isUint8Array(a) || !isUint8Array(b)) {
<ide> throw new errors.TypeError(
<del> 'ERR_INVALID_ARG_TYPE', ['buf1', 'buf2'], ['buffer', 'uint8Array']
<add> 'ERR_INVALID_ARG_TYPE', ['buf1', 'buf2'], ['Buffer', 'Uint8Array']
<ide> );
<ide> }
<ide>
<ide> Buffer.isEncoding = function isEncoding(encoding) {
<ide> Buffer[kIsEncodingSymbol] = Buffer.isEncoding;
<ide>
<ide> const kConcatErr = new errors.TypeError(
<del> 'ERR_INVALID_ARG_TYPE', 'list', ['array', 'buffer', 'uint8Array']
<add> 'ERR_INVALID_ARG_TYPE', 'list', ['Array', 'Buffer', 'Uint8Array']
<ide> );
<ide>
<ide> Buffer.concat = function concat(list, length) {
<ide> function byteLength(string, encoding) {
<ide>
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE', 'string',
<del> ['string', 'buffer', 'arrayBuffer'], string
<add> ['string', 'Buffer', 'ArrayBuffer'], string
<ide> );
<ide> }
<ide>
<ide> Buffer.prototype.equals = function equals(b) {
<ide> if (!isUint8Array(b)) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE', 'otherBuffer',
<del> ['buffer', 'uint8Array'], b
<add> ['Buffer', 'Uint8Array'], b
<ide> );
<ide> }
<ide> if (this === b)
<ide> Buffer.prototype.compare = function compare(target,
<ide> if (!isUint8Array(target)) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE', 'target',
<del> ['buffer', 'uint8Array'], target
<add> ['Buffer', 'Uint8Array'], target
<ide> );
<ide> }
<ide> if (arguments.length === 1)
<ide> function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
<ide>
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE', 'value',
<del> ['string', 'buffer', 'uint8Array'], val
<add> ['string', 'Buffer', 'Uint8Array'], val
<ide> );
<ide> }
<ide>
<ide><path>lib/dgram.js
<ide> function newHandle(type, lookup) {
<ide> if (lookup === undefined)
<ide> lookup = dns.lookup;
<ide> else if (typeof lookup !== 'function')
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'lookup', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'lookup', 'Function');
<ide>
<ide> if (type === 'udp4') {
<ide> const handle = new UDP();
<ide><path>lib/dns.js
<ide> function lookup(hostname, options, callback) {
<ide> // Parse arguments
<ide> if (hostname && typeof hostname !== 'string') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'hostname',
<del> ['string', 'falsey'], hostname);
<add> ['string', 'falsy'], hostname);
<ide> } else if (typeof options === 'function') {
<ide> callback = options;
<ide> family = 0;
<ide><path>lib/events.js
<ide> function _addListener(target, type, listener, prepend) {
<ide>
<ide> if (typeof listener !== 'function') {
<ide> const errors = lazyErrors();
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function');
<ide> }
<ide>
<ide> events = target._events;
<ide> function _onceWrap(target, type, listener) {
<ide> EventEmitter.prototype.once = function once(type, listener) {
<ide> if (typeof listener !== 'function') {
<ide> const errors = lazyErrors();
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function');
<ide> }
<ide> this.on(type, _onceWrap(this, type, listener));
<ide> return this;
<ide> EventEmitter.prototype.prependOnceListener =
<ide> if (typeof listener !== 'function') {
<ide> const errors = lazyErrors();
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener',
<del> 'function');
<add> 'Function');
<ide> }
<ide> this.prependListener(type, _onceWrap(this, type, listener));
<ide> return this;
<ide> EventEmitter.prototype.removeListener =
<ide> if (typeof listener !== 'function') {
<ide> const errors = lazyErrors();
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener',
<del> 'function');
<add> 'Function');
<ide> }
<ide>
<ide> events = this._events;
<ide><path>lib/fs.js
<ide> function getOptions(options, defaultOptions) {
<ide> } else if (typeof options !== 'object') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'options',
<del> ['string', 'object'],
<add> ['string', 'Object'],
<ide> options);
<ide> }
<ide>
<ide> function toUnixTimestamp(time) {
<ide> }
<ide> throw new errors.Error('ERR_INVALID_ARG_TYPE',
<ide> 'time',
<del> ['Date', 'time in seconds'],
<add> ['Date', 'Time in seconds'],
<ide> time);
<ide> }
<ide>
<ide> fs.watchFile = function(filename, options, listener) {
<ide> if (typeof listener !== 'function') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'listener',
<del> 'function',
<add> 'Function',
<ide> listener);
<ide> }
<ide>
<ide> fs.copyFile = function(src, dest, flags, callback) {
<ide> callback = flags;
<ide> flags = 0;
<ide> } else if (typeof callback !== 'function') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'callback', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'callback', 'Function');
<ide> }
<ide>
<ide> src = getPathFromURL(src);
<ide><path>lib/inspector.js
<ide> class Session extends EventEmitter {
<ide> }
<ide> if (params && typeof params !== 'object') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<del> 'params', 'object', params);
<add> 'params', 'Object', params);
<ide> }
<ide> if (callback && typeof callback !== 'function') {
<ide> throw new errors.TypeError('ERR_INVALID_CALLBACK');
<ide><path>lib/internal/child_process.js
<ide> ChildProcess.prototype.spawn = function(options) {
<ide> var i;
<ide>
<ide> if (options === null || typeof options !== 'object') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object',
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object',
<ide> options);
<ide> }
<ide>
<ide> function setupChannel(target, channel) {
<ide> options = undefined;
<ide> } else if (options !== undefined &&
<ide> (options === null || typeof options !== 'object')) {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object',
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object',
<ide> options);
<ide> }
<ide>
<ide><path>lib/internal/encoding.js
<ide> function makeTextDecoderICU() {
<ide> constructor(encoding = 'utf-8', options = {}) {
<ide> encoding = `${encoding}`;
<ide> if (typeof options !== 'object')
<del> throw new errors.Error('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.Error('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide>
<ide> const enc = getEncodingFromLabel(encoding);
<ide> if (enc === undefined)
<ide> function makeTextDecoderICU() {
<ide> ['ArrayBuffer', 'ArrayBufferView']);
<ide> }
<ide> if (typeof options !== 'object') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide> }
<ide>
<ide> var flags = 0;
<ide> function makeTextDecoderJS() {
<ide> constructor(encoding = 'utf-8', options = {}) {
<ide> encoding = `${encoding}`;
<ide> if (typeof options !== 'object')
<del> throw new errors.Error('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.Error('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide>
<ide> const enc = getEncodingFromLabel(encoding);
<ide> if (enc === undefined || !hasConverter(enc))
<ide> function makeTextDecoderJS() {
<ide> ['ArrayBuffer', 'ArrayBufferView']);
<ide> }
<ide> if (typeof options !== 'object') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide> }
<ide>
<ide> if (this[kFlags] & CONVERTER_FLAGS_FLUSH) {
<ide><path>lib/internal/errors.js
<ide> class SystemError extends makeNodeError(Error) {
<ide> class AssertionError extends Error {
<ide> constructor(options) {
<ide> if (typeof options !== 'object' || options === null) {
<del> throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide> }
<ide> var { actual, expected, message, operator, stackStartFunction } = options;
<ide> if (message) {
<ide><path>lib/internal/http2/core.js
<ide> function connect(authority, options, listener) {
<ide> if (typeof authority === 'string')
<ide> authority = new URL(authority);
<ide>
<del> assertIsObject(authority, 'authority', ['string', 'object', 'URL']);
<add> assertIsObject(authority, 'authority', ['string', 'Object', 'URL']);
<ide>
<ide> debug(`connecting to ${authority}`);
<ide>
<ide> function createSecureServer(options, handler) {
<ide> if (options == null || typeof options !== 'object') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'options',
<del> 'object');
<add> 'Object');
<ide> }
<ide> debug('creating http2secureserver');
<ide> return new Http2SecureServer(options, handler);
<ide><path>lib/internal/http2/util.js
<ide> class NghttpError extends Error {
<ide> }
<ide> }
<ide>
<del>function assertIsObject(value, name, types = 'object') {
<add>function assertIsObject(value, name, types = 'Object') {
<ide> if (value !== undefined &&
<ide> (value === null ||
<ide> typeof value !== 'object' ||
<ide><path>lib/internal/process.js
<ide> function setup_cpuUsage() {
<ide> if (prevValue) {
<ide> if (!previousValueIsValid(prevValue.user)) {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<del> 'preValue.user', 'Number');
<add> 'preValue.user', 'number');
<ide> }
<ide>
<ide> if (!previousValueIsValid(prevValue.system)) {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<del> 'preValue.system', 'Number');
<add> 'preValue.system', 'number');
<ide> }
<ide> }
<ide>
<ide> function setupKillAndExit() {
<ide>
<ide> // eslint-disable-next-line eqeqeq
<ide> if (pid != (pid | 0)) {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'pid', 'Number');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'pid', 'number');
<ide> }
<ide>
<ide> // preserve null signal
<ide><path>lib/internal/url.js
<ide> Object.defineProperties(URL.prototype, {
<ide> // eslint-disable-next-line func-name-matching
<ide> value: function format(options) {
<ide> if (options && typeof options !== 'object')
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide> options = util._extend({
<ide> fragment: true,
<ide> unicode: false,
<ide><path>lib/internal/util.js
<ide> const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs');
<ide>
<ide> function promisify(original) {
<ide> if (typeof original !== 'function')
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'original', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'original', 'Function');
<ide>
<ide> if (original[kCustomPromisifiedSymbol]) {
<ide> const fn = original[kCustomPromisifiedSymbol];
<ide> if (typeof fn !== 'function') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'util.promisify.custom',
<del> 'function',
<add> 'Function',
<ide> fn);
<ide> }
<ide> Object.defineProperty(fn, kCustomPromisifiedSymbol, {
<ide><path>lib/net.js
<ide> function lookupAndConnect(self, options) {
<ide> if (options.lookup && typeof options.lookup !== 'function')
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'options.lookup',
<del> 'function',
<add> 'Function',
<ide> options.lookup);
<ide>
<ide> var dnsopts = {
<ide> function Server(options, connectionListener) {
<ide> } else {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'options',
<del> 'object',
<add> 'Object',
<ide> options);
<ide> }
<ide>
<ide><path>lib/repl.js
<ide> REPLServer.prototype.defineCommand = function(keyword, cmd) {
<ide> } else if (typeof cmd.action !== 'function') {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE',
<ide> 'action',
<del> 'function',
<add> 'Function',
<ide> cmd.action);
<ide> }
<ide> this.commands[keyword] = cmd;
<ide><path>lib/url.js
<ide> function urlFormat(urlObject, options) {
<ide> urlObject = urlParse(urlObject);
<ide> } else if (typeof urlObject !== 'object' || urlObject === null) {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'urlObject',
<del> ['object', 'string'], urlObject);
<add> ['Object', 'string'], urlObject);
<ide> } else if (!(urlObject instanceof Url)) {
<ide> var format = urlObject[formatSymbol];
<ide> return format ?
<ide><path>lib/util.js
<ide> Object.defineProperty(inspect, 'defaultOptions', {
<ide> },
<ide> set(options) {
<ide> if (options === null || typeof options !== 'object') {
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object');
<ide> }
<ide> Object.assign(inspectDefaultOptions, options);
<ide> return inspectDefaultOptions;
<ide> function log() {
<ide> function inherits(ctor, superCtor) {
<ide>
<ide> if (ctor === undefined || ctor === null)
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ctor', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ctor', 'Function');
<ide>
<ide> if (superCtor === undefined || superCtor === null)
<del> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'superCtor', 'function');
<add> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'superCtor', 'Function');
<ide>
<ide> if (superCtor.prototype === undefined) {
<ide> throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'superCtor.prototype',
<del> 'function');
<add> 'Function');
<ide> }
<ide> ctor.super_ = superCtor;
<ide> Object.setPrototypeOf(ctor.prototype, superCtor.prototype);
<ide> function callbackify(original) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE',
<ide> 'original',
<del> 'function');
<add> 'Function');
<ide> }
<ide>
<ide> // We DO NOT return the promise as it gives the user a false sense that
<ide> function callbackify(original) {
<ide> throw new errors.TypeError(
<ide> 'ERR_INVALID_ARG_TYPE',
<ide> 'last argument',
<del> 'function');
<add> 'Function');
<ide> }
<ide> const cb = (...args) => { Reflect.apply(maybeCb, this, args); };
<ide> // In true node style we process the callback on `nextTick` with all the
<ide><path>test/parallel/test-assert.js
<ide> try {
<ide> common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "block" argument must be of type function. Received ' +
<del> `type ${typeName(block)}`
<add> message: 'The "block" argument must be of type Function. Received ' +
<add> 'type ' + typeName(block)
<ide> })(e);
<ide> }
<ide>
<ide> assert.throws(() => {
<ide> {
<ide> // bad args to AssertionError constructor should throw TypeError
<ide> const args = [1, true, false, '', null, Infinity, Symbol('test'), undefined];
<del> const re = /^The "options" argument must be of type object$/;
<add> const re = /^The "options" argument must be of type Object$/;
<ide> args.forEach((input) => {
<ide> assert.throws(
<ide> () => new assert.AssertionError(input),
<ide><path>test/parallel/test-buffer-alloc.js
<ide> assert.throws(() => Buffer.allocUnsafe(10).copy(),
<ide> /TypeError: argument should be a Buffer/);
<ide>
<ide> const regErrorMsg =
<del> new RegExp('The first argument must be one of type string, buffer, ' +
<del> 'arrayBuffer, array, or array-like object\\.');
<add> new RegExp('The first argument must be one of type string, Buffer, ' +
<add> 'ArrayBuffer, Array, or Array-like Object\\.');
<ide>
<ide> assert.throws(() => Buffer.from(), regErrorMsg);
<ide> assert.throws(() => Buffer.from(null), regErrorMsg);
<ide><path>test/parallel/test-buffer-bytelength.js
<ide> const vm = require('vm');
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "string" argument must be one of type string, ' +
<del> `buffer, or arrayBuffer. Received type ${typeof args[0]}`
<add> `Buffer, or ArrayBuffer. Received type ${typeof args[0]}`
<ide> }
<ide> );
<ide> });
<ide><path>test/parallel/test-buffer-compare-offset.js
<ide> assert.throws(() => a.compare(), common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "target" argument must be one of ' +
<del> 'type buffer or uint8Array. Received type undefined'
<add> 'type Buffer or Uint8Array. Received type undefined'
<ide> }));
<ide><path>test/parallel/test-buffer-compare.js
<ide> const errMsg = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "buf1", "buf2" arguments must be one of ' +
<del> 'type buffer or uint8Array'
<add> 'type Buffer or Uint8Array'
<ide> }, 2);
<ide> assert.throws(() => Buffer.compare(Buffer.alloc(1), 'abc'), errMsg);
<ide>
<ide> assert.throws(() => Buffer.alloc(1).compare('abc'), common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "target" argument must be one of ' +
<del> 'type buffer or uint8Array. Received type string'
<add> 'type Buffer or Uint8Array. Received type string'
<ide> }));
<ide><path>test/parallel/test-buffer-concat.js
<ide> function assertWrongList(value) {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "list" argument must be one of type ' +
<del> 'array, buffer, or uint8Array'
<add> 'Array, Buffer, or Uint8Array'
<ide> }));
<ide> }
<ide>
<ide><path>test/parallel/test-buffer-equals.js
<ide> common.expectsError(
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "otherBuffer" argument must be one of type ' +
<del> 'buffer or uint8Array. Received type string'
<add> 'Buffer or Uint8Array. Received type string'
<ide> }
<ide> );
<ide><path>test/parallel/test-buffer-from.js
<ide> deepStrictEqual(
<ide> const err = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The first argument must be one of type string, buffer, ' +
<del> 'arrayBuffer, array, or array-like object. Received ' +
<add> message: 'The first argument must be one of type string, Buffer, ' +
<add> 'ArrayBuffer, Array, or Array-like Object. Received ' +
<ide> `type ${actualType}`
<ide> });
<ide> throws(() => Buffer.from(input), err);
<ide><path>test/parallel/test-buffer-includes.js
<ide> for (let lengthIndex = 0; lengthIndex < lengths.length; lengthIndex++) {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "value" argument must be one of type string, ' +
<del> `buffer, or uint8Array. Received type ${typeof val}`
<add> `Buffer, or Uint8Array. Received type ${typeof val}`
<ide> }
<ide> );
<ide> });
<ide><path>test/parallel/test-buffer-indexof.js
<ide> assert.strictEqual(Buffer.from('aaaaa').indexOf('b', 'ucs2'), -1);
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "value" argument must be one of type string, ' +
<del> `buffer, or uint8Array. Received type ${typeof val}`
<add> `Buffer, or Uint8Array. Received type ${typeof val}`
<ide> }
<ide> );
<ide> });
<ide><path>test/parallel/test-child-process-constructor.js
<ide> function typeName(value) {
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "options" argument must be of type object. ' +
<add> message: 'The "options" argument must be of type Object. ' +
<ide> `Received type ${typeName(options)}`
<ide> });
<ide> });
<ide><path>test/parallel/test-dgram-custom-lookup.js
<ide> const dns = require('dns');
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "lookup" argument must be of type function'
<add> message: 'The "lookup" argument must be of type Function'
<ide> }));
<ide> });
<ide> }
<ide><path>test/parallel/test-dns-lookup.js
<ide> assert.throws(() => {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: /^The "hostname" argument must be one of type string or falsey/
<add> message: /^The "hostname" argument must be one of type string or falsy/
<ide> }));
<ide>
<ide> assert.throws(() => {
<ide><path>test/parallel/test-dns.js
<ide> assert.throws(() => {
<ide> const errorReg = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: /^The "hostname" argument must be one of type string or falsey/
<add> message: /^The "hostname" argument must be one of type string or falsy/
<ide> }, 5);
<ide>
<ide> assert.throws(() => dns.lookup({}, common.mustNotCall()), errorReg);
<ide><path>test/parallel/test-event-emitter-add-listeners.js
<ide> common.expectsError(() => {
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "listener" argument must be of type function'
<add> message: 'The "listener" argument must be of type Function'
<ide> });
<ide><path>test/parallel/test-event-emitter-once.js
<ide> common.expectsError(() => {
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "listener" argument must be of type function'
<add> message: 'The "listener" argument must be of type Function'
<ide> });
<ide>
<ide> {
<ide><path>test/parallel/test-event-emitter-prepend.js
<ide> common.expectsError(() => {
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "listener" argument must be of type function'
<add> message: 'The "listener" argument must be of type Function'
<ide> });
<ide>
<ide> // Test fallback if prependListener is undefined.
<ide><path>test/parallel/test-event-emitter-remove-listeners.js
<ide> common.expectsError(() => {
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "listener" argument must be of type function'
<add> message: 'The "listener" argument must be of type Function'
<ide> });
<ide>
<ide> {
<ide><path>test/parallel/test-fs-copyfile.js
<ide> common.expectsError(() => {
<ide> }, {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "callback" argument must be of type function'
<add> message: 'The "callback" argument must be of type Function'
<ide> });
<ide>
<ide> // Throws if the source path is not a string.
<ide><path>test/parallel/test-http-client-reject-unexpected-agent.js
<ide> server.listen(0, baseOptions.host, common.mustCall(function() {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message: 'The "Agent option" argument must be one of type ' +
<del> 'Agent-like object, undefined, or false'
<add> 'Agent-like Object, undefined, or false'
<ide> })
<ide> );
<ide> });
<ide><path>test/parallel/test-http-outgoing-proto.js
<ide> assert.throws(() => {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The first argument must be one of type string or buffer'
<add> message: 'The first argument must be one of type string or Buffer'
<ide> }));
<ide>
<ide> assert.throws(() => {
<ide> assert.throws(() => {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The first argument must be one of type string or buffer'
<add> message: 'The first argument must be one of type string or Buffer'
<ide> }));
<ide>
<ide> // addTrailers()
<ide><path>test/parallel/test-http2-createsecureserver-nooptions.js
<ide> const invalidOptions = [() => {}, 1, 'test', null, undefined];
<ide> const invalidArgTypeError = {
<ide> type: TypeError,
<ide> code: 'ERR_INVALID_ARG_TYPE',
<del> message: 'The "options" argument must be of type object'
<add> message: 'The "options" argument must be of type Object'
<ide> };
<ide>
<ide> // Error if options are not passed to createSecureServer
<ide><path>test/parallel/test-http2-misc-util.js
<ide> common.expectsError(
<ide> {
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "test" argument must be of type object'
<add> message: 'The "test" argument must be of type Object'
<ide> });
<ide>
<ide> common.expectsError(
<ide><path>test/parallel/test-http2-util-asserts.js
<ide> const {
<ide> new Date(),
<ide> new (class Foo {})()
<ide> ].forEach((i) => {
<del> assert.doesNotThrow(() => assertIsObject(i, 'foo', 'object'));
<add> assert.doesNotThrow(() => assertIsObject(i, 'foo', 'Object'));
<ide> });
<ide>
<ide> [
<ide> const {
<ide> [],
<ide> [{}]
<ide> ].forEach((i) => {
<del> assert.throws(() => assertIsObject(i, 'foo', 'object'),
<add> assert.throws(() => assertIsObject(i, 'foo', 'Object'),
<ide> common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<del> message: /^The "foo" argument must be of type object$/
<add> message: /^The "foo" argument must be of type Object$/
<ide> }));
<ide> });
<ide>
<ide><path>test/parallel/test-process-cpuUsage.js
<ide> for (let i = 0; i < 10; i++) {
<ide> const invalidUserArgument = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "preValue.user" property must be of type Number'
<add> message: 'The "preValue.user" property must be of type number'
<ide> }, 8);
<ide>
<ide> const invalidSystemArgument = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "preValue.system" property must be of type Number'
<add> message: 'The "preValue.system" property must be of type number'
<ide> }, 2);
<ide>
<ide>
<ide><path>test/parallel/test-process-kill-pid.js
<ide> const assert = require('assert');
<ide> const invalidPidArgument = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "pid" argument must be of type Number'
<add> message: 'The "pid" argument must be of type number'
<ide> }, 6);
<ide>
<ide> assert.throws(function() { process.kill('SIGTERM'); },
<ide><path>test/parallel/test-tls-no-cert-required.js
<ide> assert.throws(() => tls.createServer('this is not valid'),
<ide> common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "options" argument must be of type object'
<add> message: 'The "options" argument must be of type Object'
<ide> })
<ide> );
<ide>
<ide><path>test/parallel/test-url-format-invalid-input.js
<ide> for (const [urlObject, type] of throwsObjsAndReportTypes) {
<ide> const error = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "urlObject" argument must be one of type object or string. ' +
<add> message: 'The "urlObject" argument must be one of type Object or string. ' +
<ide> `Received type ${type}`
<ide> });
<ide> assert.throws(function() { url.format(urlObject); }, error);
<ide><path>test/parallel/test-url-format-whatwg.js
<ide> assert.strictEqual(
<ide> const expectedErr = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "options" argument must be of type object'
<add> message: 'The "options" argument must be of type Object'
<ide> }, 4);
<ide> assert.throws(() => url.format(myURL, true), expectedErr);
<ide> assert.throws(() => url.format(myURL, 1), expectedErr);
<ide><path>test/parallel/test-util-callbackify.js
<ide> const values = [
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "original" argument must be of type function'
<add> message: 'The "original" argument must be of type Function'
<ide> }));
<ide> });
<ide> }
<ide> const values = [
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The last argument must be of type function'
<add> message: 'The last argument must be of type Function'
<ide> }));
<ide> });
<ide> }
<ide><path>test/parallel/test-util-inherits.js
<ide> const inherits = require('util').inherits;
<ide> const errCheck = common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "superCtor" argument must be of type function'
<add> message: 'The "superCtor" argument must be of type Function'
<ide> });
<ide>
<ide> // super constructor
<ide> assert.throws(function() {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "superCtor.prototype" property must be of type function'
<add> message: 'The "superCtor.prototype" property must be of type Function'
<ide> })
<ide> );
<ide> assert.throws(function() {
<ide> assert.throws(function() {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "ctor" argument must be of type function'
<add> message: 'The "ctor" argument must be of type Function'
<ide> })
<ide> );
<ide><path>test/parallel/test-util-inspect.js
<ide> if (typeof Symbol !== 'undefined') {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "options" argument must be of type object'
<add> message: 'The "options" argument must be of type Object'
<ide> })
<ide> );
<ide>
<ide> if (typeof Symbol !== 'undefined') {
<ide> }, common.expectsError({
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<del> message: 'The "options" argument must be of type object'
<add> message: 'The "options" argument must be of type Object'
<ide> })
<ide> );
<ide> }
<ide><path>test/sequential/test-inspector-module.js
<ide> assert.doesNotThrow(
<ide> code: 'ERR_INVALID_ARG_TYPE',
<ide> type: TypeError,
<ide> message:
<del> 'The "params" argument must be of type object. ' +
<add> 'The "params" argument must be of type Object. ' +
<ide> `Received type ${typeof i}`
<ide> }
<ide> ); | 55 |
Javascript | Javascript | add some path benchmarks for | 0d15161c2402be7bcdb575bc425307d8c9fef32b | <ide><path>benchmark/path/format.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e7],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add> var test = conf.type === 'win32' ? {
<add> root: 'C:\\',
<add> dir: 'C:\\path\\dir',
<add> base: 'index.html',
<add> ext: '.html',
<add> name: 'index'
<add> } : {
<add> root : '/',
<add> dir : '/home/user/dir',
<add> base : 'index.html',
<add> ext : '.html',
<add> name : 'index'
<add> };
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.format(test);
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/isAbsolute.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add> var tests = conf.type === 'win32'
<add> ? ['//server', 'C:\\baz\\..', 'bar\\baz', '.']
<add> : ['/foo/bar', '/baz/..', 'bar/baz', '.'];
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> runTests(p, tests);
<add> }
<add> bench.end(n);
<add>}
<add>
<add>function runTests(p, tests) {
<add> for (var i = 0; i < tests.length; i++) {
<add> p.isAbsolute(tests[i]);
<add> }
<add>}
<ide><path>benchmark/path/join.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.join('/foo', 'bar', '', 'baz/asdf', 'quux', '..');
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/normalize.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.normalize('/foo/bar//baz/asdf/quux/..');
<add> }
<add> bench.end(n);
<add>}
<ide><path>benchmark/path/relative.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e5],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var runTest = conf.type === 'win32' ? runWin32Test : runPosixTest;
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> runTest();
<add> }
<add> bench.end(n);
<add>}
<add>
<add>function runWin32Test() {
<add> path.win32.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb');
<add>}
<add>
<add>function runPosixTest() {
<add> path.posix.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb');
<add>}
<ide><path>benchmark/path/resolve.js
<add>var common = require('../common.js');
<add>var path = require('path');
<add>
<add>var bench = common.createBenchmark(main, {
<add> type: ['win32', 'posix'],
<add> n: [1e6],
<add>});
<add>
<add>function main(conf) {
<add> var n = +conf.n;
<add> var p = path[conf.type];
<add>
<add> bench.start();
<add> for (var i = 0; i < n; i++) {
<add> p.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile');
<add> }
<add> bench.end(n);
<add>} | 6 |
Text | Text | finalize changelog for 1.8.0 | e996eacc3c684814b534fce469f37b4579846b62 | <ide><path>CHANGELOG.md
<ide>
<ide> * [BREAKING] Require Handlebars 2.0. See [blog post](http://emberjs.com/blog/2014/10/16/handlebars-update.html) for details.
<ide>
<del>### Ember 1.8.0-beta.3 (September, 27, 2014)
<del>
<add>### Ember 1.8.0 (October, 28, 2014)
<add>
<add>* [BUGFIX] Ensure published builds do not use `define` or `require` internally.
<add>* [BUGFIX] Remove strict mode for Object.create usage to work around an [iOS bug](https://bugs.webkit.org/show_bug.cgi?id=138038).
<add>* Enable testing of production builds by publishing `ember-testing.js` along with the standard builds.
<add>* [DOC] Make mandatory setter assertions more helpful.
<add>* Deprecate location: 'hash' paths that don't have a forward slash. e.g. #foo vs. #/foo.
<add>* [BUGFIX] Ensure `Ember.setProperties` can handle non-object properties.
<add>* [BUGFIX] Refactor buffer to be simpler, single parsing code-path.
<add>* [BUGFIX] Add assertion when morph is not found in RenderBuffer.
<add>* [BUGFIX] Make computed.sort generate an answer immediately.
<add>* [BUGFIX] Fix broken `Ember.computed.sort` semantics.
<add>* [BUGFIX] Ensure ember-testing is not included in production build output.
<add>* Deprecate usage of quoted paths in `{{view}}` helper.
<add>* [BUGFIX] Ensure `{{view}}` lookup works properly when name is a keyword.
<add>* [BUGFIX] Ensure `Ember.Map` works properly with falsey values.
<add>* [BUGFIX] Make Ember.Namespace#toString ember-cli aware.
<add>* [PERF] Avoid using `for x in y` in `Ember.RenderBuffer.prototype.add`.
<add>* [BUGFIX] Enable setProperties to work on Object.create(null) objects.
<add>* [PERF] Update RSVP to 3.0.14 (faster instrumentation).
<add>* [BUGFIX] Add SVG support for metal-views.
<add>* [BUGFIX] Allow camelCase attributes in DOM elements.
<add>* [BUGFIX] Update backburner to latest.
<ide> * [BUGFIX] Use contextualElements to properly handle omitted optional start tags.
<ide> * [BUGFIX] Ensure that `Route.prototype.activate` is not retriggered when the model for the current route changes.
<ide> * [PERF] Fix optimization bailouts for `{{view}}` helper.
<ide> * [ES6] Remove length in-favor of size.
<ide> * [ES6] Throw if constructor is invoked without new
<ide> * [ES6] Make inheritance work correctly
<del>
<del>
<del>### Ember 1.8.0-beta.2 (September, 20, 2014)
<del>
<ide> * [BUGFIX] Allow for bound property {{input}} type.
<ide> * [BUGFIX] Ensure pushUnique targetQueue is cleared by flush.
<ide> * [BUGFIX] instrument should still call block even without subscribers.
<ide> * [PERF] Extracts computed property set into a separate function.
<ide> * [BUGFIX] Make `GUID_KEY = intern(GUID_KEY)` actually work on ES3.
<ide> * [BUGFIX] Ensure nested routes can inherit model from parent.
<del>
<del>### Ember 1.8.0-beta.1 (August 20, 2014)
<del>
<ide> * Remove `metamorph` in favor of `morph` package (removes the need for `<script>` tags in the DOM).
<ide> * [FEATURE] ember-routing-linkto-target-attribute
<ide> * [FEATURE] ember-routing-multi-current-when | 1 |
Go | Go | fix login command | 05c18a2434ab7bd68a86c87fe866bc7107ac1941 | <ide><path>registry/service.go
<ide> func (s *Service) Auth(job *engine.Job) engine.Status {
<ide> authConfig.ServerAddress = endpoint.String()
<ide> }
<ide>
<del> if _, err := Login(authConfig, HTTPRequestFactory(nil)); err != nil {
<add> status, err := Login(authConfig, HTTPRequestFactory(nil))
<add> if err != nil {
<ide> return job.Error(err)
<ide> }
<add> job.Printf("%s\n", status)
<ide>
<ide> return engine.StatusOK
<ide> } | 1 |
PHP | PHP | add attachfromstorage to mailables | 0fa361d0e2e111a1a684606a675b414ebd471257 | <ide><path>src/Illuminate/Mail/Mailable.php
<ide> use Illuminate\Contracts\Translation\Translator;
<ide> use Illuminate\Contracts\Mail\Mailer as MailerContract;
<ide> use Illuminate\Contracts\Mail\Mailable as MailableContract;
<add>use Illuminate\Contracts\Filesystem\Factory as FilesystemFactory;
<ide>
<ide> class Mailable implements MailableContract, Renderable
<ide> {
<ide> public function attach($file, array $options = [])
<ide> return $this;
<ide> }
<ide>
<add> /**
<add> * Attach a file to the message from storage.
<add> *
<add> * @param string $path
<add> * @param string $name
<add> * @param array $options
<add> * @return $this
<add> */
<add> public function attachFromStorage($path, $name = null, array $options = [])
<add> {
<add> return $this->attachFromStorageDisk(null, $path, $name, $options);
<add> }
<add>
<add> /**
<add> * Attach a file to the message from storage.
<add> *
<add> * @param string $disk
<add> * @param string $path
<add> * @param string $name
<add> * @param array $options
<add> * @return $this
<add> */
<add> public function attachFromStorageDisk($disk, $path, $name = null, array $options = [])
<add> {
<add> $storage = Container::getInstance()->make(FilesystemFactory::class)->disk($disk);
<add>
<add> return $this->attachData(
<add> $storage->get($path), $name ?? basename($path),
<add> array_merge(['mime' => $storage->mimeType($path)], $options)
<add> );
<add> }
<add>
<ide> /**
<ide> * Attach in-memory data as an attachment.
<ide> * | 1 |
Go | Go | remove an image | de1c361a6eea95c867c43619fc1e7a7b8a147750 | <ide><path>dockerd/dockerd.go
<ide> func (srv *Server) CmdInspect(stdin io.ReadCloser, stdout io.Writer, args ...str
<ide> return nil
<ide> }
<ide>
<add>// 'docker rmi NAME' removes all images with the name NAME
<add>func (srv *Server) CmdRmi(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
<add> cmd := rcli.Subcmd(stdout, "rmimage", "[OPTIONS] IMAGE", "Remove an image")
<add> if err := cmd.Parse(args); err != nil {
<add> cmd.Usage()
<add> return nil
<add> }
<add> if cmd.NArg() < 1 {
<add> cmd.Usage()
<add> return nil
<add> }
<add> for _, name := range cmd.Args() {
<add> image := srv.images.Find(name)
<add> if image == nil {
<add> return errors.New("No such image: " + name)
<add> }
<add> if err := srv.images.Delete(name); err != nil {
<add> return err
<add> }
<add> }
<add> return nil
<add>}
<add>
<ide> func (srv *Server) CmdRm(stdin io.ReadCloser, stdout io.Writer, args ...string) error {
<ide> flags := rcli.Subcmd(stdout, "rm", "[OPTIONS] CONTAINER", "Remove a container")
<ide> if err := flags.Parse(args); err != nil {
<ide><path>image/image.go
<ide> func (index *Index) Rename(oldName, newName string) error {
<ide> return nil
<ide> }
<ide>
<add>// Delete deletes all images with the name `name`
<add>func (index *Index) Delete(name string) error {
<add> // Load
<add> if err := index.load(); err != nil {
<add> return err
<add> }
<add> if _, exists := index.ByName[name]; !exists {
<add> return errors.New("No such image: " + name)
<add> }
<add> // Remove from index lookup
<add> for _, image := range *index.ByName[name] {
<add> delete(index.ById, image.Id)
<add> }
<add> // Remove from name lookup
<add> delete(index.ByName, name)
<add> // Save
<add> if err := index.save(); err != nil {
<add> return err
<add> }
<add> return nil
<add>}
<add>
<ide> func (index *Index) Names() []string {
<ide> if err := index.load(); err != nil {
<ide> return []string{} | 2 |
Python | Python | remove explicit id column setting in test | abccbcf52da4a0f0c388b8a770b5de04d6d6e64c | <ide><path>tests/migrations/test_operations.py
<ide> def test_create_model_m2m(self):
<ide> operation.database_forwards("test_crmomm", editor, project_state, new_state)
<ide> self.assertTableExists("test_crmomm_stable")
<ide> self.assertTableExists("test_crmomm_stable_ponies")
<del> self.assertColumnNotExists("test_crmomm", "ponies")
<add> self.assertColumnNotExists("test_crmomm_stable", "ponies")
<ide> # Make sure the M2M field actually works
<ide> with atomic():
<ide> new_apps = new_state.render()
<ide> def test_alter_unique_together(self):
<ide> self.assertEqual(len(new_state.models["test_alunto", "pony"].options.get("unique_together", set())), 1)
<ide> # Make sure we can insert duplicate rows
<ide> with connection.cursor() as cursor:
<del> cursor.execute("INSERT INTO test_alunto_pony (id, pink, weight) VALUES (1, 1, 1)")
<del> cursor.execute("INSERT INTO test_alunto_pony (id, pink, weight) VALUES (2, 1, 1)")
<add> cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
<add> cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
<ide> cursor.execute("DELETE FROM test_alunto_pony")
<ide> # Test the database alteration
<ide> with connection.schema_editor() as editor:
<ide> operation.database_forwards("test_alunto", editor, project_state, new_state)
<del> cursor.execute("INSERT INTO test_alunto_pony (id, pink, weight) VALUES (1, 1, 1)")
<add> cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
<ide> with self.assertRaises(IntegrityError):
<ide> with atomic():
<del> cursor.execute("INSERT INTO test_alunto_pony (id, pink, weight) VALUES (2, 1, 1)")
<add> cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
<ide> cursor.execute("DELETE FROM test_alunto_pony")
<ide> # And test reversal
<ide> with connection.schema_editor() as editor:
<ide> operation.database_backwards("test_alunto", editor, new_state, project_state)
<del> cursor.execute("INSERT INTO test_alunto_pony (id, pink, weight) VALUES (1, 1, 1)")
<del> cursor.execute("INSERT INTO test_alunto_pony (id, pink, weight) VALUES (2, 1, 1)")
<add> cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
<add> cursor.execute("INSERT INTO test_alunto_pony (pink, weight) VALUES (1, 1)")
<ide> cursor.execute("DELETE FROM test_alunto_pony")
<ide> # Test flat unique_together
<ide> operation = migrations.AlterUniqueTogether("Pony", ("pink", "weight")) | 1 |
Javascript | Javascript | fix reducer import in test | f2542fe69fd76d4992b28b85804a1e711acba4b0 | <ide><path>examples/todos/test/reducers/todos.spec.js
<ide> import expect from 'expect'
<del>import { todos } from '../../reducers/todos'
<add>import todos from '../../reducers/todos'
<ide>
<ide> describe('todos reducer', () => {
<ide> it('should handle initial state', () => { | 1 |
Python | Python | add contextmanager methods to testing pipeline | 043f7935654798e949897c6bd0c70ebd5a6dfe90 | <ide><path>celery/tests/backends/test_redis.py
<ide> def add_step(*args, **kwargs):
<ide> return self
<ide> return add_step
<ide>
<add> def __enter__(self):
<add> return self
<add>
<add> def __exit__(self, type, value, traceback):
<add> pass
<add>
<ide> def execute(self):
<ide> return [step(*a, **kw) for step, a, kw in self.steps]
<ide> | 1 |
Javascript | Javascript | add test for gh-2177 | a639cf7d84c49a963f628db6fc9f2118a00f4efd | <ide><path>test/simple/test-dgram-send-error.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>// Some operating systems report errors when an UDP message is sent to an
<add>// unreachable host. This error can be reported by sendto() and even by
<add>// recvfrom(). Node should not propagate this error to the user.
<add>
<add>// We test this by sending a bunch of packets to random IPs. In the meantime
<add>// we also send packets to ourselves to verify that after receiving an error
<add>// we can still receive packets successfully.
<add>
<add>var ITERATIONS = 1000;
<add>
<add>var assert = require('assert'),
<add> common = require('../common'),
<add> dgram = require('dgram');
<add>
<add>var buf = new Buffer(1024);
<add>buf.fill(42);
<add>
<add>var packetsReceived = 0,
<add> packetsSent = 0;
<add>
<add>var socket = dgram.createSocket('udp4');
<add>
<add>socket.on('message', onMessage);
<add>socket.on('listening', doSend);
<add>socket.bind(common.PORT);
<add>
<add>function onMessage(message, info) {
<add> packetsReceived++;
<add> if (packetsReceived < ITERATIONS) {
<add> doSend();
<add> } else {
<add> socket.close();
<add> }
<add>}
<add>
<add>function afterSend(err) {
<add> if (err) throw err;
<add> packetsSent++;
<add>}
<add>
<add>function doSend() {
<add> // Generate a random IP.
<add> var parts = [];
<add> for (var i = 0; i < 4; i++) {
<add> // Generate a random number in the range 1..254.
<add> parts.push(Math.floor(Math.random() * 254) + 1);
<add> }
<add> var ip = parts.join('.');
<add>
<add> socket.send(buf, 0, buf.length, 1, ip, afterSend);
<add> socket.send(buf, 0, buf.length, common.PORT, '127.0.0.1', afterSend);
<add>}
<add>
<add>process.on('exit', function() {
<add> console.log(packetsSent + ' UDP packets sent, ' +
<add> packetsReceived + ' received');
<add>
<add> assert.strictEqual(packetsSent, ITERATIONS * 2);
<add> assert.strictEqual(packetsReceived, ITERATIONS);
<add>}); | 1 |
Text | Text | fix code example in readme | dbc95e81810a06600669dbc101d90753b5bae2a5 | <ide><path>src/Console/README.md
<ide> exit($runner->run($argv));
<ide> For our `Application` class we can start with:
<ide>
<ide> ```php
<del>namespace App
<add>namespace App;
<ide>
<ide> use App\Command\HelloCommand;
<del>use Cake\Core\BaseApplication;
<add>use Cake\Core\ConsoleApplicationInterface;
<ide>
<del>class Application implements HttpApplicationInterface
<add>class Application implements ConsoleApplicationInterface
<ide> {
<ide> /**
<ide> * Load all the application configuration and bootstrap logic. | 1 |
Text | Text | add missing space | ab0146075ab063f601030178f3e1da56e886199e | <ide><path>actionpack/CHANGELOG.md
<ide>
<ide> See PR [#26703](https://github.com/rails/rails/pull/26703)
<ide>
<del> *Eileen M.Uchitelle*
<add> *Eileen M. Uchitelle*
<ide>
<ide> * Remove deprecated `.to_prepare`, `.to_cleanup`, `.prepare!` and `.cleanup!` from `ActionDispatch::Reloader`.
<ide> | 1 |
Javascript | Javascript | remove useless docs heading | 1de7411c8bff2bf2c3d8dab40c4d6a5ad247084b | <ide><path>src/ng/directive/ngPluralize.js
<ide> * @restrict EA
<ide> *
<ide> * @description
<del> * # Overview
<ide> * `ngPluralize` is a directive that displays messages according to en-US localization rules.
<ide> * These rules are bundled with angular.js, but can be overridden
<ide> * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive | 1 |
Python | Python | add an executor for end-to-end running | e6f7f4533c183800c2a9ac526d8ee8887e96ac5d | <ide><path>django/db/migrations/executor.py
<add>from .loader import MigrationLoader
<add>from .recorder import MigrationRecorder
<add>
<add>
<add>class MigrationExecutor(object):
<add> """
<add> End-to-end migration execution - loads migrations, and runs them
<add> up or down to a specified set of targets.
<add> """
<add>
<add> def __init__(self, connection):
<add> self.connection = connection
<add> self.loader = MigrationLoader(self.connection)
<add> self.recorder = MigrationRecorder(self.connection)
<add>
<add> def migration_plan(self, targets):
<add> """
<add> Given a set of targets, returns a list of (Migration instance, backwards?).
<add> """
<add> plan = []
<add> applied = self.recorder.applied_migrations()
<add> for target in targets:
<add> # If the migration is already applied, do backwards mode,
<add> # otherwise do forwards mode.
<add> if target in applied:
<add> for migration in self.loader.graph.backwards_plan(target)[:-1]:
<add> if migration in applied:
<add> plan.append((self.loader.graph.nodes[migration], True))
<add> applied.remove(migration)
<add> else:
<add> for migration in self.loader.graph.forwards_plan(target):
<add> if migration not in applied:
<add> plan.append((self.loader.graph.nodes[migration], False))
<add> applied.add(migration)
<add> return plan
<add>
<add> def migrate(self, targets):
<add> """
<add> Migrates the database up to the given targets.
<add> """
<add> plan = self.migration_plan(targets)
<add> for migration, backwards in plan:
<add> if not backwards:
<add> self.apply_migration(migration)
<add> else:
<add> self.unapply_migration(migration)
<add>
<add> def apply_migration(self, migration):
<add> """
<add> Runs a migration forwards.
<add> """
<add> print "Applying %s" % migration
<add> with self.connection.schema_editor() as schema_editor:
<add> project_state = self.loader.graph.project_state((migration.app_label, migration.name), at_end=False)
<add> migration.apply(project_state, schema_editor)
<add> self.recorder.record_applied(migration.app_label, migration.name)
<add> print "Finished %s" % migration
<add>
<add> def unapply_migration(self, migration):
<add> """
<add> Runs a migration backwards.
<add> """
<add> print "Unapplying %s" % migration
<add> with self.connection.schema_editor() as schema_editor:
<add> project_state = self.loader.graph.project_state((migration.app_label, migration.name), at_end=False)
<add> migration.unapply(project_state, schema_editor)
<add> self.recorder.record_unapplied(migration.app_label, migration.name)
<add> print "Finished %s" % migration
<ide><path>django/db/migrations/migration.py
<ide> def __init__(self, name, app_label):
<ide> self.name = name
<ide> self.app_label = app_label
<ide>
<add> def __eq__(self, other):
<add> if not isinstance(other, Migration):
<add> return False
<add> return (self.name == other.name) and (self.app_label == other.app_label)
<add>
<add> def __ne__(self, other):
<add> return not (self == other)
<add>
<add> def __repr__(self):
<add> return "<Migration %s.%s>" % (self.app_label, self.name)
<add>
<ide> def mutate_state(self, project_state):
<ide> """
<ide> Takes a ProjectState and returns a new one with the migration's
<ide> def mutate_state(self, project_state):
<ide> for operation in self.operations:
<ide> operation.state_forwards(self.app_label, new_state)
<ide> return new_state
<add>
<add> def apply(self, project_state, schema_editor):
<add> """
<add> Takes a project_state representing all migrations prior to this one
<add> and a schema_editor for a live database and applies the migration
<add> in a forwards order.
<add>
<add> Returns the resulting project state for efficient re-use by following
<add> Migrations.
<add> """
<add> for operation in self.operations:
<add> # Get the state after the operation has run
<add> new_state = project_state.clone()
<add> operation.state_forwards(self.app_label, new_state)
<add> # Run the operation
<add> operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
<add> # Switch states
<add> project_state = new_state
<add> return project_state
<add>
<add> def unapply(self, project_state, schema_editor):
<add> """
<add> Takes a project_state representing all migrations prior to this one
<add> and a schema_editor for a live database and applies the migration
<add> in a reverse order.
<add> """
<add> # We need to pre-calculate the stack of project states
<add> to_run = []
<add> for operation in self.operations:
<add> new_state = project_state.clone()
<add> operation.state_forwards(self.app_label, new_state)
<add> to_run.append((operation, project_state, new_state))
<add> project_state = new_state
<add> # Now run them in reverse
<add> to_run.reverse()
<add> for operation, to_state, from_state in to_run:
<add> operation.database_backwards(self.app_label, schema_editor, from_state, to_state)
<ide><path>django/db/migrations/operations/fields.py
<ide> def state_forwards(self, app_label, state):
<ide>
<ide> def database_forwards(self, app_label, schema_editor, from_state, to_state):
<ide> app_cache = to_state.render()
<del> model = app_cache.get_model(app_label, self.name)
<del> schema_editor.add_field(model, model._meta.get_field_by_name(self.name))
<add> model = app_cache.get_model(app_label, self.model_name)
<add> schema_editor.add_field(model, model._meta.get_field_by_name(self.name)[0])
<ide>
<ide> def database_backwards(self, app_label, schema_editor, from_state, to_state):
<ide> app_cache = from_state.render()
<del> model = app_cache.get_model(app_label, self.name)
<del> schema_editor.remove_field(model, model._meta.get_field_by_name(self.name))
<add> model = app_cache.get_model(app_label, self.model_name)
<add> schema_editor.remove_field(model, model._meta.get_field_by_name(self.name)[0])
<ide>
<ide>
<ide> class RemoveField(Operation):
<ide> def state_forwards(self, app_label, state):
<ide>
<ide> def database_forwards(self, app_label, schema_editor, from_state, to_state):
<ide> app_cache = from_state.render()
<del> model = app_cache.get_model(app_label, self.name)
<del> schema_editor.remove_field(model, model._meta.get_field_by_name(self.name))
<add> model = app_cache.get_model(app_label, self.model_name)
<add> schema_editor.remove_field(model, model._meta.get_field_by_name(self.name)[0])
<ide>
<ide> def database_backwards(self, app_label, schema_editor, from_state, to_state):
<ide> app_cache = to_state.render()
<del> model = app_cache.get_model(app_label, self.name)
<del> schema_editor.add_field(model, model._meta.get_field_by_name(self.name))
<add> model = app_cache.get_model(app_label, self.model_name)
<add> schema_editor.add_field(model, model._meta.get_field_by_name(self.name)[0])
<ide><path>tests/migrations/migrations/0002_second.py
<ide> class Migration(migrations.Migration):
<ide>
<ide> migrations.RemoveField("Author", "silly_field"),
<ide>
<del> migrations.AddField("Author", "important", models.BooleanField()),
<add> migrations.AddField("Author", "rating", models.IntegerField(default=0)),
<ide>
<ide> migrations.CreateModel(
<ide> "Book",
<ide><path>tests/migrations/test_executor.py
<add>from django.test import TransactionTestCase
<add>from django.db import connection
<add>from django.db.migrations.executor import MigrationExecutor
<add>
<add>
<add>class ExecutorTests(TransactionTestCase):
<add> """
<add> Tests the migration executor (full end-to-end running).
<add>
<add> Bear in mind that if these are failing you should fix the other
<add> test failures first, as they may be propagating into here.
<add> """
<add>
<add> def test_run(self):
<add> """
<add> Tests running a simple set of migrations.
<add> """
<add> executor = MigrationExecutor(connection)
<add> # Let's look at the plan first and make sure it's up to scratch
<add> plan = executor.migration_plan([("migrations", "0002_second")])
<add> self.assertEqual(
<add> plan,
<add> [
<add> (executor.loader.graph.nodes["migrations", "0001_initial"], False),
<add> (executor.loader.graph.nodes["migrations", "0002_second"], False),
<add> ],
<add> )
<add> # Were the tables there before?
<add> self.assertNotIn("migrations_author", connection.introspection.get_table_list(connection.cursor()))
<add> self.assertNotIn("migrations_book", connection.introspection.get_table_list(connection.cursor()))
<add> # Alright, let's try running it
<add> executor.migrate([("migrations", "0002_second")])
<add> # Are the tables there now?
<add> self.assertIn("migrations_author", connection.introspection.get_table_list(connection.cursor()))
<add> self.assertIn("migrations_book", connection.introspection.get_table_list(connection.cursor()))
<ide><path>tests/migrations/test_loader.py
<ide> def test_load(self):
<ide> author_state = project_state.models["migrations", "author"]
<ide> self.assertEqual(
<ide> [x for x, y in author_state.fields],
<del> ["id", "name", "slug", "age", "important"]
<add> ["id", "name", "slug", "age", "rating"]
<ide> )
<ide>
<ide> book_state = project_state.models["migrations", "book"]
<ide><path>tests/migrations/test_operations.py
<ide> from django.test import TransactionTestCase
<ide> from django.db import connection, models, migrations
<del>from django.db.migrations.state import ProjectState, ModelState
<add>from django.db.migrations.state import ProjectState
<ide>
<ide>
<ide> class OperationTests(TransactionTestCase):
<ide> def assertTableExists(self, table):
<ide> def assertTableNotExists(self, table):
<ide> self.assertNotIn(table, connection.introspection.get_table_list(connection.cursor()))
<ide>
<add> def assertColumnExists(self, table, column):
<add> self.assertIn(column, [c.name for c in connection.introspection.get_table_description(connection.cursor(), table)])
<add>
<add> def assertColumnNotExists(self, table, column):
<add> self.assertNotIn(column, [c.name for c in connection.introspection.get_table_description(connection.cursor(), table)])
<add>
<ide> def set_up_test_model(self, app_label):
<ide> """
<ide> Creates a test model state and database table.
<ide> def test_delete_model(self):
<ide> with connection.schema_editor() as editor:
<ide> operation.database_backwards("test_dlmo", editor, new_state, project_state)
<ide> self.assertTableExists("test_dlmo_pony")
<add>
<add> def test_add_field(self):
<add> """
<add> Tests the AddField operation.
<add> """
<add> project_state = self.set_up_test_model("test_adfl")
<add> # Test the state alteration
<add> operation = migrations.AddField("Pony", "height", models.FloatField(null=True))
<add> new_state = project_state.clone()
<add> operation.state_forwards("test_adfl", new_state)
<add> self.assertEqual(len(new_state.models["test_adfl", "pony"].fields), 3)
<add> # Test the database alteration
<add> self.assertColumnNotExists("test_adfl_pony", "height")
<add> with connection.schema_editor() as editor:
<add> operation.database_forwards("test_adfl", editor, project_state, new_state)
<add> self.assertColumnExists("test_adfl_pony", "height")
<add> # And test reversal
<add> with connection.schema_editor() as editor:
<add> operation.database_backwards("test_adfl", editor, new_state, project_state)
<add> self.assertColumnNotExists("test_adfl_pony", "height") | 7 |
PHP | PHP | add fieldtype to form\schema | ff289fbc1c13f0dc93bc06436c3bd28464bfa661 | <ide><path>src/Form/Schema.php
<ide> public function isRequired($name) {
<ide> return (bool) $field['required'];
<ide> }
<ide>
<add>/**
<add> * Get the type of the named field.
<add> *
<add> * @param string $field The name of the field.
<add> * @return string|null Either the field type or null if the
<add> * field does not exist.
<add> */
<add> public function fieldType($name) {
<add> $field = $this->field($name);
<add> if (!$field) {
<add> return null;
<add> }
<add> return $field['type'];
<add> }
<add>
<ide> }
<ide><path>tests/TestCase/Form/SchemaTest.php
<ide> public function testIsRequired() {
<ide> $this->assertFalse($schema->isRequired('nope'));
<ide> }
<ide>
<add>/**
<add> * test fieldType
<add> *
<add> * @return void
<add> */
<add> public function testFieldType() {
<add> $schema = new Schema();
<add>
<add> $schema->addField('name', 'string')
<add> ->addField('numbery', [
<add> 'type' => 'decimal',
<add> 'required' => true
<add> ]);
<add> $this->assertEquals('string', $schema->fieldType('name'));
<add> $this->assertEquals('decimal', $schema->fieldType('numbery'));
<add> $this->assertNull($schema->fieldType('nope'));
<add> }
<add>
<add>
<ide> } | 2 |
Mixed | Text | add quick start pages | 6c8055194a580a2ddf63394faf51ff277332fa5b | <ide><path>docs/tutorials/quick-start.md
<add>---
<add>id: quick-start
<add>title: Quick Start
<add>sidebar_label: Quick Start
<add>hide_title: true
<add>---
<add>
<add>
<add>
<add># Redux Toolkit Quick Start
<add>
<add>:::tip What You'll Learn
<add>
<add>- How to set up and use Redux Toolkit with React-Redux
<add>
<add>:::
<add>
<add>:::info Prerequisites
<add>
<add>- Familiarity with [ES6 syntax and features](https://www.taniarascia.com/es6-syntax-and-feature-overview/)
<add>- Knowledge of React terminology: [JSX](https://reactjs.org/docs/introducing-jsx.html), [State](https://reactjs.org/docs/state-and-lifecycle.html), [Function Components, Props](https://reactjs.org/docs/components-and-props.html), and [Hooks](https://reactjs.org/docs/hooks-intro.html)
<add>- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow)
<add>
<add>:::
<add>
<add>## Introduction
<add>
<add>Welcome to the Redux Toolkit Quick Start tutorial! **This tutorial will briefly introduce you to Redux Toolkit and teach you how to start using it correctly**.
<add>
<add>### How to Read This Tutorial
<add>
<add>This page will focus on just how to set up a Redux application with Redux Toolkit and the main APIs you'll use. For explanations of what Redux is, how it works, and full examples of how to use Redux Toolkit, [see the tutorials linked in the "Tutorials Index" page](./tutorials-index.md).
<add>
<add>For this tutorial, we assume that you're using Redux Toolkit with React, but you can also use it with other UI layers as well. The examples are based on [a typical Create-React-App folder structure](https://create-react-app.dev/docs/folder-structure) where all the application code is in a `src`, but the patterns can be adapted to whatever project or folder setup you're using.
<add>
<add>The [Redux+JS template for Create-React-App](https://github.com/reduxjs/cra-template-redux) comes with this same project setup already configured.
<add>
<add>## Usage Summary
<add>
<add>### Install Redux Toolkit and React-Redux
<add>
<add>Add the Redux Toolkit and React-Redux packages to your project:
<add>
<add>```sh
<add>npm install @reduxjs/toolkit react-redux
<add>```
<add>
<add>### Create a Redux Store
<add>
<add>Create a file named `src/app/store.js`. Import the `configureStore` API from Redux Toolkit. We'll start by creating an empty Redux store, and exporting it:
<add>
<add>```js title="app/store.js"
<add>import { configureStore } from '@reduxjs/toolkit'
<add>
<add>export default configureStore({
<add> reducer: {}
<add>})
<add>```
<add>
<add>This creates a Redux store, and also automatically configure the Redux DevTools extension so that you can inspect the store while developing.
<add>
<add>### Provide the Redux Store to React
<add>
<add>Once the store is created, we can make it available to our React components by putting a React-Redux `<Provider>` around our application in `src/index.js`. Import the Redux store we just created, put a `<Provider>` around your `<App>`, and pass the store as a prop:
<add>
<add>```js title="index.js"
<add>import React from 'react'
<add>import ReactDOM from 'react-dom'
<add>import './index.css'
<add>import App from './App'
<add>// highlight-start
<add>import store from './app/store'
<add>import { Provider } from 'react-redux'
<add>// highlight-end
<add>
<add>ReactDOM.render(
<add> // highlight-next-line
<add> <Provider store={store}>
<add> <App />
<add> </Provider>,
<add> document.getElementById('root')
<add>)
<add>```
<add>
<add>### Create a Redux State Slice
<add>
<add>Add a new file named `src/features/counter/counterSlice.js`. In that file, import the `createSlice` API from Redux Toolkit.
<add>
<add>Creating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions to define how the state can be updated. Once a slice is created, we can export the generated Redux action creators and the reducer function for the whole slice.
<add>
<add>Redux requires that [we write all state updates immutably, by making copies of data and updating the copies](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow#immutability). However, Redux Toolkit's `createSlice` and `createReducer` APIs use [Immer](https://immerjs.github.io/immer/) inside to allow us to [write "mutating" update logic that becomes correct immutable updates](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux#immutable-updates-with-immer).
<add>
<add>```js title="features/counter/counterSlice.js"
<add>import { createSlice } from '@reduxjs/toolkit'
<add>
<add>export const counterSlice = createSlice({
<add> name: 'counter',
<add> initialState: {
<add> value: 0
<add> },
<add> reducers: {
<add> increment: state => {
<add> // Redux Toolkit allows us to write "mutating" logic in reducers. It
<add> // doesn't actually mutate the state because it uses the Immer library,
<add> // which detects changes to a "draft state" and produces a brand new
<add> // immutable state based off those changes
<add> state.value += 1
<add> },
<add> decrement: state => {
<add> state.value -= 1
<add> },
<add> incrementByAmount: (state, action) => {
<add> state.value += action.payload
<add> }
<add> }
<add>})
<add>
<add>// Action creators are generated for each case reducer function
<add>export const { increment, decrement, incrementByAmount } = counterSlice.actions
<add>
<add>export default counterSlice.reducer
<add>```
<add>
<add>### Add Slice Reducers to the Store
<add>
<add>Next, we need to import the reducer function from the counter slice and add it to our store. By defining a field inside the `reducers` parameter, we tell the store to use this slice reducer function to handle all updates to that state.
<add>
<add>```js title="app/store.js"
<add>import { configureStore } from '@reduxjs/toolkit'
<add>// highlight-next-line
<add>import counterReducer from '../features/counter/counterSlice'
<add>
<add>export default configureStore({
<add> reducer: {
<add> // highlight-next-line
<add> counter: counterReducer
<add> }
<add>})
<add>```
<add>
<add>### Use Redux State and Actions in React Components
<add>
<add>Now we can use the React-Redux hooks to let React components interact with the Redux store. We can read data from the store with `useSelector`, and dispatch actions using `useDispatch`. Create a `src/features/counter/Counter.js` file with a `<Counter>` component inside, then import that component into `App.js` and render it inside of `<App>`.
<add>
<add>```jsx title="features/counter/Counter.js"
<add>import React, { useState } from 'react'
<add>import { useSelector, useDispatch } from 'react-redux'
<add>import { decrement, increment } from './counterSlice'
<add>import styles from './Counter.module.css'
<add>
<add>export function Counter() {
<add> const count = useSelector(state => state.counter.value)
<add> const dispatch = useDispatch()
<add>
<add> return (
<add> <div>
<add> <div>
<add> <button
<add> aria-label="Increment value"
<add> onClick={() => dispatch(increment())}
<add> >
<add> Increment
<add> </button>
<add> <span>{count}</span>
<add> <button
<add> aria-label="Decrement value"
<add> onClick={() => dispatch(decrement())}
<add> >
<add> Decrement
<add> </button>
<add> </div>
<add> </div>
<add> )
<add>}
<add>```
<add>
<add>Now, any time you click the "Increment" and "Decrement buttons:
<add>
<add>- The corresponding Redux action will be dispatched to the store
<add>- The counter slice reducer will see the actions and update its state
<add>- The `<Counter>` component will see the new state value from the store and re-render itself with the new data
<add>
<add>## What You've Learned
<add>
<add>That was a brief overview of how to set up and use Redux Toolkit with React. Recapping the details:
<add>
<add>:::tip Summary
<add>
<add>- **Create a Redux store with `configureStore`**
<add> - `configureStore` accepts a `reducer` function as a named argument
<add> - `configureStore` automatically sets up the store with good default settings
<add>- **Provide the Redux store to the React application components**
<add> - Put a React-Redux `<Provider>` component around your `<App />`
<add> - Pass the Redux store as `<Provider store={store}>`
<add>- **Create a Redux "slice" reducer with `createSlice`**
<add> - Call `createSlice` with a string name, an initial state, and named reducer functions
<add> - Reducer functions may "mutate" the state using Immer
<add> - Export the generated slice reducer and action creators
<add>- **Use the React-Redux `useSelector/useDispatch` hooks in React components**
<add> - Read data from the store with the `useSelector` hook
<add> - Get the `dispatch` function with the `useDispatch` hook, and dispatch actions as needed
<add>
<add>:::
<add>
<add>### Full Counter App Example
<add>
<add>The counter example app shown here is also the
<add>
<add>Here's the complete counter application as a running CodeSandbox:
<add>
<add><iframe
<add> class="codesandbox"
<add> src="https://codesandbox.io/embed/github/reduxjs/redux-essentials-counter-example/tree/master/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fcounter%2FcounterSlice.js&theme=dark&runonclick=1"
<add> title="redux-essentials-example"
<add> allow="geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb"
<add> sandbox="allow-modals allow-forms allow-popups allow-scripts allow-same-origin"
<add>></iframe>
<add>
<add>## What's Next?
<add>
<add>We recommend going through [**the "Redux Essentials" and "Redux Fundamentals" tutorials in the Redux core docs**](./tutorials-index), which will give you a complete understanding of how Redux works, what Redux Toolkit does, and how to use it correctly.
<ide><path>docs/tutorials/tutorials-index.md
<ide> import 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css'
<ide>
<ide> ## Redux Official Tutorials
<ide>
<del>We have two different sets of tutorials:
<add>The [**Quick Start** page](./quick-start.md) briefly shows the basics of setting up a Redux Toolkit + React application, and the [**TypeScript Quick Start** page](./typescript.md) shows how to set up Redux Toolkit and React for use with TypeScript.
<add>
<add>We have two different full-size tutorials:
<ide>
<ide> - The [**Redux Essentials tutorial**](./essentials/part-1-overview-concepts) is a "top-down" tutorial that teaches "how to use Redux the right way", using our latest recommended APIs and best practices.
<ide> - The [**Redux Fundamentals tutorial**](./fundamentals/part-1-overview.md) is a "bottom-up" tutorial that teaches "how Redux works" from first principles and without any abstractions, and why standard Redux usage patterns exist.
<ide><path>docs/tutorials/typescript.md
<add>---
<add>id: typescript-quick-start
<add>title: TypeScript Quick Start
<add>sidebar_label: TypeScript Quick Start
<add>hide_title: true
<add>---
<add>
<add>
<add>
<add># Redux Toolkit TypeScript Quick Start
<add>
<add>:::tip What You'll Learn
<add>
<add>- How to set up and use Redux Toolkit and React-Redux with TypeScript
<add>
<add>:::
<add>
<add>:::info Prerequisites
<add>
<add>- Knowledge of React [Hooks](https://reactjs.org/docs/hooks-intro.html)
<add>- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow)
<add>- Understanding of TypeScript syntax and concepts
<add>
<add>:::
<add>
<add>## Introduction
<add>
<add>Welcome to the Redux Toolkit TypeScript Quick Start tutorial! **This tutorial will briefly show how to use TypeScript with Redux Toolkit**.
<add>
<add>This page focuses on just how to set up the TypeScript aspects . For explanations of what Redux is, how it works, and full examples of how to use Redux Toolkit, [see the tutorials linked in the "Tutorials Index" page](./tutorials-index.md).
<add>
<add>Redux Toolkit is already written in TypeScript, so its TS type definitions are built in.
<add>
<add>[React Redux](https://react-redux.js.org) has its type definitions in a separate [`@types/react-redux` typedefs package](https://npm.im/@types/react-redux) on NPM. In addition to typing the library functions, the types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.
<add>
<add>As of React Redux v7.2.3, the `react-redux` package has a dependency on `@types/react-redux`, so the type definitions will be automatically installed with the library. Otherwise, you'll need to manually install them yourself (typically `npm install @types/react-redux` ).
<add>
<add>The [Redux+TS template for Create-React-App](https://github.com/reduxjs/cra-template-redux-typescript) comes with a working example of these patterns already configured.
<add>
<add>## Project Setup
<add>
<add>### Define Root State and Dispatch Types
<add>
<add>[Redux Toolkit's `configureStore` API](https://redux-toolkit.js.org/api/configureStore) should not need any additional typings. You will, however, want to extract the `RootState` type and the `Dispatch` type so that they can be referenced as needed. Inferring these types from the store itself means that they correctly update as you add more state slices or modify middleware settings.
<add>
<add>Since those are types, it's safe to export them directly from your store setup file such as `app/store.ts` and import them directly into other files.
<add>
<add>```ts title="app/store.ts"
<add>import { configureStore } from '@reduxjs/toolkit'
<add>// ...
<add>
<add>const store = configureStore({
<add> reducer: {
<add> posts: postsReducer,
<add> comments: commentsReducer,
<add> users: usersReducer
<add> }
<add>})
<add>
<add>// highlight-start
<add>// Infer the `RootState` and `AppDispatch` types from the store itself
<add>export type RootState = ReturnType<typeof store.getState>
<add>// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
<add>export type AppDispatch = typeof store.dispatch
<add>// highlight-end
<add>```
<add>
<add>### Define Typed Hooks
<add>
<add>While it's possible to import the `RootState` and `AppDispatch` types into each component, it's **better to create typed versions of the `useDispatch` and `useSelector` hooks for usage in your application**. . This is important for a couple reasons:
<add>
<add>- For `useSelector`, it saves you the need to type `(state: RootState)` every time
<add>- For `useDispatch`, the default `Dispatch` type does not know about thunks. In order to correctly dispatch thunks, you need to use the specific customized `AppDispatch` type from the store that includes the thunk middleware types, and use that with `useDispatch`. Adding a pre-typed `useDispatch` hook keeps you from forgetting to import `AppDispatch` where it's needed.
<add>
<add>Since these are actual variables, not types, it's important to define them in a separate file such as `app/hooks.ts`, not the store setup file. This allows you to import them into any component file that needs to use the hooks, and avoids potential circular import dependency issues.
<add>
<add>```ts title="app/hooks.ts"
<add>import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'
<add>import type { RootState, AppDispatch } from './store'
<add>
<add>// highlight-start
<add>// Use throughout your app instead of plain `useDispatch` and `useSelector`
<add>export const useAppDispatch = () => useDispatch<AppDispatch>()
<add>export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
<add>// highlight-end
<add>```
<add>
<add>## Application Usage
<add>
<add>### Define Slice State and Action Types
<add>
<add>Each slice file should define a type for its initial state value, so that `createSlice` can correctly infer the type of `state` in each case reducer.
<add>
<add>All generated actions should be defined using the `PayloadAction<T>` type from Redux Toolkit, which takes the type of the `action.payload` field as its generic argument.
<add>
<add>You can safely import the `RootState` type from the store file here. It's a circular import, but the TypeScript compiler can correctly handle that for types. This may be needed for use cases like writing selector functions.
<add>
<add>```ts title="features/counter/counterSlice.ts"
<add>import { createSlice, PayloadAction } from '@reduxjs/toolkit'
<add>import type { RootState } from '../../app/store'
<add>
<add>// highlight-start
<add>// Define a type for the slice state
<add>interface CounterState {
<add> value: number
<add>}
<add>
<add>// Define the initial state using that type
<add>const initialState: CounterState = {
<add> value: 0
<add>}
<add>// highlight-end
<add>
<add>export const counterSlice = createSlice({
<add> name: 'counter',
<add> // `createSlice` will infer the state type from the `initialState` argument
<add> initialState,
<add> reducers: {
<add> increment: state => {
<add> state.value += 1
<add> },
<add> decrement: state => {
<add> state.value -= 1
<add> },
<add> // highlight-start
<add> // Use the PayloadAction type to declare the contents of `action.payload`
<add> incrementByAmount: (state, action: PayloadAction<number>) => {
<add> // highlight-end
<add> state.value += action.payload
<add> }
<add> }
<add>})
<add>
<add>export const { increment, decrement, incrementByAmount } = counterSlice.actions
<add>
<add>// Other code such as selectors can use the imported `RootState` type
<add>export const selectCount = (state: RootState) => state.counter.value
<add>
<add>export default counterSlice.reducer
<add>```
<add>
<add>The generated action creators will be correctly typed to accept a `payload` argument based on the `PayloadAction<T>` type you provided for the reducer. For example, `incrementByAmount` requires a `number` as its argument.
<add>
<add>In some cases, [TypeScript may unnecessarily tighten the type of the initial state](https://github.com/reduxjs/redux-toolkit/pull/827). If that happens, you can work around it by casting the initial state using `as`, instead of declaring the type of the variable:
<add>
<add>```ts
<add>// Workaround: cast state instead of declaring variable type
<add>const initialState = {
<add> value: 0
<add>} as CounterState
<add>```
<add>
<add>### Use Typed Hooks in Components
<add>
<add>In component files, import the pre-typed hooks instead of the standard hooks from React-Redux.
<add>
<add>```tsx title="features/counter/Counter.tsx"
<add>import React, { useState } from 'react'
<add>
<add>// highlight-next-line
<add>import { useAppSelector, useAppDispatch } from 'app/hooks'
<add>
<add>import { decrement, increment } from './counterSlice'
<add>
<add>export function Counter() {
<add> // highlight-start
<add> // The `state` arg is correctly typed as `RootState` already
<add> const count = useAppSelector(state => state.counter.value)
<add> const dispatch = useAppDispatch()
<add> // highlight-end
<add>
<add> // omit rendering logic
<add>}
<add>```
<add>
<add>## What's Next?
<add>
<add>See [the "Usage with TypeScript" page](../recipes/UsageWithTypescript.md) for extended details on how to use Redux Toolkit's APIs with TypeScript.
<ide><path>website/sidebars.js
<ide> module.exports = {
<ide> ],
<ide> Tutorials: [
<ide> 'tutorials/tutorials-index',
<add> 'tutorials/quick-start',
<add> 'tutorials/typescript-quick-start',
<ide> {
<ide> type: 'category',
<ide> label: 'Redux Essentials', | 4 |
Go | Go | add default path to 'scratch' images | d3ea7e80e879b506bddffd51c3ab65b8078a34f4 | <ide><path>builder/dockerfile/dispatchers.go
<ide> func from(b *Builder, args []string, attributes map[string]bool, original string
<ide>
<ide> name := args[0]
<ide>
<add> var (
<add> image builder.Image
<add> err error
<add> )
<add>
<ide> // Windows cannot support a container with no base image.
<ide> if name == api.NoBaseImageSpecifier {
<ide> if runtime.GOOS == "windows" {
<ide> return fmt.Errorf("Windows does not support FROM scratch")
<ide> }
<ide> b.image = ""
<ide> b.noBaseImage = true
<del> return nil
<del> }
<del>
<del> var (
<del> image builder.Image
<del> err error
<del> )
<del> // TODO: don't use `name`, instead resolve it to a digest
<del> if !b.options.PullParent {
<del> image, err = b.docker.GetImage(name)
<del> // TODO: shouldn't we error out if error is different from "not found" ?
<del> }
<del> if image == nil {
<del> image, err = b.docker.Pull(name)
<del> if err != nil {
<del> return err
<add> } else {
<add> // TODO: don't use `name`, instead resolve it to a digest
<add> if !b.options.PullParent {
<add> image, err = b.docker.GetImage(name)
<add> // TODO: shouldn't we error out if error is different from "not found" ?
<add> }
<add> if image == nil {
<add> image, err = b.docker.Pull(name)
<add> if err != nil {
<add> return err
<add> }
<ide> }
<ide> }
<add>
<ide> return b.processImageFrom(image)
<ide> }
<ide>
<ide><path>builder/dockerfile/internals.go
<ide> import (
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/pkg/tarsum"
<ide> "github.com/docker/docker/pkg/urlutil"
<add> "github.com/docker/docker/runconfig/opts"
<ide> )
<ide>
<ide> func (b *Builder) commit(id string, autoCmd *strslice.StrSlice, comment string) error {
<ide> func containsWildcards(name string) bool {
<ide> }
<ide>
<ide> func (b *Builder) processImageFrom(img builder.Image) error {
<del> b.image = img.ID()
<add> if img != nil {
<add> b.image = img.ID()
<ide>
<del> if img.Config() != nil {
<del> b.runConfig = img.Config()
<add> if img.Config() != nil {
<add> b.runConfig = img.Config()
<add> }
<ide> }
<ide>
<del> // The default path will be blank on Windows (set by HCS)
<del> if len(b.runConfig.Env) == 0 && system.DefaultPathEnv != "" {
<del> b.runConfig.Env = append(b.runConfig.Env, "PATH="+system.DefaultPathEnv)
<add> // Check to see if we have a default PATH, note that windows won't
<add> // have one as its set by HCS
<add> if system.DefaultPathEnv != "" {
<add> // Convert the slice of strings that represent the current list
<add> // of env vars into a map so we can see if PATH is already set.
<add> // If its not set then go ahead and give it our default value
<add> configEnv := opts.ConvertKVStringsToMap(b.runConfig.Env)
<add> if _, ok := configEnv["PATH"]; !ok {
<add> b.runConfig.Env = append(b.runConfig.Env,
<add> "PATH="+system.DefaultPathEnv)
<add> }
<add> }
<add>
<add> if img == nil {
<add> // Typically this means they used "FROM scratch"
<add> return nil
<ide> }
<ide>
<ide> // Process ONBUILD triggers if they exist
<ide><path>integration-cli/docker_cli_build_test.go
<ide> func (s *DockerSuite) TestBuildEnv(c *check.C) {
<ide> }
<ide> }
<ide>
<add>func (s *DockerSuite) TestBuildPATH(c *check.C) {
<add> testRequires(c, DaemonIsLinux)
<add>
<add> defPath := "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
<add>
<add> fn := func(dockerfile string, exp string) {
<add> _, err := buildImage("testbldpath", dockerfile, true)
<add> c.Assert(err, check.IsNil)
<add>
<add> res, err := inspectField("testbldpath", "Config.Env")
<add> c.Assert(err, check.IsNil)
<add>
<add> if res != exp {
<add> c.Fatalf("Env %q, expected %q for dockerfile:%q", res, exp, dockerfile)
<add> }
<add> }
<add>
<add> tests := []struct{ dockerfile, exp string }{
<add> {"FROM scratch\nMAINTAINER me", "[PATH=" + defPath + "]"},
<add> {"FROM busybox\nMAINTAINER me", "[PATH=" + defPath + "]"},
<add> {"FROM scratch\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
<add> {"FROM busybox\nENV FOO=bar", "[PATH=" + defPath + " FOO=bar]"},
<add> {"FROM scratch\nENV PATH=/test", "[PATH=/test]"},
<add> {"FROM busybox\nENV PATH=/test", "[PATH=/test]"},
<add> {"FROM scratch\nENV PATH=''", "[PATH=]"},
<add> {"FROM busybox\nENV PATH=''", "[PATH=]"},
<add> }
<add>
<add> for _, test := range tests {
<add> fn(test.dockerfile, test.exp)
<add> }
<add>}
<add>
<ide> func (s *DockerSuite) TestBuildContextCleanup(c *check.C) {
<ide> testRequires(c, DaemonIsLinux)
<ide> testRequires(c, SameHostDaemon) | 3 |
Python | Python | add tests using matrices | ff459fd2dc3641486b35c672e0d48855669a13a5 | <ide><path>numpy/lib/tests/test_nanfunctions.py
<ide> def test_matrices(self):
<ide> assert_(res.shape == (3, 1))
<ide> res = f(mat)
<ide> assert_(np.isscalar(res))
<add> # check that rows of nan are dealt with for subclasses (#4628)
<add> mat[1] = np.nan
<add> for f in self.nanfuncs:
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.simplefilter('always')
<add> res = f(mat, axis=0)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(not np.any(np.isnan(res)))
<add> assert_(len(w) == 0)
<add>
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.simplefilter('always')
<add> res = f(mat, axis=1)
<add> assert_(isinstance(res, np.matrix))
<add> assert_(np.isnan(res[1, 0]) and not np.isnan(res[0, 0])
<add> and not np.isnan(res[2, 0]))
<add> assert_(len(w) == 1, 'no warning raised')
<add> assert_(issubclass(w[0].category, RuntimeWarning))
<add>
<add> with warnings.catch_warnings(record=True) as w:
<add> warnings.simplefilter('always')
<add> res = f(mat)
<add> assert_(np.isscalar(res))
<add> assert_(res != np.nan)
<add> assert_(len(w) == 0)
<ide>
<ide>
<ide> class TestNanFunctions_ArgminArgmax(TestCase): | 1 |
Text | Text | fix typo in the changelog entry | 790b4011b27b4d4454c1613922887ed944aa6c8d | <ide><path>railties/CHANGELOG.md
<del>* Added `--model-name` scaffld\_controller\_generator option.
<add>* Added `--model-name` option to `ScaffoldControllerGenerator`.
<ide>
<ide> *yalab*
<ide> | 1 |
Ruby | Ruby | add empty string test | 29070e5cbecad6553b29bb482ce94352682b9c64 | <ide><path>Library/Homebrew/test/rubocops/formula_desc_cop_spec.rb
<ide> class Foo < Formula
<ide> end
<ide> end
<ide>
<add> it "reports an offense when desc is an empty string" do
<add> source = <<-EOS.undent
<add> class Foo < Formula
<add> url 'http://example.com/foo-1.0.tgz'
<add> desc ''
<add> end
<add> EOS
<add>
<add> msg = "The desc (description) should not be an empty string."
<add> expected_offenses = [{ message: msg,
<add> severity: :convention,
<add> line: 3,
<add> column: 2,
<add> source: source }]
<add>
<add> inspect_source(source, "/homebrew-core/Formula/foo.rb")
<add> expected_offenses.zip(cop.offenses).each do |expected, actual|
<add> expect_offense(expected, actual)
<add> end
<add> end
<add>
<ide> it "When desc is too long" do
<ide> source = <<-EOS.undent
<ide> class Foo < Formula | 1 |
PHP | PHP | add stubs for postgres + sqlite schema dialects | 5de0541c926899defe1365d0f7e6bc0d5a56d0e6 | <ide><path>lib/Cake/Database/Dialect/PostgresDialectTrait.php
<ide> public function convertFieldDescription($row, $fieldParams = []) {
<ide> return $schema;
<ide> }
<ide>
<add>/**
<add> * Get the schema dialect.
<add> *
<add> * Used by Cake\Schema package to reflect schema and
<add> * generate schema.
<add> *
<add> * @return Cake\Database\Schema\Dialect\Postgres
<add> */
<add> public function schemaDialect() {
<add> return new \Cake\Database\Schema\Dialect\Postgres($this);
<add> }
<ide> }
<ide><path>lib/Cake/Database/Dialect/SqliteDialectTrait.php
<ide> public function convertFieldDescription($row, $fieldParams = []) {
<ide> return $schema;
<ide> }
<ide>
<add>/**
<add> * Get the schema dialect.
<add> *
<add> * Used by Cake\Schema package to reflect schema and
<add> * generate schema.
<add> *
<add> * @return Cake\Database\Schema\Dialect\Sqlite
<add> */
<add> public function schemaDialect() {
<add> return new \Cake\Database\Schema\Dialect\Sqlite($this);
<add> }
<add>
<ide> } | 2 |
Java | Java | polish various test classes | 1ade9b54331d199534b729d10340bab211b3272c | <ide><path>spring-core/src/test/java/org/springframework/core/AbstractGenericsTests.java
<del>/*
<del> * Copyright 2002-2006 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.core;
<del>
<del>import java.lang.reflect.Method;
<del>import java.lang.reflect.Type;
<del>
<del>import junit.framework.TestCase;
<del>
<del>/**
<del> * @author Serge Bogatyrjov
<del> */
<del>public abstract class AbstractGenericsTests extends TestCase {
<del>
<del> protected Class<?> targetClass;
<del>
<del> protected String methods[];
<del>
<del> protected Type expectedResults[];
<del>
<del> protected void executeTest() throws NoSuchMethodException {
<del> String methodName = getName().substring(4);
<del> methodName = methodName.substring(0, 1).toLowerCase() + methodName.substring(1);
<del> for (int i = 0; i < this.methods.length; i++) {
<del> if (methodName.equals(this.methods[i])) {
<del> Method method = this.targetClass.getMethod(methodName);
<del> Type type = getType(method);
<del> assertEquals(this.expectedResults[i], type);
<del> return;
<del> }
<del> }
<del> throw new IllegalStateException("Bad test data");
<del> }
<del>
<del> protected abstract Type getType(Method method);
<del>
<del>}
<ide>\ No newline at end of file
<ide><path>spring-core/src/test/java/org/springframework/core/AttributeAccessorSupportTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.core;
<ide>
<del>import junit.framework.TestCase;
<del>
<ide> import java.util.Arrays;
<ide>
<add>import org.junit.Test;
<add>
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * @author Rob Harrop
<add> * @author Sam Brannen
<ide> * @since 2.0
<ide> */
<del>public class AttributeAccessorSupportTests extends TestCase {
<add>public class AttributeAccessorSupportTests {
<ide>
<ide> private static final String NAME = "foo";
<ide>
<ide> private static final String VALUE = "bar";
<ide>
<del> private AttributeAccessor attributeAccessor;
<add> private AttributeAccessor attributeAccessor = new SimpleAttributeAccessorSupport();
<ide>
<del> @Override
<del> @SuppressWarnings("serial")
<del> protected void setUp() throws Exception {
<del> this.attributeAccessor = new AttributeAccessorSupport() {
<del> };
<del> }
<del>
<del> public void testSetAndGet() throws Exception {
<add> @Test
<add> public void setAndGet() throws Exception {
<ide> this.attributeAccessor.setAttribute(NAME, VALUE);
<ide> assertEquals(VALUE, this.attributeAccessor.getAttribute(NAME));
<ide> }
<ide>
<del> public void testSetAndHas() throws Exception {
<add> @Test
<add> public void setAndHas() throws Exception {
<ide> assertFalse(this.attributeAccessor.hasAttribute(NAME));
<ide> this.attributeAccessor.setAttribute(NAME, VALUE);
<ide> assertTrue(this.attributeAccessor.hasAttribute(NAME));
<ide> }
<ide>
<del> public void testRemove() throws Exception {
<add> @Test
<add> public void remove() throws Exception {
<ide> assertFalse(this.attributeAccessor.hasAttribute(NAME));
<ide> this.attributeAccessor.setAttribute(NAME, VALUE);
<ide> assertEquals(VALUE, this.attributeAccessor.removeAttribute(NAME));
<ide> assertFalse(this.attributeAccessor.hasAttribute(NAME));
<ide> }
<ide>
<del> public void testAttributeNames() throws Exception {
<add> @Test
<add> public void attributeNames() throws Exception {
<ide> this.attributeAccessor.setAttribute(NAME, VALUE);
<ide> this.attributeAccessor.setAttribute("abc", "123");
<ide> String[] attributeNames = this.attributeAccessor.attributeNames();
<ide> Arrays.sort(attributeNames);
<ide> assertTrue(Arrays.binarySearch(attributeNames, NAME) > -1);
<ide> assertTrue(Arrays.binarySearch(attributeNames, "abc") > -1);
<ide> }
<del> @Override
<del> protected void tearDown() throws Exception {
<del> this.attributeAccessor.removeAttribute(NAME);
<add>
<add> @SuppressWarnings("serial")
<add> private static class SimpleAttributeAccessorSupport extends AttributeAccessorSupport {
<ide> }
<add>
<ide> }
<ide><path>spring-core/src/test/java/org/springframework/core/BridgeMethodResolverTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void someMethod(Integer theArg, Object otherArg) {
<ide> }
<ide>
<ide>
<del> public interface Adder<T> {
<add> public static interface Adder<T> {
<ide>
<ide> void add(T item);
<ide> }
<ide>
<ide>
<del> public abstract class AbstractDateAdder implements Adder<Date> {
<add> public static abstract class AbstractDateAdder implements Adder<Date> {
<ide>
<ide> @Override
<ide> public abstract void add(Date date);
<ide> }
<ide>
<ide>
<del> public class DateAdder extends AbstractDateAdder {
<add> public static class DateAdder extends AbstractDateAdder {
<ide>
<ide> @Override
<ide> public void add(Date date) {
<ide> }
<ide> }
<ide>
<ide>
<del> public class Enclosing<T> {
<add> public static class Enclosing<T> {
<ide>
<ide> public class Enclosed<S> {
<ide>
<ide> void someMethod(S s, T t, R r) {
<ide> }
<ide>
<ide>
<del> public class ExtendsEnclosing extends Enclosing<String> {
<add> public static class ExtendsEnclosing extends Enclosing<String> {
<ide>
<ide> public class ExtendsEnclosed extends Enclosed<Integer> {
<ide>
<ide> void someMethod(Integer s, String t, Long r) {
<ide> }
<ide>
<ide>
<del> public interface Boo<E, T extends Serializable> {
<add> public static interface Boo<E, T extends Serializable> {
<ide>
<ide> void foo(E e);
<ide>
<ide> void foo(T t);
<ide> }
<ide>
<ide>
<del> public class MyBoo implements Boo<String, Integer> {
<add> public static class MyBoo implements Boo<String, Integer> {
<ide>
<ide> @Override
<ide> public void foo(String e) {
<ide> public void foo(Integer t) {
<ide> }
<ide>
<ide>
<del> public interface Settings {
<add> public static interface Settings {
<ide>
<ide> }
<ide>
<ide>
<del> public interface ConcreteSettings extends Settings {
<add> public static interface ConcreteSettings extends Settings {
<ide>
<ide> }
<ide>
<ide>
<del> public interface Dao<T, S> {
<add> public static interface Dao<T, S> {
<ide>
<ide> T load();
<ide>
<ide> S loadFromParent();
<ide> }
<ide>
<ide>
<del> public interface SettingsDao<T extends Settings, S> extends Dao<T, S> {
<add> public static interface SettingsDao<T extends Settings, S> extends Dao<T, S> {
<ide>
<ide> @Override
<ide> T load();
<ide> }
<ide>
<ide>
<del> public interface ConcreteSettingsDao extends SettingsDao<ConcreteSettings, String> {
<add> public static interface ConcreteSettingsDao extends
<add> SettingsDao<ConcreteSettings, String> {
<ide>
<ide> @Override
<ide> String loadFromParent();
<ide> }
<ide>
<ide>
<del> abstract class AbstractDaoImpl<T, S> implements Dao<T, S> {
<add> static abstract class AbstractDaoImpl<T, S> implements Dao<T, S> {
<ide>
<ide> protected T object;
<ide>
<ide> public S loadFromParent() {
<ide> }
<ide>
<ide>
<del> class SettingsDaoImpl extends AbstractDaoImpl<ConcreteSettings, String> implements ConcreteSettingsDao {
<add> static class SettingsDaoImpl extends AbstractDaoImpl<ConcreteSettings, String>
<add> implements ConcreteSettingsDao {
<ide>
<ide> protected SettingsDaoImpl(ConcreteSettings object) {
<ide> super(object, "From Parent");
<ide> public List<String> subList(int fromIndex, int toIndex) {
<ide> }
<ide>
<ide>
<del> public interface Event {
<add> public static interface Event {
<ide>
<ide> int getPriority();
<ide> }
<ide>
<ide>
<del> public class GenericEvent implements Event {
<add> public static class GenericEvent implements Event {
<ide>
<ide> private int priority;
<ide>
<ide> public GenericEvent() {
<ide> }
<ide>
<ide>
<del> public interface UserInitiatedEvent {
<add> public static interface UserInitiatedEvent {
<ide>
<ide> //public Session getInitiatorSession();
<ide> }
<ide>
<ide>
<del> public abstract class BaseUserInitiatedEvent extends GenericEvent implements UserInitiatedEvent {
<add> public static abstract class BaseUserInitiatedEvent extends GenericEvent implements
<add> UserInitiatedEvent {
<ide>
<ide> }
<ide>
<ide>
<del> public class MessageEvent extends BaseUserInitiatedEvent {
<add> public static class MessageEvent extends BaseUserInitiatedEvent {
<ide>
<ide> }
<ide>
<ide>
<del> public interface Channel<E extends Event> {
<add> public static interface Channel<E extends Event> {
<ide>
<ide> void send(E event);
<ide>
<ide> public class MessageEvent extends BaseUserInitiatedEvent {
<ide> }
<ide>
<ide>
<del> public interface Broadcaster {
<add> public static interface Broadcaster {
<ide> }
<ide>
<ide>
<del> public interface EventBroadcaster extends Broadcaster {
<add> public static interface EventBroadcaster extends Broadcaster {
<ide>
<ide> public void subscribe();
<ide>
<ide> public interface EventBroadcaster extends Broadcaster {
<ide> }
<ide>
<ide>
<del> public class GenericBroadcasterImpl implements Broadcaster {
<add> public static class GenericBroadcasterImpl implements Broadcaster {
<ide>
<ide> }
<ide>
<ide>
<ide> @SuppressWarnings({ "unused", "unchecked" })
<del> public abstract class GenericEventBroadcasterImpl<T extends Event> extends GenericBroadcasterImpl
<add> public static abstract class GenericEventBroadcasterImpl<T extends Event> extends
<add> GenericBroadcasterImpl
<ide> implements EventBroadcaster {
<ide>
<ide> private Class<T>[] subscribingEvents;
<ide> public GenericEventBroadcasterImpl(Class<? extends T>... events) {
<ide> }
<ide>
<ide>
<del> public interface Receiver<E extends Event> {
<add> public static interface Receiver<E extends Event> {
<ide>
<ide> void receive(E event);
<ide> }
<ide>
<ide>
<del> public interface MessageBroadcaster extends Receiver<MessageEvent> {
<add> public static interface MessageBroadcaster extends Receiver<MessageEvent> {
<ide>
<ide> }
<ide>
<ide>
<del> public class RemovedMessageEvent extends MessageEvent {
<add> public static class RemovedMessageEvent extends MessageEvent {
<ide>
<ide> }
<ide>
<ide>
<del> public class NewMessageEvent extends MessageEvent {
<add> public static class NewMessageEvent extends MessageEvent {
<ide>
<ide> }
<ide>
<ide>
<del> public class ModifiedMessageEvent extends MessageEvent {
<add> public static class ModifiedMessageEvent extends MessageEvent {
<ide>
<ide> }
<ide>
<ide>
<ide> @SuppressWarnings("unchecked")
<del> public class MessageBroadcasterImpl extends GenericEventBroadcasterImpl<MessageEvent>
<add> public static class MessageBroadcasterImpl extends
<add> GenericEventBroadcasterImpl<MessageEvent>
<ide> implements MessageBroadcaster {
<ide>
<ide> public MessageBroadcasterImpl() {
<ide> public void receive(ModifiedMessageEvent event) {
<ide> // SPR-2454 Test Classes
<ide> //-----------------------------
<ide>
<del> public interface SimpleGenericRepository<T> {
<add> public static interface SimpleGenericRepository<T> {
<ide>
<ide> public Class<T> getPersistentClass();
<ide>
<ide> public void receive(ModifiedMessageEvent event) {
<ide> }
<ide>
<ide>
<del> public interface RepositoryRegistry {
<add> public static interface RepositoryRegistry {
<ide>
<ide> <T> SimpleGenericRepository<T> getFor(Class<T> entityType);
<ide> }
<ide>
<ide>
<ide> @SuppressWarnings("unchecked")
<del> public class SettableRepositoryRegistry<R extends SimpleGenericRepository<?>>
<add> public static class SettableRepositoryRegistry<R extends SimpleGenericRepository<?>>
<ide> implements RepositoryRegistry {
<ide>
<ide> protected void injectInto(R rep) {
<ide> public void afterPropertiesSet() throws Exception {
<ide> }
<ide>
<ide>
<del> public interface ConvenientGenericRepository<T, ID extends Serializable> extends SimpleGenericRepository<T> {
<add> public static interface ConvenientGenericRepository<T, ID extends Serializable>
<add> extends SimpleGenericRepository<T> {
<ide>
<ide> T findById(ID id, boolean lock);
<ide>
<ide> public void afterPropertiesSet() throws Exception {
<ide> }
<ide>
<ide>
<del> public class GenericHibernateRepository<T, ID extends Serializable>
<add> public static class GenericHibernateRepository<T, ID extends Serializable>
<ide> implements ConvenientGenericRepository<T, ID> {
<ide>
<ide> /**
<ide> public void delete(Collection<T> entities) {
<ide> }
<ide>
<ide>
<del> public class HibernateRepositoryRegistry extends SettableRepositoryRegistry<GenericHibernateRepository<?, ?>> {
<add> public static class HibernateRepositoryRegistry extends
<add> SettableRepositoryRegistry<GenericHibernateRepository<?, ?>> {
<ide>
<ide> @Override
<ide> public void injectInto(GenericHibernateRepository<?, ?> rep) {
<ide> public void injectInto(GenericHibernateRepository<?, ?> rep) {
<ide> // SPR-2603 classes
<ide> //-------------------
<ide>
<del> public interface Homer<E> {
<add> public static interface Homer<E> {
<ide>
<ide> void foo(E e);
<ide> }
<ide>
<ide>
<del> public class MyHomer<T extends Bounded<T>, L extends T> implements Homer<L> {
<add> public static class MyHomer<T extends Bounded<T>, L extends T> implements Homer<L> {
<ide>
<ide> @Override
<ide> public void foo(L t) {
<ide> public void foo(L t) {
<ide> }
<ide>
<ide>
<del> public class YourHomer<T extends AbstractBounded<T>, L extends T> extends MyHomer<T, L> {
<add> public static class YourHomer<T extends AbstractBounded<T>, L extends T> extends
<add> MyHomer<T, L> {
<ide>
<ide> @Override
<ide> public void foo(L t) {
<ide> public void foo(L t) {
<ide> }
<ide>
<ide>
<del> public interface GenericDao<T> {
<add> public static interface GenericDao<T> {
<ide>
<ide> public void saveOrUpdate(T t);
<ide> }
<ide>
<ide>
<del> public interface ConvenienceGenericDao<T> extends GenericDao<T> {
<add> public static interface ConvenienceGenericDao<T> extends GenericDao<T> {
<ide> }
<ide>
<ide>
<del> public class GenericSqlMapDao<T extends Serializable> implements ConvenienceGenericDao<T> {
<add> public static class GenericSqlMapDao<T extends Serializable> implements
<add> ConvenienceGenericDao<T> {
<ide>
<ide> @Override
<ide> public void saveOrUpdate(T t) {
<ide> public void saveOrUpdate(T t) {
<ide> }
<ide>
<ide>
<del> public class GenericSqlMapIntegerDao<T extends Number> extends GenericSqlMapDao<T> {
<add> public static class GenericSqlMapIntegerDao<T extends Number> extends
<add> GenericSqlMapDao<T> {
<ide>
<ide> @Override
<ide> public void saveOrUpdate(T t) {
<ide> }
<ide> }
<ide>
<ide>
<del> public class Permission {
<add> public static class Permission {
<ide> }
<ide>
<ide>
<del> public class User {
<add> public static class User {
<ide> }
<ide>
<ide>
<del> public interface UserDao {
<add> public static interface UserDao {
<ide>
<ide> //@Transactional
<ide> void save(User user);
<ide> public interface UserDao {
<ide> }
<ide>
<ide>
<del> public abstract class AbstractDao<T> {
<add> public static abstract class AbstractDao<T> {
<ide>
<ide> public void save(T t) {
<ide> }
<ide> public void saveVararg(T t, Object... args) {
<ide> }
<ide>
<ide>
<del> public class UserDaoImpl extends AbstractDao<User> implements UserDao {
<add> public static class UserDaoImpl extends AbstractDao<User> implements UserDao {
<ide>
<ide> @Override
<ide> public void save(Permission perm) {
<ide> public void saveVararg(User user, Object... args) {
<ide> }
<ide>
<ide>
<del> public interface DaoInterface<T,P> {
<add> public static interface DaoInterface<T, P> {
<ide> T get(P id);
<ide> }
<ide>
<ide>
<del> public abstract class BusinessGenericDao<T, PK extends Serializable> implements DaoInterface<T, PK> {
<add> public static abstract class BusinessGenericDao<T, PK extends Serializable>
<add> implements DaoInterface<T, PK> {
<ide>
<ide> public void save(T object) {
<ide> }
<ide> }
<ide>
<ide>
<del> public class Business<T> {
<add> public static class Business<T> {
<ide> }
<ide>
<ide>
<del> public class BusinessDao extends BusinessGenericDao<Business<?>, Long> {
<add> public static class BusinessDao extends BusinessGenericDao<Business<?>, Long> {
<ide>
<del> @Override
<del> public void save(Business<?> business) {
<del> }
<add> @Override
<add> public void save(Business<?> business) {
<add> }
<ide>
<ide> @Override
<ide> public Business<?> get(Long id) {
<ide> private static class DomainObjectExtendsSuper extends DomainObjectSuper {
<ide> }
<ide>
<ide>
<del> public interface IGenericInterface<D extends DomainObjectSuper> {
<add> public static interface IGenericInterface<D extends DomainObjectSuper> {
<ide>
<ide> <T> void doSomething(final D domainObject, final T value);
<ide> }
<ide> public void method2(ParameterType p, byte[] r) {
<ide> // SPR-3534 classes
<ide> //-------------------
<ide>
<del> public interface SearchProvider<RETURN_TYPE, CONDITIONS_TYPE> {
<add> public static interface SearchProvider<RETURN_TYPE, CONDITIONS_TYPE> {
<ide>
<ide> Collection<RETURN_TYPE> findBy(CONDITIONS_TYPE conditions);
<ide> }
<ide> public static class SearchConditions {
<ide> }
<ide>
<ide>
<del> public interface IExternalMessageProvider<S extends ExternalMessage, T extends ExternalMessageSearchConditions<?>>
<add> public static interface IExternalMessageProvider<S extends ExternalMessage, T extends ExternalMessageSearchConditions<?>>
<ide> extends SearchProvider<S, T> {
<ide> }
<ide>
<add><path>spring-core/src/test/java/org/springframework/core/ControlFlowTests.java
<del><path>spring-core/src/test/java/org/springframework/core/AbstractControlFlowTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.core;
<ide>
<del>import junit.framework.TestCase;
<add>import org.junit.Test;
<add>
<add>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * @author Rod Johnson
<add> * @author Sam Brannen
<ide> */
<del>public abstract class AbstractControlFlowTests extends TestCase {
<del>
<del> protected abstract ControlFlow createControlFlow();
<add>public class ControlFlowTests {
<ide>
<del> /*
<del> * Class to test for boolean under(Class)
<del> */
<del> public void testUnderClassAndMethod() {
<add> @Test
<add> public void underClassAndMethod() {
<ide> new One().test();
<ide> new Two().testing();
<ide> new Three().test();
<ide> }
<ide>
<del> /*
<del> public void testUnderPackage() {
<del> ControlFlow cflow = new ControlFlow();
<del> assertFalse(cflow.underPackage("org.springframework.aop"));
<del> assertTrue(cflow.underPackage("org.springframework.aop.support"));
<del> assertFalse(cflow.underPackage("com.interface21"));
<del> }
<del> */
<del>
<add> static class One {
<ide>
<del> public class One {
<del>
<del> public void test() {
<del> ControlFlow cflow = createControlFlow();
<add> void test() {
<add> ControlFlow cflow = ControlFlowFactory.createControlFlow();
<ide> assertTrue(cflow.under(One.class));
<del> assertTrue(cflow.under(AbstractControlFlowTests.class));
<add> assertTrue(cflow.under(ControlFlowTests.class));
<ide> assertFalse(cflow.under(Two.class));
<ide> assertTrue(cflow.under(One.class, "test"));
<ide> assertFalse(cflow.under(One.class, "hashCode"));
<ide> }
<del>
<ide> }
<ide>
<add> static class Two {
<ide>
<del> public class Two {
<del>
<del> public void testing() {
<del> ControlFlow cflow = createControlFlow();
<add> void testing() {
<add> ControlFlow cflow = ControlFlowFactory.createControlFlow();
<ide> assertTrue(cflow.under(Two.class));
<del> assertTrue(cflow.under(AbstractControlFlowTests.class));
<add> assertTrue(cflow.under(ControlFlowTests.class));
<ide> assertFalse(cflow.under(One.class));
<ide> assertFalse(cflow.under(Two.class, "test"));
<ide> assertTrue(cflow.under(Two.class, "testing"));
<ide> }
<ide> }
<ide>
<add> static class Three {
<ide>
<del> public class Three {
<del>
<del> public void test() {
<add> void test() {
<ide> testing();
<ide> }
<ide>
<ide> private void testing() {
<del> ControlFlow cflow = createControlFlow();
<add> ControlFlow cflow = ControlFlowFactory.createControlFlow();
<ide> assertTrue(cflow.under(Three.class));
<del> assertTrue(cflow.under(AbstractControlFlowTests.class));
<add> assertTrue(cflow.under(ControlFlowTests.class));
<ide> assertFalse(cflow.under(One.class));
<ide> assertTrue(cflow.under(Three.class, "test"));
<ide> assertTrue(cflow.under(Three.class, "testing"));
<ide><path>spring-core/src/test/java/org/springframework/core/DefaultControlFlowTests.java
<del>/*
<del> * Copyright 2002-2012 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.core;
<del>
<del>/**
<del> * Tests with ControlFlowFactory return.
<del> *
<del> * @author Rod Johnson
<del> */
<del>public class DefaultControlFlowTests extends AbstractControlFlowTests {
<del>
<del> /**
<del> * Necessary only because Eclipse won't run test suite unless
<del> * it declares some methods as well as inherited methods.
<del> */
<del> public void testThisClassPlease() {
<del> }
<del>
<del> @Override
<del> protected ControlFlow createControlFlow() {
<del> return ControlFlowFactory.createControlFlow();
<del> }
<del>
<del>}
<ide><path>spring-core/src/test/java/org/springframework/core/GenericCollectionTypeResolverTests.java
<ide> /*
<del> * Copyright 2002-2013 the original author or authors.
<add> * Copyright 2002-2014 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.Map;
<ide> import java.util.Set;
<ide>
<add>import org.junit.Before;
<add>import org.junit.Test;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.tests.sample.objects.GenericObject;
<ide>
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * @author Serge Bogatyrjov
<ide> * @author Juergen Hoeller
<add> * @author Sam Brannen
<ide> */
<del>public class GenericCollectionTypeResolverTests extends AbstractGenericsTests {
<add>public class GenericCollectionTypeResolverTests {
<add>
<add> protected Class<?> targetClass;
<add>
<add> protected String[] methods;
<ide>
<del> @Override
<del> protected void setUp() throws Exception {
<add> protected Type[] expectedResults;
<add>
<add> @Before
<add> public void setUp() throws Exception {
<ide> this.targetClass = Foo.class;
<del> this.methods = new String[] {"a", "b", "b2", "b3", "c", "d", "d2", "d3", "e", "e2", "e3"};
<del> this.expectedResults = new Class[] {
<del> Integer.class, null, Set.class, Set.class, null, Integer.class,
<del> Integer.class, Integer.class, Integer.class, Integer.class, Integer.class};
<add> this.methods = new String[] { "a", "b", "b2", "b3", "c", "d", "d2", "d3", "e",
<add> "e2", "e3" };
<add> this.expectedResults = new Class[] { Integer.class, null, Set.class, Set.class,
<add> null, Integer.class, Integer.class, Integer.class, Integer.class,
<add> Integer.class, Integer.class };
<add> }
<add>
<add> protected void executeTest(String methodName) throws NoSuchMethodException {
<add> for (int i = 0; i < this.methods.length; i++) {
<add> if (methodName.equals(this.methods[i])) {
<add> Method method = this.targetClass.getMethod(methodName);
<add> Type type = getType(method);
<add> assertEquals(this.expectedResults[i], type);
<add> return;
<add> }
<add> }
<add> throw new IllegalStateException("Bad test data");
<ide> }
<ide>
<del> @Override
<ide> protected Type getType(Method method) {
<ide> return GenericCollectionTypeResolver.getMapValueReturnType(method);
<ide> }
<ide>
<del> public void testA() throws Exception {
<del> executeTest();
<add> @Test
<add> public void a() throws Exception {
<add> executeTest("a");
<ide> }
<ide>
<del> public void testB() throws Exception {
<del> executeTest();
<add> @Test
<add> public void b() throws Exception {
<add> executeTest("b");
<ide> }
<ide>
<del> public void testB2() throws Exception {
<del> executeTest();
<add> @Test
<add> public void b2() throws Exception {
<add> executeTest("b2");
<ide> }
<ide>
<del> public void testB3() throws Exception {
<del> executeTest();
<add> @Test
<add> public void b3() throws Exception {
<add> executeTest("b3");
<ide> }
<ide>
<del> public void testC() throws Exception {
<del> executeTest();
<add> @Test
<add> public void c() throws Exception {
<add> executeTest("c");
<ide> }
<ide>
<del> public void testD() throws Exception {
<del> executeTest();
<add> @Test
<add> public void d() throws Exception {
<add> executeTest("d");
<ide> }
<ide>
<del> public void testD2() throws Exception {
<del> executeTest();
<add> @Test
<add> public void d2() throws Exception {
<add> executeTest("d2");
<ide> }
<ide>
<del> public void testD3() throws Exception {
<del> executeTest();
<add> @Test
<add> public void d3() throws Exception {
<add> executeTest("d3");
<ide> }
<ide>
<del> public void testE() throws Exception {
<del> executeTest();
<add> @Test
<add> public void e() throws Exception {
<add> executeTest("e");
<ide> }
<ide>
<del> public void testE2() throws Exception {
<del> executeTest();
<add> @Test
<add> public void e2() throws Exception {
<add> executeTest("e2");
<ide> }
<ide>
<del> public void testE3() throws Exception {
<del> executeTest();
<add> @Test
<add> public void e3() throws Exception {
<add> executeTest("e3");
<ide> }
<ide>
<del> public void testProgrammaticListIntrospection() throws Exception {
<add> @Test
<add> public void programmaticListIntrospection() throws Exception {
<ide> Method setter = GenericObject.class.getMethod("setResourceList", List.class);
<del> assertEquals(Resource.class,
<del> GenericCollectionTypeResolver.getCollectionParameterType(new MethodParameter(setter, 0)));
<add> assertEquals(
<add> Resource.class,
<add> GenericCollectionTypeResolver.getCollectionParameterType(new MethodParameter(
<add> setter, 0)));
<ide>
<ide> Method getter = GenericObject.class.getMethod("getResourceList");
<ide> assertEquals(Resource.class,
<ide> GenericCollectionTypeResolver.getCollectionReturnType(getter));
<ide> }
<ide>
<del> public void testClassResolution() {
<del> assertEquals(String.class, GenericCollectionTypeResolver.getCollectionType(CustomSet.class));
<del> assertEquals(String.class, GenericCollectionTypeResolver.getMapKeyType(CustomMap.class));
<del> assertEquals(Integer.class, GenericCollectionTypeResolver.getMapValueType(CustomMap.class));
<add> @Test
<add> public void classResolution() {
<add> assertEquals(String.class,
<add> GenericCollectionTypeResolver.getCollectionType(CustomSet.class));
<add> assertEquals(String.class,
<add> GenericCollectionTypeResolver.getMapKeyType(CustomMap.class));
<add> assertEquals(Integer.class,
<add> GenericCollectionTypeResolver.getMapValueType(CustomMap.class));
<ide> }
<ide>
<del>
<del> private abstract class CustomSet<T> extends AbstractSet<String> {
<add> private static abstract class CustomSet<T> extends AbstractSet<String> {
<ide> }
<ide>
<del>
<del> private abstract class CustomMap<T> extends AbstractMap<String, Integer> {
<add> private static abstract class CustomMap<T> extends AbstractMap<String, Integer> {
<ide> }
<ide>
<del>
<del> private abstract class OtherCustomMap<T> implements Map<String, Integer> {
<add> private static abstract class OtherCustomMap<T> implements Map<String, Integer> {
<ide> }
<ide>
<del>
<del> private interface Foo {
<add> @SuppressWarnings("rawtypes")
<add> private static interface Foo {
<ide>
<ide> Map<String, Integer> a();
<ide>
<ide><path>spring-core/src/test/java/org/springframework/core/Jdk14ControlFlowTests.java
<del>/*
<del> * Copyright 2002-2012 the original author or authors.
<del> *
<del> * Licensed under the Apache License, Version 2.0 (the "License");
<del> * you may not use this file except in compliance with the License.
<del> * You may obtain a copy of the License at
<del> *
<del> * http://www.apache.org/licenses/LICENSE-2.0
<del> *
<del> * Unless required by applicable law or agreed to in writing, software
<del> * distributed under the License is distributed on an "AS IS" BASIS,
<del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<del> * See the License for the specific language governing permissions and
<del> * limitations under the License.
<del> */
<del>
<del>package org.springframework.core;
<del>
<del>/**
<del> * Tests with ControlFlowFactory return.
<del> *
<del> * @author Rod Johnson
<del> */
<del>public class Jdk14ControlFlowTests extends AbstractControlFlowTests {
<del>
<del> /**
<del> * Necessary only because Eclipse won't run test suite unless it declares
<del> * some methods as well as inherited methods
<del> */
<del> public void testThisClassPlease() {
<del> }
<del>
<del> @Override
<del> protected ControlFlow createControlFlow() {
<del> return ControlFlowFactory.createControlFlow();
<del> }
<del>
<del>} | 7 |
Ruby | Ruby | remove warnings on ruby 2.1 | 5402b72faafecfa1eda8afce0e0f194fcf385fe3 | <ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb
<ide> def deep_symbolize_keys; to_hash.deep_symbolize_keys! end
<ide> def to_options!; self end
<ide>
<ide> def select(*args, &block)
<del> dup.tap {|hash| hash.select!(*args, &block)}
<add> dup.tap { |hash| hash.select!(*args, &block)}
<add> end
<add>
<add> def reject(*args, &block)
<add> dup.tap { |hash| hash.reject!(*args, &block)}
<ide> end
<ide>
<ide> # Convert to a regular hash with string keys.
<ide><path>activesupport/lib/active_support/ordered_hash.rb
<ide> def encode_with(coder)
<ide> coder.represent_seq '!omap', map { |k,v| { k => v } }
<ide> end
<ide>
<add> def reject(*args, &block)
<add> dup.tap { |hash| hash.reject!(*args, &block)}
<add> end
<add>
<ide> def nested_under_indifferent_access
<ide> self
<ide> end | 2 |
Java | Java | use dynamicfromobject to avoid maps | a46fba5dd366144d76a56a6e780c5183a14d18cb | <ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/DynamicFromObject.java
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> */
<add>
<add>package com.facebook.react.bridge;
<add>
<add>import com.facebook.common.logging.FLog;
<add>import com.facebook.react.common.ReactConstants;
<add>import javax.annotation.Nullable;
<add>
<add>/**
<add> * Implementation of Dynamic wrapping a ReadableArray.
<add> */
<add>public class DynamicFromObject implements Dynamic {
<add> private @Nullable Object mObject;
<add>
<add> public DynamicFromObject(@Nullable Object obj) {
<add> mObject = obj;
<add> }
<add>
<add> @Override
<add> public void recycle() {
<add> // Noop - nothing to recycle since there is no pooling
<add> }
<add>
<add> @Override
<add> public boolean isNull() {
<add> return mObject == null;
<add> }
<add>
<add> @Override
<add> public boolean asBoolean() {
<add> return (boolean)mObject;
<add> }
<add>
<add> @Override
<add> public double asDouble() {
<add> return (double)mObject;
<add> }
<add>
<add> @Override
<add> public int asInt() {
<add> // Numbers from JS are always Doubles
<add> return ((Double)mObject).intValue();
<add> }
<add>
<add> @Override
<add> public String asString() {
<add> return (String)mObject;
<add> }
<add>
<add> @Override
<add> public ReadableArray asArray() {
<add> return (ReadableArray)mObject;
<add> }
<add>
<add> @Override
<add> public ReadableMap asMap() {
<add> return (ReadableMap)mObject;
<add> }
<add>
<add> @Override
<add> public ReadableType getType() {
<add> if (isNull()) {
<add> return ReadableType.Null;
<add> }
<add> if (mObject instanceof Boolean) {
<add> return ReadableType.Boolean;
<add> }
<add> if (mObject instanceof Number) {
<add> return ReadableType.Number;
<add> }
<add> if (mObject instanceof String) {
<add> return ReadableType.String;
<add> }
<add> if (mObject instanceof ReadableMap) {
<add> return ReadableType.Map;
<add> }
<add> if (mObject instanceof ReadableArray) {
<add> return ReadableType.Array;
<add> }
<add> FLog.e(ReactConstants.TAG, "Unmapped object type " + mObject.getClass().getName());
<add> return ReadableType.Null;
<add> }
<add>}
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/JavaOnlyMap.java
<ide> /**
<ide> * Copyright (c) Facebook, Inc. and its affiliates.
<ide> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
<add> * directory of this source tree.
<ide> */
<del>
<ide> package com.facebook.react.bridge;
<ide>
<ide> import java.util.HashMap;
<ide> * of {@link WritableNativeMap} created via {@link Arguments#createMap} or just {@link ReadableMap}
<ide> * interface if you want your "native" module method to take a map from JS as an argument.
<ide> *
<del> * Main purpose for this class is to be used in java-only unit tests, but could also be used outside
<del> * of tests in the code that operates only in java and needs to communicate with RN modules via
<del> * their JS-exposed API.
<add> * <p>Main purpose for this class is to be used in java-only unit tests, but could also be used
<add> * outside of tests in the code that operates only in java and needs to communicate with RN modules
<add> * via their JS-exposed API.
<ide> */
<ide> public class JavaOnlyMap implements ReadableMap, WritableMap {
<ide>
<ide> public static JavaOnlyMap deepClone(ReadableMap map) {
<ide> return res;
<ide> }
<ide>
<del> /**
<del> * @param keysAndValues keys and values, interleaved
<del> */
<add> /** @param keysAndValues keys and values, interleaved */
<ide> private JavaOnlyMap(Object... keysAndValues) {
<ide> if (keysAndValues.length % 2 != 0) {
<ide> throw new IllegalArgumentException("You must provide the same number of keys and values");
<ide> }
<ide> mBackingMap = new HashMap();
<ide> for (int i = 0; i < keysAndValues.length; i += 2) {
<del> mBackingMap.put(keysAndValues[i], keysAndValues[i + 1]);
<add> Object val = keysAndValues[i + 1];
<add> if (val instanceof Number) {
<add> // all values from JS are doubles, so emulate that here for tests.
<add> val = ((Number)val).doubleValue();
<add> }
<add> mBackingMap.put(keysAndValues[i], val);
<ide> }
<ide> }
<ide>
<ide> public JavaOnlyArray getArray(@Nonnull String name) {
<ide> } else if (value instanceof Dynamic) {
<ide> return ((Dynamic) value).getType();
<ide> } else {
<del> throw new IllegalArgumentException("Invalid value " + value.toString() + " for key " + name +
<del> "contained in JavaOnlyMap");
<add> throw new IllegalArgumentException(
<add> "Invalid value " + value.toString() + " for key " + name + "contained in JavaOnlyMap");
<ide> }
<ide> }
<ide>
<add> @Override
<add> public @Nonnull Iterator<Map.Entry<String, Object>> getEntryIterator() {
<add> return mBackingMap.entrySet().iterator();
<add> }
<add>
<ide> @Override
<ide> public @Nonnull ReadableMapKeySetIterator keySetIterator() {
<ide> return new ReadableMapKeySetIterator() {
<del> Iterator<String> mIterator = mBackingMap.keySet().iterator();
<add> Iterator<Map.Entry<String, Object>> mIterator = mBackingMap.entrySet().iterator();
<ide>
<ide> @Override
<ide> public boolean hasNextKey() {
<ide> public boolean hasNextKey() {
<ide>
<ide> @Override
<ide> public String nextKey() {
<del> return mIterator.next();
<add> return mIterator.next().getKey();
<ide> }
<ide> };
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableMap.java
<ide> /**
<ide> * Copyright (c) Facebook, Inc. and its affiliates.
<ide> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
<add> * directory of this source tree.
<ide> */
<del>
<ide> package com.facebook.react.bridge;
<ide>
<ide> import java.util.HashMap;
<add>import java.util.Iterator;
<add>import java.util.Map;
<ide>
<ide> import javax.annotation.Nonnull;
<ide> import javax.annotation.Nullable;
<ide> public interface ReadableMap {
<ide>
<ide> boolean hasKey(@Nonnull String name);
<add>
<ide> boolean isNull(@Nonnull String name);
<add>
<ide> boolean getBoolean(@Nonnull String name);
<add>
<ide> double getDouble(@Nonnull String name);
<add>
<ide> int getInt(@Nonnull String name);
<del> @Nullable String getString(@Nonnull String name);
<del> @Nullable ReadableArray getArray(@Nonnull String name);
<del> @Nullable ReadableMap getMap(@Nonnull String name);
<del> @Nonnull Dynamic getDynamic(@Nonnull String name);
<del> @Nonnull ReadableType getType(@Nonnull String name);
<del> @Nonnull ReadableMapKeySetIterator keySetIterator();
<del> @Nonnull HashMap<String, Object> toHashMap();
<ide>
<add> @Nullable
<add> String getString(@Nonnull String name);
<add>
<add> @Nullable
<add> ReadableArray getArray(@Nonnull String name);
<add>
<add> @Nullable
<add> ReadableMap getMap(@Nonnull String name);
<add>
<add> @Nonnull
<add> Dynamic getDynamic(@Nonnull String name);
<add>
<add> @Nonnull
<add> ReadableType getType(@Nonnull String name);
<add>
<add> @Nonnull
<add> Iterator<Map.Entry<String, Object>> getEntryIterator();
<add>
<add> @Nonnull
<add> ReadableMapKeySetIterator keySetIterator();
<add>
<add> @Nonnull
<add> HashMap<String, Object> toHashMap();
<ide> }
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java
<ide> /**
<ide> * Copyright (c) Facebook, Inc. and its affiliates.
<ide> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<add> * <p>This source code is licensed under the MIT license found in the LICENSE file in the root
<add> * directory of this source tree.
<ide> */
<del>
<ide> package com.facebook.react.bridge;
<ide>
<ide> import com.facebook.infer.annotation.Assertions;
<ide> import com.facebook.react.config.ReactFeatureFlags;
<ide> import java.util.HashMap;
<ide> import java.util.Iterator;
<add>import java.util.Map;
<ide>
<ide> import javax.annotation.Nonnull;
<ide> import javax.annotation.Nullable;
<ide> protected ReadableNativeMap(HybridData hybridData) {
<ide> }
<ide>
<ide> private @Nullable String[] mKeys;
<del> private @Nullable HashMap<String,Object> mLocalMap;
<del> private @Nullable HashMap<String,ReadableType> mLocalTypeMap;
<add> private @Nullable HashMap<String, Object> mLocalMap;
<add> private @Nullable HashMap<String, ReadableType> mLocalTypeMap;
<ide> private static int mJniCallCounter;
<add>
<ide> public static void setUseNativeAccessor(boolean useNativeAccessor) {
<ide> ReactFeatureFlags.useMapNativeAccessor = useNativeAccessor;
<ide> }
<add>
<ide> public static int getJNIPassCounter() {
<ide> return mJniCallCounter;
<ide> }
<ide>
<del> private HashMap<String,Object> getLocalMap() {
<add> private HashMap<String, Object> getLocalMap() {
<ide> // Fast return for the common case
<ide> if (mLocalMap != null) {
<ide> return mLocalMap;
<ide> private HashMap<String,Object> getLocalMap() {
<ide> mJniCallCounter++;
<ide> int length = mKeys.length;
<ide> mLocalMap = new HashMap<>(length);
<del> for(int i = 0; i< length; i++) {
<add> for (int i = 0; i < length; i++) {
<ide> mLocalMap.put(mKeys[i], values[i]);
<ide> }
<ide> }
<ide> }
<ide> return mLocalMap;
<ide> }
<add>
<ide> private native String[] importKeys();
<add>
<ide> private native Object[] importValues();
<ide>
<del> private @Nonnull HashMap<String,ReadableType> getLocalTypeMap() {
<add> private @Nonnull HashMap<String, ReadableType> getLocalTypeMap() {
<ide> // Fast and non-blocking return for common case
<ide> if (mLocalTypeMap != null) {
<ide> return mLocalTypeMap;
<ide> private HashMap<String,Object> getLocalMap() {
<ide> mJniCallCounter++;
<ide> int length = mKeys.length;
<ide> mLocalTypeMap = new HashMap<>(length);
<del> for(int i = 0; i< length; i++) {
<add> for (int i = 0; i < length; i++) {
<ide> mLocalTypeMap.put(mKeys[i], (ReadableType) types[i]);
<ide> }
<ide> }
<ide> }
<ide> return mLocalTypeMap;
<ide> }
<add>
<ide> private native Object[] importTypes();
<ide>
<ide> @Override
<ide> public boolean hasKey(@Nonnull String name) {
<ide> }
<ide> return getLocalMap().containsKey(name);
<ide> }
<add>
<ide> private native boolean hasKeyNative(String name);
<ide>
<ide> @Override
<ide> public boolean isNull(@Nonnull String name) {
<ide> }
<ide> throw new NoSuchKeyException(name);
<ide> }
<add>
<ide> private native boolean isNullNative(@Nonnull String name);
<ide>
<ide> private @Nonnull Object getValue(@Nonnull String name) {
<ide> private <T> T getValue(String name, Class<T> type) {
<ide> private void checkInstance(String name, Object value, Class type) {
<ide> if (value != null && !type.isInstance(value)) {
<ide> throw new ClassCastException(
<del> "Value for " + name + " cannot be cast from " +
<del> value.getClass().getSimpleName() + " to " + type.getSimpleName());
<add> "Value for "
<add> + name
<add> + " cannot be cast from "
<add> + value.getClass().getSimpleName()
<add> + " to "
<add> + type.getSimpleName());
<ide> }
<ide> }
<ide>
<ide> public boolean getBoolean(@Nonnull String name) {
<ide> }
<ide> return getValue(name, Boolean.class).booleanValue();
<ide> }
<add>
<ide> private native boolean getBooleanNative(String name);
<ide>
<ide> @Override
<ide> public double getDouble(@Nonnull String name) {
<ide> }
<ide> return getValue(name, Double.class).doubleValue();
<ide> }
<add>
<ide> private native double getDoubleNative(String name);
<ide>
<ide> @Override
<ide> public int getInt(@Nonnull String name) {
<ide> // All numbers coming out of native are doubles, so cast here then truncate
<ide> return getValue(name, Double.class).intValue();
<ide> }
<add>
<ide> private native int getIntNative(String name);
<ide>
<ide> @Override
<ide> public int getInt(@Nonnull String name) {
<ide> }
<ide> return getNullableValue(name, String.class);
<ide> }
<add>
<ide> private native String getStringNative(String name);
<ide>
<ide> @Override
<ide> public int getInt(@Nonnull String name) {
<ide> }
<ide> return getNullableValue(name, ReadableArray.class);
<ide> }
<add>
<ide> private native ReadableNativeArray getArrayNative(String name);
<ide>
<ide> @Override
<ide> public int getInt(@Nonnull String name) {
<ide> }
<ide> return getNullableValue(name, ReadableNativeMap.class);
<ide> }
<add>
<ide> private native ReadableNativeMap getMapNative(String name);
<ide>
<ide> @Override
<ide> public int getInt(@Nonnull String name) {
<ide> }
<ide> throw new NoSuchKeyException(name);
<ide> }
<add>
<ide> private native ReadableType getTypeNative(String name);
<ide>
<ide> @Override
<ide> public @Nonnull Dynamic getDynamic(@Nonnull String name) {
<ide> return DynamicFromMap.create(this, name);
<ide> }
<ide>
<add> @Override
<add> public @Nonnull Iterator<Map.Entry<String, Object>> getEntryIterator() {
<add> return getLocalMap().entrySet().iterator();
<add> }
<add>
<ide> @Override
<ide> public @Nonnull ReadableMapKeySetIterator keySetIterator() {
<ide> return new ReadableNativeMapKeySetIterator(this);
<ide> public boolean equals(Object obj) {
<ide> break;
<ide> default:
<ide> throw new IllegalArgumentException("Could not convert object with key: " + key + ".");
<del> }
<ide> }
<add> }
<ide> return hashMap;
<ide> }
<ide>
<ide> public boolean equals(Object obj) {
<ide> return hashMap;
<ide> }
<ide>
<del> /**
<del> * Implementation of a {@link ReadableNativeMap} iterator in native memory.
<del> */
<add> /** Implementation of a {@link ReadableNativeMap} iterator in native memory. */
<ide> @DoNotStrip
<ide> private static class ReadableNativeMapKeySetIterator implements ReadableMapKeySetIterator {
<del> @DoNotStrip
<del> private final HybridData mHybridData;
<add> @DoNotStrip private final HybridData mHybridData;
<ide>
<ide> // Need to hold a strong ref to the map so that our native references remain valid.
<del> @DoNotStrip
<del> private final ReadableNativeMap mMap;
<add> @DoNotStrip private final ReadableNativeMap mMap;
<ide>
<ide> public ReadableNativeMapKeySetIterator(ReadableNativeMap readableNativeMap) {
<ide> mMap = readableNativeMap;
<ide> public ReadableNativeMapKeySetIterator(ReadableNativeMap readableNativeMap) {
<ide>
<ide> @Override
<ide> public native boolean hasNextKey();
<add>
<ide> @Override
<ide> public native String nextKey();
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/processing/ReactPropertyProcessor.java
<ide>
<ide> import com.facebook.infer.annotation.SuppressFieldNotInitialized;
<ide> import com.facebook.react.bridge.Dynamic;
<add>import com.facebook.react.bridge.DynamicFromObject;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.uimanager.annotations.ReactProp;
<ide>
<ide> /**
<ide> * This annotation processor crawls subclasses of ReactShadowNode and ViewManager and finds their
<del> * exported properties with the @ReactProp or @ReactGroupProp annotation. It generates a class
<del> * per shadow node/view manager that is named {@code <classname>$$PropSetter}. This class contains methods
<del> * to retrieve the name and type of all methods and a way to set these properties without
<add> * exported properties with the @ReactProp or @ReactGroupProp annotation. It generates a class per
<add> * shadow node/view manager that is named {@code <classname>$$PropSetter}. This class contains
<add> * methods to retrieve the name and type of all methods and a way to set these properties without
<ide> * reflection.
<ide> */
<ide> @SupportedAnnotationTypes("com.facebook.react.uimanager.annotations.ReactPropertyHolder")
<ide> public class ReactPropertyProcessor extends AbstractProcessor {
<ide>
<ide> private static final TypeName PROPS_TYPE =
<ide> ClassName.get("com.facebook.react.uimanager", "ReactStylesDiffMap");
<add> private static final TypeName OBJECT_TYPE = TypeName.get(Object.class);
<ide> private static final TypeName STRING_TYPE = TypeName.get(String.class);
<ide> private static final TypeName READABLE_MAP_TYPE = TypeName.get(ReadableMap.class);
<ide> private static final TypeName READABLE_ARRAY_TYPE = TypeName.get(ReadableArray.class);
<ide> private static final TypeName DYNAMIC_TYPE = TypeName.get(Dynamic.class);
<add> private static final TypeName DYNAMIC_FROM_OBJECT_TYPE = TypeName.get(DynamicFromObject.class);
<ide>
<ide> private static final TypeName VIEW_MANAGER_TYPE =
<ide> ClassName.get("com.facebook.react.uimanager", "ViewManager");
<ide> public class ReactPropertyProcessor extends AbstractProcessor {
<ide>
<ide> private static final ClassName VIEW_MANAGER_SETTER_TYPE =
<ide> ClassName.get(
<del> "com.facebook.react.uimanager",
<del> "ViewManagerPropertyUpdater",
<del> "ViewManagerSetter");
<add> "com.facebook.react.uimanager", "ViewManagerPropertyUpdater", "ViewManagerSetter");
<ide> private static final ClassName SHADOW_NODE_SETTER_TYPE =
<ide> ClassName.get(
<del> "com.facebook.react.uimanager",
<del> "ViewManagerPropertyUpdater",
<del> "ShadowNodeSetter");
<add> "com.facebook.react.uimanager", "ViewManagerPropertyUpdater", "ShadowNodeSetter");
<ide>
<ide> private static final TypeName PROPERTY_MAP_TYPE =
<ide> ParameterizedTypeName.get(Map.class, String.class, String.class);
<ide> public class ReactPropertyProcessor extends AbstractProcessor {
<ide>
<ide> private final Map<ClassName, ClassInfo> mClasses;
<ide>
<del> @SuppressFieldNotInitialized
<del> private Filer mFiler;
<del> @SuppressFieldNotInitialized
<del> private Messager mMessager;
<del> @SuppressFieldNotInitialized
<del> private Elements mElements;
<del> @SuppressFieldNotInitialized
<del> private Types mTypes;
<add> @SuppressFieldNotInitialized private Filer mFiler;
<add> @SuppressFieldNotInitialized private Messager mMessager;
<add> @SuppressFieldNotInitialized private Elements mElements;
<add> @SuppressFieldNotInitialized private Types mTypes;
<ide>
<ide> static {
<ide> DEFAULT_TYPES = new HashMap<>();
<ide> public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment
<ide> if (!shouldIgnoreClass(classInfo)) {
<ide> // Sort by name
<ide> Collections.sort(
<del> classInfo.mProperties, new Comparator<PropertyInfo>() {
<add> classInfo.mProperties,
<add> new Comparator<PropertyInfo>() {
<ide> @Override
<ide> public int compare(PropertyInfo a, PropertyInfo b) {
<ide> return a.mProperty.name().compareTo(b.mProperty.name());
<ide> private void findProperties(ClassInfo classInfo, TypeElement typeElement) {
<ide> classInfo.addProperty(propertyBuilder.build(element, new RegularProperty(prop)));
<ide> } else if (propGroup != null) {
<ide> for (int i = 0, size = propGroup.names().length; i < size; i++) {
<del> classInfo
<del> .addProperty(propertyBuilder.build(element, new GroupProperty(propGroup, i)));
<add> classInfo.addProperty(
<add> propertyBuilder.build(element, new GroupProperty(propGroup, i)));
<ide> }
<ide> }
<ide> } catch (ReactPropertyException e) {
<ide> private TypeName getTargetType(TypeMirror mirror) {
<ide>
<ide> private void generateCode(ClassInfo classInfo, List<PropertyInfo> properties)
<ide> throws IOException, ReactPropertyException {
<del> MethodSpec getMethods = MethodSpec.methodBuilder("getProperties")
<del> .addModifiers(PUBLIC)
<del> .addAnnotation(Override.class)
<del> .addParameter(PROPERTY_MAP_TYPE, "props")
<del> .returns(TypeName.VOID)
<del> .addCode(generateGetProperties(properties))
<del> .build();
<add> MethodSpec getMethods =
<add> MethodSpec.methodBuilder("getProperties")
<add> .addModifiers(PUBLIC)
<add> .addAnnotation(Override.class)
<add> .addParameter(PROPERTY_MAP_TYPE, "props")
<add> .returns(TypeName.VOID)
<add> .addCode(generateGetProperties(properties))
<add> .build();
<ide>
<ide> TypeName superType = getSuperType(classInfo);
<ide> ClassName className = classInfo.mClassName;
<ide>
<ide> String holderClassName =
<ide> getClassName((TypeElement) classInfo.mElement, className.packageName()) + "$$PropsSetter";
<del> TypeSpec holderClass = TypeSpec.classBuilder(holderClassName)
<del> .addSuperinterface(superType)
<del> .addModifiers(PUBLIC)
<del> .addMethod(generateSetPropertySpec(classInfo, properties))
<del> .addMethod(getMethods)
<del> .build();
<del>
<del> JavaFile javaFile = JavaFile.builder(className.packageName(), holderClass)
<del> .addFileComment("Generated by " + getClass().getName())
<del> .build();
<add> TypeSpec holderClass =
<add> TypeSpec.classBuilder(holderClassName)
<add> .addSuperinterface(superType)
<add> .addModifiers(PUBLIC)
<add> .addMethod(generateSetPropertySpec(classInfo, properties))
<add> .addMethod(getMethods)
<add> .build();
<add>
<add> JavaFile javaFile =
<add> JavaFile.builder(className.packageName(), holderClass)
<add> .addFileComment("Generated by " + getClass().getName())
<add> .build();
<ide>
<ide> javaFile.writeTo(mFiler);
<ide> }
<ide> private static TypeName getSuperType(ClassInfo classInfo) {
<ide> switch (classInfo.getType()) {
<ide> case VIEW_MANAGER:
<ide> return ParameterizedTypeName.get(
<del> VIEW_MANAGER_SETTER_TYPE,
<del> classInfo.mClassName,
<del> classInfo.mViewType);
<add> VIEW_MANAGER_SETTER_TYPE, classInfo.mClassName, classInfo.mViewType);
<ide> case SHADOW_NODE:
<ide> return ParameterizedTypeName.get(SHADOW_NODE_SETTER_TYPE, classInfo.mClassName);
<ide> default:
<ide> private static TypeName getSuperType(ClassInfo classInfo) {
<ide> }
<ide>
<ide> private static MethodSpec generateSetPropertySpec(
<del> ClassInfo classInfo,
<del> List<PropertyInfo> properties) {
<del> MethodSpec.Builder builder = MethodSpec.methodBuilder("setProperty")
<del> .addModifiers(PUBLIC)
<del> .addAnnotation(Override.class)
<del> .returns(TypeName.VOID);
<add> ClassInfo classInfo, List<PropertyInfo> properties) {
<add> MethodSpec.Builder builder =
<add> MethodSpec.methodBuilder("setProperty")
<add> .addModifiers(PUBLIC)
<add> .addAnnotation(Override.class)
<add> .returns(TypeName.VOID);
<ide>
<ide> switch (classInfo.getType()) {
<ide> case VIEW_MANAGER:
<ide> private static MethodSpec generateSetPropertySpec(
<ide> .addParameter(classInfo.mViewType, "view");
<ide> break;
<ide> case SHADOW_NODE:
<del> builder
<del> .addParameter(classInfo.mClassName, "node");
<add> builder.addParameter(classInfo.mClassName, "node");
<ide> break;
<ide> }
<ide>
<ide> return builder
<ide> .addParameter(STRING_TYPE, "name")
<del> .addParameter(PROPS_TYPE, "props")
<add> .addParameter(OBJECT_TYPE, "value")
<ide> .addCode(generateSetProperty(classInfo, properties))
<ide> .build();
<ide> }
<ide> private static CodeBlock generateSetProperty(ClassInfo info, List<PropertyInfo>
<ide> builder.add("switch (name) {\n").indent();
<ide> for (int i = 0, size = properties.size(); i < size; i++) {
<ide> PropertyInfo propertyInfo = properties.get(i);
<del> builder
<del> .add("case \"$L\":\n", propertyInfo.mProperty.name())
<del> .indent();
<add> builder.add("case \"$L\":\n", propertyInfo.mProperty.name()).indent();
<ide>
<ide> switch (info.getType()) {
<ide> case VIEW_MANAGER:
<ide> private static CodeBlock generateSetProperty(ClassInfo info, List<PropertyInfo>
<ide> builder.add("$L, ", ((GroupProperty) propertyInfo.mProperty).mGroupIndex);
<ide> }
<ide> if (BOXED_PRIMITIVES.contains(propertyInfo.propertyType)) {
<del> builder.add("props.isNull(name) ? null : ");
<add> builder.add("value == null ? null : ");
<ide> }
<ide> getPropertyExtractor(propertyInfo, builder);
<ide> builder.addStatement(")");
<ide>
<del> builder
<del> .addStatement("break")
<del> .unindent();
<add> builder.addStatement("break").unindent();
<ide> }
<ide> builder.unindent().add("}\n");
<ide>
<ide> return builder.build();
<ide> }
<ide>
<ide> private static CodeBlock.Builder getPropertyExtractor(
<del> PropertyInfo info,
<del> CodeBlock.Builder builder) {
<add> PropertyInfo info, CodeBlock.Builder builder) {
<ide> TypeName propertyType = info.propertyType;
<ide> if (propertyType.equals(STRING_TYPE)) {
<del> return builder.add("props.getString(name)");
<add> return builder.add("($L)value", STRING_TYPE);
<ide> } else if (propertyType.equals(READABLE_ARRAY_TYPE)) {
<del> return builder.add("props.getArray(name)");
<add> return builder.add("($L)value", READABLE_ARRAY_TYPE); // TODO: use real type but needs import
<ide> } else if (propertyType.equals(READABLE_MAP_TYPE)) {
<del> return builder.add("props.getMap(name)");
<add> return builder.add("($L)value", READABLE_MAP_TYPE);
<ide> } else if (propertyType.equals(DYNAMIC_TYPE)) {
<del> return builder.add("props.getDynamic(name)");
<add> return builder.add("new $L(value)", DYNAMIC_FROM_OBJECT_TYPE);
<ide> }
<ide>
<ide> if (BOXED_PRIMITIVES.contains(propertyType)) {
<ide> propertyType = propertyType.unbox();
<ide> }
<ide>
<ide> if (propertyType.equals(TypeName.BOOLEAN)) {
<del> return builder.add("props.getBoolean(name, $L)", info.mProperty.defaultBoolean());
<del> } if (propertyType.equals(TypeName.DOUBLE)) {
<add> return builder.add("value == null ? $L : (boolean) value", info.mProperty.defaultBoolean());
<add> }
<add> if (propertyType.equals(TypeName.DOUBLE)) {
<ide> double defaultDouble = info.mProperty.defaultDouble();
<ide> if (Double.isNaN(defaultDouble)) {
<del> return builder.add("props.getDouble(name, $T.NaN)", Double.class);
<add> return builder.add("value == null ? $T.NaN : (double) value", Double.class);
<ide> } else {
<del> return builder.add("props.getDouble(name, $Lf)", defaultDouble);
<add> return builder.add("value == null ? $Lf : (double) value", defaultDouble);
<ide> }
<ide> }
<ide> if (propertyType.equals(TypeName.FLOAT)) {
<ide> float defaultFloat = info.mProperty.defaultFloat();
<ide> if (Float.isNaN(defaultFloat)) {
<del> return builder.add("props.getFloat(name, $T.NaN)", Float.class);
<add> return builder.add("value == null ? $T.NaN : ((Double)value).floatValue()", Float.class);
<ide> } else {
<del> return builder.add("props.getFloat(name, $Lf)", defaultFloat);
<add> return builder.add("value == null ? $Lf : ((Double)value).floatValue()", defaultFloat);
<ide> }
<ide> }
<ide> if (propertyType.equals(TypeName.INT)) {
<del> return builder.add("props.getInt(name, $L)", info.mProperty.defaultInt());
<add> return builder.add(
<add> "value == null ? $L : ((Double)value).intValue()", info.mProperty.defaultInt());
<ide> }
<ide>
<ide> throw new IllegalArgumentException();
<ide> private static CodeBlock generateGetProperties(List<PropertyInfo> properties)
<ide>
<ide> private static String getPropertypTypeName(Property property, TypeName propertyType) {
<ide> String defaultType = DEFAULT_TYPES.get(propertyType);
<del> String useDefaultType = property instanceof RegularProperty ?
<del> ReactProp.USE_DEFAULT_TYPE : ReactPropGroup.USE_DEFAULT_TYPE;
<add> String useDefaultType =
<add> property instanceof RegularProperty
<add> ? ReactProp.USE_DEFAULT_TYPE
<add> : ReactPropGroup.USE_DEFAULT_TYPE;
<ide> return useDefaultType.equals(property.customType()) ? defaultType : property.customType();
<ide> }
<ide>
<ide> private static void checkElement(Element element) throws ReactPropertyException {
<del> if (element.getKind() == ElementKind.METHOD
<del> && element.getModifiers().contains(PUBLIC)) {
<add> if (element.getKind() == ElementKind.METHOD && element.getModifiers().contains(PUBLIC)) {
<ide> return;
<ide> }
<ide>
<ide> throw new ReactPropertyException(
<del> "@ReactProp and @ReachPropGroup annotation must be on a public method",
<del> element);
<add> "@ReactProp and @ReachPropGroup annotation must be on a public method", element);
<ide> }
<ide>
<ide> private static boolean shouldIgnoreClass(ClassInfo classInfo) {
<ide> private void warning(Element element, String message) {
<ide>
<ide> private interface Property {
<ide> String name();
<add>
<ide> String customType();
<add>
<ide> double defaultDouble();
<add>
<ide> float defaultFloat();
<add>
<ide> int defaultInt();
<add>
<ide> boolean defaultBoolean();
<ide> }
<ide>
<ide> public void addProperty(PropertyInfo propertyInfo) throws ReactPropertyException
<ide> String name = propertyInfo.mProperty.name();
<ide> if (checkPropertyExists(name)) {
<ide> throw new ReactPropertyException(
<del> "Module " + mClassName + " has already registered a property named \"" +
<del> name + "\". If you want to override a property, don't add" +
<del> "the @ReactProp annotation to the property in the subclass", propertyInfo);
<add> "Module "
<add> + mClassName
<add> + " has already registered a property named \""
<add> + name
<add> + "\". If you want to override a property, don't add"
<add> + "the @ReactProp annotation to the property in the subclass",
<add> propertyInfo);
<ide> }
<ide>
<ide> mProperties.add(propertyInfo);
<ide> private static class PropertyInfo {
<ide> public final Property mProperty;
<ide>
<ide> private PropertyInfo(
<del> String methodName,
<del> TypeName propertyType,
<del> Element element,
<del> Property property) {
<add> String methodName, TypeName propertyType, Element element, Property property) {
<ide> this.methodName = methodName;
<ide> this.propertyType = propertyType;
<ide> this.element = element;
<ide> public Builder(Types types, Elements elements, ClassInfo classInfo) {
<ide> mClassInfo = classInfo;
<ide> }
<ide>
<del> public PropertyInfo build(Element element, Property property)
<del> throws ReactPropertyException {
<add> public PropertyInfo build(Element element, Property property) throws ReactPropertyException {
<ide> String methodName = element.getSimpleName().toString();
<ide>
<ide> ExecutableElement method = (ExecutableElement) element;
<ide> public PropertyInfo build(Element element, Property property)
<ide> TypeName indexType = TypeName.get(parameters.get(index++).asType());
<ide> if (!indexType.equals(TypeName.INT)) {
<ide> throw new ReactPropertyException(
<del> "Argument " + index + " must be an int for @ReactPropGroup",
<del> element);
<add> "Argument " + index + " must be an int for @ReactPropGroup", element);
<ide> }
<ide> }
<ide>
<ide> TypeName propertyType = TypeName.get(parameters.get(index++).asType());
<ide> if (!DEFAULT_TYPES.containsKey(propertyType)) {
<ide> throw new ReactPropertyException(
<del> "Argument " + index + " must be of a supported type",
<del> element);
<add> "Argument " + index + " must be of a supported type", element);
<ide> }
<ide>
<ide> return new PropertyInfo(methodName, propertyType, element, property);
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagerPropertyUpdater.java
<ide> package com.facebook.react.uimanager;
<ide>
<ide> import java.util.HashMap;
<add>import java.util.Iterator;
<ide> import java.util.Map;
<ide>
<ide> import android.view.View;
<ide>
<ide> import com.facebook.common.logging.FLog;
<add>import com.facebook.react.bridge.Dynamic;
<add>import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> import com.facebook.react.bridge.ReadableMapKeySetIterator;
<ide>
<ide> public class ViewManagerPropertyUpdater {
<ide> public interface Settable {
<del> void getProperties(Map<String, String> props);
<add> void getProperties(Map<String, String> props);
<ide> }
<ide>
<ide> public interface ViewManagerSetter<T extends ViewManager, V extends View> extends Settable {
<del> void setProperty(T manager, V view, String name, ReactStylesDiffMap props);
<add> void setProperty(T manager, V view, String name, Object value);
<ide> }
<ide>
<ide> public interface ShadowNodeSetter<T extends ReactShadowNode> extends Settable {
<del> void setProperty(T node, String name, ReactStylesDiffMap props);
<add> void setProperty(T node, String name, Object value);
<ide> }
<ide>
<ide> private static final String TAG = "ViewManagerPropertyUpdater";
<ide> public static void clear() {
<ide> }
<ide>
<ide> public static <T extends ViewManager, V extends View> void updateProps(
<del> T manager,
<del> V v,
<del> ReactStylesDiffMap props) {
<add> T manager, V v, ReactStylesDiffMap props) {
<ide> ViewManagerSetter<T, V> setter = findManagerSetter(manager.getClass());
<del> ReadableMap propMap = props.mBackingMap;
<del> ReadableMapKeySetIterator iterator = propMap.keySetIterator();
<del> while (iterator.hasNextKey()) {
<del> String key = iterator.nextKey();
<del> setter.setProperty(manager, v, key, props);
<add> Iterator<Map.Entry<String, Object>> iterator = props.mBackingMap.getEntryIterator();
<add> while (iterator.hasNext()) {
<add> Map.Entry<String, Object> entry = iterator.next();
<add> setter.setProperty(manager, v, entry.getKey(), entry.getValue());
<ide> }
<ide> }
<ide>
<ide> public static <T extends ReactShadowNode> void updateProps(T node, ReactStylesDiffMap props) {
<ide> ShadowNodeSetter<T> setter = findNodeSetter(node.getClass());
<del> ReadableMap propMap = props.mBackingMap;
<del> ReadableMapKeySetIterator iterator = propMap.keySetIterator();
<del> while (iterator.hasNextKey()) {
<del> String key = iterator.nextKey();
<del> setter.setProperty(node, key, props);
<add> Iterator<Map.Entry<String, Object>> iterator = props.mBackingMap.getEntryIterator();
<add> while (iterator.hasNext()) {
<add> Map.Entry<String, Object> entry = iterator.next();
<add> setter.setProperty(node, entry.getKey(), entry.getValue());
<ide> }
<ide> }
<ide>
<ide> private FallbackViewManagerSetter(Class<? extends ViewManager> viewManagerClass)
<ide> }
<ide>
<ide> @Override
<del> public void setProperty(T manager, V v, String name, ReactStylesDiffMap props) {
<add> public void setProperty(T manager, V v, String name, Object value) {
<ide> ViewManagersPropertyCache.PropSetter setter = mPropSetters.get(name);
<ide> if (setter != null) {
<del> setter.updateViewProp(manager, v, props);
<add> setter.updateViewProp(manager, v, value);
<ide> }
<ide> }
<ide>
<ide> private FallbackShadowNodeSetter(Class<? extends ReactShadowNode> shadowNodeClas
<ide> }
<ide>
<ide> @Override
<del> public void setProperty(ReactShadowNode node, String name, ReactStylesDiffMap props) {
<add> public void setProperty(ReactShadowNode node, String name, Object value) {
<ide> ViewManagersPropertyCache.PropSetter setter = mPropSetters.get(name);
<ide> if (setter != null) {
<del> setter.updateShadowNodeProp(node, props);
<add> setter.updateShadowNodeProp(node, value);
<ide> }
<ide> }
<ide>
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/ViewManagersPropertyCache.java
<ide> import android.view.View;
<ide> import com.facebook.common.logging.FLog;
<ide> import com.facebook.react.bridge.Dynamic;
<add>import com.facebook.react.bridge.DynamicFromObject;
<ide> import com.facebook.react.bridge.JSApplicationIllegalArgumentException;
<ide> import com.facebook.react.bridge.ReadableArray;
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> public static void clear() {
<ide> EMPTY_PROPS_MAP.clear();
<ide> }
<ide>
<del> /*package*/ static abstract class PropSetter {
<add> /*package*/ abstract static class PropSetter {
<ide>
<ide> protected final String mPropName;
<ide> protected final String mPropType;
<ide> public static void clear() {
<ide>
<ide> private PropSetter(ReactProp prop, String defaultType, Method setter) {
<ide> mPropName = prop.name();
<del> mPropType = ReactProp.USE_DEFAULT_TYPE.equals(prop.customType()) ?
<del> defaultType : prop.customType();
<add> mPropType =
<add> ReactProp.USE_DEFAULT_TYPE.equals(prop.customType()) ? defaultType : prop.customType();
<ide> mSetter = setter;
<ide> mIndex = null;
<ide> }
<ide>
<ide> private PropSetter(ReactPropGroup prop, String defaultType, Method setter, int index) {
<ide> mPropName = prop.names()[index];
<del> mPropType = ReactPropGroup.USE_DEFAULT_TYPE.equals(prop.customType()) ?
<del> defaultType : prop.customType();
<add> mPropType =
<add> ReactPropGroup.USE_DEFAULT_TYPE.equals(prop.customType())
<add> ? defaultType
<add> : prop.customType();
<ide> mSetter = setter;
<ide> mIndex = index;
<ide> }
<ide> public String getPropType() {
<ide> return mPropType;
<ide> }
<ide>
<del> public void updateViewProp(
<del> ViewManager viewManager,
<del> View viewToUpdate,
<del> ReactStylesDiffMap props) {
<add> public void updateViewProp(ViewManager viewManager, View viewToUpdate, Object value) {
<ide> try {
<ide> if (mIndex == null) {
<ide> VIEW_MGR_ARGS[0] = viewToUpdate;
<del> VIEW_MGR_ARGS[1] = extractProperty(props);
<add> VIEW_MGR_ARGS[1] = getValueOrDefault(value);
<ide> mSetter.invoke(viewManager, VIEW_MGR_ARGS);
<ide> Arrays.fill(VIEW_MGR_ARGS, null);
<ide> } else {
<ide> VIEW_MGR_GROUP_ARGS[0] = viewToUpdate;
<ide> VIEW_MGR_GROUP_ARGS[1] = mIndex;
<del> VIEW_MGR_GROUP_ARGS[2] = extractProperty(props);
<add> VIEW_MGR_GROUP_ARGS[2] = getValueOrDefault(value);
<ide> mSetter.invoke(viewManager, VIEW_MGR_GROUP_ARGS);
<ide> Arrays.fill(VIEW_MGR_GROUP_ARGS, null);
<ide> }
<ide> } catch (Throwable t) {
<ide> FLog.e(ViewManager.class, "Error while updating prop " + mPropName, t);
<del> throw new JSApplicationIllegalArgumentException("Error while updating property '" +
<del> mPropName + "' of a view managed by: " + viewManager.getName(), t);
<add> throw new JSApplicationIllegalArgumentException(
<add> "Error while updating property '"
<add> + mPropName
<add> + "' of a view managed by: "
<add> + viewManager.getName(),
<add> t);
<ide> }
<ide> }
<ide>
<del> public void updateShadowNodeProp(
<del> ReactShadowNode nodeToUpdate,
<del> ReactStylesDiffMap props) {
<add> public void updateShadowNodeProp(ReactShadowNode nodeToUpdate, Object value) {
<ide> try {
<ide> if (mIndex == null) {
<del> SHADOW_ARGS[0] = extractProperty(props);
<add> SHADOW_ARGS[0] = getValueOrDefault(value);
<ide> mSetter.invoke(nodeToUpdate, SHADOW_ARGS);
<ide> Arrays.fill(SHADOW_ARGS, null);
<ide> } else {
<ide> SHADOW_GROUP_ARGS[0] = mIndex;
<del> SHADOW_GROUP_ARGS[1] = extractProperty(props);
<add> SHADOW_GROUP_ARGS[1] = getValueOrDefault(value);
<ide> mSetter.invoke(nodeToUpdate, SHADOW_GROUP_ARGS);
<ide> Arrays.fill(SHADOW_GROUP_ARGS, null);
<ide> }
<ide> } catch (Throwable t) {
<ide> FLog.e(ViewManager.class, "Error while updating prop " + mPropName, t);
<del> throw new JSApplicationIllegalArgumentException("Error while updating property '" +
<del> mPropName + "' in shadow node of type: " + nodeToUpdate.getViewClass(), t);
<add> throw new JSApplicationIllegalArgumentException(
<add> "Error while updating property '"
<add> + mPropName
<add> + "' in shadow node of type: "
<add> + nodeToUpdate.getViewClass(),
<add> t);
<ide> }
<ide> }
<ide>
<del> protected abstract @Nullable Object extractProperty(ReactStylesDiffMap props);
<add> protected abstract @Nullable Object getValueOrDefault(Object value);
<ide> }
<ide>
<ide> private static class DynamicPropSetter extends PropSetter {
<ide> public DynamicPropSetter(ReactPropGroup prop, Method setter, int index) {
<ide> }
<ide>
<ide> @Override
<del> protected Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getDynamic(mPropName);
<add> protected Object getValueOrDefault(Object value) {
<add> if (value instanceof Dynamic) {
<add> return value;
<add> } else {
<add> return new DynamicFromObject(value);
<add> }
<ide> }
<ide> }
<ide>
<ide> public IntPropSetter(ReactPropGroup prop, Method setter, int index, int defaultV
<ide> }
<ide>
<ide> @Override
<del> protected Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getInt(mPropName, mDefaultValue);
<add> protected Object getValueOrDefault(Object value) {
<add> // All numbers from JS are Doubles which can't be simply cast to Integer
<add> return value == null ? mDefaultValue : (Integer) ((Double)value).intValue();
<ide> }
<ide> }
<ide>
<ide> public DoublePropSetter(ReactPropGroup prop, Method setter, int index, double de
<ide> }
<ide>
<ide> @Override
<del> protected Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getDouble(mPropName, mDefaultValue);
<add> protected Object getValueOrDefault(Object value) {
<add> return value == null ? mDefaultValue : (Double) value;
<ide> }
<ide> }
<ide>
<ide> public BooleanPropSetter(ReactProp prop, Method setter, boolean defaultValue) {
<ide> }
<ide>
<ide> @Override
<del> protected Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getBoolean(mPropName, mDefaultValue) ? Boolean.TRUE : Boolean.FALSE;
<add> protected Object getValueOrDefault(Object value) {
<add> boolean val = value == null ? mDefaultValue : (boolean) value;
<add> return val ? Boolean.TRUE : Boolean.FALSE;
<ide> }
<ide> }
<ide>
<ide> public FloatPropSetter(ReactPropGroup prop, Method setter, int index, float defa
<ide> }
<ide>
<ide> @Override
<del> protected Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getFloat(mPropName, mDefaultValue);
<add> protected Object getValueOrDefault(Object value) {
<add> // All numbers from JS are Doubles which can't be simply cast to Float
<add> return value == null ? mDefaultValue : (Float) ((Double)value).floatValue();
<ide> }
<ide> }
<ide>
<ide> public ArrayPropSetter(ReactProp prop, Method setter) {
<ide> }
<ide>
<ide> @Override
<del> protected @Nullable Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getArray(mPropName);
<add> protected @Nullable Object getValueOrDefault(Object value) {
<add> return (ReadableArray) value;
<ide> }
<ide> }
<ide>
<ide> public MapPropSetter(ReactProp prop, Method setter) {
<ide> }
<ide>
<ide> @Override
<del> protected @Nullable Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getMap(mPropName);
<add> protected @Nullable Object getValueOrDefault(Object value) {
<add> return (ReadableMap) value;
<ide> }
<ide> }
<ide>
<ide> public StringPropSetter(ReactProp prop, Method setter) {
<ide> }
<ide>
<ide> @Override
<del> protected @Nullable Object extractProperty(ReactStylesDiffMap props) {
<del> return props.getString(mPropName);
<add> protected @Nullable Object getValueOrDefault(Object value) {
<add> return (String) value;
<ide> }
<ide> }
<ide>
<ide> public BoxedBooleanPropSetter(ReactProp prop, Method setter) {
<ide> }
<ide>
<ide> @Override
<del> protected @Nullable Object extractProperty(ReactStylesDiffMap props) {
<del> if (!props.isNull(mPropName)) {
<del> return props.getBoolean(mPropName, /* ignored */ false) ? Boolean.TRUE : Boolean.FALSE;
<add> protected @Nullable Object getValueOrDefault(Object value) {
<add> if (value != null) {
<add> return (boolean) value ? Boolean.TRUE : Boolean.FALSE;
<ide> }
<ide> return null;
<ide> }
<ide> public BoxedIntPropSetter(ReactPropGroup prop, Method setter, int index) {
<ide> }
<ide>
<ide> @Override
<del> protected @Nullable Object extractProperty(ReactStylesDiffMap props) {
<del> if (!props.isNull(mPropName)) {
<del> return props.getInt(mPropName, /* ignored */ 0);
<add> protected @Nullable Object getValueOrDefault(Object value) {
<add> if (value != null) {
<add> return (Integer) value;
<ide> }
<ide> return null;
<ide> }
<ide> public BoxedIntPropSetter(ReactPropGroup prop, Method setter, int index) {
<ide> }
<ide> // This is to include all the setters from parent classes. Once calculated the result will be
<ide> // stored in CLASS_PROPS_CACHE so that we only scan for @ReactProp annotations once per class.
<del> props = new HashMap<>(
<del> getNativePropSettersForViewManagerClass(
<del> (Class<? extends ViewManager>) cls.getSuperclass()));
<add> props =
<add> new HashMap<>(
<add> getNativePropSettersForViewManagerClass(
<add> (Class<? extends ViewManager>) cls.getSuperclass()));
<ide> extractPropSettersFromViewManagerClassDefinition(cls, props);
<ide> CLASS_PROPS_CACHE.put(cls, props);
<ide> return props;
<ide> public BoxedIntPropSetter(ReactPropGroup prop, Method setter, int index) {
<ide> return props;
<ide> }
<ide> // This is to include all the setters from parent classes up to ReactShadowNode class
<del> props = new HashMap<>(
<del> getNativePropSettersForShadowNodeClass(
<del> (Class<? extends ReactShadowNode>) cls.getSuperclass()));
<add> props =
<add> new HashMap<>(
<add> getNativePropSettersForShadowNodeClass(
<add> (Class<? extends ReactShadowNode>) cls.getSuperclass()));
<ide> extractPropSettersFromShadowNodeClassDefinition(cls, props);
<ide> CLASS_PROPS_CACHE.put(cls, props);
<ide> return props;
<ide> }
<ide>
<ide> private static PropSetter createPropSetter(
<del> ReactProp annotation,
<del> Method method,
<del> Class<?> propTypeClass) {
<add> ReactProp annotation, Method method, Class<?> propTypeClass) {
<ide> if (propTypeClass == Dynamic.class) {
<ide> return new DynamicPropSetter(annotation, method);
<ide> } else if (propTypeClass == boolean.class) {
<ide> private static PropSetter createPropSetter(
<ide> } else if (propTypeClass == ReadableMap.class) {
<ide> return new MapPropSetter(annotation, method);
<ide> } else {
<del> throw new RuntimeException("Unrecognized type: " + propTypeClass + " for method: " +
<del> method.getDeclaringClass().getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Unrecognized type: "
<add> + propTypeClass
<add> + " for method: "
<add> + method.getDeclaringClass().getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> }
<ide>
<ide> private static void createPropSetters(
<ide> String[] names = annotation.names();
<ide> if (propTypeClass == Dynamic.class) {
<ide> for (int i = 0; i < names.length; i++) {
<del> props.put(
<del> names[i],
<del> new DynamicPropSetter(annotation, method, i));
<add> props.put(names[i], new DynamicPropSetter(annotation, method, i));
<ide> }
<ide> } else if (propTypeClass == int.class) {
<ide> for (int i = 0; i < names.length; i++) {
<del> props.put(
<del> names[i],
<del> new IntPropSetter(annotation, method, i, annotation.defaultInt()));
<add> props.put(names[i], new IntPropSetter(annotation, method, i, annotation.defaultInt()));
<ide> }
<ide> } else if (propTypeClass == float.class) {
<ide> for (int i = 0; i < names.length; i++) {
<del> props.put(
<del> names[i],
<del> new FloatPropSetter(annotation, method, i, annotation.defaultFloat()));
<add> props.put(names[i], new FloatPropSetter(annotation, method, i, annotation.defaultFloat()));
<ide> }
<ide> } else if (propTypeClass == double.class) {
<ide> for (int i = 0; i < names.length; i++) {
<ide> props.put(
<del> names[i],
<del> new DoublePropSetter(annotation, method, i, annotation.defaultDouble()));
<add> names[i], new DoublePropSetter(annotation, method, i, annotation.defaultDouble()));
<ide> }
<ide> } else if (propTypeClass == Integer.class) {
<ide> for (int i = 0; i < names.length; i++) {
<del> props.put(
<del> names[i],
<del> new BoxedIntPropSetter(annotation, method, i));
<add> props.put(names[i], new BoxedIntPropSetter(annotation, method, i));
<ide> }
<ide> } else {
<del> throw new RuntimeException("Unrecognized type: " + propTypeClass + " for method: " +
<del> method.getDeclaringClass().getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Unrecognized type: "
<add> + propTypeClass
<add> + " for method: "
<add> + method.getDeclaringClass().getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> }
<ide>
<ide> private static void extractPropSettersFromViewManagerClassDefinition(
<del> Class<? extends ViewManager> cls,
<del> Map<String, PropSetter> props) {
<add> Class<? extends ViewManager> cls, Map<String, PropSetter> props) {
<ide> Method[] declaredMethods = cls.getDeclaredMethods();
<ide> for (int i = 0; i < declaredMethods.length; i++) {
<ide> Method method = declaredMethods[i];
<ide> ReactProp annotation = method.getAnnotation(ReactProp.class);
<ide> if (annotation != null) {
<ide> Class<?>[] paramTypes = method.getParameterTypes();
<ide> if (paramTypes.length != 2) {
<del> throw new RuntimeException("Wrong number of args for prop setter: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Wrong number of args for prop setter: " + cls.getName() + "#" + method.getName());
<ide> }
<ide> if (!View.class.isAssignableFrom(paramTypes[0])) {
<del> throw new RuntimeException("First param should be a view subclass to be updated: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "First param should be a view subclass to be updated: "
<add> + cls.getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> props.put(annotation.name(), createPropSetter(annotation, method, paramTypes[1]));
<ide> }
<ide>
<ide> ReactPropGroup groupAnnotation = method.getAnnotation(ReactPropGroup.class);
<ide> if (groupAnnotation != null) {
<del> Class<?> [] paramTypes = method.getParameterTypes();
<add> Class<?>[] paramTypes = method.getParameterTypes();
<ide> if (paramTypes.length != 3) {
<del> throw new RuntimeException("Wrong number of args for group prop setter: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Wrong number of args for group prop setter: "
<add> + cls.getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> if (!View.class.isAssignableFrom(paramTypes[0])) {
<del> throw new RuntimeException("First param should be a view subclass to be updated: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "First param should be a view subclass to be updated: "
<add> + cls.getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> if (paramTypes[1] != int.class) {
<del> throw new RuntimeException("Second argument should be property index: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Second argument should be property index: "
<add> + cls.getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> createPropSetters(groupAnnotation, method, paramTypes[2], props);
<ide> }
<ide> }
<ide> }
<ide>
<ide> private static void extractPropSettersFromShadowNodeClassDefinition(
<del> Class<? extends ReactShadowNode> cls,
<del> Map<String, PropSetter> props) {
<add> Class<? extends ReactShadowNode> cls, Map<String, PropSetter> props) {
<ide> for (Method method : cls.getDeclaredMethods()) {
<ide> ReactProp annotation = method.getAnnotation(ReactProp.class);
<ide> if (annotation != null) {
<ide> Class<?>[] paramTypes = method.getParameterTypes();
<ide> if (paramTypes.length != 1) {
<del> throw new RuntimeException("Wrong number of args for prop setter: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Wrong number of args for prop setter: " + cls.getName() + "#" + method.getName());
<ide> }
<ide> props.put(annotation.name(), createPropSetter(annotation, method, paramTypes[0]));
<ide> }
<ide>
<ide> ReactPropGroup groupAnnotation = method.getAnnotation(ReactPropGroup.class);
<ide> if (groupAnnotation != null) {
<del> Class<?> [] paramTypes = method.getParameterTypes();
<add> Class<?>[] paramTypes = method.getParameterTypes();
<ide> if (paramTypes.length != 2) {
<del> throw new RuntimeException("Wrong number of args for group prop setter: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Wrong number of args for group prop setter: "
<add> + cls.getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> if (paramTypes[0] != int.class) {
<del> throw new RuntimeException("Second argument should be property index: " +
<del> cls.getName() + "#" + method.getName());
<add> throw new RuntimeException(
<add> "Second argument should be property index: "
<add> + cls.getName()
<add> + "#"
<add> + method.getName());
<ide> }
<ide> createPropSetters(groupAnnotation, method, paramTypes[1], props);
<ide> }
<ide><path>ReactAndroid/src/test/java/com/facebook/react/uimanager/SimpleViewPropertyTest.java
<ide>
<ide> import java.util.Map;
<ide>
<add>import android.graphics.drawable.ColorDrawable;
<ide> import android.view.View;
<ide>
<ide> import com.facebook.react.bridge.ReadableMap;
<ide> public void testOpacity() {
<ide> assertThat(view.getAlpha()).isEqualTo(1.0f);
<ide> }
<ide>
<add> @Test
<add> public void testBackgroundColor() {
<add> View view = mManager.createView(mThemedContext, new JSResponderHandler());
<add>
<add> mManager.updateProperties(view, buildStyles());
<add> assertThat(view.getBackground()).isEqualTo(null);
<add>
<add> mManager.updateProperties(view, buildStyles("backgroundColor", 12));
<add> assertThat(((ColorDrawable)view.getBackground()).getColor()).isEqualTo(12);
<add>
<add> mManager.updateProperties(view, buildStyles("backgroundColor", null));
<add> assertThat(((ColorDrawable)view.getBackground()).getColor()).isEqualTo(0);
<add> }
<add>
<ide> @Test
<ide> public void testGetNativeProps() {
<ide> Map<String, String> nativeProps = mManager.getNativeProps(); | 8 |
Text | Text | clarify usage of tmpdir.refresh() | 127f47e3e83389605079544f6e73b32459b39b1a | <ide><path>test/common/README.md
<ide> The realpath of the testing temporary directory.
<ide>
<ide> Deletes and recreates the testing temporary directory.
<ide>
<del>The first time `refresh()` runs, it adds a listener to process `'exit'` that
<add>The first time `refresh()` runs, it adds a listener to process `'exit'` that
<ide> cleans the temporary directory. Thus, every file under `tmpdir.path` needs to
<ide> be closed before the test completes. A good way to do this is to add a
<ide> listener to process `'beforeExit'`. If a file needs to be left open until
<ide> Node.js completes, use a child process and call `refresh()` only in the
<ide> parent.
<ide>
<add>It is usually only necessary to call `refresh()` once in a test file.
<add>Avoid calling it more than once in an asynchronous context as one call
<add>might refresh the temporary directory of a different context, causing
<add>the test to fail somewhat mysteriously.
<add>
<ide> ## UDP pair helper
<ide>
<ide> The `common/udppair` module exports a function `makeUDPPair` and a class | 1 |
Javascript | Javascript | fix eslint warnings using 'yarn lint --fix' | edb6ca72fdc04576a503aa8e5f34c32d2f727750 | <ide><path>Libraries/Alert/Alert.js
<ide> type Options = {
<ide>
<ide> /**
<ide> * Launches an alert dialog with the specified title and message.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/alert.html
<ide> */
<ide> class Alert {
<ide>
<ide> /**
<ide> * Launches an alert dialog with the specified title and message.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/alert.html#alert
<ide> */
<ide> static alert(
<ide><path>Libraries/Alert/AlertIOS.js
<ide> class AlertIOS {
<ide>
<ide> /**
<ide> * Create and display a prompt to enter some text.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/alertios.html#prompt
<ide> */
<ide> static prompt(
<ide><path>Libraries/AppState/AppState.js
<ide> class AppState extends NativeEventEmitter {
<ide> let eventUpdated = false;
<ide>
<ide> // TODO: this is a terrible solution - in order to ensure `currentState`
<del> // prop is up to date, we have to register an observer that updates it
<del> // whenever the state changes, even if nobody cares. We should just
<add> // prop is up to date, we have to register an observer that updates it
<add> // whenever the state changes, even if nobody cares. We should just
<ide> // deprecate the `currentState` property and get rid of this.
<ide> this.addListener(
<ide> 'appStateDidChange',
<ide> class AppState extends NativeEventEmitter {
<ide> }
<ide>
<ide> // TODO: now that AppState is a subclass of NativeEventEmitter, we could
<del> // deprecate `addEventListener` and `removeEventListener` and just use
<del> // addListener` and `listener.remove()` directly. That will be a breaking
<add> // deprecate `addEventListener` and `removeEventListener` and just use
<add> // addListener` and `listener.remove()` directly. That will be a breaking
<ide> // change though, as both the method and event names are different
<ide> // (addListener events are currently required to be globally unique).
<ide> /**
<ide> * Add a handler to AppState changes by listening to the `change` event type
<ide> * and providing the handler.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/appstate.html#addeventlistener
<ide> */
<ide> addEventListener(
<ide> class AppState extends NativeEventEmitter {
<ide>
<ide> /**
<ide> * Remove a handler by passing the `change` event type and the handler.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/appstate.html#removeeventlistener
<ide> */
<ide> removeEventListener(
<ide><path>Libraries/Components/AccessibilityInfo/AccessibilityInfo.android.js
<ide> var _subscriptions = new Map();
<ide> /**
<ide> * Sometimes it's useful to know whether or not the device has a screen reader
<ide> * that is currently active. The `AccessibilityInfo` API is designed for this
<del> * purpose. You can use it to query the current state of the screen reader as
<del> * well as to register to be notified when the state of the screen reader
<add> * purpose. You can use it to query the current state of the screen reader as
<add> * well as to register to be notified when the state of the screen reader
<ide> * changes.
<ide> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html
<ide><path>Libraries/Components/AccessibilityInfo/AccessibilityInfo.ios.js
<ide> var _subscriptions = new Map();
<ide> /**
<ide> * Sometimes it's useful to know whether or not the device has a screen reader
<ide> * that is currently active. The `AccessibilityInfo` API is designed for this
<del> * purpose. You can use it to query the current state of the screen reader as
<del> * well as to register to be notified when the state of the screen reader
<add> * purpose. You can use it to query the current state of the screen reader as
<add> * well as to register to be notified when the state of the screen reader
<ide> * changes.
<ide> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html
<ide> */
<ide> var AccessibilityInfo = {
<ide>
<ide> /**
<del> * Query whether a screen reader is currently enabled.
<del> *
<del> * Returns a promise which resolves to a boolean.
<add> * Query whether a screen reader is currently enabled.
<add> *
<add> * Returns a promise which resolves to a boolean.
<ide> * The result is `true` when a screen reader is enabledand `false` otherwise.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#fetch
<ide> */
<ide> fetch: function(): Promise {
<ide> var AccessibilityInfo = {
<ide> * - `announcement`: The string announced by the screen reader.
<ide> * - `success`: A boolean indicating whether the announcement was
<ide> * successfully made.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#addeventlistener
<ide> */
<ide> addEventListener: function (
<ide> var AccessibilityInfo = {
<ide>
<ide> /**
<ide> * Set accessibility focus to a react component.
<del> *
<add> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#setaccessibilityfocus
<ide> */
<ide> setAccessibilityFocus: function(
<ide> var AccessibilityInfo = {
<ide> * Post a string to be announced by the screen reader.
<ide> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#announceforaccessibility
<ide> */
<ide> announceForAccessibility: function(
<ide> var AccessibilityInfo = {
<ide>
<ide> /**
<ide> * Remove an event handler.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/accessibilityinfo.html#removeeventlistener
<ide> */
<ide> removeEventListener: function(
<ide><path>Libraries/Components/ActivityIndicator/ActivityIndicator.js
<ide> const ActivityIndicator = createReactClass({
<ide> ...ViewPropTypes,
<ide> /**
<ide> * Whether to show the indicator (true, the default) or hide it (false).
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/activityindicator.html#animating
<ide> */
<ide> animating: PropTypes.bool,
<ide> /**
<ide> * The foreground color of the spinner (default is gray).
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/activityindicator.html#color
<ide> */
<ide> color: ColorPropType,
<ide> /**
<ide> * Size of the indicator (default is 'small').
<ide> * Passing a number to the size prop is only supported on Android.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/activityindicator.html#size
<ide> */
<ide> size: PropTypes.oneOfType([
<ide> const ActivityIndicator = createReactClass({
<ide> * Whether the indicator should hide when not animating (true by default).
<ide> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/activityindicator.html#hideswhenstopped
<ide> */
<ide> hidesWhenStopped: PropTypes.bool,
<ide><path>Libraries/Components/View/ViewPropTypes.js
<ide> module.exports = {
<ide> ...PlatformViewPropTypes,
<ide>
<ide> /**
<del> * When `true`, indicates that the view is an accessibility element.
<add> * When `true`, indicates that the view is an accessibility element.
<ide> * By default, all the touchable elements are accessible.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessible
<ide> */
<ide> accessible: PropTypes.bool,
<ide> module.exports = {
<ide> * Overrides the text that's read by the screen reader when the user interacts
<ide> * with the element. By default, the label is constructed by traversing all
<ide> * the children and accumulating all the `Text` nodes separated by space.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessibilitylabel
<ide> */
<ide> accessibilityLabel: PropTypes.node,
<ide> module.exports = {
<ide> * native one. Works for Android only.
<ide> *
<ide> * @platform android
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessibilitycomponenttype
<ide> */
<ide> accessibilityComponentType: PropTypes.oneOf(AccessibilityComponentTypes),
<ide> module.exports = {
<ide> * when this view changes. Works for Android API >= 19 only.
<ide> *
<ide> * @platform android
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessibilityliveregion
<ide> */
<ide> accessibilityLiveRegion: PropTypes.oneOf([
<ide> module.exports = {
<ide> * that query the screen. Works for Android only.
<ide> *
<ide> * @platform android
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#importantforaccessibility
<ide> */
<ide> importantForAccessibility: PropTypes.oneOf([
<ide> module.exports = {
<ide> * You can provide one trait or an array of many traits.
<ide> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessibilitytraits
<ide> */
<ide> accessibilityTraits: PropTypes.oneOfType([
<ide> module.exports = {
<ide> * Default is `false`.
<ide> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessibilityviewismodal
<ide> */
<ide> accessibilityViewIsModal: PropTypes.bool,
<del>
<add>
<ide> /**
<ide> * A value indicating whether the accessibility elements contained within
<ide> * this accessibility element are hidden.
<ide> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#accessibilityElementsHidden
<ide> */
<ide> accessibilityElementsHidden: PropTypes.bool,
<ide> module.exports = {
<ide> /**
<ide> * When `accessible` is true, the system will try to invoke this function
<ide> * when the user performs accessibility tap gesture.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onaccessibilitytap
<ide> */
<ide> onAccessibilityTap: PropTypes.func,
<ide>
<ide> /**
<ide> * When `accessible` is `true`, the system will invoke this function when the
<ide> * user performs the magic tap gesture.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onmagictap
<ide> */
<ide> onMagicTap: PropTypes.func,
<ide> module.exports = {
<ide> * Used to locate this view in end-to-end tests.
<ide> *
<ide> * > This disables the 'layout-only view removal' optimization for this view!
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#testid
<ide> */
<ide> testID: PropTypes.string,
<ide> module.exports = {
<ide> * Used to locate this view from native classes.
<ide> *
<ide> * > This disables the 'layout-only view removal' optimization for this view!
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#nativeid
<ide> */
<ide> nativeID: PropTypes.string,
<ide> module.exports = {
<ide> */
<ide>
<ide> /**
<del> * The View is now responding for touch events. This is the time to highlight
<add> * The View is now responding for touch events. This is the time to highlight
<ide> * and show the user what is happening.
<ide> *
<ide> * `View.props.onResponderGrant: (event) => {}`, where `event` is a synthetic
<ide> * touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onrespondergrant
<ide> */
<ide> onResponderGrant: PropTypes.func,
<ide>
<ide> /**
<ide> * The user is moving their finger.
<ide> *
<del> * `View.props.onResponderMove: (event) => {}`, where `event` is a synthetic
<add> * `View.props.onResponderMove: (event) => {}`, where `event` is a synthetic
<ide> * touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onrespondermove
<ide> */
<ide> onResponderMove: PropTypes.func,
<ide>
<ide> /**
<del> * Another responder is already active and will not release it to that `View`
<add> * Another responder is already active and will not release it to that `View`
<ide> * asking to be the responder.
<ide> *
<del> * `View.props.onResponderReject: (event) => {}`, where `event` is a
<add> * `View.props.onResponderReject: (event) => {}`, where `event` is a
<ide> * synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onresponderreject
<ide> */
<ide> onResponderReject: PropTypes.func,
<ide>
<ide> /**
<ide> * Fired at the end of the touch.
<ide> *
<del> * `View.props.onResponderRelease: (event) => {}`, where `event` is a
<add> * `View.props.onResponderRelease: (event) => {}`, where `event` is a
<ide> * synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onresponderrelease
<ide> */
<ide> onResponderRelease: PropTypes.func,
<ide>
<ide> /**
<ide> * The responder has been taken from the `View`. Might be taken by other
<del> * views after a call to `onResponderTerminationRequest`, or might be taken
<del> * by the OS without asking (e.g., happens with control center/ notification
<add> * views after a call to `onResponderTerminationRequest`, or might be taken
<add> * by the OS without asking (e.g., happens with control center/ notification
<ide> * center on iOS)
<ide> *
<del> * `View.props.onResponderTerminate: (event) => {}`, where `event` is a
<add> * `View.props.onResponderTerminate: (event) => {}`, where `event` is a
<ide> * synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onresponderterminate
<ide> */
<ide> onResponderTerminate: PropTypes.func,
<ide>
<ide> /**
<del> * Some other `View` wants to become responder and is asking this `View` to
<add> * Some other `View` wants to become responder and is asking this `View` to
<ide> * release its responder. Returning `true` allows its release.
<ide> *
<del> * `View.props.onResponderTerminationRequest: (event) => {}`, where `event`
<add> * `View.props.onResponderTerminationRequest: (event) => {}`, where `event`
<ide> * is a synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onresponderterminationrequest
<ide> */
<ide> onResponderTerminationRequest: PropTypes.func,
<ide>
<ide> /**
<ide> * Does this view want to become responder on the start of a touch?
<ide> *
<del> * `View.props.onStartShouldSetResponder: (event) => [true | false]`, where
<add> * `View.props.onStartShouldSetResponder: (event) => [true | false]`, where
<ide> * `event` is a synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onstartshouldsetresponder
<ide> */
<ide> onStartShouldSetResponder: PropTypes.func,
<ide>
<ide> /**
<del> * If a parent `View` wants to prevent a child `View` from becoming responder
<add> * If a parent `View` wants to prevent a child `View` from becoming responder
<ide> * on a touch start, it should have this handler which returns `true`.
<ide> *
<del> * `View.props.onStartShouldSetResponderCapture: (event) => [true | false]`,
<add> * `View.props.onStartShouldSetResponderCapture: (event) => [true | false]`,
<ide> * where `event` is a synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onstartshouldsetrespondercapture
<ide> */
<ide> onStartShouldSetResponderCapture: PropTypes.func,
<ide>
<ide> /**
<del> * Does this view want to "claim" touch responsiveness? This is called for
<add> * Does this view want to "claim" touch responsiveness? This is called for
<ide> * every touch move on the `View` when it is not the responder.
<ide> *
<del> * `View.props.onMoveShouldSetResponder: (event) => [true | false]`, where
<add> * `View.props.onMoveShouldSetResponder: (event) => [true | false]`, where
<ide> * `event` is a synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onmoveshouldsetresponder
<ide> */
<ide> onMoveShouldSetResponder: PropTypes.func,
<ide>
<ide> /**
<ide> * If a parent `View` wants to prevent a child `View` from becoming responder
<ide> * on a move, it should have this handler which returns `true`.
<del> *
<add> *
<ide> * `View.props.onMoveShouldSetResponderCapture: (event) => [true | false]`,
<ide> * where `event` is a synthetic touch event as described above.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onMoveShouldsetrespondercapture
<ide> */
<ide> onMoveShouldSetResponderCapture: PropTypes.func,
<ide> module.exports = {
<ide> * > The touch area never extends past the parent view bounds and the Z-index
<ide> * > of sibling views always takes precedence if a touch hits two overlapping
<ide> * > views.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#hitslop
<ide> */
<ide> hitSlop: EdgeInsetsPropType,
<ide> module.exports = {
<ide> * This event is fired immediately once the layout has been calculated, but
<ide> * the new layout may not yet be reflected on the screen at the time the
<ide> * event is received, especially if a layout animation is in progress.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#onlayout
<ide> */
<ide> onLayout: PropTypes.func,
<ide>
<ide> /**
<ide> * Controls whether the `View` can be the target of touch events.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#pointerevents
<ide> */
<ide> pointerEvents: PropTypes.oneOf([
<ide> module.exports = {
<ide> * view that contains many subviews that extend outside its bound. The
<ide> * subviews must also have `overflow: hidden`, as should the containing view
<ide> * (or one of its superviews).
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#removeclippedsubviews
<ide> */
<ide> removeClippedSubviews: PropTypes.bool,
<ide> module.exports = {
<ide> * single hardware texture on the GPU.
<ide> *
<ide> * @platform android
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#rendertohardwaretextureandroid
<ide> */
<ide> renderToHardwareTextureAndroid: PropTypes.bool,
<ide> module.exports = {
<ide> * Whether this `View` should be rendered as a bitmap before compositing.
<ide> *
<ide> * @platform ios
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#shouldrasterizeios
<ide> */
<ide> shouldRasterizeIOS: PropTypes.bool,
<ide> module.exports = {
<ide> * ensure that this `View` exists in the native view hierarchy.
<ide> *
<ide> * @platform android
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#collapsable
<ide> */
<ide> collapsable: PropTypes.bool,
<ide>
<ide> /**
<del> * Whether this `View` needs to rendered offscreen and composited with an
<del> * alpha in order to preserve 100% correct colors and blending behavior.
<add> * Whether this `View` needs to rendered offscreen and composited with an
<add> * alpha in order to preserve 100% correct colors and blending behavior.
<ide> *
<ide> * @platform android
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/view.html#needsoffscreenalphacompositing
<ide> */
<ide> needsOffscreenAlphaCompositing: PropTypes.bool,
<ide><path>Libraries/Geolocation/Geolocation.js
<ide> var Geolocation = {
<ide>
<ide> /*
<ide> * Request suitable Location permission based on the key configured on pList.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/geolocation.html#requestauthorization
<ide> */
<ide> requestAuthorization: function() {
<ide> RCTLocationObserver.requestAuthorization();
<ide> },
<ide>
<ide> /*
<del> * Invokes the success callback once with the latest location info.
<del> *
<add> * Invokes the success callback once with the latest location info.
<add> *
<ide> * See https://facebook.github.io/react-native/docs/geolocation.html#getcurrentposition
<ide> */
<ide> getCurrentPosition: async function(
<ide> var Geolocation = {
<ide>
<ide> /*
<ide> * Invokes the success callback whenever the location changes.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/geolocation.html#watchposition
<ide> */
<ide> watchPosition: function(success: Function, error?: Function, options?: GeoOptions): number {
<ide><path>Libraries/Linking/Linking.js
<ide> const LinkingManager = Platform.OS === 'android' ?
<ide> /**
<ide> * `Linking` gives you a general interface to interact with both incoming
<ide> * and outgoing app links.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/linking.html
<ide> */
<ide> class Linking extends NativeEventEmitter {
<ide> class Linking extends NativeEventEmitter {
<ide> /**
<ide> * Add a handler to Linking changes by listening to the `url` event type
<ide> * and providing the handler
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/linking.html#addeventlistener
<ide> */
<ide> addEventListener(type: string, handler: Function) {
<ide> class Linking extends NativeEventEmitter {
<ide>
<ide> /**
<ide> * Remove a handler by passing the `url` event type and the handler.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/linking.html#removeeventlistener
<ide> */
<ide> removeEventListener(type: string, handler: Function ) {
<ide><path>Libraries/Modal/Modal.js
<ide> import type EmitterSubscription from 'EmitterSubscription';
<ide>
<ide> /**
<ide> * The Modal component is a simple way to present content above an enclosing view.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html
<ide> */
<ide>
<ide> class Modal extends React.Component<Object> {
<ide> animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
<ide> /**
<ide> * The `presentationStyle` prop controls how the modal appears.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#presentationstyle
<ide> */
<ide> presentationStyle: PropTypes.oneOf(['fullScreen', 'pageSheet', 'formSheet', 'overFullScreen']),
<ide> /**
<ide> * The `transparent` prop determines whether your modal will fill the
<del> * entire view.
<del> *
<add> * entire view.
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#transparent
<ide> */
<ide> transparent: PropTypes.bool,
<ide> /**
<ide> * The `hardwareAccelerated` prop controls whether to force hardware
<ide> * acceleration for the underlying window.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#hardwareaccelerated
<ide> */
<ide> hardwareAccelerated: PropTypes.bool,
<ide> /**
<ide> * The `visible` prop determines whether your modal is visible.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#visible
<ide> */
<ide> visible: PropTypes.bool,
<ide> /**
<ide> * The `onRequestClose` callback is called when the user taps the hardware
<ide> * back button on Android or the menu button on Apple TV.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#onrequestclose
<ide> */
<ide> onRequestClose: (Platform.isTVOS || Platform.OS === 'android') ? PropTypes.func.isRequired : PropTypes.func,
<ide> /**
<ide> * The `onShow` prop allows passing a function that will be called once the
<ide> * modal has been shown.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#onshow
<ide> */
<ide> onShow: PropTypes.func,
<ide> /**
<ide> * The `onDismiss` prop allows passing a function that will be called once
<ide> * the modal has been dismissed.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#ondismiss
<ide> */
<ide> onDismiss: PropTypes.func,
<ide> class Modal extends React.Component<Object> {
<ide> ),
<ide> /**
<ide> * The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#supportedorientations
<ide> */
<ide> supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])),
<ide> /**
<ide> * The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/modal.html#onorientationchange
<ide> */
<ide> onOrientationChange: PropTypes.func,
<ide><path>Libraries/Network/NetInfo.js
<ide> const _isConnectedSubscriptions = new Map();
<ide>
<ide> /**
<ide> * NetInfo exposes info about online/offline status.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/netinfo.html
<ide> */
<ide> const NetInfo = {
<ide> /**
<ide> * Adds an event handler.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/netinfo.html#addeventlistener
<ide> */
<ide> addEventListener(
<ide> const NetInfo = {
<ide>
<ide> /**
<ide> * Removes the listener for network status changes.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/netinfo.html#removeeventlistener
<ide> */
<ide> removeEventListener(
<ide> const NetInfo = {
<ide> },
<ide>
<ide> /**
<del> * This function is deprecated. Use `getConnectionInfo` instead.
<add> * This function is deprecated. Use `getConnectionInfo` instead.
<ide> * Returns a promise that resolves with one of the deprecated connectivity
<ide> * types:
<del> *
<add> *
<ide> * The following connectivity types are deprecated. They're used by the
<ide> * deprecated APIs `fetch` and the `change` event.
<ide> *
<ide> const NetInfo = {
<ide> * - `MOBILE_HIPRI` - A High Priority Mobile data connection.
<ide> * - `MOBILE_MMS` - An MMS-specific Mobile data connection.
<ide> * - `MOBILE_SUPL` - A SUPL-specific Mobile data connection.
<del> * - `VPN` - A virtual network using one or more native bearers. Requires
<add> * - `VPN` - A virtual network using one or more native bearers. Requires
<ide> * API Level 21
<ide> * - `WIFI` - The WIFI data connection.
<ide> * - `WIMAX` - The WiMAX data connection.
<ide> * - `UNKNOWN` - Unknown data connection.
<ide> *
<del> * The rest of the connectivity types are hidden by the Android API, but can
<add> * The rest of the connectivity types are hidden by the Android API, but can
<ide> * be used if necessary.
<ide> */
<ide> fetch(): Promise<any> {
<ide> const NetInfo = {
<ide> /**
<ide> * An object with the same methods as above but the listener receives a
<ide> * boolean which represents the internet connectivity.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/netinfo.html#isconnected
<ide> */
<ide> isConnected: {
<ide><path>Libraries/PermissionsAndroid/PermissionsAndroid.js
<ide> type Rationale = {
<ide> type PermissionStatus = 'granted' | 'denied' | 'never_ask_again';
<ide> /**
<ide> * `PermissionsAndroid` provides access to Android M's new permissions model.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html
<ide> */
<ide>
<ide> class PermissionsAndroid {
<ide> /**
<ide> * Returns a promise resolving to a boolean value as to whether the specified
<ide> * permissions has been granted
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html#check
<ide> */
<ide> check(permission: string) : Promise<boolean> {
<ide> class PermissionsAndroid {
<ide> * Prompts the user to enable multiple permissions in the same dialog and
<ide> * returns an object with the permissions as keys and strings as values
<ide> * indicating whether the user allowed or denied the request
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html#requestmultiple
<ide> */
<ide> requestMultiple(permissions: Array<string>) : Promise<{[permission: string]: PermissionStatus}> {
<ide><path>Libraries/PushNotificationIOS/PushNotificationIOS.js
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Cancels all scheduled localNotifications.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#cancelalllocalnotifications
<ide> */
<ide> static cancelAllLocalNotifications() {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Remove all delivered notifications from Notification Center.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#removealldeliverednotifications
<ide> */
<ide> static removeAllDeliveredNotifications(): void {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Sets the badge number for the app icon on the home screen.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#setapplicationiconbadgenumber
<ide> */
<ide> static setApplicationIconBadgeNumber(number: number) {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the current badge number for the app icon on the home screen.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getapplicationiconbadgenumber
<ide> */
<ide> static getApplicationIconBadgeNumber(callback: Function) {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the local notifications that are currently scheduled.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getscheduledlocalnotifications
<ide> */
<ide> static getScheduledLocalNotifications(callback: Function) {
<ide> class PushNotificationIOS {
<ide> /**
<ide> * Removes the event listener. Do this in `componentWillUnmount` to prevent
<ide> * memory leaks.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#removeeventlistener
<ide> */
<ide> static removeEventListener(type: PushNotificationEventName, handler: Function) {
<ide> class PushNotificationIOS {
<ide> * dialog box. By default, it will request all notification permissions, but
<ide> * a subset of these can be requested by passing a map of requested
<ide> * permissions.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#requestpermissions
<ide> */
<ide> static requestPermissions(permissions?: {
<ide> class PushNotificationIOS {
<ide> /**
<ide> * See what push permissions are currently enabled. `callback` will be
<ide> * invoked with a `permissions` object.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#checkpermissions
<ide> */
<ide> static checkPermissions(callback: Function) {
<ide> class PushNotificationIOS {
<ide> /**
<ide> * This method returns a promise that resolves to either the notification
<ide> * object if the app was launched by a push notification, or `null` otherwise.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getinitialnotification
<ide> */
<ide> static getInitialNotification(): Promise<?PushNotificationIOS> {
<ide> class PushNotificationIOS {
<ide> * You will never need to instantiate `PushNotificationIOS` yourself.
<ide> * Listening to the `notification` event and invoking
<ide> * `getInitialNotification` is sufficient
<del> *
<add> *
<ide> */
<ide> constructor(nativeNotif: Object) {
<ide> this._data = {};
<ide> class PushNotificationIOS {
<ide> /**
<ide> * This method is available for remote notifications that have been received via:
<ide> * `application:didReceiveRemoteNotification:fetchCompletionHandler:`
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#finish
<ide> */
<ide> finish(fetchResult: string) {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the sound string from the `aps` object
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getsound
<ide> */
<ide> getSound(): ?string {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the category string from the `aps` object
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getcategory
<ide> */
<ide> getCategory(): ?string {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the notification's main message from the `aps` object
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getalert
<ide> */
<ide> getAlert(): ?string | ?Object {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the content-available number from the `aps` object
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getcontentavailable
<ide> */
<ide> getContentAvailable(): ContentAvailable {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the badge count number from the `aps` object
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getbadgecount
<ide> */
<ide> getBadgeCount(): ?number {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the data object on the notif
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getdata
<ide> */
<ide> getData(): ?Object {
<ide> class PushNotificationIOS {
<ide>
<ide> /**
<ide> * Gets the thread ID on the notif
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/pushnotificationios.html#getthreadid
<ide> */
<ide> getThreadID(): ?string {
<ide><path>Libraries/Storage/AsyncStorage.js
<ide> const RCTAsyncStorage = NativeModules.AsyncRocksDBStorage ||
<ide>
<ide> /**
<ide> * `AsyncStorage` is a simple, unencrypted, asynchronous, persistent, key-value
<del> * storage system that is global to the app. It should be used instead of
<add> * storage system that is global to the app. It should be used instead of
<ide> * LocalStorage.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html
<ide> */
<ide> var AsyncStorage = {
<ide> var AsyncStorage = {
<ide>
<ide> /**
<ide> * Fetches an item for a `key` and invokes a callback upon completion.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#getitem
<ide> */
<ide> getItem: function(
<ide> var AsyncStorage = {
<ide>
<ide> /**
<ide> * Sets the value for a `key` and invokes a callback upon completion.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#setitem
<ide> */
<ide> setItem: function(
<ide> var AsyncStorage = {
<ide>
<ide> /**
<ide> * Removes an item for a `key` and invokes a callback upon completion.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#removeitem
<ide> */
<ide> removeItem: function(
<ide> var AsyncStorage = {
<ide> * Erases *all* `AsyncStorage` for all clients, libraries, etc. You probably
<ide> * don't want to call this; use `removeItem` or `multiRemove` to clear only
<ide> * your app's keys.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#clear
<ide> */
<ide> clear: function(callback?: ?(error: ?Error) => void): Promise {
<ide> var AsyncStorage = {
<ide> * indicate which key caused the error.
<ide> */
<ide>
<del> /**
<add> /**
<ide> * Flushes any pending requests using a single batch call to get the data.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#flushgetrequests
<ide> * */
<ide> flushGetRequests: function(): void {
<ide> var AsyncStorage = {
<ide> * This allows you to batch the fetching of items given an array of `key`
<ide> * inputs. Your callback will be invoked with an array of corresponding
<ide> * key-value pairs found.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#multiget
<ide> */
<ide> multiGet: function(
<ide> var AsyncStorage = {
<ide>
<ide> /**
<ide> * Call this to batch the deletion of all keys in the `keys` array.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#multiremove
<ide> */
<ide> multiRemove: function(
<ide> var AsyncStorage = {
<ide> /**
<ide> * Batch operation to merge in existing and new values for a given set of
<ide> * keys. This assumes that the values are stringified JSON.
<del> *
<add> *
<ide> * **NOTE**: This is not supported by all native implementations.
<del> *
<add> *
<ide> * See http://facebook.github.io/react-native/docs/asyncstorage.html#multimerge
<ide> */
<ide> multiMerge: function(
<ide><path>Libraries/Vibration/Vibration.js
<ide> var Platform = require('Platform');
<ide>
<ide> /**
<ide> * Vibration API
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/vibration.html
<ide> */
<ide>
<ide> function vibrateScheduler(id, pattern: Array<number>, repeat: boolean, nextIndex
<ide> var Vibration = {
<ide> /**
<ide> * Trigger a vibration with specified `pattern`.
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/vibration.html#vibrate
<ide> */
<ide> vibrate: function(pattern: number | Array<number> = 400, repeat: boolean = false) {
<ide> var Vibration = {
<ide> },
<ide> /**
<ide> * Stop vibration
<del> *
<add> *
<ide> * See https://facebook.github.io/react-native/docs/vibration.html#cancel
<ide> */
<ide> cancel: function() {
<ide><path>RNTester/js/ListExampleShared.js
<ide> function pressItem(context: Object, key: string) {
<ide> }
<ide>
<ide> function renderSmallSwitchOption(context: Object, key: string) {
<del> if(Platform.isTVOS) {
<add> if (Platform.isTVOS) {
<ide> return null;
<ide> }
<ide> return (
<ide><path>RNTester/js/RNTesterApp.ios.js
<ide> const styles = StyleSheet.create({
<ide> borderBottomColor: '#96969A',
<ide> backgroundColor: '#F5F5F6',
<ide> },
<del> header: {
<del> height: 40,
<del> flexDirection: 'row'
<add> header: {
<add> height: 40,
<add> flexDirection: 'row'
<ide> },
<ide> headerLeft: {
<ide> },
<ide><path>bots/dangerfile.js
<ide> if (danger.git.modified_files + danger.git.added_files + danger.git.deleted_file
<ide> const issueCommandsFileModified = includes(danger.git.modified_files, 'bots/IssueCommands.txt');
<ide> if (issueCommandsFileModified) {
<ide> const title = ':exclamation: Bots';
<del> const idea = 'This PR appears to modify the list of people that may issue ' +
<add> const idea = 'This PR appears to modify the list of people that may issue ' +
<ide> 'commands to the GitHub bot.';
<ide> warn(`${title} - <i>${idea}</i>`);
<ide> }
<ide>
<ide> // Warns if the PR is opened against stable, as commits need to be cherry picked and tagged by a release maintainer.
<ide> // Fails if the PR is opened against anything other than `master` or `-stable`.
<ide> const isMergeRefMaster = danger.github.pr.base.ref === 'master';
<del>const isMergeRefStable = danger.github.pr.base.ref.indexOf(`-stable`) !== -1;
<add>const isMergeRefStable = danger.github.pr.base.ref.indexOf('-stable') !== -1;
<ide> if (!isMergeRefMaster && isMergeRefStable) {
<ide> const title = ':grey_question: Base Branch';
<ide> const idea = 'The base branch for this PR is something other than `master`. Are you sure you want to merge these changes into a stable release? If you are interested in backporting updates to an older release, the suggested approach is to land those changes on `master` first and then cherry-pick the commits into the branch for that release. The [Releases Guide](https://github.com/facebook/react-native/blob/master/Releases.md) has more information.';
<ide><path>flow-github/metro.js
<ide> declare module 'metro/src/HmrServer' {
<ide>
<ide> declare module 'metro/src/lib/bundle-modules/HMRClient' {
<ide> declare module.exports: any;
<del>}
<ide>\ No newline at end of file
<add>}
<ide><path>local-cli/link/ios/getTargets.js
<ide> module.exports = function getTargets(project) {
<ide> target: nativeTargetSection[key],
<ide> name: nativeTargetSection[key].productReference_comment,
<ide> isTVOS: (buildConfiguration.buildSettings.SDKROOT && (buildConfiguration.buildSettings.SDKROOT.indexOf('appletv') !== -1)) || false
<del> }
<add> };
<ide> });
<ide> };
<ide><path>local-cli/link/ios/registerNativeModule.js
<ide> module.exports = function registerNativeModuleIOS(dependencyConfig, projectConfi
<ide> getTargets(dependencyProject).forEach(product => {
<ide> var i;
<ide> if (!product.isTVOS) {
<del> for (i=0; i<targets.length; i++) {
<del> if(!targets[i].isTVOS) {
<add> for (i = 0; i < targets.length; i++) {
<add> if (!targets[i].isTVOS) {
<ide> project.addStaticLibrary(product.name, {
<ide> target: targets[i].uuid
<ide> });
<ide> module.exports = function registerNativeModuleIOS(dependencyConfig, projectConfi
<ide> }
<ide>
<ide> if (product.isTVOS) {
<del> for (i=0; i<targets.length; i++) {
<del> if(targets[i].isTVOS) {
<add> for (i = 0; i < targets.length; i++) {
<add> if (targets[i].isTVOS) {
<ide> project.addStaticLibrary(product.name, {
<ide> target: targets[i].uuid
<ide> });
<ide><path>local-cli/link/unlink.js
<ide> function unlink(args, config) {
<ide> if (!linkConfig || !linkConfig.unlinkAssets) {
<ide> return;
<ide> }
<del>
<add>
<ide> log.info(`Unlinking assets from ${platform} project`);
<ide> linkConfig.unlinkAssets(assets, project[platform]);
<ide> }); | 22 |
PHP | PHP | add attribute pattern matching | 31181f58d6b9b60225cd3a225d8d40d1265fb70a | <ide><path>lib/Cake/Test/Case/Utility/Set2Test.php
<ide> public function testExtractAttributeMultiple() {
<ide> $this->assertEquals(4, $expected[0]['user_id']);
<ide> }
<ide>
<add>/**
<add> * Test attribute pattern matching.
<add> *
<add> * @return void
<add> */
<add> public function testExtractAttributePattern() {
<add> $data = self::articleData();
<add>
<add> $result = Set2::extract($data, '{n}.Article[title=/^First/]');
<add> $expected = array($data[0]['Article']);
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Utility/Set2.php
<ide> protected static function _traverse(array &$data, $path, $callback) {
<ide> }
<ide> }
<ide> }
<del>
<ide> }
<ide>
<ide> // Filter for attributes.
<ide> protected static function _matches(array $data, $selector) {
<ide>
<ide> // Presence test.
<ide> if (empty($op) && empty($val) && !isset($data[$attr])) {
<del> $ok = false;
<add> return false;
<ide> }
<ide>
<ide> // Empty attribute = fail.
<ide> if (!isset($data[$attr])) {
<del> $ok = false;
<add> return false;
<ide> }
<ide>
<ide> $prop = isset($data[$attr]) ? $data[$attr] : null;
<ide>
<del> if (
<add> // Pattern matches and other operators.
<add> if ($op === '=' && $val && $val[0] === '/') {
<add> if (!preg_match($val, $prop)) {
<add> return false;
<add> }
<add> } elseif (
<ide> ($op === '=' && $prop != $val) ||
<ide> ($op === '!=' && $prop == $val) ||
<ide> ($op === '>' && $prop <= $val) ||
<ide> ($op === '<' && $prop >= $val) ||
<ide> ($op === '>=' && $prop < $val) ||
<ide> ($op === '<=' && $prop > $val)
<ide> ) {
<del> $ok = false;
<del> }
<del> if (!$ok) {
<ide> return false;
<ide> }
<add>
<ide> }
<ide> return true;
<ide> } | 2 |
Javascript | Javascript | make test for source.buffer more strict | 6e383cfbab3b18b88cccde4d4ceb99234d3fce8c | <ide><path>lib/Compiler.js
<ide> class Compiler extends Tapable {
<ide> // get the binary (Buffer) content from the Source
<ide> /** @type {Buffer} */
<ide> let content;
<del> if (source.buffer) {
<add> if (typeof source.buffer === "function") {
<ide> content = source.buffer();
<ide> } else {
<ide> const bufferOrString = source.source(); | 1 |
Text | Text | fix default config init in transformer api docs | d0236136a22d0b3019c6a68343c26e193d7f5510 | <ide><path>website/docs/api/transformer.md
<ide> on the transformer architectures and their arguments and hyperparameters.
<ide> > #### Example
<ide> >
<ide> > ```python
<del>> from spacy_transformers import Transformer, DEFAULT_CONFIG
<add>> from spacy_transformers import Transformer
<add>> from spacy_transformers.pipeline_component import DEFAULT_CONFIG
<ide> >
<del>> nlp.add_pipe("transformer", config=DEFAULT_CONFIG)
<add>> nlp.add_pipe("transformer", config=DEFAULT_CONFIG["transformer"])
<ide> > ```
<ide>
<ide> | Setting | Description | | 1 |
PHP | PHP | apply fixes from styleci | 618b49a38bfc88717ea61869284c2254aca5bbfb | <ide><path>tests/Mail/MailLogTransportTest.php
<ide> use Psr\Log\LoggerInterface;
<ide> use Orchestra\Testbench\TestCase;
<ide> use Monolog\Handler\StreamHandler;
<del>use Monolog\Handler\RotatingFileHandler;
<ide> use Illuminate\Mail\Transport\LogTransport;
<ide>
<ide> class MailLogTransportTest extends TestCase | 1 |
Python | Python | remove `xcom_push` flag from `bashoperator` | 05b7a625aec759ccdc4276c11ec0b827aebdb013 | <ide><path>airflow/operators/bash.py
<ide> def __init__(
<ide> self.skip_exit_code = skip_exit_code
<ide> self.cwd = cwd
<ide> self.append_env = append_env
<del> if kwargs.get('xcom_push') is not None:
<del> raise AirflowException("'xcom_push' was deprecated, use 'BaseOperator.do_xcom_push' instead")
<ide>
<ide> @cached_property
<ide> def subprocess_hook(self): | 1 |
Go | Go | add trust key creation on client | ac8d964b28f23c9790102462a040054e7857cb26 | <ide><path>docker/docker.go
<ide> import (
<ide> "fmt"
<ide> "io/ioutil"
<ide> "os"
<add> "path"
<ide> "strings"
<ide>
<ide> log "github.com/Sirupsen/logrus"
<ide> import (
<ide> flag "github.com/docker/docker/pkg/mflag"
<ide> "github.com/docker/docker/pkg/reexec"
<ide> "github.com/docker/docker/utils"
<add> "github.com/docker/libtrust"
<ide> )
<ide>
<ide> const (
<ide> func main() {
<ide> }
<ide> protoAddrParts := strings.SplitN(flHosts[0], "://", 2)
<ide>
<add> err := os.MkdirAll(path.Dir(*flTrustKey), 0700)
<add> if err != nil {
<add> log.Fatal(err)
<add> }
<add> trustKey, err := libtrust.LoadKeyFile(*flTrustKey)
<add> if err == libtrust.ErrKeyFileDoesNotExist {
<add> trustKey, err = libtrust.GenerateECP256PrivateKey()
<add> if err != nil {
<add> log.Fatalf("Error generating key: %s", err)
<add> }
<add> if err := libtrust.SaveKey(*flTrustKey, trustKey); err != nil {
<add> log.Fatalf("Error saving key file: %s", err)
<add> }
<add> } else if err != nil {
<add> log.Fatalf("Error loading key file: %s", err)
<add> }
<add>
<ide> var (
<ide> cli *client.DockerCli
<ide> tlsConfig tls.Config
<ide> func main() {
<ide> }
<ide>
<ide> if *flTls || *flTlsVerify {
<del> cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, nil, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
<add> cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, trustKey, protoAddrParts[0], protoAddrParts[1], &tlsConfig)
<ide> } else {
<del> cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, nil, protoAddrParts[0], protoAddrParts[1], nil)
<add> cli = client.NewDockerCli(os.Stdin, os.Stdout, os.Stderr, trustKey, protoAddrParts[0], protoAddrParts[1], nil)
<ide> }
<ide>
<ide> if err := cli.Cmd(flag.Args()...); err != nil { | 1 |
Ruby | Ruby | fix rdoc code formatting for railtie [ci skip] | 8859978b43eeb24f53c73afd9c8e57cdbd5a1d5c | <ide><path>railties/lib/rails/railtie.rb
<ide> module Rails
<ide> # this less confusing for everyone.
<ide> # It can be used like this:
<ide> #
<del> # class MyRailtie < Rails::Railtie
<del> # server do
<del> # WebpackServer.start
<add> # class MyRailtie < Rails::Railtie
<add> # server do
<add> # WebpackServer.start
<add> # end
<ide> # end
<del> # end
<ide> #
<ide> # == Application and Engine
<ide> # | 1 |
Go | Go | fix govet warnings | 2457d2549f28e2091397168be99bc356c80214f2 | <ide><path>libnetwork/drivers.go
<ide> func RegisterNetworkType(name string, creatorFn interface{}, creatorArg interfac
<ide> ctorArg := []reflect.Type{reflect.TypeOf((*string)(nil)), reflect.TypeOf(creatorArg)}
<ide> ctorRet := []reflect.Type{reflect.TypeOf((*Network)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}
<ide> if err := validateFunctionSignature(creatorFn, ctorArg, ctorRet); err != nil {
<del> sig := fmt.Sprintf("func (%s) (Network, error)", ctorArg[0].Name)
<add> sig := fmt.Sprintf("func (%s) (Network, error)", ctorArg[0].Name())
<ide> return fmt.Errorf("invalid signature for %q creator function (expected %s)", name, sig)
<ide> }
<ide>
<ide> func validateFunctionSignature(fn interface{}, params []reflect.Type, returns []
<ide> // Valid that argument is a function.
<ide> fnType := reflect.TypeOf(fn)
<ide> if fnType.Kind() != reflect.Func {
<del> return fmt.Errorf("argument is %s, not function", fnType.Name)
<add> return fmt.Errorf("argument is %s, not function", fnType.Name())
<ide> }
<ide>
<ide> // Vaidate arguments numbers and types.
<ide> func validateFunctionSignature(fn interface{}, params []reflect.Type, returns []
<ide> }
<ide> for i, argType := range params {
<ide> if argType != fnType.In(i) {
<del> return fmt.Errorf("argument %d type should be %s, got %s", i, argType.Name, fnType.In(i).Name)
<add> return fmt.Errorf("argument %d type should be %s, got %s", i, argType.Name(), fnType.In(i).Name())
<ide> }
<ide> }
<ide>
<ide> func validateFunctionSignature(fn interface{}, params []reflect.Type, returns []
<ide> }
<ide> for i, retType := range returns {
<ide> if retType != fnType.Out(i) {
<del> return fmt.Errorf("return value %d type should be %s, got %s", i, retType.Name, fnType.Out(i).Name)
<add> return fmt.Errorf("return value %d type should be %s, got %s", i, retType.Name(), fnType.Out(i).Name())
<ide> }
<ide> }
<ide>
<ide><path>libnetwork/drivers/bridge/setup_ipv4.go
<ide> func setupBridgeIPv4(i *bridgeInterface) error {
<ide> }
<ide>
<ide> log.Debugf("Creating bridge interface %q with network %s", i.Config.BridgeName, bridgeIPv4)
<del> if err := netlink.AddrAdd(i.Link, &netlink.Addr{bridgeIPv4, ""}); err != nil {
<add> if err := netlink.AddrAdd(i.Link, &netlink.Addr{IPNet: bridgeIPv4}); err != nil {
<ide> return fmt.Errorf("Failed to add IPv4 address %s to bridge: %v", bridgeIPv4, err)
<ide> }
<ide>
<ide><path>libnetwork/drivers/bridge/setup_ipv6.go
<ide> func setupBridgeIPv6(i *bridgeInterface) error {
<ide> return fmt.Errorf("Unable to enable IPv6 addresses on bridge: %v", err)
<ide> }
<ide>
<del> if err := netlink.AddrAdd(i.Link, &netlink.Addr{bridgeIPv6, ""}); err != nil {
<add> if err := netlink.AddrAdd(i.Link, &netlink.Addr{IPNet: bridgeIPv6}); err != nil {
<ide> return fmt.Errorf("Failed to add IPv6 address %s to bridge: %v", bridgeIPv6, err)
<ide> }
<ide> | 3 |
Javascript | Javascript | add feature flags for scheduler experiments | b0b53ae2c1f38a7bf82b537dafb5f60f1bf14d0d | <ide><path>packages/scheduler/src/SchedulerFeatureFlags.js
<ide> export const enableSchedulerDebugging = false;
<ide> export const enableIsInputPending = false;
<ide> export const enableProfiling = false;
<add>export const enableIsInputPendingContinuous = false;
<add>export const frameYieldMs = 5;
<add>export const continuousYieldMs = 50;
<ide><path>packages/scheduler/src/forks/Scheduler.js
<ide> import {
<ide> enableSchedulerDebugging,
<ide> enableProfiling,
<add> enableIsInputPending,
<add> enableIsInputPendingContinuous,
<add> frameYieldMs,
<add> continuousYieldMs,
<ide> } from '../SchedulerFeatureFlags';
<ide>
<ide> import {push, pop, peek} from '../SchedulerMinHeap';
<ide> import {
<ide> startLoggingProfilingEvents,
<ide> } from '../SchedulerProfiling';
<ide>
<del>import {enableIsInputPending} from '../SchedulerFeatureFlags';
<del>
<ide> let getCurrentTime;
<ide> const hasPerformanceNow =
<ide> typeof performance === 'object' && typeof performance.now === 'function';
<ide> const isInputPending =
<ide> ? navigator.scheduling.isInputPending.bind(navigator.scheduling)
<ide> : null;
<ide>
<del>const continuousOptions = {includeContinuous: true};
<add>const continuousOptions = {includeContinuous: enableIsInputPendingContinuous};
<ide>
<ide> function advanceTimers(currentTime) {
<ide> // Check for tasks that are no longer delayed and add them to the queue.
<ide> let taskTimeoutID = -1;
<ide> // thread, like user events. By default, it yields multiple times per frame.
<ide> // It does not attempt to align with frame boundaries, since most tasks don't
<ide> // need to be frame aligned; for those that do, use requestAnimationFrame.
<del>// TODO: Make these configurable
<del>let frameInterval = 5;
<del>const continuousInputInterval = 50;
<add>let frameInterval = frameYieldMs;
<add>const continuousInputInterval = continuousYieldMs;
<ide> const maxInterval = 300;
<ide> let startTime = -1;
<ide>
<ide> function forceFrameRate(fps) {
<ide> frameInterval = Math.floor(1000 / fps);
<ide> } else {
<ide> // reset the framerate
<del> frameInterval = 5;
<add> frameInterval = frameYieldMs;
<ide> }
<ide> }
<ide>
<ide><path>packages/scheduler/src/forks/SchedulerFeatureFlags.www-dynamic.js
<ide> export const enableIsInputPending = __VARIANT__;
<ide> export const enableSchedulerDebugging = __VARIANT__;
<ide> export const enableProfiling = __VARIANT__;
<add>export const enableIsInputPendingContinuous = __VARIANT__;
<add>export const frameYieldMs = 5;
<add>export const continuousYieldMs = 50;
<ide><path>packages/scheduler/src/forks/SchedulerFeatureFlags.www.js
<ide> export const {
<ide> enableIsInputPending,
<ide> enableSchedulerDebugging,
<ide> enableProfiling: enableProfilingFeatureFlag,
<add> enableIsInputPendingContinuous,
<add> frameYieldMs,
<add> continuousYieldMs,
<ide> } = dynamicFeatureFlags;
<ide>
<ide> export const enableProfiling = __PROFILE__ && enableProfilingFeatureFlag; | 4 |
Go | Go | add fixedcidrv6 test | 882f4d7e741eb6f0c28dc74431162d5bb4c4c7ca | <ide><path>libnetwork/drivers/bridge/setup_fixedcidrv6.go
<ide> package bridge
<ide>
<ide> import (
<add> "fmt"
<add>
<ide> log "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/daemon/networkdriver/ipallocator"
<ide> )
<ide>
<ide> func SetupFixedCIDRv6(i *Interface) error {
<ide> log.Debugf("Using IPv6 subnet: %v", i.Config.FixedCIDRv6)
<del> return ipallocator.RegisterSubnet(i.Config.FixedCIDRv6, i.Config.FixedCIDRv6)
<add> if err := ipallocator.RegisterSubnet(i.Config.FixedCIDRv6, i.Config.FixedCIDRv6); err != nil {
<add> return fmt.Errorf("Setup FixedCIDRv6 failed for subnet %s in %s: %v", i.Config.FixedCIDRv6, i.Config.FixedCIDRv6, err)
<add> }
<add>
<add> return nil
<ide> }
<ide><path>libnetwork/drivers/bridge/setup_fixedcidrv6_test.go
<add>package bridge
<add>
<add>import (
<add> "net"
<add> "testing"
<add>
<add> "github.com/docker/docker/daemon/networkdriver/ipallocator"
<add> "github.com/docker/libnetwork"
<add>)
<add>
<add>func TestSetupFixedCIDRv6(t *testing.T) {
<add> defer libnetwork.SetupTestNetNS(t)()
<add>
<add> br := NewInterface(&Configuration{})
<add>
<add> _, br.Config.FixedCIDRv6, _ = net.ParseCIDR("2002:db8::/48")
<add> if err := SetupDevice(br); err != nil {
<add> t.Fatalf("Bridge creation failed: %v", err)
<add> }
<add> if err := SetupBridgeIPv4(br); err != nil {
<add> t.Fatalf("Assign IPv4 to bridge failed: %v", err)
<add> }
<add>
<add> if err := SetupBridgeIPv6(br); err != nil {
<add> t.Fatalf("Assign IPv4 to bridge failed: %v", err)
<add> }
<add>
<add> if err := SetupFixedCIDRv6(br); err != nil {
<add> t.Fatalf("Failed to setup bridge FixedCIDRv6: %v", err)
<add> }
<add>
<add> if ip, err := ipallocator.RequestIP(br.Config.FixedCIDRv6, nil); err != nil {
<add> t.Fatalf("Failed to request IP to allocator: %v", err)
<add> } else if expected := "2002:db8::1"; ip.String() != expected {
<add> t.Fatalf("Expected allocated IP %s, got %s", expected, ip)
<add> }
<add>} | 2 |
Go | Go | use pipes for save/load tests | b81105eaca56e7b22c97e24b7314419ee0a4f2a9 | <ide><path>integration-cli/docker_cli_save_load_test.go
<ide> import (
<ide>
<ide> // save a repo using gz compression and try to load it using stdout
<ide> func TestSaveXzAndLoadRepoStdout(t *testing.T) {
<del> tempDir, err := ioutil.TempDir("", "test-save-xz-gz-load-repo-stdout")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tempDir)
<del>
<del> tarballPath := filepath.Join(tempDir, "foobar-save-load-test.tar.xz.gz")
<del>
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> if err != nil {
<ide> func TestSaveXzAndLoadRepoStdout(t *testing.T) {
<ide> t.Fatalf("the repo should exist before saving it: %v %v", before, err)
<ide> }
<ide>
<del> saveCmdTemplate := `%v save %v | xz -c | gzip -c > %s`
<del> saveCmdFinal := fmt.Sprintf(saveCmdTemplate, dockerBinary, repoName, tarballPath)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> out, _, err = runCommandWithOutput(saveCmd)
<add> repoTarball, _, err := runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "save", repoName),
<add> exec.Command("xz", "-c"),
<add> exec.Command("gzip", "-c"))
<ide> if err != nil {
<ide> t.Fatalf("failed to save repo: %v %v", out, err)
<ide> }
<del>
<ide> deleteImages(repoName)
<ide>
<del> loadCmdFinal := fmt.Sprintf(`cat %s | docker load`, tarballPath)
<del> loadCmd := exec.Command("bash", "-c", loadCmdFinal)
<add> loadCmd := exec.Command(dockerBinary, "load")
<add> loadCmd.Stdin = strings.NewReader(repoTarball)
<ide> out, _, err = runCommandWithOutput(loadCmd)
<ide> if err == nil {
<ide> t.Fatalf("expected error, but succeeded with no error and output: %v", out)
<ide> func TestSaveXzAndLoadRepoStdout(t *testing.T) {
<ide> t.Fatalf("the repo should not exist: %v", after)
<ide> }
<ide>
<del> deleteContainer(cleanedContainerID)
<ide> deleteImages(repoName)
<ide>
<ide> logDone("load - save a repo with xz compression & load it using stdout")
<ide> }
<ide>
<ide> // save a repo using xz+gz compression and try to load it using stdout
<ide> func TestSaveXzGzAndLoadRepoStdout(t *testing.T) {
<del> tempDir, err := ioutil.TempDir("", "test-save-xz-gz-load-repo-stdout")
<del> if err != nil {
<del> t.Fatal(err)
<del> }
<del> defer os.RemoveAll(tempDir)
<del>
<del> tarballPath := filepath.Join(tempDir, "foobar-save-load-test.tar.xz.gz")
<del>
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true")
<ide> out, _, err := runCommandWithOutput(runCmd)
<ide> if err != nil {
<ide> func TestSaveXzGzAndLoadRepoStdout(t *testing.T) {
<ide> t.Fatalf("the repo should exist before saving it: %v %v", before, err)
<ide> }
<ide>
<del> saveCmdTemplate := `%v save %v | xz -c | gzip -c > %s`
<del> saveCmdFinal := fmt.Sprintf(saveCmdTemplate, dockerBinary, repoName, tarballPath)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> out, _, err = runCommandWithOutput(saveCmd)
<add> out, _, err = runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "save", repoName),
<add> exec.Command("xz", "-c"),
<add> exec.Command("gzip", "-c"))
<ide> if err != nil {
<ide> t.Fatalf("failed to save repo: %v %v", out, err)
<ide> }
<ide>
<ide> deleteImages(repoName)
<ide>
<del> loadCmdFinal := fmt.Sprintf(`cat %s | docker load`, tarballPath)
<del> loadCmd := exec.Command("bash", "-c", loadCmdFinal)
<add> loadCmd := exec.Command(dockerBinary, "load")
<add> loadCmd.Stdin = strings.NewReader(out)
<ide> out, _, err = runCommandWithOutput(loadCmd)
<ide> if err == nil {
<ide> t.Fatalf("expected error, but succeeded with no error and output: %v", out)
<ide> func TestSaveXzGzAndLoadRepoStdout(t *testing.T) {
<ide> func TestSaveSingleTag(t *testing.T) {
<ide> repoName := "foobar-save-single-tag-test"
<ide>
<del> tagCmdFinal := fmt.Sprintf("%v tag busybox:latest %v:latest", dockerBinary, repoName)
<del> tagCmd := exec.Command("bash", "-c", tagCmdFinal)
<add> tagCmd := exec.Command(dockerBinary, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName))
<add> defer deleteImages(repoName)
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> t.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<ide>
<del> idCmdFinal := fmt.Sprintf("%v images -q --no-trunc %v", dockerBinary, repoName)
<del> idCmd := exec.Command("bash", "-c", idCmdFinal)
<add> idCmd := exec.Command(dockerBinary, "images", "-q", "--no-trunc", repoName)
<ide> out, _, err := runCommandWithOutput(idCmd)
<ide> if err != nil {
<ide> t.Fatalf("failed to get repo ID: %s, %v", out, err)
<ide> }
<del>
<ide> cleanedImageID := stripTrailingCharacters(out)
<ide>
<del> saveCmdFinal := fmt.Sprintf("%v save %v:latest | tar t | grep -E '(^repositories$|%v)'", dockerBinary, repoName, cleanedImageID)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> if out, _, err = runCommandWithOutput(saveCmd); err != nil {
<add> out, _, err = runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", repoName)),
<add> exec.Command("tar", "t"),
<add> exec.Command("grep", "-E", fmt.Sprintf("(^repositories$|%v)", cleanedImageID)))
<add> if err != nil {
<ide> t.Fatalf("failed to save repo with image ID and 'repositories' file: %s, %v", out, err)
<ide> }
<ide>
<del> deleteImages(repoName)
<del>
<ide> logDone("save - save a specific image:tag")
<ide> }
<ide>
<ide> func TestSaveImageId(t *testing.T) {
<ide> repoName := "foobar-save-image-id-test"
<ide>
<del> tagCmdFinal := fmt.Sprintf("%v tag emptyfs:latest %v:latest", dockerBinary, repoName)
<del> tagCmd := exec.Command("bash", "-c", tagCmdFinal)
<add> tagCmd := exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName))
<add> defer deleteImages(repoName)
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> t.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<ide>
<del> idLongCmdFinal := fmt.Sprintf("%v images -q --no-trunc %v", dockerBinary, repoName)
<del> idLongCmd := exec.Command("bash", "-c", idLongCmdFinal)
<add> idLongCmd := exec.Command(dockerBinary, "images", "-q", "--no-trunc", repoName)
<ide> out, _, err := runCommandWithOutput(idLongCmd)
<ide> if err != nil {
<ide> t.Fatalf("failed to get repo ID: %s, %v", out, err)
<ide> }
<ide>
<ide> cleanedLongImageID := stripTrailingCharacters(out)
<ide>
<del> idShortCmdFinal := fmt.Sprintf("%v images -q %v", dockerBinary, repoName)
<del> idShortCmd := exec.Command("bash", "-c", idShortCmdFinal)
<add> idShortCmd := exec.Command(dockerBinary, "images", "-q", repoName)
<ide> out, _, err = runCommandWithOutput(idShortCmd)
<ide> if err != nil {
<ide> t.Fatalf("failed to get repo short ID: %s, %v", out, err)
<ide> }
<ide>
<ide> cleanedShortImageID := stripTrailingCharacters(out)
<ide>
<del> saveCmdFinal := fmt.Sprintf("%v save %v | tar t | grep %v", dockerBinary, cleanedShortImageID, cleanedLongImageID)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> if out, _, err = runCommandWithOutput(saveCmd); err != nil {
<del> t.Fatalf("failed to save repo with image ID: %s, %v", out, err)
<add> saveCmd := exec.Command(dockerBinary, "save", cleanedShortImageID)
<add> tarCmd := exec.Command("tar", "t")
<add> tarCmd.Stdin, err = saveCmd.StdoutPipe()
<add> if err != nil {
<add> t.Fatalf("cannot set stdout pipe for tar: %v", err)
<add> }
<add> grepCmd := exec.Command("grep", cleanedLongImageID)
<add> grepCmd.Stdin, err = tarCmd.StdoutPipe()
<add> if err != nil {
<add> t.Fatalf("cannot set stdout pipe for grep: %v", err)
<ide> }
<ide>
<del> deleteImages(repoName)
<add> if err = tarCmd.Start(); err != nil {
<add> t.Fatalf("tar failed with error: %v", err)
<add> }
<add> if err = saveCmd.Start(); err != nil {
<add> t.Fatalf("docker save failed with error: %v", err)
<add> }
<add> defer saveCmd.Wait()
<add> defer tarCmd.Wait()
<add>
<add> out, _, err = runCommandWithOutput(grepCmd)
<add>
<add> if err != nil {
<add> t.Fatalf("failed to save repo with image ID: %s, %v", out, err)
<add> }
<ide>
<ide> logDone("save - save a image by ID")
<ide> }
<ide> func TestSaveAndLoadRepoFlags(t *testing.T) {
<ide> }
<ide>
<ide> cleanedContainerID := stripTrailingCharacters(out)
<add> defer deleteContainer(cleanedContainerID)
<ide>
<ide> repoName := "foobar-save-load-test"
<ide>
<ide> func TestSaveAndLoadRepoFlags(t *testing.T) {
<ide> }
<ide>
<ide> commitCmd := exec.Command(dockerBinary, "commit", cleanedContainerID, repoName)
<add> deleteImages(repoName)
<ide> if out, _, err = runCommandWithOutput(commitCmd); err != nil {
<ide> t.Fatalf("failed to commit container: %s, %v", out, err)
<ide> }
<ide> func TestSaveAndLoadRepoFlags(t *testing.T) {
<ide> before, _, err := runCommandWithOutput(inspectCmd)
<ide> if err != nil {
<ide> t.Fatalf("the repo should exist before saving it: %s, %v", before, err)
<del> }
<ide>
<del> saveCmdTemplate := `%v save -o /tmp/foobar-save-load-test.tar %v`
<del> saveCmdFinal := fmt.Sprintf(saveCmdTemplate, dockerBinary, repoName)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> if out, _, err = runCommandWithOutput(saveCmd); err != nil {
<del> t.Fatalf("failed to save repo: %s, %v", out, err)
<ide> }
<ide>
<del> deleteImages(repoName)
<del>
<del> loadCmdFinal := `docker load -i /tmp/foobar-save-load-test.tar`
<del> loadCmd := exec.Command("bash", "-c", loadCmdFinal)
<del> if out, _, err = runCommandWithOutput(loadCmd); err != nil {
<del> t.Fatalf("failed to load repo: %s, %v", out, err)
<add> out, _, err = runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "save", repoName),
<add> exec.Command(dockerBinary, "load"))
<add> if err != nil {
<add> t.Fatalf("failed to save and load repo: %s, %v", out, err)
<ide> }
<ide>
<ide> inspectCmd = exec.Command(dockerBinary, "inspect", repoName)
<ide> func TestSaveAndLoadRepoFlags(t *testing.T) {
<ide> t.Fatalf("inspect is not the same after a save / load")
<ide> }
<ide>
<del> deleteContainer(cleanedContainerID)
<del> deleteImages(repoName)
<del>
<del> os.Remove("/tmp/foobar-save-load-test.tar")
<del>
<ide> logDone("save - save a repo using -o && load a repo using -i")
<ide> }
<ide>
<ide> func TestSaveMultipleNames(t *testing.T) {
<ide> repoName := "foobar-save-multi-name-test"
<ide>
<ide> // Make one image
<del> tagCmdFinal := fmt.Sprintf("%v tag emptyfs:latest %v-one:latest", dockerBinary, repoName)
<del> tagCmd := exec.Command("bash", "-c", tagCmdFinal)
<add> tagCmd := exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v-one:latest", repoName))
<ide> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<ide> t.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<ide> defer deleteImages(repoName + "-one")
<ide>
<ide> // Make two images
<del> tagCmdFinal = fmt.Sprintf("%v tag emptyfs:latest %v-two:latest", dockerBinary, repoName)
<del> tagCmd = exec.Command("bash", "-c", tagCmdFinal)
<del> if out, _, err := runCommandWithOutput(tagCmd); err != nil {
<add> tagCmd = exec.Command(dockerBinary, "tag", "emptyfs:latest", fmt.Sprintf("%v-two:latest", repoName))
<add> out, _, err := runCommandWithOutput(tagCmd)
<add> if err != nil {
<ide> t.Fatalf("failed to tag repo: %s, %v", out, err)
<ide> }
<ide> defer deleteImages(repoName + "-two")
<ide>
<del> saveCmdFinal := fmt.Sprintf("%v save %v-one %v-two:latest | tar xO repositories | grep -q -E '(-one|-two)'", dockerBinary, repoName, repoName)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> if out, _, err := runCommandWithOutput(saveCmd); err != nil {
<add> out, _, err = runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "save", fmt.Sprintf("%v-one", repoName), fmt.Sprintf("%v-two:latest", repoName)),
<add> exec.Command("tar", "xO", "repositories"),
<add> exec.Command("grep", "-q", "-E", "(-one|-two)"),
<add> )
<add> if err != nil {
<ide> t.Fatalf("failed to save multiple repos: %s, %v", out, err)
<ide> }
<ide>
<del> deleteImages(repoName)
<del>
<ide> logDone("save - save by multiple names")
<ide> }
<ide>
<ide> func TestSaveRepoWithMultipleImages(t *testing.T) {
<ide> t.Fatalf("failed to create a container: %v %v", out, err)
<ide> }
<ide> cleanedContainerID := stripTrailingCharacters(out)
<add> defer deleteContainer(cleanedContainerID)
<ide>
<ide> commitCmd := exec.Command(dockerBinary, "commit", cleanedContainerID, tag)
<ide> if out, _, err = runCommandWithOutput(commitCmd); err != nil {
<ide> t.Fatalf("failed to commit container: %v %v", out, err)
<ide> }
<ide> imageID := stripTrailingCharacters(out)
<del>
<del> deleteContainer(cleanedContainerID)
<ide> return imageID
<ide> }
<ide>
<ide> func TestSaveRepoWithMultipleImages(t *testing.T) {
<ide> tagBar := repoName + ":bar"
<ide>
<ide> idFoo := makeImage("busybox:latest", tagFoo)
<add> defer deleteImages(idFoo)
<ide> idBar := makeImage("busybox:latest", tagBar)
<add> defer deleteImages(idBar)
<ide>
<ide> deleteImages(repoName)
<ide>
<ide> // create the archive
<del> saveCmdFinal := fmt.Sprintf("%v save %v | tar t | grep 'VERSION' |cut -d / -f1", dockerBinary, repoName)
<del> saveCmd := exec.Command("bash", "-c", saveCmdFinal)
<del> out, _, err := runCommandWithOutput(saveCmd)
<add> out, _, err := runCommandPipelineWithOutput(
<add> exec.Command(dockerBinary, "save", repoName),
<add> exec.Command("tar", "t"),
<add> exec.Command("grep", "VERSION"),
<add> exec.Command("cut", "-d", "/", "-f1"))
<ide> if err != nil {
<ide> t.Fatalf("failed to save multiple images: %s, %v", out, err)
<ide> }
<ide> actual := strings.Split(stripTrailingCharacters(out), "\n")
<ide>
<ide> // make the list of expected layers
<del> historyCmdFinal := fmt.Sprintf("%v history -q --no-trunc %v", dockerBinary, "busybox:latest")
<del> historyCmd := exec.Command("bash", "-c", historyCmdFinal)
<del> out, _, err = runCommandWithOutput(historyCmd)
<add> out, _, err = runCommandWithOutput(exec.Command(dockerBinary, "history", "-q", "--no-trunc", "busybox:latest"))
<ide> if err != nil {
<ide> t.Fatalf("failed to get history: %s, %v", out, err)
<ide> }
<ide><path>integration-cli/utils.go
<ide> package main
<ide> import (
<ide> "bytes"
<ide> "encoding/json"
<add> "errors"
<ide> "fmt"
<ide> "io"
<ide> "math/rand"
<ide> func runCommand(cmd *exec.Cmd) (exitCode int, err error) {
<ide> return
<ide> }
<ide>
<add>func runCommandPipelineWithOutput(cmds ...*exec.Cmd) (output string, exitCode int, err error) {
<add> if len(cmds) < 2 {
<add> return "", 0, errors.New("pipeline does not have multiple cmds")
<add> }
<add>
<add> // connect stdin of each cmd to stdout pipe of previous cmd
<add> for i, cmd := range cmds {
<add> if i > 0 {
<add> prevCmd := cmds[i-1]
<add> cmd.Stdin, err = prevCmd.StdoutPipe()
<add> if err != nil {
<add> return "", 0, fmt.Errorf("cannot set stdout pipe for %s: %v", cmd.Path, err)
<add> }
<add> }
<add> }
<add>
<add> // start all cmds except the last
<add> for _, cmd := range cmds[:len(cmds)-1] {
<add> if err = cmd.Start(); err != nil {
<add> return "", 0, fmt.Errorf("starting %s failed with error: %v", cmd.Path, err)
<add> }
<add> }
<add>
<add> defer func() {
<add> // wait all cmds except the last to release their resources
<add> for _, cmd := range cmds[:len(cmds)-1] {
<add> cmd.Wait()
<add> }
<add> }()
<add>
<add> // wait on last cmd
<add> return runCommandWithOutput(cmds[len(cmds)-1])
<add>}
<add>
<ide> func logDone(message string) {
<ide> fmt.Printf("[PASSED]: %s\n", message)
<ide> } | 2 |
Ruby | Ruby | add tests for existing timestamp behaviour | eba75952498d5ea9cc2bc91ae231b3c9c7ffdb1f | <ide><path>activerecord/test/cases/insert_all_test.rb
<ide> require "models/author"
<ide> require "models/book"
<ide> require "models/cart"
<add>require "models/ship"
<ide> require "models/speedometer"
<ide> require "models/subscription"
<ide> require "models/subscriber"
<ide> def test_upsert_all_uses_given_updated_on_over_implicit_updated_on
<ide> assert_equal updated_on, Book.find(101).updated_on
<ide> end
<ide>
<add> def test_upsert_all_does_not_implicitly_set_timestamps_on_create_even_when_model_record_timestamps_is_true
<add> with_record_timestamps(Ship, true) do
<add> Ship.upsert_all [{ id: 101, name: "RSS Boaty McBoatface" }]
<add>
<add> ship = Ship.find(101)
<add> assert_nil ship.created_at
<add> assert_nil ship.created_on
<add> assert_nil ship.updated_at
<add> assert_nil ship.updated_on
<add> end
<add> end
<add>
<add> def test_upsert_all_does_not_implicitly_set_timestamps_on_create_when_model_record_timestamps_is_false
<add> with_record_timestamps(Ship, false) do
<add> Ship.upsert_all [{ id: 101, name: "RSS Boaty McBoatface" }]
<add>
<add> ship = Ship.find(101)
<add> assert_nil ship.created_at
<add> assert_nil ship.created_on
<add> assert_nil ship.updated_at
<add> assert_nil ship.updated_on
<add> end
<add> end
<add>
<add> def test_upsert_all_implicitly_sets_timestamps_on_update_when_model_record_timestamps_is_true
<add> skip unless supports_insert_on_duplicate_update?
<add>
<add> with_record_timestamps(Ship, true) do
<add> travel_to(Date.new(2016, 4, 17)) { Ship.create! id: 101, name: "RSS Boaty McBoatface" }
<add>
<add> Ship.upsert_all [{ id: 101, name: "RSS Sir David Attenborough" }]
<add>
<add> ship = Ship.find(101)
<add> assert_equal 2016, ship.created_at.year
<add> assert_equal 2016, ship.created_on.year
<add> assert_equal Time.now.year, ship.updated_at.year
<add> assert_equal Time.now.year, ship.updated_on.year
<add> end
<add> end
<add>
<add> def test_upsert_all_implicitly_sets_timestamps_on_update_even_when_model_record_timestamps_is_false
<add> skip unless supports_insert_on_duplicate_update?
<add>
<add> with_record_timestamps(Ship, false) do
<add> Ship.create! id: 101, name: "RSS Boaty McBoatface"
<add>
<add> Ship.upsert_all [{ id: 101, name: "RSS Sir David Attenborough" }]
<add>
<add> ship = Ship.find(101)
<add> assert_nil ship.created_at
<add> assert_nil ship.created_on
<add> assert_equal Time.now.year, ship.updated_at.year
<add> assert_equal Time.now.year, ship.updated_on.year
<add> end
<add> end
<add>
<ide> def test_insert_all_raises_on_unknown_attribute
<ide> assert_raise ActiveRecord::UnknownAttributeError do
<ide> Book.insert_all! [{ unknown_attribute: "Test" }]
<ide> def capture_log_output
<ide> ActiveRecord::Base.logger = old_logger
<ide> end
<ide> end
<add>
<add> def with_record_timestamps(model, value)
<add> original = model.record_timestamps
<add> model.record_timestamps = value
<add> yield
<add> ensure
<add> model.record_timestamps = original
<add> end
<ide> end | 1 |
Javascript | Javascript | add enableasyncsubtreeapi to host config | 26d70fd3347b7c730644d32b70c4fa752a29a610 | <ide><path>src/renderers/dom/fiber/ReactDOMFiber.js
<ide> var DOMRenderer = ReactFiberReconciler({
<ide> scheduleDeferredCallback: ReactDOMFrameScheduling.rIC,
<ide>
<ide> useSyncScheduling: !ReactDOMFeatureFlags.fiberAsyncScheduling,
<add> enableAsyncSubtreeAPI: ReactDOMFeatureFlags.enableAsyncSubtreeAPI,
<ide> });
<ide>
<ide> ReactGenericBatching.injection.injectFiberBatchedUpdates(
<ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js
<ide> export type HostConfig<T, P, I, TI, PI, C, CX, PL> = {
<ide> resetAfterCommit(): void,
<ide>
<ide> useSyncScheduling?: boolean,
<add> enableAsyncSubtreeAPI?: boolean,
<ide> };
<ide>
<ide> export type Reconciler<C, I, TI> = {
<ide><path>src/renderers/shared/fiber/ReactFiberScheduler.js
<ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>(
<ide> useSyncScheduling,
<ide> prepareForCommit,
<ide> resetAfterCommit,
<add> enableAsyncSubtreeAPI,
<ide> } = config;
<ide>
<ide> // The priority level to use when scheduling an update. We use NoWork to
<ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>(
<ide> function getPriorityContext(fiber: Fiber): PriorityLevel {
<ide> let priorityLevel = priorityContext;
<ide> if (priorityLevel === NoWork) {
<del> if (!useSyncScheduling || fiber.contextTag & AsyncUpdates) {
<add> if (
<add> !useSyncScheduling ||
<add> (enableAsyncSubtreeAPI === true && fiber.contextTag & AsyncUpdates)
<add> ) {
<ide> priorityLevel = LowPriority;
<ide> } else {
<ide> priorityLevel = SynchronousPriority; | 3 |
PHP | PHP | simplify pattern and fix mistakes | b05bc8d4eda7dc69586379f2423f730f0a37cc92 | <ide><path>src/Console/CommandCollection.php
<ide> public function add($name, $command)
<ide> "Cannot use '$class' for command '$name' it is not a subclass of Cake\Console\Shell or Cake\Console\Command."
<ide> );
<ide> }
<del> if (!preg_match('/^[\p{L}\p{N}\-_:.]+(?:(?: [\p{L}\p{N}\-_:.]+){1,2})?$/ui', $name)) {
<add> if (!preg_match('/^[^\s]+(?:(?: [^\s]+){1,2})?$/ui', $name)) {
<ide> throw new InvalidArgumentException(
<del> "The command name `{$name}` is invalid. " .
<del> 'Names must use only letters/numbers + punctuation characters and be 3 words or fewer.'
<add> "The command name `{$name}` is invalid. Names can only be a maximum of three words."
<ide> );
<ide> }
<ide>
<ide><path>tests/TestCase/Console/CommandCollectionTest.php
<ide> use Cake\Shell\I18nShell;
<ide> use Cake\Shell\RoutesShell;
<ide> use Cake\TestSuite\TestCase;
<add>use InvalidArgumentException;
<ide> use stdClass;
<ide> use TestApp\Command\DemoCommand;
<ide>
<ide> public function invalidNameProvider()
<ide> public function testAddCommandInvalidName($name)
<ide> {
<ide> $this->expectException(InvalidArgumentException::class);
<del> $this->expectExceptionMessage('Invalid command name');
<add> $this->expectExceptionMessage("The command name `$name` is invalid.");
<ide> $collection = new CommandCollection();
<ide> $collection->add($name, DemoCommand::class);
<ide> } | 2 |
Javascript | Javascript | add testid to newappscreen header component | 41f145fa47a338cb9daca0cc1d0e9dd0cc30b88a | <ide><path>Libraries/NewAppScreen/components/Header.js
<ide> const Header = (): Node => {
<ide> return (
<ide> <ImageBackground
<ide> accessibilityRole="image"
<add> testID="new-app-screen-header"
<ide> source={require('./logo.png')}
<ide> style={[
<ide> styles.background, | 1 |
PHP | PHP | fix doc string | 71dafc7034b61ea3a573aff827b3db0540123ab6 | <ide><path>src/Http/Cookie/CookieCollection.php
<ide> public static function createFromHeader(array $header)
<ide> /**
<ide> * Create a new collection from the cookies in a ServerRequest
<ide> *
<del> * @param \Psr\Http\Message\ServerRequestInterface $request The array of set-cookie header values.
<add> * @param \Psr\Http\Message\ServerRequestInterface $request The request to extract cookie data from
<ide> * @return static
<ide> */
<ide> public static function createFromServerRequest(ServerRequestInterface $request) | 1 |
Javascript | Javascript | replace csspropsaware branch | 272b8d69dcff771ffdb61ccd33c4e83eaea8ca50 | <ide><path>src/css.js
<ide> jQuery.extend({
<ide>
<ide> css: function( elem, name, extra ) {
<ide> // Make sure that we're working with the right name
<del> var ret, origName = jQuery.camelCase( name ),
<del> hooks = jQuery.cssHooks[ origName ];
<del>
<del> name = jQuery.cssProps[ origName ] || origName;
<add> var ret,
<add> hooks;
<add>
<add> name = jQuery.camelCase( name );
<add> hooks = jQuery.cssHooks[ name ];
<add> name = jQuery.cssProps[ name ] || name;
<add> // cssFloat needs a special treatment
<add> if ( name === 'cssFloat' ) {
<add> name = 'float';
<add> }
<ide>
<ide> // If a hook was provided get the computed value from there
<ide> if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
<ide> return ret;
<ide>
<ide> // Otherwise, if a way to get the computed value exists, use that
<ide> } else if ( curCSS ) {
<del> return curCSS( elem, name, origName );
<add> return curCSS( elem, name );
<ide> }
<ide> },
<ide>
<ide> jQuery(function() {
<ide> });
<ide>
<ide> if ( document.defaultView && document.defaultView.getComputedStyle ) {
<del> getComputedStyle = function( elem, newName, name ) {
<add> getComputedStyle = function( elem, name ) {
<ide> var ret, defaultView, computedStyle;
<ide>
<ide> name = name.replace( rupper, "-$1" ).toLowerCase();
<ide><path>test/unit/css.js
<ide> test("marginRight computed style (bug #3333)", function() {
<ide>
<ide> equals($div.css("marginRight"), "0px");
<ide> });
<add>
<add>test("jQuery.cssProps behavior, (bug #8402)", function() {
<add> var div = jQuery( "<div>" ).appendTo(document.body).css({
<add> position: "absolute",
<add> top: 0,
<add> left: 10
<add> });
<add> jQuery.cssProps.top = "left";
<add> equal( div.css("top"), "10px", "the fixed property is used when accessing the computed style");
<add> div.css("top", "100px");
<add> equal( div[0].style.left, "100px", "the fixed property is used when setting the style");
<add> // cleanup jQuery.cssProps
<add> jQuery.cssProps.top = undefined;
<add>});
<ide>\ No newline at end of file | 2 |
Go | Go | move chunkedencoding from integration | 7c574b9e9d62f14c8d73ea358a557a771dcd8d4d | <ide><path>integration-cli/docker_api_containers_test.go
<ide> import (
<ide> "encoding/json"
<ide> "io"
<ide> "net/http"
<add> "net/http/httputil"
<ide> "os"
<ide> "os/exec"
<ide> "strings"
<ide> func (s *DockerSuite) TestContainerApiDeleteRemoveVolume(c *check.C) {
<ide> c.Fatalf("expected to get ErrNotExist error, got %v", err)
<ide> }
<ide> }
<add>
<add>// Regression test for https://github.com/docker/docker/issues/6231
<add>func (s *DockerSuite) TestContainersApiChunkedEncoding(c *check.C) {
<add> out, _ := dockerCmd(c, "create", "-v", "/foo", "busybox", "true")
<add> id := strings.TrimSpace(out)
<add>
<add> conn, err := sockConn(time.Duration(10 * time.Second))
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add> client := httputil.NewClientConn(conn, nil)
<add> defer client.Close()
<add>
<add> bindCfg := strings.NewReader(`{"Binds": ["/tmp:/foo"]}`)
<add> req, err := http.NewRequest("POST", "/containers/"+id+"/start", bindCfg)
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add> req.Header.Set("Content-Type", "application/json")
<add> // This is a cheat to make the http request do chunked encoding
<add> // Otherwise (just setting the Content-Encoding to chunked) net/http will overwrite
<add> // https://golang.org/src/pkg/net/http/request.go?s=11980:12172
<add> req.ContentLength = -1
<add>
<add> resp, err := client.Do(req)
<add> if err != nil {
<add> c.Fatalf("error starting container with chunked encoding: %v", err)
<add> }
<add> resp.Body.Close()
<add> if resp.StatusCode != 204 {
<add> c.Fatalf("expected status code 204, got %d", resp.StatusCode)
<add> }
<add>
<add> out, err = inspectFieldJSON(id, "HostConfig.Binds")
<add> if err != nil {
<add> c.Fatal(err)
<add> }
<add>
<add> var binds []string
<add> if err := json.NewDecoder(strings.NewReader(out)).Decode(&binds); err != nil {
<add> c.Fatal(err)
<add> }
<add> if len(binds) != 1 {
<add> c.Fatalf("got unexpected binds: %v", binds)
<add> }
<add>
<add> expected := "/tmp:/foo"
<add> if binds[0] != expected {
<add> c.Fatalf("got incorrect bind spec, wanted %s, got: %s", expected, binds[0])
<add> }
<add>} | 1 |
Javascript | Javascript | slice the right buffer in _writeout | 684740c23200be67368fb1b225140e06c1fec295 | <ide><path>lib/net.js
<ide> Stream.prototype._writeOut = function (data, encoding) {
<ide> this._writeWatcher.start();
<ide>
<ide> // Slice out the data left.
<del> var leftOver = data.slice(off + bytesWritten, off + len);
<add> var leftOver = buffer.slice(off + bytesWritten, off + len);
<ide> leftOver.used = leftOver.length; // used the whole thing...
<ide>
<ide> // sys.error('data.used = ' + data.used); | 1 |
PHP | PHP | remove duplicate bootstrap reference | 26fce312c5e5d51ae32e97128a06599b7cfd2d21 | <ide><path>resources/views/app.blade.php
<ide> <title>Laravel</title>
<ide>
<ide> <!-- Bootstrap -->
<del> <link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet">
<ide> <link href="/css/app.css" rel="stylesheet">
<ide>
<ide> <!-- Fonts --> | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.