content_type
stringclasses 8
values | main_lang
stringclasses 7
values | message
stringlengths 1
50
| sha
stringlengths 40
40
| patch
stringlengths 52
962k
| file_count
int64 1
300
|
---|---|---|---|---|---|
Python | Python | add tests for it | cfe0038ff84ee027a1c536ce77d8c57f2049a4c9 | <ide><path>libcloud/compute/drivers/gce.py
<ide> def ex_get_disktype(self, name, zone=None):
<ide> response = self.connection.request(request_path, method='GET')
<ide>
<ide> if 'items' in response.object:
<add> # Aggregated response, zone not provided
<ide> data = None
<ide>
<del> # Aggregated response, zone not provided
<ide> for zone_item in response.object['items'].values():
<ide> for item in zone_item['diskTypes']:
<ide> if item['name'] == name:
<ide> def ex_get_disktype(self, name, zone=None):
<ide> data = response.object
<ide>
<ide> if not data:
<del> raise ValueError('Disk type with name %s not found' % (name))
<add> raise ValueError('Disk type with name "%s" not found' % (name))
<ide>
<ide> return self._to_disktype(data)
<ide>
<ide><path>libcloud/test/compute/test_gce.py
<ide> def test_create_node_req(self):
<ide> self.assertTrue(node_data['networkInterfaces'][0][
<ide> 'network'].startswith('https://'))
<ide>
<add> def test_create_node_location_not_provided(self):
<add> # location is not specified neither via datacenter constructor argument
<add> # nor via location method argument
<add> node_name = 'node-name'
<add> size = self.driver.ex_get_size('n1-standard-1')
<add> del size.extra['zone']
<add> image = self.driver.ex_get_image('debian-7')
<add> self.driver.zone = None
<add>
<add> expected_msg = 'Zone not provided'
<add> self.assertRaisesRegex(ValueError, expected_msg,
<add> self.driver.create_node,
<add> node_name, size, image)
<add>
<add> def test_create_node_location_not_provided_inferred_from_size(self):
<add> # test a scenario where node location is inferred from NodeSize zone attribute
<add> node_name = 'node-name'
<add> size = self.driver.ex_get_size('n1-standard-1')
<add> image = self.driver.ex_get_image('debian-7')
<add> zone = self.driver.ex_list_zones()[0]
<add> zone = self.driver.ex_get_zone('us-central1-a')
<add>
<add> self.driver.zone = None
<add> size.extra['zone'] = zone
<add>
<add> node = self.driver.create_node(node_name, size, image)
<add> self.assertTrue(node)
<add>
<ide> def test_create_node_network_opts(self):
<ide> node_name = 'node-name'
<ide> size = self.driver.ex_get_size('n1-standard-1')
<ide> def test_ex_get_disktype(self):
<ide> self.assertEqual(disktype.extra['valid_disk_size'], '10GB-10240GB')
<ide> self.assertEqual(disktype.extra['default_disk_size_gb'], '100')
<ide>
<add> # zone not set
<add> disktype_name = 'pd-ssd'
<add> disktype = self.driver.ex_get_disktype(disktype_name)
<add> self.assertEqual(disktype.name, disktype_name)
<add>
<ide> def test_ex_get_zone(self):
<ide> zone_name = 'us-central1-b'
<ide> zone = self.driver.ex_get_zone(zone_name) | 2 |
Javascript | Javascript | fix lints for 'script' dir | 3e7b532c0bd1339a8e853c8b6d6610f669730dae | <ide><path>script/lib/check-chromedriver-version.js
<ide> 'use strict';
<ide>
<ide> const buildMetadata = require('../package.json');
<del>const CONFIG = require('../config');
<ide> const semver = require('semver');
<add>const chromedriverMetadataPath = require('electron-chromedriver/package.json');
<add>const mksnapshotMetadataPath = require('electron-mksnapshot/package.json');
<ide>
<ide> module.exports = function() {
<ide> // Chromedriver should be at least v9.0.0
<ide> // Mksnapshot should be at least v9.0.2
<ide> const chromedriverVer = buildMetadata.dependencies['electron-chromedriver'];
<ide> const mksnapshotVer = buildMetadata.dependencies['electron-mksnapshot'];
<del> const chromedriverActualVer = require('electron-chromedriver/package.json').version;
<del> const mksnapshotActualVer = require('electron-mksnapshot/package.json').version;
<add> const chromedriverActualVer = chromedriverMetadataPath.version;
<add> const mksnapshotActualVer = mksnapshotMetadataPath.version;
<ide>
<ide> // Always use caret on electron-chromedriver so that it can pick up the best minor/patch versions
<ide> if (!chromedriverVer.startsWith('^')) {
<ide><path>script/redownload-electron-bins.js
<ide> const { spawn } = require('child_process');
<ide> const electronVersion = require('./config').appMetadata.electronVersion;
<ide>
<ide> if (process.env.ELECTRON_CUSTOM_VERSION !== electronVersion) {
<add> const electronEnv = process.env.ELECTRON_CUSTOM_VERSION;
<ide> console.info(
<ide> `env var ELECTRON_CUSTOM_VERSION is not set,\n` +
<ide> `or doesn't match electronVersion in ../package.json.\n` +
<del> `(is: "${process.env.ELECTRON_CUSTOM_VERSION}", wanted: "${electronVersion}").\n` +
<add> `(is: "${electronEnv}", wanted: "${electronVersion}").\n` +
<ide> `Setting, and re-downloading chromedriver and mksnapshot.\n`
<ide> );
<ide>
<ide> process.env.ELECTRON_CUSTOM_VERSION = electronVersion;
<del> const downloadChromedriverPath = require.resolve('electron-chromedriver/download-chromedriver.js');
<del> const downloadMksnapshotPath = require.resolve('electron-mksnapshot/download-mksnapshot.js');
<add> const downloadChromedriverPath = require.resolve(
<add> 'electron-chromedriver/download-chromedriver.js'
<add> );
<add> const downloadMksnapshotPath = require.resolve(
<add> 'electron-mksnapshot/download-mksnapshot.js'
<add> );
<ide> const downloadChromedriver = spawn('node', [downloadChromedriverPath]);
<ide> const downloadMksnapshot = spawn('node', [downloadMksnapshotPath]);
<ide> var exitStatus;
<ide>
<del> downloadChromedriver.on('close', (code) => {
<add> downloadChromedriver.on('close', code => {
<ide> if (code === 0) {
<del> exitStatus = "success";
<add> exitStatus = 'success';
<ide> } else {
<del> exitStatus = "error";
<add> exitStatus = 'error';
<ide> }
<ide>
<del> console.info(`info: Done re-downloading chromedriver. Status: ${exitStatus}`);
<add> console.info(
<add> `info: Done re-downloading chromedriver. Status: ${exitStatus}`
<add> );
<ide> });
<ide>
<del> downloadMksnapshot.on('close', (code) => {
<add> downloadMksnapshot.on('close', code => {
<ide> if (code === 0) {
<del> exitStatus = "success";
<add> exitStatus = 'success';
<ide> } else {
<del> exitStatus = "error";
<add> exitStatus = 'error';
<ide> }
<ide>
<ide> console.info(`info: Done re-downloading mksnapshot. Status: ${exitStatus}`);
<ide> });
<ide> } else {
<del> console.info('info: env var "ELECTRON_CUSTOM_VERSION" is already set correctly.\n(No need to re-download chromedriver or mksnapshot). Skipping.\n');
<add> console.info(
<add> 'info: env var "ELECTRON_CUSTOM_VERSION" is already set correctly.\n(No need to re-download chromedriver or mksnapshot). Skipping.\n'
<add> );
<ide> } | 2 |
PHP | PHP | fix exception message | b856355d162e35b249bf05e85ec454f289e59928 | <ide><path>src/Illuminate/Foundation/Testing/WithoutMiddleware.php
<ide> public function disableMiddlewareForAllTests()
<ide> if (method_exists($this, 'withoutMiddleware')) {
<ide> $this->withoutMiddleware();
<ide> } else {
<del> throw new Exception('Unable to disable middleware. CrawlerTrait not used.');
<add> throw new Exception('Unable to disable middleware. MakesHttpRequests trait not used.');
<ide> }
<ide> }
<ide> } | 1 |
Ruby | Ruby | use method from hash | ee2979b90539ef1e4fd13513c6b3f3ffd00244e2 | <ide><path>activesupport/lib/active_support/hash_with_indifferent_access.rb
<ide> def reverse_merge(other_hash)
<ide>
<ide> # Same semantics as +reverse_merge+ but modifies the receiver in-place.
<ide> def reverse_merge!(other_hash)
<del> replace(reverse_merge(other_hash))
<add> super(self.class.new(other_hash))
<ide> end
<ide>
<ide> # Replaces the contents of this hash with other_hash. | 1 |
Ruby | Ruby | use native chmod to set write permissions | 53b95c62604fb902425c93aa01d68dc873067635 | <ide><path>Library/Homebrew/cask/quarantine.rb
<ide> def propagate(from: nil, to: nil)
<ide>
<ide> resolved_paths = Pathname.glob(to/"**/*", File::FNM_DOTMATCH)
<ide>
<del> FileUtils.chmod "u+w", resolved_paths
<add> system_command!("/bin/chmod", args: ["-R", "u+w", to])
<ide>
<ide> quarantiner = system_command("/usr/bin/xargs",
<ide> args: [ | 1 |
Javascript | Javascript | await getcachedpathstatus in specs | d8985c8175f25e6f40026c07980846c68d4da935 | <ide><path>spec/git-repository-async-spec.js
<ide> fdescribe('GitRepositoryAsync-js', () => {
<ide> fs.writeFileSync(modifiedPath, 'making this path modified')
<ide> await repo.refreshStatus()
<ide>
<del> expect(repo.getCachedPathStatus(cleanPath)).toBeUndefined()
<del> expect(repo.isStatusNew(repo.getCachedPathStatus(newPath))).toBeTruthy()
<del> expect(repo.isStatusModified(repo.getCachedPathStatus(modifiedPath))).toBeTruthy()
<add> expect(await repo.getCachedPathStatus(cleanPath)).toBeUndefined()
<add> expect(repo.isStatusNew(await repo.getCachedPathStatus(newPath))).toBeTruthy()
<add> expect(repo.isStatusModified(await repo.getCachedPathStatus(modifiedPath))).toBeTruthy()
<ide> })
<ide> })
<ide> | 1 |
PHP | PHP | allow string content on fake file creation | 181db51595d546cbd24b3fac0cb276255e147286 | <ide><path>src/Illuminate/Http/Testing/File.php
<ide> public function __construct($name, $tempFile)
<ide> * Create a new fake file.
<ide> *
<ide> * @param string $name
<del> * @param int $kilobytes
<add> * @param string|int $kilobytes
<ide> * @return \Illuminate\Http\Testing\File
<ide> */
<ide> public static function create($name, $kilobytes = 0)
<ide><path>src/Illuminate/Http/Testing/FileFactory.php
<ide> class FileFactory
<ide> * Create a new fake file.
<ide> *
<ide> * @param string $name
<del> * @param int $kilobytes
<add> * @param string|int $kilobytes
<ide> * @return \Illuminate\Http\Testing\File
<ide> */
<ide> public function create($name, $kilobytes = 0)
<ide> {
<del> return tap(new File($name, tmpfile()), function ($file) use ($kilobytes) {
<del> $file->sizeToReport = $kilobytes * 1024;
<add> $tmp = tmpfile();
<add>
<add> if (is_string($kilobytes)) {
<add> file_put_contents($tmp, $kilobytes);
<add> }
<add>
<add> return tap(new File($name, $tmp), function ($file) use ($kilobytes) {
<add> $file->sizeToReport = is_string($kilobytes) ? fstat($tmp)['size'] : ($kilobytes * 1024);
<ide> });
<ide> }
<ide> | 2 |
Java | Java | fix evaltagtests with locales other than english | 261a863e8f61504a335dcfdbe1ed9f01d7e1fcbc | <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/tags/EvalTagTests.java
<ide>
<ide> import java.math.BigDecimal;
<ide> import java.util.HashMap;
<add>import java.util.Locale;
<ide> import java.util.Map;
<ide>
<ide> import javax.servlet.jsp.tagext.Tag;
<ide> import org.springframework.core.env.MapPropertySource;
<ide> import org.springframework.format.annotation.NumberFormat;
<ide> import org.springframework.format.annotation.NumberFormat.Style;
<add>import org.springframework.format.number.PercentFormatter;
<ide> import org.springframework.format.support.FormattingConversionServiceFactoryBean;
<ide> import org.springframework.mock.web.test.MockHttpServletResponse;
<ide> import org.springframework.mock.web.test.MockPageContext;
<ide> public void testPrintNullAsEmptyString() throws Exception {
<ide> }
<ide>
<ide> public void testPrintFormattedScopedAttributeResult() throws Exception {
<add> PercentFormatter formatter = new PercentFormatter();
<ide> tag.setExpression("bean.formattable");
<ide> int action = tag.doStartTag();
<ide> assertEquals(Tag.EVAL_BODY_INCLUDE, action);
<ide> action = tag.doEndTag();
<ide> assertEquals(Tag.EVAL_PAGE, action);
<del> assertEquals("25%", ((MockHttpServletResponse) context.getResponse()).getContentAsString());
<add> assertEquals(formatter.print(new BigDecimal(".25"), Locale.getDefault()),
<add> ((MockHttpServletResponse) context.getResponse()).getContentAsString());
<ide> }
<ide>
<ide> public void testPrintHtmlEscapedAttributeResult() throws Exception { | 1 |
Python | Python | remove neural turing machine, unviable in 0.3.0 | 54c025ac26c81fc1cc58adf0be8f3d596ec73a3a | <ide><path>examples/neural_turing_machine_copy.py
<del>from __future__ import absolute_import
<del>from __future__ import print_function
<del>import numpy as np
<del>np.random.seed(123)
<del>import matplotlib.pyplot as plt
<del>
<del>from theano import function
<del>
<del>from keras.models import Sequential
<del>from keras.layers.core import TimeDistributedDense, Activation
<del>from keras.layers.recurrent import LSTM
<del>from keras.optimizers import Adam
<del>from keras.utils import generic_utils
<del>
<del>from keras.layers.ntm import NeuralTuringMachine as NTM
<del>
<del>"""
<del>Copy Problem defined in Graves et. al [0]
<del>
<del>Training data is made of sequences with length 1 to 20.
<del>Test data are sequences of length 100.
<del>The model is tested every 500 weight updates.
<del>After about 3500 updates, the accuracy jumps from around 50% to >90%.
<del>
<del>Estimated compile time: 12 min
<del>Estimated time to train Neural Turing Machine and 3 layer LSTM on an NVidia GTX 680: 2h
<del>
<del>[0]: http://arxiv.org/pdf/1410.5401v2.pdf
<del>"""
<del>
<del>batch_size = 100
<del>
<del>h_dim = 128
<del>n_slots = 128
<del>m_length = 20
<del>input_dim = 8
<del>lr = 1e-3
<del>clipvalue = 10
<del>
<del>##### Neural Turing Machine ######
<del>
<del>ntm = NTM(h_dim, n_slots=n_slots, m_length=m_length, shift_range=3,
<del> inner_rnn='lstm', return_sequences=True, input_dim=input_dim)
<del>model = Sequential()
<del>model.add(ntm)
<del>model.add(TimeDistributedDense(input_dim))
<del>model.add(Activation('sigmoid'))
<del>
<del>sgd = Adam(lr=lr, clipvalue=clipvalue)
<del>model.compile(loss='binary_crossentropy', optimizer=sgd)
<del>
<del># LSTM - Run this for comparison
<del>
<del>sgd2 = Adam(lr=lr, clipvalue=clipvalue)
<del>lstm = Sequential()
<del>lstm.add(LSTM(input_dim=input_dim, output_dim=h_dim*2, return_sequences=True))
<del>lstm.add(LSTM(output_dim=h_dim*2, return_sequences=True))
<del>lstm.add(LSTM(output_dim=h_dim*2, return_sequences=True))
<del>lstm.add(TimeDistributedDense(input_dim))
<del>lstm.add(Activation('sigmoid'))
<del>
<del>lstm.compile(loss='binary_crossentropy', optimizer=sgd)
<del>
<del>###### DATASET ########
<del>
<del>def get_sample(batch_size=128, n_bits=8, max_size=20, min_size=1):
<del> # generate samples with random length
<del> inp = np.zeros((batch_size, 2*max_size-1, n_bits))
<del> out = np.zeros((batch_size, 2*max_size-1, n_bits))
<del> sw = np.zeros((batch_size, 2*max_size-1, 1))
<del> for i in range(batch_size):
<del> t = np.random.randint(low=min_size, high=max_size)
<del> x = np.random.uniform(size=(t, n_bits)) > .5
<del> for j,f in enumerate(x.sum(axis=-1)): # remove fake flags
<del> if f>=n_bits:
<del> x[j, :] = 0.
<del> del_flag = np.ones((1, n_bits))
<del> inp[i, :t+1] = np.concatenate([x, del_flag], axis=0)
<del> out[i, t+1:(2*t+1)] = x
<del> sw[i, t+1:(2*t+1)] = 1
<del> return inp, out, sw
<del>
<del>def show_pattern(inp, out, sw, file_name='ntm_output.png'):
<del> ''' Helper function to visualize results '''
<del> plt.figure(figsize=(10, 10))
<del> plt.subplot(131)
<del> plt.imshow(inp>.5)
<del> plt.subplot(132)
<del> plt.imshow(out>.5)
<del> plt.subplot(133)
<del> plt.imshow(sw>.5)
<del> plt.savefig(file_name)
<del> plt.close()
<del>
<del># Show data example:
<del>inp, out, sw = get_sample(1, 8, 20)
<del>
<del>plt.subplot(131)
<del>plt.title('input')
<del>plt.imshow(inp[0], cmap='gray')
<del>plt.subplot(132)
<del>plt.title('desired')
<del>plt.imshow(out[0], cmap='gray')
<del>plt.subplot(133)
<del>plt.title('sample_weight')
<del>plt.imshow(sw[0], cmap='gray')
<del>
<del># training uses sequences of length 1 to 20. Test uses series of length 100.
<del>def test_model(model, file_name, min_size=100):
<del> I, V, sw = get_sample(batch_size=500, n_bits=input_dim, max_size=min_size+1, min_size=min_size)
<del> Y = np.asarray(model.predict(I, batch_size=100) > .5).astype('float64')
<del> acc = (V[:, -min_size:, :] == Y[:, -min_size:, :]).mean() * 100
<del> show_pattern(Y[0], V[0], sw[0], file_name)
<del> return acc
<del>
<del>##### TRAIN ######
<del>nb_epoch = 4000
<del>progbar = generic_utils.Progbar(nb_epoch)
<del>for e in range(nb_epoch):
<del> I, V, sw = get_sample(n_bits=input_dim, max_size=20, min_size=1, batch_size=100)
<del>
<del> loss1 = model.train_on_batch(I, V, sample_weight=sw)
<del> loss2 = lstm.train_on_batch(I, V, sample_weight=sw)
<del>
<del> progbar.add(1, values=[("NTM", loss1), ("LSTM", loss2)])
<del>
<del> if e % 500 == 0:
<del> print("")
<del> acc1 = test_model(model, 'ntm.png')
<del> acc2 = test_model(lstm, 'lstm.png')
<del> print("NTM test acc: {}".format(acc1))
<del> print("LSTM test acc: {}".format(acc2))
<del>
<del>##### VISUALIZATION #####
<del>X = model.get_input()
<del>Y = ntm.get_full_output()[0:3] # (memory over time, read_vectors, write_vectors)
<del>F = function([X], Y, allow_input_downcast=True)
<del>
<del>inp, out, sw = get_sample(1, 8, 21, 20)
<del>mem, read, write = F(inp.astype('float32'))
<del>Y = model.predict(inp)
<del>
<del>plt.figure(figsize=(15, 12))
<del>
<del>plt.subplot(221)
<del>plt.imshow(write[0])
<del>plt.xlabel('memory location')
<del>plt.ylabel('time')
<del>plt.title('write')
<del>
<del>plt.subplot(222)
<del>plt.imshow(read[0])
<del>plt.title('read')
<del>
<del>plt.subplot(223)
<del>plt.title('desired')
<del>plt.imshow(out[0])
<del>
<del>plt.subplot(224)
<del>plt.imshow(Y[0]>.5)
<del>plt.title('output')
<del>
<del>plt.figure(figsize=(15, 10))
<del>plt.subplot(325)
<del>plt.ylabel('time')
<del>plt.xlabel('location')
<del>plt.title('memory evolving in time (avg value per location)')
<del>plt.imshow(mem[0].mean(axis=-1))
<ide><path>keras/layers/ntm.py
<del>import numpy as np
<del>from scipy.linalg import circulant
<del>
<del>from .. import backend as K
<del>import theano
<del>import theano.tensor as T
<del>floatX = theano.config.floatX
<del>
<del>from keras.layers.recurrent import Recurrent, GRU, LSTM
<del>from keras.utils.theano_utils import shared_zeros, alloc_zeros_matrix, shared_scalar
<del>tol = 1e-4
<del>
<del>
<del>def _update_controller(self, inp, h_tm1, M, mask):
<del> """ Update inner RNN controler
<del> We have to update the inner RNN inside the Neural Turing Machine, this
<del> is an almost literal copy of keras.layers.recurrent.GRU and
<del> keras.layers.recurrent.LSTM see these clases for further details.
<del> """
<del> x = T.concatenate([inp, M], axis=-1)
<del> # get inputs
<del> if self.inner_rnn == 'gru':
<del> x_z = T.dot(x, self.rnn.W_z) + self.rnn.b_z
<del> x_r = T.dot(x, self.rnn.W_r) + self.rnn.b_r
<del> x_h = T.dot(x, self.rnn.W_h) + self.rnn.b_h
<del>
<del> elif self.inner_rnn == 'lstm':
<del> xi = T.dot(x, self.rnn.W_i) + self.rnn.b_i
<del> xf = T.dot(x, self.rnn.W_f) + self.rnn.b_f
<del> xc = T.dot(x, self.rnn.W_c) + self.rnn.b_c
<del> xo = T.dot(x, self.rnn.W_o) + self.rnn.b_o
<del>
<del> elif self.inner_rnn == 'simple':
<del> x = T.dot(x, self.rnn.W) + self.rnn.b
<del>
<del> # update state
<del> if self.inner_rnn == 'gru':
<del> h = self.rnn._step(x_z, x_r, x_h, 1., h_tm1[0],
<del> self.rnn.U_z,
<del> self.rnn.U_r,
<del> self.rnn.U_h)
<del> h = mask[:, None] * h + (1-mask[:, None])*h_tm1[0]
<del> h = (h, )
<del>
<del> elif self.inner_rnn == 'lstm':
<del> h = self.rnn._step(xi, xf, xo, xc, 1.,
<del> h_tm1[1], h_tm1[0],
<del> self.rnn.U_i, self.rnn.U_f,
<del> self.rnn.U_o, self.rnn.U_c)
<del> h = h[::-1]
<del> h = tuple([mask[:, None]*h[i] +
<del> (1-mask[:, None])*h_tm1[i] for i in range(len(h))])
<del>
<del> elif self.inner_rnn == 'simple':
<del> h = self.rnn._step(x, 1, h_tm1[0], self.rnn.U)
<del> h = mask[:, None] * h + (1-mask[:, None])*h_tm1[0]
<del> h = (h, )
<del>
<del> return h
<del>
<del>
<del>def _circulant(leng, n_shifts):
<del> """ Generate circulant copies of a vector.
<del> This will generate a tensor with `n_shifts` of rotated versions the
<del> identity matrix. When this tensor is multiplied by a vector
<del> the result are `n_shifts` shifted versions of that vector. Since
<del> everything is done with inner products, this operation is differentiable.
<del>
<del> Paramters:
<del> ----------
<del> leng: int > 0, number of memory locations
<del> n_shifts: int > 0, number of allowed shifts (if 1, no shift)
<del>
<del> Returns:
<del> --------
<del> shift operation, a tensor with dimensions (n_shifts, leng, leng)
<del> """
<del> eye = np.eye(leng)
<del> shifts = range(n_shifts//2, -n_shifts//2, -1)
<del> C = np.asarray([np.roll(eye, s, axis=1) for s in shifts])
<del> return theano.shared(C.astype(theano.config.floatX))
<del>
<del>
<del>def _renorm(x):
<del> return x / (x.sum(axis=1, keepdims=True))
<del>
<del>
<del>def _softmax(x):
<del> wt = x.flatten(ndim=2)
<del> w = T.nnet.softmax(wt)
<del> return w.reshape(x.shape) # T.clip(s, 0, 1)
<del>
<del>
<del>def _cosine_distance(M, k):
<del> dot = (M * k[:, None, :]).sum(axis=-1)
<del> nM = T.sqrt((M**2).sum(axis=-1))
<del> nk = T.sqrt((k**2).sum(axis=-1, keepdims=True))
<del> return dot / (nM * nk)
<del>
<del>
<del>class NeuralTuringMachine(Recurrent):
<del> """ Neural Turing Machines
<del>
<del> Parameters:
<del> -----------
<del> shift_range: int, number of available shifts, ex. if 3, avilable shifts are
<del> (-1, 0, 1)
<del> n_slots: number of memory locations
<del> m_length: memory length at each location
<del> inner_rnn: str, supported values are 'gru' and 'lstm'
<del> output_dim: hidden state size (RNN controller output_dim)
<del>
<del> Known issues and TODO:
<del> ----------------------
<del> Theano may complain when n_slots == 1.
<del> Add multiple reading and writing heads.
<del>
<del> """
<del> def __init__(self, output_dim, n_slots, m_length, shift_range=3,
<del> inner_rnn='gru', truncate_gradient=-1, return_sequences=False,
<del> init='glorot_uniform', inner_init='orthogonal',
<del> input_dim=None, input_length=None, **kwargs):
<del> if K._BACKEND != 'theano':
<del> raise Exception('NeuralTuringMachine is only available for Theano for the time being. ' +
<del> 'It will be adapted to TensorFlow soon.')
<del> self.output_dim = output_dim
<del> self.n_slots = n_slots
<del> self.m_length = m_length
<del> self.shift_range = shift_range
<del> self.init = init
<del> self.inner_init = inner_init
<del> self.inner_rnn = inner_rnn
<del> self.return_sequences = return_sequences
<del> self.truncate_gradient = truncate_gradient
<del>
<del> self.input_dim = input_dim
<del> self.input_length = input_length
<del> if self.input_dim:
<del> kwargs['input_shape'] = (self.input_length, self.input_dim)
<del> super(NeuralTuringMachine, self).__init__(**kwargs)
<del>
<del> def build(self):
<del> input_leng, input_dim = self.input_shape[1:]
<del> self.input = T.tensor3()
<del>
<del> if self.inner_rnn == 'gru':
<del> self.rnn = GRU(
<del> input_dim=input_dim+self.m_length,
<del> input_length=input_leng,
<del> output_dim=self.output_dim, init=self.init,
<del> inner_init=self.inner_init)
<del> elif self.inner_rnn == 'lstm':
<del> self.rnn = LSTM(
<del> input_dim=input_dim+self.m_length,
<del> input_length=input_leng,
<del> output_dim=self.output_dim, init=self.init,
<del> inner_init=self.inner_init)
<del> else:
<del> raise ValueError('this inner_rnn is not implemented yet.')
<del>
<del> self.rnn.build()
<del>
<del> # initial memory, state, read and write vecotrs
<del> self.M = theano.shared((.001*np.ones((1,)).astype(floatX)))
<del> self.init_h = shared_zeros((self.output_dim))
<del> self.init_wr = self.rnn.init((self.n_slots,))
<del> self.init_ww = self.rnn.init((self.n_slots,))
<del>
<del> # write
<del> self.W_e = self.rnn.init((self.output_dim, self.m_length)) # erase
<del> self.b_e = shared_zeros((self.m_length))
<del> self.W_a = self.rnn.init((self.output_dim, self.m_length)) # add
<del> self.b_a = shared_zeros((self.m_length))
<del>
<del> # get_w parameters for reading operation
<del> self.W_k_read = self.rnn.init((self.output_dim, self.m_length))
<del> self.b_k_read = self.rnn.init((self.m_length, ))
<del> self.W_c_read = self.rnn.init((self.output_dim, 3)) # 3 = beta, g, gamma see eq. 5, 7, 9 in Graves et. al 2014
<del> self.b_c_read = shared_zeros((3))
<del> self.W_s_read = self.rnn.init((self.output_dim, self.shift_range))
<del> self.b_s_read = shared_zeros((self.shift_range))
<del>
<del> # get_w parameters for writing operation
<del> self.W_k_write = self.rnn.init((self.output_dim, self.m_length))
<del> self.b_k_write = self.rnn.init((self.m_length, ))
<del> self.W_c_write = self.rnn.init((self.output_dim, 3)) # 3 = beta, g, gamma see eq. 5, 7, 9
<del> self.b_c_write = shared_zeros((3))
<del> self.W_s_write = self.rnn.init((self.output_dim, self.shift_range))
<del> self.b_s_write = shared_zeros((self.shift_range))
<del>
<del> self.C = _circulant(self.n_slots, self.shift_range)
<del>
<del> self.params = self.rnn.params + [
<del> self.W_e, self.b_e,
<del> self.W_a, self.b_a,
<del> self.W_k_read, self.b_k_read,
<del> self.W_c_read, self.b_c_read,
<del> self.W_s_read, self.b_s_read,
<del> self.W_k_write, self.b_k_write,
<del> self.W_s_write, self.b_s_write,
<del> self.W_c_write, self.b_c_write,
<del> self.M,
<del> self.init_h, self.init_wr, self.init_ww]
<del>
<del> if self.inner_rnn == 'lstm':
<del> self.init_c = shared_zeros((self.output_dim))
<del> self.params = self.params + [self.init_c, ]
<del>
<del> def _read(self, w, M):
<del> return (w[:, :, None]*M).sum(axis=1)
<del>
<del> def _write(self, w, e, a, M, mask):
<del> Mtilda = M * (1 - w[:, :, None]*e[:, None, :])
<del> Mout = Mtilda + w[:, :, None]*a[:, None, :]
<del> return mask[:, None, None]*Mout + (1-mask[:, None, None])*M
<del>
<del> def _get_content_w(self, beta, k, M):
<del> num = beta[:, None] * _cosine_distance(M, k)
<del> return _softmax(num)
<del>
<del> def _get_location_w(self, g, s, C, gamma, wc, w_tm1, mask):
<del> wg = g[:, None] * wc + (1-g[:, None])*w_tm1
<del> Cs = (C[None, :, :, :] * wg[:, None, None, :]).sum(axis=3)
<del> wtilda = (Cs * s[:, :, None]).sum(axis=1)
<del> wout = _renorm(wtilda ** gamma[:, None])
<del> return mask[:, None] * wout + (1-mask[:, None])*w_tm1
<del>
<del> def _get_controller_output(self, h, W_k, b_k, W_c, b_c, W_s, b_s):
<del> k = T.tanh(T.dot(h, W_k) + b_k) # + 1e-6
<del> c = T.dot(h, W_c) + b_c
<del> beta = T.nnet.relu(c[:, 0]) + 1e-6
<del> g = T.nnet.sigmoid(c[:, 1])
<del> gamma = T.nnet.relu(c[:, 2]) + 1
<del> s = T.nnet.softmax(T.dot(h, W_s) + b_s)
<del> return k, beta, g, gamma, s
<del>
<del> def _get_initial_states(self, batch_size):
<del> init_M = self.M.dimshuffle(0, 'x', 'x').repeat(
<del> batch_size, axis=0).repeat(self.n_slots, axis=1).repeat(
<del> self.m_length, axis=2)
<del>
<del> init_h = self.init_h.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
<del> init_wr = self.init_wr.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
<del> init_ww = self.init_ww.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
<del> if self.inner_rnn == 'lstm':
<del> init_c = self.init_c.dimshuffle(('x', 0)).repeat(batch_size, axis=0)
<del> return init_M, T.nnet.softmax(init_wr), T.nnet.softmax(init_ww), init_h, init_c
<del> else:
<del> return init_M, T.nnet.softmax(init_wr), T.nnet.softmax(init_ww), init_h
<del>
<del> def _step(self, x, mask, M_tm1, wr_tm1, ww_tm1, *args):
<del> # read
<del> if self.inner_rnn == 'lstm':
<del> h_tm1 = args[0:2][::-1] # (cell_tm1, h_tm1)
<del> else:
<del> h_tm1 = args[0:1] # (h_tm1, )
<del> k_read, beta_read, g_read, gamma_read, s_read = self._get_controller_output(
<del> h_tm1[-1], self.W_k_read, self.b_k_read, self.W_c_read, self.b_c_read,
<del> self.W_s_read, self.b_s_read)
<del> wc_read = self._get_content_w(beta_read, k_read, M_tm1)
<del> wr_t = self._get_location_w(g_read, s_read, self.C, gamma_read,
<del> wc_read, wr_tm1, mask)
<del> M_read = self._read(wr_t, M_tm1)
<del>
<del> # update controller
<del> h_t = _update_controller(self, x, h_tm1, M_read, mask)
<del>
<del> # write
<del> k_write, beta_write, g_write, gamma_write, s_write = self._get_controller_output(
<del> h_t[-1], self.W_k_write, self.b_k_write, self.W_c_write,
<del> self.b_c_write, self.W_s_write, self.b_s_write)
<del> wc_write = self._get_content_w(beta_write, k_write, M_tm1)
<del> ww_t = self._get_location_w(g_write, s_write, self.C, gamma_write,
<del> wc_write, ww_tm1, mask)
<del> e = T.nnet.sigmoid(T.dot(h_t[-1], self.W_e) + self.b_e)
<del> a = T.tanh(T.dot(h_t[-1], self.W_a) + self.b_a)
<del> M_t = self._write(ww_t, e, a, M_tm1, mask)
<del>
<del> return (M_t, wr_t, ww_t) + h_t
<del>
<del> def get_output(self, train=False):
<del> outputs = self.get_full_output(train)
<del>
<del> if self.return_sequences:
<del> return outputs[-1]
<del> else:
<del> return outputs[-1][:, -1]
<del>
<del> @property
<del> def output_shape(self):
<del> input_shape = self.input_shape
<del> if self.return_sequences:
<del> return input_shape[0], input_shape[1], self.output_dim
<del> else:
<del> return input_shape[0], self.output_dim
<del>
<del> def get_full_output(self, train=False):
<del> """
<del> This method is for research and visualization purposes. Use it as:
<del> X = model.get_input() # full model
<del> Y = ntm.get_output() # this layer
<del> F = theano.function([X], Y, allow_input_downcast=True)
<del> [memory, read_address, write_address, rnn_state] = F(x)
<del>
<del> if inner_rnn == "lstm" use it as:
<del> [memory, read_address, write_address, rnn_cell, rnn_state] = F(x)
<del>
<del> """
<del> X = self.get_input(train)
<del> padded_mask = self.get_padded_shuffled_mask(train, X, pad=1)[:, :, 0]
<del> X = X.dimshuffle((1, 0, 2))
<del>
<del> init_states = self._get_initial_states(X.shape[1])
<del> outputs, updates = theano.scan(self._step,
<del> sequences=[X, padded_mask],
<del> outputs_info=init_states,
<del> non_sequences=self.params,
<del> truncate_gradient=self.truncate_gradient)
<del>
<del> out = [outputs[0].dimshuffle((1, 0, 2, 3)),
<del> outputs[1].dimshuffle(1, 0, 2),
<del> outputs[2].dimshuffle((1, 0, 2)),
<del> outputs[3].dimshuffle((1, 0, 2))]
<del> if self.inner_rnn == 'lstm':
<del> out + [outputs[4].dimshuffle((1, 0, 2))]
<del> return out | 2 |
Python | Python | update typo in `compute_output_shape` | ff614c0bfb3987903f95cf191a03514eed495795 | <ide><path>keras/engine/base_layer.py
<ide> def compute_output_shape(self, input_shape):
<ide> instead of an integer.
<ide>
<ide> Returns:
<del> An input shape tuple.
<add> An output shape tuple.
<ide> """
<ide> if tf.executing_eagerly():
<ide> # In this case we build the model first in order to do shape | 1 |
PHP | PHP | add skips to bake related tests | 8333cc7fd7764057bfc886a815f08e4d7de56749 | <ide><path>lib/Cake/Test/TestCase/Console/Command/Task/ModelTaskTest.php
<ide> <?php
<ide> /**
<del> * ModelTaskTest file
<del> *
<del> * Test Case for test generation shell task
<del> *
<del> * PHP 5
<del> *
<ide> * CakePHP : Rapid Development Framework (http://cakephp.org)
<ide> * Copyright 2005-2012, Cake Software Foundation, Inc.
<ide> *
<ide> *
<ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc.
<ide> * @link http://cakephp.org CakePHP Project
<del> * @package Cake.Test.Case.Console.Command.Task
<ide> * @since CakePHP v 1.2.6
<ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
<ide> */
<ide> /**
<ide> * ModelTaskTest class
<ide> *
<del> * @package Cake.Test.Case.Console.Command.Task
<add> * @package Cake.Test.Case.Console.Command.Task
<ide> */
<ide> class ModelTaskTest extends TestCase {
<ide>
<ide> class ModelTaskTest extends TestCase {
<ide> * @return void
<ide> */
<ide> public function setUp() {
<add> $this->markTestIncomplete('Model baking will not work as models do not work.');
<add>
<ide> parent::setUp();
<ide> $out = $this->getMock('Cake\Console\ConsoleOutput', array(), array(), '', false);
<ide> $in = $this->getMock('Cake\Console\ConsoleInput', array(), array(), '', false);
<ide><path>lib/Cake/Test/TestCase/Console/Command/Task/ViewTaskTest.php
<ide> class ViewTaskTest extends TestCase {
<ide> */
<ide> public function setUp() {
<ide> parent::setUp();
<add> $this->markTestIncomplete('Model baking will not work as models do not work.');
<add>
<ide> $out = $this->getMock('Cake\Console\ConsoleOutput', array(), array(), '', false);
<ide> $in = $this->getMock('Cake\Console\ConsoleInput', array(), array(), '', false);
<ide> | 2 |
Text | Text | add instruction for internal links | be5fe6d4b71b91d4c5df6d96dfba8a80b7a0e6ab | <ide><path>docs/_sidebar.md
<ide> - [Work on localized client web app](how-to-work-on-localized-client-webapp.md)
<ide> - [Work on Cypress tests](how-to-add-cypress-tests.md)
<ide> - [Work on video challenges](how-to-help-with-video-challenges.md)
<del> - [Work on the docs theme](how-to-work-on-the-docs-theme.md)
<add> - [Work on documentation](how-to-work-on-the-docs-theme.md)
<ide> - [Work on the component library](how-to-work-on-the-component-library.md)
<ide> - **Additional Guides**
<ide> - [Test translations locally](how-to-test-translations-locally.md)
<ide><path>docs/how-to-translate-files.md
<ide> Translating our contributing documentation is a similar flow to translating our
<ide> > [!NOTE]
<ide> > Our contributing documentation is powered by `docsify`, and we have special parsing for message boxes like this one. If you see strings that start with `[!NOTE]`, `[!WARNING]`, or `[!TIP]`, these words should NOT be translated.
<ide>
<add>### How to translate documentation with internal links
<add>
<add>When you work on translating contributing documentation, watch out for internal links targeting a different section of the documentation.
<add>
<add>Make sure to replace the id of the target section (the part after `#`) with the id on the translated document. For example, it will look like this in Japanese:
<add>
<add>Before translation
<add>
<add>```
<add>// in HTML
<add><a href="target-file-name.md#target-section-heading-id">Link text</a>
<add><a href="#target-section-heading-id">Link text</a>
<add>
<add>// in Markdown
<add>[Link text](target-file-name.md#target-section-heading-id)
<add>[Link text](#target-section-heading-id)
<add>```
<add>
<add>After translation
<add>
<add>```
<add>// in HTML
<add><a href="target-file-name.md#翻訳後の-id">翻訳後のリンクテキスト</a>
<add><a href="#翻訳後の-id">翻訳後のリンクテキスト</a>
<add>
<add>// in Markdown
<add>[翻訳後のリンクテキスト](target-file-name.md#翻訳後の-id)
<add>[翻訳後のリンクテキスト](#翻訳後の-id)
<add>```
<add>
<add>The actual files in docs are written in Markdown, but they will appear as HTML tags on Crowdin.
<add>
<add>You can find out how `docsify` converts a string in your language into an id by looking into the translated pages. If the translation is not deployed yet, you can preview it by [running the docs site locally](how-to-work-on-the-docs-theme.md#serving-the-documentation-site-locally).
<add>
<add>You can learn more about [internal links in our docs here](how-to-work-on-the-docs-theme.md#how-to-create-an-internal-link).
<add>
<ide> ## Translate the LearnToCode RPG
<ide>
<ide> The LearnToCode RPG runs on Ren'Py, which uses special syntax for translated strings: (See [Ren'Py Text documentation](https://www.renpy.org/doc/html/text.html))
<ide><path>docs/how-to-work-on-the-docs-theme.md
<del># How to work on the docs theme
<add># How to work on documentation
<add>
<add>## Work on the docs content
<add>
<add>To work on the contributing guidelines, you can edit or add files in the `docs` directory [available here](https://github.com/freeCodeCamp/freeCodeCamp/tree/main/docs). When your changes are merged, it will be made available automatically at the documentation site.
<add>
<add>### How to create an internal link
<add>
<add>If you want to create a link targeting a different section of the contributing guidelines, follow this format:
<add>
<add>```md
<add>[Link text](target-file-name.md#target-section-heading-id)
<add>
<add>// If the target section is within the same page, you can omit the file name
<add>[Link text](#target-section-heading-id)
<add>```
<add>
<add>Make sure you include the file extension (`.md`). Don't specify the full URL or append `/` before the file name.
<add>
<add>This is necessary to make these links work for the translated version of the document. Otherwise, they will redirect to the English version of the page regardless of the language.
<add>
<add>#### Translating docs with internal links
<add>
<add>When you work on translating docs on Crowdin, make sure to replace the `#target-section-heading-id` with the id on the translated document. [Learn more about translating docs here](how-to-translate-files.md#translate-documentation).
<add>
<add>## Work on the docs theme
<ide>
<ide> > [!NOTE]
<ide> > A quick reminder that you do not need to setup anything for working on the content for the documentation site.
<ide> >
<del>> To work on the contributing guidelines, you can edit or add files in the `docs` directory [available here](https://github.com/freeCodeCamp/freeCodeCamp/tree/main/docs). When your changes are merged, it will be made available automatically at the documentation site.
<add>> To work on the contributing guidelines, see [work on the docs content](#work-on-the-docs-content) section.
<ide>
<del>## Structure of the docs website
<add>### Structure of the docs website
<ide>
<ide> The site is generated using [`docsify`](https://docsify.js.org), and served using GitHub pages.
<ide>
<ide> Typically you would not need to change any configuration or build the site local
<ide> - The homepage is generated from the [`_coverpage.md`](_coverpage.md).
<ide> - the sidebar navigation is generated from [`_sidebar.md`](_sidebar.md).
<ide>
<del>## Serving the documentation site locally
<add>### Serving the documentation site locally
<ide>
<ide> Clone freeCodeCamp:
<ide>
<ide> docsify serve docs
<ide>
<ide> Alternatively, if you have installed freeCodeCamp locally (see the local setup guide), we bundled the CLI with the development tools so you can run any of the below commands as needed from the root of the repo:
<ide>
<del>### Serve and launch the documentation site only
<add>#### Serve and launch the documentation site only
<ide>
<ide> ```console
<ide> npm run docs:serve
<ide> ```
<ide>
<del>### Serve the documentation site alongside freeCodeCamp locally:
<add>#### Serve the documentation site alongside freeCodeCamp locally:
<ide>
<ide> ```console
<ide> npm run develop | 3 |
Ruby | Ruby | fix the error message on generate mailer | f3cf76d32dfce86a29c6e8a417841beb8c0a04a2 | <ide><path>railties/lib/rails_generator/generators/components/mailer/mailer_generator.rb
<ide> def manifest
<ide> File.join('app/views', class_path, file_name, "#{action}.rhtml"),
<ide> :assigns => { :action => action }
<ide> m.template "fixture.rhtml",
<del> "test/fixtures/#{table_name}/#{action}",
<ide> File.join('test/fixtures', class_path, table_name, action),
<ide> :assigns => { :action => action }
<ide> end | 1 |
Javascript | Javascript | extend urlsearchparams constructor | cc48f21c8335da8d74b8b82f0314c872c027ab14 | <ide><path>lib/internal/url.js
<ide> function defineIDLClass(proto, classStr, obj) {
<ide> }
<ide>
<ide> class URLSearchParams {
<del> constructor(init = '') {
<del> if (init instanceof URLSearchParams) {
<del> const childParams = init[searchParams];
<del> this[searchParams] = childParams.slice();
<add> // URL Standard says the default value is '', but as undefined and '' have
<add> // the same result, undefined is used to prevent unnecessary parsing.
<add> // Default parameter is necessary to keep URLSearchParams.length === 0 in
<add> // accordance with Web IDL spec.
<add> constructor(init = undefined) {
<add> if (init === null || init === undefined) {
<add> this[searchParams] = [];
<add> } else if (typeof init === 'object') {
<add> const method = init[Symbol.iterator];
<add> if (method === this[Symbol.iterator]) {
<add> // While the spec does not have this branch, we can use it as a
<add> // shortcut to avoid having to go through the costly generic iterator.
<add> const childParams = init[searchParams];
<add> this[searchParams] = childParams.slice();
<add> } else if (method !== null && method !== undefined) {
<add> if (typeof method !== 'function') {
<add> throw new TypeError('Query pairs must be iterable');
<add> }
<add>
<add> // sequence<sequence<USVString>>
<add> // Note: per spec we have to first exhaust the lists then process them
<add> const pairs = [];
<add> for (const pair of init) {
<add> if (typeof pair !== 'object' ||
<add> typeof pair[Symbol.iterator] !== 'function') {
<add> throw new TypeError('Each query pair must be iterable');
<add> }
<add> pairs.push(Array.from(pair));
<add> }
<add>
<add> this[searchParams] = [];
<add> for (const pair of pairs) {
<add> if (pair.length !== 2) {
<add> throw new TypeError('Each query pair must be a name/value tuple');
<add> }
<add> this[searchParams].push(String(pair[0]), String(pair[1]));
<add> }
<add> } else {
<add> // record<USVString, USVString>
<add> this[searchParams] = [];
<add> for (const key of Object.keys(init)) {
<add> const value = String(init[key]);
<add> this[searchParams].push(key, value);
<add> }
<add> }
<ide> } else {
<add> // USVString
<ide> init = String(init);
<ide> if (init[0] === '?') init = init.slice(1);
<ide> initSearchParams(this, init);
<ide><path>test/parallel/test-whatwg-url-searchparams-constructor.js
<ide> assert.strictEqual(params + '', 'a=b');
<ide> params = new URLSearchParams(params);
<ide> assert.strictEqual(params + '', 'a=b');
<ide>
<del>// URLSearchParams constructor, empty.
<add>// URLSearchParams constructor, no arguments
<add>params = new URLSearchParams();
<add>assert.strictEqual(params.toString(), '');
<add>
<ide> assert.throws(() => URLSearchParams(), TypeError,
<ide> 'Calling \'URLSearchParams\' without \'new\' should throw.');
<del>// assert.throws(() => new URLSearchParams(DOMException.prototype), TypeError);
<del>assert.throws(() => {
<del> new URLSearchParams({
<del> toString() { throw new TypeError('Illegal invocation'); }
<del> });
<del>}, TypeError);
<add>
<add>// URLSearchParams constructor, undefined and null as argument
<add>params = new URLSearchParams(undefined);
<add>assert.strictEqual(params.toString(), '');
<add>params = new URLSearchParams(null);
<add>assert.strictEqual(params.toString(), '');
<add>
<add>// URLSearchParams constructor, empty string as argument
<ide> params = new URLSearchParams('');
<del>assert.notStrictEqual(params, null, 'constructor returned non-null value.');
<add>// eslint-disable-next-line no-restricted-properties
<add>assert.notEqual(params, null, 'constructor returned non-null value.');
<ide> // eslint-disable-next-line no-proto
<ide> assert.strictEqual(params.__proto__, URLSearchParams.prototype,
<ide> 'expected URLSearchParams.prototype as prototype.');
<add>
<add>// URLSearchParams constructor, {} as argument
<ide> params = new URLSearchParams({});
<del>// assert.strictEqual(params + '', '%5Bobject+Object%5D=');
<del>assert.strictEqual(params + '', '%5Bobject%20Object%5D=');
<add>assert.strictEqual(params + '', '');
<ide>
<ide> // URLSearchParams constructor, string.
<ide> params = new URLSearchParams('a=b');
<ide> params = new URLSearchParams('a=b%f0%9f%92%a9c');
<ide> assert.strictEqual(params.get('a'), 'b\uD83D\uDCA9c');
<ide> params = new URLSearchParams('a%f0%9f%92%a9b=c');
<ide> assert.strictEqual(params.get('a\uD83D\uDCA9b'), 'c');
<add>
<add>// Constructor with sequence of sequences of strings
<add>params = new URLSearchParams([]);
<add>// eslint-disable-next-line no-restricted-properties
<add>assert.notEqual(params, null, 'constructor returned non-null value.');
<add>params = new URLSearchParams([['a', 'b'], ['c', 'd']]);
<add>assert.strictEqual(params.get('a'), 'b');
<add>assert.strictEqual(params.get('c'), 'd');
<add>assert.throws(() => new URLSearchParams([[1]]),
<add> /^TypeError: Each query pair must be a name\/value tuple$/);
<add>assert.throws(() => new URLSearchParams([[1, 2, 3]]),
<add> /^TypeError: Each query pair must be a name\/value tuple$/);
<add>
<add>[
<add> // Further confirmation needed
<add> // https://github.com/w3c/web-platform-tests/pull/4523#discussion_r98337513
<add> // {
<add> // input: {'+': '%C2'},
<add> // output: [[' ', '\uFFFD']],
<add> // name: 'object with +'
<add> // },
<add> {
<add> input: {c: 'x', a: '?'},
<add> output: [['c', 'x'], ['a', '?']],
<add> name: 'object with two keys'
<add> },
<add> {
<add> input: [['c', 'x'], ['a', '?']],
<add> output: [['c', 'x'], ['a', '?']],
<add> name: 'array with two keys'
<add> }
<add>].forEach((val) => {
<add> const params = new URLSearchParams(val.input);
<add> assert.deepStrictEqual(Array.from(params), val.output,
<add> `Construct with ${val.name}`);
<add>});
<add>
<add>// Custom [Symbol.iterator]
<add>params = new URLSearchParams();
<add>params[Symbol.iterator] = function *() {
<add> yield ['a', 'b'];
<add>};
<add>const params2 = new URLSearchParams(params);
<add>assert.strictEqual(params2.get('a'), 'b');
<add>
<add>assert.throws(() => new URLSearchParams({ [Symbol.iterator]: 42 }),
<add> /^TypeError: Query pairs must be iterable$/);
<add>assert.throws(() => new URLSearchParams([{}]),
<add> /^TypeError: Each query pair must be iterable$/);
<add>assert.throws(() => new URLSearchParams(['a']),
<add> /^TypeError: Each query pair must be iterable$/);
<add>assert.throws(() => new URLSearchParams([{ [Symbol.iterator]: 42 }]),
<add> /^TypeError: Each query pair must be iterable$/); | 2 |
Javascript | Javascript | add detail view for network inspector | d12d07597751939829e574928bd6243fd08adff1 | <ide><path>Libraries/Inspector/NetworkOverlay.js
<ide> const ListView = require('ListView');
<ide> const React = require('React');
<ide> const RecyclerViewBackedScrollView = require('RecyclerViewBackedScrollView');
<add>const ScrollView = require('ScrollView');
<ide> const StyleSheet = require('StyleSheet');
<ide> const Text = require('Text');
<ide> const TouchableHighlight = require('TouchableHighlight');
<ide> class NetworkOverlay extends React.Component {
<ide> _listViewDataSource: ListView.DataSource;
<ide> _listView: ?ListView;
<ide> _listViewHighlighted: bool;
<del> _listViewHeight: ?number;
<add> _listViewHeight: number;
<add> _scrollView: ?ScrollView;
<add> _detailViewItems: Array<Array<ReactElement<any>>>;
<ide> _listViewOnLayout: (event: Event) => void;
<del> _captureRequestList: (listRef: ?ListView) => void;
<add> _captureRequestListView: (listRef: ?ListView) => void;
<add> _captureDetailScrollView: (scrollRef: ?ScrollView) => void;
<ide> _renderRow: (
<ide> rowData: NetworkRequestInfo,
<ide> sectionID: number,
<ide> rowID: number,
<ide> highlightRow: (sectionID: number, rowID: number) => void,
<ide> ) => ReactElement<any>;
<ide> _renderScrollComponent: (props: Object) => ReactElement<any>;
<add> _closeButtonClicked: () => void;
<ide>
<ide> state: {
<ide> dataSource: ListView.DataSource,
<add> newDetailInfo: bool,
<add> detailRowID: ?number,
<ide> };
<ide>
<ide> constructor(props: Object) {
<ide> super(props);
<ide> this._requests = [];
<add> this._detailViewItems = [];
<ide> this._listViewDataSource =
<ide> new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
<ide> this.state = {
<ide> dataSource: this._listViewDataSource.cloneWithRows([]),
<add> newDetailInfo: false,
<add> detailRowID: null,
<ide> };
<ide> this._listViewHighlighted = false;
<del> this._listViewHeight = null;
<del> this._captureRequestList = this._captureRequestList.bind(this);
<add> this._listViewHeight = 0;
<add> this._captureRequestListView = this._captureRequestListView.bind(this);
<add> this._captureDetailScrollView = this._captureDetailScrollView.bind(this);
<ide> this._listViewOnLayout = this._listViewOnLayout.bind(this);
<ide> this._renderRow = this._renderRow.bind(this);
<ide> this._renderScrollComponent = this._renderScrollComponent.bind(this);
<add> this._closeButtonClicked = this._closeButtonClicked.bind(this);
<ide> }
<ide>
<ide> _enableInterception(): void {
<ide> class NetworkOverlay extends React.Component {
<ide> // so that we can distinguish different xhr objects in callbacks.
<ide> xhr._index = this._requests.length;
<ide> const _xhr: NetworkRequestInfo = {'method': method, 'url': url};
<del> this._requests = this._requests.concat(_xhr);
<add> this._requests.push(_xhr);
<add> this._detailViewItems.push([]);
<add> this._genDetailViewItem(xhr._index);
<ide> this.setState(
<ide> {dataSource: this._listViewDataSource.cloneWithRows(this._requests)},
<ide> this._scrollToBottom(),
<ide> );
<ide> }.bind(this));
<ide>
<ide> XHRInterceptor.setRequestHeaderCallback(function(header, value, xhr) {
<del> if (!this._requests[xhr._index].requestHeaders) {
<del> this._requests[xhr._index].requestHeaders = {};
<add> const networkInfo = this._requests[xhr._index];
<add> if (!networkInfo.requestHeaders) {
<add> networkInfo.requestHeaders = {};
<ide> }
<del> this._requests[xhr._index].requestHeaders[header] = value;
<add> networkInfo.requestHeaders[header] = value;
<add> this._genDetailViewItem(xhr._index);
<ide> }.bind(this));
<ide>
<ide> XHRInterceptor.setSendCallback(function(data, xhr) {
<ide> this._requests[xhr._index].dataSent = data;
<add> this._genDetailViewItem(xhr._index);
<ide> }.bind(this));
<ide>
<ide> XHRInterceptor.setHeaderReceivedCallback(
<ide> function(type, size, responseHeaders, xhr) {
<del> this._requests[xhr._index].responseContentType = type;
<del> this._requests[xhr._index].responseSize = size;
<del> this._requests[xhr._index].responseHeaders = responseHeaders;
<add> const networkInfo = this._requests[xhr._index];
<add> networkInfo.responseContentType = type;
<add> networkInfo.responseSize = size;
<add> networkInfo.responseHeaders = responseHeaders;
<add> this._genDetailViewItem(xhr._index);
<ide> }.bind(this)
<ide> );
<ide>
<ide> class NetworkOverlay extends React.Component {
<ide> responseType,
<ide> xhr,
<ide> ) {
<del> this._requests[xhr._index].status = status;
<del> this._requests[xhr._index].timeout = timeout;
<del> this._requests[xhr._index].response = response;
<del> this._requests[xhr._index].responseURL = responseURL;
<del> this._requests[xhr._index].responseType = responseType;
<add> const networkInfo = this._requests[xhr._index];
<add> networkInfo.status = status;
<add> networkInfo.timeout = timeout;
<add> networkInfo.response = response;
<add> networkInfo.responseURL = responseURL;
<add> networkInfo.responseType = responseType;
<add> this._genDetailViewItem(xhr._index);
<ide> }.bind(this)
<ide> );
<ide>
<ide> class NetworkOverlay extends React.Component {
<ide> }
<ide>
<ide> _scrollToBottom(): void {
<del> if (!!this._listView && !!this._listViewHeight) {
<add> if (this._listView) {
<ide> const scrollResponder = this._listView.getScrollResponder();
<ide> if (scrollResponder) {
<ide> const scrollY = Math.max(
<ide> class NetworkOverlay extends React.Component {
<ide> }
<ide> }
<ide>
<del> _captureRequestList(listRef: ?ListView): void {
<add> _captureRequestListView(listRef: ?ListView): void {
<ide> this._listView = listRef;
<ide> }
<ide>
<ide> class NetworkOverlay extends React.Component {
<ide> }
<ide>
<ide> /**
<del> * TODO: When item is pressed, should pop up another view to show details.
<add> * Popup a scrollView to dynamically show detailed information of
<add> * the request, when pressing a row in the network flow listView.
<ide> */
<ide> _pressRow(rowID: number): void {
<ide> this._listViewHighlighted = true;
<add> this.setState(
<add> {detailRowID: rowID},
<add> this._scrollToTop(),
<add> );
<add> }
<add>
<add> _scrollToTop(): void {
<add> if (this._scrollView) {
<add> this._scrollView.scrollTo({
<add> y: 0,
<add> animated: false,
<add> });
<add> }
<add> }
<add>
<add> _captureDetailScrollView(scrollRef: ?ScrollView): void {
<add> this._scrollView = scrollRef;
<add> }
<add>
<add> _closeButtonClicked() {
<add> this.setState({detailRowID: null});
<add> }
<add>
<add> _getStringByValue(value: any): string {
<add> if (value === undefined) {
<add> return 'undefined';
<add> }
<add> if (typeof value === 'object') {
<add> return JSON.stringify(value);
<add> }
<add> if (typeof value === 'string' && value.length > 500) {
<add> return String(value).substr(0, 500).concat('\n***TRUNCATED TO 500 CHARACTERS***');
<add> }
<add> return value;
<add> }
<add>
<add> /**
<add> * Generate a list of views containing network request information for
<add> * a XHR object, to be shown in the detail scrollview. This function
<add> * should be called every time there is a new update of the XHR object,
<add> * in order to show network request/response information in real time.
<add> */
<add> _genDetailViewItem(index: number): void {
<add> this._detailViewItems[index] = [];
<add> const detailViewItem = this._detailViewItems[index];
<add> const requestItem = this._requests[index];
<add> for (let key in requestItem) {
<add> detailViewItem.push(
<add> <View style={styles.detailViewRow} key={key}>
<add> <Text style={[styles.detailViewText, styles.detailKeyCellView]}>
<add> {key}
<add> </Text>
<add> <Text style={[styles.detailViewText, styles.detailValueCellView]}>
<add> {this._getStringByValue(requestItem[key])}
<add> </Text>
<add> </View>
<add> );
<add> }
<add> // Re-render if this network request is showing in the detail view.
<add> if (this.state.detailRowID != null && this.state.detailRowID == index) {
<add> this.setState({newDetailInfo: true});
<add> }
<ide> }
<ide>
<ide> render() {
<ide> return (
<ide> <View style={styles.container}>
<del> {this._requests.length > 0 &&
<del> <View>
<add> {this.state.detailRowID != null &&
<add> <TouchableHighlight
<add> style={styles.closeButton}
<add> onPress={this._closeButtonClicked}>
<add> <View>
<add> <Text style={styles.clostButtonText}>v</Text>
<add> </View>
<add> </TouchableHighlight>}
<add> {this.state.detailRowID != null &&
<add> <ScrollView
<add> style={styles.detailScrollView}
<add> ref={this._captureDetailScrollView}>
<add> {this._detailViewItems[this.state.detailRowID]}
<add> </ScrollView>}
<add> <View style={styles.listViewTitle}>
<add> {this._requests.length > 0 &&
<ide> <View style={styles.tableRow}>
<ide> <View style={styles.urlTitleCellView}>
<ide> <Text style={styles.cellText} numberOfLines={1}>URL</Text>
<ide> </View>
<ide> <View style={styles.methodTitleCellView}>
<ide> <Text style={styles.cellText} numberOfLines={1}>Method</Text>
<ide> </View>
<del> </View>
<del> </View>}
<add> </View>}
<add> </View>
<ide> <ListView
<ide> style={styles.listView}
<del> ref={this._captureRequestList}
<add> ref={this._captureRequestListView}
<ide> dataSource={this.state.dataSource}
<ide> renderRow={this._renderRow}
<ide> renderScrollComponent={this._renderScrollComponent}
<ide> class NetworkOverlay extends React.Component {
<ide>
<ide> const styles = StyleSheet.create({
<ide> container: {
<del> height: 100,
<ide> paddingTop: 10,
<ide> paddingBottom: 10,
<ide> paddingLeft: 5,
<ide> paddingRight: 5,
<ide> },
<add> listViewTitle: {
<add> height: 20,
<add> },
<ide> listView: {
<ide> flex: 1,
<add> height: 60,
<ide> },
<ide> tableRow: {
<ide> flexDirection: 'row',
<ide> const styles = StyleSheet.create({
<ide> flex: 5,
<ide> paddingLeft: 3,
<ide> },
<add> detailScrollView: {
<add> flex: 1,
<add> height: 180,
<add> marginTop: 5,
<add> marginBottom: 5,
<add> },
<add> detailKeyCellView: {
<add> flex: 1.3,
<add> },
<add> detailValueCellView: {
<add> flex: 2,
<add> },
<add> detailViewRow: {
<add> flexDirection: 'row',
<add> paddingHorizontal: 3,
<add> },
<add> detailViewText: {
<add> color: 'white',
<add> fontSize: 11,
<add> },
<add> clostButtonText: {
<add> color: 'white',
<add> fontSize: 10,
<add> },
<add> closeButton: {
<add> backgroundColor: '#888',
<add> justifyContent: 'center',
<add> alignItems: 'center',
<add> right: 0,
<add> },
<ide> });
<ide>
<ide> module.exports = NetworkOverlay; | 1 |
Ruby | Ruby | save an allocation in visit cat | bb611e59a62b61bcb78e1fa2a6cfbcf518c52a6c | <ide><path>actionpack/lib/action_dispatch/journey/path/pattern.rb
<ide> def accept(node)
<ide> end
<ide>
<ide> def visit_CAT(node)
<del> [visit(node.left), visit(node.right)].join
<add> "#{visit(node.left)}#{visit(node.right)}"
<ide> end
<ide>
<ide> def visit_SYMBOL(node) | 1 |
Go | Go | replace more uses of "syscall" | 079fb80657c70a843fe28719bd6bd6f731bf816a | <ide><path>pkg/system/path_windows.go
<ide> package system // import "github.com/docker/docker/pkg/system"
<ide>
<del>import "syscall"
<add>import "golang.org/x/sys/windows"
<ide>
<ide> // GetLongPathName converts Windows short pathnames to full pathnames.
<ide> // For example C:\Users\ADMIN~1 --> C:\Users\Administrator.
<ide> // It is a no-op on non-Windows platforms
<ide> func GetLongPathName(path string) (string, error) {
<ide> // See https://groups.google.com/forum/#!topic/golang-dev/1tufzkruoTg
<del> p := syscall.StringToUTF16(path)
<add> p, err := windows.UTF16FromString(path)
<add> if err != nil {
<add> return "", err
<add> }
<ide> b := p // GetLongPathName says we can reuse buffer
<del> n, err := syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
<add> n, err := windows.GetLongPathName(&p[0], &b[0], uint32(len(b)))
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> if n > uint32(len(b)) {
<ide> b = make([]uint16, n)
<del> _, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b)))
<add> _, err = windows.GetLongPathName(&p[0], &b[0], uint32(len(b)))
<ide> if err != nil {
<ide> return "", err
<ide> }
<ide> }
<del> return syscall.UTF16ToString(b), nil
<add> return windows.UTF16ToString(b), nil
<ide> } | 1 |
Javascript | Javascript | use oop for outgoingmessage._finish | 831de7cbb911ebae58237babed22a672dc6a9da0 | <ide><path>lib/_http_client.js
<ide> util.inherits(ClientRequest, OutgoingMessage);
<ide>
<ide> exports.ClientRequest = ClientRequest;
<ide>
<add>ClientRequest.prototype._finish = function() {
<add> DTRACE_HTTP_CLIENT_REQUEST(this, this.connection);
<add> COUNTER_HTTP_CLIENT_REQUEST();
<add> OutgoingMessage.prototype._finish.call(this);
<add>};
<add>
<ide> ClientRequest.prototype._implicitHeader = function() {
<ide> this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
<ide> this._renderHeaders());
<ide><path>lib/_http_outgoing.js
<ide> OutgoingMessage.prototype.end = function(data, encoding) {
<ide> };
<ide>
<ide>
<del>var ServerResponse, ClientRequest;
<del>
<ide> OutgoingMessage.prototype._finish = function() {
<ide> assert(this.connection);
<del>
<del> if (!ServerResponse)
<del> ServerResponse = require('_http_server').ServerResponse;
<del>
<del> if (!ClientRequest)
<del> ClientRequest = require('_http_client').ClientRequest;
<del>
<del> if (this instanceof ServerResponse) {
<del> DTRACE_HTTP_SERVER_RESPONSE(this.connection);
<del> COUNTER_HTTP_SERVER_RESPONSE();
<del> } else {
<del> assert(this instanceof ClientRequest);
<del> DTRACE_HTTP_CLIENT_REQUEST(this, this.connection);
<del> COUNTER_HTTP_CLIENT_REQUEST();
<del> }
<ide> this.emit('finish');
<ide> };
<ide>
<ide><path>lib/_http_server.js
<ide> function ServerResponse(req) {
<ide> }
<ide> util.inherits(ServerResponse, OutgoingMessage);
<ide>
<add>ServerResponse.prototype._finish = function() {
<add> DTRACE_HTTP_SERVER_RESPONSE(this.connection);
<add> COUNTER_HTTP_SERVER_RESPONSE();
<add> OutgoingMessage.prototype._finish.call(this);
<add>};
<add>
<add>
<ide>
<ide> exports.ServerResponse = ServerResponse;
<ide> | 3 |
Javascript | Javascript | add dynamic anchors to anchor list | c1260716de634f0cc25ae884ffc481ed6b7d520a | <ide><path>docs/src/ngdoc.js
<ide> function checkBrokenLinks(docs) {
<ide>
<ide> docs.forEach(function(doc) {
<ide> byFullId[doc.section + '/' + doc.id] = doc;
<add> if (doc.section === 'api') {
<add> doc.anchors.push('directive', 'service', 'filter', 'function');
<add> }
<ide> });
<ide>
<ide> docs.forEach(function(doc) { | 1 |
Ruby | Ruby | enforce 10.5 as minimum osx sdk framework to use | 7ebe8084ec545170ed665dac82e106f8aabbd46f | <ide><path>Library/Homebrew/brewkit.rb
<ide> # http://forums.mozillazine.org/viewtopic.php?f=12&t=577299
<ide> # http://gcc.gnu.org/onlinedocs/gcc-4.0.1/gcc/i386-and-x86_002d64-Options.html
<ide> ENV['MACOSX_DEPLOYMENT_TARGET']='10.5'
<del>ENV['CFLAGS']=ENV['CXXFLAGS']='-O3 -w -pipe -fomit-frame-pointer -march=prescott'
<add>ENV['CFLAGS']=ENV['CXXFLAGS']='-O3 -w -pipe -fomit-frame-pointer -march=prescott -mmacosx-version-min=10.5'
<ide>
<ide> # lets use gcc 4.2, it is newer and "better", at least I believe so, mail me
<ide> # if I'm wrong | 1 |
PHP | PHP | remove unused variable | fd29db13a8419ca9c163f73b79dc951a3d3b4c7d | <ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testMapSpread()
<ide> {
<ide> $c = new Collection([[1, 'a'], [2, 'b']]);
<ide>
<del> $result = $c->mapSpread(function ($number, $character) use (&$result) {
<add> $result = $c->mapSpread(function ($number, $character) {
<ide> return "{$number}-{$character}";
<ide> });
<ide> $this->assertEquals(['1-a', '2-b'], $result->all());
<ide>
<del> $result = $c->mapSpread(function ($number, $character, $key) use (&$result) {
<add> $result = $c->mapSpread(function ($number, $character, $key) {
<ide> return "{$number}-{$character}-{$key}";
<ide> });
<ide> $this->assertEquals(['1-a-0', '2-b-1'], $result->all());
<ide>
<ide> $c = new Collection([new Collection([1, 'a']), new Collection([2, 'b'])]);
<del> $result = $c->mapSpread(function ($number, $character, $key) use (&$result) {
<add> $result = $c->mapSpread(function ($number, $character, $key) {
<ide> return "{$number}-{$character}-{$key}";
<ide> });
<ide> $this->assertEquals(['1-a-0', '2-b-1'], $result->all()); | 1 |
PHP | PHP | fix message parsing in translator | 3fb876148b68ef240d5c6bafb48e106a483d8345 | <ide><path>src/I18n/Translator.php
<ide> public function translate($key, array $tokensValues = [])
<ide>
<ide> // No or missing context, fallback to the key/first message
<ide> if ($context === null) {
<del> $message = current($message['_context']);
<add> if (isset($message['_context'][''])) {
<add> $message = $message['_context'][''];
<add> } else {
<add> $message = current($message['_context']);
<add> }
<ide> } elseif (!isset($message['_context'][$context])) {
<ide> $message = $key;
<ide> } elseif (is_string($message['_context'][$context]) &&
<ide><path>tests/TestCase/I18n/Parser/PoFileParserTest.php
<ide> public function testParseContextOnSomeMessages()
<ide> $file = APP . 'Locale' . DS . 'en' . DS . 'context.po';
<ide> $messages = $parser->parse($file);
<ide>
<del> I18n::translator('default', 'en_US', function () use ($messages) {
<add> I18n::translator('default', 'de_DE', function () use ($messages) {
<ide> $package = new Package('default');
<ide> $package->setMessages($messages);
<ide>
<ide> public function testParseContextOnSomeMessages()
<ide> $this->assertSame('En resolved - context', $messages['Resolved']['_context']['Pay status']);
<ide>
<ide> // Confirm actual behavior
<del> I18n::locale('en_US');
<add> I18n::locale('de_DE');
<ide> $this->assertSame('En cours', __('Pending'));
<ide> $this->assertSame('En cours - context', __x('Pay status', 'Pending'));
<ide> $this->assertSame('En resolved', __('Resolved')); | 2 |
Ruby | Ruby | fix typo and improve example [ci skip] | e32bbc1356a7e72f721373344202c3d63fc37312 | <ide><path>activerecord/lib/active_record/attribute_methods/before_type_cast.rb
<ide> module BeforeTypeCast
<ide> attribute_method_suffix "_before_type_cast"
<ide> end
<ide>
<del> # Returns the value of the attribuet identified by +attr_name+ before
<add> # Returns the value of the attribute identified by +attr_name+ before
<ide> # typecasting and deserialization.
<ide> #
<ide> # class Task < ActiveRecord::Base
<ide> def read_attribute_before_type_cast(attr_name)
<ide> # end
<ide> #
<ide> # task = Task.new(title: nil, is_done: true, completed_on: '2012-10-21')
<add> # task.attributes
<add> # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>Sun, 21 Oct 2012, "created_at"=>nil, "updated_at"=>nil}
<ide> # task.attributes_before_type_cast
<ide> # # => {"id"=>nil, "title"=>nil, "is_done"=>true, "completed_on"=>"2012-10-21", "created_at"=>nil, "updated_at"=>nil}
<ide> def attributes_before_type_cast | 1 |
Python | Python | fix buggy config check for complex functions | 0910a8e1aa858c58b3dce6930d4a0160b348b0da | <ide><path>numpy/core/setup.py
<ide> def check_complex(config, mathlibs):
<ide> pub.append(('NPY_HAVE_%s' % type2def(t), 1))
<ide>
<ide> def check_prec(prec):
<del> flist = [f + prec for f in C99_COMPLEX_TYPES]
<del> if not config.check_funcs_once(flist):
<add> flist = [f + prec for f in C99_COMPLEX_FUNCS]
<add> decl = dict([(f, True) for f in flist])
<add> if not config.check_funcs_once(flist, call=decl, decl=decl,
<add> libraries=mathlibs):
<ide> for f in flist:
<del> if config.check_func(f):
<add> if config.check_func(f, call=True, decl=True,
<add> libraries=mathlibs):
<ide> priv.append(fname2def(f))
<add> else:
<add> priv.extend([fname2def(f) for f in flist])
<add>
<add> check_prec('')
<add> check_prec('f')
<add> check_prec('l')
<ide>
<ide> return priv, pub
<ide> | 1 |
PHP | PHP | add macroable trait to redirectresponse | d8ca3e632dbde7f8233463f330c4053f4fb08f3f | <ide><path>src/Illuminate/Http/RedirectResponse.php
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Support\MessageBag;
<ide> use Illuminate\Support\ViewErrorBag;
<add>use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Session\Store as SessionStore;
<ide> use Illuminate\Contracts\Support\MessageProvider;
<ide> use Symfony\Component\HttpFoundation\File\UploadedFile as SymfonyUploadedFile;
<ide> use Symfony\Component\HttpFoundation\RedirectResponse as BaseRedirectResponse;
<ide>
<ide> class RedirectResponse extends BaseRedirectResponse
<ide> {
<del> use ResponseTrait;
<add> use ResponseTrait, Macroable {
<add> Macroable::__call as macroCall;
<add> }
<ide>
<ide> /**
<ide> * The request instance.
<ide> public function setSession(SessionStore $session)
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<add> if (static::hasMacro($method)) {
<add> return $this->macroCall($method, $parameters);
<add> }
<add>
<ide> if (Str::startsWith($method, 'with')) {
<ide> return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
<ide> } | 1 |
Javascript | Javascript | remove references to three | c6ec6d3f9d65401bf623eac8ce124da4fbed7094 | <ide><path>src/renderers/webvr/WebVRManager.js
<ide> function WebVRManager( renderer ) {
<ide>
<ide> }
<ide>
<del> var matrixWorldInverse = new THREE.Matrix4();
<add> var matrixWorldInverse = new Matrix4();
<ide>
<del> var standingMatrix = new THREE.Matrix4();
<del> var standingMatrixInverse = new THREE.Matrix4();
<add> var standingMatrix = new Matrix4();
<add> var standingMatrixInverse = new Matrix4();
<ide>
<del> var cameraL = new THREE.PerspectiveCamera();
<del> cameraL.bounds = new THREE.Vector4( 0.0, 0.0, 0.5, 1.0 );
<add> var cameraL = new PerspectiveCamera();
<add> cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
<ide> cameraL.layers.enable( 1 );
<ide>
<del> var cameraR = new THREE.PerspectiveCamera();
<del> cameraR.bounds = new THREE.Vector4( 0.5, 0.0, 0.5, 1.0 );
<add> var cameraR = new PerspectiveCamera();
<add> cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
<ide> cameraR.layers.enable( 2 );
<ide>
<del> var cameraVR = new THREE.ArrayCamera( [ cameraL, cameraR ] );
<add> var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
<ide>
<ide> //
<ide> | 1 |
Python | Python | return actual action object | 0c1808fbd2e488b6cf822487eafdef0d2641c0bb | <ide><path>libcloud/container/drivers/rancher.py
<ide> def start_container(self, container):
<ide> """
<ide> result = self.connection.request('%s/containers/%s?action=start' %
<ide> (self.baseuri, container.id),
<del> method='POST')
<del> if result.status in VALID_RESPONSE_CODES:
<del> return self.get_container(container.id)
<del> else:
<del> raise RancherException(result.status, 'failed to start container')
<add> method='POST').object
<add>
<add> return self._to_container(result)
<ide>
<ide> def stop_container(self, container):
<ide> """
<ide> def stop_container(self, container):
<ide> """
<ide> result = self.connection.request('%s/containers/%s?action=stop' %
<ide> (self.baseuri, container.id),
<del> method='POST')
<del> if result.status in VALID_RESPONSE_CODES:
<del> return self.get_container(container.id)
<del> else:
<del> raise RancherException(result.status, 'failed to stop container')
<add> method='POST').object
<add>
<add> return self._to_container(result)
<ide>
<ide> def ex_search_containers(self, search_params):
<ide> """
<ide> def destroy_container(self, container):
<ide> :rtype: ``bool``
<ide> """
<ide> result = self.connection.request('%s/containers/%s' % (self.baseuri,
<del> container.id), method='DELETE')
<del> if result.status in VALID_RESPONSE_CODES:
<del> return self.get_container(container.id)
<del> else:
<del> raise RancherException(result.status, 'failed to stop container')
<add> container.id), method='DELETE').object
<add>
<add> return self._to_container(result)
<ide>
<ide> def _gen_image(self, imageuuid):
<ide> """ | 1 |
Javascript | Javascript | add missing import | 3a7809fbf0053305483f16ee723482f783f6437f | <ide><path>examples/jsm/exporters/GLTFExporter.js
<ide> import {
<ide> ClampToEdgeWrapping,
<ide> DoubleSide,
<ide> InterpolateDiscrete,
<add> InterpolateLinear,
<ide> LinearFilter,
<ide> LinearMipMapLinearFilter,
<ide> LinearMipMapNearestFilter, | 1 |
Text | Text | fix typo on tutorial.md. | 7c1e971e7fb4f9329f42c8f8f9f3fbb6803cb0a5 | <ide><path>docs/tutorial/tutorial.md
<ide> In [JavaScript classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/
<ide> Now change the Square `render` method to display the value from the current state, and to toggle it on click:
<ide>
<ide> * Replace `this.props.value` with `this.state.value` inside the `<button>` tag.
<del>* Replace the `() => alert()` event handler with `() => setState({value: 'X'})`.
<add>* Replace the `() => alert()` event handler with `() => this.setState({value: 'X'})`.
<ide>
<ide> Now the `<button>` tag looks like this:
<ide> | 1 |
Java | Java | add filter to add exchange to reactor context | ed650891cad795cbabb078d6ae023a9da18105fa | <ide><path>spring-web/src/main/java/org/springframework/web/filter/reactive/ServerWebExchangeContextFilter.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.filter.reactive;
<add>
<add>import java.util.Optional;
<add>
<add>import reactor.core.publisher.Mono;
<add>import reactor.util.context.Context;
<add>
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.WebFilter;
<add>import org.springframework.web.server.WebFilterChain;
<add>
<add>/**
<add> * Inserts an attribute in the Reactor {@link Context} that makes the current
<add> * {@link ServerWebExchange} available under the attribute name
<add> * {@link #EXCHANGE_CONTEXT_ATTRIBUTE}. This is useful for access to the
<add> * exchange without explicitly passing it to components that participate in
<add> * request processing.
<add> *
<add> * <p>The convenience method {@link #get(Context)} looks up the exchange.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 5.2
<add> */
<add>public class ServerWebExchangeContextFilter implements WebFilter {
<add>
<add> /** Attribute name under which the exchange is saved in the context. */
<add> public static final String EXCHANGE_CONTEXT_ATTRIBUTE =
<add> ServerWebExchangeContextFilter.class.getName() + ".EXCHANGE_CONTEXT";
<add>
<add>
<add> @Override
<add> public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
<add> return chain.filter(exchange)
<add> .subscriberContext(cxt -> cxt.put(EXCHANGE_CONTEXT_ATTRIBUTE, exchange));
<add> }
<add>
<add>
<add> /**
<add> * Access the {@link ServerWebExchange} from the Reactor Context, if available,
<add> * which is if {@link ServerWebExchangeContextFilter} is configured for use
<add> * and the give context was obtained from a request processing chain.
<add> * @param context the context in which to access the exchange
<add> * @return the exchange
<add> */
<add> public static Optional<ServerWebExchange> get(Context context) {
<add> return context.getOrEmpty(EXCHANGE_CONTEXT_ATTRIBUTE);
<add> }
<add>
<add>}
<ide><path>spring-web/src/test/java/org/springframework/web/filter/reactive/ServerWebExchangeContextFilterTests.java
<add>/*
<add> * Copyright 2002-2019 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>package org.springframework.web.filter.reactive;
<add>
<add>import java.time.Duration;
<add>import java.util.concurrent.atomic.AtomicReference;
<add>
<add>import org.junit.Test;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.http.server.reactive.HttpHandler;
<add>import org.springframework.mock.http.server.reactive.test.MockServerHttpRequest;
<add>import org.springframework.mock.http.server.reactive.test.MockServerHttpResponse;
<add>import org.springframework.web.server.ServerWebExchange;
<add>import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
<add>
<add>import static org.junit.Assert.*;
<add>
<add>/**
<add> * Unit tests for {@link ServerWebExchangeContextFilter}.
<add> * @author Rossen Stoyanchev
<add> */
<add>public class ServerWebExchangeContextFilterTests {
<add>
<add> @Test
<add> public void extractServerWebExchangeFromContext() {
<add> MyService service = new MyService();
<add>
<add> HttpHandler httpHandler = WebHttpHandlerBuilder
<add> .webHandler(exchange -> service.service().then())
<add> .filter(new ServerWebExchangeContextFilter())
<add> .build();
<add>
<add> httpHandler.handle(MockServerHttpRequest.get("/path").build(), new MockServerHttpResponse())
<add> .block(Duration.ofSeconds(5));
<add>
<add> assertNotNull(service.getExchange());
<add> }
<add>
<add>
<add> private static class MyService {
<add>
<add> private final AtomicReference<ServerWebExchange> exchangeRef = new AtomicReference<>();
<add>
<add>
<add> public ServerWebExchange getExchange() {
<add> return this.exchangeRef.get();
<add> }
<add>
<add> public Mono<String> service() {
<add> return Mono.just("result").subscriberContext(context -> {
<add> ServerWebExchangeContextFilter.get(context).ifPresent(exchangeRef::set);
<add> return context;
<add> });
<add> }
<add> }
<add>
<add>} | 2 |
Python | Python | add conversion rule for .conll | 55dab77de88d60640bc553297c1206106157110d | <ide><path>spacy/cli/convert.py
<ide> # from /converters.
<ide>
<ide> CONVERTERS = {
<del> '.conllu': conllu2json
<add> '.conllu': conllu2json,
<add> '.conll': conllu2json
<ide> }
<ide>
<ide>
<ide><path>spacy/cli/converters/conllu2json.py
<ide> def conllu2json(input_path, output_path, n_sents=10, use_morphology=False):
<ide> sentences = []
<ide>
<ide> output_filename = input_path.parts[-1].replace(".conllu", ".json")
<add> output_filename = input_path.parts[-1].replace(".conll", ".json")
<ide> output_file = output_path / output_filename
<ide> with output_file.open('w', encoding='utf-8') as f:
<ide> f.write(json_dumps(docs))
<ide> def read_conllx(input_path, use_morphology=False, n=0):
<ide> tokens = []
<ide> for line in lines:
<ide>
<del> id_, word, lemma, pos, tag, morph, head, dep, _1, \
<del> _2 = line.split('\t')
<add> parts = line.split('\t')
<add> id_, word, lemma, pos, tag, morph, head, dep, _1, _2 = parts
<ide> if '-' in id_ or '.' in id_:
<ide> continue
<ide> try: | 2 |
Javascript | Javascript | fix lint error | 06a2b944f58ba2a0bc131ff2f2f22e5b38450660 | <ide><path>examples/counter/src/App.test.js
<ide> import React from 'react';
<del>import { render } from '@testing-library/react';
<add>import { render, screen } from '@testing-library/react';
<ide> import { Provider } from 'react-redux';
<ide> import { store } from './app/store';
<ide> import App from './App';
<ide>
<ide> test('renders learn react link', () => {
<del> const { getByText } = render(
<add> render(
<ide> <Provider store={store}>
<ide> <App />
<ide> </Provider>
<ide> );
<ide>
<del> expect(getByText(/learn/i)).toBeInTheDocument();
<add> expect(screen.getByText(/learn/i)).toBeInTheDocument();
<ide> }); | 1 |
Javascript | Javascript | introduce a way to make es5 getters from `mixin`s | 48e52b3d267d62e1c28d192a4679f25d669eb7d7 | <ide><path>packages/ember-metal/lib/descriptor.js
<add>import { Descriptor as EmberDescriptor } from 'ember-metal/properties';
<add>
<add>export default function descriptor(desc) {
<add> return new Descriptor(desc);
<add>}
<add>
<add>/**
<add> A wrapper for a native ES5 descriptor. In an ideal world, we wouldn't need
<add> this at all, however, the way we currently flatten/merge our mixins require
<add> a special value to denote a descriptor.
<add>
<add> @class Descriptor
<add> @private
<add>*/
<add>class Descriptor extends EmberDescriptor {
<add> constructor(desc) {
<add> super();
<add> this.desc = desc;
<add> }
<add>
<add> setup(obj, key) {
<add> Object.defineProperty(obj, key, this.desc);
<add> }
<add>
<add> teardown(obj, key) {
<add> }
<add>}
<ide><path>packages/ember-metal/tests/descriptor_test.js
<add>import EmberObject from 'ember-runtime/system/object';
<add>import { Mixin } from 'ember-metal/mixin';
<add>import { defineProperty } from 'ember-metal/properties';
<add>import descriptor from 'ember-metal/descriptor';
<add>
<add>class DescriptorTest {
<add>
<add> /* abstract static module(title: string); */
<add>
<add> static test(title, callback) {
<add> QUnit.test(title, assert => {
<add> callback(assert, new this(assert));
<add> });
<add> }
<add>
<add> constructor(assert) {
<add> this.assert = assert;
<add> }
<add>
<add> /* abstract install(key: string, desc: Descriptor); */
<add>
<add> /* abstract set(key: string, value: any); */
<add>
<add> /* abstract finalize(): Object; */
<add>}
<add>
<add>let classes = [
<add>
<add> class extends DescriptorTest {
<add> static module(title) {
<add> QUnit.module(`${title}: using defineProperty on an object directly`);
<add> }
<add>
<add> constructor(assert) {
<add> super(assert);
<add> this.object = {};
<add> }
<add>
<add> install(key, desc) {
<add> let { object, assert } = this;
<add>
<add> defineProperty(object, key, desc);
<add>
<add> assert.ok(object.hasOwnProperty(key));
<add> }
<add>
<add> set(key, value) {
<add> this.object[key] = value;
<add> }
<add>
<add> finalize() {
<add> return this.object;
<add> }
<add>
<add> source() {
<add> return this.object;
<add> }
<add> },
<add>
<add> class extends DescriptorTest {
<add> static module(title) {
<add> QUnit.module(`${title}: using defineProperty on a prototype`);
<add> }
<add>
<add> constructor(assert) {
<add> super(assert);
<add> this.proto = {};
<add> }
<add>
<add> install(key, desc) {
<add> let { proto, assert } = this;
<add>
<add> defineProperty(proto, key, desc);
<add>
<add> assert.ok(proto.hasOwnProperty(key));
<add> }
<add>
<add> set(key, value) {
<add> this.proto[key] = value;
<add> }
<add>
<add> finalize() {
<add> return Object.create(this.proto);
<add> }
<add>
<add> source() {
<add> return this.proto;
<add> }
<add> },
<add>
<add> class extends DescriptorTest {
<add> static module(title) {
<add> QUnit.module(`${title}: in EmberObject.extend()`);
<add> }
<add>
<add> constructor(assert) {
<add> super(assert);
<add> this.klass = null;
<add> this.props = {};
<add> }
<add>
<add> install(key, desc) {
<add> this.props[key] = desc;
<add> }
<add>
<add> set(key, value) {
<add> this.props[key] = value;
<add> }
<add>
<add> finalize() {
<add> this.klass = EmberObject.extend(this.props);
<add> return this.klass.create();
<add> }
<add>
<add> source() {
<add> return this.klass.prototype;
<add> }
<add> },
<add>
<add> class extends DescriptorTest {
<add> static module(title) {
<add> QUnit.module(`${title}: in EmberObject.extend() through a mixin`);
<add> }
<add>
<add> constructor(assert) {
<add> super(assert);
<add> this.klass = null;
<add> this.props = {};
<add> }
<add>
<add> install(key, desc) {
<add> this.props[key] = desc;
<add> }
<add>
<add> set(key, value) {
<add> this.props[key] = value;
<add> }
<add>
<add> finalize() {
<add> this.klass = EmberObject.extend(Mixin.create(this.props));
<add> return this.klass.create();
<add> }
<add>
<add> source() {
<add> return this.klass.prototype;
<add> }
<add> },
<add>
<add> class extends DescriptorTest {
<add> static module(title) {
<add> QUnit.module(`${title}: inherited from another EmberObject super class`);
<add> }
<add>
<add> constructor(assert) {
<add> super(assert);
<add> this.superklass = null;
<add> this.props = {};
<add> }
<add>
<add> install(key, desc) {
<add> this.props[key] = desc;
<add> }
<add>
<add> set(key, value) {
<add> this.props[key] = value;
<add> }
<add>
<add> finalize() {
<add> this.superklass = EmberObject.extend(this.props);
<add> return this.superklass.extend().create();
<add> }
<add>
<add> source() {
<add> return this.superklass.prototype;
<add> }
<add> }
<add>
<add>];
<add>
<add>classes.forEach(TestClass => {
<add> TestClass.module('ember-metal/descriptor');
<add>
<add> TestClass.test('defining a configurable property', function(assert, factory) {
<add> factory.install('foo', descriptor({ configurable: true, value: 'bar' }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> let source = factory.source();
<add>
<add> delete source.foo;
<add>
<add> assert.strictEqual(obj.foo, undefined);
<add>
<add> Object.defineProperty(source, 'foo', { configurable: true, value: 'baz' });
<add>
<add> assert.equal(obj.foo, 'baz');
<add> });
<add>
<add> TestClass.test('defining a non-configurable property', function(assert, factory) {
<add> factory.install('foo', descriptor({ configurable: false, value: 'bar' }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> let source = factory.source();
<add>
<add> assert.throws(() => delete source.foo, TypeError);
<add>
<add> assert.throws(() => Object.defineProperty(source, 'foo', { configurable: true, value: 'baz' }), TypeError);
<add> });
<add>
<add> TestClass.test('defining an enumerable property', function(assert, factory) {
<add> factory.install('foo', descriptor({ enumerable: true, value: 'bar' }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> let source = factory.source();
<add>
<add> assert.ok(Object.keys(source).indexOf('foo') !== -1);
<add> });
<add>
<add> TestClass.test('defining a non-enumerable property', function(assert, factory) {
<add> factory.install('foo', descriptor({ enumerable: false, value: 'bar' }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> let source = factory.source();
<add>
<add> assert.ok(Object.keys(source).indexOf('foo') === -1);
<add> });
<add>
<add> TestClass.test('defining a writable property', function(assert, factory) {
<add> factory.install('foo', descriptor({ writable: true, value: 'bar' }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> let source = factory.source();
<add>
<add> source.foo = 'baz';
<add>
<add> assert.equal(obj.foo, 'baz');
<add>
<add> obj.foo = 'bat';
<add>
<add> assert.equal(obj.foo, 'bat');
<add> });
<add>
<add> TestClass.test('defining a non-writable property', function(assert, factory) {
<add> factory.install('foo', descriptor({ writable: false, value: 'bar' }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> let source = factory.source();
<add>
<add> assert.throws(() => source.foo = 'baz', TypeError);
<add>
<add> assert.throws(() => obj.foo = 'baz', TypeError);
<add> });
<add>
<add> TestClass.test('defining a getter', function(assert, factory) {
<add> factory.install('foo', descriptor({
<add> get: function() {
<add> return this.__foo__;
<add> }
<add> }));
<add>
<add> factory.set('__foo__', 'bar');
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.foo, 'bar');
<add>
<add> obj.__foo__ = 'baz';
<add>
<add> assert.equal(obj.foo, 'baz');
<add> });
<add>
<add> TestClass.test('defining a setter', function(assert, factory) {
<add> factory.install('foo', descriptor({
<add> set: function(value) {
<add> this.__foo__ = value;
<add> }
<add> }));
<add>
<add> factory.set('__foo__', 'bar');
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.__foo__, 'bar');
<add>
<add> obj.foo = 'baz';
<add>
<add> assert.equal(obj.__foo__, 'baz');
<add> });
<add>
<add> TestClass.test('combining multiple setter and getters', function(assert, factory) {
<add> factory.install('foo', descriptor({
<add> get: function() {
<add> return this.__foo__;
<add> },
<add>
<add> set: function(value) {
<add> this.__foo__ = value;
<add> }
<add> }));
<add>
<add> factory.set('__foo__', 'foo');
<add>
<add> factory.install('bar', descriptor({
<add> get: function() {
<add> return this.__bar__;
<add> },
<add>
<add> set: function(value) {
<add> this.__bar__ = value;
<add> }
<add> }));
<add>
<add> factory.set('__bar__', 'bar');
<add>
<add> factory.install('fooBar', descriptor({
<add> get: function() {
<add> return this.foo + '-' + this.bar;
<add> }
<add> }));
<add>
<add> let obj = factory.finalize();
<add>
<add> assert.equal(obj.fooBar, 'foo-bar');
<add>
<add> obj.foo = 'FOO';
<add>
<add> assert.equal(obj.fooBar, 'FOO-bar');
<add>
<add> obj.__bar__ = 'BAR';
<add>
<add> assert.equal(obj.fooBar, 'FOO-BAR');
<add>
<add> assert.throws(() => obj.fooBar = 'foobar', TypeError);
<add> });
<add>}); | 2 |
Javascript | Javascript | fix warning message | 90c92c7007628aec73fc3302df70274a614ad309 | <ide><path>packages/react-test-renderer/src/ReactTestHostConfig.js
<ide> export function appendChild(
<ide> warning(
<ide> Array.isArray(parentInstance.children),
<ide> 'An invalid container has been provided. ' +
<del> 'This may indicate that another render is being used in addition to the test renderer. ' +
<add> 'This may indicate that another renderer is being used in addition to the test renderer. ' +
<ide> '(For example, ReactDOM.createPortal inside of a ReactTestRenderer tree.) ' +
<ide> 'This is not supported.',
<ide> ); | 1 |
Text | Text | add section on how to purge unattached uploads | f4c51e8660bf1771268d45325fff8378eb90698e | <ide><path>guides/source/active_storage_overview.md
<ide> class Uploader {
<ide> }
<ide> ```
<ide>
<add>NOTE: Using [Direct Uploads](#direct-uploads) can sometimes result in a file that uploads, but never attaches to a record. Consider [purging unattached uploads](#purging-unattached-uploads).
<add>
<ide> Discarding Files Stored During System Tests
<ide> -------------------------------------------
<ide>
<ide> If you need to support a cloud service other than these, you will need to
<ide> implement the Service. Each service extends
<ide> [`ActiveStorage::Service`](https://github.com/rails/rails/blob/main/activestorage/lib/active_storage/service.rb)
<ide> by implementing the methods necessary to upload and download files to the cloud.
<add>
<add>Purging Unattached Uploads
<add>--------------------------
<add>
<add>There are cases where a file is uploaded but never attached to a record. This can happen when using [Direct Uploads](#direct-uploads). You can query for unattached records using the [unattached scope](https://github.com/rails/rails/blob/8ef5bd9ced351162b673904a0b77c7034ca2bc20/activestorage/app/models/active_storage/blob.rb#L49). Below is an example using a [custom rake task](command_line.html#custom-rake-tasks).
<add>
<add>```ruby
<add>namespace :active_storage do
<add> desc "Purges unattached Active Storage blobs. Run regularly."
<add> task purge_unattached: :environment do
<add> ActiveStorage::Blob.unattached.where("active_storage_blobs.created_at <= ?", 2.days.ago).find_each(&:purge_later)
<add> end
<add>end
<add>```
<add>
<add>WARNING: The query generated by `ActiveStorage::Blob.unattached` can be slow and potentially disruptive on applications with larger databases. | 1 |
Python | Python | remove stray debug print | 80cf9fd93f2c1e361b8650c0eba96d21d4a588bc | <ide><path>numpy/distutils/system_info.py
<ide> def check_symbols(self, info):
<ide> %(calls)s
<ide> return 0;
<ide> }""") % dict(prototypes=prototypes, calls=calls)
<del> print(s)
<ide> src = os.path.join(tmpdir, 'source.c')
<ide> out = os.path.join(tmpdir, 'a.out')
<ide> # Add the additional "extra" arguments | 1 |
Javascript | Javascript | add test for type assign-properties | 8250133209810223f1377ccb43abb12922439af1 | <ide><path>test/configCases/library/type-assign-properties/index.js
<add>it("should define global object with property", function () {
<add> expect(MyLibrary["answer"]).toEqual(42);
<add>});
<add>export const answer = 42;
<ide><path>test/configCases/library/type-assign-properties/webpack.config.js
<add>/** @type {import("../../../../").Configuration} */
<add>module.exports = {
<add> output: {
<add> library: {
<add> name: "MyLibrary",
<add> type: "assign-properties"
<add> }
<add> }
<add>}; | 2 |
Java | Java | introduce dedicated tests for disabledifcondition | 9d21abcd37a3a6f7626418b67b529e6c1d0b1aa9 | <ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfConditionTestCase.java
<add>/*
<add> * Copyright 2002-2016 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.test.context.junit.jupiter;
<add>
<add>import java.lang.reflect.Method;
<add>import java.util.Optional;
<add>
<add>import org.hamcrest.Matcher;
<add>
<add>import org.junit.jupiter.api.Test;
<add>import org.junit.jupiter.api.extension.ConditionEvaluationResult;
<add>import org.junit.jupiter.api.extension.ExtensionContext.Store;
<add>import org.junit.jupiter.api.extension.TestExtensionContext;
<add>
<add>import org.springframework.context.annotation.Configuration;
<add>import org.springframework.test.context.TestContextManager;
<add>import org.springframework.util.ReflectionUtils;
<add>
<add>import static org.hamcrest.CoreMatchers.containsString;
<add>import static org.hamcrest.CoreMatchers.endsWith;
<add>import static org.hamcrest.CoreMatchers.equalTo;
<add>import static org.hamcrest.CoreMatchers.is;
<add>import static org.hamcrest.CoreMatchers.startsWith;
<add>import static org.hamcrest.MatcherAssert.assertThat;
<add>import static org.junit.jupiter.api.Assertions.assertAll;
<add>import static org.junit.jupiter.api.Assertions.assertFalse;
<add>import static org.junit.jupiter.api.Assertions.assertNotNull;
<add>import static org.junit.jupiter.api.Assertions.assertTrue;
<add>import static org.junit.jupiter.api.Assertions.expectThrows;
<add>import static org.mockito.Matchers.any;
<add>import static org.mockito.Mockito.mock;
<add>import static org.mockito.Mockito.when;
<add>
<add>/**
<add> * Tests for {@link DisabledIfCondition} that verify actual condition evaluation
<add> * results and exception handling; whereas, {@link DisabledIfTestCase} only tests
<add> * the <em>happy paths</em>.
<add> *
<add> * @author Sam Brannen
<add> * @since 5.0
<add> * @see DisabledIfTestCase
<add> */
<add>class DisabledIfConditionTestCase {
<add>
<add> private final DisabledIfCondition condition = new DisabledIfCondition();
<add>
<add>
<add> @Test
<add> void missingDisabledIf() {
<add> IllegalStateException exception = expectThrows(IllegalStateException.class,
<add> () -> condition.evaluate(buildExtensionContext("missingDisabledIf")));
<add>
<add> assertThat(exception.getMessage(), startsWith("@DisabledIf must be present"));
<add> }
<add>
<add> @Test
<add> void disabledByEmptyExpression() {
<add> // @formatter:off
<add> assertAll(
<add> () -> assertExpressionIsBlank("emptyExpression"),
<add> () -> assertExpressionIsBlank("blankExpression")
<add> );
<add> // @formatter:on
<add> }
<add>
<add> @Test
<add> void invalidExpressionEvaluationType() {
<add> IllegalStateException exception = expectThrows(IllegalStateException.class,
<add> () -> condition.evaluate(buildExtensionContext("nonBooleanOrStringExpression")));
<add>
<add> assertThat(exception.getMessage(),
<add> is(equalTo("@DisabledIf(\"#{6 * 7}\") must evaluate to a String or a Boolean, not java.lang.Integer")));
<add> }
<add>
<add> @Test
<add> void disabledWithCustomReason() {
<add> assertResult(condition.evaluate(buildExtensionContext("customReason")), true, is(equalTo("Because... 42!")));
<add> }
<add>
<add> @Test
<add> void disabledWithDefaultReason() {
<add> assertResult(condition.evaluate(buildExtensionContext("defaultReason")), true,
<add> endsWith("defaultReason() is disabled because @DisabledIf(\"#{1 + 1 eq 2}\") evaluated to true"));
<add> }
<add>
<add> @Test
<add> void notDisabledWithDefaultReason() {
<add> assertResult(condition.evaluate(buildExtensionContext("neverDisabledWithDefaultReason")), false, endsWith(
<add> "neverDisabledWithDefaultReason() is enabled because @DisabledIf(\"false\") did not evaluate to true"));
<add> }
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> private TestExtensionContext buildExtensionContext(String methodName) {
<add> Class<?> testClass = SpringTestCase.class;
<add> Method method = ReflectionUtils.findMethod(getClass(), methodName);
<add> Store store = mock(Store.class);
<add> when(store.getOrComputeIfAbsent(any(), any(), any())).thenReturn(new TestContextManager(testClass));
<add>
<add> TestExtensionContext extensionContext = mock(TestExtensionContext.class);
<add> when(extensionContext.getTestClass()).thenReturn(Optional.of(testClass));
<add> when(extensionContext.getElement()).thenReturn(Optional.of(method));
<add> when(extensionContext.getStore(any())).thenReturn(store);
<add> return extensionContext;
<add> }
<add>
<add> private void assertExpressionIsBlank(String methodName) {
<add> IllegalStateException exception = expectThrows(IllegalStateException.class,
<add> () -> condition.evaluate(buildExtensionContext(methodName)));
<add>
<add> assertThat(exception.getMessage(), containsString("must not be blank"));
<add> }
<add>
<add> private void assertResult(ConditionEvaluationResult result, boolean disabled, Matcher<String> matcher) {
<add> assertNotNull(result);
<add>
<add> if (disabled) {
<add> assertTrue(result.isDisabled());
<add> }
<add> else {
<add> assertFalse(result.isDisabled());
<add> }
<add>
<add> Optional<String> reason = result.getReason();
<add> assertTrue(reason.isPresent());
<add> assertThat(reason.get(), matcher);
<add> }
<add>
<add> // -------------------------------------------------------------------------
<add>
<add> @DisabledIf("")
<add> private void emptyExpression() {
<add> }
<add>
<add> @DisabledIf("\t")
<add> private void blankExpression() {
<add> }
<add>
<add> @DisabledIf("#{6 * 7}")
<add> private void nonBooleanOrStringExpression() {
<add> }
<add>
<add> @DisabledIf(expression = "#{6 * 7 == 42}", reason = "Because... 42!")
<add> private void customReason() {
<add> }
<add>
<add> @DisabledIf("#{1 + 1 eq 2}")
<add> private void defaultReason() {
<add> }
<add>
<add> @DisabledIf("false")
<add> private void neverDisabledWithDefaultReason() {
<add> }
<add>
<add>
<add> private static class SpringTestCase {
<add>
<add> @Configuration
<add> static class Config {
<add> }
<add> }
<add>
<add>}
<ide><path>spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfTestCase.java
<ide> * @author Tadaya Tsuyukubo
<ide> * @author Sam Brannen
<ide> * @since 5.0
<add> * @see DisabledIfConditionTestCase
<ide> * @see DisabledIf
<ide> * @see SpringExtension
<ide> */ | 2 |
Javascript | Javascript | add failing test for #90 | 96313a71e0c33227f3d8933197d1829a117afd4f | <ide><path>test/createRedux.spec.js
<ide> describe('createRedux', () => {
<ide> ]);
<ide> expect(changeListenerSpy.calls.length).toBe(1);
<ide> });
<add>
<add> it('should use existing state when replacing the dispatcher', () => {
<add> redux.dispatch(addTodo('Hello'));
<add>
<add> let nextRedux = createRedux({ todoStore });
<add> redux.replaceDispatcher(nextRedux.getDispatcher());
<add>
<add> let action = (_, getState) => {
<add> expect(getState().todoStore).toEqual(redux.getState().todoStore);
<add> };
<add>
<add> nextRedux.dispatch(action);
<add> });
<ide> }); | 1 |
Javascript | Javascript | fix behavior of reactdomselect | 25e2cd0db6673f0ae80534b983b57a8cde1a0be4 | <ide><path>src/dom/components/ReactDOMSelect.js
<ide> function selectValueType(props, propName, componentName) {
<ide> */
<ide> function updateOptions() {
<ide> /*jshint validthis:true */
<del> if (this.props.value == null) {
<del> return;
<del> }
<add> var value = this.props.value != null ? this.props.value : this.state.value;
<ide> var options = this.getDOMNode().options;
<del> var selectedValue = '' + this.props.value;
<add> var selectedValue = '' + value;
<ide>
<ide> for (var i = 0, l = options.length; i < l; i++) {
<ide> var selected = this.props.multiple ?
<ide><path>src/dom/components/__tests__/ReactDOMSelect-test.js
<add>/**
<add> * Copyright 2013 Facebook, Inc.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> *
<add> * @jsx React.DOM
<add> * @emails react-core
<add> */
<add>
<add>"use strict";
<add>
<add>/*jshint evil:true */
<add>
<add>describe('ReactDOMSelect', function() {
<add> var React;
<add> var ReactTestUtils;
<add>
<add> var renderSelect;
<add>
<add> beforeEach(function() {
<add> React = require('React');
<add> ReactTestUtils = require('ReactTestUtils');
<add>
<add> renderSelect = function(component) {
<add> var stub = ReactTestUtils.renderIntoDocument(component);
<add> var node = stub.getDOMNode();
<add> return node;
<add> };
<add> });
<add>
<add> it('should allow setting `defaultValue`', function() {
<add> var stub =
<add> <select defaultValue="giraffe">
<add> <option value="monkey">A monkey!</option>
<add> <option value="giraffe">A giraffe!</option>
<add> <option value="gorilla">A gorilla!</option>
<add> </select>;
<add> var node = renderSelect(stub);
<add>
<add> expect(node.value).toBe('giraffe');
<add>
<add> // Changing `defaultValue` should do nothing.
<add> stub.setProps({defaultValue: 'gorilla'});
<add> expect(node.value).toEqual('giraffe');
<add> });
<add>
<add> it('should allow setting `defaultValue` with multiple', function() {
<add> var stub =
<add> <select multiple={true} defaultValue={['giraffe', 'gorilla']}>
<add> <option value="monkey">A monkey!</option>
<add> <option value="giraffe">A giraffe!</option>
<add> <option value="gorilla">A gorilla!</option>
<add> </select>;
<add> var node = renderSelect(stub);
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(true); // gorilla
<add>
<add> // Changing `defaultValue` should do nothing.
<add> stub.setProps({defaultValue: ['monkey']});
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(true); // gorilla
<add> });
<add>
<add> it('should allow setting `value`', function() {
<add> var stub =
<add> <select value="giraffe">
<add> <option value="monkey">A monkey!</option>
<add> <option value="giraffe">A giraffe!</option>
<add> <option value="gorilla">A gorilla!</option>
<add> </select>;
<add> var node = renderSelect(stub);
<add>
<add> expect(node.value).toBe('giraffe');
<add>
<add> // Changing the `value` prop should change the selected option.
<add> stub.setProps({value: 'gorilla'});
<add> expect(node.value).toEqual('gorilla');
<add> });
<add>
<add> it('should allow setting `value` with multiple', function() {
<add> var stub =
<add> <select multiple={true} value={['giraffe', 'gorilla']}>
<add> <option value="monkey">A monkey!</option>
<add> <option value="giraffe">A giraffe!</option>
<add> <option value="gorilla">A gorilla!</option>
<add> </select>;
<add> var node = renderSelect(stub);
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(true); // gorilla
<add>
<add> // Changing the `value` prop should change the selected options.
<add> stub.setProps({value: ['monkey']});
<add>
<add> expect(node.options[0].selected).toBe(true); // monkey
<add> expect(node.options[1].selected).toBe(false); // giraffe
<add> expect(node.options[2].selected).toBe(false); // gorilla
<add> });
<add>
<add> it('should allow switching to multiple', function() {
<add> var stub =
<add> <select defaultValue="giraffe">
<add> <option value="monkey">A monkey!</option>
<add> <option value="giraffe">A giraffe!</option>
<add> <option value="gorilla">A gorilla!</option>
<add> </select>;
<add> var node = renderSelect(stub);
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(false); // gorilla
<add>
<add> // When making it multiple, giraffe should still be selected
<add> stub.setProps({multiple: true, defaultValue: null});
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(false); // gorilla
<add> });
<add>
<add> it('should allow switching from multiple', function() {
<add> var stub =
<add> <select multiple={true} defaultValue={['giraffe', 'gorilla']}>
<add> <option value="monkey">A monkey!</option>
<add> <option value="giraffe">A giraffe!</option>
<add> <option value="gorilla">A gorilla!</option>
<add> </select>;
<add> var node = renderSelect(stub);
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(true); // gorilla
<add>
<add> // When removing multiple, giraffe should still be selected (but gorilla
<add> // will no longer be)
<add> stub.setProps({multiple: false, defaultValue: null});
<add>
<add> expect(node.options[0].selected).toBe(false); // monkey
<add> expect(node.options[1].selected).toBe(true); // giraffe
<add> expect(node.options[2].selected).toBe(false); // gorilla
<add> });
<add>}); | 2 |
Javascript | Javascript | avoid leaking memory | a3be72b24c667470194dbee679fbdb86d7f56982 | <ide><path>lib/Compiler.js
<ide> ${other}`);
<ide> }
<ide> },
<ide> err => {
<add> // Clear map to free up memory
<add> caseInsensitiveMap.clear();
<ide> if (err) return callback(err);
<ide>
<ide> this.hooks.afterEmit.callAsync(compilation, err => { | 1 |
Text | Text | assign pr semantics | fc0da7f6b435c6980b8f84869df0f5e02b2761c1 | <ide><path>COLLABORATOR_GUIDE.md
<ide> As soon as the PR is ready to land, please do so. Landing your own pull requests
<ide> allows other Collaborators to focus on other pull requests. If your pull request
<ide> is still awaiting the [minimum time to land](#waiting-for-approvals), add the
<ide> `author ready` label so other Collaborators know it can land as soon as the time
<del>ends.
<add>ends. If instead you wish to land the PR yourself, indicate this intent by using
<add>the "assign yourself" button, to self-assign the PR.
<ide>
<ide> ## Accepting Modifications
<ide>
<ide> The TSC should serve as the final arbiter where required.
<ide>
<ide> ## Landing Pull Requests
<ide>
<add>1. Avoid landing PRs that are assigned to someone else. Authors who wish to land
<add> their own PRs will self-assign them, or delegate to someone else. If in
<add> doubt, ask the assignee whether it is okay to land.
<ide> 1. Never use GitHub's green ["Merge Pull Request"][] button. Reasons for not
<ide> using the web interface button:
<ide> * The "Create a merge commit" method will add an unnecessary merge commit. | 1 |
Go | Go | check integration test requirements using daemon | b1fb41988dc1b7071a58f76f6ad2730fc1a02eca | <ide><path>integration-cli/docker_cli_run_unix_test.go
<ide> func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) {
<ide> }
<ide>
<ide> func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
<del> testRequires(c, memoryReservationSupport)
<add> testRequires(c, SameHostDaemon, memoryReservationSupport)
<ide>
<ide> file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
<ide> out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
<ide> func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) {
<ide>
<ide> func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) {
<ide> testRequires(c, memoryLimitSupport)
<del> testRequires(c, memoryReservationSupport)
<add> testRequires(c, SameHostDaemon, memoryReservationSupport)
<ide> out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
<ide> c.Assert(err, check.NotNil)
<ide> expected := "Minimum memory limit can not be less than memory reservation limit"
<ide> func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) {
<ide>
<ide> // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit
<ide> func (s *DockerSuite) TestRunPIDsLimit(c *check.C) {
<del> testRequires(c, pidsLimit)
<add> testRequires(c, SameHostDaemon, pidsLimit)
<ide>
<ide> file := "/sys/fs/cgroup/pids/pids.max"
<ide> out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file)
<ide><path>integration-cli/docker_cli_update_unix_test.go
<ide> import (
<ide> "github.com/docker/docker/client"
<ide> "github.com/docker/docker/integration-cli/checker"
<ide> "github.com/docker/docker/integration-cli/request"
<del> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/go-check/check"
<ide> "github.com/kr/pty"
<ide> )
<ide> func (s *DockerSuite) TestUpdateKernelMemory(c *check.C) {
<ide> func (s *DockerSuite) TestUpdateKernelMemoryUninitialized(c *check.C) {
<ide> testRequires(c, DaemonIsLinux, kernelMemorySupport)
<ide>
<del> isNewKernel := kernel.CheckKernelVersion(4, 6, 0)
<add> isNewKernel := CheckKernelVersion(4, 6, 0)
<ide> name := "test-update-container"
<ide> dockerCmd(c, "run", "-d", "--name", name, "busybox", "top")
<ide> _, _, err := dockerCmdWithError("update", "--kernel-memory", "100M", name)
<ide><path>integration-cli/requirements_unix_test.go
<ide> var (
<ide> )
<ide>
<ide> func cpuCfsPeriod() bool {
<del> return SysInfo.CPUCfsPeriod
<add> return testEnv.DaemonInfo.CPUCfsPeriod
<ide> }
<ide>
<ide> func cpuCfsQuota() bool {
<del> return SysInfo.CPUCfsQuota
<add> return testEnv.DaemonInfo.CPUCfsQuota
<ide> }
<ide>
<ide> func cpuShare() bool {
<del> return SysInfo.CPUShares
<add> return testEnv.DaemonInfo.CPUShares
<ide> }
<ide>
<ide> func oomControl() bool {
<del> return SysInfo.OomKillDisable
<add> return testEnv.DaemonInfo.OomKillDisable
<ide> }
<ide>
<ide> func pidsLimit() bool {
<ide> return SysInfo.PidsLimit
<ide> }
<ide>
<ide> func kernelMemorySupport() bool {
<del> return SysInfo.KernelMemory
<add> return testEnv.DaemonInfo.KernelMemory
<ide> }
<ide>
<ide> func memoryLimitSupport() bool {
<del> return SysInfo.MemoryLimit
<add> return testEnv.DaemonInfo.MemoryLimit
<ide> }
<ide>
<ide> func memoryReservationSupport() bool {
<ide> return SysInfo.MemoryReservation
<ide> }
<ide>
<ide> func swapMemorySupport() bool {
<del> return SysInfo.SwapLimit
<add> return testEnv.DaemonInfo.SwapLimit
<ide> }
<ide>
<ide> func memorySwappinessSupport() bool {
<del> return SysInfo.MemorySwappiness
<add> return SameHostDaemon() && SysInfo.MemorySwappiness
<ide> }
<ide>
<ide> func blkioWeight() bool {
<del> return SysInfo.BlkioWeight
<add> return SameHostDaemon() && SysInfo.BlkioWeight
<ide> }
<ide>
<ide> func cgroupCpuset() bool {
<del> return SysInfo.Cpuset
<add> return testEnv.DaemonInfo.CPUSet
<ide> }
<ide>
<ide> func seccompEnabled() bool {
<ide> func overlay2Supported() bool {
<ide> }
<ide>
<ide> func init() {
<del> SysInfo = sysinfo.New(true)
<add> if SameHostDaemon() {
<add> SysInfo = sysinfo.New(true)
<add> }
<ide> }
<ide><path>integration-cli/utils_test.go
<ide> import (
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/client"
<add> "github.com/docker/docker/pkg/parsers/kernel"
<ide> "github.com/docker/docker/pkg/stringutils"
<ide> "github.com/go-check/check"
<ide> "github.com/gotestyourself/gotestyourself/icmd"
<ide> func NewEnvClientWithVersion(version string) (*client.Client, error) {
<ide> cli.NegotiateAPIVersionPing(types.Ping{APIVersion: version})
<ide> return cli, nil
<ide> }
<add>
<add>// GetKernelVersion gets the current kernel version.
<add>func GetKernelVersion() *kernel.VersionInfo {
<add> v, _ := kernel.ParseRelease(testEnv.DaemonInfo.KernelVersion)
<add> return v
<add>}
<add>
<add>// CheckKernelVersion checks if current kernel is newer than (or equal to)
<add>// the given version.
<add>func CheckKernelVersion(k, major, minor int) bool {
<add> v := GetKernelVersion()
<add> if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
<add> return false
<add> }
<add> return true
<add>} | 4 |
Javascript | Javascript | fix weird string error | 2d950701a14638480d0e375180e6dff4b50a709b | <ide><path>test/parallel/test-stdio-pipe-access.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> if (!common.isMainThread)
<del> common.skip('Workers don’t have process-like stdio');
<add> common.skip("Workers don't have process-like stdio");
<ide>
<ide> // Test if Node handles acessing process.stdin if it is a redirected
<ide> // pipe without deadlocking
<ide><path>test/parallel/test-stdio-pipe-redirect.js
<ide> 'use strict';
<ide> const common = require('../common');
<ide> if (!common.isMainThread)
<del> common.skip('Workers don’t have process-like stdio');
<add> common.skip("Workers don't have process-like stdio");
<ide>
<ide> // Test if Node handles redirecting one child process stdout to another
<ide> // process stdin without crashing. | 2 |
Go | Go | add more moods to random name generator | 60809a4f72984881e8a8dc07bf585f07975baf7d | <ide><path>namesgenerator/names-generator.go
<ide> type NameChecker interface {
<ide> }
<ide>
<ide> var (
<del> left = [...]string{"happy", "jolly", "dreamy", "sad", "angry", "pensive", "focused", "sleepy", "grave", "distracted", "determined", "stoic", "stupefied", "sharp", "agitated", "cocky", "tender", "goofy", "furious", "desperate", "hopeful", "compassionate", "silly", "lonely", "condescending", "naughty", "kickass", "drunk", "boring", "nostalgic", "ecstatic", "insane", "cranky", "mad", "jovial", "sick", "hungry", "thirsty", "elegant", "backstabbing", "clever", "trusting", "loving", "suspicious"}
<add> left = [...]string{"happy", "jolly", "dreamy", "sad", "angry", "pensive", "focused", "sleepy", "grave", "distracted", "determined", "stoic", "stupefied", "sharp", "agitated", "cocky", "tender", "goofy", "furious", "desperate", "hopeful", "compassionate", "silly", "lonely", "condescending", "naughty", "kickass", "drunk", "boring", "nostalgic", "ecstatic", "insane", "cranky", "mad", "jovial", "sick", "hungry", "thirsty", "elegant", "backstabbing", "clever", "trusting", "loving", "suspicious", "berserk", "high", "romantic", "prickly", "evil"}
<ide> // Docker 0.7.x generates names from notable scientists and hackers.
<ide> //
<ide> // Ada Lovelace invented the first algorithm. http://en.wikipedia.org/wiki/Ada_Lovelace (thanks James Turnbull)
<ide> var (
<ide> // Charles Darwin established the principles of natural evolution. http://en.wikipedia.org/wiki/Charles_Darwin.
<ide> // Dennis Ritchie and Ken Thompson created UNIX and the C programming language. http://en.wikipedia.org/wiki/Dennis_Ritchie http://en.wikipedia.org/wiki/Ken_Thompson
<ide> // Douglas Engelbart gave the mother of all demos: http://en.wikipedia.org/wiki/Douglas_Engelbart
<add> // Emmett Brown invented time travel. http://en.wikipedia.org/wiki/Emmett_Brown (thanks Brian Goff)
<ide> // Enrico Fermi invented the first nuclear reactor. http://en.wikipedia.org/wiki/Enrico_Fermi.
<ide> // Euclid invented geometry. http://en.wikipedia.org/wiki/Euclid
<ide> // Galileo was a founding father of modern astronomy, and faced politics and obscurantism to establish scientific truth. http://en.wikipedia.org/wiki/Galileo_Galilei
<ide> var (
<ide> // Stephen Hawking pioneered the field of cosmology by combining general relativity and quantum mechanics. http://en.wikipedia.org/wiki/Stephen_Hawking
<ide> // Steve Wozniak invented the Apple I and Apple II. http://en.wikipedia.org/wiki/Steve_Wozniak
<ide> // Werner Heisenberg was a founding father of quantum mechanics. http://en.wikipedia.org/wiki/Werner_Heisenberg
<del> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclide", "newton", "fermat", "archimede", "poincare", "heisenberg", "feynmann", "hawkings", "fermi", "paré", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean"}
<add> // William Shockley, Walter Houser Brattain and John Bardeen co-invented the transistor (thanks Brian Goff).
<add> // http://en.wikipedia.org/wiki/John_Bardeen
<add> // http://en.wikipedia.org/wiki/Walter_Houser_Brattain
<add> // http://en.wikipedia.org/wiki/William_Shockley
<add> right = [...]string{"lovelace", "franklin", "tesla", "einstein", "bohr", "davinci", "pasteur", "nobel", "curie", "darwin", "turing", "ritchie", "torvalds", "pike", "thompson", "wozniak", "galileo", "euclide", "newton", "fermat", "archimede", "poincare", "heisenberg", "feynmann", "hawkings", "fermi", "paré", "mccarthy", "engelbart", "babbage", "albattani", "ptolemy", "bell", "wright", "lumiere", "morse", "mclean", "brown", "bardeen", "brattain", "shockley"}
<ide> )
<ide>
<ide> func GenerateRandomName(checker NameChecker) (string, error) { | 1 |
Text | Text | add parameters for settings events | e954aa0e0c5e97d2e9256e9145d13bb59ee6dfb1 | <ide><path>doc/api/http2.md
<ide> event is emitted.
<ide> added: v8.4.0
<ide> -->
<ide>
<add>* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
<add>
<ide> The `'localSettings'` event is emitted when an acknowledgment `SETTINGS` frame
<del>has been received. When invoked, the handler function will receive a copy of
<del>the local settings.
<add>has been received.
<ide>
<ide> When using `http2session.settings()` to submit new settings, the modified
<ide> settings do not take effect until the `'localSettings'` event is emitted.
<ide> session.on('localSettings', (settings) => {
<ide> added: v8.4.0
<ide> -->
<ide>
<add>* `settings` {HTTP/2 Settings Object} A copy of the `SETTINGS` frame received.
<add>
<ide> The `'remoteSettings'` event is emitted when a new `SETTINGS` frame is received
<del>from the connected peer. When invoked, the handler function will receive a copy
<del>of the remote settings.
<add>from the connected peer.
<ide>
<ide> ```js
<ide> session.on('remoteSettings', (settings) => { | 1 |
Javascript | Javascript | fix manual msaa | 6f995385f5a7d6360bf694c10c5f934d6c92665d | <ide><path>examples/js/postprocessing/ManualMSAARenderPass.js
<ide> THREE.ManualMSAARenderPass.prototype = Object.assign( Object.create( THREE.Pass.
<ide>
<ide> var baseSampleWeight = 1.0 / jitterOffsets.length;
<ide> var roundingRange = 1 / 32;
<del> this.copyUniforms[ "tDiffuse" ].value = this.sampleRenderTarget.texture;
<add> this.copyUniforms[ "tDiffuse" ] = new THREE.Uniform( this.sampleRenderTarget.texture );
<ide>
<ide> var width = readBuffer.width, height = readBuffer.height;
<ide>
<ide> THREE.ManualMSAARenderPass.prototype = Object.assign( Object.create( THREE.Pass.
<ide> sampleWeight += roundingRange * uniformCenteredDistribution;
<ide> }
<ide>
<del> this.copyUniforms[ "opacity" ].value = sampleWeight;
<add> this.copyUniforms[ "opacity" ] = new THREE.Uniform( sampleWeight );
<ide> renderer.setClearColor( this.clearColor, this.clearAlpha );
<ide> renderer.render( this.scene, this.camera, this.sampleRenderTarget, true );
<ide> if (i === 0) { | 1 |
PHP | PHP | remove colon from message | ddfacfb64afbf8da8044bd96b702cb4e21dc7657 | <ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public static function findOrFail($id, $columns = array('*'))
<ide> {
<ide> if ( ! is_null($model = static::find($id, $columns))) return $model;
<ide>
<del> throw new ModelNotFoundException(get_called_class().': model not found');
<add> throw new ModelNotFoundException(get_called_class().' model not found');
<ide> }
<ide>
<ide> /** | 1 |
Ruby | Ruby | improve formula not found handling (#96) | fdf55e77e10f938d1c5d8a72e015e04451be938a | <ide><path>Library/Homebrew/cmd/install.rb
<ide> def install
<ide> rescue FormulaUnavailableError => e
<ide> if (blacklist = blacklisted?(e.name))
<ide> ofail "#{e.message}\n#{blacklist}"
<add> elsif e.name == "updog"
<add> ofail "What's updog?"
<ide> else
<ide> ofail e.message
<ide> query = query_regexp(e.name) | 1 |
Text | Text | improve translation of title and first paragraph | c178dbf64faf3b30fc6ff90d4f23175721534d44 | <ide><path>guide/spanish/c/if-statements/index.md
<ide> title: Logical Operators and If Statements
<ide> localeTitle: Operadores lógicos y declaraciones if
<ide> ---
<del># Si las declaraciones en C
<add># Sentencias if en C
<ide>
<del>La capacidad de cambiar el comportamiento de un fragmento de código que se basa en cierta información en el entorno se conoce como flujo de código condicional. A veces, usted quiere que su código se ejecute de acuerdo con ciertas condiciones. En tal situación podemos usar declaraciones de if. También se conoce como declaración de toma de decisiones ya que toma la decisión sobre la base de una expresión dada (o en una condición dada). Si la expresión se evalúa como verdadera, entonces se ejecutará el bloque de código dentro de la declaración "if". Si la expresión se evalúa como falsa, entonces se ejecutará el primer conjunto de código después del final de la instrucción 'if' (después de la llave de cierre). Una expresión es una expresión que tiene operadores relacionales y / o lógicos que operan en variables booleanas . Una expresión se evalúa como verdadera o falsa.
<add>La capacidad de cambiar el comportamiento de un fragmento de código que se basa en cierta información en el entorno se conoce como flujo de código condicional. A veces, usted quiere que su código se ejecute de acuerdo con ciertas condiciones. En tal situación podemos usar sentencias "if". También se conoce como sentencias de toma de decisiones ya que toma la decisión sobre la base de una expresión dada (o en una condición dada). Si la expresión se evalúa como verdadera, entonces se ejecutará el bloque de código dentro de la sentencia "if". Si la expresión se evalúa como falsa, entonces se ejecutará el primer conjunto de código después del final de la instrucción 'if' (después de la llave de cierre). Una expresión es una expresión que tiene operadores relacionales y / o lógicos que operan en variables booleanas. Una expresión se evalúa como verdadera o falsa.
<ide>
<ide> ## Sintaxis de la _sentencia if_
<ide> ```
<ide> Se comparará entre dos variables pero "= 'es el operador de asignación cuando
<ide> * También tenemos algunos operadores lógicos, que nos permiten encadenar operaciones lógicas:
<ide> * ! Se llama operador NO-Invierte el estado del operando
<ide> * && se llama AND operator-Devuelve verdadero cuando ambas condiciones son verdaderas
<del>* || se llama OR operator-Devuelve verdadero cuando al menos una de las condiciones es verdadera
<ide>\ No newline at end of file
<add>* || se llama OR operator-Devuelve verdadero cuando al menos una de las condiciones es verdadera | 1 |
Python | Python | use post instead of get for sanity of use-case | d1371cc949afcc66c7e7f497bab62ec655cddf31 | <ide><path>tests/test_atomic_requests.py
<ide>
<ide>
<ide> class BasicView(APIView):
<del> def get(self, request, *args, **kwargs):
<add> def post(self, request, *args, **kwargs):
<ide> BasicModel.objects.create()
<ide> return Response({'method': 'GET'})
<ide>
<ide>
<ide> class ErrorView(APIView):
<del> def get(self, request, *args, **kwargs):
<add> def post(self, request, *args, **kwargs):
<ide> BasicModel.objects.create()
<ide> raise Exception
<ide>
<ide>
<ide> class APIExceptionView(APIView):
<del> def get(self, request, *args, **kwargs):
<add> def post(self, request, *args, **kwargs):
<ide> BasicModel.objects.create()
<ide> raise APIException
<ide>
<ide> def tearDown(self):
<ide> connections.databases['default']['ATOMIC_REQUESTS'] = False
<ide>
<ide> def test_no_exception_conmmit_transaction(self):
<del> request = factory.get('/')
<add> request = factory.post('/')
<ide>
<ide> with self.assertNumQueries(1):
<ide> response = self.view(request)
<ide> def test_error_rollback_transaction(self):
<ide> Transaction is eventually managed by outer-most transaction atomic
<ide> block. DRF do not try to interfere here.
<ide> """
<del> request = factory.get('/')
<add> request = factory.post('/')
<ide> with self.assertNumQueries(3):
<ide> # 1 - begin savepoint
<ide> # 2 - insert
<ide> def test_api_exception_rollback_transaction(self):
<ide> """
<ide> Transaction is rollbacked by our transaction atomic block.
<ide> """
<del> request = factory.get('/')
<add> request = factory.post('/')
<ide> num_queries = (4 if getattr(connection.features,
<ide> 'can_release_savepoints', False) else 3)
<ide> with self.assertNumQueries(num_queries): | 1 |
PHP | PHP | remove boolean param for merging | 551f93b4521983f9ee5267877f777319a8c57c44 | <ide><path>src/Form/Form.php
<ide> public function getData($field = null)
<ide> return Hash::get($this->_data, $field);
<ide> }
<ide>
<del> public function setData(array $data, $merge = true)
<add> public function setData(array $data)
<ide> {
<del> if ($merge) {
<del> $this->_data = Hash::merge($this->_data, $data);
<del> } else {
<del> $this->_data = $data;
<del> }
<add> $this->_data = $data;
<ide>
<ide> return $this;
<ide> } | 1 |
Go | Go | use prefix naming for port tests | 6e8c9e7bee5319b1e324c72240ef9d7a77946135 | <ide><path>integration-cli/docker_cli_port_test.go
<ide> import (
<ide> "testing"
<ide> )
<ide>
<del>func TestListPorts(t *testing.T) {
<add>func TestPortList(t *testing.T) {
<ide> // one port
<ide> runCmd := exec.Command(dockerBinary, "run", "-d", "-p", "9876:80", "busybox", "top")
<ide> out, _, err := runCommandWithOutput(runCmd) | 1 |
Javascript | Javascript | fix object flickering with canvasrenderer | d707242f4143eb5dcbada19858ffb1c8ab46d4e5 | <ide><path>examples/js/renderers/Projector.js
<ide> THREE.Projector = function () {
<ide>
<ide> if ( groups.length > 0 ) {
<ide>
<del> for ( var o = 0; o < groups.length; o ++ ) {
<add> for ( var g = 0; g < groups.length; g ++ ) {
<ide>
<del> var group = groups[ o ];
<add> var group = groups[ g ];
<ide>
<ide> for ( var i = group.start, l = group.start + group.count; i < l; i += 3 ) {
<ide> | 1 |
Ruby | Ruby | create gem_home when installing gems | 5b19563937bab44fb98648a8dabdb9dc930a0ac3 | <ide><path>Library/Homebrew/utils.rb
<ide> def install_gem_setup_path!(name, version = nil, executable = name)
<ide> Gem.clear_paths
<ide> Gem::Specification.reset
<ide>
<add> # Create GEM_HOME which may not exist yet so it exists when creating PATH.
<add> FileUtils.mkdir_p Gem.bindir
<add>
<ide> # Add Gem binary directory and (if missing) Ruby binary directory to PATH.
<ide> path = PATH.new(ENV["PATH"])
<ide> path.prepend(RUBY_BIN) if which("ruby") != RUBY_PATH | 1 |
Python | Python | fix broken triggering dag from ui functionality | b2a3ab59b5c4980af99ea44f7e8b56327c1506ca | <ide><path>airflow/models/dag.py
<ide> def get_paused_dag_ids(dag_ids: List[str], session: Session = None) -> Set[str]:
<ide> def safe_dag_id(self):
<ide> return self.dag_id.replace('.', '__dot__')
<ide>
<del> @provide_session
<del> def create_dagrun(self,
<del> run_id,
<del> state,
<del> execution_date,
<del> start_date=None,
<del> external_trigger=False,
<del> conf=None,
<del> session=None):
<del> """
<del> Creates a dag run from this dag including the tasks associated with this dag.
<del> Returns the dag run.
<del>
<del> :param run_id: defines the run id for this dag run
<del> :type run_id: str
<del> :param execution_date: the execution date of this dag run
<del> :type execution_date: datetime.datetime
<del> :param state: the state of the dag run
<del> :type state: airflow.utils.state.State
<del> :param start_date: the date this dag run should be evaluated
<del> :type start_date: datetime.datetime
<del> :param external_trigger: whether this dag run is externally triggered
<del> :type external_trigger: bool
<del> :param session: database session
<del> :type session: sqlalchemy.orm.session.Session
<del> """
<del>
<del> return self.get_dag().create_dagrun(run_id=run_id,
<del> state=state,
<del> execution_date=execution_date,
<del> start_date=start_date,
<del> external_trigger=external_trigger,
<del> conf=conf,
<del> session=session)
<del>
<ide> @provide_session
<ide> def set_is_paused(self,
<ide> is_paused: bool,
<ide><path>airflow/www/views.py
<ide> def trigger(self, session=None):
<ide> conf=''
<ide> )
<ide>
<del> dag = session.query(models.DagModel).filter(models.DagModel.dag_id == dag_id).first()
<del> if not dag:
<add> dag_orm = session.query(models.DagModel).filter(models.DagModel.dag_id == dag_id).first()
<add> if not dag_orm:
<ide> flash("Cannot find dag {}".format(dag_id))
<ide> return redirect(origin)
<ide>
<ide> def trigger(self, session=None):
<ide> conf=conf
<ide> )
<ide>
<add> dag = get_dag(dag_orm, STORE_SERIALIZED_DAGS)
<ide> dag.create_dagrun(
<ide> run_id=run_id,
<ide> execution_date=execution_date,
<ide><path>tests/www/test_views.py
<ide> from airflow.ti_deps.dependencies_states import QUEUEABLE_STATES, RUNNABLE_STATES
<ide> from airflow.utils import dates, timezone
<ide> from airflow.utils.session import create_session
<add>from airflow.utils.sqlalchemy import using_mysql
<ide> from airflow.utils.state import State
<ide> from airflow.utils.timezone import datetime
<ide> from airflow.utils.types import DagRunType
<ide> def test_trigger_dag_button_normal_exist(self):
<ide> self.assertIn('/trigger?dag_id=example_bash_operator', resp.data.decode('utf-8'))
<ide> self.assertIn("return confirmDeleteDag(this, 'example_bash_operator')", resp.data.decode('utf-8'))
<ide>
<del> @pytest.mark.xfail(condition=True, reason="This test might be flaky on mysql")
<add> @pytest.mark.xfail(condition=using_mysql, reason="This test might be flaky on mysql")
<ide> def test_trigger_dag_button(self):
<ide>
<ide> test_dag_id = "example_bash_operator"
<ide> def test_trigger_dag_button(self):
<ide> self.assertIsNotNone(run)
<ide> self.assertIn("manual__", run.run_id)
<ide>
<del> @pytest.mark.xfail(condition=True, reason="This test might be flaky on mysql")
<add> @pytest.mark.xfail(condition=using_mysql, reason="This test might be flaky on mysql")
<ide> def test_trigger_dag_conf(self):
<ide>
<ide> test_dag_id = "example_bash_operator" | 3 |
PHP | PHP | add accessor for pivot accessor | f09ea98bc814c708215896dad702d715923f3bc3 | <ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php
<ide> public function getRelationName()
<ide> {
<ide> return $this->relationName;
<ide> }
<add>
<add> /**
<add> * Get the name of the pivot accessor for this relationship.
<add> *
<add> * @return string
<add> */
<add> public function getPivotAccessor()
<add> {
<add> return $this->accessor;
<add> }
<ide> } | 1 |
Ruby | Ruby | remove controller construction | 208956c0d014b6e4c560ac40145fdac97c72aa39 | <ide><path>actionpack/test/controller/live_stream_test.rb
<ide> def capture_log_output
<ide> end
<ide>
<ide> def test_set_cookie
<del> @controller = TestController.new
<ide> get :set_cookie
<ide> assert_equal({'hello' => 'world'}, @response.cookies)
<ide> assert_equal "hello world", @response.body
<ide> def test_thread_locals_get_copied
<ide> end
<ide>
<ide> def test_live_stream_default_header
<del> @controller.request = @request
<del> @controller.response = @response
<del> @controller.process :default_header
<del> _, headers, _ = @response.prepare!
<del> assert headers['Content-Type']
<add> get :default_header
<add> assert response.headers['Content-Type']
<ide> end
<ide>
<ide> def test_render_text
<ide> def test_exceptions_raised_handling_exceptions_and_committed
<ide>
<ide> def test_stale_without_etag
<ide> get :with_stale
<del> assert_equal 200, @response.status.to_i
<add> assert_equal 200, response.status.to_i
<ide> end
<ide>
<ide> def test_stale_with_etag
<ide> @request.if_none_match = Digest::MD5.hexdigest("123")
<ide> get :with_stale
<del> assert_equal 304, @response.status.to_i
<add> assert_equal 304, response.status.to_i
<ide> end
<ide> end
<ide> | 1 |
Text | Text | use serial comma in dns docs | 89df3546adf2948cae32d4be976639019d149d4c | <ide><path>doc/api/dns.md
<ide> using `dns.resolve()` and using the address instead of a host name. Also, some
<ide> networking APIs (such as [`socket.connect()`][] and [`dgram.createSocket()`][])
<ide> allow the default resolver, `dns.lookup()`, to be replaced.
<ide>
<del>### `dns.resolve()`, `dns.resolve*()` and `dns.reverse()`
<add>### `dns.resolve()`, `dns.resolve*()`, and `dns.reverse()`
<ide>
<ide> These functions are implemented quite differently than [`dns.lookup()`][]. They
<ide> do not use getaddrinfo(3) and they _always_ perform a DNS query on the | 1 |
Javascript | Javascript | enable eager listeners statically | 993ca533b42756811731f6b7791ae06a35ee6b4d | <ide><path>packages/react-dom/src/__tests__/ReactDOMFiber-test.js
<ide> describe('ReactDOMFiber', () => {
<ide> expect(ops).toEqual([]);
<ide> });
<ide>
<del> // @gate enableEagerRootListeners
<ide> it('listens to events that do not exist in the Portal subtree', () => {
<ide> const onClick = jest.fn();
<ide>
<ide><path>packages/react-dom/src/client/ReactDOMComponent.js
<ide> import {
<ide> shouldRemoveAttribute,
<ide> } from '../shared/DOMProperty';
<ide> import assertValidProps from '../shared/assertValidProps';
<del>import {
<del> DOCUMENT_NODE,
<del> ELEMENT_NODE,
<del> COMMENT_NODE,
<del> DOCUMENT_FRAGMENT_NODE,
<del>} from '../shared/HTMLNodeType';
<add>import {DOCUMENT_NODE} from '../shared/HTMLNodeType';
<ide> import isCustomComponent from '../shared/isCustomComponent';
<ide> import possibleStandardNames from '../shared/possibleStandardNames';
<ide> import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook';
<ide> import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook';
<ide> import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook';
<ide> import {REACT_OPAQUE_ID_TYPE} from 'shared/ReactSymbols';
<ide>
<add>import {enableTrustedTypesIntegration} from 'shared/ReactFeatureFlags';
<ide> import {
<del> enableTrustedTypesIntegration,
<del> enableEagerRootListeners,
<del>} from 'shared/ReactFeatureFlags';
<del>import {
<del> listenToReactEvent,
<ide> mediaEventTypes,
<ide> listenToNonDelegatedEvent,
<ide> } from '../events/DOMPluginEventSystem';
<ide> if (__DEV__) {
<ide> };
<ide> }
<ide>
<del>export function ensureListeningTo(
<del> rootContainerInstance: Element | Node,
<del> reactPropEvent: string,
<del> targetElement: Element | null,
<del>): void {
<del> if (!enableEagerRootListeners) {
<del> // If we have a comment node, then use the parent node,
<del> // which should be an element.
<del> const rootContainerElement =
<del> rootContainerInstance.nodeType === COMMENT_NODE
<del> ? rootContainerInstance.parentNode
<del> : rootContainerInstance;
<del> if (__DEV__) {
<del> if (
<del> rootContainerElement == null ||
<del> (rootContainerElement.nodeType !== ELEMENT_NODE &&
<del> // This is to support rendering into a ShadowRoot:
<del> rootContainerElement.nodeType !== DOCUMENT_FRAGMENT_NODE)
<del> ) {
<del> console.error(
<del> 'ensureListeningTo(): received a container that was not an element node. ' +
<del> 'This is likely a bug in React. Please file an issue.',
<del> );
<del> }
<del> }
<del> listenToReactEvent(
<del> reactPropEvent,
<del> ((rootContainerElement: any): Element),
<del> targetElement,
<del> );
<del> }
<del>}
<del>
<ide> function getOwnerDocumentFromRootContainer(
<ide> rootContainerElement: Element | Document,
<ide> ): Document {
<ide> function setInitialDOMProperties(
<ide> if (__DEV__ && typeof nextProp !== 'function') {
<ide> warnForInvalidEventListener(propKey, nextProp);
<ide> }
<del> if (!enableEagerRootListeners) {
<del> ensureListeningTo(rootContainerElement, propKey, domElement);
<del> } else if (propKey === 'onScroll') {
<add> if (propKey === 'onScroll') {
<ide> listenToNonDelegatedEvent('scroll', domElement);
<ide> }
<ide> }
<ide> export function setInitialProperties(
<ide> // We listen to this event in case to ensure emulated bubble
<ide> // listeners still fire for the invalid event.
<ide> listenToNonDelegatedEvent('invalid', domElement);
<del> if (!enableEagerRootListeners) {
<del> // For controlled components we always need to ensure we're listening
<del> // to onChange. Even if there is no listener.
<del> ensureListeningTo(rootContainerElement, 'onChange', domElement);
<del> }
<ide> break;
<ide> case 'option':
<ide> ReactDOMOptionValidateProps(domElement, rawProps);
<ide> export function setInitialProperties(
<ide> // We listen to this event in case to ensure emulated bubble
<ide> // listeners still fire for the invalid event.
<ide> listenToNonDelegatedEvent('invalid', domElement);
<del> if (!enableEagerRootListeners) {
<del> // For controlled components we always need to ensure we're listening
<del> // to onChange. Even if there is no listener.
<del> ensureListeningTo(rootContainerElement, 'onChange', domElement);
<del> }
<ide> break;
<ide> case 'textarea':
<ide> ReactDOMTextareaInitWrapperState(domElement, rawProps);
<ide> props = ReactDOMTextareaGetHostProps(domElement, rawProps);
<ide> // We listen to this event in case to ensure emulated bubble
<ide> // listeners still fire for the invalid event.
<ide> listenToNonDelegatedEvent('invalid', domElement);
<del> if (!enableEagerRootListeners) {
<del> // For controlled components we always need to ensure we're listening
<del> // to onChange. Even if there is no listener.
<del> ensureListeningTo(rootContainerElement, 'onChange', domElement);
<del> }
<ide> break;
<ide> default:
<ide> props = rawProps;
<ide> export function diffProperties(
<ide> if (__DEV__ && typeof nextProp !== 'function') {
<ide> warnForInvalidEventListener(propKey, nextProp);
<ide> }
<del> if (!enableEagerRootListeners) {
<del> ensureListeningTo(rootContainerElement, propKey, domElement);
<del> } else if (propKey === 'onScroll') {
<add> if (propKey === 'onScroll') {
<ide> listenToNonDelegatedEvent('scroll', domElement);
<ide> }
<ide> }
<ide> export function diffHydratedProperties(
<ide> // We listen to this event in case to ensure emulated bubble
<ide> // listeners still fire for the invalid event.
<ide> listenToNonDelegatedEvent('invalid', domElement);
<del> if (!enableEagerRootListeners) {
<del> // For controlled components we always need to ensure we're listening
<del> // to onChange. Even if there is no listener.
<del> ensureListeningTo(rootContainerElement, 'onChange', domElement);
<del> }
<ide> break;
<ide> case 'option':
<ide> ReactDOMOptionValidateProps(domElement, rawProps);
<ide> export function diffHydratedProperties(
<ide> // We listen to this event in case to ensure emulated bubble
<ide> // listeners still fire for the invalid event.
<ide> listenToNonDelegatedEvent('invalid', domElement);
<del> if (!enableEagerRootListeners) {
<del> // For controlled components we always need to ensure we're listening
<del> // to onChange. Even if there is no listener.
<del> ensureListeningTo(rootContainerElement, 'onChange', domElement);
<del> }
<ide> break;
<ide> case 'textarea':
<ide> ReactDOMTextareaInitWrapperState(domElement, rawProps);
<ide> // We listen to this event in case to ensure emulated bubble
<ide> // listeners still fire for the invalid event.
<ide> listenToNonDelegatedEvent('invalid', domElement);
<del> if (!enableEagerRootListeners) {
<del> // For controlled components we always need to ensure we're listening
<del> // to onChange. Even if there is no listener.
<del> ensureListeningTo(rootContainerElement, 'onChange', domElement);
<del> }
<ide> break;
<ide> }
<ide>
<ide> export function diffHydratedProperties(
<ide> if (__DEV__ && typeof nextProp !== 'function') {
<ide> warnForInvalidEventListener(propKey, nextProp);
<ide> }
<del> if (!enableEagerRootListeners) {
<del> ensureListeningTo(rootContainerElement, propKey, domElement);
<del> } else if (propKey === 'onScroll') {
<add> if (propKey === 'onScroll') {
<ide> listenToNonDelegatedEvent('scroll', domElement);
<ide> }
<ide> }
<ide><path>packages/react-dom/src/client/ReactDOMEventHandle.js
<ide> import type {
<ide>
<ide> import {allNativeEvents} from '../events/EventRegistry';
<ide> import {
<del> getClosestInstanceFromNode,
<ide> getEventHandlerListeners,
<ide> setEventHandlerListeners,
<del> getFiberFromScopeInstance,
<ide> doesTargetHaveEventHandle,
<ide> addEventHandleToTarget,
<ide> } from './ReactDOMComponentTree';
<del>import {ELEMENT_NODE, COMMENT_NODE} from '../shared/HTMLNodeType';
<add>import {ELEMENT_NODE} from '../shared/HTMLNodeType';
<ide> import {listenToNativeEvent} from '../events/DOMPluginEventSystem';
<ide>
<del>import {HostRoot, HostPortal} from 'react-reconciler/src/ReactWorkTags';
<ide> import {IS_EVENT_HANDLE_NON_MANAGED_NODE} from '../events/EventSystemFlags';
<ide>
<ide> import {
<ide> enableScopeAPI,
<ide> enableCreateEventHandleAPI,
<del> enableEagerRootListeners,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import invariant from 'shared/invariant';
<ide>
<ide> type EventHandleOptions = {|
<ide> capture?: boolean,
<ide> |};
<ide>
<del>function getNearestRootOrPortalContainer(node: Fiber): null | Element {
<del> while (node !== null) {
<del> const tag = node.tag;
<del> // Once we encounter a host container or root container
<del> // we can return their DOM instance.
<del> if (tag === HostRoot || tag === HostPortal) {
<del> return node.stateNode.containerInfo;
<del> }
<del> node = node.return;
<del> }
<del> return null;
<del>}
<del>
<ide> function isValidEventTarget(target: EventTarget | ReactScopeInstance): boolean {
<ide> return typeof (target: Object).addEventListener === 'function';
<ide> }
<ide> function createEventHandleListener(
<ide> };
<ide> }
<ide>
<del>function registerEventOnNearestTargetContainer(
<del> targetFiber: Fiber,
<del> domEventName: DOMEventName,
<del> isCapturePhaseListener: boolean,
<del> targetElement: Element | null,
<del>): void {
<del> if (!enableEagerRootListeners) {
<del> // If it is, find the nearest root or portal and make it
<del> // our event handle target container.
<del> let targetContainer = getNearestRootOrPortalContainer(targetFiber);
<del> if (targetContainer === null) {
<del> if (__DEV__) {
<del> console.error(
<del> 'ReactDOM.createEventHandle: setListener called on an target ' +
<del> 'that did not have a corresponding root. This is likely a bug in React.',
<del> );
<del> }
<del> return;
<del> }
<del> if (targetContainer.nodeType === COMMENT_NODE) {
<del> targetContainer = ((targetContainer.parentNode: any): Element);
<del> }
<del> listenToNativeEvent(
<del> domEventName,
<del> isCapturePhaseListener,
<del> targetContainer,
<del> targetElement,
<del> );
<del> }
<del>}
<del>
<ide> function registerReactDOMEvent(
<ide> target: EventTarget | ReactScopeInstance,
<ide> domEventName: DOMEventName,
<ide> isCapturePhaseListener: boolean,
<ide> ): void {
<del> // Check if the target is a DOM element.
<ide> if ((target: any).nodeType === ELEMENT_NODE) {
<del> if (!enableEagerRootListeners) {
<del> const targetElement = ((target: any): Element);
<del> // Check if the DOM element is managed by React.
<del> const targetFiber = getClosestInstanceFromNode(targetElement);
<del> if (targetFiber === null) {
<del> if (__DEV__) {
<del> console.error(
<del> 'ReactDOM.createEventHandle: setListener called on an element ' +
<del> 'target that is not managed by React. Ensure React rendered the DOM element.',
<del> );
<del> }
<del> return;
<del> }
<del> registerEventOnNearestTargetContainer(
<del> targetFiber,
<del> domEventName,
<del> isCapturePhaseListener,
<del> targetElement,
<del> );
<del> }
<add> // Do nothing. We already attached all root listeners.
<ide> } else if (enableScopeAPI && isReactScope(target)) {
<del> if (!enableEagerRootListeners) {
<del> const scopeTarget = ((target: any): ReactScopeInstance);
<del> const targetFiber = getFiberFromScopeInstance(scopeTarget);
<del> if (targetFiber === null) {
<del> // Scope is unmounted, do not proceed.
<del> return;
<del> }
<del> registerEventOnNearestTargetContainer(
<del> targetFiber,
<del> domEventName,
<del> isCapturePhaseListener,
<del> null,
<del> );
<del> }
<add> // Do nothing. We already attached all root listeners.
<ide> } else if (isValidEventTarget(target)) {
<ide> const eventTarget = ((target: any): EventTarget);
<ide> // These are valid event targets, but they are also
<ide><path>packages/react-dom/src/client/ReactDOMHostConfig.js
<ide> import {
<ide> enableFundamentalAPI,
<ide> enableCreateEventHandleAPI,
<ide> enableScopeAPI,
<del> enableEagerRootListeners,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {HostComponent, HostText} from 'react-reconciler/src/ReactWorkTags';
<del>import {
<del> listenToReactEvent,
<del> listenToAllSupportedEvents,
<del>} from '../events/DOMPluginEventSystem';
<add>import {listenToAllSupportedEvents} from '../events/DOMPluginEventSystem';
<ide>
<ide> export type Type = string;
<ide> export type Props = {
<ide> export function makeOpaqueHydratingObject(
<ide> }
<ide>
<ide> export function preparePortalMount(portalInstance: Instance): void {
<del> if (enableEagerRootListeners) {
<del> listenToAllSupportedEvents(portalInstance);
<del> } else {
<del> listenToReactEvent('onMouseEnter', portalInstance, null);
<del> }
<add> listenToAllSupportedEvents(portalInstance);
<ide> }
<ide>
<ide> export function prepareScopeUpdate(
<ide><path>packages/react-dom/src/client/ReactDOMRoot.js
<ide> import {
<ide> unmarkContainerAsRoot,
<ide> } from './ReactDOMComponentTree';
<ide> import {listenToAllSupportedEvents} from '../events/DOMPluginEventSystem';
<del>import {eagerlyTrapReplayableEvents} from '../events/ReactDOMEventReplaying';
<ide> import {
<ide> ELEMENT_NODE,
<ide> COMMENT_NODE,
<ide> DOCUMENT_NODE,
<ide> DOCUMENT_FRAGMENT_NODE,
<ide> } from '../shared/HTMLNodeType';
<del>import {ensureListeningTo} from './ReactDOMComponent';
<ide>
<ide> import {
<ide> createContainer,
<ide> import {
<ide> registerMutableSourceForHydration,
<ide> } from 'react-reconciler/src/ReactFiberReconciler';
<ide> import invariant from 'shared/invariant';
<del>import {enableEagerRootListeners} from 'shared/ReactFeatureFlags';
<ide> import {
<ide> BlockingRoot,
<ide> ConcurrentRoot,
<ide> function createRootImpl(
<ide> null;
<ide> const root = createContainer(container, tag, hydrate, hydrationCallbacks);
<ide> markContainerAsRoot(root.current, container);
<del> const containerNodeType = container.nodeType;
<del>
<del> if (enableEagerRootListeners) {
<del> const rootContainerElement =
<del> container.nodeType === COMMENT_NODE ? container.parentNode : container;
<del> listenToAllSupportedEvents(rootContainerElement);
<del> } else {
<del> if (hydrate && tag !== LegacyRoot) {
<del> const doc =
<del> containerNodeType === DOCUMENT_NODE
<del> ? container
<del> : container.ownerDocument;
<del> // We need to cast this because Flow doesn't work
<del> // with the hoisted containerNodeType. If we inline
<del> // it, then Flow doesn't complain. We intentionally
<del> // hoist it to reduce code-size.
<del> eagerlyTrapReplayableEvents(container, ((doc: any): Document));
<del> } else if (
<del> containerNodeType !== DOCUMENT_FRAGMENT_NODE &&
<del> containerNodeType !== DOCUMENT_NODE
<del> ) {
<del> ensureListeningTo(container, 'onMouseEnter', null);
<del> }
<del> }
<add>
<add> const rootContainerElement =
<add> container.nodeType === COMMENT_NODE ? container.parentNode : container;
<add> listenToAllSupportedEvents(rootContainerElement);
<ide>
<ide> if (mutableSources) {
<ide> for (let i = 0; i < mutableSources.length; i++) {
<ide><path>packages/react-dom/src/events/DOMPluginEventSystem.js
<ide> import type {
<ide> } from './ReactSyntheticEventType';
<ide> import type {Fiber} from 'react-reconciler/src/ReactInternalTypes';
<ide>
<del>import {registrationNameDependencies, allNativeEvents} from './EventRegistry';
<add>import {allNativeEvents} from './EventRegistry';
<ide> import {
<ide> IS_CAPTURE_PHASE,
<ide> IS_EVENT_HANDLE_NON_MANAGED_NODE,
<ide> import {
<ide> enableLegacyFBSupport,
<ide> enableCreateEventHandleAPI,
<ide> enableScopeAPI,
<del> enableEagerRootListeners,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {
<ide> invokeGuardedCallbackAndCatchFirstError,
<ide> const listeningMarker =
<ide> .slice(2);
<ide>
<ide> export function listenToAllSupportedEvents(rootContainerElement: EventTarget) {
<del> if (enableEagerRootListeners) {
<del> if ((rootContainerElement: any)[listeningMarker]) {
<del> // Performance optimization: don't iterate through events
<del> // for the same portal container or root node more than once.
<del> // TODO: once we remove the flag, we may be able to also
<del> // remove some of the bookkeeping maps used for laziness.
<del> return;
<del> }
<del> (rootContainerElement: any)[listeningMarker] = true;
<del> allNativeEvents.forEach(domEventName => {
<del> if (!nonDelegatedEvents.has(domEventName)) {
<del> listenToNativeEvent(
<del> domEventName,
<del> false,
<del> ((rootContainerElement: any): Element),
<del> null,
<del> );
<del> }
<add> if ((rootContainerElement: any)[listeningMarker]) {
<add> // Performance optimization: don't iterate through events
<add> // for the same portal container or root node more than once.
<add> // TODO: once we remove the flag, we may be able to also
<add> // remove some of the bookkeeping maps used for laziness.
<add> return;
<add> }
<add> (rootContainerElement: any)[listeningMarker] = true;
<add> allNativeEvents.forEach(domEventName => {
<add> if (!nonDelegatedEvents.has(domEventName)) {
<ide> listenToNativeEvent(
<ide> domEventName,
<del> true,
<add> false,
<ide> ((rootContainerElement: any): Element),
<ide> null,
<ide> );
<del> });
<del> }
<add> }
<add> listenToNativeEvent(
<add> domEventName,
<add> true,
<add> ((rootContainerElement: any): Element),
<add> null,
<add> );
<add> });
<ide> }
<ide>
<ide> export function listenToNativeEvent(
<ide> export function listenToNativeEvent(
<ide> }
<ide> }
<ide>
<del>export function listenToReactEvent(
<del> reactEvent: string,
<del> rootContainerElement: Element,
<del> targetElement: Element | null,
<del>): void {
<del> if (!enableEagerRootListeners) {
<del> const dependencies = registrationNameDependencies[reactEvent];
<del> const dependenciesLength = dependencies.length;
<del> // If the dependencies length is 1, that means we're not using a polyfill
<del> // plugin like ChangeEventPlugin, BeforeInputPlugin, EnterLeavePlugin
<del> // and SelectEventPlugin. We always use the native bubble event phase for
<del> // these plugins and emulate two phase event dispatching. SimpleEventPlugin
<del> // always only has a single dependency and SimpleEventPlugin events also
<del> // use either the native capture event phase or bubble event phase, there
<del> // is no emulation (except for focus/blur, but that will be removed soon).
<del> const isPolyfillEventPlugin = dependenciesLength !== 1;
<del>
<del> if (isPolyfillEventPlugin) {
<del> const listenerSet = getEventListenerSet(rootContainerElement);
<del> // When eager listeners are off, this Set has a dual purpose: it both
<del> // captures which native listeners we registered (e.g. "click__bubble")
<del> // and *React* lazy listeners (e.g. "onClick") so we don't do extra checks.
<del> // This second usage does not exist in the eager mode.
<del> if (!listenerSet.has(reactEvent)) {
<del> listenerSet.add(reactEvent);
<del> for (let i = 0; i < dependenciesLength; i++) {
<del> listenToNativeEvent(
<del> dependencies[i],
<del> false,
<del> rootContainerElement,
<del> targetElement,
<del> );
<del> }
<del> }
<del> } else {
<del> const isCapturePhaseListener =
<del> reactEvent.substr(-7) === 'Capture' &&
<del> // Edge case: onGotPointerCapture and onLostPointerCapture
<del> // end with "Capture" but that's part of their event names.
<del> // The Capture versions would end with CaptureCapture.
<del> // So we have to check against that.
<del> // This check works because none of the events we support
<del> // end with "Pointer".
<del> reactEvent.substr(-14, 7) !== 'Pointer';
<del> listenToNativeEvent(
<del> dependencies[0],
<del> isCapturePhaseListener,
<del> rootContainerElement,
<del> targetElement,
<del> );
<del> }
<del> }
<del>}
<del>
<ide> function addTrappedEventListener(
<ide> targetContainer: EventTarget,
<ide> domEventName: DOMEventName,
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide> import {getClosestInstanceFromNode} from '../client/ReactDOMComponentTree';
<ide>
<ide> import {
<ide> enableLegacyFBSupport,
<del> enableEagerRootListeners,
<ide> decoupleUpdatePriorityFromScheduler,
<ide> } from 'shared/ReactFeatureFlags';
<ide> import {
<ide> export function dispatchEvent(
<ide> if (!_enabled) {
<ide> return;
<ide> }
<del> let allowReplay = true;
<del> if (enableEagerRootListeners) {
<del> // TODO: replaying capture phase events is currently broken
<del> // because we used to do it during top-level native bubble handlers
<del> // but now we use different bubble and capture handlers.
<del> // In eager mode, we attach capture listeners early, so we need
<del> // to filter them out until we fix the logic to handle them correctly.
<del> // This could've been outside the flag but I put it inside to reduce risk.
<del> allowReplay = (eventSystemFlags & IS_CAPTURE_PHASE) === 0;
<del> }
<add>
<add> // TODO: replaying capture phase events is currently broken
<add> // because we used to do it during top-level native bubble handlers
<add> // but now we use different bubble and capture handlers.
<add> // In eager mode, we attach capture listeners early, so we need
<add> // to filter them out until we fix the logic to handle them correctly.
<add> const allowReplay = (eventSystemFlags & IS_CAPTURE_PHASE) === 0;
<add>
<ide> if (
<ide> allowReplay &&
<ide> hasQueuedDiscreteEvents() &&
<ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js
<ide> import type {EventSystemFlags} from './EventSystemFlags';
<ide> import type {FiberRoot} from 'react-reconciler/src/ReactInternalTypes';
<ide> import type {LanePriority} from 'react-reconciler/src/ReactFiberLane';
<ide>
<del>import {
<del> enableSelectiveHydration,
<del> enableEagerRootListeners,
<del>} from 'shared/ReactFeatureFlags';
<add>import {enableSelectiveHydration} from 'shared/ReactFeatureFlags';
<ide> import {
<ide> unstable_runWithPriority as runWithPriority,
<ide> unstable_scheduleCallback as scheduleCallback,
<ide> type PointerEvent = Event & {
<ide> };
<ide>
<ide> import {IS_REPLAYED} from './EventSystemFlags';
<del>import {listenToNativeEvent} from './DOMPluginEventSystem';
<ide>
<ide> type QueuedReplayableEvent = {|
<ide> blockedOn: null | Container | SuspenseInstance,
<ide> const discreteReplayableEvents: Array<DOMEventName> = [
<ide> 'submit',
<ide> ];
<ide>
<del>const continuousReplayableEvents: Array<DOMEventName> = [
<del> 'dragenter',
<del> 'dragleave',
<del> 'focusin',
<del> 'focusout',
<del> 'mouseover',
<del> 'mouseout',
<del> 'pointerover',
<del> 'pointerout',
<del> 'gotpointercapture',
<del> 'lostpointercapture',
<del>];
<del>
<ide> export function isReplayableDiscreteEvent(eventType: DOMEventName): boolean {
<ide> return discreteReplayableEvents.indexOf(eventType) > -1;
<ide> }
<ide>
<del>function trapReplayableEventForContainer(
<del> domEventName: DOMEventName,
<del> container: Container,
<del>) {
<del> // When the flag is on, we do this in a unified codepath elsewhere.
<del> if (!enableEagerRootListeners) {
<del> listenToNativeEvent(domEventName, false, ((container: any): Element), null);
<del> }
<del>}
<del>
<del>export function eagerlyTrapReplayableEvents(
<del> container: Container,
<del> document: Document,
<del>) {
<del> // When the flag is on, we do this in a unified codepath elsewhere.
<del> if (!enableEagerRootListeners) {
<del> // Discrete
<del> discreteReplayableEvents.forEach(domEventName => {
<del> trapReplayableEventForContainer(domEventName, container);
<del> });
<del> // Continuous
<del> continuousReplayableEvents.forEach(domEventName => {
<del> trapReplayableEventForContainer(domEventName, container);
<del> });
<del> }
<del>}
<del>
<ide> function createQueuedReplayableEvent(
<ide> blockedOn: null | Container | SuspenseInstance,
<ide> domEventName: DOMEventName,
<ide><path>packages/react-dom/src/events/__tests__/DOMPluginEventSystem-test.internal.js
<ide> describe('DOMPluginEventSystem', () => {
<ide> expect(log[5]).toEqual(['bubble', buttonElement]);
<ide> });
<ide>
<del> // @gate experimental && enableEagerRootListeners
<add> // @gate experimental
<ide> it('propagates known createEventHandle events through portals without inner listeners', () => {
<ide> const buttonRef = React.createRef();
<ide> const divRef = React.createRef();
<ide><path>packages/react-dom/src/events/plugins/SelectEventPlugin.js
<ide> import {canUseDOM} from 'shared/ExecutionEnvironment';
<ide> import {SyntheticEvent} from '../../events/SyntheticEvent';
<ide> import isTextInputElement from '../isTextInputElement';
<ide> import shallowEqual from 'shared/shallowEqual';
<del>import {enableEagerRootListeners} from 'shared/ReactFeatureFlags';
<ide>
<ide> import {registerTwoPhaseEvent} from '../EventRegistry';
<ide> import getActiveElement from '../../client/getActiveElement';
<del>import {
<del> getNodeFromInstance,
<del> getEventListenerSet,
<del>} from '../../client/ReactDOMComponentTree';
<add>import {getNodeFromInstance} from '../../client/ReactDOMComponentTree';
<ide> import {hasSelectionCapabilities} from '../../client/ReactInputSelection';
<ide> import {DOCUMENT_NODE} from '../../shared/HTMLNodeType';
<ide> import {accumulateTwoPhaseListeners} from '../DOMPluginEventSystem';
<ide> function extractEvents(
<ide> eventSystemFlags: EventSystemFlags,
<ide> targetContainer: EventTarget,
<ide> ) {
<del> if (!enableEagerRootListeners) {
<del> const eventListenerSet = getEventListenerSet(targetContainer);
<del> // Track whether all listeners exists for this plugin. If none exist, we do
<del> // not extract events. See #3639.
<del> if (
<del> // If we are handling selectionchange, then we don't need to
<del> // check for the other dependencies, as selectionchange is only
<del> // event attached from the onChange plugin and we don't expose an
<del> // onSelectionChange event from React.
<del> domEventName !== 'selectionchange' &&
<del> !eventListenerSet.has('onSelect') &&
<del> !eventListenerSet.has('onSelectCapture')
<del> ) {
<del> return;
<del> }
<del> }
<del>
<ide> const targetNode = targetInst ? getNodeFromInstance(targetInst) : window;
<ide>
<ide> switch (domEventName) {
<ide><path>packages/react-dom/src/events/plugins/__tests__/SimpleEventPlugin-test.js
<ide> describe('SimpleEventPlugin', function() {
<ide> return nativeAddEventListener.apply(this, arguments);
<ide> };
<ide>
<del> ReactDOM.render(
<del> <div
<del> // Affected by the intervention:
<del> // https://github.com/facebook/react/issues/19651
<del> onTouchStart={() => {}}
<del> onTouchMove={() => {}}
<del> onWheel={() => {}}
<del> // A few events that should be unaffected:
<del> onClick={() => {}}
<del> onScroll={() => {}}
<del> onTouchEnd={() => {}}
<del> onChange={() => {}}
<del> onPointerDown={() => {}}
<del> onPointerMove={() => {}}
<del> />,
<del> container,
<del> );
<del>
<del> if (gate(flags => flags.enableEagerRootListeners)) {
<del> expect(passiveEvents).toEqual([
<del> 'touchstart',
<del> 'touchstart',
<del> 'touchmove',
<del> 'touchmove',
<del> 'wheel',
<del> 'wheel',
<del> ]);
<del> } else {
<del> expect(passiveEvents).toEqual(['touchstart', 'touchmove', 'wheel']);
<del> }
<add> ReactDOM.render(<div />, container);
<add>
<add> expect(passiveEvents).toEqual([
<add> 'touchstart',
<add> 'touchstart',
<add> 'touchmove',
<add> 'touchmove',
<add> 'wheel',
<add> 'wheel',
<add> ]);
<ide> });
<ide> });
<ide> });
<ide><path>packages/shared/ReactFeatureFlags.js
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide>
<ide> export const enableDiscreteEventFlushingChange = false;
<ide>
<del>export const enableEagerRootListeners = true;
<del>
<ide> export const enableDoubleInvokingEffects = false;
<ide><path>packages/shared/forks/ReactFeatureFlags.native-fb.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.native-oss.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.native.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.test-renderer.www.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = false;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.testing.www.js
<ide> export const enableNewReconciler = false;
<ide> export const deferRenderPhaseUpdateToNextBatch = true;
<ide> export const decoupleUpdatePriorityFromScheduler = false;
<ide> export const enableDiscreteEventFlushingChange = true;
<del>export const enableEagerRootListeners = true;
<ide>
<ide> export const enableDoubleInvokingEffects = false;
<ide>
<ide><path>packages/shared/forks/ReactFeatureFlags.www-dynamic.js
<ide> export const enableFilterEmptyStringAttributesDOM = __VARIANT__;
<ide> export const enableLegacyFBSupport = __VARIANT__;
<ide> export const decoupleUpdatePriorityFromScheduler = __VARIANT__;
<ide> export const skipUnmountedBoundaries = __VARIANT__;
<del>export const enableEagerRootListeners = !__VARIANT__;
<ide>
<ide> // Enable this flag to help with concurrent mode debugging.
<ide> // It logs information to the console about React scheduling, rendering, and commit phases.
<ide><path>packages/shared/forks/ReactFeatureFlags.www.js
<ide> export const {
<ide> decoupleUpdatePriorityFromScheduler,
<ide> enableDebugTracing,
<ide> skipUnmountedBoundaries,
<del> enableEagerRootListeners,
<ide> enableDoubleInvokingEffects,
<ide> } = dynamicFeatureFlags;
<ide> | 21 |
Javascript | Javascript | add tests for current ast plugin format | 101322cdc5cb4bc669322d9f4c117de3c7dd228d | <ide><path>packages/ember-template-compiler/tests/system/compile_options_test.js
<ide> moduleFor(
<ide> );
<ide>
<ide> let customTransformCounter = 0;
<del>class CustomTransform {
<add>class LegacyCustomTransform {
<ide> constructor(options) {
<ide> customTransformCounter++;
<ide> this.options = options;
<ide> class CustomTransform {
<ide> }
<ide> }
<ide>
<add>function customTransform() {
<add> customTransformCounter++;
<add>
<add> return {
<add> name: 'remove-data-test',
<add>
<add> visitor: {
<add> ElementNode(node) {
<add> for (var i = 0; i < node.attributes.length; i++) {
<add> let attribute = node.attributes[i];
<add>
<add> if (attribute.name === 'data-test') {
<add> node.attributes.splice(i, 1);
<add> }
<add> }
<add> },
<add> },
<add> };
<add>}
<add>
<ide> class CustomPluginsTests extends RenderingTestCase {
<ide> afterEach() {
<ide> customTransformCounter = 0;
<ide> class CustomPluginsTests extends RenderingTestCase {
<ide> }
<ide> }
<ide>
<add>moduleFor(
<add> 'ember-template-compiler: registerPlugin with a custom plugins in legacy format',
<add> class extends CustomPluginsTests {
<add> beforeEach() {
<add> registerPlugin('ast', LegacyCustomTransform);
<add> }
<add>
<add> afterEach() {
<add> unregisterPlugin('ast', LegacyCustomTransform);
<add> return super.afterEach();
<add> }
<add>
<add> ['@test custom registered plugins are deduplicated'](assert) {
<add> registerPlugin('ast', LegacyCustomTransform);
<add> this.registerTemplate(
<add> 'application',
<add> '<div data-test="foo" data-blah="derp" class="hahaha"></div>'
<add> );
<add> assert.equal(customTransformCounter, 1, 'transform should only be instantiated once');
<add> }
<add> }
<add>);
<add>
<ide> moduleFor(
<ide> 'ember-template-compiler: registerPlugin with a custom plugins',
<ide> class extends CustomPluginsTests {
<ide> beforeEach() {
<del> registerPlugin('ast', CustomTransform);
<add> registerPlugin('ast', customTransform);
<ide> }
<ide>
<ide> afterEach() {
<del> unregisterPlugin('ast', CustomTransform);
<add> unregisterPlugin('ast', customTransform);
<ide> return super.afterEach();
<ide> }
<ide>
<ide> ['@test custom registered plugins are deduplicated'](assert) {
<del> registerPlugin('ast', CustomTransform);
<add> registerPlugin('ast', customTransform);
<ide> this.registerTemplate(
<ide> 'application',
<ide> '<div data-test="foo" data-blah="derp" class="hahaha"></div>'
<ide> moduleFor(
<ide> }
<ide> );
<ide>
<add>moduleFor(
<add> 'ember-template-compiler: custom plugins in legacy format passed to compile',
<add> class extends RenderingTestCase {
<add> // override so that we can provide custom AST plugins to compile
<add> compile(templateString) {
<add> return compile(templateString, {
<add> plugins: {
<add> ast: [LegacyCustomTransform],
<add> },
<add> });
<add> }
<add> }
<add>);
<add>
<ide> moduleFor(
<ide> 'ember-template-compiler: custom plugins passed to compile',
<ide> class extends RenderingTestCase {
<ide> // override so that we can provide custom AST plugins to compile
<ide> compile(templateString) {
<ide> return compile(templateString, {
<ide> plugins: {
<del> ast: [CustomTransform],
<add> ast: [customTransform],
<ide> },
<ide> });
<ide> } | 1 |
Ruby | Ruby | use tt in doc for action_mailer [ci skip] | 70f75caaa3dc78e44e2a1c9bc97b86e1bed84d25 | <ide><path>actionmailer/lib/action_mailer/rescuable.rb
<ide> # frozen_string_literal: true
<ide>
<ide> module ActionMailer #:nodoc:
<del> # Provides `rescue_from` for mailers. Wraps mailer action processing,
<add> # Provides +rescue_from+ for mailers. Wraps mailer action processing,
<ide> # mail job processing, and mail delivery.
<ide> module Rescuable
<ide> extend ActiveSupport::Concern | 1 |
Python | Python | use nonexperimental lso api in base_task.py | cc12499b45c32463ceed05327a44e2b283b3474b | <ide><path>official/core/base_task.py
<ide> def create_optimizer(cls, optimizer_config: OptimizationConfig,
<ide> optimizer,
<ide> use_float16=runtime_config.mixed_precision_dtype == "float16",
<ide> loss_scale=runtime_config.loss_scale,
<del> use_experimental_api=True)
<add> use_experimental_api=False)
<ide>
<ide> return optimizer
<ide>
<ide><path>official/vision/beta/projects/yolo/tasks/image_classification.py
<ide> def train_step(self, inputs, model, optimizer, metrics=None):
<ide>
<ide> # For mixed_precision policy, when LossScaleOptimizer is used, loss is
<ide> # scaled for numerical stability.
<del> if isinstance(
<del> optimizer, tf.keras.mixed_precision.experimental.LossScaleOptimizer):
<add> if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
<ide> scaled_loss = optimizer.get_scaled_loss(scaled_loss)
<ide>
<ide> tvars = model.trainable_variables
<ide> grads = tape.gradient(scaled_loss, tvars)
<ide> # Scales back gradient before apply_gradients when LossScaleOptimizer is
<ide> # used.
<del> if isinstance(
<del> optimizer, tf.keras.mixed_precision.experimental.LossScaleOptimizer):
<add> if isinstance(optimizer, tf.keras.mixed_precision.LossScaleOptimizer):
<ide> grads = optimizer.get_unscaled_gradients(grads)
<ide>
<ide> # Apply gradient clipping.
<ide><path>official/vision/beta/projects/yt8m/tasks/yt8m_task.py
<ide> def train_step(self, inputs, model, optimizer, metrics=None):
<ide> # For mixed_precision policy, when LossScaleOptimizer is used, loss is
<ide> # scaled for numerical stability.
<ide> if isinstance(optimizer,
<del> tf.keras.mixed_precision.experimental.LossScaleOptimizer):
<add> tf.keras.mixed_precision.LossScaleOptimizer):
<ide> scaled_loss = optimizer.get_scaled_loss(scaled_loss)
<ide>
<ide> tvars = model.trainable_variables
<ide> grads = tape.gradient(scaled_loss, tvars)
<ide> # Scales back gradient before apply_gradients when LossScaleOptimizer is
<ide> # used.
<ide> if isinstance(optimizer,
<del> tf.keras.mixed_precision.experimental.LossScaleOptimizer):
<add> tf.keras.mixed_precision.LossScaleOptimizer):
<ide> grads = optimizer.get_unscaled_gradients(grads)
<ide>
<ide> # Apply gradient clipping. | 3 |
Text | Text | fix minor typos | 2333f7c1b882dff09b944967a29162f9aca42e7d | <ide><path>docs/basic-features/typescript.md
<ide> npm run dev
<ide>
<ide> # You'll see instructions like these:
<ide> #
<del># Please install typescript, @types/react, and @types/node by running:
<add># Please install TypeScript, @types/react, and @types/node by running:
<ide> #
<ide> # yarn add --dev typescript @types/react @types/node
<ide> #
<ide><path>examples/with-aws-amplify-typescript/README.md
<del># AWS Amplify and Typescript with NextJS
<add># AWS Amplify and TypeScript with NextJS
<ide>
<ide> [](https://console.aws.amazon.com/amplify/home#/deploy?repo=https://github.com/vercel/next.js/tree/canary/examples/with-aws-amplify-typescript)
<ide>
<ide><path>examples/with-chakra-ui-typescript/README.md
<del># Example app with [chakra-ui](https://github.com/chakra-ui/chakra-ui) and Typescript
<add># Example app with [chakra-ui](https://github.com/chakra-ui/chakra-ui) and TypeScript
<ide>
<del>This example features how to use [chakra-ui](https://github.com/chakra-ui/chakra-ui) as the component library within a Next.js app with typescript.
<add>This example features how to use [chakra-ui](https://github.com/chakra-ui/chakra-ui) as the component library within a Next.js app with TypeScript.
<ide>
<ide> Next.js and chakra-ui have built-in TypeScript declarations, so we'll get autocompletion for their modules straight away.
<ide> | 3 |
PHP | PHP | apply fixes from styleci | 2dbb28ffe45804c408a79f9817a6b560de3ed82a | <ide><path>tests/Cache/RedisCacheIntegrationTest.php
<ide> <?php
<ide>
<add>use Mockery as m;
<ide> use Illuminate\Cache\RedisStore;
<ide> use Illuminate\Cache\Repository;
<del>use Mockery as m;
<ide>
<ide> class RedisCacheTest extends PHPUnit_Framework_TestCase
<ide> {
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> <?php
<ide>
<ide> use Illuminate\Database\Capsule\Manager as DB;
<del>use Illuminate\Database\Eloquent\Model as Eloquent;
<ide> use Illuminate\Database\Eloquent\Relations\Pivot;
<add>use Illuminate\Database\Eloquent\Model as Eloquent;
<ide> use Illuminate\Database\Eloquent\Relations\Relation;
<ide> use Illuminate\Pagination\AbstractPaginator as Paginator;
<ide>
<ide><path>tests/Database/SeedCommandTest.php
<ide> <?php
<ide>
<add>use Illuminate\Database\Seeder;
<ide> use Illuminate\Container\Container;
<del>use Illuminate\Database\ConnectionResolverInterface;
<ide> use Illuminate\Database\Console\Seeds\SeedCommand;
<del>use Illuminate\Database\Seeder;
<add>use Illuminate\Database\ConnectionResolverInterface;
<ide>
<ide> class SeedCommandTest extends PHPUnit_Framework_TestCase
<ide> { | 3 |
PHP | PHP | provide hook into job creation for sqs | 0dd091ed8f8c2416628bf245d0bc6e81232a9a07 | <ide><path>src/Illuminate/Queue/SqsQueue.php
<ide> class SqsQueue extends Queue implements QueueContract
<ide> */
<ide> protected $default;
<ide>
<add> /**
<add> * The job creator callback.
<add> *
<add> * @var callable|null
<add> */
<add> protected $jobCreator;
<add>
<ide> /**
<ide> * Create a new Amazon SQS queue instance.
<ide> *
<ide> public function pop($queue = null)
<ide> );
<ide>
<ide> if (count($response['Messages']) > 0) {
<del> return new SqsJob($this->container, $this->sqs, $queue, $response['Messages'][0]);
<add> if ($this->jobCreator) {
<add> return call_user_func($this->jobCreator, $this->container, $this->sqs, $queue, $response);
<add> } else {
<add> return new SqsJob($this->container, $this->sqs, $queue, $response['Messages'][0]);
<add> }
<ide> }
<ide> }
<ide>
<add> /**
<add> * Define the job creator callback for the connection.
<add> *
<add> * @param callable $callback
<add> * @return $this
<add> */
<add> public function createJobsUsing(callable $callback)
<add> {
<add> $this->jobCreator = $callback;
<add>
<add> return $this;
<add> }
<add>
<ide> /**
<ide> * Get the queue or return the default.
<ide> *
<ide><path>tests/Queue/QueueSqsQueueTest.php
<ide> public function testPopProperlyPopsJobOffOfSqs()
<ide> $this->assertInstanceOf('Illuminate\Queue\Jobs\SqsJob', $result);
<ide> }
<ide>
<add> public function testPopProperlyPopsJobOffOfSqsWithCustomJobCreator()
<add> {
<add> $queue = $this->getMock('Illuminate\Queue\SqsQueue', ['getQueue'], [$this->sqs, $this->queueName, $this->account]);
<add> $queue->createJobsUsing(function () { return 'job!'; });
<add> $queue->setContainer(m::mock('Illuminate\Container\Container'));
<add> $queue->expects($this->once())->method('getQueue')->with($this->queueName)->will($this->returnValue($this->queueUrl));
<add> $this->sqs->shouldReceive('receiveMessage')->once()->with(['QueueUrl' => $this->queueUrl, 'AttributeNames' => ['ApproximateReceiveCount']])->andReturn($this->mockedReceiveMessageResponseModel);
<add> $result = $queue->pop($this->queueName);
<add> $this->assertEquals('job!', $result);
<add> }
<add>
<ide> public function testDelayedPushWithDateTimeProperlyPushesJobOntoSqs()
<ide> {
<ide> $now = Carbon\Carbon::now(); | 2 |
Text | Text | ignore no-literal-urls in changelogs | 6fc17fbec91b2a7c694035136f1d6fd8b4902213 | <ide><path>doc/changelogs/CHANGELOG_ARCHIVE.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_IOJS.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V010.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V012.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V10.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V11.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V12.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V13.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V4.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V5.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V6.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V7.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V8.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr>
<ide><path>doc/changelogs/CHANGELOG_V9.md
<ide>
<ide> <!--lint disable prohibited-strings-->
<ide> <!--lint disable maximum-line-length-->
<add><!--lint disable no-literal-urls-->
<ide>
<ide> <table>
<ide> <tr> | 14 |
Javascript | Javascript | clean the structure of conditons in parseweekday | 1cee6e74d56caea332ba8b41da6445d43113e408 | <ide><path>src/lib/units/day-of-week.js
<ide> addWeekParseToken(['d', 'e', 'E'], function (input, week, config, token) {
<ide> // HELPERS
<ide>
<ide> function parseWeekday(input, locale) {
<del> if (typeof input === 'string') {
<del> if (!isNaN(input)) {
<del> input = parseInt(input, 10);
<del> }
<del> else {
<del> input = locale.weekdaysParse(input);
<del> if (typeof input !== 'number') {
<del> return null;
<del> }
<del> }
<add> if (typeof input !== 'string') {
<add> return input;
<add> }
<add>
<add> if (!isNaN(input)) {
<add> return parseInt(input, 10);
<ide> }
<del> return input;
<add>
<add> input = locale.weekdaysParse(input);
<add> if (typeof input === 'number') {
<add> return input;
<add> }
<add>
<add> return null;
<ide> }
<ide>
<ide> // LOCALES | 1 |
Ruby | Ruby | eliminate another curl call | 951cf09d4b76ffa14b76f089e30b4be06cf00011 | <ide><path>Library/Homebrew/dev-cmd/pr-pull.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "download_strategy"
<ide> require "cli/parser"
<ide> require "utils/github"
<ide> require "tmpdir"
<ide> require "bintray"
<ide>
<del>class CurlNoResumeDownloadStrategy < CurlDownloadStrategy
<del> private
<del>
<del> def _fetch(url:, resolved_url:)
<del> curl("--location", "--remote-time", "--create-dirs", "--output", temporary_path, resolved_url)
<del> end
<del>end
<del>
<ide> module Homebrew
<ide> module_function
<ide>
<ide> def formulae_need_bottles?(tap, original_commit)
<ide> nil
<ide> end
<ide>
<add> def download_artifact(url, dir, pr)
<add> token, username = GitHub.api_credentials
<add> case GitHub.api_credentials_type
<add> when :env_username_password, :keychain_username_password
<add> curl_args = ["--user", "#{username}:#{token}"]
<add> when :env_token
<add> curl_args = ["--header", "Authorization: token #{token}"]
<add> when :none
<add> raise Error, "Credentials must be set to access the Artifacts API"
<add> end
<add>
<add> # Download the artifact as a zip file and unpack it into `dir`. This is
<add> # preferred over system `curl` and `tar` as this leverages the Homebrew
<add> # cache to avoid repeated downloads of (possibly large) bottles.
<add> FileUtils.chdir dir do
<add> downloader = GitHubArtifactDownloadStrategy.new(url, "artifact", pr, curl_args: curl_args, secrets: [token])
<add> downloader.fetch
<add> downloader.stage
<add> end
<add> end
<add>
<ide> def pr_pull
<ide> pr_pull_args.parse
<ide>
<ide> def pr_pull
<ide>
<ide> workflow = args.workflow || "tests.yml"
<ide> artifact = args.artifact || "bottles"
<del> tap = Tap.fetch(args.tap || "homebrew/core")
<add> tap = Tap.fetch(args.tap || CoreTap.instance.name)
<ide>
<ide> setup_git_environment!
<ide>
<ide> def pr_pull
<ide> next
<ide> end
<ide>
<del> GitHub.fetch_artifact(user, repo, pr, dir, workflow_id: workflow,
<del> artifact_name: artifact,
<del> strategy: CurlNoResumeDownloadStrategy)
<add> url = GitHub.get_artifact_url(user, repo, pr, workflow_id: workflow, artifact_name: artifact)
<add> download_artifact(url, dir, pr)
<ide>
<ide> if Homebrew.args.dry_run?
<ide> puts "brew bottle --merge --write #{Dir["*.json"].join " "}"
<ide> def pr_pull
<ide> end
<ide> end
<ide> end
<add>
<add>class GitHubArtifactDownloadStrategy < AbstractFileDownloadStrategy
<add> def fetch
<add> ohai "Downloading #{url}"
<add> if cached_location.exist?
<add> puts "Already downloaded: #{cached_location}"
<add> else
<add> begin
<add> curl "--location", "--create-dirs", "--output", temporary_path, url,
<add> *meta.fetch(:curl_args, []),
<add> secrets: meta.fetch(:secrets, [])
<add> rescue ErrorDuringExecution
<add> raise CurlDownloadStrategyError, url
<add> end
<add> ignore_interrupts do
<add> cached_location.dirname.mkpath
<add> temporary_path.rename(cached_location)
<add> symlink_location.dirname.mkpath
<add> end
<add> end
<add> FileUtils.ln_s cached_location.relative_path_from(symlink_location.dirname), symlink_location, force: true
<add> end
<add>
<add> private
<add>
<add> def resolved_basename
<add> "artifact.zip"
<add> end
<add>end
<ide><path>Library/Homebrew/utils/github.rb
<ide> # frozen_string_literal: true
<ide>
<del>require "download_strategy"
<ide> require "tempfile"
<ide> require "uri"
<ide>
<ide> def dispatch_event(user, repo, event, **payload)
<ide> scopes: CREATE_ISSUE_FORK_OR_PR_SCOPES)
<ide> end
<ide>
<del> def fetch_artifact(user, repo, pr, dir,
<del> workflow_id: "tests.yml", artifact_name: "bottles", strategy: CurlDownloadStrategy)
<add> def get_artifact_url(user, repo, pr, workflow_id: "tests.yml", artifact_name: "bottles")
<ide> scopes = CREATE_ISSUE_FORK_OR_PR_SCOPES
<ide> base_url = "#{API_URL}/repos/#{user}/#{repo}"
<ide> pr_payload = open_api("#{base_url}/pulls/#{pr}", scopes: scopes)
<ide> def fetch_artifact(user, repo, pr, dir,
<ide> EOS
<ide> end
<ide>
<del> artifact_url = artifact.first["archive_download_url"]
<del>
<del> token, username = api_credentials
<del> case api_credentials_type
<del> when :env_username_password, :keychain_username_password
<del> curl_args = { user: "#{username}:#{token}" }
<del> when :env_token
<del> curl_args = { header: "Authorization: token #{token}" }
<del> when :none
<del> raise Error, "Credentials must be set to access the Artifacts API"
<del> end
<del>
<del> # Download the artifact as a zip file and unpack it into `dir`. This is
<del> # preferred over system `curl` and `tar` as this leverages the Homebrew
<del> # cache to avoid repeated downloads of (possibly large) bottles.
<del> FileUtils.chdir dir do
<del> curl_args[:cache] = Pathname.new(dir)
<del> curl_args[:secrets] = [token]
<del> downloader = strategy.new(artifact_url, "artifact", pr, **curl_args)
<del> downloader.fetch
<del> downloader.stage
<del> end
<add> artifact.first["archive_download_url"]
<ide> end
<ide>
<ide> def api_errors | 2 |
Ruby | Ruby | reject dot dirs as racks | f818f0e68139fd1e7b2665f0cd415936aa8cc63d | <ide><path>Library/Homebrew/formula.rb
<ide> def self.clear_installed_formulae_cache
<ide> def self.racks
<ide> @racks ||= if HOMEBREW_CELLAR.directory?
<ide> HOMEBREW_CELLAR.subdirs.reject do |rack|
<del> rack.symlink? || rack.subdirs.empty?
<add> rack.symlink? || rack.basename.to_s.start_with?(".") || rack.subdirs.empty?
<ide> end
<ide> else
<ide> [] | 1 |
Text | Text | fix typographical error | 8c101dec1778ffaf8a80f4b6ae06d495a2342bb0 | <ide><path>doc/api/perf_hooks.md
<ide> The standard deviation of the recorded event loop delays.
<ide> ### Measuring the duration of async operations
<ide>
<ide> The following example uses the [Async Hooks][] and Performance APIs to measure
<del>the actual duration of a Timeout operation (including the amount of time it
<add>the actual duration of a Timeout operation (including the amount of time it took
<ide> to execute the callback).
<ide>
<ide> ```js | 1 |
Javascript | Javascript | blacklist the attribute `usemap` | 234053fc9ad90e0d05be7e8359c6af66be94c094 | <ide><path>src/ngSanitize/sanitize.js
<ide> var validElements = angular.extend({},
<ide> optionalEndTagElements);
<ide>
<ide> //Attributes that have href and hence need to be sanitized
<del>var uriAttrs = toMap("background,cite,href,longdesc,src,usemap,xlink:href");
<add>var uriAttrs = toMap("background,cite,href,longdesc,src,xlink:href");
<ide>
<ide> var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
<ide> 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
<ide><path>test/ngSanitize/sanitizeSpec.js
<ide> describe('HTML', function() {
<ide>
<ide> it('should remove unsafe value', function() {
<ide> expectHTML('<a href="javascript:alert()">').toEqual('<a></a>');
<add> expectHTML('<img src="foo.gif" usemap="#foomap">').toEqual('<img src="foo.gif">');
<ide> });
<ide>
<ide> it('should handle self closed elements', function() { | 2 |
Python | Python | update version [ci skip] | a0fb1acb104a88c5dff8ccfdf6d5ae6c049c627e | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "2.2.3.dev0"
<add>__version__ = "2.2.3"
<ide> __release__ = True
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" | 1 |
Text | Text | fix logic in rules+model entity example [ci skip] | 7fc39f124c2bf9b62c63caccd005e9ae7add078b | <ide><path>website/docs/usage/rule-based-matching.md
<ide> def expand_person_entities(doc):
<ide> if prev_token.text in ("Dr", "Dr.", "Mr", "Mr.", "Ms", "Ms."):
<ide> new_ent = Span(doc, ent.start - 1, ent.end, label=ent.label)
<ide> new_ents.append(new_ent)
<add> else:
<add> new_ents.append(ent)
<ide> else:
<ide> new_ents.append(ent)
<ide> doc.ents = new_ents | 1 |
Ruby | Ruby | request method explanations | 237272e049e409c9f620dfadb7cf0688e8c91b0f | <ide><path>actionpack/lib/action_dispatch/http/request.rb
<ide> def method_symbol
<ide> end
<ide>
<ide> # Is this a GET (or HEAD) request?
<del> # Equivalent to <tt>request.request_method == :get</tt>.
<add> # Equivalent to <tt>request.request_method_symbol == :get</tt>.
<ide> def get?
<ide> HTTP_METHOD_LOOKUP[request_method] == :get
<ide> end
<ide>
<ide> # Is this a POST request?
<del> # Equivalent to <tt>request.request_method == :post</tt>.
<add> # Equivalent to <tt>request.request_method_symbol == :post</tt>.
<ide> def post?
<ide> HTTP_METHOD_LOOKUP[request_method] == :post
<ide> end
<ide>
<ide> # Is this a PUT request?
<del> # Equivalent to <tt>request.request_method == :put</tt>.
<add> # Equivalent to <tt>request.request_method_symbol == :put</tt>.
<ide> def put?
<ide> HTTP_METHOD_LOOKUP[request_method] == :put
<ide> end
<ide>
<ide> # Is this a DELETE request?
<del> # Equivalent to <tt>request.request_method == :delete</tt>.
<add> # Equivalent to <tt>request.request_method_symbol == :delete</tt>.
<ide> def delete?
<ide> HTTP_METHOD_LOOKUP[request_method] == :delete
<ide> end
<ide>
<ide> # Is this a HEAD request?
<del> # Equivalent to <tt>request.method == :head</tt>.
<add> # Equivalent to <tt>request.method_symbol == :head</tt>.
<ide> def head?
<ide> HTTP_METHOD_LOOKUP[method] == :head
<ide> end | 1 |
PHP | PHP | implement more parts of the request class | fb829bdd7b31330b968d067e868d7713975d4921 | <ide><path>lib/Cake/Network/Http/Request.php
<ide>
<ide> /**
<ide> * Implements methods for HTTP requests.
<add> *
<add> * Used by Cake\Network\Http\Client to contain request information
<add> * for making requests.
<ide> */
<ide> class Request {
<ide>
<ide> class Request {
<ide> 'User-Agent' => 'CakePHP'
<ide> ];
<ide>
<add>/**
<add> * Get/Set the HTTP method.
<add> *
<add> * @param string|null $method The method for the request.
<add> * @return mixed Either this or the current method.
<add> * @throws Cake\Error\Exception On invalid methods.
<add> */
<ide> public function method($method = null) {
<ide> if ($method === null) {
<ide> return $this->_method;
<ide> public function method($method = null) {
<ide> return $this;
<ide> }
<ide>
<add>/**
<add> * Get/Set the url for the request.
<add> *
<add> * @param string|null $url The url for the request. Leave null for get
<add> * @return mixed Either $this or the url value.
<add> */
<ide> public function url($url = null) {
<ide> if ($url === null) {
<ide> return $this->_url; | 1 |
Python | Python | add comment for a note of caution | 703c2925b3ead8d3f23fc9acee1d90b9c7d46835 | <ide><path>keras/backend/tensorflow_backend.py
<ide> def shape(x):
<ide> def int_shape(x):
<ide> '''Returns the shape of a tensor as a tuple of
<ide> integers or None entries.
<add> Note that this function only works with TensorFlow.
<ide> '''
<ide> shape = x.get_shape()
<ide> return tuple([i.__int__() for i in shape]) | 1 |
Go | Go | fix some data races | 7917a36cc787ada58987320e67cc6d96858f3b55 | <ide><path>api/types/network/network.go
<ide> type EndpointIPAMConfig struct {
<ide> LinkLocalIPs []string `json:",omitempty"`
<ide> }
<ide>
<add>// Copy makes a copy of the endpoint ipam config
<add>func (cfg *EndpointIPAMConfig) Copy() *EndpointIPAMConfig {
<add> cfgCopy := *cfg
<add> cfgCopy.LinkLocalIPs = make([]string, 0, len(cfg.LinkLocalIPs))
<add> cfgCopy.LinkLocalIPs = append(cfgCopy.LinkLocalIPs, cfg.LinkLocalIPs...)
<add> return &cfgCopy
<add>}
<add>
<ide> // PeerInfo represents one peer of an overlay network
<ide> type PeerInfo struct {
<ide> Name string
<ide> type EndpointSettings struct {
<ide> MacAddress string
<ide> }
<ide>
<add>// Copy makes a deep copy of `EndpointSettings`
<add>func (es *EndpointSettings) Copy() *EndpointSettings {
<add> epCopy := *es
<add> if es.IPAMConfig != nil {
<add> epCopy.IPAMConfig = es.IPAMConfig.Copy()
<add> }
<add>
<add> if es.Links != nil {
<add> links := make([]string, 0, len(es.Links))
<add> epCopy.Links = append(links, es.Links...)
<add> }
<add>
<add> if es.Aliases != nil {
<add> aliases := make([]string, 0, len(es.Aliases))
<add> epCopy.Aliases = append(aliases, es.Aliases...)
<add> }
<add> return &epCopy
<add>}
<add>
<ide> // NetworkingConfig represents the container's networking configuration for each of its interfaces
<ide> // Carries the networking configs specified in the `docker run` and `docker network connect` commands
<ide> type NetworkingConfig struct {
<ide><path>daemon/container.go
<ide> import (
<ide> "github.com/docker/docker/pkg/signal"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/pkg/truncindex"
<add> "github.com/docker/docker/runconfig"
<ide> "github.com/docker/go-connections/nat"
<ide> )
<ide>
<ide> func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *
<ide> return err
<ide> }
<ide>
<add> runconfig.SetDefaultNetModeIfBlank(hostConfig)
<ide> container.HostConfig = hostConfig
<ide> return container.ToDisk()
<ide> }
<ide><path>daemon/create.go
<ide> func (daemon *Daemon) create(params types.ContainerCreateConfig, managed bool) (
<ide> }
<ide> // Make sure NetworkMode has an acceptable value. We do this to ensure
<ide> // backwards API compatibility.
<del> container.HostConfig = runconfig.SetDefaultNetModeIfBlank(container.HostConfig)
<add> runconfig.SetDefaultNetModeIfBlank(container.HostConfig)
<ide>
<ide> daemon.updateContainerNetworkSettings(container, endpointsConfigs)
<ide>
<ide><path>daemon/inspect.go
<ide> import (
<ide> "github.com/docker/docker/api/types/versions/v1p20"
<ide> "github.com/docker/docker/container"
<ide> "github.com/docker/docker/daemon/network"
<add> "github.com/docker/go-connections/nat"
<ide> )
<ide>
<ide> // ContainerInspect returns low-level information about a
<ide> func (daemon *Daemon) ContainerInspectCurrent(name string, size bool) (*types.Co
<ide> apiNetworks := make(map[string]*networktypes.EndpointSettings)
<ide> for name, epConf := range container.NetworkSettings.Networks {
<ide> if epConf.EndpointSettings != nil {
<del> apiNetworks[name] = epConf.EndpointSettings
<add> // We must make a copy of this pointer object otherwise it can race with other operations
<add> apiNetworks[name] = epConf.EndpointSettings.Copy()
<ide> }
<ide> }
<ide>
<ide> func (daemon *Daemon) ContainerInspectCurrent(name string, size bool) (*types.Co
<ide> HairpinMode: container.NetworkSettings.HairpinMode,
<ide> LinkLocalIPv6Address: container.NetworkSettings.LinkLocalIPv6Address,
<ide> LinkLocalIPv6PrefixLen: container.NetworkSettings.LinkLocalIPv6PrefixLen,
<del> Ports: container.NetworkSettings.Ports,
<ide> SandboxKey: container.NetworkSettings.SandboxKey,
<ide> SecondaryIPAddresses: container.NetworkSettings.SecondaryIPAddresses,
<ide> SecondaryIPv6Addresses: container.NetworkSettings.SecondaryIPv6Addresses,
<ide> func (daemon *Daemon) ContainerInspectCurrent(name string, size bool) (*types.Co
<ide> Networks: apiNetworks,
<ide> }
<ide>
<add> ports := make(nat.PortMap, len(container.NetworkSettings.Ports))
<add> for k, pm := range container.NetworkSettings.Ports {
<add> ports[k] = pm
<add> }
<add> networkSettings.NetworkSettingsBase.Ports = ports
<add>
<ide> return &types.ContainerJSON{
<ide> ContainerJSONBase: base,
<ide> Mounts: mountPoints,
<ide><path>daemon/monitor.go
<ide> func (daemon *Daemon) StateChanged(id string, e libcontainerd.StateInfo) error {
<ide> case libcontainerd.StateExit:
<ide> // if container's AutoRemove flag is set, remove it after clean up
<ide> autoRemove := func() {
<del> if c.HostConfig.AutoRemove {
<add> c.Lock()
<add> ar := c.HostConfig.AutoRemove
<add> c.Unlock()
<add> if ar {
<ide> if err := daemon.ContainerRm(c.ID, &types.ContainerRmConfig{ForceRemove: true, RemoveVolume: true}); err != nil {
<ide> logrus.Errorf("can't remove container %s: %v", c.ID, err)
<ide> }
<ide><path>daemon/start.go
<ide> import (
<ide> "github.com/docker/docker/api/types"
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/container"
<del> "github.com/docker/docker/runconfig"
<ide> )
<ide>
<ide> // ContainerStart starts a container.
<ide> func (daemon *Daemon) containerStart(container *container.Container, checkpoint
<ide> return err
<ide> }
<ide>
<del> // Make sure NetworkMode has an acceptable value. We do this to ensure
<del> // backwards API compatibility.
<del> container.HostConfig = runconfig.SetDefaultNetModeIfBlank(container.HostConfig)
<del>
<ide> if err := daemon.initializeNetworking(container); err != nil {
<ide> return err
<ide> }
<ide><path>runconfig/config_unix.go
<ide> func (w *ContainerConfigWrapper) getHostConfig() *container.HostConfig {
<ide>
<ide> // Make sure NetworkMode has an acceptable value. We do this to ensure
<ide> // backwards compatible API behavior.
<del> hc = SetDefaultNetModeIfBlank(hc)
<add> SetDefaultNetModeIfBlank(hc)
<ide>
<ide> return hc
<ide> }
<ide><path>runconfig/hostconfig.go
<ide> func DecodeHostConfig(src io.Reader) (*container.HostConfig, error) {
<ide> // to default if it is not populated. This ensures backwards compatibility after
<ide> // the validation of the network mode was moved from the docker CLI to the
<ide> // docker daemon.
<del>func SetDefaultNetModeIfBlank(hc *container.HostConfig) *container.HostConfig {
<add>func SetDefaultNetModeIfBlank(hc *container.HostConfig) {
<ide> if hc != nil {
<ide> if hc.NetworkMode == container.NetworkMode("") {
<ide> hc.NetworkMode = container.NetworkMode("default")
<ide> }
<ide> }
<del> return hc
<ide> } | 8 |
Text | Text | update docs on static image imports | 2967fe1df39ec0946d171ac2a36c9805cfccff0d | <ide><path>docs/basic-features/image-optimization.md
<ide> To add an image to your application, import the [`next/image`](/docs/api-referen
<ide>
<ide> ```jsx
<ide> import Image from 'next/image'
<del>import profilePic from '../public/me.png'
<ide>
<ide> function Home() {
<ide> return (
<ide> <>
<ide> <h1>My Homepage</h1>
<ide> <Image
<del> src={profilePic}
<add> src="/me.png"
<ide> alt="Picture of the author"
<ide> width={500}
<ide> height={500}
<ide> function Home() {
<ide> export default Home
<ide> ```
<ide>
<add>## Image Imports
<add>
<add>You can `import` images that live in your project. (Note that `require` is not supported—only `import`.)
<add>
<add>With direct `import`s, `width`, `height`, and `blurDataURL` will be automatically provided to the image component. Alt text is still needed separately.
<add>
<add>```js
<add>import Image from 'next/image'
<add>import profilePic from '../public/me.png'
<add>
<add>function Home() {
<add> return (
<add> <>
<add> <h1>My Homepage</h1>
<add> <Image
<add> src={profilePic}
<add> alt="Picture of the author"
<add> // width={500} automatically provided
<add> // height={500} automatically provided
<add> // blurDataURL="data:..." automatically provided
<add> // Optionally allows to add a blurred version of the image while loading
<add> // placeholder="blur"
<add> />
<add> <p>Welcome to my homepage!</p>
<add> </>
<add> )
<add>}
<add>```
<add>
<add>For dynamic images you have to provide `width`, `height` and `blurDataURL` manually.
<add>
<add>## Properties
<add>
<ide> [View all properties](/docs/api-reference/next/image.md) available to the `next/image` component.
<ide>
<ide> ## Configuration | 1 |
Javascript | Javascript | fix compiler test | d544027af7891d5dac6a7a35129bc184fa7b0034 | <ide><path>test/Compiler.test.js
<ide> describe("Compiler", () => {
<ide> it("should compile a file with multiple chunks", done => {
<ide> compile("./chunks", {}, (stats, files) => {
<ide> expect(stats.chunks).toHaveLength(2);
<del> expect(Object.keys(files)).toEqual(["/main.js", "/0.js"]);
<add> expect(Object.keys(files)).toEqual(["/main.js", "/324.js"]);
<ide> const bundle = files["/main.js"];
<del> const chunk = files["/0.js"];
<add> const chunk = files["/324.js"];
<ide> expect(bundle).toMatch("function __webpack_require__(");
<ide> expect(bundle).toMatch("__webpack_require__(/*! ./b */");
<ide> expect(chunk).not.toMatch("__webpack_require__(/* ./b */"); | 1 |
Javascript | Javascript | use common.pipe in simple/test-cluster-eaccess | b9cecc305bf75a7246cba2768fabd3c72a7248dc | <ide><path>test/simple/test-cluster-eaccess.js
<ide> // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<ide> // USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide>
<del>
<ide> var common = require('../common');
<ide> var assert = require('assert');
<ide> var cluster = require('cluster');
<del>var path = require('path');
<ide> var fs = require('fs');
<ide> var net = require('net');
<ide>
<del>var socketPath = path.join(common.fixturesDir, 'socket-path');
<add>var socketPath = common.PIPE;
<ide>
<ide> if (cluster.isMaster) {
<ide> var worker = cluster.fork(); | 1 |
PHP | PHP | use tableschema constants in sqlite schema | 21b16a74824dd389f1a7b484789291473f2379b4 | <ide><path>src/Database/Schema/SqliteSchema.php
<ide> namespace Cake\Database\Schema;
<ide>
<ide> use Cake\Database\Exception;
<add>use Cake\Database\Schema\TableSchema;
<ide>
<ide> /**
<ide> * Schema management/reflection features for Sqlite
<ide> protected function _convertColumn($column)
<ide> }
<ide>
<ide> if ($col === 'bigint') {
<del> return ['type' => 'biginteger', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_BIGINTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if ($col == 'smallint') {
<del> return ['type' => 'smallinteger', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_SMALLINTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if ($col == 'tinyint') {
<del> return ['type' => 'tinyinteger', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_TINYINTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if (strpos($col, 'int') !== false) {
<del> return ['type' => 'integer', 'length' => $length, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_INTEGER, 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> if (strpos($col, 'decimal') !== false) {
<del> return ['type' => 'decimal', 'length' => null, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_DECIMAL, 'length' => null, 'unsigned' => $unsigned];
<ide> }
<ide> if (in_array($col, ['float', 'real', 'double'])) {
<del> return ['type' => 'float', 'length' => null, 'unsigned' => $unsigned];
<add> return ['type' => TableSchema::TYPE_FLOAT, 'length' => null, 'unsigned' => $unsigned];
<ide> }
<ide>
<ide> if (strpos($col, 'boolean') !== false) {
<del> return ['type' => 'boolean', 'length' => null];
<add> return ['type' => TableSchema::TYPE_BOOLEAN, 'length' => null];
<ide> }
<ide>
<ide> if ($col === 'char' && $length === 36) {
<del> return ['type' => 'uuid', 'length' => null];
<add> return ['type' => TableSchema::TYPE_UUID, 'length' => null];
<ide> }
<ide> if ($col === 'char') {
<del> return ['type' => 'string', 'fixed' => true, 'length' => $length];
<add> return ['type' => TableSchema::TYPE_STRING, 'fixed' => true, 'length' => $length];
<ide> }
<ide> if (strpos($col, 'char') !== false) {
<del> return ['type' => 'string', 'length' => $length];
<add> return ['type' => TableSchema::TYPE_STRING, 'length' => $length];
<ide> }
<ide>
<ide> if (in_array($col, ['blob', 'clob'])) {
<del> return ['type' => 'binary', 'length' => null];
<add> return ['type' => TableSchema::TYPE_BINARY, 'length' => null];
<ide> }
<ide> if (in_array($col, ['date', 'time', 'timestamp', 'datetime'])) {
<ide> return ['type' => $col, 'length' => null];
<ide> }
<ide>
<del> return ['type' => 'text', 'length' => null];
<add> return ['type' => TableSchema::TYPE_TEXT, 'length' => null];
<ide> }
<ide>
<ide> /**
<ide> public function columnSql(TableSchema $schema, $name)
<ide> {
<ide> $data = $schema->column($name);
<ide> $typeMap = [
<del> 'uuid' => ' CHAR(36)',
<del> 'smallinteger' => ' SMALLINT',
<del> 'tinyinteger' => ' TINYINT',
<del> 'integer' => ' INTEGER',
<del> 'biginteger' => ' BIGINT',
<del> 'boolean' => ' BOOLEAN',
<del> 'binary' => ' BLOB',
<del> 'float' => ' FLOAT',
<del> 'decimal' => ' DECIMAL',
<del> 'date' => ' DATE',
<del> 'time' => ' TIME',
<del> 'datetime' => ' DATETIME',
<del> 'timestamp' => ' TIMESTAMP',
<del> 'json' => ' TEXT'
<add> TableSchema::TYPE_UUID => ' CHAR(36)',
<add> TableSchema::TYPE_TINYINTEGER => ' TINYINT',
<add> TableSchema::TYPE_SMALLINTEGER => ' SMALLINT',
<add> TableSchema::TYPE_INTEGER => ' INTEGER',
<add> TableSchema::TYPE_BIGINTEGER => ' BIGINT',
<add> TableSchema::TYPE_BOOLEAN => ' BOOLEAN',
<add> TableSchema::TYPE_BINARY => ' BLOB',
<add> TableSchema::TYPE_FLOAT => ' FLOAT',
<add> TableSchema::TYPE_DECIMAL => ' DECIMAL',
<add> TableSchema::TYPE_DATE => ' DATE',
<add> TableSchema::TYPE_TIME => ' TIME',
<add> TableSchema::TYPE_DATETIME => ' DATETIME',
<add> TableSchema::TYPE_TIMESTAMP => ' TIMESTAMP',
<add> TableSchema::TYPE_JSON => ' TEXT'
<ide> ];
<ide>
<ide> $out = $this->_driver->quoteIdentifier($name);
<del> $hasUnsigned = ['smallinteger', 'tinyinteger', 'biginteger', 'integer', 'float', 'decimal'];
<add> $hasUnsigned = [
<add> TableSchema::TYPE_TINYINTEGER,
<add> TableSchema::TYPE_SMALLINTEGER,
<add> TableSchema::TYPE_INTEGER,
<add> TableSchema::TYPE_BIGINTEGER,
<add> TableSchema::TYPE_FLOAT,
<add> TableSchema::TYPE_DECIMAL
<add> ];
<ide>
<ide> if (in_array($data['type'], $hasUnsigned, true) &&
<ide> isset($data['unsigned']) && $data['unsigned'] === true
<ide> ) {
<del> if ($data['type'] !== 'integer' || [$name] !== (array)$schema->primaryKey()) {
<add> if ($data['type'] !== TableSchema::TYPE_INTEGER || [$name] !== (array)$schema->primaryKey()) {
<ide> $out .= ' UNSIGNED';
<ide> }
<ide> }
<ide> public function columnSql(TableSchema $schema, $name)
<ide> $out .= $typeMap[$data['type']];
<ide> }
<ide>
<del> if ($data['type'] === 'text' && $data['length'] !== TableSchema::LENGTH_TINY) {
<add> if ($data['type'] === TableSchema::TYPE_TEXT && $data['length'] !== TableSchema::LENGTH_TINY) {
<ide> $out .= ' TEXT';
<ide> }
<ide>
<del> if ($data['type'] === 'string' || ($data['type'] === 'text' && $data['length'] === TableSchema::LENGTH_TINY)) {
<add> if ($data['type'] === TableSchema::TYPE_STRING ||
<add> ($data['type'] === TableSchema::TYPE_TEXT && $data['length'] === TableSchema::LENGTH_TINY)
<add> ) {
<ide> $out .= ' VARCHAR';
<ide>
<ide> if (isset($data['length'])) {
<ide> $out .= '(' . (int)$data['length'] . ')';
<ide> }
<ide> }
<ide>
<del> $integerTypes = ['integer', 'smallinteger', 'tinyinteger'];
<add> $integerTypes = [
<add> TableSchema::TYPE_TINYINTEGER,
<add> TableSchema::TYPE_SMALLINTEGER,
<add> TableSchema::TYPE_INTEGER,
<add> ];
<ide> if (in_array($data['type'], $integerTypes, true) &&
<ide> isset($data['length']) && [$name] !== (array)$schema->primaryKey()
<ide> ) {
<ide> $out .= '(' . (int)$data['length'] . ')';
<ide> }
<ide>
<del> $hasPrecision = ['float', 'decimal'];
<add> $hasPrecision = [TableSchema::TYPE_FLOAT, TableSchema::TYPE_DECIMAL];
<ide> if (in_array($data['type'], $hasPrecision, true) &&
<ide> (isset($data['length']) || isset($data['precision']))
<ide> ) {
<ide> public function columnSql(TableSchema $schema, $name)
<ide> $out .= ' NOT NULL';
<ide> }
<ide>
<del> if ($data['type'] === 'integer' && [$name] === (array)$schema->primaryKey()) {
<add> if ($data['type'] === TableSchema::TYPE_INTEGER && [$name] === (array)$schema->primaryKey()) {
<ide> $out .= ' PRIMARY KEY AUTOINCREMENT';
<ide> }
<ide>
<del> if (isset($data['null']) && $data['null'] === true && $data['type'] === 'timestamp') {
<add> if (isset($data['null']) && $data['null'] === true && $data['type'] === TableSchema::TYPE_TIMESTAMP) {
<ide> $out .= ' DEFAULT NULL';
<ide> }
<ide> if (isset($data['default'])) {
<ide> public function constraintSql(TableSchema $schema, $name)
<ide> $data = $schema->constraint($name);
<ide> if ($data['type'] === TableSchema::CONSTRAINT_PRIMARY &&
<ide> count($data['columns']) === 1 &&
<del> $schema->column($data['columns'][0])['type'] === 'integer'
<add> $schema->column($data['columns'][0])['type'] === TableSchema::TYPE_INTEGER
<ide> ) {
<ide> return '';
<ide> } | 1 |
Ruby | Ruby | use the factory method to construct the mapping | 4097ff5c5faa67b4b9a00488c42c7b16b0fdd2fc | <ide><path>actionpack/test/dispatch/mapper_test.rb
<ide> def test_initialize
<ide>
<ide> def test_mapping_requirements
<ide> options = { :controller => 'foo', :action => 'bar', :via => :get }
<del> m = Mapper::Mapping.new({}, '/store/:name(*rest)', options)
<add> m = Mapper::Mapping.build({}, '/store/:name(*rest)', options)
<ide> _, _, requirements, _ = m.to_route
<ide> assert_equal(/.+?/, requirements[:rest])
<ide> end | 1 |
PHP | PHP | fix failing tests caused by directory changes | fa0b32323729158323e72b5e96aa0f9955966e86 | <ide><path>Cake/Test/TestCase/Utility/DebuggerTest.php
<ide> public function customFormat($error, $strings) {
<ide> */
<ide> public function testTrimPath() {
<ide> $this->assertEquals('APP/', Debugger::trimPath(APP));
<del> $this->assertEquals('CORE', Debugger::trimPath(CAKE_CORE_INCLUDE_PATH));
<del> $this->assertEquals('ROOT', Debugger::trimPath(ROOT));
<ide> $this->assertEquals('CORE' . DS . 'Cake' . DS, Debugger::trimPath(CAKE));
<ide> $this->assertEquals('Some/Other/Path', Debugger::trimPath('Some/Other/Path'));
<ide> }
<ide><path>Cake/Test/TestCase/Utility/FolderTest.php
<ide> public function testInCakePath() {
<ide> $result = $Folder->inCakePath($path);
<ide> $this->assertFalse($result);
<ide>
<del> $path = DS . 'lib' . DS . 'Cake' . DS . 'Config';
<del> $Folder->cd(ROOT . DS . 'lib' . DS . 'Cake' . DS . 'Config');
<add> $path = DS . 'Cake' . DS . 'Config';
<add> $Folder->cd(ROOT . DS . 'Cake' . DS . 'Config');
<ide> $result = $Folder->inCakePath($path);
<ide> $this->assertTrue($result);
<ide> }
<ide><path>Cake/Test/init.php
<ide> define('LOG_ERROR', LOG_ERR);
<ide>
<ide> // Point app constants to the test app.
<del>define('APP', ROOT . '/lib/Cake/Test/TestApp/');
<add>define('APP', ROOT . '/Cake/Test/TestApp/');
<ide> define('WWW_ROOT', APP . WEBROOT_DIR . DS);
<ide> define('TESTS', APP . 'Test' . DS);
<ide>
<del>define('TEST_APP', ROOT . '/lib/Cake/Test/TestApp/');
<add>define('TEST_APP', ROOT . '/Cake/Test/TestApp/');
<ide>
<ide> //@codingStandardsIgnoreStart
<ide> @mkdir(LOGS); | 3 |
Python | Python | remove has_key from config | 944bb9fb73ed888f9917e3059274af2f3fa652fb | <ide><path>numpy/distutils/command/config.py
<ide> def check_funcs_once(self, funcs,
<ide> body.append("int main (void) {")
<ide> if call:
<ide> for f in funcs:
<del> if call.has_key(f) and call[f]:
<del> if not (call_args and call_args.has_key(f) and call_args[f]):
<add> if f in call and call[f]:
<add> if not (call_args and f in call_args and call_args[f]):
<ide> args = ''
<ide> else:
<ide> args = call_args[f] | 1 |
PHP | PHP | change is_callable checks to instanceof closure | fb3a0df0ddaf7bf65a041c07dd33979196994d51 | <ide><path>laravel/arr.php
<ide> public static function get($array, $key, $default = null)
<ide> {
<ide> if ( ! is_array($array) or ! array_key_exists($segment, $array))
<ide> {
<del> return is_callable($default) ? call_user_func($default) : $default;
<add> return ($default instanceof \Closure) ? call_user_func($default) : $default;
<ide> }
<ide>
<ide> $array = $array[$segment];
<ide><path>laravel/cache/driver.php
<ide> public function get($key, $default = null)
<ide> {
<ide> if ( ! is_null($item = $this->retrieve($key))) return $item;
<ide>
<del> return (is_callable($default)) ? call_user_func($default) : $default;
<add> return ($default instanceof \Closure) ? call_user_func($default) : $default;
<ide> }
<ide>
<ide> /**
<ide> public function remember($key, $value, $minutes)
<ide> {
<ide> if ( ! is_null($item = $this->get($key, null))) return $item;
<ide>
<del> $default = is_callable($default) ? call_user_func($default) : $default;
<add> $default = ($default instanceof \Closure) ? call_user_func($default) : $default;
<ide>
<ide> $this->put($key, $default, $minutes);
<ide>
<ide><path>laravel/config.php
<ide> public static function get($key, $default = null)
<ide>
<ide> if ( ! static::load($file))
<ide> {
<del> return is_callable($default) ? call_user_func($default) : $default;
<add> return ($default instanceof \Closure) ? call_user_func($default) : $default;
<ide> }
<ide>
<ide> if (is_null($key)) return static::$items[$file];
<ide><path>laravel/lang.php
<ide> public function get($default = null)
<ide>
<ide> if ( ! $this->load($file))
<ide> {
<del> return is_callable($default) ? call_user_func($default) : $default;
<add> return ($default instanceof \Closure) ? call_user_func($default) : $default;
<ide> }
<ide>
<ide> $line = Arr::get(static::$lines[$this->language.$file], $line, $default);
<ide><path>laravel/routing/handler.php
<ide> protected function find_route_closure(Route $route)
<ide> {
<ide> if (isset($route->callback['do'])) return $route->callback['do'];
<ide>
<del> foreach ($route->callback as $value) { if (is_callable($value)) return $value; }
<add> foreach ($route->callback as $value) { if ($value instanceof Closure) return $value; }
<ide> }
<ide>
<ide> /**
<ide><path>laravel/session/driver.php
<ide> public function get($key, $default = null)
<ide> if (array_key_exists($possibility, $this->session['data'])) return $this->session['data'][$possibility];
<ide> }
<ide>
<del> return is_callable($default) ? call_user_func($default) : $default;
<add> return ($default instanceof \Closure) ? call_user_func($default) : $default;
<ide> }
<ide>
<ide> /**
<ide><path>laravel/view.php
<ide> protected function compose()
<ide> {
<ide> foreach ((array) $composers[$this->view] as $key => $value)
<ide> {
<del> if (is_callable($value)) return call_user_func($value, $this);
<add> if ($value instanceof \Closure) return call_user_func($value, $this);
<ide> }
<ide> }
<ide> } | 7 |
PHP | PHP | fix return of add method in cache repository | cf8238d45e6c037566619e9ca0c01a91e8816f69 | <ide><path>src/Illuminate/Cache/Repository.php
<ide> public function add($key, $value, $minutes)
<ide> // so it exists for subsequent requests. Then, we will return true so it is
<ide> // easy to know if the value gets added. Otherwise, we will return false.
<ide> if (is_null($this->get($key))) {
<del> $this->put($key, $value, $minutes);
<del>
<del> return true;
<add> return $this->put($key, $value, $minutes);
<ide> }
<ide>
<ide> return false;
<ide><path>tests/Cache/CacheRepositoryTest.php
<ide> public function testAddWithDatetimeInPastOrZeroSecondsReturnsImmediately()
<ide> $this->assertFalse($result);
<ide> }
<ide>
<add> public function testAddWithStoreFailureReturnsFalse()
<add> {
<add> $repo = $this->getRepository();
<add> $repo->getStore()->shouldReceive('add')->never();
<add> $repo->getStore()->shouldReceive('get')->andReturn(null);
<add> $repo->getStore()->shouldReceive('put')->andReturn(false);
<add> $this->assertFalse($repo->add('foo', 'bar', 60));
<add> }
<add>
<ide> public function testCacheAddCallsRedisStoreAdd()
<ide> {
<ide> $store = m::mock(RedisStore::class); | 2 |
Javascript | Javascript | fix webcrypto import of cfrg raw public keys | 5fad0b93667ffc6e4def52996b9529ac99b26319 | <ide><path>lib/internal/crypto/cfrg.js
<ide> function verifyAcceptableCfrgKeyUse(name, type, usages) {
<ide> }
<ide> }
<ide>
<del>function createECPublicKeyRaw(name, keyData) {
<del> const handle = new KeyObjectHandle();
<del> keyData = getArrayBufferOrView(keyData, 'keyData');
<del> if (handle.initECRaw(name.toLowerCase(), keyData))
<del> return new PublicKeyObject(handle);
<del>}
<del>
<ide> function createCFRGRawKey(name, keyData, isPublic) {
<ide> const handle = new KeyObjectHandle();
<ide> keyData = getArrayBufferOrView(keyData, 'keyData');
<ide> async function cfrgImportKey(
<ide> }
<ide> case 'raw': {
<ide> verifyAcceptableCfrgKeyUse(name, 'public', usagesSet);
<del> keyObject = createECPublicKeyRaw(name, keyData);
<add> keyObject = createCFRGRawKey(name, keyData, true);
<ide> if (keyObject === undefined)
<ide> throw lazyDOMException('Unable to import CFRG key', 'OperationError');
<ide> break;
<ide><path>test/parallel/test-webcrypto-export-import-cfrg.js
<ide> async function testImportJwk({ name, publicUsages, privateUsages }, extractable)
<ide> }
<ide> }
<ide>
<add>async function testImportRaw({ name, publicUsages }) {
<add> const jwk = keyData[name].jwk;
<add>
<add> const publicKey = await subtle.importKey(
<add> 'raw',
<add> Buffer.from(jwk.x, 'base64url'),
<add> { name },
<add> true, publicUsages);
<add>
<add> assert.strictEqual(publicKey.type, 'public');
<add> assert.deepStrictEqual(publicKey.usages, publicUsages);
<add> assert.strictEqual(publicKey.algorithm.name, name);
<add>}
<add>
<ide> (async function() {
<ide> const tests = [];
<ide> testVectors.forEach((vector) => {
<ide> async function testImportJwk({ name, publicUsages, privateUsages }, extractable)
<ide> tests.push(testImportPkcs8(vector, extractable));
<ide> tests.push(testImportJwk(vector, extractable));
<ide> });
<add> tests.push(testImportRaw(vector));
<ide> });
<ide>
<ide> await Promise.all(tests); | 2 |
Python | Python | convert int to str before adding to a str | f382a8decda82062bb6911f05b646f404eacfdd4 | <ide><path>examples/run_lm_finetuning.py
<ide> class TextDataset(Dataset):
<ide> def __init__(self, tokenizer, file_path='train', block_size=512):
<ide> assert os.path.isfile(file_path)
<ide> directory, filename = os.path.split(file_path)
<del> cached_features_file = os.path.join(directory, 'cached_lm_' + block_size + '_' + filename)
<add> cached_features_file = os.path.join(directory, 'cached_lm_' + str(block_size) + '_' + filename)
<ide>
<ide> if os.path.exists(cached_features_file):
<ide> logger.info("Loading features from cached file %s", cached_features_file) | 1 |
Python | Python | fix results for cassandra backend in detailed mode | 7a14d6f1a1158839e0beae75a4e634b2e84e654c | <ide><path>celery/backends/cassandra.py
<ide> def _store_result(self, task_id, result, status,
<ide> """Store return value and status of an executed task."""
<ide>
<ide> def _do_store():
<del> detailed = self.detailed_mode
<ide> cf = self._get_column_family()
<ide> date_done = self.app.now()
<ide> meta = {'status': status,
<ide> 'date_done': date_done.strftime('%Y-%m-%dT%H:%M:%SZ'),
<ide> 'traceback': self.encode(traceback),
<del> 'result': result if detailed else self.encode(result),
<add> 'result': self.encode(result),
<ide> 'children': self.encode(
<ide> self.current_task_children(request),
<ide> )}
<del> if detailed:
<add> if self.detailed_mode:
<ide> cf.insert(
<ide> task_id, {date_done: self.encode(meta)}, ttl=self.expires,
<ide> )
<ide> def _do_get():
<ide> try:
<ide> if self.detailed_mode:
<ide> row = cf.get(task_id, column_reversed=True, column_count=1)
<del> meta = self.decode(list(row.values())[0])
<del> meta['task_id'] = task_id
<add> return self.decode(list(row.values())[0])
<ide> else:
<ide> obj = cf.get(task_id)
<del> meta = self.meta_from_decoded({
<add> return self.meta_from_decoded({
<ide> 'task_id': task_id,
<ide> 'status': obj['status'],
<ide> 'result': self.decode(obj['result']),
<ide> def _do_get():
<ide> 'children': self.decode(obj['children']),
<ide> })
<ide> except (KeyError, pycassa.NotFoundException):
<del> meta = {'status': states.PENDING, 'result': None}
<del> return meta
<add> return {'status': states.PENDING, 'result': None}
<ide>
<ide> return self._retry_on_error(_do_get)
<ide> | 1 |
Python | Python | fix a typo for an error message in the gce driver | 9d253dba668316954e96a986cff01bf915831ab6 | <ide><path>libcloud/compute/drivers/gce.py
<ide> def ex_set_node_scheduling(self, node, on_host_maintenance=None,
<ide> on_host_maintenance = on_host_maintenance.upper()
<ide> ohm_values = ['MIGRATE', 'TERMINATE']
<ide> if on_host_maintenance not in ohm_values:
<del> raise ValueError('on_host_maintenence must be one of %s' %
<add> raise ValueError('on_host_maintenance must be one of %s' %
<ide> ','.join(ohm_values))
<ide>
<ide> request = '/zones/%s/instances/%s/setScheduling' % ( | 1 |
Javascript | Javascript | remove lanepriority from getbumpedlaneforhydration | 3221e8fba4cc96cf6c7723bab9485223a266d796 | <ide><path>packages/react-reconciler/src/ReactFiberLane.new.js
<ide> export function getBumpedLaneForHydration(
<ide> root: FiberRoot,
<ide> renderLanes: Lanes,
<ide> ): Lane {
<del> getHighestPriorityLanes(renderLanes);
<del> const highestLanePriority = return_highestLanePriority;
<add> const renderLane = getHighestPriorityLane(renderLanes);
<ide>
<ide> let lane;
<del> switch (highestLanePriority) {
<del> case SyncLanePriority:
<del> lane = NoLane;
<del> break;
<del> case InputContinuousLanePriority:
<add> switch (renderLane) {
<add> case InputContinuousLane:
<ide> lane = InputContinuousHydrationLane;
<ide> break;
<del> case DefaultHydrationLanePriority:
<del> case DefaultLanePriority:
<add> case DefaultLane:
<ide> lane = DefaultHydrationLane;
<ide> break;
<del> case TransitionHydrationPriority:
<del> case TransitionPriority:
<del> lane = TransitionHydrationLane;
<del> break;
<del> case RetryLanePriority:
<del> // Shouldn't be reachable under normal circumstances, so there's no
<del> // dedicated lane for retry priority. Use the one for long transitions.
<add> case TransitionLane1:
<add> case TransitionLane2:
<add> case TransitionLane3:
<add> case TransitionLane4:
<add> case TransitionLane5:
<add> case TransitionLane6:
<add> case TransitionLane7:
<add> case TransitionLane8:
<add> case TransitionLane9:
<add> case TransitionLane10:
<add> case TransitionLane11:
<add> case TransitionLane12:
<add> case TransitionLane13:
<add> case TransitionLane14:
<add> case TransitionLane15:
<add> case TransitionLane16:
<add> case RetryLane1:
<add> case RetryLane2:
<add> case RetryLane3:
<add> case RetryLane4:
<add> case RetryLane5:
<ide> lane = TransitionHydrationLane;
<ide> break;
<del> case SelectiveHydrationLanePriority:
<del> lane = SelectiveHydrationLane;
<del> break;
<del> case IdleHydrationLanePriority:
<del> case IdleLanePriority:
<add> case IdleLane:
<ide> lane = IdleHydrationLane;
<ide> break;
<del> case OffscreenLanePriority:
<del> case NoLanePriority:
<add> default:
<add> // Everything else is already either a hydration lane, or shouldn't
<add> // be retried at a hydration lane.
<ide> lane = NoLane;
<ide> break;
<del> default:
<del> invariant(false, 'Invalid lane: %s. This is a bug in React.', lane);
<ide> }
<ide>
<ide> // Check if the lane we chose is suspended. If so, that indicates that we
<ide><path>packages/react-reconciler/src/ReactFiberLane.old.js
<ide> export function getBumpedLaneForHydration(
<ide> root: FiberRoot,
<ide> renderLanes: Lanes,
<ide> ): Lane {
<del> getHighestPriorityLanes(renderLanes);
<del> const highestLanePriority = return_highestLanePriority;
<add> const renderLane = getHighestPriorityLane(renderLanes);
<ide>
<ide> let lane;
<del> switch (highestLanePriority) {
<del> case SyncLanePriority:
<del> lane = NoLane;
<del> break;
<del> case InputContinuousLanePriority:
<add> switch (renderLane) {
<add> case InputContinuousLane:
<ide> lane = InputContinuousHydrationLane;
<ide> break;
<del> case DefaultHydrationLanePriority:
<del> case DefaultLanePriority:
<add> case DefaultLane:
<ide> lane = DefaultHydrationLane;
<ide> break;
<del> case TransitionHydrationPriority:
<del> case TransitionPriority:
<del> lane = TransitionHydrationLane;
<del> break;
<del> case RetryLanePriority:
<del> // Shouldn't be reachable under normal circumstances, so there's no
<del> // dedicated lane for retry priority. Use the one for long transitions.
<add> case TransitionLane1:
<add> case TransitionLane2:
<add> case TransitionLane3:
<add> case TransitionLane4:
<add> case TransitionLane5:
<add> case TransitionLane6:
<add> case TransitionLane7:
<add> case TransitionLane8:
<add> case TransitionLane9:
<add> case TransitionLane10:
<add> case TransitionLane11:
<add> case TransitionLane12:
<add> case TransitionLane13:
<add> case TransitionLane14:
<add> case TransitionLane15:
<add> case TransitionLane16:
<add> case RetryLane1:
<add> case RetryLane2:
<add> case RetryLane3:
<add> case RetryLane4:
<add> case RetryLane5:
<ide> lane = TransitionHydrationLane;
<ide> break;
<del> case SelectiveHydrationLanePriority:
<del> lane = SelectiveHydrationLane;
<del> break;
<del> case IdleHydrationLanePriority:
<del> case IdleLanePriority:
<add> case IdleLane:
<ide> lane = IdleHydrationLane;
<ide> break;
<del> case OffscreenLanePriority:
<del> case NoLanePriority:
<add> default:
<add> // Everything else is already either a hydration lane, or shouldn't
<add> // be retried at a hydration lane.
<ide> lane = NoLane;
<ide> break;
<del> default:
<del> invariant(false, 'Invalid lane: %s. This is a bug in React.', lane);
<ide> }
<ide>
<ide> // Check if the lane we chose is suspended. If so, that indicates that we | 2 |
Javascript | Javascript | fix the normals for morphs | d1261c9293d6b743d417c4e2da307f2c8685caee | <ide><path>src/renderers/WebGLRenderer.js
<ide> THREE.WebGLRenderer = function ( parameters ) {
<ide> object.__webglMorphTargetInfluences[ m ] = influences[ gonnaUse[m]];
<ide> } else {
<ide> _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
<add> if ( material.morphNormals ) {
<add> _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
<add> }
<ide> object.__webglMorphTargetInfluences[ m ] = 0;
<ide> }
<ide> //used[ candidate ] = 1; | 1 |
PHP | PHP | extract common code into a helper method | 95d9b0673d7a95806cccb0cb393a568ad556b596 | <ide><path>src/Network/Request.php
<ide> public function here($base = true)
<ide> return $url;
<ide> }
<ide>
<add> /**
<add> * Normalize a header name into the SERVER version.
<add> *
<add> * @param string $name The header name.
<add> * @return string The normalized header name.
<add> */
<add> protected function normalizeHeaderName($name)
<add> {
<add> $name = str_replace('-', '_', strtoupper($name));
<add> if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<add> $name = 'HTTP_' . $name;
<add> }
<add> return $name;
<add> }
<add>
<ide> /**
<ide> * Read an HTTP header from the Request information.
<ide> *
<ide> public function here($base = true)
<ide> */
<ide> public function header($name)
<ide> {
<del> $name = str_replace('-', '_', $name);
<del> if (!in_array(strtoupper($name), ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<del> $name = 'HTTP_' . $name;
<del> }
<del>
<add> $name = $this->normalizeHeaderName($name);
<ide> return $this->env($name);
<ide> }
<ide>
<ide> public function getHeaders()
<ide> */
<ide> public function getHeader($name)
<ide> {
<del> $name = str_replace('-', '_', strtoupper($name));
<del> if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<del> $name = 'HTTP_' . $name;
<del> }
<add> $name = $this->normalizeHeaderName($name);
<ide> if (isset($this->_environment[$name])) {
<ide> return (array)$this->_environment[$name];
<ide> }
<ide> public function getHeaderLine($name)
<ide> public function withHeader($name, $value)
<ide> {
<ide> $new = clone $this;
<del> $name = strtoupper(str_replace('-', '_', $name));
<del> if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'])) {
<del> $name = 'HTTP_' . $name;
<del> }
<add> $name = $this->normalizeHeaderName($name);
<ide> $new->_environment[$name] = $value;
<ide>
<ide> return $new;
<ide> public function withAddedHeader($name, $value)
<ide> */
<ide> public function withoutHeader($name)
<ide> {
<add> $new = clone $this;
<add> $name = $this->normalizeHeaderName($name);
<add> $new->_environment[$name] = $value;
<add>
<add> return $new;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Network/RequestTest.php
<ide> public function testWithHeader()
<ide>
<ide> $this->assertEquals(1337, $request->getHeaderLine('Content-length'), 'old request is unchanged');
<ide> $this->assertEquals(999, $new->getHeaderLine('Content-length'), 'new request is correct');
<add> $this->assertEquals(999, $new->header('Content-Length'));
<ide>
<ide> $new = $request->withHeader('Double', ['a']);
<ide> $this->assertEquals(['a'], $new->getHeader('Double'), 'List values are overwritten');
<add> $this->assertEquals(['a'], $new->header('Double'), 'headers written in bc way.');
<ide> }
<ide>
<ide> /** | 2 |
Python | Python | set version to v3.5.0 | 32396e0bda3aceda74f2d7d050180032cd381d32 | <ide><path>spacy/about.py
<ide> # fmt: off
<ide> __title__ = "spacy"
<del>__version__ = "3.4.2"
<add>__version__ = "3.5.0"
<ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download"
<ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json"
<ide> __projects__ = "https://github.com/explosion/projects" | 1 |
Ruby | Ruby | clarify path requirements | 78f9b23218a45fd5d5b2237741b0b2bb89dca66b | <ide><path>Library/Contributions/cmd/brew-bundle.rb
<ide> # Looks for a Brewfile and runs each line as a brew command.
<ide> #
<ide> # brew bundle # Looks for "./Brewfile"
<del># brew bundle path/to/dir # Looks for "./path/to/dir/Brewfile"
<del># brew bundle path/to/file # Looks for "./path/to/file"
<add># brew bundle path/to/dir # Looks for "path/to/dir/Brewfile"
<add># brew bundle path/to/file # Looks for "path/to/file"
<ide> #
<ide> # For example, given a Brewfile with the following contents:
<ide> # tap foo/bar | 1 |
Javascript | Javascript | add infra for prepack build option | 43f18ffd087280e6df1e4900deb6fe201b87741a | <ide><path>local-cli/bundle/__tests__/saveBundleAndMap-test.js
<del>/**
<del> * Copyright (c) 2015-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> */
<del>'use strict';
<del>
<del>jest.autoMockOff();
<del>
<del>jest.mock('fs');
<del>jest.mock('../sign');
<del>
<del>const saveBundleAndMap = require('../saveBundleAndMap');
<del>const fs = require('fs');
<del>const temp = require('temp');
<del>
<del>const code = 'const foo = "bar";';
<del>const map = JSON.stringify({
<del> version: 3,
<del> file: 'foo.js.map',
<del> sources: ['foo.js'],
<del> sourceRoot: '/',
<del> names: ['bar'],
<del> mappings: 'AAA0B,kBAAhBA,QAAOC,SACjBD,OAAOC,OAAO'
<del>});
<del>
<del>describe('saveBundleAndMap', () => {
<del> beforeEach(() => {
<del> fs.writeFileSync = jest.genMockFn();
<del> });
<del>
<del> it('should save bundle', () => {
<del> const codeWithMap = {code: code};
<del> const bundleOutput = temp.path({suffix: '.bundle'});
<del>
<del> saveBundleAndMap(
<del> codeWithMap,
<del> 'ios',
<del> bundleOutput,
<del> 'utf8',
<del> );
<del>
<del> expect(fs.writeFileSync.mock.calls[0]).toEqual([bundleOutput, code, 'utf8']);
<del> });
<del>
<del> it('should save sourcemaps if required so', () => {
<del> const codeWithMap = {code: code, map: map};
<del> const bundleOutput = temp.path({suffix: '.bundle'});
<del> const sourceMapOutput = temp.path({suffix: '.map'});
<del> saveBundleAndMap(
<del> codeWithMap,
<del> 'ios',
<del> bundleOutput,
<del> 'utf8',
<del> sourceMapOutput
<del> );
<del>
<del> expect(fs.writeFileSync.mock.calls[1]).toEqual([sourceMapOutput, map]);
<del> });
<del>});
<ide><path>local-cli/bundle/buildBundle.js
<ide> */
<ide> 'use strict';
<ide>
<add>const fs = require('fs');
<ide> const log = require('../util/log').out('bundle');
<del>const processBundle = require('./processBundle');
<ide> const Promise = require('promise');
<ide> const ReactPackager = require('../../packager/react-packager');
<del>const saveBundleAndMap = require('./saveBundleAndMap');
<add>const saveAssets = require('./saveAssets');
<add>
<add>const sign = require('./sign');
<add>
<add>function saveBundleAndMap(
<add> bundle,
<add> bundleOutput,
<add> encoding,
<add> sourcemapOutput,
<add> dev
<add>) {
<add> log('start');
<add> let codeWithMap;
<add> if (!dev) {
<add> codeWithMap = bundle.getMinifiedSourceAndMap(dev);
<add> } else {
<add> codeWithMap = {
<add> code: bundle.getSource({ dev }),
<add> map: JSON.stringify(bundle.getSourceMap({ dev })),
<add> };
<add> }
<add> log('finish');
<add>
<add> log('Writing bundle output to:', bundleOutput);
<add> fs.writeFileSync(bundleOutput, sign(codeWithMap.code), encoding);
<add> log('Done writing bundle output');
<add>
<add> if (sourcemapOutput) {
<add> log('Writing sourcemap output to:', sourcemapOutput);
<add> fs.writeFileSync(sourcemapOutput, codeWithMap.map);
<add> log('Done writing sourcemap output');
<add> }
<add>}
<add>
<add>function savePrepackBundleAndMap(
<add> bundle,
<add> bundleOutput,
<add> sourcemapOutput,
<add> bridgeConfig
<add>) {
<add> log('Writing prepack bundle output to:', bundleOutput);
<add> const result = bundle.build({
<add> batchedBridgeConfig: bridgeConfig
<add> });
<add> fs.writeFileSync(bundleOutput, result, 'ucs-2');
<add> log('Done writing prepack bundle output');
<add>}
<ide>
<ide> function buildBundle(args, config) {
<ide> return new Promise((resolve, reject) => {
<ide> function buildBundle(args, config) {
<ide> platform: args.platform,
<ide> };
<ide>
<del> resolve(ReactPackager.createClientFor(options).then(client => {
<del> log('Created ReactPackager');
<del> return client.buildBundle(requestOpts)
<add> const prepack = args.prepack;
<add>
<add> const client = ReactPackager.createClientFor(options);
<add>
<add> client.then(() => log('Created ReactPackager'));
<add>
<add> // Build and save the bundle
<add> let bundle;
<add> if (prepack) {
<add> bundle = client.then(c => c.buildPrepackBundle(requestOpts))
<ide> .then(outputBundle => {
<del> log('Closing client');
<del> client.close();
<add> savePrepackBundleAndMap(
<add> outputBundle,
<add> args['bundle-output'],
<add> args['sourcemap-output'],
<add> args['bridge-config']
<add> );
<ide> return outputBundle;
<del> })
<del> .then(outputBundle => processBundle(outputBundle, args.dev))
<del> .then(outputBundle => saveBundleAndMap(
<del> outputBundle,
<add> });
<add> } else {
<add> bundle = client.then(c => c.buildBundle(requestOpts))
<add> .then(outputBundle => {
<add> saveBundleAndMap(
<add> outputBundle,
<add> args['bundle-output'],
<add> args['bundle-encoding'],
<add> args['sourcemap-output'],
<add> args.dev
<add> );
<add> return outputBundle;
<add> });
<add> }
<add>
<add> // When we're done bundling, close the client
<add> bundle.then(() => client.then(c => {
<add> log('Closing client');
<add> c.close();
<add> }));
<add>
<add> // Save the assets of the bundle
<add> const assets = bundle
<add> .then(outputBundle => outputBundle.getAssets())
<add> .then(outputAssets => saveAssets(
<add> outputAssets,
<ide> args.platform,
<del> args['bundle-output'],
<del> args['bundle-encoding'],
<del> args['sourcemap-output'],
<ide> args['assets-dest']
<ide> ));
<del> }));
<add>
<add> // When we're done saving the assets, we're done.
<add> resolve(assets);
<ide> });
<ide> }
<ide>
<ide><path>local-cli/bundle/bundleCommandLineArgs.js
<ide> module.exports = [
<ide> command: 'dev',
<ide> description: 'If false, warnings are disabled and the bundle is minified',
<ide> default: true,
<add> }, {
<add> command: 'prepack',
<add> description: 'If true, the output bundle will use the Prepack format.',
<add> default: false
<add> }, {
<add> command: 'bridge-config',
<add> description: 'File name of a a JSON export of __fbBatchedBridgeConfig. Used by Prepack. Ex. ./bridgeconfig.json',
<add> type: 'string'
<ide> }, {
<ide> command: 'bundle-output',
<ide> description: 'File name where to store the resulting bundle, ex. /tmp/groups.bundle',
<ide><path>local-cli/bundle/processBundle.js
<del>/**
<del> * Copyright (c) 2015-present, Facebook, Inc.
<del> * All rights reserved.
<del> *
<del> * This source code is licensed under the BSD-style license found in the
<del> * LICENSE file in the root directory of this source tree. An additional grant
<del> * of patent rights can be found in the PATENTS file in the same directory.
<del> */
<del>'use strict';
<del>
<del>const log = require('../util/log').out('bundle');
<del>
<del>function processBundle(input, dev) {
<del> log('start');
<del> let bundle;
<del> if (!dev) {
<del> bundle = input.getMinifiedSourceAndMap(dev);
<del> } else {
<del> bundle = {
<del> code: input.getSource({ dev }),
<del> map: JSON.stringify(input.getSourceMap({ dev })),
<del> };
<del> }
<del> bundle.assets = input.getAssets();
<del> log('finish');
<del> return bundle;
<del>}
<del>
<del>module.exports = processBundle;
<add><path>local-cli/bundle/saveAssets.js
<del><path>local-cli/bundle/saveBundleAndMap.js
<ide> const getAssetDestPathAndroid = require('./getAssetDestPathAndroid');
<ide> const getAssetDestPathIOS = require('./getAssetDestPathIOS');
<ide> const log = require('../util/log').out('bundle');
<ide> const path = require('path');
<del>const sign = require('./sign');
<ide>
<del>function saveBundleAndMap(
<del> codeWithMap,
<add>function saveAssets(
<add> assets,
<ide> platform,
<del> bundleOutput,
<del> encoding,
<del> sourcemapOutput,
<ide> assetsDest
<ide> ) {
<del> log('Writing bundle output to:', bundleOutput);
<del> fs.writeFileSync(bundleOutput, sign(codeWithMap.code), encoding);
<del> log('Done writing bundle output');
<del>
<del> if (sourcemapOutput) {
<del> log('Writing sourcemap output to:', sourcemapOutput);
<del> fs.writeFileSync(sourcemapOutput, codeWithMap.map);
<del> log('Done writing sourcemap output');
<del> }
<del>
<ide> if (!assetsDest) {
<ide> console.warn('Assets destination folder is not set, skipping...');
<ide> return Promise.resolve();
<ide> function saveBundleAndMap(
<ide> : getAssetDestPathIOS;
<ide>
<ide> const filesToCopy = Object.create(null); // Map src -> dest
<del> codeWithMap.assets
<add> assets
<ide> .filter(asset => !asset.deprecated)
<ide> .forEach(asset =>
<ide> asset.scales.forEach((scale, idx) => {
<ide> function copy(src, dest, callback) {
<ide> });
<ide> }
<ide>
<del>module.exports = saveBundleAndMap;
<add>module.exports = saveAssets;
<ide><path>packager/react-packager/index.js
<ide> exports.buildBundle = function(options, bundleOptions) {
<ide> });
<ide> };
<ide>
<add>exports.buildPrepackBundle = function(options, bundleOptions) {
<add> var server = createNonPersistentServer(options);
<add> return server.buildPrepackBundle(bundleOptions)
<add> .then(function(p) {
<add> server.end();
<add> return p;
<add> });
<add>};
<add>
<ide> exports.buildPackageFromUrl =
<ide> exports.buildBundleFromUrl = function(options, reqUrl) {
<ide> var server = createNonPersistentServer(options);
<ide><path>packager/react-packager/src/Bundler/PrepackBundle.js
<add>/**
<add> * Copyright (c) 2015-present, Facebook, Inc.
<add> * All rights reserved.
<add> *
<add> * This source code is licensed under the BSD-style license found in the
<add> * LICENSE file in the root directory of this source tree. An additional grant
<add> * of patent rights can be found in the PATENTS file in the same directory.
<add> */
<add>'use strict';
<add>
<add>const fs = require('fs');
<add>
<add>class PrepackBundle {
<add> constructor(sourceMapUrl) {
<add> this._finalized = false;
<add> this._moduleIds = Object.create(null);
<add> this._modules = Object.create(null);
<add> this._eagerModules = [];
<add> this._mainModule = null;
<add> this._assets = [];
<add> this._sourceMapUrl = sourceMapUrl;
<add> }
<add>
<add> addModule(id, module, deps, isPolyfill) {
<add> this._modules[module.sourcePath] = { module, deps };
<add> this._moduleIds[id] = module.sourcePath;
<add> if (isPolyfill) {
<add> this._eagerModules.push(id);
<add> }
<add> }
<add>
<add> addAsset(asset) {
<add> this._assets.push(asset);
<add> }
<add>
<add> // Synchronously load a file path.
<add> _loadFilename(path) {
<add> const module = this._modules[path];
<add> if (!module) {
<add> throw new Error('Could not find file "' + path + '" in preloaded files.');
<add> }
<add> return module.module.code;
<add> }
<add>
<add> // Synchronously resolve a relative require from a parent module.
<add> _resolveFilename(parentPath, relativePath) {
<add> if (!parentPath) {
<add> const resolvedPath = this._moduleIds[relativePath];
<add> if (!resolvedPath) {
<add> throw new Error('Could not resolve "' + relativePath + '".');
<add> }
<add> return resolvedPath;
<add> }
<add> const deps = this._modules[parentPath].deps;
<add> const resolvedPath = deps[relativePath];
<add> if (!resolvedPath) {
<add> throw new Error(
<add> 'Could not resolve "' + relativePath + '" from "' + parentPath + '".'
<add> );
<add> }
<add> return resolvedPath;
<add> }
<add>
<add> build(options) {
<add> var prepack = require('prepack');
<add>
<add> var batchedBridgeConfig = (options && options.batchedBridgeConfig) || null;
<add> if (typeof batchedBridgeConfig === 'string') {
<add> batchedBridgeConfig = JSON.parse(
<add> fs.readFileSync(batchedBridgeConfig, 'utf-8')
<add> );
<add> }
<add>
<add> var options = {
<add> batchedBridgeConfig: batchedBridgeConfig,
<add> environment: 'react-native',
<add> resolveFilename: this._resolveFilename.bind(this),
<add> loadFilename: this._loadFilename.bind(this),
<add> eagerModules: this._eagerModules
<add> };
<add>
<add> return prepack.compileModule(this._mainModule, options);
<add> }
<add>
<add> finalize(options) {
<add> options = options || {};
<add> if (options.runMainModule) {
<add> options.runBeforeMainModule.forEach(this._addRequireCall, this);
<add> this._mainModule = options.mainModuleId;
<add> }
<add>
<add> Object.freeze(this._moduleIds);
<add> Object.freeze(this._modules);
<add> Object.freeze(this._assets);
<add> Object.freeze(this._eagerModules);
<add> this._finalized = true;
<add> }
<add>
<add> _addRequireCall(moduleId) {
<add> this._eagerModules.push(moduleId);
<add> }
<add>
<add> _assertFinalized() {
<add> if (!this._finalized) {
<add> throw new Error('Bundle needs to be finalized before getting any source');
<add> }
<add> }
<add>
<add> getAssets() {
<add> return this._assets;
<add> }
<add>
<add> toJSON() {
<add> if (!this._finalized) {
<add> throw new Error('Cannot serialize bundle unless finalized');
<add> }
<add>
<add> return {
<add> modules: this._modules,
<add> moduleIds: this._moduleIds,
<add> assets: this._assets,
<add> sourceMapUrl: this._sourceMapUrl,
<add> mainModule: this._mainModule,
<add> eagerModules: this._eagerModules,
<add> };
<add> }
<add>
<add> static fromJSON(json) {
<add> const bundle = new PrepackBundle(json.sourceMapUrl);
<add> bundle._assets = json.assets;
<add> bundle._moduleIds = json.moduleIds;
<add> bundle._modules = json.modules;
<add> bundle._sourceMapUrl = json.sourceMapUrl;
<add>
<add> bundle._eagerModules = json.eagerModules;
<add> bundle._mainModule = json.mainModule;
<add>
<add> Object.freeze(bundle._moduleIds);
<add> Object.freeze(bundle._modules);
<add> Object.freeze(bundle._assets);
<add> Object.freeze(bundle._eagerModules);
<add>
<add> bundle._finalized = true;
<add>
<add> return bundle;
<add> }
<add>}
<add>
<add>module.exports = PrepackBundle;
<ide><path>packager/react-packager/src/Bundler/index.js
<ide> const Cache = require('../Cache');
<ide> const Transformer = require('../JSTransformer');
<ide> const Resolver = require('../Resolver');
<ide> const Bundle = require('./Bundle');
<add>const PrepackBundle = require('./PrepackBundle');
<ide> const Activity = require('../Activity');
<ide> const ModuleTransport = require('../lib/ModuleTransport');
<ide> const declareOpts = require('../lib/declareOpts');
<ide> class Bundler {
<ide> if (bar) {
<ide> bar.tick();
<ide> }
<del> return transformed;
<add> return this._wrapTransformedModule(response, module, transformed);
<ide> })
<ide> )
<ide> );
<ide> class Bundler {
<ide> });
<ide> }
<ide>
<add> prepackBundle({
<add> entryFile,
<add> runModule: runMainModule,
<add> runBeforeMainModule,
<add> sourceMapUrl,
<add> dev: isDev,
<add> platform,
<add> }) {
<add> const bundle = new PrepackBundle(sourceMapUrl);
<add> const findEventId = Activity.startEvent('find dependencies');
<add> let transformEventId;
<add> let mainModuleId;
<add>
<add> return this.getDependencies(entryFile, isDev, platform).then((response) => {
<add> Activity.endEvent(findEventId);
<add> transformEventId = Activity.startEvent('transform');
<add>
<add> let bar;
<add> if (process.stdout.isTTY) {
<add> bar = new ProgressBar('transforming [:bar] :percent :current/:total', {
<add> complete: '=',
<add> incomplete: ' ',
<add> width: 40,
<add> total: response.dependencies.length,
<add> });
<add> }
<add>
<add> mainModuleId = response.mainModuleId;
<add>
<add> return Promise.all(
<add> response.dependencies.map(
<add> module => this._transformModule(
<add> bundle,
<add> response,
<add> module,
<add> platform
<add> ).then(transformed => {
<add> if (bar) {
<add> bar.tick();
<add> }
<add>
<add> var deps = Object.create(null);
<add> var pairs = response.getResolvedDependencyPairs(module);
<add> if (pairs) {
<add> pairs.forEach(pair => {
<add> deps[pair[0]] = pair[1].path;
<add> });
<add> }
<add>
<add> return module.getName().then(name => {
<add> bundle.addModule(name, transformed, deps, module.isPolyfill());
<add> });
<add> })
<add> )
<add> );
<add> }).then(() => {
<add> Activity.endEvent(transformEventId);
<add> bundle.finalize({runBeforeMainModule, runMainModule, mainModuleId });
<add> return bundle;
<add> });
<add> }
<add>
<ide> invalidateFile(filePath) {
<ide> this._transformer.invalidateFile(filePath);
<ide> }
<ide> class Bundler {
<ide> }
<ide>
<ide> _transformModule(bundle, response, module, platform = null) {
<del> let transform;
<del>
<ide> if (module.isAsset_DEPRECATED()) {
<del> transform = this.generateAssetModule_DEPRECATED(bundle, module);
<add> return this.generateAssetModule_DEPRECATED(bundle, module);
<ide> } else if (module.isAsset()) {
<del> transform = this.generateAssetModule(bundle, module, platform);
<add> return this.generateAssetModule(bundle, module, platform);
<ide> } else if (module.isJSON()) {
<del> transform = generateJSONModule(module);
<add> return generateJSONModule(module);
<ide> } else {
<del> transform = this._transformer.loadFileAndTransform(
<add> return this._transformer.loadFileAndTransform(
<ide> path.resolve(module.path)
<ide> );
<ide> }
<add> }
<ide>
<del> const resolver = this._resolver;
<del> return transform.then(
<del> transformed => resolver.wrapModule(
<del> response,
<del> module,
<del> transformed.code
<del> ).then(
<del> code => new ModuleTransport({
<del> code: code,
<del> map: transformed.map,
<del> sourceCode: transformed.sourceCode,
<del> sourcePath: transformed.sourcePath,
<del> virtual: transformed.virtual,
<del> })
<del> )
<add> _wrapTransformedModule(response, module, transformed) {
<add> return this._resolver.wrapModule(
<add> response,
<add> module,
<add> transformed.code
<add> ).then(
<add> code => new ModuleTransport({
<add> code: code,
<add> map: transformed.map,
<add> sourceCode: transformed.sourceCode,
<add> sourcePath: transformed.sourcePath,
<add> virtual: transformed.virtual,
<add> })
<ide> );
<ide> }
<ide>
<ide><path>packager/react-packager/src/Server/index.js
<ide> class Server {
<ide> });
<ide> }
<ide>
<add> buildPrepackBundle(options) {
<add> return Promise.resolve().then(() => {
<add> if (!options.platform) {
<add> options.platform = getPlatformExtension(options.entryFile);
<add> }
<add>
<add> const opts = bundleOpts(options);
<add> return this._bundler.prepackBundle(opts);
<add> });
<add> }
<add>
<ide> buildBundleFromUrl(reqUrl) {
<ide> const options = this._getOptionsFromUrl(reqUrl);
<ide> return this.buildBundle(options);
<ide><path>packager/react-packager/src/SocketInterface/SocketClient.js
<ide> 'use strict';
<ide>
<ide> const Bundle = require('../Bundler/Bundle');
<add>const PrepackBundle = require('../Bundler/PrepackBundle');
<ide> const Promise = require('promise');
<ide> const bser = require('bser');
<ide> const debug = require('debug')('ReactNativePackager:SocketClient');
<ide> class SocketClient {
<ide> }).then(json => Bundle.fromJSON(json));
<ide> }
<ide>
<add> buildPrepackBundle(options) {
<add> return this._send({
<add> type: 'buildPrepackBundle',
<add> data: options,
<add> }).then(json => PrepackBundle.fromJSON(json));
<add> }
<add>
<ide> _send(message) {
<ide> message.id = uid();
<ide> this._sock.write(bser.dumpToBuffer(message));
<ide><path>packager/react-packager/src/SocketInterface/SocketServer.js
<ide> class SocketServer {
<ide> );
<ide> break;
<ide>
<add> case 'buildPrepackBundle':
<add> this._jobs++;
<add> this._packagerServer.buildPrepackBundle(m.data).then(
<add> (result) => this._reply(sock, m.id, 'result', result),
<add> handleError,
<add> );
<add> break;
<add>
<ide> case 'getOrderedDependencyPaths':
<ide> this._jobs++;
<ide> this._packagerServer.getOrderedDependencyPaths(m.data).then( | 11 |
PHP | PHP | fix docs about ordering of callbacks | 75f1a8406908b62240dee0a4d805bedbf77b34b4 | <ide><path>lib/Cake/Controller/Component.php
<ide> public function startup(Controller $controller) {
<ide> }
<ide>
<ide> /**
<del> * Called after the Controller::beforeRender(), after the view class is loaded, and before the
<del> * Controller::render()
<add> * Called before the Controller::beforeRender(), and before
<add> * the view class is loaded, and before Controller::render()
<ide> *
<ide> * @param Controller $controller Controller with components to beforeRender
<ide> * @return void | 1 |
Text | Text | fix minor typo in "docker engine runs navitvely" | 435bc9d9898febc8b9c16a02e4114745a52374fc | <ide><path>docs/getstarted/step_one.md
<ide> If you have an earlier Windows system that doesn't meet the Docker for Windows p
<ide> See [Docker Toolbox Overview](/toolbox/overview.md) for help on installing Docker with Toolbox.
<ide>
<ide> ### Docker for Linux
<del>Docker Engine runs navitvely on Linux distributions.
<add>Docker Engine runs natively on Linux distributions.
<ide>
<ide> For full instructions on getting Docker for various Linux distributions, see [Install Docker Engine](/engine/installation/index.md).
<ide> | 1 |
Javascript | Javascript | remove most of attrsproxy | 87694af87d7decf2fcbc52d646138a2f7cfe4cdb | <ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> ComponentNodeManager.prototype.rerender = function(_env, attrs, visitor) {
<ide> var snapshot = takeSnapshot(attrs);
<ide>
<ide> if (component._renderNode.shouldReceiveAttrs) {
<add> if (component.propagateAttrsToThis) {
<add> component.propagateAttrsToThis(takeLegacySnapshot(attrs));
<add> }
<add>
<ide> env.renderer.componentUpdateAttrs(component, snapshot);
<ide> component._renderNode.shouldReceiveAttrs = false;
<ide> }
<ide> export function createComponent(_component, isAngleBracket, _props, renderNode,
<ide> props.attrs = snapshot;
<ide>
<ide> if (!isAngleBracket) {
<del> let proto = _component.proto();
<del>
<ide> assert('controller= is no longer supported', !('controller' in attrs));
<ide>
<del> mergeBindings(props, shadowedAttrs(proto, snapshot));
<add> mergeBindings(props, snapshot);
<ide> } else {
<ide> props._isAngleBracket = true;
<ide> }
<ide> export function createComponent(_component, isAngleBracket, _props, renderNode,
<ide> return component;
<ide> }
<ide>
<del>function shadowedAttrs(target, attrs) {
<del> let shadowed = {};
<del>
<del> // For backwards compatibility, set the component property
<del> // if it has an attr with that name. Undefined attributes
<del> // are handled on demand via the `unknownProperty` hook.
<del> for (var attr in attrs) {
<del> if (attr in target) {
<del> // TODO: Should we issue a deprecation here?
<del> // deprecate(deprecation(attr));
<del> shadowed[attr] = attrs[attr];
<del> }
<add>function takeSnapshot(attrs) {
<add> let hash = {};
<add>
<add> for (var prop in attrs) {
<add> hash[prop] = getCellOrValue(attrs[prop]);
<ide> }
<ide>
<del> return shadowed;
<add> return hash;
<ide> }
<ide>
<del>function takeSnapshot(attrs) {
<add>export function takeLegacySnapshot(attrs) {
<ide> let hash = {};
<ide>
<ide> for (var prop in attrs) {
<del> hash[prop] = getCellOrValue(attrs[prop]);
<add> hash[prop] = getValue(attrs[prop]);
<ide> }
<ide>
<ide> return hash;
<ide><path>packages/ember-htmlbars/lib/node-managers/view-node-manager.js
<ide> import View from 'ember-views/views/view';
<ide> import { MUTABLE_CELL } from 'ember-views/compat/attrs-proxy';
<ide> import getCellOrValue from 'ember-htmlbars/hooks/get-cell-or-value';
<ide> import { instrument } from 'ember-htmlbars/system/instrumentation-support';
<add>import { takeLegacySnapshot } from 'ember-htmlbars/node-managers/component-node-manager';
<ide>
<ide> // In theory this should come through the env, but it should
<ide> // be safe to import this until we make the hook system public
<ide> ViewNodeManager.prototype.rerender = function(env, attrs, visitor) {
<ide> env.renderer.willUpdate(component, snapshot);
<ide>
<ide> if (component._renderNode.shouldReceiveAttrs) {
<add> if (component.propagateAttrsToThis) {
<add> component.propagateAttrsToThis(takeLegacySnapshot(attrs));
<add> }
<add>
<ide> env.renderer.componentUpdateAttrs(component, snapshot);
<ide> component._renderNode.shouldReceiveAttrs = false;
<ide> }
<ide> export function createOrUpdateComponent(component, options, createOptions, rende
<ide> merge(props, createOptions);
<ide> }
<ide>
<del> mergeBindings(props, shadowedAttrs(proto, snapshot));
<add> mergeBindings(props, snapshot);
<ide> props.container = options.parentView ? options.parentView.container : env.container;
<ide> props.renderer = options.parentView ? options.parentView.renderer : props.container && props.container.lookup('renderer:-dom');
<ide> props._viewRegistry = options.parentView ? options.parentView._viewRegistry : props.container && props.container.lookup('-view-registry:main');
<ide> export function createOrUpdateComponent(component, options, createOptions, rende
<ide> } else {
<ide> env.renderer.componentUpdateAttrs(component, snapshot);
<ide> setProperties(component, props);
<add>
<add> if (component.propagateAttrsToThis) {
<add> component.propagateAttrsToThis(takeLegacySnapshot(attrs));
<add> }
<ide> }
<ide>
<ide> if (options.parentView) {
<ide> export function createOrUpdateComponent(component, options, createOptions, rende
<ide> return component;
<ide> }
<ide>
<del>function shadowedAttrs(target, attrs) {
<del> let shadowed = {};
<del>
<del> // For backwards compatibility, set the component property
<del> // if it has an attr with that name. Undefined attributes
<del> // are handled on demand via the `unknownProperty` hook.
<del> for (var attr in attrs) {
<del> if (attr in target) {
<del> // TODO: Should we issue a deprecation here?
<del> // deprecate(deprecation(attr));
<del> shadowed[attr] = attrs[attr];
<del> }
<del> }
<del>
<del> return shadowed;
<del>}
<del>
<ide> function takeSnapshot(attrs) {
<ide> let hash = {};
<ide>
<ide><path>packages/ember-metal-views/lib/renderer.js
<ide> Renderer.prototype.setAttrs = function (view, attrs) {
<ide> }; // set attrs the first time
<ide>
<ide> Renderer.prototype.componentInitAttrs = function (component, attrs) {
<del> // for attrs-proxy support
<del> component.trigger('_internalDidReceiveAttrs');
<ide> component.trigger('didInitAttrs', { attrs });
<ide> component.trigger('didReceiveAttrs', { newAttrs: attrs });
<ide> }; // set attrs the first time
<ide> Renderer.prototype.componentUpdateAttrs = function (component, newAttrs) {
<ide> set(component, 'attrs', newAttrs);
<ide> }
<ide>
<del> // for attrs-proxy support
<del> component.trigger('_internalDidReceiveAttrs');
<ide> component.trigger('didUpdateAttrs', { oldAttrs, newAttrs });
<ide> component.trigger('didReceiveAttrs', { oldAttrs, newAttrs });
<ide> };
<ide><path>packages/ember-views/lib/compat/attrs-proxy.js
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import { symbol } from 'ember-metal/utils';
<ide> import { PROPERTY_DID_CHANGE } from 'ember-metal/property_events';
<del>import { on } from 'ember-metal/events';
<del>import EmptyObject from 'ember-metal/empty_object';
<ide>
<ide> export function deprecation(key) {
<ide> return `You tried to look up an attribute directly on the component. This is deprecated. Use attrs.${key} instead.`;
<ide> function isCell(val) {
<ide> return val && val[MUTABLE_CELL];
<ide> }
<ide>
<del>function setupAvoidPropagating(instance) {
<del> // This caches the list of properties to avoid setting onto the component instance
<del> // inside `_propagateAttrsToThis`. We cache them so that every instantiated component
<del> // does not have to pay the calculation penalty.
<del> let constructor = instance.constructor;
<del> if (!constructor.__avoidPropagating) {
<del> constructor.__avoidPropagating = new EmptyObject();
<del> let i, l;
<del> for (i = 0, l = instance.concatenatedProperties.length; i < l; i++) {
<del> let prop = instance.concatenatedProperties[i];
<del>
<del> constructor.__avoidPropagating[prop] = true;
<del> }
<del>
<del> for (i = 0, l = instance.mergedProperties.length; i < l; i++) {
<del> let prop = instance.mergedProperties[i];
<del>
<del> constructor.__avoidPropagating[prop] = true;
<del> }
<del> }
<del>}
<del>
<ide> let AttrsProxyMixin = {
<ide> attrs: null,
<ide>
<del> init() {
<del> this._super(...arguments);
<del>
<del> setupAvoidPropagating(this);
<del> },
<del>
<ide> getAttr(key) {
<ide> let attrs = this.attrs;
<ide> if (!attrs) { return; }
<ide> let AttrsProxyMixin = {
<ide> val.update(value);
<ide> },
<ide>
<del> _propagateAttrsToThis() {
<del> let attrs = this.attrs;
<del>
<del> for (let prop in attrs) {
<del> if (prop !== 'attrs' && !this.constructor.__avoidPropagating[prop]) {
<del> this.set(prop, this.getAttr(prop));
<del> }
<del> }
<del> },
<del>
<del> initializeShape: on('init', function() {
<del> this._isDispatchingAttrs = false;
<del> }),
<del>
<del> _internalDidReceiveAttrs() {
<del> this._super();
<add> propagateAttrsToThis(attrs) {
<ide> this._isDispatchingAttrs = true;
<del> this._propagateAttrsToThis();
<add> this.setProperties(attrs);
<ide> this._isDispatchingAttrs = false;
<del> },
<del>
<del>
<del> unknownProperty(key) {
<del> if (this._isAngleBracket) { return; }
<del>
<del> var attrs = this.attrs;
<del>
<del> if (attrs && key in attrs) {
<del> // do not deprecate accessing `this[key]` at this time.
<del> // add this back when we have a proper migration path
<del> // deprecate(deprecation(key), { id: 'ember-views.', until: '3.0.0' });
<del> let possibleCell = attrs[key];
<del>
<del> if (possibleCell && possibleCell[MUTABLE_CELL]) {
<del> return possibleCell.value;
<del> }
<del>
<del> return possibleCell;
<del> }
<ide> }
<del>
<del> //setUnknownProperty(key) {
<del>
<del> //}
<ide> };
<ide>
<ide> AttrsProxyMixin[PROPERTY_DID_CHANGE] = function(key) { | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.