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
|
handle case without cache in beam search
|
eb5bdcdfa51f743887ee1d9c7f230444d7a8b23c
|
<ide><path>src/transformers/generation_tf_utils.py
<ide> def gather_fn(tensor):
<ide>
<ide> # 3. init tensors to use for "xla-compileable" generate function
<ide> batch_size, num_beams, cur_len = input_ids.shape
<add> input_ids_length = cur_len
<ide>
<ide> # per batch, beam-item holding current token in loop, pre-populated with `pad_token_id`
<ide> sequences = tf.TensorArray(
<ide> def gather_fn(tensor):
<ide> # 4. define "xla-compile-able" stop-condition and auto-regressive function
<ide> # define stop-condition and auto-regressive function
<ide> def beam_search_cond_fn(
<del> cur_len, running_sequences, running_scores, sequences, scores, is_sent_finished, model_kwargs
<add> cur_len,
<add> running_sequences,
<add> running_scores,
<add> sequences,
<add> scores,
<add> is_sent_finished,
<add> model_kwargs,
<add> input_ids_length,
<ide> ):
<ide> """
<ide> Beam Search termination condition function -- halts the generation loop if any of these conditions becomes
<ide> def beam_search_body_fn(
<ide> scores,
<ide> is_sent_finished,
<ide> model_kwargs,
<del> input_ids_length=1,
<add> input_ids_length,
<ide> intermediary_running_sequences=None,
<ide> ):
<ide> """
<ide> def beam_search_body_fn(
<ide>
<ide> # if we don't cache past key values we need the whole input
<ide> if model_kwargs.get("past", None) is None:
<del> input_ids_length = cur_len + 1
<add> next_input_ids_length = cur_len + 1
<ide> # let's throw out `past` since we don't want `None` tensors
<ide> model_kwargs.pop("past", None)
<add> else:
<add> next_input_ids_length = 1
<ide>
<ide> # 9. Prepare the `tf.TensorArray` for the next iteration
<ide> next_sequences = sequences.unstack(tf.transpose(next_sequences_seq_last, perm=[2, 0, 1]))
<ide> def beam_search_body_fn(
<ide> next_scores,
<ide> next_is_sent_finished,
<ide> next_model_kwargs,
<add> next_input_ids_length,
<ide> )
<ide>
<ide> # 5. run generation
<ide> def beam_search_body_fn(
<ide> beam_search_body_fn, intermediary_running_sequences=intermediary_running_sequences
<ide> )
<ide>
<del> # 1st generation step has to be run before to initialize `past`
<del> beam_search_body_fn_first_iter = partial(beam_search_body_fn, input_ids_length=cur_len)
<add> # 1st generation step has to be run before to initialize `past` (if active)
<ide> (
<ide> cur_len,
<ide> running_sequences,
<ide> def beam_search_body_fn(
<ide> scores,
<ide> is_sent_finished,
<ide> model_kwargs,
<del> ) = beam_search_body_fn_first_iter(
<del> cur_len, running_sequences, running_scores, sequences, scores, is_sent_finished, model_kwargs
<add> input_ids_length,
<add> ) = beam_search_body_fn(
<add> cur_len,
<add> running_sequences,
<add> running_scores,
<add> sequences,
<add> scores,
<add> is_sent_finished,
<add> model_kwargs,
<add> input_ids_length,
<ide> )
<ide>
<ide> # 2-to-n generation steps can then be run in autoregressive fashion (only in case 1st generation step does
<ide> # NOT yield EOS token though)
<ide> if beam_search_cond_fn(
<del> cur_len, running_sequences, running_scores, sequences, scores, is_sent_finished, model_kwargs
<add> cur_len,
<add> running_sequences,
<add> running_scores,
<add> sequences,
<add> scores,
<add> is_sent_finished,
<add> model_kwargs,
<add> input_ids_length,
<ide> ):
<ide> maximum_iterations = max_length - cur_len
<del> cur_len, running_sequences, running_scores, sequences, scores, is_sent_finished, _ = tf.while_loop(
<add> cur_len, running_sequences, running_scores, sequences, scores, is_sent_finished, _, _ = tf.while_loop(
<ide> beam_search_cond_fn,
<ide> beam_search_body_fn,
<del> (cur_len, running_sequences, running_scores, sequences, scores, is_sent_finished, model_kwargs),
<add> (
<add> cur_len,
<add> running_sequences,
<add> running_scores,
<add> sequences,
<add> scores,
<add> is_sent_finished,
<add> model_kwargs,
<add> input_ids_length,
<add> ),
<ide> maximum_iterations=maximum_iterations,
<ide> )
<ide>
| 1
|
Go
|
Go
|
use only unavailable image when load from tarball
|
a34dd216119bd343eb4a1f68ad209816d7a3f4c9
|
<ide><path>archive/archive.go
<ide> func TarWithOptions(srcPath string, options *TarOptions) (io.ReadCloser, error)
<ide> // identity (uncompressed), gzip, bzip2, xz.
<ide> // FIXME: specify behavior when target path exists vs. doesn't exist.
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<add> if options == nil {
<add> options = &TarOptions{}
<add> }
<add>
<ide> if archive == nil {
<ide> return fmt.Errorf("Empty archive")
<ide> }
<ide>
<add> if options.Excludes == nil {
<add> options.Excludes = []string{}
<add> }
<add>
<ide> decompressedArchive, err := DecompressStream(archive)
<ide> if err != nil {
<ide> return err
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<ide> var dirs []*tar.Header
<ide>
<ide> // Iterate through the files in the archive.
<add>loop:
<ide> for {
<ide> hdr, err := tr.Next()
<ide> if err == io.EOF {
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<ide> // Normalize name, for safety and for a simple is-root check
<ide> hdr.Name = filepath.Clean(hdr.Name)
<ide>
<add> for _, exclude := range options.Excludes {
<add> if strings.HasPrefix(hdr.Name, exclude) {
<add> continue loop
<add> }
<add> }
<add>
<ide> if !strings.HasSuffix(hdr.Name, "/") {
<ide> // Not the root directory, ensure that the parent directory exists
<ide> parent := filepath.Dir(hdr.Name)
<ide> func Untar(archive io.Reader, dest string, options *TarOptions) error {
<ide> }
<ide> }
<ide> trBuf.Reset(tr)
<del> if err := createTarFile(path, dest, hdr, trBuf, options == nil || !options.NoLchown); err != nil {
<add> if err := createTarFile(path, dest, hdr, trBuf, !options.NoLchown); err != nil {
<ide> return err
<ide> }
<ide>
<ide><path>archive/archive_test.go
<ide> func TestTarUntar(t *testing.T) {
<ide> if err := ioutil.WriteFile(path.Join(origin, "2"), []byte("welcome!"), 0700); err != nil {
<ide> t.Fatal(err)
<ide> }
<add> if err := ioutil.WriteFile(path.Join(origin, "3"), []byte("will be ignored"), 0700); err != nil {
<add> t.Fatal(err)
<add> }
<ide>
<ide> for _, c := range []Compression{
<ide> Uncompressed,
<ide> Gzip,
<ide> } {
<ide> changes, err := tarUntar(t, origin, &TarOptions{
<ide> Compression: c,
<add> Excludes: []string{"3"},
<ide> })
<ide>
<ide> if err != nil {
<ide> t.Fatalf("Error tar/untar for compression %s: %s", c.Extension(), err)
<ide> }
<ide>
<del> if len(changes) != 0 {
<add> if len(changes) != 1 || changes[0].Path != "/3" {
<ide> t.Fatalf("Unexpected differences after tarUntar: %v", changes)
<ide> }
<ide> }
<ide><path>graph/load.go
<ide> func (s *TagStore) CmdLoad(job *engine.Job) engine.Status {
<ide> if err := os.Mkdir(repoDir, os.ModeDir); err != nil {
<ide> return job.Error(err)
<ide> }
<del> if err := archive.Untar(repoFile, repoDir, nil); err != nil {
<add> images, err := s.graph.Map()
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> excludes := make([]string, len(images))
<add> i := 0
<add> for k := range images {
<add> excludes[i] = k
<add> i++
<add> }
<add> if err := archive.Untar(repoFile, repoDir, &archive.TarOptions{Excludes: excludes}); err != nil {
<ide> return job.Error(err)
<ide> }
<ide>
| 3
|
PHP
|
PHP
|
remove old missingmethod action
|
bf5d221037d9857a74020f2623839e282035a420
|
<ide><path>src/Illuminate/Routing/Controller.php
<ide> public function callAction($method, $parameters)
<ide> return call_user_func_array([$this, $method], $parameters);
<ide> }
<ide>
<del> /**
<del> * Handle calls to missing methods on the controller.
<del> *
<del> * @param array $parameters
<del> * @return mixed
<del> *
<del> * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
<del> */
<del> public function missingMethod($parameters = [])
<del> {
<del> throw new NotFoundHttpException('Controller method not found.');
<del> }
<del>
<ide> /**
<ide> * Handle calls to missing methods on the controller.
<ide> *
| 1
|
Javascript
|
Javascript
|
add check on overwriting canvas height/width
|
6b824d933451243a4fc57d973da6a8ebe6175b8f
|
<ide><path>src/core/core.helpers.js
<ide> module.exports = function(Chart) {
<ide> // If no style has been set on the canvas, the render size is used as display size,
<ide> // making the chart visually bigger, so let's enforce it to the "correct" values.
<ide> // See https://github.com/chartjs/Chart.js/issues/3575
<del> canvas.style.height = height + 'px';
<del> canvas.style.width = width + 'px';
<add> if (!canvas.style.height && !canvas.style.width) {
<add> canvas.style.height = height + 'px';
<add> canvas.style.width = width + 'px';
<add> }
<ide> };
<ide> // -- Canvas methods
<ide> helpers.fontString = function(pixelSize, fontStyle, fontFamily) {
<ide><path>test/specs/core.helpers.tests.js
<ide> describe('Core helper tests', function() {
<ide> document.body.removeChild(div);
<ide> });
<ide>
<add> it ('should leave styled height and width on canvas if explicitly set', function() {
<add> var chart = window.acquireChart({}, {
<add> canvas: {
<add> height: 200,
<add> width: 200,
<add> style: 'height: 400px; width: 400px;'
<add> }
<add> });
<add>
<add> helpers.retinaScale(chart, true);
<add>
<add> var canvas = chart.canvas;
<add>
<add> expect(canvas.style.height).toBe('400px');
<add> expect(canvas.style.width).toBe('400px');
<add> });
<add>
<ide> describe('Color helper', function() {
<ide> function isColorInstance(obj) {
<ide> return typeof obj === 'object' && obj.hasOwnProperty('values') && obj.values.hasOwnProperty('rgb');
| 2
|
Ruby
|
Ruby
|
add option to support previous encryption schemes
|
ae38e58ef6f085ce9086dd435284d848bb514d9d
|
<ide><path>activerecord/lib/active_record/encryption/config.rb
<ide> module Encryption
<ide> class Config
<ide> attr_accessor :master_key, :deterministic_key, :store_key_references, :key_derivation_salt,
<ide> :support_unencrypted_data, :encrypt_fixtures, :validate_column_size, :add_to_filter_parameters,
<del> :excluded_from_filter_parameters
<add> :excluded_from_filter_parameters, :support_previous_encryption_schemes
<ide>
<ide> def initialize
<ide> set_defaults
<ide> def set_defaults
<ide> self.encrypt_fixtures = false
<ide> self.validate_column_size = true
<ide> self.add_to_filter_parameters = true
<add> self.support_previous_encryption_schemes = true
<ide> self.excluded_from_filter_parameters = []
<ide> end
<ide> end
<ide><path>activerecord/lib/active_record/railtie.rb
<ide> class ActiveRecord::Fixture
<ide> end
<ide>
<ide> # Support extended queries for deterministic attributes
<del> if ActiveRecord::Encryption.config.support_unencrypted_data
<add> if ActiveRecord::Encryption.config.support_unencrypted_data || ActiveRecord::Encryption.config.support_previous_encryption_schemes
<ide> ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support
<ide> end
<ide>
| 2
|
Java
|
Java
|
fix cxxbridge usage of settablefuture
|
12bec39da12d1acde94e620b67bcc29ee5982c6f
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/queue/MessageQueueThreadImpl.java
<ide> package com.facebook.react.bridge.queue;
<ide>
<ide> import java.util.concurrent.Callable;
<add>import java.util.concurrent.ExecutionException;
<ide> import java.util.concurrent.Future;
<ide> import java.util.concurrent.TimeUnit;
<add>import java.util.concurrent.TimeoutException;
<ide>
<ide> import android.os.Looper;
<ide>
<ide> public void run() {
<ide> name,
<ide> simpleSettableFuture.get(5000, TimeUnit.MILLISECONDS),
<ide> exceptionHandler);
<del> } catch (Throwable t) {
<del> throw new RuntimeException(t);
<add> } catch (InterruptedException | ExecutionException | TimeoutException e) {
<add> throw new RuntimeException(e);
<ide> }
<ide> }
<ide> }
| 1
|
Javascript
|
Javascript
|
use remote tags and increment patch version
|
fe0e434a87be433bce69b46031b3ef2c379ce353
|
<ide><path>lib/grunt/utils.js
<ide> var shell = require('shelljs');
<ide> var grunt = require('grunt');
<ide> var spawn = require('child_process').spawn;
<ide> var semver = require('semver');
<del>var versionInfo = require('../versions/version-info');
<ide>
<ide> var _ = require('lodash');
<ide>
<ide><path>lib/versions/version-info.js
<ide> var isStable = function(version) {
<ide> * @return {Array.<SemVer>} The collection of previous versions
<ide> */
<ide> var getPreviousVersions = function() {
<del> var tagResults = shell.exec('git tag', {silent: true});
<add> // always use the remote tags as the local clone might
<add> // not contain all commits when cloned with git clone --depth=...
<add> // Needed e.g. for Travis
<add> var tagResults = shell.exec('git ls-remote --tags | grep -o -e "v[0-9].*[0-9]$"', {silent: true});
<ide> if ( tagResults.code === 0 ) {
<ide> return _(tagResults.output.trim().split('\n'))
<ide> .map(function(tag) {
<ide> var getPreviousVersions = function() {
<ide> * @return {SemVer} The snapshot version
<ide> */
<ide> var getSnapshotVersion = function() {
<del>
<ide> version = _(previousVersions)
<ide> .filter(function(tag) {
<ide> return semver.satisfies(tag, currentPackage.branchVersion);
<ide> })
<ide> .last();
<ide>
<ide> if ( !version ) {
<del> throw new Error("No valid versions can be found that match the current branch (" +
<del> currentPackage.branchVersion + ").\n" +
<del> "Try running `git fetch -t` to download the tags from the repository.");
<add> // a snapshot version before the first tag on the branch
<add> version = semver(currentPackage.branchVersion.replace('*','0-beta.1'));
<ide> }
<ide>
<ide> // We need to clone to ensure that we are not modifying another version
<ide> version = semver(version.raw);
<ide>
<ide> var jenkinsBuild = process.env.TRAVIS_BUILD_NUMBER || process.env.BUILD_NUMBER;
<add> if (!version.prerelease || !version.prerelease.length) {
<add> // last release was a non beta release. Increment the patch level to
<add> // indicate the next release that we will be doing.
<add> // E.g. last release was 1.3.0, then the snapshot will be
<add> // 1.3.1-build.1, which is lesser than 1.3.1 accorind the semver!
<add>
<add> // If the last release was a beta release we don't update the
<add> // beta number by purpose, as otherwise the semver comparison
<add> // does not work any more when the next beta is released.
<add> // E.g. don't generate 1.3.0-beta.2.build.1
<add> // as this is bigger than 1.3.0-beta.2 according to semver
<add> version.patch++;
<add> }
<ide> version.prerelease = jenkinsBuild ? ['build', jenkinsBuild] : ['local'];
<ide> version.build = getBuild();
<ide> version.codeName = 'snapshot';
| 2
|
Javascript
|
Javascript
|
increase the platform timeout for aix
|
75e073f2b2a0f5a5e002b485afd7288c9adecac6
|
<ide><path>test/common.js
<ide> exports.platformTimeout = function(ms) {
<ide> if (process.config.target_defaults.default_configuration === 'Debug')
<ide> ms = 2 * ms;
<ide>
<add> if (exports.isAix)
<add> return 2 * ms; // default localhost speed is slower on AIX
<add>
<ide> if (process.arch !== 'arm')
<ide> return ms;
<ide>
| 1
|
Text
|
Text
|
fix typo in doc/guides/collaborator-guide.md
|
c347f23175758fd0f0958c4ae335fc430dfecd35
|
<ide><path>doc/guides/collaborator-guide.md
<ide> describing a security issue, take the following steps:
<ide> pull request to the issue. Add screenshots of discussion from the pull request
<ide> to the issue.
<ide> * Open a ticket with GitHub asking that the pull requests be deleted through
<del> [GitHub suppport](https://support.github.com/contact)
<add> [GitHub support](https://support.github.com/contact)
<ide> using Node.js(team) as the account organization.
<ide> * Open a new issue in the repository in which the issue was originally
<ide> reported with a brief FYI to the originator: "FYI @xxxx we asked GitHub
| 1
|
Ruby
|
Ruby
|
add check for versioned gcc linkage
|
fec5b4080a87cb99e1aff19d36afcbbec4f725cf
|
<ide><path>Library/Homebrew/extend/os/linux/diagnostic.rb
<ide> def check_linuxbrew_bottle_domain
<ide> e.g. by using homebrew instead).
<ide> EOS
<ide> end
<add>
<add> def check_gcc_dependent_linkage
<add> gcc_dependents = Formula.installed.select do |formula|
<add> next false unless formula.tap&.core_tap?
<add>
<add> formula.recursive_dependencies.map(&:name).include? "gcc"
<add> rescue TapFormulaUnavailableError
<add> false
<add> end
<add> return if gcc_dependents.empty?
<add>
<add> badly_linked = gcc_dependents.select do |dependent|
<add> keg = Keg.new(dependent.prefix)
<add> keg.binary_executable_or_library_files.any? do |binary|
<add> paths = binary.rpath.split(":")
<add> versioned_linkage = paths.any? { |path| path.match?(%r{lib/gcc/\d+$}) }
<add> unversioned_linkage = paths.any? { |path| path.match?(%r{lib/gcc/current$}) }
<add>
<add> versioned_linkage && !unversioned_linkage
<add> end
<add> end
<add> return if badly_linked.empty?
<add>
<add> inject_file_list badly_linked, <<~EOS
<add> Formulae which link to GCC through a versioned path were found. These formulae
<add> are prone to breaking when GCC is updated. You should `brew reinstall` these formulae:
<add> EOS
<add> end
<ide> end
<ide> end
<ide> end
| 1
|
Ruby
|
Ruby
|
fix digest etag test
|
a7060a6e21cb6a6f501fef2a585df9ccda886863
|
<ide><path>railties/test/application/middleware_test.rb
<ide> def index
<ide> end
<ide> end
<ide>
<del> etag = "5af83e3196bf99f440f31f2e1a6c9afe".inspect
<add> etag = "W/" + ("5af83e3196bf99f440f31f2e1a6c9afe".inspect)
<ide>
<ide> get "/"
<ide> assert_equal 200, last_response.status
| 1
|
Text
|
Text
|
add example of malloc
|
e6a6bb0c82833a16a646404981702308ee8d106a
|
<ide><path>guide/english/c/malloc/index.md
<ide> free( arrayPtr );
<ide> ```
<ide> This statement will deallocate the memory previously allocated. C does not come with a `garbage collector` like some other languages, such as Java. As a result, memory not properly freed will continue to be allocated after the program is closed.
<ide>
<add>### Example
<add>```C
<add>#include <stdio.h>
<add>#include <stdlib.h>
<add>
<add>int main()
<add>{
<add> int num, i, *ptr, sum = 0;
<add>
<add> printf("Enter number of elements: ");
<add> scanf("%d", &num);
<add>
<add> ptr = (int*) malloc(num * sizeof(int)); //memory is allocated using malloc
<add> if(ptr == NULL)
<add> {
<add> printf("Error! memory not allocated.");
<add> exit(0);
<add> }
<add>
<add> printf("Enter elements of array: ");
<add> for(i = 0; i < num; ++i)
<add> {
<add> scanf("%d", ptr + i);
<add> sum += *(ptr + i);
<add> }
<add>
<add> printf("Sum = %d", sum);
<add> free(ptr);
<add> return 0;
<add>}
<add>```
<add>
<ide> # Before you go on...
<ide> ## A Review
<ide> * Malloc is used for dynamic memory allocation and is useful when you don't know the amount of memory needed during compile time.
| 1
|
Python
|
Python
|
add ndmin keyword to loadtxt. closes
|
a311969ea2f47b486da14da99a26e72c12a0c20f
|
<ide><path>numpy/lib/npyio.py
<ide> def _getconv(dtype):
<ide>
<ide>
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None,
<del> converters=None, skiprows=0, usecols=None, unpack=False):
<add> converters=None, skiprows=0, usecols=None, unpack=False,
<add> ndmin=0):
<ide> """
<ide> Load data from a text file.
<ide>
<ide> def loadtxt(fname, dtype=float, comments='#', delimiter=None,
<ide> If True, the returned array is transposed, so that arguments may be
<ide> unpacked using ``x, y, z = loadtxt(...)``. When used with a record
<ide> data-type, arrays are returned for each field. Default is False.
<add> ndmin : int, optional
<add> The returned array must have at least `ndmin` dimensions.
<add> Legal values: 0 (default), 1 or 2.
<ide>
<ide> Returns
<ide> -------
<ide> def split_line(line):
<ide>
<ide> X = np.array(X, dtype)
<ide>
<del> X = np.squeeze(X)
<add> # Verify that the array has at least dimensions `ndmin`.
<add> # Check correctness of the values of `ndmin`
<add> if not ndmin in [0, 1, 2]:
<add> raise ValueError('Illegal value of ndmin keyword: %s' % ndmin)
<add> # Tweak the size and shape of the arrays
<add> if X.ndim > ndmin:
<add> X = np.squeeze(X)
<add> # Has to be in this order for the odd case ndmin=1, X.squeeze().ndim=0
<add> if X.ndim < ndmin:
<add> if ndmin == 1:
<add> X.shape = (X.size, )
<add> elif ndmin == 2:
<add> X.shape = (X.size, 1)
<add>
<ide> if unpack:
<ide> if len(dtype_types) > 1:
<ide> # For structured arrays, return an array for each field.
<ide><path>numpy/lib/tests/test_io.py
<ide> def test_structure_unpack(self):
<ide> assert_array_equal(b, np.array([21, 35]))
<ide> assert_array_equal(c, np.array([ 72., 58.]))
<ide>
<add> def test_ndmin_keyword(self):
<add> c = StringIO()
<add> c.write(asbytes('1,2,3\n4,5,6'))
<add> c.seek(0)
<add> x = np.loadtxt(c, dtype=int, delimiter=',', ndmin=1)
<add> a = np.array([[1, 2, 3], [4, 5, 6]])
<add> assert_array_equal(x, a)
<add> d = StringIO()
<add> d.write(asbytes('0,1,2'))
<add> d.seek(0)
<add> x = np.loadtxt(d, dtype=int, delimiter=',', ndmin=2)
<add> assert_(x.shape == (3, 1))
<add> assert_raises(ValueError, np.loadtxt, d, ndmin=3)
<add> assert_raises(ValueError, np.loadtxt, d, ndmin=1.5)
<add> e = StringIO()
<add> assert_(np.loadtxt(e, ndmin=2).shape == (0, 1,))
<add>
<ide>
<ide> class Testfromregex(TestCase):
<ide> def test_record(self):
| 2
|
Text
|
Text
|
correct typos in readme
|
226b8ef063e210794d177cdf8e1cbf2a302c6d08
|
<ide><path>docs/README.md
<ide> limitations under the License.
<ide>
<ide> # Generating the documentation
<ide>
<del>To generate the documentation, you first have to build it. Several packages are necessary to build the doc,
<add>To generate the documentation, you first have to build it. Several packages are necessary to build the doc,
<ide> you can install them with the following command, at the root of the code repository:
<ide>
<ide> ```bash
<ide> pip install git+https://github.com/huggingface/doc-builder
<ide> **NOTE**
<ide>
<ide> You only need to generate the documentation to inspect it locally (if you're planning changes and want to
<del>check how they look like before committing for instance). You don't have to commit the built documentation.
<add>check how they look before committing for instance). You don't have to commit the built documentation.
<ide>
<ide> ---
<ide>
<ide> the filename without the extension in the [`_toctree.yml`](https://github.com/hu
<ide>
<ide> ## Renaming section headers and moving sections
<ide>
<del>It helps to keep the old links working when renaming section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums and Social media and it'd be make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information.
<add>It helps to keep the old links working when renaming the section header and/or moving sections from one document to another. This is because the old links are likely to be used in Issues, Forums, and Social media and it'd make for a much more superior user experience if users reading those months later could still easily navigate to the originally intended information.
<ide>
<ide> Therefore we simply keep a little map of moved sections at the end of the document where the original section was. The key is to preserve the original anchor.
<ide>
<ide> Sections that were moved:
<ide>
<ide> [ <a href="#section-b">Section A</a><a id="section-a"></a> ]
<ide> ```
<del>and of course if you moved it to another file, then:
<add>and of course, if you moved it to another file, then:
<ide>
<ide> ```
<ide> Sections that were moved:
<ide> Sections that were moved:
<ide>
<ide> Use the relative style to link to the new file so that the versioned docs continue to work.
<ide>
<del>For an example of a rich moved sections set please see the very end of [the Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/main_classes/trainer.mdx).
<add>For an example of a rich moved section set please see the very end of [the Trainer doc](https://github.com/huggingface/transformers/blob/main/docs/source/en/main_classes/trainer.mdx).
<ide>
<ide>
<ide> ## Writing Documentation - Specification
<ide> Adding a new tutorial or section is done in two steps:
<ide> - Link that file in `./source/_toctree.yml` on the correct toc-tree.
<ide>
<ide> Make sure to put your new file under the proper section. It's unlikely to go in the first section (*Get Started*), so
<del>depending on the intended targets (beginners, more advanced users or researchers) it should go in section two, three or
<add>depending on the intended targets (beginners, more advanced users, or researchers) it should go in sections two, three, or
<ide> four.
<ide>
<ide> ### Translating
<ide> not to be displayed in the documentation, you can do so by specifying which meth
<ide> - save_vocabulary
<ide> ```
<ide>
<del>If you just want to add a method that is not documented (for instance magic method like `__call__` are not documented
<del>byt default) you can put the list of methods to add in a list that contains `all`:
<add>If you just want to add a method that is not documented (for instance magic methods like `__call__` are not documented
<add>by default) you can put the list of methods to add in a list that contains `all`:
<ide>
<ide> ```
<ide> ## XXXTokenizer
<ide> byt default) you can put the list of methods to add in a list that contains `all
<ide> ### Writing source documentation
<ide>
<ide> Values that should be put in `code` should either be surrounded by backticks: \`like so\`. Note that argument names
<del>and objects like True, None or any strings should usually be put in `code`.
<add>and objects like True, None, or any strings should usually be put in `code`.
<ide>
<del>When mentioning a class, function or method, it is recommended to use our syntax for internal links so that our tool
<add>When mentioning a class, function, or method, it is recommended to use our syntax for internal links so that our tool
<ide> adds a link to its documentation with this syntax: \[\`XXXClass\`\] or \[\`function\`\]. This requires the class or
<ide> function to be in the main package.
<ide>
<ide> The same works for methods so you can either use \[\`XXXClass.method\`\] or \[~\
<ide> #### Defining arguments in a method
<ide>
<ide> Arguments should be defined with the `Args:` (or `Arguments:` or `Parameters:`) prefix, followed by a line return and
<del>an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon and its
<add>an indentation. The argument should be followed by its type, with its shape if it is a tensor, a colon, and its
<ide> description:
<ide>
<ide> ```
<ide> description:
<ide> ```
<ide>
<ide> If the description is too long to fit in one line, another indentation is necessary before writing the description
<del>after th argument.
<add>after the argument.
<ide>
<ide> Here's an example showcasing everything so far:
<ide>
<ide> Multi-line code blocks can be useful for displaying examples. They are done betw
<ide> ````
<ide>
<ide> We follow the [doctest](https://docs.python.org/3/library/doctest.html) syntax for the examples to automatically test
<del>the results stay consistent with the library.
<add>the results to stay consistent with the library.
<ide>
<ide> #### Writing a return block
<ide>
<ide> The return block should be introduced with the `Returns:` prefix, followed by a line return and an indentation.
<ide> The first line should be the type of the return, followed by a line return. No need to indent further for the elements
<ide> building the return.
<ide>
<del>Here's an example for a single value return:
<add>Here's an example of a single value return:
<ide>
<ide> ```
<ide> Returns:
<ide> `List[int]`: A list of integers in the range [0, 1] --- 1 for a special token, 0 for a sequence token.
<ide> ```
<ide>
<del>Here's an example for tuple return, comprising several objects:
<add>Here's an example of a tuple return, comprising several objects:
<ide>
<ide> ```
<ide> Returns:
<ide> `tuple(torch.FloatTensor)` comprising various elements depending on the configuration ([`BertConfig`]) and inputs:
<ide> - ** loss** (*optional*, returned when `masked_lm_labels` is provided) `torch.FloatTensor` of shape `(1,)` --
<del> Total loss as the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
<add> Total loss is the sum of the masked language modeling loss and the next sequence prediction (classification) loss.
<ide> - **prediction_scores** (`torch.FloatTensor` of shape `(batch_size, sequence_length, config.vocab_size)`) --
<ide> Prediction scores of the language modeling head (scores for each vocabulary token before SoftMax).
<ide> ```
<ide>
<ide> #### Adding an image
<ide>
<del>Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
<add>Due to the rapidly growing repository, it is important to make sure that no files that would significantly weigh down the repository are added. This includes images, videos, and other non-text files. We prefer to leverage a hf.co hosted `dataset` like
<ide> the ones hosted on [`hf-internal-testing`](https://huggingface.co/hf-internal-testing) in which to place these files and reference
<ide> them by URL. We recommend putting them in the following dataset: [huggingface/documentation-images](https://huggingface.co/datasets/huggingface/documentation-images).
<ide> If an external contribution, feel free to add the images to your PR and ask a Hugging Face member to migrate your images
<ide> We use pytests' [doctest integration](https://docs.pytest.org/doctest.html) to v
<ide> For Transformers, the doctests are run on a daily basis via GitHub Actions as can be
<ide> seen [here](https://github.com/huggingface/transformers/actions/workflows/doctests.yml).
<ide>
<del>To include your example in the daily doctests, you need add the filename that
<add>To include your example in the daily doctests, you need to add the filename that
<ide> contains the example docstring to the [documentation_tests.txt](../utils/documentation_tests.txt).
<ide>
<ide> ### For Python files
<ide> Here are a few tips to help you debug the doctests and make them pass:
<ide>
<ide> - The outputs of the code need to match the expected output **exactly**, so make sure you have the same outputs. In particular doctest will see a difference between single quotes and double quotes, or a missing parenthesis. The only exceptions to that rule are:
<ide> * whitespace: one give whitespace (space, tabulation, new line) is equivalent to any number of whitespace, so you can add new lines where there are spaces to make your output more readable.
<del> * numerical values: you should never put more than 4 or 5 digits to expected results as different setups or library versions might get you slightly different results. `doctest` is configure to ignore any difference lower than the precision to which you wrote (so 1e-4 if you write 4 digits).
<add> * numerical values: you should never put more than 4 or 5 digits to expected results as different setups or library versions might get you slightly different results. `doctest` is configured to ignore any difference lower than the precision to which you wrote (so 1e-4 if you write 4 digits).
<ide> - Don't leave a block of code that is very long to execute. If you can't make it fast, you can either not use the doctest syntax on it (so that it's ignored), or if you want to use the doctest syntax to show the results, you can add a comment `# doctest: +SKIP` at the end of the lines of code too long to execute
<ide> - Each line of code that produces a result needs to have that result written below. You can ignore an output if you don't want to show it in your code example by adding a comment ` # doctest: +IGNORE_RESULT` at the end of the line of code producing it.
| 1
|
Javascript
|
Javascript
|
apply custom header to generated files
|
1ae579eb0d1bb688db2902072fafa37863bf59a4
|
<ide><path>tasks/transpile.js
<ide> module.exports = function (grunt) {
<ide> }
<ide>
<ide> function transpile(opts) {
<del> // base, entry, skip, headerFile, skipLines, target
<add> // base, entry, skipMoment, headerFile, skipLines, target
<ide> var umdName = opts.headerFile != null && opts.headerFile !== 'none' ? 'not_used' : opts.umdName,
<ide> headerFile = opts.headerFile ? opts.headerFile : 'templates/default.js',
<ide> header = getHeaderByFile(headerFile),
<ide> module.exports = function (grunt) {
<ide> return rollupBundle({
<ide> entry: path.join(opts.base, opts.entry),
<ide> skipMoment: opts.skipMoment != null ? opts.skipMoment : false,
<del> // skip: opts.skip || [],
<ide> umdName: umdName
<ide> }).then(function (code) {
<ide> var fixed = header + code.split('\n').slice(skipLines).join('\n');
<ide> module.exports = function (grunt) {
<ide> });
<ide> }
<ide>
<del> function generateLocales(target, localeFiles) {
<add> function generateLocales(target, localeFiles, opts) {
<ide> var files = localeFiles,
<ide> code = [
<ide> 'import moment from "./moment";'
<ide> module.exports = function (grunt) {
<ide> base: 'src',
<ide> code: code,
<ide> target: target,
<del> skipMoment: true,
<del> headerFile: 'none', //'templates/locale-header.js',
<del> skipLines: 0, // 5
<del> });
<del> }
<del>
<del> function generateMomentWithLocales(target, localeFiles) {
<del> var files = localeFiles,
<del> code = [
<del> 'import moment from "./moment";'
<del> ].concat(files.map(function (file) {
<del> var identifier = path.basename(file, '.js').replace('-', '_');
<del> return 'import ' + identifier + ' from "./' + file + '";';
<del> })).concat([
<del> // Reset the language back to 'en', because every defineLocale
<del> // also sets it.
<del> 'moment.locale("en");',
<del> 'export default moment;'
<del> ]).join('\n');
<del>
<del> return transpileCode({
<del> base: 'src',
<del> code: code,
<del> target: target,
<del> headerFile: 'none', //'templates/locale-header.js',
<del> skipLines: 0, // 5
<add> skipMoment: opts.skipMoment,
<add> headerFile: 'templates/locale-header.js',
<add> skipLines: 7
<ide> });
<ide> }
<ide>
<ide> module.exports = function (grunt) {
<ide> entry: 'moment.js',
<ide> umdName: 'moment',
<ide> target: 'build/umd/moment.js',
<del>
<del> skipLines: 0, // 5
<del> headerFile: 'none', // wasn't set --> default
<del>
<add> skipLines: 5,
<ide> moveComments: true
<ide> }).then(function () {
<ide> grunt.log.ok('build/umd/moment.js');
<ide> }).then(function () {
<ide> return transpileMany({
<ide> base: 'src',
<ide> pattern: 'locale/*.js',
<del> headerFile: 'none', // 'templates/locale-header.js',
<del> skipLines: 0, // 5
<add> headerFile: 'templates/locale-header.js',
<add> skipLines: 7,
<ide> moveComments: true,
<ide> targetDir: 'build/umd',
<ide> skipMoment: true,
<ide> module.exports = function (grunt) {
<ide> return transpileMany({
<ide> base: 'src',
<ide> pattern: 'test/moment/*.js',
<del> headerFile: 'none', //'templates/test-header.js',
<del> skipLines: 0, // 5
<add> headerFile: 'templates/test-header.js',
<add> skipLines: 7,
<ide> moveComments: true,
<ide> targetDir: 'build/umd',
<ide> skipMoment: true
<ide> module.exports = function (grunt) {
<ide> return transpileMany({
<ide> base: 'src',
<ide> pattern: 'test/locale/*.js',
<del> headerFile: 'none', //'templates/test-header.js',
<del> skipLines: 0, // 5
<add> headerFile: 'templates/test-header.js',
<add> skipLines: 7,
<ide> moveComments: true,
<ide> targetDir: 'build/umd',
<ide> skipMoment: true
<ide> module.exports = function (grunt) {
<ide> }).then(function () {
<ide> return generateLocales(
<ide> 'build/umd/min/locales.js',
<del> grunt.file.expand({cwd: 'src'}, 'locale/*.js'
<del> ));
<add> grunt.file.expand({cwd: 'src'}, 'locale/*.js'),
<add> {skipMoment: true}
<add> );
<ide> }).then(function () {
<ide> grunt.log.ok('build/umd/min/locales.js');
<ide> }).then(function () {
<del> return generateMomentWithLocales('build/umd/min/moment-with-locales.js',
<del> grunt.file.expand({cwd: 'src'}, 'locale/*.js'));
<add> return generateLocales(
<add> 'build/umd/min/moment-with-locales.js',
<add> grunt.file.expand({cwd: 'src'}, 'locale/*.js'),
<add> {skipMoment: false}
<add> );
<ide> }).then(function () {
<ide> grunt.log.ok('build/umd/min/moment-with-locales.js');
<ide> }).then(done, function (e) {
<ide><path>templates/default.js
<ide> typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
<ide> typeof define === 'function' && define.amd ? define(factory) :
<ide> global.moment = factory()
<del>}(this, function () { 'use strict';
<add>}(this, (function () { 'use strict';
<ide><path>templates/locale-header.js
<ide> && typeof require === 'function' ? factory(require('../moment')) :
<ide> typeof define === 'function' && define.amd ? define(['../moment'], factory) :
<ide> factory(global.moment)
<del>}(this, function (moment) { 'use strict';
<add>}(this, (function (moment) { 'use strict';
<ide><path>templates/test-header.js
<ide> && typeof require === 'function' ? factory(require('../../moment')) :
<ide> typeof define === 'function' && define.amd ? define(['../../moment'], factory) :
<ide> factory(global.moment)
<del>}(this, function (moment) { 'use strict';
<add>}(this, (function (moment) { 'use strict';
| 4
|
Text
|
Text
|
use variable instead of hardcoding version in repo
|
196bd38fdbd05701294eb924755fd551b977d87c
|
<ide><path>docs/installation/centos.md
<ide> package manager.
<ide>
<ide> 3. Add the yum repo.
<ide>
<del> $ sudo tee /etc/yum.repos.d/docker.repo <<-EOF
<add> $ sudo tee /etc/yum.repos.d/docker.repo <<-'EOF'
<ide> [dockerrepo]
<ide> name=Docker Repository
<del> baseurl=https://yum.dockerproject.org/repo/main/centos/7
<add> baseurl=https://yum.dockerproject.org/repo/main/centos/$releasever/
<ide> enabled=1
<ide> gpgcheck=1
<ide> gpgkey=https://yum.dockerproject.org/gpg
<ide><path>docs/installation/fedora.md
<ide> There are two ways to install Docker Engine. You can install with the `yum` pac
<ide>
<ide> 3. Add the yum repo yourself.
<ide>
<del> For Fedora 21 run:
<del>
<del> $ sudo tee /etc/yum.repos.d/docker.repo <<-EOF
<del> [dockerrepo]
<del> name=Docker Repository
<del> baseurl=https://yum.dockerproject.org/repo/main/fedora/21
<del> enabled=1
<del> gpgcheck=1
<del> gpgkey=https://yum.dockerproject.org/gpg
<del> EOF
<del>
<del> For Fedora 22 run:
<del>
<del> $ cat >/etc/yum.repos.d/docker.repo <<-EOF
<add> $ sudo tee /etc/yum.repos.d/docker.repo <<-'EOF'
<ide> [dockerrepo]
<ide> name=Docker Repository
<del> baseurl=https://yum.dockerproject.org/repo/main/fedora/22
<add> baseurl=https://yum.dockerproject.org/repo/main/fedora/$releasever/
<ide> enabled=1
<ide> gpgcheck=1
<ide> gpgkey=https://yum.dockerproject.org/gpg
| 2
|
Python
|
Python
|
fix mappings of get_data_disks
|
4e9ec02fd276883238a762e12453fa1d62c2325d
|
<ide><path>libcloud/compute/drivers/ecs.py
<ide> def _get_data_disks(self, ex_data_disks):
<ide> mappings = {'size': 'Size',
<ide> 'category': 'Category',
<ide> 'snapshot_id': 'SnapshotId',
<del> 'disk_name': 'DiskName',
<add> 'name': 'DiskName',
<ide> 'description': 'Description',
<ide> 'device': 'Device',
<del> 'delete_with_instance': 'DeleteWithInstance'}
<add> 'delete_on_termination': 'DeleteWithInstance'}
<ide> params = {}
<ide> for idx, disk in enumerate(data_disks):
<ide> key_base = 'DataDisk.{0}.'.format(idx + 1)
| 1
|
Python
|
Python
|
add test for minibatch util
|
85b0597ed5f8e23de337f56966e4b342827a99c3
|
<ide><path>spacy/tests/test_util.py
<add>import pytest
<add>from spacy.gold import Example
<add>
<add>from .util import get_doc
<add>
<add>from spacy.util import minibatch_by_words
<add>
<add>
<add>@pytest.mark.parametrize(
<add> "doc_sizes, expected_batches",
<add> [
<add> ([400, 400, 199], [3]),
<add> ([400, 400, 199, 3], [4]),
<add> ([400, 400, 199, 3, 250], [3, 2]),
<add> ],
<add>)
<add>def test_util_minibatch(doc_sizes, expected_batches):
<add> docs = [get_doc(doc_size) for doc_size in doc_sizes]
<add>
<add> examples = [Example(doc=doc) for doc in docs]
<add>
<add> batches = list(minibatch_by_words(examples=examples, size=1000))
<add> assert [len(batch) for batch in batches] == expected_batches
<ide><path>spacy/tests/util.py
<ide> def get_batch(batch_size):
<ide> return docs
<ide>
<ide>
<add>def get_doc(n_words):
<add> vocab = Vocab()
<add> # Make the words numbers, so that they're easy to track.
<add> numbers = [str(i) for i in range(0, n_words)]
<add> return Doc(vocab, words=numbers)
<add>
<add>
<ide> def apply_transition_sequence(parser, doc, sequence):
<ide> """Perform a series of pre-specified transitions, to put the parser in a
<ide> desired state."""
| 2
|
Python
|
Python
|
add unit test for log retrieval url
|
061caff2862d9df078336dc94efa5a6915935b7e
|
<ide><path>airflow/utils/log/file_task_handler.py
<ide> def _read(self, ti: TaskInstance, try_number: int, metadata: dict[str, Any] | No
<ide> else:
<ide> import httpx
<ide>
<del> url = urljoin(
<del> f"http://{ti.hostname}:{conf.get('logging', 'WORKER_LOG_SERVER_PORT')}/log/",
<del> log_relative_path,
<del> )
<add> url = self._get_log_retrieval_url(ti, log_relative_path)
<ide> log += f"*** Log file does not exist: {location}\n"
<ide> log += f"*** Fetching from: {url}\n"
<ide> try:
<ide> def _read(self, ti: TaskInstance, try_number: int, metadata: dict[str, Any] | No
<ide>
<ide> return log, {'end_of_log': end_of_log, 'log_pos': log_pos}
<ide>
<add> @staticmethod
<add> def _get_log_retrieval_url(ti: TaskInstance, log_relative_path: str) -> str:
<add> url = urljoin(
<add> f"http://{ti.hostname}:{conf.get('logging', 'WORKER_LOG_SERVER_PORT')}/log/",
<add> log_relative_path,
<add> )
<add> return url
<add>
<ide> def read(self, task_instance, try_number=None, metadata=None):
<ide> """
<ide> Read logs of given task instance from local machine.
<ide><path>tests/utils/test_log_handlers.py
<ide> def test_jinja_rendering(self, create_log_template, create_task_instance):
<ide> fth = FileTaskHandler("")
<ide> rendered_filename = fth._render_filename(filename_rendering_ti, 42)
<ide> assert expected_filename == rendered_filename
<add>
<add>
<add>class TestLogUrl:
<add> def test_log_retrieval_valid(self, create_task_instance):
<add> log_url_ti = create_task_instance(
<add> dag_id="dag_for_testing_filename_rendering",
<add> task_id="task_for_testing_filename_rendering",
<add> run_type=DagRunType.SCHEDULED,
<add> execution_date=DEFAULT_DATE,
<add> )
<add> log_url_ti.hostname = 'hostname'
<add> url = FileTaskHandler._get_log_retrieval_url(log_url_ti, 'DYNAMIC_PATH')
<add> assert url == "http://hostname:8793/log/DYNAMIC_PATH"
| 2
|
Text
|
Text
|
sanitize css comments on typography lesson
|
a329eec0a8f12aa975413f29b105981b9862caf3
|
<ide><path>curriculum/challenges/english/01-responsive-web-design/responsive-web-design-principles/make-typography-responsive.md
<ide> Set the `width` of the `h2` tag to 80% of the viewport's width and the `width` o
<ide> Your `h2` tag should have a `width` of 80vw.
<ide>
<ide> ```js
<del>assert(code.match(/h2\s*?{\s*?width:\s*?80vw;\s*?}/g));
<add>assert(
<add> __helpers
<add> .removeCssComments(code)
<add> .match(/h2\s*?{\s*?width:\s*?80vw;\s*?}/g)
<add>);
<ide> ```
<ide>
<ide> Your `p` tag should have a `width` of 75vmin.
<ide>
<ide> ```js
<del>assert(code.match(/p\s*?{\s*?width:\s*?75vmin;\s*?}/g));
<add>assert(
<add> __helpers
<add> .removeCssComments(code)
<add> .match(/p\s*?{\s*?width:\s*?75vmin;\s*?}/g)
<add>);
<ide> ```
<ide>
<ide> # --seed--
| 1
|
Python
|
Python
|
update fabfile from develop
|
04af13e29a1fbad38fb453fb39b6b10ac0804cd5
|
<ide><path>fabfile.py
<ide> def env(lang='python2.7'):
<ide> if path.exists(VENV_DIR):
<ide> local('rm -rf {env}'.format(env=VENV_DIR))
<add> local('pip install virtualenv')
<ide> local('python -m virtualenv -p {lang} {env}'.format(lang=lang, env=VENV_DIR))
<ide>
<ide>
<ide> def make():
<ide> local('pip install -r requirements.txt')
<ide> local('python setup.py build_ext --inplace')
<ide>
<add>def sdist():
<add> with virtualenv(VENV_DIR):
<add> with lcd(path.dirname(__file__)):
<add> local('python setup.py sdist')
<ide>
<ide> def clean():
<ide> with lcd(path.dirname(__file__)):
| 1
|
PHP
|
PHP
|
implement createfile on consoleio
|
c86ebc5bc7d12e01a34942434acdaa99b75f8602
|
<ide><path>src/Console/ConsoleIo.php
<ide> */
<ide> namespace Cake\Console;
<ide>
<add>use Cake\Console\Exception\StopException;
<ide> use Cake\Log\Engine\ConsoleLog;
<ide> use Cake\Log\Log;
<add>use RuntimeException;
<add>use SplFileObject;
<ide>
<ide> /**
<ide> * A wrapper around the various IO operations shell tasks need to do.
<ide> class ConsoleIo
<ide> */
<ide> protected $_lastWritten = 0;
<ide>
<add> /**
<add> * Whether or not files should be overwritten
<add> *
<add> * @var bool
<add> */
<add> protected $forceOverwrite = false;
<add>
<ide> /**
<ide> * Constructor
<ide> *
<ide> public function helper($name, array $settings = [])
<ide>
<ide> return $this->_helpers->load($name, $settings);
<ide> }
<add>
<add> /**
<add> * Create a file at the given path.
<add> *
<add> * This method will prompt the user if a file will be overwritten.
<add> * Setting `forceOverwrite` to true will suppress this behavior
<add> * and always overwrite the file.
<add> *
<add> * If the user replies `a` subsequent `forceOverwrite` parameters will
<add> * be coerced to true and all files will be overwritten.
<add> *
<add> * @param string $path The path to create the file at.
<add> * @param string $contents The contents to put into the file.
<add> * @param bool $forceOverwrite Whether or not the file should be overwritten.
<add> * If true, no question will be asked about whether or not to overwrite existing files.
<add> * @return bool Success.
<add> * @throws \Cake\Console\Exception\StopException When `q` is given as an answer
<add> * to whether or not a file should be overwritten.
<add> */
<add> public function createFile($path, $contents, $forceOverwrite = false)
<add> {
<add> $path = str_replace(
<add> DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR,
<add> DIRECTORY_SEPARATOR,
<add> $path
<add> );
<add>
<add> $this->out();
<add> $forceOverwrite = $forceOverwrite || $this->forceOverwrite;
<add>
<add> if (file_exists($path) && $forceOverwrite === false) {
<add> $this->warning("File `{$path}` exists");
<add> $key = $this->askChoice('Do you want to overwrite?', ['y', 'n', 'a', 'q'], 'n');
<add> $key = strtolower($key);
<add>
<add> if ($key === 'q') {
<add> $this->error('Quitting.', 2);
<add> throw new StopException('Not creating file. Quitting.');
<add> }
<add> if ($key === 'a') {
<add> $this->forceOverwrite = true;
<add> $key = 'y';
<add> }
<add> if ($key !== 'y') {
<add> $this->out("Skip `{$path}`", 2);
<add>
<add> return false;
<add> }
<add> } else {
<add> $this->out("Creating file {$path}");
<add> }
<add>
<add> try {
<add> $file = new SplFileObject($path, 'w');
<add> } catch (RuntimeException $e) {
<add> $this->error("Could not write to `{$path}`. Permission denied.", 2);
<add>
<add> return false;
<add> }
<add>
<add> $file->rewind();
<add> if ($file->fwrite($contents) > 0) {
<add> $this->out("<success>Wrote</success> `{$path}`");
<add>
<add> return true;
<add> }
<add> $this->error("Could not write to `{$path}`.", 2);
<add>
<add> return false;
<add> }
<ide> }
<ide><path>tests/TestCase/Console/ConsoleIoTest.php
<ide> namespace Cake\Test\TestCase\Console;
<ide>
<ide> use Cake\Console\ConsoleIo;
<add>use Cake\Filesystem\Folder;
<ide> use Cake\Log\Log;
<ide> use Cake\TestSuite\TestCase;
<ide>
<ide> public function setUp()
<ide> $this->io = new ConsoleIo($this->out, $this->err, $this->in);
<ide> }
<ide>
<add> /**
<add> * teardown method
<add> *
<add> * @return void
<add> */
<add> public function tearDown()
<add> {
<add> parent::tearDown();
<add> if (is_dir(TMP . 'shell_test')) {
<add> $folder = new Folder(TMP . 'shell_test');
<add> $folder->delete();
<add> }
<add> }
<add>
<ide> /**
<ide> * Provider for testing choice types.
<ide> *
<ide> public function testErrHelpers($method)
<ide> $this->io->{$method}('Just a test');
<ide> $this->io->{$method}(['Just', 'a test']);
<ide> }
<add>
<add> /**
<add> * Test that createFile
<add> *
<add> * @return void
<add> */
<add> public function testCreateFileSuccess()
<add> {
<add> $path = TMP . 'shell_test';
<add> mkdir($path);
<add>
<add> $file = $path . DS . 'file1.php';
<add> $contents = 'some content';
<add> $result = $this->io->createFile($file, $contents);
<add>
<add> $this->assertTrue($result);
<add> $this->assertFileExists($file);
<add> $this->assertEquals($contents, file_get_contents($file));
<add> }
<add>
<add> /**
<add> * Test that createFile with permissions error.
<add> *
<add> * @return void
<add> */
<add> public function testCreateFilePermissionsError()
<add> {
<add> $this->skipIf(DS === '\\', 'Cant perform operations using permissions on windows.');
<add>
<add> $path = TMP . 'shell_test';
<add> $file = $path . DS . 'no_perms';
<add>
<add> if (!is_dir($path)) {
<add> mkdir($path);
<add> }
<add> chmod($path, 0444);
<add>
<add> $this->io->createFile($file, 'testing');
<add> $this->assertFileNotExists($file);
<add>
<add> chmod($path, 0744);
<add> rmdir($path);
<add> }
<add>
<add> /**
<add> * Test that `q` raises an error.
<add> *
<add> * @expectedException \Cake\Console\Exception\StopException
<add> * @return void
<add> */
<add> public function testCreateFileOverwriteQuit()
<add> {
<add> $path = TMP . 'shell_test';
<add> mkdir($path);
<add>
<add> $file = $path . DS . 'file1.php';
<add> touch($file);
<add>
<add> $this->in->expects($this->once())
<add> ->method('read')
<add> ->will($this->returnValue('q'));
<add>
<add> $this->io->createFile($file, 'some content');
<add> }
<add>
<add> /**
<add> * Test that `n` raises an error.
<add> *
<add> * @return void
<add> */
<add> public function testCreateFileOverwriteNo()
<add> {
<add> $path = TMP . 'shell_test';
<add> mkdir($path);
<add>
<add> $file = $path . DS . 'file1.php';
<add> file_put_contents($file, 'original');
<add> touch($file);
<add>
<add> $this->in->expects($this->once())
<add> ->method('read')
<add> ->will($this->returnValue('n'));
<add>
<add> $contents = 'new content';
<add> $result = $this->io->createFile($file, $contents);
<add>
<add> $this->assertFalse($result);
<add> $this->assertFileExists($file);
<add> $this->assertEquals('original', file_get_contents($file));
<add> }
<add>
<add> /**
<add> * Test the forceOverwrite parameter
<add> *
<add> * @return void
<add> */
<add> public function testCreateFileOverwriteParam()
<add> {
<add> $path = TMP . 'shell_test';
<add> mkdir($path);
<add>
<add> $file = $path . DS . 'file1.php';
<add> file_put_contents($file, 'original');
<add> touch($file);
<add>
<add> $contents = 'new content';
<add> $result = $this->io->createFile($file, $contents, true);
<add>
<add> $this->assertTrue($result);
<add> $this->assertFileExists($file);
<add> $this->assertEquals($contents, file_get_contents($file));
<add> }
<add>
<add> /**
<add> * Test the `a` response
<add> *
<add> * @return void
<add> */
<add> public function testCreateFileOverwriteAll()
<add> {
<add> $path = TMP . 'shell_test';
<add> mkdir($path);
<add>
<add> $file = $path . DS . 'file1.php';
<add> file_put_contents($file, 'original');
<add> touch($file);
<add>
<add> $this->in->expects($this->once())
<add> ->method('read')
<add> ->will($this->returnValue('a'));
<add>
<add> $this->io->createFile($file, 'new content');
<add> $this->assertEquals('new content', file_get_contents($file));
<add>
<add> $this->io->createFile($file, 'newer content');
<add> $this->assertEquals('newer content', file_get_contents($file));
<add>
<add> $this->io->createFile($file, 'newest content', false);
<add> $this->assertEquals(
<add> 'newest content',
<add> file_get_contents($file),
<add> 'overwrite state replaces parameter'
<add> );
<add> }
<ide> }
| 2
|
Text
|
Text
|
update layout property part
|
1ab90c142c22e6e444488e4af5b308bcd33dd1e8
|
<ide><path>docs/api-reference/next/image.md
<ide> When `responsive`, the image will scale the dimensions down for smaller
<ide> viewports and scale up for larger viewports.
<ide>
<ide> When `fill`, the image will stretch both width and height to the dimensions of
<del>the parent element, usually paired with
<del>[object-fit](https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit).
<add>the parent element, usually paired with the [`objectFit`](#objectFit) property.
<ide>
<ide> Try it out:
<ide>
| 1
|
Java
|
Java
|
update webclient javadoc
|
6e05a5881e404b8a1ab7eac049d82d0faeb7eb10
|
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
<ide> import org.springframework.web.reactive.function.BodyInserter;
<ide> import org.springframework.web.util.UriBuilder;
<ide> import org.springframework.web.util.UriBuilderFactory;
<add>import org.springframework.web.reactive.function.BodyInserters;
<ide>
<ide> /**
<del> * The main entry point for initiating web requests on the client side.
<add> * A non-blocking, reactive client for performing HTTP requests with Reactive
<add> * Streams back pressure. Provides a higher level, common API over HTTP client
<add> * libraries. Reactor Netty is used by default but other clients may be plugged
<add> * in with a {@link ClientHttpConnector}.
<ide> *
<del> * <pre class="code">
<del> * // Initialize the client
<del> * WebClient client = WebClient.create("http://abc.com");
<add> * <p>Use one of the static factory methods {@link #create()} or
<add> * {@link #create(String)} or obtain a {@link WebClient#builder()} to create an
<add> * instance.
<ide> *
<del> * // Perform requests...
<del> * Mono<String> result = client.get()
<del> * .uri("/foo")
<del> * .exchange()
<del> * .then(response -> response.bodyToMono(String.class));
<del> * </pre>
<add> * <p>For examples with a response body see
<add> * {@link RequestHeadersSpec#retrieve() retrieve()} and
<add> * {@link RequestHeadersSpec#exchange() exchange()}.
<add> * For examples with a request body see
<add> * {@link RequestBodySpec#body(Publisher, Class) body(Publisher,Class)},
<add> * {@link RequestBodySpec#syncBody(Object) syncBody(Object)}, and
<add> * {@link RequestBodySpec#body(BodyInserter) body(BodyInserter)}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @author Arjen Poutsma
<ide> public interface WebClient {
<ide> // Static, factory methods
<ide>
<ide> /**
<del> * Create a new {@code WebClient} with no default, shared preferences across
<del> * requests such as base URI, default headers, and others.
<add> * Create a new {@code WebClient} with a Reactor Netty connector.
<ide> * @see #create(String)
<add> * @see #builder()
<ide> */
<ide> static WebClient create() {
<ide> return new DefaultWebClientBuilder().build();
<ide> }
<ide>
<ide> /**
<del> * Configure a base URI for requests performed through the client for
<del> * example to avoid repeating the same host, port, base path, or even
<del> * query parameters with every request.
<del> * <p>For example given this initialization:
<del> * <pre class="code">
<del> * WebClient client = WebClient.create("http://abc.com/v1");
<del> * </pre>
<del> * <p>The base URI is applied to exchanges with a URI template:
<del> * <pre class="code">
<del> * // GET http://abc.com/v1/accounts/43
<del> * Mono<Account> result = client.get()
<del> * .uri("/accounts/{id}", 43)
<del> * .exchange()
<del> * .then(response -> response.bodyToMono(Account.class));
<del> * </pre>
<del> * <p>The base URI is also applied to exchanges with a {@code UriBuilder}:
<del> * <pre class="code">
<del> * // GET http://abc.com/v1/accounts?q=12
<del> * Flux<Account> result = client.get()
<del> * .uri(builder -> builder.path("/accounts").queryParam("q", "12").build())
<del> * .exchange()
<del> * .then(response -> response.bodyToFlux(Account.class));
<del> * </pre>
<del> * <p>The base URI can be overridden with an absolute URI:
<del> * <pre class="code">
<del> * // GET http://xyz.com/path
<del> * Mono<Account> result = client.get()
<del> * .uri("http://xyz.com/path")
<del> * .exchange()
<del> * .then(response -> response.bodyToMono(Account.class));
<del> * </pre>
<del> * <p>The base URI can be partially overridden with a {@code UriBuilder}:
<del> * <pre class="code">
<del> * // GET http://abc.com/v2/accounts?q=12
<del> * Flux<Account> result = client.get()
<del> * .uri(builder -> builder.replacePath("/v2/accounts").queryParam("q", "12").build())
<del> * .exchange()
<del> * .then(response -> response.bodyToFlux(Account.class));
<del> * </pre>
<add> * A variant of {@link #create()} that accepts a default base URL. For more
<add> * details see {@link Builder#baseUrl(String) Builder.baseUrl(String)}.
<ide> * @param baseUrl the base URI for all requests
<ide> */
<ide> static WebClient create(String baseUrl) {
<ide> static WebClient.Builder builder() {
<ide>
<ide>
<ide> /**
<del> * A mutable builder for a {@link WebClient}.
<add> * A mutable builder for creating a {@link WebClient}.
<ide> */
<ide> interface Builder {
<ide>
<ide> /**
<del> * Configure a base URI as described in {@link WebClient#create(String)
<del> * WebClient.create(String)}.
<add> * Configure a base URL for requests performed through the client.
<add> *
<add> * <p>For example given base URL "http://abc.com/v1":
<add> * <p><pre class="code">
<add> * Mono<Account> result = client.get()
<add> * .uri("/accounts/{id}", 43)
<add> * .exchange()
<add> * .then(response -> response.bodyToMono(Account.class));
<add> *
<add> * // Result: http://abc.com/v1/accounts/43
<add> *
<add> * Flux<Account> result = client.get()
<add> * .uri(builder -> builder.path("/accounts").queryParam("q", "12").build())
<add> * .exchange()
<add> * .then(response -> response.bodyToFlux(Account.class));
<add> *
<add> * // Result: http://abc.com/v1/accounts?q=12
<add> * </pre>
<add> *
<add> * <p>The base URL can be overridden with an absolute URI:
<add> * <pre class="code">
<add> * Mono<Account> result = client.get()
<add> * .uri("http://xyz.com/path")
<add> * .exchange()
<add> * .then(response -> response.bodyToMono(Account.class));
<add> *
<add> * // Result: http://xyz.com/path
<add> * </pre>
<add> *
<add> * <p>Or partially overridden with a {@code UriBuilder}:
<add> * <pre class="code">
<add> * Flux<Account> result = client.get()
<add> * .uri(builder -> builder.replacePath("/v2/accounts").queryParam("q", "12").build())
<add> * .exchange()
<add> * .then(response -> response.bodyToFlux(Account.class));
<add> *
<add> * // Result: http://abc.com/v2/accounts?q=12
<add> * </pre>
<add> *
<ide> * @see #defaultUriVariables(Map)
<ide> * @see #uriBuilderFactory(UriBuilderFactory)
<ide> */
<ide> interface RequestBodySpec extends RequestHeadersSpec<RequestBodySpec> {
<ide> RequestBodySpec contentType(MediaType contentType);
<ide>
<ide> /**
<del> * Set the body of the request to the given {@code BodyInserter}.
<del> * @param inserter the {@code BodyInserter} that writes to the request
<add> * Set the body of the request using the given body inserter.
<add> * {@link BodyInserters} provides access to built-in implementations of
<add> * {@link BodyInserter}.
<add> * @param inserter the body inserter to use for the request body
<ide> * @return this builder
<add> * @see org.springframework.web.reactive.function.BodyInserters
<ide> */
<ide> RequestHeadersSpec<?> body(BodyInserter<?, ? super ClientHttpRequest> inserter);
<ide>
<ide> /**
<del> * Set the body of the request to the given asynchronous {@code Publisher}.
<del> * <p>This method is a convenient shortcut for {@link #body(BodyInserter)} with a
<del> * {@linkplain org.springframework.web.reactive.function.BodyInserters#fromPublisher}
<del> * Publisher body inserter}.
<add> * A shortcut for {@link #body(BodyInserter)} with a
<add> * {@linkplain BodyInserters#fromPublisher Publisher inserter}.
<add> * For example:
<add> * <p><pre>
<add> * Mono<Person> personMono = ... ;
<add> *
<add> * Mono<Void> result = client.post()
<add> * .uri("/persons/{id}", id)
<add> * .contentType(MediaType.APPLICATION_JSON)
<add> * .body(personMono, Person.class)
<add> * .retrieve()
<add> * .bodyToMono(Void.class);
<add> * </pre>
<ide> * @param publisher the {@code Publisher} to write to the request
<del> * @param typeReference the type reference of elements contained in the publisher
<add> * @param elementClass the class of elements contained in the publisher
<ide> * @param <T> the type of the elements contained in the publisher
<ide> * @param <P> the type of the {@code Publisher}
<ide> * @return this builder
<ide> */
<del> <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, ParameterizedTypeReference<T> typeReference);
<add> <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, Class<T> elementClass);
<ide>
<ide> /**
<del> * Set the body of the request to the given asynchronous {@code Publisher}.
<del> * <p>This method is a convenient shortcut for {@link #body(BodyInserter)} with a
<del> * {@linkplain org.springframework.web.reactive.function.BodyInserters#fromPublisher}
<del> * Publisher body inserter}.
<add> * A variant of {@link #body(Publisher, Class)} that allows providing
<add> * element type information that includes generics via a
<add> * {@link ParameterizedTypeReference}.
<ide> * @param publisher the {@code Publisher} to write to the request
<del> * @param elementClass the class of elements contained in the publisher
<add> * @param typeReference the type reference of elements contained in the publisher
<ide> * @param <T> the type of the elements contained in the publisher
<ide> * @param <P> the type of the {@code Publisher}
<ide> * @return this builder
<ide> */
<del> <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher, Class<T> elementClass);
<add> <T, P extends Publisher<T>> RequestHeadersSpec<?> body(P publisher,
<add> ParameterizedTypeReference<T> typeReference);
<ide>
<ide> /**
<del> * Set the body of the request to the given synchronous {@code Object}.
<del> * <p>This method is a convenient shortcut for:
<del> * <pre class="code">
<del> * .body(BodyInserters.fromObject(object))
<add> * A shortcut for {@link #body(BodyInserter)} with an
<add> * {@linkplain BodyInserters#fromObject Object inserter}.
<add> * For example:
<add> * <p><pre class="code">
<add> * Person person = ... ;
<add> *
<add> * Mono<Void> result = client.post()
<add> * .uri("/persons/{id}", id)
<add> * .contentType(MediaType.APPLICATION_JSON)
<add> * .syncBody(person)
<add> * .retrieve()
<add> * .bodyToMono(Void.class);
<ide> * </pre>
<del> * <p>The body can be a
<del> * {@link org.springframework.util.MultiValueMap MultiValueMap} to create
<del> * a multipart request. The values in the {@code MultiValueMap} can be
<del> * any Object representing the body of the part, or an
<del> * {@link org.springframework.http.HttpEntity HttpEntity} representing a
<del> * part with body and headers. The {@code MultiValueMap} can be built
<del> * conveniently using
<add> * <p>For multipart requests, provide a
<add> * {@link org.springframework.util.MultiValueMap MultiValueMap}. The
<add> * values in the {@code MultiValueMap} can be any Object representing
<add> * the body of the part, or an
<add> * {@link org.springframework.http.HttpEntity HttpEntity} representing
<add> * a part with body and headers. The {@code MultiValueMap} can be built
<add> * with {@link org.springframework.http.client.MultipartBodyBuilder
<add> * MultipartBodyBuilder}.
<ide> * @param body the {@code Object} to write to the request
<ide> * @return this builder
<ide> */
| 1
|
Ruby
|
Ruby
|
fix isolated test failure
|
8efcf9bf82d3c2f03e6cc88774f2e02ce9ec1b2e
|
<ide><path>activerecord/test/cases/associations/has_one_through_disable_joins_associations_test.rb
<ide>
<ide> require "cases/helper"
<ide> require "models/member"
<add>require "models/member_detail"
<ide> require "models/organization"
<ide>
<ide> class HasOneThroughDisableJoinsAssociationsTest < ActiveRecord::TestCase
| 1
|
Mixed
|
Ruby
|
pass options accessor to cache#fetch block
|
b84b04b33fff38baf3602cba4aa2924876f8b307
|
<ide><path>activesupport/CHANGELOG.md
<add>* `ActiveSupport::Cache:Store#fetch` now passes an options accessor to the block.
<add>
<add> It makes possible to override cache options:
<add>
<add> Rails.cache.fetch("3rd-party-token") do |name, options|
<add> token = fetch_token_from_remote
<add> # set cache's TTL to match token's TTL
<add> options.expires_in = token.expires_in
<add> token
<add> end
<add>
<add> *Andrii Gladkyi*, *Jean Boussier*
<add>
<ide> * `default` option of `thread_mattr_accessor` now applies through inheritance and
<ide> also across new threads.
<ide>
<ide><path>activesupport/lib/active_support/cache.rb
<ide> def mute
<ide> # val_1 # => "new value 1"
<ide> # val_2 # => "original value"
<ide> #
<add> # ==== Dynamic Options
<add> #
<add> # In some cases it may be necessary to to dynamically compute options based
<add> # on the cached value. For this purpose, a ActiveSupport::Cache::WriteOptions
<add> # instance is passed as a second argument to the block
<add> #
<add> # cache.fetch("authentication-token:#{user.id}") do |key, options|
<add> # token = authenticate_to_service
<add> # options.expires_at = token.expires_at
<add> # token
<add> # end
<add> #
<add> # Only some options can be set dynamically:
<add> #
<add> # - +:expires_in+
<add> # - +:expires_at+
<add> # - +:version+
<add> #
<ide> def fetch(name, options = nil, &block)
<ide> if block_given?
<ide> options = merged_options(options)
<ide> def get_entry_value(entry, name, options)
<ide>
<ide> def save_block_result_to_cache(name, options)
<ide> result = instrument(:generate, name, options) do
<del> yield(name)
<add> yield(name, WriteOptions.new(options))
<ide> end
<ide>
<ide> write(name, result, options) unless result.nil? && options[:skip_nil]
<ide> result
<ide> end
<ide> end
<ide>
<add> class WriteOptions
<add> def initialize(options) # :nodoc:
<add> @options = options
<add> end
<add>
<add> def version
<add> @options[:version]
<add> end
<add>
<add> def version=(version)
<add> @options[:version] = version
<add> end
<add>
<add> def expires_in
<add> @options[:expires_in]
<add> end
<add>
<add> def expires_in=(expires_in)
<add> @options.delete(:expires_at)
<add> @options[:expires_in] = expires_in
<add> end
<add>
<add> def expires_at
<add> @options[:expires_at]
<add> end
<add>
<add> def expires_at=(expires_at)
<add> @options.delete(:expires_in)
<add> @options[:expires_at] = expires_at
<add> end
<add> end
<add>
<ide> module NullCoder # :nodoc:
<ide> extend self
<ide>
<ide><path>activesupport/test/cache/behaviors/cache_store_behavior.rb
<ide> def test_fetch_with_cache_miss_passes_key_to_block
<ide> assert_not cache_miss
<ide> end
<ide>
<add> def test_fetch_with_dynamic_options
<add> key = SecureRandom.uuid
<add> expiry = 10.minutes.from_now
<add> expected_options = @cache.options.dup
<add> expected_options.delete(:expires_in)
<add> expected_options.merge!(
<add> expires_at: expiry,
<add> version: "v42",
<add> )
<add>
<add> assert_called_with(@cache, :write, [key, "bar", expected_options]) do
<add> @cache.fetch(key) do |key, options|
<add> assert_equal @cache.options[:expires_in], options.expires_in
<add> assert_nil options.expires_at
<add> assert_nil options.version
<add>
<add> options.expires_at = expiry
<add> options.version = "v42"
<add>
<add> assert_nil options.expires_in
<add> assert_equal expiry, options.expires_at
<add> assert_equal "v42", options.version
<add>
<add> "bar"
<add> end
<add> end
<add> end
<add>
<ide> def test_fetch_with_forced_cache_miss
<ide> key = SecureRandom.uuid
<ide> @cache.write(key, "bar")
| 3
|
Python
|
Python
|
enable pytorch 1.13
|
9643ecf8ca15b088784512e3329b9a7d6a02931d
|
<ide><path>.circleci/create_circleci_config.py
<ide> COMMON_ENV_VARIABLES = {"OMP_NUM_THREADS": 1, "TRANSFORMERS_IS_CI": True, "PYTEST_TIMEOUT": 120}
<ide> COMMON_PYTEST_OPTIONS = {"max-worker-restart": 0, "dist": "loadfile", "s": None}
<ide> DEFAULT_DOCKER_IMAGE = [{"image": "cimg/python:3.7.12"}]
<del>TORCH_SCATTER_INSTALL = "pip install torch-scatter -f https://pytorch-geometric.com/whl/torch-1.12.0+cpu.html"
<ide>
<ide>
<ide> @dataclass
<ide> def job_name(self):
<ide> "git lfs install",
<ide> "pip install --upgrade pip",
<ide> "pip install .[sklearn,tf-cpu,torch,testing,sentencepiece,torch-speech,vision]",
<del> TORCH_SCATTER_INSTALL,
<ide> "pip install tensorflow_probability",
<ide> "pip install git+https://github.com/huggingface/accelerate",
<ide> ],
<ide> def job_name(self):
<ide> "sudo apt-get -y update && sudo apt-get install -y libsndfile1-dev espeak-ng",
<ide> "pip install --upgrade pip",
<ide> "pip install .[sklearn,flax,torch,testing,sentencepiece,torch-speech,vision]",
<del> TORCH_SCATTER_INSTALL,
<ide> "pip install git+https://github.com/huggingface/accelerate",
<ide> ],
<ide> marker="is_pt_flax_cross_test",
<ide> def job_name(self):
<ide> "sudo apt-get -y update && sudo apt-get install -y libsndfile1-dev espeak-ng time",
<ide> "pip install --upgrade pip",
<ide> "pip install .[sklearn,torch,testing,sentencepiece,torch-speech,vision,timm]",
<del> TORCH_SCATTER_INSTALL,
<ide> "pip install git+https://github.com/huggingface/accelerate",
<ide> ],
<ide> pytest_num_workers=3,
<ide> def job_name(self):
<ide> "sudo apt-get -y update && sudo apt-get install -y libsndfile1-dev espeak-ng",
<ide> "pip install --upgrade pip",
<ide> "pip install .[sklearn,torch,testing,sentencepiece,torch-speech,vision,timm]",
<del> TORCH_SCATTER_INSTALL,
<ide> ],
<ide> pytest_options={"rA": None},
<ide> tests_to_run="tests/pipelines/"
<ide> def job_name(self):
<ide> "repo_utils",
<ide> install_steps=[
<ide> "pip install --upgrade pip",
<del> "pip install .[all,quality,testing]",
<add> "pip install .[quality,testing]",
<ide> ],
<ide> parallelism=None,
<ide> pytest_num_workers=1,
<ide><path>setup.py
<ide> "timeout-decorator",
<ide> "timm",
<ide> "tokenizers>=0.11.1,!=0.11.3,<0.14",
<del> "torch>=1.7,!=1.12.0,<1.13.0",
<add> "torch>=1.7,!=1.12.0",
<ide> "torchaudio",
<ide> "pyctcdecode>=0.4.0",
<ide> "tqdm>=4.27",
<ide><path>src/transformers/dependency_versions_table.py
<ide> "timeout-decorator": "timeout-decorator",
<ide> "timm": "timm",
<ide> "tokenizers": "tokenizers>=0.11.1,!=0.11.3,<0.14",
<del> "torch": "torch>=1.7,!=1.12.0,<1.13.0",
<add> "torch": "torch>=1.7,!=1.12.0",
<ide> "torchaudio": "torchaudio",
<ide> "pyctcdecode": "pyctcdecode>=0.4.0",
<ide> "tqdm": "tqdm>=4.27",
<ide><path>tests/models/bart/test_modeling_bart.py
<ide> class BartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
<ide> )
<ide> all_generative_model_classes = (BartForConditionalGeneration,) if is_torch_available() else ()
<ide> is_encoder_decoder = True
<del> fx_compatible = True
<add> fx_compatible = False # Fix me Michael
<ide> test_pruning = False
<ide>
<ide> def setUp(self):
<ide><path>tests/models/mbart/test_modeling_mbart.py
<ide> class MBartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase)
<ide> )
<ide> all_generative_model_classes = (MBartForConditionalGeneration,) if is_torch_available() else ()
<ide> is_encoder_decoder = True
<del> fx_compatible = True
<add> fx_compatible = False # Fix me Michael
<ide> test_pruning = False
<ide> test_missing_keys = False
<ide>
<ide><path>tests/models/plbart/test_modeling_plbart.py
<ide> class PLBartModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase
<ide> )
<ide> all_generative_model_classes = (PLBartForConditionalGeneration,) if is_torch_available() else ()
<ide> is_encoder_decoder = True
<del> fx_compatible = True
<add> fx_compatible = False # Fix me Michael
<ide> test_pruning = False
<ide> test_missing_keys = False
<ide>
| 6
|
Text
|
Text
|
add example commands for creating reproductions
|
1dd34620fd29d957fba42284662dedf98a110dcc
|
<ide><path>examples/reproduction-template/README.md
<ide> These are the steps you should follow when creating a bug report:
<ide> - If you think the issue is not in Next.js, the best place to ask for help is our [Discord community](https://nextjs.org/discord) or [GitHub discussions](https://github.com/vercel/next.js/discussions). Our community is welcoming and can often answer a project-related question faster than the Next.js core team.
<ide> - Make the reproduction as minimal as possible. Try to exclude any code that does not help reproducing the issue. E.g. if you experience problems with Routing, including ESLint configurations or API routes aren't necessary. The less lines of code is to read through, the easier it is for the Next.js team to investigate. It may also help catching bugs in your codebase before publishing an issue.
<ide>
<add>## How to use this template
<add>
<add>Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
<add>
<add>```bash
<add>npx create-next-app --example reproduction-template reproduction-app
<add>```
<add>
<add>```bash
<add>yarn create next-app --example reproduction-template reproduction-app
<add>```
<add>
<add>```bash
<add>pnpm create next-app --example reproduction-template reproduction-app
<add>```
<add>
<ide> ## Learn More
<ide>
<ide> To learn more about Next.js, take a look at the following resources:
| 1
|
Javascript
|
Javascript
|
remove private polling mechanism
|
9b35dfb658411ff12ded73be44e52072e43e0c1c
|
<ide><path>src/ng/browser.js
<ide> function Browser(window, document, $log, $sniffer) {
<ide> * @param {function()} callback Function that will be called when no outstanding request
<ide> */
<ide> self.notifyWhenNoOutstandingRequests = function(callback) {
<del> // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
<del> // at some deterministic time in respect to the test runner's actions. Leaving things up to the
<del> // regular poller would result in flaky tests.
<del> forEach(pollFns, function(pollFn) { pollFn(); });
<del>
<ide> if (outstandingRequestCount === 0) {
<ide> callback();
<ide> } else {
<ide> outstandingRequestCallbacks.push(callback);
<ide> }
<ide> };
<ide>
<del> //////////////////////////////////////////////////////////////
<del> // Poll Watcher API
<del> //////////////////////////////////////////////////////////////
<del> var pollFns = [],
<del> pollTimeout;
<del>
<del> /**
<del> * @name $browser#addPollFn
<del> *
<del> * @param {function()} fn Poll function to add
<del> *
<del> * @description
<del> * Adds a function to the list of functions that poller periodically executes,
<del> * and starts polling if not started yet.
<del> *
<del> * @returns {function()} the added function
<del> */
<del> self.addPollFn = function(fn) {
<del> if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
<del> pollFns.push(fn);
<del> return fn;
<del> };
<del>
<del> /**
<del> * @param {number} interval How often should browser call poll functions (ms)
<del> * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
<del> *
<del> * @description
<del> * Configures the poller to run in the specified intervals, using the specified
<del> * setTimeout fn and kicks it off.
<del> */
<del> function startPoller(interval, setTimeout) {
<del> (function check() {
<del> forEach(pollFns, function(pollFn) { pollFn(); });
<del> pollTimeout = setTimeout(check, interval);
<del> })();
<del> }
<del>
<ide> //////////////////////////////////////////////////////////////
<ide> // URL API
<ide> //////////////////////////////////////////////////////////////
<ide><path>src/ngMock/angular-mocks.js
<ide> angular.mock.$Browser.prototype = {
<ide> });
<ide> },
<ide>
<del> addPollFn: function(pollFn) {
<del> this.pollFns.push(pollFn);
<del> return pollFn;
<del> },
<del>
<ide> url: function(url, replace, state) {
<ide> if (angular.isUndefined(state)) {
<ide> state = null;
<ide> if (window.jasmine || window.mocha) {
<ide>
<ide> if (injector) {
<ide> injector.get('$rootElement').off();
<del> injector.get('$browser').pollFns.length = 0;
<ide> }
<ide>
<ide> // clean up jquery's fragment cache
<ide><path>test/ng/browserSpecs.js
<ide> describe('browser', function() {
<ide> });
<ide>
<ide>
<del> describe('poller', function() {
<del>
<del> it('should call functions in pollFns in regular intervals', function() {
<del> var log = '';
<del> browser.addPollFn(function() {log+='a';});
<del> browser.addPollFn(function() {log+='b';});
<del> expect(log).toEqual('');
<del> fakeWindow.setTimeout.flush();
<del> expect(log).toEqual('ab');
<del> fakeWindow.setTimeout.flush();
<del> expect(log).toEqual('abab');
<del> });
<del>
<del> it('should startPoller', function() {
<del> expect(fakeWindow.timeouts.length).toEqual(0);
<del>
<del> browser.addPollFn(function() {});
<del> expect(fakeWindow.timeouts.length).toEqual(1);
<del>
<del> //should remain 1 as it is the check fn
<del> browser.addPollFn(function() {});
<del> expect(fakeWindow.timeouts.length).toEqual(1);
<del> });
<del>
<del> it('should return fn that was passed into addPollFn', function() {
<del> var fn = function() { return 1; };
<del> var returnedFn = browser.addPollFn(fn);
<del> expect(returnedFn).toBe(fn);
<del> });
<del> });
<del>
<ide> describe('url', function() {
<ide> var pushState, replaceState, locationReplace;
<ide>
<ide> describe('browser', function() {
<ide> fakeWindow.location.href = newUrl;
<ide> });
<ide> $provide.value('$browser', browser);
<del> browser.pollFns = [];
<ide>
<ide> sniffer.history = options.history;
<ide> $provide.value('$sniffer', sniffer);
<ide> describe('browser', function() {
<ide>
<ide> beforeEach(module(function($provide, $locationProvider) {
<ide> $provide.value('$browser', browser);
<del> browser.pollFns = [];
<ide> }));
<ide>
<ide> it('should not interfere with legacy browser url replace behavior', function() {
<ide><path>test/ng/locationSpec.js
<ide> describe('$location', function() {
<ide>
<ide> /* global Browser: false */
<ide> var b = new Browser($window, $document, fakeLog, sniffer);
<del> b.pollFns = [];
<ide> return b;
<ide> };
<ide> });
| 4
|
Text
|
Text
|
fix documentation errors
|
383a1696c098c907fd4507056b7eef15cadf4902
|
<ide><path>doc/api/http2.md
<ide> req.end('Jane');
<ide>
<ide> ## Compatibility API
<ide>
<del>The Compatibility API has the goal of providing a similar developer experience of
<del>HTTP/1 when using HTTP/2, making it possible to develop applications
<del>that supports both [HTTP/1](HTTP/1) and HTTP/2. This API targets only the **public
<del>API** of the [HTTP/1](HTTP/1), however many modules uses internal
<add>The Compatibility API has the goal of providing a similar developer experience
<add>of HTTP/1 when using HTTP/2, making it possible to develop applications
<add>that supports both [HTTP/1](HTTP/1) and HTTP/2. This API targets only the
<add>**public API** of the [HTTP/1](HTTP/1), however many modules uses internal
<ide> methods or state, and those _are not supported_ as it is a completely
<ide> different implementation.
<ide>
<ide> const server = http2.createServer((req, res) => {
<ide> });
<ide> ```
<ide>
<del>In order to create a mixed [HTTPs](https) and HTTP/2 server, refer to the
<add>In order to create a mixed [HTTPS](https) and HTTP/2 server, refer to the
<ide> [ALPN negotiation](alpn-negotiation) section.
<ide> Upgrading from non-tls HTTP/1 servers is not supported.
<ide>
<ide> the status message for HTTP codes is ignored.
<ide>
<ide> ### ALPN negotiation
<ide>
<del>ALPN negotiation allows to support both [HTTPs](https) and HTTP/2 over
<del>the same socket. the `req` and `res` object could be either HTTP/1 or
<add>ALPN negotiation allows to support both [HTTPS](https) and HTTP/2 over
<add>the same socket. The `req` and `res` objects can be either HTTP/1 or
<ide> HTTP/2, and an application **must** restrict itself to the public API of
<ide> [HTTP/1](), and detect if it is possible to use the more advanced
<ide> features of HTTP/2.
<ide> const server = createSecureServer(
<ide> ).listen(4443);
<ide>
<ide> function onRequest(req, res) {
<del> // detects if it is a HTTPs request or HTTP/2
<add> // detects if it is a HTTPS request or HTTP/2
<ide> const { socket: { alpnProtocol } } = request.httpVersion === '2.0' ?
<ide> request.stream.session : request;
<ide> response.writeHead(200, { 'content-type': 'application/json' });
<ide> function onRequest(req, res) {
<ide> }
<ide> ```
<ide>
<del>The `'request'` event works identically on both [HTTPs](https) and
<add>The `'request'` event works identically on both [HTTPS](https) and
<ide> HTTP/2.
<ide>
<ide> ### Class: http2.Http2ServerRequest
<ide> added: REPLACEME
<ide> -->
<ide>
<ide> A `Http2ServerRequest` object is created by [`http2.Server`][] or
<del>[`http2.SecureServer`][] and passed as the first argument to the [`'request'`][] event. It may be used to access a request status,
<del>headers and data.
<add>[`http2.SecureServer`][] and passed as the first argument to the
<add>[`'request'`][] event. It may be used to access a request status, headers and
<add>data.
<ide>
<ide> It implements the [Readable Stream][] interface, as well as the
<ide> following additional events, methods, and properties.
<ide> added: REPLACEME
<ide>
<ide> * `error` {Error}
<ide>
<del>Calls `destroy()` on the [Http2Stream]() that received the `ServerRequest`. If `error`
<del>is provided, an `'error'` event is emitted and `error` is passed as an argument
<del>to any listeners on the event.
<add>Calls `destroy()` on the [Http2Stream]() that received the `ServerRequest`. If
<add>`error` is provided, an `'error'` event is emitted and `error` is passed as an
<add>argument to any listeners on the event.
<ide>
<ide> It does nothing if the stream was already destroyed.
<ide>
<ide> added: REPLACEME
<ide> * `name` {string}
<ide> * Returns: {string}
<ide>
<del>Reads out a header that's already been queued but not sent to the client.
<add>Reads out a header that has already been queued but not sent to the client.
<ide> Note that the name is case insensitive.
<ide>
<ide> Example:
<ide> added: REPLACEME
<ide>
<ide> * `name` {string}
<ide>
<del>Removes a header that's queued for implicit sending.
<add>Removes a header that has been queued for implicit sending.
<ide>
<ide> Example:
<ide>
<ide> response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
<ide> Attempting to set a header field name or value that contains invalid characters
<ide> will result in a [`TypeError`][] being thrown.
<ide>
<del>When headers have been set with [`response.setHeader()`][], they will be merged with
<del>any headers passed to [`response.writeHead()`][], with the headers passed to
<del>[`response.writeHead()`][] given precedence.
<add>When headers have been set with [`response.setHeader()`][], they will be merged
<add>with any headers passed to [`response.writeHead()`][], with the headers passed
<add>to [`response.writeHead()`][] given precedence.
<ide>
<ide> ```js
<ide> // returns content-type = text/plain
<ide> provided, then it is added as a listener on the `'timeout'` event on
<ide> the response object.
<ide>
<ide> If no `'timeout'` listener is added to the request, the response, or
<del>the server, then [`Http2Stream`]()s are destroyed when they time out. If a handler is
<del>assigned to the request, the response, or the server's `'timeout'` events,
<del>timed out sockets must be handled explicitly.
<add>the server, then [`Http2Stream`]()s are destroyed when they time out. If a
<add>handler is assigned to the request, the response, or the server's `'timeout'`
<add>events, timed out sockets must be handled explicitly.
<ide>
<ide> Returns `response`.
<ide>
<ide> buffer. Returns `false` if all or part of the data was queued in user memory.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>Throws an error as the `'continue'` flow is not current implemented. Added for parity with [HTTP/1]().
<add>Throws an error as the `'continue'` flow is not current implemented. Added for
<add>parity with [HTTP/1]().
<ide>
<ide> ### response.writeHead(statusCode[, statusMessage][, headers])
<ide> <!-- YAML
<ide> added: REPLACEME
<ide>
<ide> Sends a response header to the request. The status code is a 3-digit HTTP
<ide> status code, like `404`. The last argument, `headers`, are the response headers.
<del>For compatibility with [HTTP/1](), one can give a human-readable `statusMessage` as the second argument, which will be silenty ignored and emit a warning.
<add>
<add>For compatibility with [HTTP/1](), a human-readable `statusMessage` may be
<add>passed as the second argument. However, because the `statusMessage` has no
<add>meaning within HTTP/2, the argument will have no effect and a process warning
<add>will be emitted.
<ide>
<ide> Example:
<ide>
<ide> response.writeHead(200, {
<ide> 'Content-Type': 'text/plain' });
<ide> ```
<ide>
<del>This method must only be called once on a message and it must
<del>be called before [`response.end()`][] is called.
<add>Note that Content-Length is given in bytes not characters. The
<add>`Buffer.byteLength()` API may be used to determine the number of bytes in a
<add>given encoding. On outbound messages, Node.js does not check if Content-Length
<add>and the length of the body being transmitted are equal or not. However, when
<add>receiving messages, Node.js will automatically reject messages when the
<add>Content-Length does not match the actual payload size.
<add>
<add>This method may be called at most one time on a message before
<add>[`response.end()`][] is called.
<ide>
<ide> If [`response.write()`][] or [`response.end()`][] are called before calling
<ide> this, the implicit/mutable headers will be calculated and call this function.
<ide>
<del>When headers have been set with [`response.setHeader()`][], they will be merged with
<del>any headers passed to [`response.writeHead()`][], with the headers passed to
<del>[`response.writeHead()`][] given precedence.
<add>When headers have been set with [`response.setHeader()`][], they will be merged
<add>with any headers passed to [`response.writeHead()`][], with the headers passed
<add>to [`response.writeHead()`][] given precedence.
<ide>
<ide> ```js
<ide> // returns content-type = text/plain
<ide> const server = http2.createServer((req, res) => {
<ide> });
<ide> ```
<ide>
<del>Note that Content-Length is given in bytes not characters. The above example
<del>works because the string `'hello world'` contains only single byte characters.
<del>If the body contains higher coded characters then `Buffer.byteLength()`
<del>should be used to determine the number of bytes in a given encoding.
<del>And Node.js does not check whether Content-Length and the length of the body
<del>which has been transmitted are equal or not.
<del>
<ide> Attempting to set a header field name or value that contains invalid characters
<ide> will result in a [`TypeError`][] being thrown.
<ide>
| 1
|
Go
|
Go
|
improve timestamp formatting
|
04c94a013ccba1690933156830efdc314de67ef8
|
<ide><path>api/client/task/print.go
<ide> import (
<ide> )
<ide>
<ide> const (
<del> psTaskItemFmt = "%s\t%s\t%s\t%s\t%s %s\t%s\t%s\n"
<add> psTaskItemFmt = "%s\t%s\t%s\t%s\t%s %s ago\t%s\t%s\n"
<ide> )
<ide>
<ide> type tasksBySlot []swarm.Task
<ide> func Print(dockerCli *client.DockerCli, ctx context.Context, tasks []swarm.Task,
<ide> serviceValue,
<ide> task.Spec.ContainerSpec.Image,
<ide> client.PrettyPrint(task.Status.State),
<del> units.HumanDuration(time.Since(task.Status.Timestamp)),
<add> strings.ToLower(units.HumanDuration(time.Since(task.Status.Timestamp))),
<ide> client.PrettyPrint(task.DesiredState),
<ide> nodeValue,
<ide> )
| 1
|
Go
|
Go
|
pull only latest when no tag specified
|
b8e338144e90a6bb76110ab04cc216966640a3f4
|
<ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdRun(args ...string) error {
<ide>
<ide> v := url.Values{}
<ide> repos, tag := utils.ParseRepositoryTag(config.Image)
<add> // pull only the image tagged 'latest' if no tag was specified
<add> if tag == "" {
<add> tag = "latest"
<add> }
<ide> v.Set("fromImage", repos)
<ide> v.Set("tag", tag)
<ide>
| 1
|
Go
|
Go
|
fix uneccessary calls to `volume.unmount()`
|
9a2d0bc3adc0c21c82cd1974be45ea0449f9f224
|
<ide><path>container/container.go
<ide> func (container *Container) AddMountPointWithVolume(destination string, vol volu
<ide> }
<ide> }
<ide>
<add>// UnmountVolumes unmounts all volumes
<add>func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error {
<add> var errors []string
<add> for _, volumeMount := range container.MountPoints {
<add> // Check if the mounpoint has an ID, this is currently the best way to tell if it's actually mounted
<add> // TODO(cpuguyh83): there should be a better way to handle this
<add> if volumeMount.Volume != nil && volumeMount.ID != "" {
<add> if err := volumeMount.Volume.Unmount(volumeMount.ID); err != nil {
<add> errors = append(errors, err.Error())
<add> continue
<add> }
<add> volumeMount.ID = ""
<add>
<add> attributes := map[string]string{
<add> "driver": volumeMount.Volume.DriverName(),
<add> "container": container.ID,
<add> }
<add> volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
<add> }
<add> }
<add> if len(errors) > 0 {
<add> return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; "))
<add> }
<add> return nil
<add>}
<add>
<ide> // IsDestinationMounted checks whether a path is mounted on the container or not.
<ide> func (container *Container) IsDestinationMounted(destination string) bool {
<ide> return container.MountPoints[destination] != nil
<ide><path>container/container_unix.go
<ide> func (container *Container) BuildHostnameFile() error {
<ide> return ioutil.WriteFile(container.HostnamePath, []byte(container.Config.Hostname+"\n"), 0644)
<ide> }
<ide>
<del>// appendNetworkMounts appends any network mounts to the array of mount points passed in
<del>func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
<del> for _, mnt := range container.NetworkMounts() {
<del> dest, err := container.GetResourcePath(mnt.Destination)
<del> if err != nil {
<del> return nil, err
<del> }
<del> volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest})
<del> }
<del> return volumeMounts, nil
<del>}
<del>
<ide> // NetworkMounts returns the list of network mounts.
<ide> func (container *Container) NetworkMounts() []Mount {
<ide> var mounts []Mount
<ide> func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfi
<ide> return nil
<ide> }
<ide>
<del>// UnmountVolumes unmounts all volumes
<del>func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
<del> var (
<del> volumeMounts []volume.MountPoint
<del> err error
<del> )
<add>// DetachAndUnmount uses a detached mount on all mount destinations, then
<add>// unmounts each volume normally.
<add>// This is used from daemon/archive for `docker cp`
<add>func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
<add> networkMounts := container.NetworkMounts()
<add> mountPaths := make([]string, 0, len(container.MountPoints)+len(networkMounts))
<ide>
<ide> for _, mntPoint := range container.MountPoints {
<ide> dest, err := container.GetResourcePath(mntPoint.Destination)
<ide> if err != nil {
<del> return err
<add> logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, mntPoint.Destination, err)
<add> continue
<ide> }
<del>
<del> volumeMounts = append(volumeMounts, volume.MountPoint{Destination: dest, Volume: mntPoint.Volume, ID: mntPoint.ID})
<del> }
<del>
<del> // Append any network mounts to the list (this is a no-op on Windows)
<del> if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
<del> return err
<add> mountPaths = append(mountPaths, dest)
<ide> }
<ide>
<del> for _, volumeMount := range volumeMounts {
<del> if forceSyscall {
<del> if err := detachMounted(volumeMount.Destination); err != nil {
<del> logrus.Warnf("%s unmountVolumes: Failed to do lazy umount %v", container.ID, err)
<del> }
<add> for _, m := range networkMounts {
<add> dest, err := container.GetResourcePath(m.Destination)
<add> if err != nil {
<add> logrus.Warnf("Failed to get volume destination path for container '%s' at '%s' while lazily unmounting: %v", container.ID, m.Destination, err)
<add> continue
<ide> }
<add> mountPaths = append(mountPaths, dest)
<add> }
<ide>
<del> if volumeMount.Volume != nil {
<del> if err := volumeMount.Volume.Unmount(volumeMount.ID); err != nil {
<del> return err
<del> }
<del> volumeMount.ID = ""
<del>
<del> attributes := map[string]string{
<del> "driver": volumeMount.Volume.DriverName(),
<del> "container": container.ID,
<del> }
<del> volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
<add> for _, mountPath := range mountPaths {
<add> if err := detachMounted(mountPath); err != nil {
<add> logrus.Warnf("%s unmountVolumes: Failed to do lazy umount fo volume '%s': %v", container.ID, mountPath, err)
<ide> }
<ide> }
<del>
<del> return nil
<add> return container.UnmountVolumes(volumeEventLog)
<ide> }
<ide>
<ide> // copyExistingContents copies from the source to the destination and
<ide><path>container/container_windows.go
<ide> import (
<ide>
<ide> containertypes "github.com/docker/docker/api/types/container"
<ide> "github.com/docker/docker/utils"
<del> "github.com/docker/docker/volume"
<ide> )
<ide>
<ide> // Container holds fields specific to the Windows implementation. See
<ide> func (container *Container) UnmountSecrets() error {
<ide> return nil
<ide> }
<ide>
<del>// UnmountVolumes explicitly unmounts volumes from the container.
<del>func (container *Container) UnmountVolumes(forceSyscall bool, volumeEventLog func(name, action string, attributes map[string]string)) error {
<del> var (
<del> volumeMounts []volume.MountPoint
<del> err error
<del> )
<del>
<del> for _, mntPoint := range container.MountPoints {
<del> // Do not attempt to get the mountpoint destination on the host as it
<del> // is not accessible on Windows in the case that a container is running.
<del> // (It's a special reparse point which doesn't have any contextual meaning).
<del> volumeMounts = append(volumeMounts, volume.MountPoint{Volume: mntPoint.Volume, ID: mntPoint.ID})
<del> }
<del>
<del> // atm, this is a no-op.
<del> if volumeMounts, err = appendNetworkMounts(container, volumeMounts); err != nil {
<del> return err
<del> }
<del>
<del> for _, volumeMount := range volumeMounts {
<del> if volumeMount.Volume != nil {
<del> if err := volumeMount.Volume.Unmount(volumeMount.ID); err != nil {
<del> return err
<del> }
<del> volumeMount.ID = ""
<del>
<del> attributes := map[string]string{
<del> "driver": volumeMount.Volume.DriverName(),
<del> "container": container.ID,
<del> }
<del> volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
<del> }
<del> }
<del>
<del> return nil
<add>// DetachAndUnmount unmounts all volumes.
<add>// On Windows it only delegates to `UnmountVolumes` since there is nothing to
<add>// force unmount.
<add>func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error {
<add> return container.UnmountVolumes(volumeEventLog)
<ide> }
<ide>
<ide> // TmpfsMounts returns the list of tmpfs mounts
<ide> func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfi
<ide> return nil
<ide> }
<ide>
<del>// appendNetworkMounts appends any network mounts to the array of mount points passed in.
<del>// Windows does not support network mounts (not to be confused with SMB network mounts), so
<del>// this is a no-op.
<del>func appendNetworkMounts(container *Container, volumeMounts []volume.MountPoint) ([]volume.MountPoint, error) {
<del> return volumeMounts, nil
<del>}
<del>
<ide> // cleanResourcePath cleans a resource path by removing C:\ syntax, and prepares
<ide> // to combine with a volume path
<ide> func cleanResourcePath(path string) string {
<ide><path>daemon/archive.go
<ide> func (daemon *Daemon) containerStatPath(container *container.Container, path str
<ide> defer daemon.Unmount(container)
<ide>
<ide> err = daemon.mountVolumes(container)
<del> defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
<add> defer container.DetachAndUnmount(daemon.LogVolumeEvent)
<ide> if err != nil {
<ide> return nil, err
<ide> }
<ide> func (daemon *Daemon) containerArchivePath(container *container.Container, path
<ide> defer func() {
<ide> if err != nil {
<ide> // unmount any volumes
<del> container.UnmountVolumes(true, daemon.LogVolumeEvent)
<add> container.DetachAndUnmount(daemon.LogVolumeEvent)
<ide> // unmount the container's rootfs
<ide> daemon.Unmount(container)
<ide> }
<ide> func (daemon *Daemon) containerArchivePath(container *container.Container, path
<ide>
<ide> content = ioutils.NewReadCloserWrapper(data, func() error {
<ide> err := data.Close()
<del> container.UnmountVolumes(true, daemon.LogVolumeEvent)
<add> container.DetachAndUnmount(daemon.LogVolumeEvent)
<ide> daemon.Unmount(container)
<ide> container.Unlock()
<ide> return err
<ide> func (daemon *Daemon) containerExtractToDir(container *container.Container, path
<ide> defer daemon.Unmount(container)
<ide>
<ide> err = daemon.mountVolumes(container)
<del> defer container.UnmountVolumes(true, daemon.LogVolumeEvent)
<add> defer container.DetachAndUnmount(daemon.LogVolumeEvent)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (daemon *Daemon) containerCopy(container *container.Container, resource str
<ide> defer func() {
<ide> if err != nil {
<ide> // unmount any volumes
<del> container.UnmountVolumes(true, daemon.LogVolumeEvent)
<add> container.DetachAndUnmount(daemon.LogVolumeEvent)
<ide> // unmount the container's rootfs
<ide> daemon.Unmount(container)
<ide> }
<ide> func (daemon *Daemon) containerCopy(container *container.Container, resource str
<ide>
<ide> reader := ioutils.NewReadCloserWrapper(archive, func() error {
<ide> err := archive.Close()
<del> container.UnmountVolumes(true, daemon.LogVolumeEvent)
<add> container.DetachAndUnmount(daemon.LogVolumeEvent)
<ide> daemon.Unmount(container)
<ide> container.Unlock()
<ide> return err
<ide><path>daemon/start.go
<ide> func (daemon *Daemon) Cleanup(container *container.Container) {
<ide> }
<ide>
<ide> if container.BaseFS != "" {
<del> if err := container.UnmountVolumes(false, daemon.LogVolumeEvent); err != nil {
<add> if err := container.UnmountVolumes(daemon.LogVolumeEvent); err != nil {
<ide> logrus.Warnf("%s cleanup: Failed to umount volumes: %v", container.ID, err)
<ide> }
<ide> }
<ide><path>integration-cli/docker_cli_external_volume_driver_unix_test.go
<ide> type vol struct {
<ide> Mountpoint string
<ide> Ninja bool // hack used to trigger a null volume return on `Get`
<ide> Status map[string]interface{}
<add> Options map[string]string
<ide> }
<ide>
<ide> func (p *volumePlugin) Close() {
<ide> func newVolumePlugin(c *check.C, name string) *volumePlugin {
<ide> }
<ide> _, isNinja := pr.Opts["ninja"]
<ide> status := map[string]interface{}{"Hello": "world"}
<del> s.vols[pr.Name] = vol{Name: pr.Name, Ninja: isNinja, Status: status}
<add> s.vols[pr.Name] = vol{Name: pr.Name, Ninja: isNinja, Status: status, Options: pr.Opts}
<ide> send(w, nil)
<ide> })
<ide>
<ide> func newVolumePlugin(c *check.C, name string) *volumePlugin {
<ide> return
<ide> }
<ide>
<add> if v, exists := s.vols[pr.Name]; exists {
<add> // Use this to simulate a mount failure
<add> if _, exists := v.Options["invalidOption"]; exists {
<add> send(w, fmt.Errorf("invalid argument"))
<add> return
<add> }
<add> }
<add>
<ide> p := hostVolumePath(pr.Name)
<ide> if err := os.MkdirAll(p, 0755); err != nil {
<ide> send(w, &pluginResp{Err: err.Error()})
<ide> func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverOutOfBandDelete(c *c
<ide> out, err = s.d.Cmd("volume", "create", "-d", "local", "--name", "test")
<ide> c.Assert(err, checker.IsNil, check.Commentf(out))
<ide> }
<add>
<add>func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnmountOnMountFail(c *check.C) {
<add> c.Assert(s.d.StartWithBusybox(), checker.IsNil)
<add> s.d.Cmd("volume", "create", "-d", "test-external-volume-driver", "--opt=invalidOption=1", "--name=testumount")
<add>
<add> out, _ := s.d.Cmd("run", "-v", "testumount:/foo", "busybox", "true")
<add> c.Assert(s.ec.unmounts, checker.Equals, 0, check.Commentf(out))
<add> out, _ = s.d.Cmd("run", "-w", "/foo", "-v", "testumount:/foo", "busybox", "true")
<add> c.Assert(s.ec.unmounts, checker.Equals, 0, check.Commentf(out))
<add>}
<ide><path>volume/volume.go
<ide> type DetailedVolume interface {
<ide> // specifies which volume is to be used and where inside a container it should
<ide> // be mounted.
<ide> type MountPoint struct {
<del> Source string // Container host directory
<del> Destination string // Inside the container
<del> RW bool // True if writable
<del> Name string // Name set by user
<del> Driver string // Volume driver to use
<del> Type mounttypes.Type `json:",omitempty"` // Type of mount to use, see `Type<foo>` definitions
<del> Volume Volume `json:"-"`
<add> // Source is the source path of the mount.
<add> // E.g. `mount --bind /foo /bar`, `/foo` is the `Source`.
<add> Source string
<add> // Destination is the path relative to the container root (`/`) to the mount point
<add> // It is where the `Source` is mounted to
<add> Destination string
<add> // RW is set to true when the mountpoint should be mounted as read-write
<add> RW bool
<add> // Name is the name reference to the underlying data defined by `Source`
<add> // e.g., the volume name
<add> Name string
<add> // Driver is the volume driver used to create the volume (if it is a volume)
<add> Driver string
<add> // Type of mount to use, see `Type<foo>` definitions in github.com/docker/docker/api/types/mount
<add> Type mounttypes.Type `json:",omitempty"`
<add> // Volume is the volume providing data to this mountpoint.
<add> // This is nil unless `Type` is set to `TypeVolume`
<add> Volume Volume `json:"-"`
<ide>
<add> // Mode is the comma separated list of options supplied by the user when creating
<add> // the bind/volume mount.
<ide> // Note Mode is not used on Windows
<ide> Mode string `json:"Relabel,omitempty"` // Originally field was `Relabel`"
<ide>
<add> // Propagation describes how the mounts are propagated from the host into the
<add> // mount point, and vice-versa.
<add> // See https://www.kernel.org/doc/Documentation/filesystems/sharedsubtree.txt
<ide> // Note Propagation is not used on Windows
<ide> Propagation mounttypes.Propagation `json:",omitempty"` // Mount propagation string
<ide>
<ide> type MountPoint struct {
<ide> CopyData bool `json:"-"`
<ide> // ID is the opaque ID used to pass to the volume driver.
<ide> // This should be set by calls to `Mount` and unset by calls to `Unmount`
<del> ID string `json:",omitempty"`
<add> ID string `json:",omitempty"`
<add>
<add> // Sepc is a copy of the API request that created this mount.
<ide> Spec mounttypes.Mount
<ide> }
<ide>
<ide> // Setup sets up a mount point by either mounting the volume if it is
<ide> // configured, or creating the source directory if supplied.
<ide> func (m *MountPoint) Setup(mountLabel string, rootUID, rootGID int) (string, error) {
<ide> if m.Volume != nil {
<del> if m.ID == "" {
<del> m.ID = stringid.GenerateNonCryptoID()
<add> id := m.ID
<add> if id == "" {
<add> id = stringid.GenerateNonCryptoID()
<add> }
<add> path, err := m.Volume.Mount(id)
<add> if err != nil {
<add> return "", errors.Wrapf(err, "error while mounting volume '%s'", m.Source)
<ide> }
<del> path, err := m.Volume.Mount(m.ID)
<del> return path, errors.Wrapf(err, "error while mounting volume '%s'", m.Source)
<add> m.ID = id
<add> return path, nil
<ide> }
<ide> if len(m.Source) == 0 {
<ide> return "", fmt.Errorf("Unable to setup mount point, neither source nor volume defined")
| 7
|
Python
|
Python
|
address another comment
|
a3efa3fed2ffa33a64259d0a8547851b72a5b20f
|
<ide><path>official/mnist/mnist.py
<ide> def __init__(self, data_format):
<ide> 64, 5, padding='same', data_format=data_format, activation=tf.nn.relu)
<ide> self.fc1 = tf.layers.Dense(1024, activation=tf.nn.relu)
<ide> self.fc2 = tf.layers.Dense(10)
<del> self.dropout = tf.layers.Dropout(0.5)
<add> self.dropout = tf.layers.Dropout(0.4)
<ide> self.max_pool2d = tf.layers.MaxPooling2D(
<ide> (2, 2), (2, 2), padding='same', data_format=data_format)
<ide>
| 1
|
Javascript
|
Javascript
|
fix svgloader strokes not rendering in firefox
|
898c14affc264d90801239c3b27a88bf8fd6f691
|
<ide><path>examples/jsm/loaders/SVGLoader.js
<ide> SVGLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
<ide>
<ide> function clamp( v ) {
<ide>
<del> return Math.max( 0, Math.min( 1, v ) );
<add> return Math.max( 0, Math.min( 1, parseFloat( v ) ) );
<ide>
<ide> }
<ide>
<ide> function positive( v ) {
<ide>
<del> return Math.max( 0, v );
<add> return Math.max( 0, parseFloat( v ) );
<ide>
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
add point at beginning of initializecore
|
d279b7c74dbd570da5a269e59542c72f3f689805
|
<ide><path>Libraries/Utilities/PerformanceLogger.js
<ide> const PerformanceLogger = {
<ide> infoLog(extras);
<ide> },
<ide>
<del> markPoint(key: string) {
<add> markPoint(key: string, timestamp?: number) {
<ide> if (points[key]) {
<ide> if (__DEV__) {
<ide> infoLog(
<ide> const PerformanceLogger = {
<ide> }
<ide> return;
<ide> }
<del> points[key] = performanceNow();
<add> points[key] = timestamp ?? performanceNow();
<ide> },
<ide>
<ide> getPoints() {
| 1
|
Text
|
Text
|
update the docs
|
b21d1476085851aa1be870d11d6217c9e87fdfbc
|
<ide><path>docs/02-Line-Chart.md
<ide> var data = {
<ide> label: "My First dataset",
<ide>
<ide> // Boolean - if true fill the area under the line
<del> fill: false,
<add> fill: false,
<add>
<add> // Tension - bezier curve tension of the line. Set to 0 to draw straight lines connecting points
<add> // Used to be called "tension" but was renamed for consistency. The old option name continues to work for compatibility.
<add> lineTension: 0.1,
<ide>
<ide> // String - the color to fill the area under the line with if fill is true
<del> backgroundColor: "rgba(220,220,220,0.2)",
<del>
<del> // The properties below allow an array to be specified to change the value of the item at the given index
<add> backgroundColor: "rgba(220,220,220,0.2)",
<ide>
<del> // String or array - Line color
<add> // String - Line color
<ide> borderColor: "rgba(220,220,220,1)",
<ide>
<ide> // String - cap style of the line. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineCap
<ide> var data = {
<ide> borderDashOffset: 0.0,
<ide>
<ide> // String - line join style. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
<del> borderJoinStyle: 'miter',
<add> borderJoinStyle: 'miter',
<add>
<add> // The properties below allow an array to be specified to change the value of the item at the given index
<ide>
<del> // String or array - Point stroke color
<add> // String or Array - Point stroke color
<ide> pointBorderColor: "rgba(220,220,220,1)",
<ide>
<del> // String or array - Point fill color
<add> // String or Array - Point fill color
<ide> pointBackgroundColor: "#fff",
<ide>
<del> // Number or array - Stroke width of point border
<add> // Number or Array - Stroke width of point border
<ide> pointBorderWidth: 1,
<ide>
<del> // Number or array - Radius of point when hovered
<add> // Number or Array - Radius of point when hovered
<ide> pointHoverRadius: 5,
<ide>
<del> // String or array - point background color when hovered
<add> // String or Array - point background color when hovered
<ide> pointHoverBackgroundColor: "rgba(220,220,220,1)",
<ide>
<del> // Point border color when hovered
<add> // String or Array - Point border color when hovered
<ide> pointHoverBorderColor: "rgba(220,220,220,1)",
<ide>
<del> // Number or array - border width of point when hovered
<del> pointHoverBorderWidth: 2,
<del>
<del> // Tension - bezier curve tension of the line. Set to 0 to draw straight lines connecting points
<del> // Used to be called "tension" but was renamed for consistency. The old option name continues to work for compatibility.
<del> lineTension: 0.1,
<del>
<del> // Number - the pixel size of the point shape. Can be set to 0 to not render a circle over the point
<del> radius: 1,
<add> // Number or Array - border width of point when hovered
<add> pointHoverBorderWidth: 2,
<add>
<add> // Number or Array - the pixel size of the point shape. Can be set to 0 to not render a circle over the point
<add> // Used to be called "radius" but was renamed for consistency. The old option name continues to work for compatibility.
<add> pointRadius: 1,
<add>
<add> // Number or Array - the pixel size of the non-displayed point that reacts to mouse hover events
<add> //
<add> // Used to be called "hitRadius" but was renamed for consistency. The old option name continues to work for compatibility.
<add> pointHitRadius: 10,
<ide>
<ide> // The actual data
<ide> data: [65, 59, 80, 81, 56, 55, 40],
| 1
|
PHP
|
PHP
|
fix a styling issue
|
eb5de12c443b10c8eb4936a5d09977adc43a2a54
|
<ide><path>src/Illuminate/Database/Schema/Builder.php
<ide> public function registerCustomDBALType($class, $name, $type)
<ide> if (! $this->connection->isDoctrineAvailable()) {
<ide> return;
<ide> }
<add>
<ide> if (! Type::hasType($name)) {
<ide> Type::addType($name, $class);
<ide> $this->connection
| 1
|
Python
|
Python
|
add line break as soon tests are done
|
5b90902b8bf260518d73aa2afbccb10dcf82e78a
|
<ide><path>tools/test.py
<ide> def Starting(self):
<ide> pass
<ide>
<ide> def Done(self):
<del> self.PrintProgress('Done')
<add> self.PrintProgress('Done\n')
<ide>
<ide> def AboutToRun(self, case):
<ide> self.PrintProgress(case.GetLabel())
| 1
|
Python
|
Python
|
add xcom push for ecsoperator
|
8d42d9ed69b03b372c6bc01309ef22e01b8db55f
|
<ide><path>airflow/providers/amazon/aws/operators/ecs.py
<ide> # under the License.
<ide> import re
<ide> import sys
<add>from collections import deque
<ide> from datetime import datetime
<del>from typing import Dict, Optional
<add>from typing import Dict, Generator, Optional
<ide>
<ide> from botocore.waiter import Waiter
<ide>
<ide> def execute(self, context):
<ide> self._wait_for_task_ended()
<ide>
<ide> self._check_success_task()
<add>
<ide> self.log.info('ECS Task has been successfully executed')
<ide>
<add> if self.do_xcom_push:
<add> return self._last_log_message()
<add>
<add> return None
<add>
<ide> def _start_task(self):
<ide> run_opts = {
<ide> 'cluster': self.cluster,
<ide> def _wait_for_task_ended(self) -> None:
<ide> waiter.config.max_attempts = sys.maxsize # timeout is managed by airflow
<ide> waiter.wait(cluster=self.cluster, tasks=[self.arn])
<ide>
<add> return
<add>
<add> def _cloudwatch_log_events(self) -> Generator:
<add> if self._aws_logs_enabled():
<add> task_id = self.arn.split("/")[-1]
<add> stream_name = f"{self.awslogs_stream_prefix}/{task_id}"
<add> yield from self.get_logs_hook().get_log_events(self.awslogs_group, stream_name)
<add> else:
<add> yield from ()
<add>
<add> def _aws_logs_enabled(self):
<add> return self.awslogs_group and self.awslogs_stream_prefix
<add>
<add> def _last_log_message(self):
<add> try:
<add> return deque(self._cloudwatch_log_events(), maxlen=1).pop()["message"]
<add> except IndexError:
<add> return None
<add>
<ide> def _check_success_task(self) -> None:
<ide> if not self.client or not self.arn:
<ide> return
<ide> def _check_success_task(self) -> None:
<ide> self.log.info('ECS Task stopped, check status: %s', response)
<ide>
<ide> # Get logs from CloudWatch if the awslogs log driver was used
<del> if self.awslogs_group and self.awslogs_stream_prefix:
<del> self.log.info('ECS Task logs output:')
<del> task_id = self.arn.split("/")[-1]
<del> stream_name = f"{self.awslogs_stream_prefix}/{task_id}"
<del> for event in self.get_logs_hook().get_log_events(self.awslogs_group, stream_name):
<del> event_dt = datetime.fromtimestamp(event['timestamp'] / 1000.0)
<del> self.log.info("[%s] %s", event_dt.isoformat(), event['message'])
<add> for event in self._cloudwatch_log_events():
<add> event_dt = datetime.fromtimestamp(event['timestamp'] / 1000.0)
<add> self.log.info("[%s] %s", event_dt.isoformat(), event['message'])
<ide>
<ide> if len(response.get('failures', [])) > 0:
<ide> raise AirflowException(response)
<ide><path>tests/providers/amazon/aws/operators/test_ecs.py
<ide> def test_reattach_successful(self, launch_type, tags, start_mock, check_mock, wa
<ide> self.assertEqual(
<ide> self.ecs.arn, 'arn:aws:ecs:us-east-1:012345678910:task/d8c67b3c-ac87-4ffe-a847-4785bc3a8b55'
<ide> )
<add>
<add> @mock.patch.object(ECSOperator, '_last_log_message', return_value="Log output")
<add> def test_execute_xcom_with_log(self, mock_cloudwatch_log_message):
<add> self.ecs.do_xcom_push = True
<add> self.assertEqual(self.ecs.execute(None), mock_cloudwatch_log_message.return_value)
<add>
<add> @mock.patch.object(ECSOperator, '_last_log_message', return_value=None)
<add> def test_execute_xcom_with_no_log(self, mock_cloudwatch_log_message):
<add> self.ecs.do_xcom_push = True
<add> self.assertEqual(self.ecs.execute(None), mock_cloudwatch_log_message.return_value)
<add>
<add> @mock.patch.object(ECSOperator, '_last_log_message', return_value="Log output")
<add> def test_execute_xcom_disabled(self, mock_cloudwatch_log_message):
<add> self.ecs.do_xcom_push = False
<add> self.assertEqual(self.ecs.execute(None), None)
| 2
|
Javascript
|
Javascript
|
add line-height to unitless css props, test cases
|
27ee9c6eb07fd2f65afb69645d6496811e588346
|
<ide><path>src/dom/CSSProperty.js
<ide> var isUnitlessNumber = {
<ide> fillOpacity: true,
<ide> fontWeight: true,
<add> lineHeight: true,
<ide> opacity: true,
<ide> orphans: true,
<ide> zIndex: true,
<ide><path>src/dom/__tests__/CSSPropertyOperations-test.js
<ide> describe('CSSPropertyOperations', function() {
<ide> })).toBe('left:0;margin:16px;opacity:0.5;padding:4px;');
<ide> });
<ide>
<add> it('should not append `px` to styles that might need a number', function() {
<add> expect(CSSPropertyOperations.createMarkupForStyles({
<add> fillOpacity: 1,
<add> fontWeight: 2,
<add> opacity: 3,
<add> orphans: 4,
<add> zIndex: 5,
<add> zoom: 6,
<add> lineHeight: 7
<add> })).toBe(
<add> 'fill-opacity:1;font-weight:2;opacity:3;orphans:4;z-index:5;zoom:6;' +
<add> 'line-height:7;'
<add> );
<add> });
<add>
<ide> it('should set style attribute when styles exist', function() {
<ide> var styles = {
<ide> backgroundColor: '#000',
| 2
|
Ruby
|
Ruby
|
build sql ast nodes rather than generate strings
|
820582883a301ad813534492f8f3223a582824f1
|
<ide><path>activerecord/lib/active_record/associations/through_association_scope.rb
<ide> def construct_create_scope
<ide>
<ide> # Build SQL conditions from attributes, qualified by table name.
<ide> def construct_conditions
<del> table_name = @reflection.through_reflection.quoted_table_name
<add> table = @reflection.through_reflection.klass.arel_table
<ide> conditions = construct_quoted_owner_attributes(@reflection.through_reflection).map do |attr, value|
<del> "#{table_name}.#{attr} = #{value}"
<add> table[attr].eq(value)
<ide> end
<del> conditions << sql_conditions if sql_conditions
<del> "(" + conditions.join(') AND (') + ")"
<add> conditions << Arel.sql(sql_conditions) if sql_conditions
<add> table.create_and(conditions)
<ide> end
<ide>
<ide> # Associate attributes pointing to owner, quoted.
<ide> def construct_quoted_owner_attributes(reflection)
<ide> if as = reflection.options[:as]
<del> { "#{as}_id" => owner_quoted_id,
<del> "#{as}_type" => reflection.klass.quote_value(
<del> @owner.class.base_class.name.to_s,
<del> reflection.klass.columns_hash["#{as}_type"]) }
<add> { "#{as}_id" => @owner.id,
<add> "#{as}_type" => @owner.class.base_class.name }
<ide> elsif reflection.macro == :belongs_to
<del> { reflection.klass.primary_key => @owner.class.quote_value(@owner[reflection.primary_key_name]) }
<add> { reflection.klass.primary_key => @owner[reflection.primary_key_name] }
<ide> else
<del> { reflection.primary_key_name => owner_quoted_id }
<add> { reflection.primary_key_name => @owner.id }
<ide> end
<ide> end
<ide>
| 1
|
PHP
|
PHP
|
add host name matching to routecollection/route
|
017a1f9aca17cd7d231dc8a7581ce35360c0a3aa
|
<ide><path>src/Routing/Route/Route.php
<ide> public function parse($url, $method = '')
<ide> */
<ide> public function hostMatches($host)
<ide> {
<del> // Will be implemented later
<del> return true;
<add> if (!isset($this->options['_host'])) {
<add> return true;
<add> }
<add> $pattern = '@^' . str_replace('\*', '.*', preg_quote($this->options['_host'], '@')) . '$@';
<add> return preg_match($pattern, $host) !== 0;
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Routing/RouteCollectionTest.php
<ide> namespace Cake\Test\TestCase\Routing;
<ide>
<ide> use Cake\Http\ServerRequest;
<add>use Cake\Routing\Exception\MissingRouteException;
<ide> use Cake\Routing\RouteBuilder;
<ide> use Cake\Routing\RouteCollection;
<ide> use Cake\Routing\Route\Route;
<ide> public function testParseRequestMissingRoute()
<ide> $this->assertEquals([], $result, 'Should not match, missing /b');
<ide> }
<ide>
<add> /**
<add> * Test parseRequest() checks host conditions
<add> *
<add> * @return void
<add> */
<add> public function testParseRequestCheckHostCondition()
<add> {
<add> $routes = new RouteBuilder($this->collection, '/');
<add> $routes->connect('/fallback', ['controller' => 'Articles', 'action' => 'index'], ['_host' => '*.example.com']);
<add>
<add> $request = new ServerRequest([
<add> 'environment' => [
<add> 'HTTP_HOST' => 'a.example.com',
<add> 'PATH_INFO' => '/fallback'
<add> ]
<add> ]);
<add> $result = $this->collection->parseRequest($request);
<add> $expected = [
<add> 'controller' => 'Articles',
<add> 'action' => 'index',
<add> 'pass' => [],
<add> 'plugin' => null,
<add> '_matchedRoute' => '/fallback'
<add> ];
<add> $this->assertEquals($expected, $result, 'Should match, domain is correct');
<add>
<add> $request = new ServerRequest([
<add> 'environment' => [
<add> 'HTTP_HOST' => 'foo.bar.example.com',
<add> 'PATH_INFO' => '/fallback'
<add> ]
<add> ]);
<add> $result = $this->collection->parseRequest($request);
<add> $this->assertEquals($expected, $result, 'Should match, domain is a matching subdomain');
<add>
<add> $request = new ServerRequest([
<add> 'environment' => [
<add> 'HTTP_HOST' => 'example.test.com',
<add> 'PATH_INFO' => '/fallback'
<add> ]
<add> ]);
<add> try {
<add> $this->collection->parseRequest($request);
<add> $this->fail('No exception raised');
<add> } catch (MissingRouteException $e) {
<add> $this->assertContains('/fallback', $e->getMessage());
<add> }
<add> }
<add>
<add> /**
<add> * Get a list of hostnames
<add> *
<add> * @return array
<add> */
<add> public static function hostProvider()
<add> {
<add> return [
<add> ['wrong.example'],
<add> ['example.com'],
<add> ['aexample.com'],
<add> ];
<add> }
<add>
<add> /**
<add> * Test parseRequest() checks host conditions
<add> *
<add> * @dataProvider hostProvider
<add> * @expectedException \Cake\Routing\Exception\MissingRouteException
<add> * @expectedExceptionMessage A route matching "/fallback" could not be found
<add> */
<add> public function testParseRequestCheckHostConditionFail($host)
<add> {
<add> $routes = new RouteBuilder($this->collection, '/');
<add> $routes->connect('/fallback', ['controller' => 'Articles', 'action' => 'index'], ['_host' => '*.example.com']);
<add>
<add> $request = new ServerRequest([
<add> 'environment' => [
<add> 'HTTP_HOST' => $host,
<add> 'PATH_INFO' => '/fallback'
<add> ]
<add> ]);
<add> $this->collection->parseRequest($request);
<add> }
<add>
<ide> /**
<ide> * Test parsing routes.
<ide> *
| 2
|
Javascript
|
Javascript
|
add renderer.gammaoutput to program code
|
7ffac6f5df245129f6841a5dfee01c015176c253
|
<ide><path>src/renderers/webgl/WebGLPrograms.js
<ide> function WebGLPrograms( renderer, capabilities ) {
<ide>
<ide> }
<ide>
<add> array.push( renderer.gammaOutput );
<add>
<ide> return array.join();
<ide>
<ide> };
| 1
|
Python
|
Python
|
fix spelling error in npy_tempita kwarg
|
a0b3874811e53d17b45ae1911888ddccd8d85c22
|
<ide><path>tools/npy_tempita/__init__.py
<ide> class Template(object):
<ide>
<ide> def __init__(self, content, name=None, namespace=None, stacklevel=None,
<ide> get_template=None, default_inherit=None, line_offset=0,
<del> delimeters=None):
<add> delimiters=None):
<ide> self.content = content
<ide>
<del> # set delimeters
<del> if delimeters is None:
<del> delimeters = (self.default_namespace['start_braces'],
<add> # set delimiters
<add> if delimiters is None:
<add> delimiters = (self.default_namespace['start_braces'],
<ide> self.default_namespace['end_braces'])
<ide> else:
<del> assert len(delimeters) == 2 and all(
<del> [isinstance(delimeter, basestring_)
<del> for delimeter in delimeters])
<add> assert len(delimiters) == 2 and all(
<add> [isinstance(delimiter, basestring_)
<add> for delimiter in delimiters])
<ide> self.default_namespace = self.__class__.default_namespace.copy()
<del> self.default_namespace['start_braces'] = delimeters[0]
<del> self.default_namespace['end_braces'] = delimeters[1]
<del> self.delimeters = delimeters
<add> self.default_namespace['start_braces'] = delimiters[0]
<add> self.default_namespace['end_braces'] = delimiters[1]
<add> self.delimiters = delimiters
<ide>
<ide> self._unicode = is_unicode(content)
<ide> if name is None and stacklevel is not None:
<ide> def __init__(self, content, name=None, namespace=None, stacklevel=None,
<ide> self.name = name
<ide> self._parsed = parse(
<ide> content, name=name, line_offset=line_offset,
<del> delimeters=self.delimeters)
<add> delimiters=self.delimiters)
<ide> if namespace is None:
<ide> namespace = {}
<ide> self.namespace = namespace
<ide> def _add_line_info(self, msg, pos):
<ide> return msg
<ide>
<ide>
<del>def sub(content, delimeters=None, **kw):
<add>def sub(content, delimiters=None, **kw):
<ide> name = kw.get('__name')
<del> tmpl = Template(content, name=name, delimeters=delimeters)
<add> tmpl = Template(content, name=name, delimiters=delimiters)
<ide> return tmpl.substitute(kw)
<ide>
<ide>
<ide> def __bool__(self):
<ide> ############################################################
<ide>
<ide>
<del>def lex(s, name=None, trim_whitespace=True, line_offset=0, delimeters=None):
<del> if delimeters is None:
<del> delimeters = (Template.default_namespace['start_braces'],
<add>def lex(s, name=None, trim_whitespace=True, line_offset=0, delimiters=None):
<add> if delimiters is None:
<add> delimiters = (Template.default_namespace['start_braces'],
<ide> Template.default_namespace['end_braces'])
<ide> in_expr = False
<ide> chunks = []
<ide> last = 0
<ide> last_pos = (line_offset + 1, 1)
<del> token_re = re.compile(r'%s|%s' % (re.escape(delimeters[0]),
<del> re.escape(delimeters[1])))
<add> token_re = re.compile(r'%s|%s' % (re.escape(delimiters[0]),
<add> re.escape(delimiters[1])))
<ide> for match in token_re.finditer(s):
<ide> expr = match.group(0)
<ide> pos = find_position(s, match.end(), last, last_pos)
<del> if expr == delimeters[0] and in_expr:
<del> raise TemplateError('%s inside expression' % delimeters[0],
<add> if expr == delimiters[0] and in_expr:
<add> raise TemplateError('%s inside expression' % delimiters[0],
<ide> position=pos,
<ide> name=name)
<del> elif expr == delimeters[1] and not in_expr:
<del> raise TemplateError('%s outside expression' % delimeters[1],
<add> elif expr == delimiters[1] and not in_expr:
<add> raise TemplateError('%s outside expression' % delimiters[1],
<ide> position=pos,
<ide> name=name)
<del> if expr == delimeters[0]:
<add> if expr == delimiters[0]:
<ide> part = s[last:match.start()]
<ide> if part:
<ide> chunks.append(part)
<ide> def lex(s, name=None, trim_whitespace=True, line_offset=0, delimeters=None):
<ide> last = match.end()
<ide> last_pos = pos
<ide> if in_expr:
<del> raise TemplateError('No %s to finish last expression' % delimeters[1],
<add> raise TemplateError('No %s to finish last expression' % delimiters[1],
<ide> name=name, position=last_pos)
<ide> part = s[last:]
<ide> if part:
<ide> def find_position(string, index, last_index, last_pos):
<ide> return (last_pos[0] + lines, column)
<ide>
<ide>
<del>def parse(s, name=None, line_offset=0, delimeters=None):
<add>def parse(s, name=None, line_offset=0, delimiters=None):
<ide>
<del> if delimeters is None:
<del> delimeters = (Template.default_namespace['start_braces'],
<add> if delimiters is None:
<add> delimiters = (Template.default_namespace['start_braces'],
<ide> Template.default_namespace['end_braces'])
<del> tokens = lex(s, name=name, line_offset=line_offset, delimeters=delimeters)
<add> tokens = lex(s, name=name, line_offset=line_offset, delimiters=delimiters)
<ide> result = []
<ide> while tokens:
<ide> next_chunk, tokens = parse_expr(tokens, name)
| 1
|
Javascript
|
Javascript
|
make transitionevent on state manager configurable
|
ee1d2d55bb66cc8bb82c8ca1e535995c37221a53
|
<ide><path>packages/ember-states/lib/router.js
<ide> require('ember-states/routable');
<ide> */
<ide> Ember.Router = Ember.StateManager.extend(
<ide> /** @scope Ember.Router.prototype */ {
<add>
<ide> initialState: 'root',
<ide>
<add> /**
<add> On router, transitionEvent should be called connectOutlets
<add>
<add> @property {String}
<add> */
<add> transitionEvent: 'connectOutlets',
<add>
<ide> route: function(path) {
<ide> if (path.charAt(0) === '/') {
<ide> path = path.substr(1);
<ide><path>packages/ember-states/lib/state.js
<ide> Ember.State = Ember.Object.extend(Ember.Evented, {
<ide> return !get(this, 'childStates').length;
<ide> }).cacheable(),
<ide>
<del> connectOutlets: Ember.K,
<add> setup: Ember.K,
<ide> enter: Ember.K,
<ide> exit: Ember.K
<ide> });
<ide><path>packages/ember-states/lib/state_manager.js
<ide> Ember.StateManager = Ember.State.extend(
<ide>
<ide> currentState: null,
<ide>
<add> /**
<add> The name of transitionEvent that this stateManager will dispatch
<add>
<add> @property {String}
<add> */
<add> transitionEvent: 'setup',
<add>
<ide> /**
<ide> If set to true, `errorOnUnhandledEvents` will cause an exception to be
<ide> raised if you attempt to send an event to a state manager that is not
<ide> Ember.StateManager = Ember.State.extend(
<ide> // 1. Normalize arguments
<ide> // 2. Ensure that we are in the correct state
<ide> // 3. Map provided path to context objects and send
<del> // appropriate connectOutlets events
<add> // appropriate transitionEvent events
<ide>
<ide> if (Ember.empty(name)) { return; }
<ide>
<ide> Ember.StateManager = Ember.State.extend(
<ide> state = this.findStatesByRoute(state, path);
<ide> state = state[state.length-1];
<ide>
<del> state.fire('connectOutlets', this, context);
<add> state.fire(get(this, 'transitionEvent'), this, context);
<ide> }, this);
<ide> },
<ide>
<ide><path>packages/ember-states/tests/state_manager_test.js
<ide> test("goToState with current state does not trigger enter or exit", function() {
<ide>
<ide> module("Transition contexts");
<ide>
<del>test("if a context is passed to a transition, the state's connectOutlets event is triggered after the transition has completed", function() {
<add>test("if a context is passed to a transition, the state's setup event is triggered after the transition has completed", function() {
<ide> expect(1);
<ide> var context = {};
<ide>
<ide> test("if a context is passed to a transition, the state's connectOutlets event i
<ide> }),
<ide>
<ide> next: Ember.State.create({
<del> connectOutlets: function(manager, passedContext) {
<add> setup: function(manager, passedContext) {
<ide> equal(context, passedContext, "The context is passed through");
<ide> }
<ide> })
<ide> test("if a context is passed to a transition, the state's connectOutlets event i
<ide> stateManager.send('goNext', context);
<ide> });
<ide>
<del>test("if a context is passed to a transition and the path is to the current state, the state's connectOutlets event is triggered again", function() {
<add>test("if a context is passed to a transition and the path is to the current state, the state's setup event is triggered again", function() {
<ide> expect(2);
<ide> var counter = 0;
<ide>
<ide> test("if a context is passed to a transition and the path is to the current stat
<ide> manager.goToState('next', counter);
<ide> },
<ide>
<del> connectOutlets: function(manager, context) {
<add> setup: function(manager, context) {
<ide> equal(context, counter, "The context is passed through");
<ide> }
<ide> })
<ide> test("if a context is passed to a transition and the path is to the current stat
<ide> stateManager.send('goNext', counter);
<ide> });
<ide>
<del>test("if no context is provided, connectOutlets is triggered with an undefined context", function() {
<add>test("if no context is provided, setup is triggered with an undefined context", function() {
<ide> expect(2);
<ide>
<ide> Ember.run(function() {
<ide> test("if no context is provided, connectOutlets is triggered with an undefined c
<ide> manager.transitionTo('next');
<ide> },
<ide>
<del> connectOutlets: function(manager, context) {
<del> equal(context, undefined, "connectOutlets is called with no context");
<add> setup: function(manager, context) {
<add> equal(context, undefined, "setup is called with no context");
<ide> }
<ide> })
<ide> })
<ide> test("multiple contexts can be provided in a single transitionTo", function() {
<ide> }),
<ide>
<ide> planters: Ember.State.create({
<del> connectOutlets: function(manager, context) {
<add> setup: function(manager, context) {
<ide> deepEqual(context, { company: true });
<ide> },
<ide>
<ide> nuts: Ember.State.create({
<del> connectOutlets: function(manager, context) {
<add> setup: function(manager, context) {
<ide> deepEqual(context, { product: true });
<ide> }
<ide> })
| 4
|
Javascript
|
Javascript
|
fix bug with double updates in a single batch
|
c1e3f7ec14971dbf678a731408d38959545793eb
|
<ide><path>src/renderers/shared/reconciler/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = {
<ide> this._nativeContainerInfo = null;
<ide>
<ide> // See ReactUpdateQueue
<add> this._updateBatchNumber = null;
<ide> this._pendingElement = null;
<ide> this._pendingStateQueue = null;
<ide> this._pendingReplaceState = false;
<ide> var ReactCompositeComponentMixin = {
<ide> transaction,
<ide> this._context
<ide> );
<del> }
<del>
<del> if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
<add> } else if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
<ide> this.updateComponent(
<ide> transaction,
<ide> this._currentElement,
<ide> this._currentElement,
<ide> this._context,
<ide> this._context
<ide> );
<add> } else {
<add> this._updateBatchNumber = null;
<ide> }
<ide> },
<ide>
<ide> var ReactCompositeComponentMixin = {
<ide> );
<ide> }
<ide>
<add> this._updateBatchNumber = null;
<ide> if (shouldUpdate) {
<ide> this._pendingForceUpdate = false;
<ide> // Will set `this.props`, `this.state` and `this.context`.
<ide><path>src/renderers/shared/reconciler/ReactReconciler.js
<ide> var ReactRef = require('ReactRef');
<ide> var ReactInstrumentation = require('ReactInstrumentation');
<ide>
<add>var invariant = require('invariant');
<add>
<ide> /**
<ide> * Helper to call ReactRef.attachRefs with this composite component, split out
<ide> * to avoid allocations in the transaction mount-ready queue.
<ide> var ReactReconciler = {
<ide> */
<ide> performUpdateIfNecessary: function(
<ide> internalInstance,
<del> transaction
<add> transaction,
<add> updateBatchNumber
<ide> ) {
<add> if (internalInstance._updateBatchNumber !== updateBatchNumber) {
<add> // The component's enqueued batch number should always be the current
<add> // batch or the following one.
<add> invariant(
<add> internalInstance._updateBatchNumber == null ||
<add> internalInstance._updateBatchNumber === updateBatchNumber + 1,
<add> 'performUpdateIfNecessary: Unexpected batch number (current %s, ' +
<add> 'pending %s)',
<add> updateBatchNumber,
<add> internalInstance._updateBatchNumber
<add> );
<add> return;
<add> }
<ide> if (__DEV__) {
<ide> if (internalInstance._debugID !== 0) {
<ide> ReactInstrumentation.debugTool.onBeginReconcilerTimer(
<ide><path>src/renderers/shared/reconciler/ReactUpdates.js
<ide> var Transaction = require('Transaction');
<ide> var invariant = require('invariant');
<ide>
<ide> var dirtyComponents = [];
<add>var updateBatchNumber = 0;
<ide> var asapCallbackQueue = CallbackQueue.getPooled();
<ide> var asapEnqueued = false;
<ide>
<ide> function runBatchedUpdates(transaction) {
<ide> // them before their children by sorting the array.
<ide> dirtyComponents.sort(mountOrderComparator);
<ide>
<add> // Any updates enqueued while reconciling must be performed after this entire
<add> // batch. Otherwise, if dirtyComponents is [A, B] where A has children B and
<add> // C, B could update twice in a single batch if C's render enqueues an update
<add> // to B (since B would have already updated, we should skip it, and the only
<add> // way we can know to do so is by checking the batch counter).
<add> updateBatchNumber++;
<add>
<ide> for (var i = 0; i < len; i++) {
<ide> // If a component is unmounted before pending changes apply, it will still
<ide> // be here, but we assume that it has cleared its _pendingCallbacks and
<ide> function runBatchedUpdates(transaction) {
<ide>
<ide> ReactReconciler.performUpdateIfNecessary(
<ide> component,
<del> transaction.reconcileTransaction
<add> transaction.reconcileTransaction,
<add> updateBatchNumber
<ide> );
<ide>
<ide> if (markerName) {
<ide> function enqueueUpdate(component) {
<ide> }
<ide>
<ide> dirtyComponents.push(component);
<add> if (component._updateBatchNumber == null) {
<add> component._updateBatchNumber = updateBatchNumber + 1;
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>src/renderers/shared/reconciler/__tests__/ReactUpdates-test.js
<ide> describe('ReactUpdates', function() {
<ide> 'to be a function. Instead received: Foo (keys: a, b).'
<ide> );
<ide> });
<add>
<add> it('does not update one component twice in a batch (#2410)', function() {
<add> var Parent = React.createClass({
<add> getChild: function() {
<add> return this.refs.child;
<add> },
<add> render: function() {
<add> return <Child ref="child" />;
<add> },
<add> });
<add>
<add> var renderCount = 0;
<add> var postRenderCount = 0;
<add> var once = false;
<add> var Child = React.createClass({
<add> getInitialState: function() {
<add> return {updated: false};
<add> },
<add> componentWillUpdate: function() {
<add> if (!once) {
<add> once = true;
<add> this.setState({updated: true});
<add> }
<add> },
<add> componentDidMount: function() {
<add> expect(renderCount).toBe(postRenderCount + 1);
<add> postRenderCount++;
<add> },
<add> componentDidUpdate: function() {
<add> expect(renderCount).toBe(postRenderCount + 1);
<add> postRenderCount++;
<add> },
<add> render: function() {
<add> expect(renderCount).toBe(postRenderCount);
<add> renderCount++;
<add> return <div />;
<add> },
<add> });
<add>
<add> var parent = ReactTestUtils.renderIntoDocument(<Parent />);
<add> var child = parent.getChild();
<add> ReactDOM.unstable_batchedUpdates(function() {
<add> parent.forceUpdate();
<add> child.forceUpdate();
<add> });
<add> });
<add>
<add> it('does not update one component twice in a batch (#6371)', function() {
<add> var callbacks = [];
<add> function emitChange() {
<add> callbacks.forEach(c => c());
<add> }
<add>
<add> class App extends React.Component {
<add> constructor(props) {
<add> super(props);
<add> this.state = { showChild: true };
<add> }
<add> componentDidMount() {
<add> console.log('about to remove child via set state');
<add> this.setState({ showChild: false });
<add> }
<add> render() {
<add> return (
<add> <div>
<add> <ForceUpdatesOnChange />
<add> {this.state.showChild && <EmitsChangeOnUnmount />}
<add> </div>
<add> );
<add> }
<add> }
<add>
<add> class EmitsChangeOnUnmount extends React.Component {
<add> componentWillUnmount() {
<add> emitChange();
<add> }
<add> render() {
<add> return null;
<add> }
<add> }
<add>
<add> class ForceUpdatesOnChange extends React.Component {
<add> componentDidMount() {
<add> this.onChange = () => this.forceUpdate();
<add> this.onChange();
<add> callbacks.push(this.onChange);
<add> }
<add> componentWillUnmount() {
<add> callbacks = callbacks.filter((c) => c !== this.onChange);
<add> }
<add> render() {
<add> return <div key={Math.random()} onClick={function() {}} />;
<add> }
<add> }
<add>
<add> ReactDOM.render(<App />, document.createElement('div'));
<add> });
<add>
<ide> });
| 4
|
Python
|
Python
|
fix evaluation bug
|
64b2a828c0b16368810d15c6fff1640e33a34125
|
<ide><path>examples/run_squad.py
<ide> def main():
<ide> output_args_file = os.path.join(args.output_dir, 'training_args.bin')
<ide> torch.save(args, output_args_file)
<ide> else:
<del> model = BertForQuestionAnswering.from_pretrained(args.bert_model)
<add> # Load a trained model and vocabulary that you have fine-tuned
<add> model = BertForQuestionAnswering.from_pretrained(args.output_dir)
<add> tokenizer = BertTokenizer.from_pretrained(args.output_dir, do_lower_case=args.do_lower_case)
<ide>
<ide> model.to(device)
<ide>
| 1
|
Python
|
Python
|
clean the code..
|
b5d68b1cc360725e140f18fed4f927890d9ef3c8
|
<ide><path>glances/glances.py
<ide> def __update__(self):
<ide> # NET
<ide> if psutil_network_io_tag:
<ide> self.network = []
<del> try:
<del> self.network_old
<del> except Exception:
<del> self.network_old = psutil.network_io_counters(True)
<del> else:
<del> try:
<del> self.network_new = psutil.network_io_counters(True)
<del> except Exception:
<del> pass
<add> if hasattr(psutil, 'network_io_counters'):
<add> if not hasattr(self, 'network_old'):
<add> self.network_old = psutil.network_io_counters(True)
<ide> else:
<add> self.network_new = psutil.network_io_counters(True)
<ide> for net in self.network_new:
<ide> try:
<add> # Try necessary to manage dynamic network interface
<ide> netstat = {}
<ide> netstat['interface_name'] = net
<ide> netstat['rx'] = (self.network_new[net].bytes_recv -
<ide> def __update__(self):
<ide> # DISK I/O
<ide> if psutil_disk_io_tag:
<ide> self.diskio = []
<del> try:
<del> self.diskio_old
<del> except Exception:
<del> if psutil_disk_io_tag:
<add> if psutil_disk_io_tag and hasattr(psutil, 'disk_io_counters'):
<add> if not hasattr(self, 'diskio_old'):
<ide> self.diskio_old = psutil.disk_io_counters(True)
<del> else:
<del> try:
<del> self.diskio_new = psutil.disk_io_counters(True)
<del> except Exception:
<del> pass
<ide> else:
<add> self.diskio_new = psutil.disk_io_counters(True)
<ide> for disk in self.diskio_new:
<ide> try:
<add> # Try necessary to manage dynamic disk creation/del
<ide> diskstat = {}
<ide> diskstat['disk_name'] = disk
<ide> diskstat['read_bytes'] = (
<ide> def __update__(self):
<ide>
<ide> # FILE SYSTEM
<ide> if psutil_fs_usage_tag:
<del> try:
<del> self.fs = self.glancesgrabfs.get()
<del> except Exception:
<del> self.fs = {}
<add> self.fs = self.glancesgrabfs.get()
<ide>
<ide> # PROCESS
<ide> # Initialiation of the running processes list
<ide> # Data are refreshed every two cycle (refresh_time * 2)
<ide> if self.process_list_refresh:
<ide> self.process_first_grab = False
<del> try:
<del> self.process_all
<del> except Exception:
<add> if not hasattr(self, 'process_all'):
<ide> self.process_all = [proc for proc in psutil.process_iter()]
<ide> self.process_first_grab = True
<ide> self.process = []
<ide> def getProcessList(self, sortedby='auto'):
<ide> # Auto selection
<ide> # If global MEM > 70% sort by MEM usage
<ide> # else sort by CPU usage
<del> real_used_phymem = self.mem['used'] - self.mem['cache']
<del> try:
<del> memtotal = (real_used_phymem * 100) / self.mem['total']
<del> except Exception:
<del> pass
<del> else:
<add> if (self.mem['total'] != 0):
<add> memtotal = ((self.mem['used'] - self.mem['cache']) * 100) / self.mem['total']
<ide> if memtotal > limits.getSTDWarning():
<ide> sortedby = 'memory_percent'
<ide> elif sortedby == 'name':
<ide> def __init__(self, refresh_time=1):
<ide> if not self.screen:
<ide> print(_("Error: Cannot init the curses library.\n"))
<ide>
<del> curses.start_color()
<add> # Set curses options
<add> if hasattr(curses, 'start_color'):
<add> curses.start_color()
<ide> if hasattr(curses, 'use_default_colors'):
<del> try:
<del> curses.use_default_colors()
<del> except Exception:
<del> pass
<add> curses.use_default_colors()
<ide> if hasattr(curses, 'noecho'):
<del> try:
<del> curses.noecho()
<del> except Exception:
<del> pass
<add> curses.noecho()
<ide> if hasattr(curses, 'cbreak'):
<del> try:
<del> curses.cbreak()
<del> except Exception:
<del> pass
<add> curses.cbreak()
<ide> if hasattr(curses, 'curs_set'):
<del> try:
<del> curses.curs_set(0)
<del> except Exception:
<del> pass
<add> curses.curs_set(0)
<ide>
<ide> # Init colors
<ide> self.hascolors = False
<ide> def __getAlert(self, current=0, max=100):
<ide> # If current > CAREFUL of max then alert = CAREFUL
<ide> # If current > WARNING of max then alert = WARNING
<ide> # If current > CRITICAL of max then alert = CRITICAL
<del> try:
<add> if max != 0:
<ide> (current * 100) / max
<del> except ZeroDivisionError:
<add> else:
<ide> return 'DEFAULT'
<ide>
<ide> variable = (current * 100) / max
| 1
|
Javascript
|
Javascript
|
fix unbound keyword
|
508d9de45bd6d729c8cb0954f97fd7ed83531276
|
<ide><path>packages/ember-htmlbars/lib/hooks/subexpr.js
<ide> import create from "ember-metal/platform/create";
<ide> import { subscribe, addDependency, read, labelsFor, labelFor } from "ember-metal/streams/utils";
<ide>
<ide> export default function subexpr(env, scope, helperName, params, hash) {
<add> // TODO: Keywords and helper invocation should be integrated into
<add> // the subexpr hook upstream in HTMLBars.
<add> var keyword = env.hooks.keywords[helperName];
<add> if (keyword) {
<add> return keyword(null, env, scope, params, hash, null, null);
<add> }
<add>
<ide> var helper = lookupHelper(helperName, scope.self, env);
<ide> var invoker = function(params, hash) {
<ide> return env.hooks.invokeHelper(null, env, scope, null, params, hash, helper, { template: {}, inverse: {} }, undefined).value;
<ide><path>packages/ember-htmlbars/lib/keywords/unbound.js
<ide> export default function unbound(morph, env, scope, originalParams, hash, templat
<ide> var params = originalParams.slice();
<ide> var valueStream = params.shift();
<ide>
<add> // If `morph` is `null` the keyword is being invoked as a subexpression.
<add> if (morph === null) {
<add> if (originalParams.length > 1) {
<add> valueStream = env.hooks.subexpr(env, scope, valueStream.key, params, hash);
<add> }
<add>
<add> return new VolatileStream(valueStream);
<add> }
<add>
<ide> if (params.length === 0) {
<ide> env.hooks.range(morph, env, scope, null, valueStream);
<ide> } else if (template === null) {
<ide> export default function unbound(morph, env, scope, originalParams, hash, templat
<ide>
<ide> return true;
<ide> }
<add>
<add>import merge from "ember-metal/merge";
<add>import create from "ember-metal/platform/create";
<add>import Stream from "ember-metal/streams/stream";
<add>import { read } from "ember-metal/streams/utils";
<add>
<add>function VolatileStream(source) {
<add> this.init(`(volatile ${source.label})`);
<add> this.source = this.addDependency(source);
<add>}
<add>
<add>VolatileStream.prototype = create(Stream.prototype);
<add>
<add>merge(VolatileStream.prototype, {
<add> value() {
<add> return read(this.source);
<add> },
<add>
<add> notify() {}
<add>});
<ide><path>packages/ember-htmlbars/tests/helpers/unbound_test.js
<ide> QUnit.test('it should not re-render if the property changes', function() {
<ide> equal(view.$().text(), 'BORK BORK', 'should not re-render if the property changes');
<ide> });
<ide>
<add>QUnit.test('it should re-render if the parent view rerenders', function() {
<add> run(function() {
<add> view.set('context.foo', 'OOF');
<add> view.rerender();
<add> });
<add> equal(view.$().text(), 'OOF OOF', 'should re-render if the parent view rerenders');
<add>});
<add>
<ide> QUnit.test('it should throw the helper missing error if multiple properties are provided', function() {
<ide> expectAssertion(function() {
<ide> runAppend(EmberView.create({
<ide> QUnit.test('it should throw the helper missing error if multiple properties are
<ide> }, /A helper named 'foo' could not be found/);
<ide> });
<ide>
<del>QUnit.skip('should property escape unsafe hrefs', function() {
<add>QUnit.test('should property escape unsafe hrefs', function() {
<ide> /* jshint scripturl:true */
<ide>
<ide> expect(3);
<ide> QUnit.skip('should property escape unsafe hrefs', function() {
<ide> }
<ide> });
<ide>
<add>QUnit.module('ember-htmlbars: {{#unbound}} subexpression', {
<add> setup() {
<add> Ember.lookup = lookup = { Ember: Ember };
<add>
<add> registerBoundHelper('capitalize', function(value) {
<add> return value.toUpperCase();
<add> });
<add>
<add> view = EmberView.create({
<add> template: compile('{{capitalize (unbound foo)}}'),
<add> context: EmberObject.create({
<add> foo: 'bork'
<add> })
<add> });
<add>
<add> runAppend(view);
<add> },
<add>
<add> teardown() {
<add> delete helpers['capitalize'];
<add>
<add> runDestroy(view);
<add> Ember.lookup = originalLookup;
<add> }
<add>});
<add>
<add>QUnit.test('it should render the current value of a property on the context', function() {
<add> equal(view.$().text(), 'BORK', 'should render the current value of a property');
<add>});
<add>
<add>QUnit.test('it should not re-render if the property changes', function() {
<add> run(function() {
<add> view.set('context.foo', 'oof');
<add> });
<add> equal(view.$().text(), 'BORK', 'should not re-render if the property changes');
<add>});
<add>
<add>QUnit.test('it should re-render if the parent view rerenders', function() {
<add> run(function() {
<add> view.set('context.foo', 'oof');
<add> view.rerender();
<add> });
<add> equal(view.$().text(), 'OOF', 'should re-render if the parent view rerenders');
<add>});
<add>
<add>QUnit.module('ember-htmlbars: {{#unbound}} subexpression - helper form', {
<add> setup() {
<add> Ember.lookup = lookup = { Ember: Ember };
<add>
<add> registerBoundHelper('capitalize', function(value) {
<add> return value.toUpperCase();
<add> });
<add>
<add> registerBoundHelper('doublize', function(value) {
<add> return `${value} ${value}`;
<add> });
<add>
<add> view = EmberView.create({
<add> template: compile('{{capitalize (unbound doublize foo)}}'),
<add> context: EmberObject.create({
<add> foo: 'bork'
<add> })
<add> });
<add>
<add> runAppend(view);
<add> },
<add>
<add> teardown() {
<add> delete helpers['capitalize'];
<add> delete helpers['doublize'];
<add>
<add> runDestroy(view);
<add> Ember.lookup = originalLookup;
<add> }
<add>});
<add>
<add>QUnit.test('it should render the current value of a property on the context', function() {
<add> equal(view.$().text(), 'BORK BORK', 'should render the current value of a property');
<add>});
<add>
<add>QUnit.test('it should not re-render if the property changes', function() {
<add> run(function() {
<add> view.set('context.foo', 'oof');
<add> });
<add> equal(view.$().text(), 'BORK BORK', 'should not re-render if the property changes');
<add>});
<add>
<add>QUnit.test('it should re-render if the parent view rerenders', function() {
<add> run(function() {
<add> view.set('context.foo', 'oof');
<add> view.rerender();
<add> });
<add> equal(view.$().text(), 'OOF OOF', 'should re-render if the parent view rerenders');
<add>});
<add>
<ide> QUnit.module("ember-htmlbars: {{#unbound boundHelper arg1 arg2... argN}} form: render unbound helper invocations", {
<ide> setup() {
<ide> Ember.lookup = lookup = { Ember: Ember };
<ide> QUnit.test("should be able to use unbound helper in #each helper (with objects)"
<ide> equal(view.$('li').children().length, 0, 'No markers');
<ide> });
<ide>
<del>QUnit.skip('should work properly with attributes', function() {
<add>QUnit.test('should work properly with attributes', function() {
<ide> expect(4);
<ide>
<ide> view = EmberView.create({
| 3
|
Javascript
|
Javascript
|
add locale switcher to i18n-routing example
|
9cbc4aacd50d0e79be7b8178eec9219457514da9
|
<ide><path>examples/i18n-routing/components/locale-switcher.js
<add>import Link from 'next/link'
<add>import { useRouter } from 'next/router'
<add>
<add>export default function LocaleSwitcher() {
<add> const router = useRouter()
<add> const { locales, locale: activeLocale } = router
<add> const otherLocales = locales.filter((locale) => locale !== activeLocale)
<add>
<add> return (
<add> <div>
<add> <p>Locale switcher:</p>
<add> <ul>
<add> {otherLocales.map((locale) => {
<add> const { pathname, query, asPath } = router
<add> return (
<add> <li key={locale}>
<add> <Link href={{ pathname, query }} as={asPath} locale={locale}>
<add> <a>{locale}</a>
<add> </Link>
<add> </li>
<add> )
<add> })}
<add> </ul>
<add> </div>
<add> )
<add>}
<ide><path>examples/i18n-routing/pages/gsp/[slug].js
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<add>import LocaleSwitcher from '../../components/locale-switcher'
<ide>
<ide> export default function GspPage(props) {
<ide> const router = useRouter()
<ide> export default function GspPage(props) {
<ide> <p>Default locale: {defaultLocale}</p>
<ide> <p>Configured locales: {JSON.stringify(props.locales)}</p>
<ide>
<add> <LocaleSwitcher />
<add>
<ide> <Link href="/gsp">
<ide> <a>To getStaticProps page</a>
<ide> </Link>
<ide><path>examples/i18n-routing/pages/gsp/index.js
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<add>import LocaleSwitcher from '../../components/locale-switcher'
<ide>
<ide> export default function GspPage(props) {
<ide> const router = useRouter()
<ide> export default function GspPage(props) {
<ide> <p>Default locale: {defaultLocale}</p>
<ide> <p>Configured locales: {JSON.stringify(props.locales)}</p>
<ide>
<add> <LocaleSwitcher />
<add>
<ide> <Link href="/gsp/first">
<ide> <a>To dynamic getStaticProps page</a>
<ide> </Link>
<ide><path>examples/i18n-routing/pages/gssp.js
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<add>import LocaleSwitcher from '../components/locale-switcher'
<ide>
<ide> export default function GsspPage(props) {
<ide> const router = useRouter()
<ide> export default function GsspPage(props) {
<ide> <p>Default locale: {defaultLocale}</p>
<ide> <p>Configured locales: {JSON.stringify(props.locales)}</p>
<ide>
<add> <LocaleSwitcher />
<add>
<ide> <Link href="/gsp">
<ide> <a>To getStaticProps page</a>
<ide> </Link>
<ide><path>examples/i18n-routing/pages/index.js
<ide> import Link from 'next/link'
<ide> import { useRouter } from 'next/router'
<add>import LocaleSwitcher from '../components/locale-switcher'
<ide>
<ide> export default function IndexPage(props) {
<ide> const router = useRouter()
<ide> export default function IndexPage(props) {
<ide> <p>Default locale: {defaultLocale}</p>
<ide> <p>Configured locales: {JSON.stringify(locales)}</p>
<ide>
<add> <LocaleSwitcher />
<add>
<ide> <Link href="/gsp">
<ide> <a>To getStaticProps page</a>
<ide> </Link>
| 5
|
Python
|
Python
|
fix dilated convolution for cntk backend.
|
d88f2006af35179b986479ac6ad5a20dac8ac9d1
|
<ide><path>keras/backend/cntk_backend.py
<ide> def conv2d(x, kernel, strides=(1, 1), padding='valid',
<ide> x = _preprocess_conv2d_input(x, data_format)
<ide> kernel = _preprocess_conv2d_kernel(kernel, data_format)
<ide> padding = _preprocess_border_mode(padding)
<del> if dilation_rate == (1, 1):
<del> strides = (1,) + strides
<del> x = C.convolution(
<del> kernel,
<del> x,
<del> strides,
<del> auto_padding=[
<del> False,
<del> padding,
<del> padding])
<del> else:
<del> assert dilation_rate[0] == dilation_rate[1]
<del> assert strides == (1, 1), 'Invalid strides for dilated convolution'
<del> x = C.convolution(
<del> kernel,
<del> x,
<del> strides=dilation_rate[0],
<del> auto_padding=[
<del> False,
<del> padding,
<del> padding])
<add>
<add> if dev.type() == 0 and dilation_rate != (1, 1):
<add> raise ValueError('Dilated convolution on CPU is not supported by CNTK backend. ' +
<add> 'Please set dilation_rate with (1, 1).')
<add>
<add> x = C.convolution(kernel,
<add> x,
<add> strides,
<add> auto_padding=[False, padding, padding],
<add> dilation=dilation_rate)
<add>
<ide> return _postprocess_conv2d_output(x, data_format)
<ide>
<ide>
<ide><path>tests/keras/layers/convolutional_test.py
<ide> def test_averagepooling_1d():
<ide>
<ide> @keras_test
<ide> @pytest.mark.skipif((K.backend() == 'cntk'),
<del> reason="cntk does not support dilated conv")
<add> reason="cntk only supports dilated conv on GPU")
<ide> def test_convolution_2d():
<ide> num_samples = 2
<ide> filters = 2
| 2
|
Python
|
Python
|
unify coding style
|
a85263fb3edee30623f7c9c1ffb6505b4f983d14
|
<ide><path>examples/variational_autoencoder_deconv.py
<ide> def sampling(args):
<ide> padding='same',
<ide> strides=1,
<ide> activation='relu')
<del>decoder_deconv_2 = Conv2DTranspose(filters, num_conv,
<add>decoder_deconv_2 = Conv2DTranspose(filters,
<add> kernel_size=num_conv,
<ide> padding='same',
<ide> strides=1,
<ide> activation='relu')
| 1
|
Go
|
Go
|
ignore cleanup with /dev/mapper does not exist
|
5dd12ba20a962c0f67e5eefb7b0e00e5caccb1e1
|
<ide><path>runtime_test.go
<ide> func cleanupDevMapper() error {
<ide> // Remove any leftover devmapper devices from previous unit run tests
<ide> infos, err := ioutil.ReadDir("/dev/mapper")
<ide> if err != nil {
<add> // If the mapper file does not exist there is nothing to clean up
<add> if os.IsNotExist(err) {
<add> return nil
<add> }
<ide> return err
<ide> }
<ide> pools := []string{}
<ide> func init() {
<ide> os.Setenv("TEST", "1")
<ide> os.Setenv("DOCKER_LOOPBACK_DATA_SIZE", "209715200") // 200MB
<ide> os.Setenv("DOCKER_LOOPBACK_META_SIZE", "104857600") // 100MB
<del> os.Setenv("DOCKER_BASE_FS_SIZE", "157286400") // 150MB
<add> os.Setenv("DOCKER_BASE_FS_SIZE", "157286400") // 150MB
<ide>
<ide> // Hack to run sys init during unit testing
<ide> if selfPath := utils.SelfPath(); selfPath == "/sbin/init" || selfPath == "/.dockerinit" {
| 1
|
Text
|
Text
|
fix wrong parameters
|
c5bfb97aa0704da69e002aa5288e39258853d11e
|
<ide><path>docs/recipes/ReducingBoilerplate.md
<ide> const ADD_TODO = 'ADD_TODO'
<ide> const EDIT_TODO = 'EDIT_TODO'
<ide> const REMOVE_TODO = 'REMOVE_TODO'
<ide>
<del>export const addTodo = makeActionCreator(ADD_TODO, 'todo')
<del>export const editTodo = makeActionCreator(EDIT_TODO, 'id', 'todo')
<add>export const addTodo = makeActionCreator(ADD_TODO, 'text')
<add>export const editTodo = makeActionCreator(EDIT_TODO, 'id', 'text')
<ide> export const removeTodo = makeActionCreator(REMOVE_TODO, 'id')
<ide> ```
<ide> There are also utility libraries to aid in generating action creators, such as [redux-act](https://github.com/pauldijou/redux-act) and [redux-actions](https://github.com/acdlite/redux-actions). These can help reduce boilerplate code and enforce adherence to standards such as [Flux Standard Action (FSA)](https://github.com/acdlite/flux-standard-action).
| 1
|
Text
|
Text
|
add the text of use of inheritance
|
9d8e538ac09e5a7310ae0a1e1b713efe8300382d
|
<ide><path>guide/english/java/inheritance/index.md
<ide> Java inheritance refers to the ability of a Java Class to `inherit` the properti
<ide> * The Class that extends or inherits is called a **subclass**
<ide> * The Class that is being extended or inherited is called a **superclass**
<ide>
<add>## Why use inheritance in java
<add>- For Method Overriding (so runtime polymorphism can be achieved).
<add>- For Code Reusability.
<add>
<add>## Terms used in Inheritance
<add>- Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created.
<add>- Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class.
<add>- Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class.
<add>- Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class.
<add>
<ide> Thus, inheritance gives Java the cool capability of _re-using_ code, or sharing code between classes!
<ide>
<ide> Let's describe it with the classic example of a `Vehicle` class and a `Car` class :
| 1
|
Javascript
|
Javascript
|
test only public api and use better test data
|
2fdbca0d8cc5575ca45a13820b5729109424ee32
|
<add><path>test/Connector.spec.js
<del><path>test/components/Connector.spec.js
<ide> // import expect from 'expect';
<del>// import { Connector } from '../../src';
<add>// import { Connector } from '../src';
<ide>
<ide> describe('Components', () => {
<ide> describe('Connector', () => {
<add><path>test/Provider.spec.js
<del><path>test/components/Provider.spec.js
<ide> // import expect from 'expect';
<del>// import { Provider } from '../../src';
<add>// import { Provider } from '../src';
<ide>
<ide> describe('Components', () => {
<ide> describe('Provider', () => {
<ide><path>test/Redux.spec.js
<del>import expect from 'expect';
<del>import Redux from '../src/Redux';
<del>
<del>const initialState = {};
<del>const fakeState = { foo: 'bar' };
<del>
<del>function fakeStore(state = initialState, action) {
<del> const { type } = action;
<del> if (type === 'FOO') {
<del> return action.body;
<del> }
<del> return state;
<del>}
<del>
<del>function foo() {
<del> return {
<del> type: 'FOO',
<del> body: fakeState
<del> };
<del>}
<del>
<del>describe('Redux', () => {
<del>
<del> let redux;
<del>
<del> beforeEach(() => {
<del> redux = new Redux({ fakeStore });
<del> });
<del>
<del> it('should correctly initialize', () => {
<del> expect(redux.state).toEqual({ fakeStore: {} });
<del> expect(redux.listeners).toEqual([]);
<del> expect(redux.dispatcher).toBeA('function');
<del> expect(redux.dispatchFn).toBeA('function');
<del> });
<del>
<del> it('should subscribe to changes', done => {
<del> let state = redux.getState();
<del> expect(state.fakeStore).toEqual({});
<del> redux.subscribe(() => {
<del> state = redux.getState();
<del> expect(state.fakeStore).toEqual(fakeState);
<del> done();
<del> });
<del> redux.dispatch(foo());
<del> });
<del>
<del> it('should unsubscribe a listener', () => {
<del> const changeListenerSpy = expect.createSpy(() => {});
<del> const unsubscribe = redux.subscribe(changeListenerSpy);
<del>
<del> expect(changeListenerSpy.calls.length).toBe(0);
<del>
<del> redux.setState(fakeState);
<del> expect(changeListenerSpy.calls.length).toBe(1);
<del>
<del> unsubscribe();
<del> redux.setState(fakeState);
<del> expect(changeListenerSpy.calls.length).toBe(1);
<del> });
<del>});
<ide><path>test/_helpers.js
<add>const ADD_TODO = 'ADD_TODO';
<add>const ADD_TODO_ASYNC = 'ADD_TODO_ASYNC';
<add>
<add>export const initialState = [];
<add>export const defaultText = 'Hello World!';
<add>export const constants = { ADD_TODO, ADD_TODO_ASYNC };
<add>
<add>export function todoStore(state = initialState, action) {
<add> const { type } = action;
<add> if (type === ADD_TODO || type === ADD_TODO_ASYNC) {
<add> return [{
<add> id: state[0] ? state[0].id + 1 : 1,
<add> text: action.text
<add> }, ...state];
<add> }
<add> return state;
<add>}
<add>
<add>export const todoActions = {
<add> addTodo(text) {
<add> return { type: ADD_TODO, text };
<add> },
<add>
<add> addTodoAsync(text, cb/* for testing only */) {
<add> return dispatch => {
<add> setTimeout(() => {
<add> dispatch({ type: ADD_TODO_ASYNC, text });
<add> cb();
<add> }, 500);
<add> };
<add> }
<add>};
<ide><path>test/bindActionCreators.spec.js
<add>import expect from 'expect';
<add>import { bindActionCreators, createRedux } from '../src';
<add>import * as helpers from './_helpers';
<add>
<add>const { todoActions, todoStore } = helpers;
<add>
<add>describe('Utils', () => {
<add> describe('bindActionCreators', () => {
<add>
<add> let redux;
<add>
<add> beforeEach(() => {
<add> redux = createRedux({ todoStore });
<add> });
<add>
<add> it('should bind given actions to the dispatcher', done => {
<add> let expectedCallCount = 2;
<add> // just for monitoring the dispatched actions
<add> redux.subscribe(() => {
<add> expectedCallCount--;
<add> if (expectedCallCount === 0) {
<add> const state = redux.getState();
<add> expect(state.todoStore).toEqual([
<add> { id: 2, text: 'World' },
<add> { id: 1, text: 'Hello' }
<add> ]);
<add> done();
<add> }
<add> });
<add> const actions = bindActionCreators(todoActions, redux.dispatch);
<add> expect(Object.keys(actions)).toEqual(Object.keys(todoActions));
<add>
<add> actions.addTodo('Hello');
<add> actions.addTodoAsync('World');
<add> });
<add> });
<add>});
<ide><path>test/compose.spec.js
<add>// import expect from 'expect';
<add>// import { compose } from '../src';
<add>
<add>describe('Utils', () => {
<add> describe('compose', () => {
<add>
<add> it('should call map stores');
<add> });
<add>});
<add><path>test/composeStores.spec.js
<del><path>test/utils/composeStores.spec.js
<ide> // import expect from 'expect';
<del>// import { composeStores } from '../../src';
<add>// import { composeStores } from '../src';
<ide>
<ide> describe('Utils', () => {
<ide> describe('composeStores', () => {
<add><path>test/connect.spec.js
<del><path>test/components/connect.spec.js
<ide> // import expect from 'expect';
<del>// import { connect } from '../../src';
<add>// import { connect } from '../src';
<ide>
<ide> describe('Decorators', () => {
<ide> describe('connect', () => {
<ide><path>test/createDispatcher.spec.js
<ide> import expect from 'expect';
<ide> import { createDispatcher, composeStores } from '../src';
<ide> import thunkMiddleware from '../src/middleware/thunk';
<add>import * as helpers from './_helpers';
<ide>
<del>const fakeState = { foo: 'bar' };
<del>const fakeAction = { type: 'FOO', foo: 'bar' };
<del>const fakeActionAsync = { type: 'FOO_ASYNC', fooAsync: 'barAsync' };
<del>
<del>function fakeStore(state = fakeState, action) {
<del> const { type } = action;
<del> if (type === 'FOO') {
<del> return action.foo;
<del> }
<del> if (type === 'FOO_ASYNC') {
<del> return action.fooAsync;
<del> }
<del> return state;
<del>}
<del>
<del>function foo() {
<del> return fakeAction;
<del>}
<del>
<del>function fooAsync(cb/* for testing only */) {
<del> return dispatch => {
<del> setTimeout(() => {
<del> dispatch(fakeActionAsync);
<del> cb();
<del> }, 500);
<del> };
<del>}
<add>const { constants, defaultText, todoActions, todoStore } = helpers;
<add>const { addTodo, addTodoAsync } = todoActions;
<add>const { ADD_TODO } = constants;
<ide>
<ide> describe('createDispatcher', () => {
<ide>
<ide> it('should handle sync and async dispatches', done => {
<ide> const spy = expect.createSpy(() => {});
<ide> const dispatcher = createDispatcher(
<del> composeStores({ fakeStore }),
<add> composeStores({ todoStore }),
<add> // we need this middleware to handle async actions
<ide> getState => [thunkMiddleware(getState)]);
<add>
<ide> expect(dispatcher).toBeA('function');
<ide>
<del> const dispatchFn = dispatcher(fakeState, spy);
<del> expect(spy).toHaveBeenCalledWith({ fakeStore: fakeState });
<add> const dispatchFn = dispatcher(undefined, spy);
<add> expect(spy.calls.length).toBe(1);
<add> expect(spy).toHaveBeenCalledWith({ todoStore: [] });
<ide>
<del> const fooAction = dispatchFn(foo());
<del> expect(fooAction).toEqual(fakeAction);
<add> const addTodoAction = dispatchFn(addTodo(defaultText));
<add> expect(addTodoAction).toEqual({ type: ADD_TODO, text: defaultText });
<ide> expect(spy.calls.length).toBe(2);
<del> expect(spy).toHaveBeenCalledWith({ fakeStore: 'bar' });
<add> expect(spy).toHaveBeenCalledWith({ todoStore: [
<add> { id: 1, text: defaultText }
<add> ] });
<ide>
<del> dispatchFn(fooAsync(() => {
<add> dispatchFn(addTodoAsync(('Say hi!'), () => {
<ide> expect(spy.calls.length).toBe(3);
<del> expect(spy).toHaveBeenCalledWith({ fakeStore: 'barAsync' });
<add> expect(spy).toHaveBeenCalledWith({ todoStore: [
<add> { id: 2, text: 'Say hi!' },
<add> { id: 1, text: defaultText }
<add> ] });
<ide> done();
<ide> }));
<ide> });
<ide><path>test/createRedux.spec.js
<ide> import expect from 'expect';
<ide> import { createRedux } from '../src';
<add>import * as helpers from './_helpers';
<ide>
<del>const fakeState = { foo: 'bar' };
<del>
<del>function fakeStore() {
<del> return fakeState;
<del>}
<add>const { defaultText, todoActions, todoStore } = helpers;
<add>const { addTodo } = todoActions;
<ide>
<ide> describe('createRedux', () => {
<ide>
<add> let redux;
<add>
<add> beforeEach(() => {
<add> redux = createRedux({ todoStore });
<add> });
<add>
<ide> it('should expose Redux public API', () => {
<del> const redux = createRedux({ fakeStore });
<ide> const methods = Object.keys(redux);
<ide>
<ide> expect(methods.length).toBe(5);
<ide> describe('createRedux', () => {
<ide> expect(methods).toContain('getDispatcher');
<ide> expect(methods).toContain('replaceDispatcher');
<ide> });
<add>
<add> it('should subscribe to changes', done => {
<add> let state = redux.getState();
<add> expect(state.todoStore).toEqual({});
<add> redux.subscribe(() => {
<add> state = redux.getState();
<add> expect(state.todoStore).toEqual([{ id: 1, text: 'Hello World!' }]);
<add> done();
<add> });
<add> redux.dispatch(addTodo(defaultText));
<add> });
<add>
<add> it('should unsubscribe a listener', () => {
<add> const changeListenerSpy = expect.createSpy(() => {});
<add> const unsubscribe = redux.subscribe(changeListenerSpy);
<add>
<add> expect(changeListenerSpy.calls.length).toBe(0);
<add>
<add> redux.dispatch(addTodo('Hello'));
<add> expect(redux.getState().todoStore).toEqual([{ id: 1, text: 'Hello'}]);
<add> expect(changeListenerSpy.calls.length).toBe(1);
<add>
<add> unsubscribe();
<add> redux.dispatch(addTodo('World'));
<add> expect(redux.getState().todoStore).toEqual([
<add> { id: 2, text: 'World'},
<add> { id: 1, text: 'Hello'}
<add> ]);
<add> expect(changeListenerSpy.calls.length).toBe(1);
<add> });
<ide> });
<ide><path>test/exports.spec.js
<del>import expect from 'expect';
<del>import * as redux from '../src';
<del>
<del>describe('Redux', () => {
<del>
<del> it('should export necessary components', () => {
<del> const imports = Object.keys(redux);
<del> expect(imports.length).toBe(9);
<del>
<del> expect(imports).toContain('createRedux');
<del> expect(imports).toContain('createDispatcher');
<del>
<del> expect(imports).toContain('Provider');
<del> expect(imports).toContain('Connector');
<del>
<del> expect(imports).toContain('provide');
<del> expect(imports).toContain('connect');
<del>
<del> expect(imports).toContain('compose');
<del> expect(imports).toContain('composeStores');
<del> expect(imports).toContain('bindActionCreators');
<del> });
<del>
<del>});
<add><path>test/getDisplayName.spec.js
<del><path>test/utils/getDisplayName.spec.js
<ide> import expect from 'expect';
<del>import getDisplayName from '../../src/utils/getDisplayName';
<add>import getDisplayName from '../src/utils/getDisplayName';
<ide>
<ide> describe('Utils', () => {
<ide> describe('getDisplayName', () => {
<add><path>test/provide.spec.js
<del><path>test/components/provide.spec.js
<ide> // import expect from 'expect';
<del>// import { provide } from '../../src';
<add>// import { provide } from '../src';
<ide>
<ide> describe('Decorators', () => {
<ide> describe('provide', () => {
<ide><path>test/utils/bindActionCreators.spec.js
<del>import expect from 'expect';
<del>import { bindActionCreators, createRedux } from '../../src';
<del>
<del>const fakeState = { foo: 'bar' };
<del>
<del>function fakeStore(state = 0, action) {
<del> if (action.type) {
<del> return fakeState;
<del> }
<del> return state;
<del>}
<del>
<del>const fakeActionCreators = {
<del> foo() {
<del> return { type: 'FOO' };
<del> },
<del> fooAsync() {
<del> return dispatch => {
<del> setTimeout(() => {
<del> dispatch({ type: 'FOO_ASYNC' });
<del> }, 1000);
<del> };
<del> }
<del>};
<del>
<del>describe('Utils', () => {
<del> describe('bindActionCreators', () => {
<del>
<del> let redux;
<del>
<del> beforeEach(() => {
<del> redux = createRedux({ fakeStore });
<del> });
<del>
<del> it('should bind given actions to the dispatcher', done => {
<del> let expectedCallCount = 2;
<del> // Let us subscribe to monitor the dispatched actions
<del> redux.subscribe(() => {
<del> expectedCallCount--;
<del> const state = redux.getState();
<del>
<del> expect(state.fakeStore).toEqual(fakeState);
<del> if (expectedCallCount === 0) { done(); }
<del> });
<del> const actions = bindActionCreators(fakeActionCreators, redux.dispatch);
<del> expect(Object.keys(actions))
<del> .toEqual(Object.keys(fakeActionCreators));
<del>
<del> actions.foo();
<del> actions.fooAsync();
<del> });
<del> });
<del>});
<ide><path>test/utils/shallowEqual.spec.js
<del>// import expect from 'expect';
<del>// import shallowEqual from '../../src/utils/shallowEqual';
<del>
<del>describe('Utils', () => {
<del> describe('shallowEqual', () => {
<del>
<del> it('should check if given objects have equal properties');
<del> });
<del>});
<ide><path>test/utils/shallowEqualScalar.spec.js
<del>// import expect from 'expect';
<del>// import shallowEqualScalar from '../../src/utils/shallowEqualScalar';
<del>
<del>describe('Utils', () => {
<del> describe('shallowEqualScalar', () => {
<del>
<del> it('should check if given objects have equal properties');
<del> });
<del>});
| 16
|
Python
|
Python
|
fix backup tests
|
6ef330e9672688aa3a58821c011be84eaa3d0259
|
<ide><path>libcloud/test/backup/test_dimensiondata_v2_3.py
<ide> from libcloud.backup.drivers.dimensiondata import DEFAULT_BACKUP_PLAN
<ide>
<ide> from libcloud.test import MockHttp, unittest
<del>from libcloud.test.backup import TestCaseMixin
<ide> from libcloud.test.file_fixtures import BackupFileFixtures
<ide>
<ide> from libcloud.test.secrets import DIMENSIONDATA_PARAMS
<ide>
<ide>
<del>class DimensionData_v2_3_Tests(unittest.TestCase, TestCaseMixin):
<add>class DimensionData_v2_3_Tests(unittest.TestCase):
<ide>
<ide> def setUp(self):
<ide> DimensionData.connectionCls.active_api_version = '2.3'
<ide><path>libcloud/test/backup/test_dimensiondata_v2_4.py
<ide> from libcloud.backup.drivers.dimensiondata import DEFAULT_BACKUP_PLAN
<ide>
<ide> from libcloud.test import MockHttp, unittest
<del>from libcloud.test.backup import TestCaseMixin
<ide> from libcloud.test.file_fixtures import BackupFileFixtures
<ide>
<ide> from libcloud.test.secrets import DIMENSIONDATA_PARAMS
<ide>
<ide>
<del>class DimensionData_v2_4_Tests(unittest.TestCase, TestCaseMixin):
<add>class DimensionData_v2_4_Tests(unittest.TestCase):
<ide>
<ide> def setUp(self):
<ide> DimensionData.connectionCls.active_api_version = '2.4'
| 2
|
Ruby
|
Ruby
|
fix kwarg to not have circular dependency
|
f6628adc11e2e57db75030fca9bae035be5cd95b
|
<ide><path>activerecord/lib/active_record/migration.rb
<ide> def initialize(env = "production")
<ide> end
<ide>
<ide> class EnvironmentMismatchError < ActiveRecordError
<del> def initialize(current: current, stored: stored)
<add> def initialize(current: , stored: )
<ide> msg = "You are attempting to modify a database that was last run in #{ stored } environment.\n"
<ide> msg << "You are running in #{ current } environment."
<ide> msg << "if you are sure you want to continue, run the same command with the environment variable\n"
| 1
|
Python
|
Python
|
remove unused util function
|
1f9f867c70fc76ae1c0b307e38997c17e084c051
|
<ide><path>spacy/util.py
<ide> def ensure_path(path):
<ide> return path
<ide>
<ide>
<del>def or_(val1, val2):
<del> if val1 is not None:
<del> return val1
<del> elif callable(val2):
<del> return val2()
<del> else:
<del> return val2
<del>
<del>
<ide> def read_regex(path):
<ide> path = ensure_path(path)
<ide> with path.open() as file_:
| 1
|
PHP
|
PHP
|
add start helper method
|
f5e95c357c93f6cc60ce9f2aa3bfc7e218e6a6f3
|
<ide><path>src/Illuminate/Console/Application.php
<ide> class Application extends \Symfony\Component\Console\Application {
<ide> */
<ide> protected $laravel;
<ide>
<add> /**
<add> * Create and boot a new Console application.
<add> *
<add> * @param \Illuminate\Foundation\Application $app
<add> * @return \Illuminate\Console\Application
<add> */
<add> public static function start($app)
<add> {
<add> return static::make($app)->boot();
<add> }
<add>
<ide> /**
<ide> * Create a new Console application.
<ide> *
<ide> public static function make($app)
<ide> /**
<ide> * Boot the Console application.
<ide> *
<del> * @return void
<add> * @return \Illuminate\Console\Application
<ide> */
<ide> public function boot()
<ide> {
| 1
|
Python
|
Python
|
add colors to airflow config command
|
d711dca697868e6c3fc65bd38bf75e68c7bfd88b
|
<ide><path>airflow/cli/cli_parser.py
<ide> from airflow.configuration import conf
<ide> from airflow.exceptions import AirflowException
<ide> from airflow.executors.executor_loader import ExecutorLoader
<add>from airflow.utils.cli import ColorMode
<ide> from airflow.utils.helpers import partition
<ide> from airflow.utils.module_loading import import_string
<ide> from airflow.utils.timezone import parse as parsedate
<ide> def __init__(self, flags=None, help=None, action=None, default=None, nargs=None,
<ide> ),
<ide> choices=tabulate_formats,
<ide> default="fancy_grid")
<add>ARG_COLOR = Arg(
<add> ('--color',),
<add> help="Do emit colored output (default: auto)",
<add> choices={ColorMode.ON, ColorMode.OFF, ColorMode.AUTO},
<add> default=ColorMode.AUTO)
<ide>
<ide> # list_dag_runs
<ide> ARG_NO_BACKFILL = Arg(
<ide> class GroupCommand(NamedTuple):
<ide> name='config',
<ide> help='Show current application configuration',
<ide> func=lazy_load_command('airflow.cli.commands.config_command.show_config'),
<del> args=(),
<add> args=(ARG_COLOR, ),
<ide> ),
<ide> ActionCommand(
<ide> name='info',
<ide><path>airflow/cli/commands/config_command.py
<ide> """Config sub-commands"""
<ide> import io
<ide>
<add>import pygments
<add>from pygments.formatters.terminal import TerminalFormatter
<add>from pygments.lexers.configs import IniLexer
<add>
<ide> from airflow.configuration import conf
<add>from airflow.utils.cli import should_use_colors
<ide>
<ide>
<ide> def show_config(args):
<ide> """Show current application configuration"""
<ide> with io.StringIO() as output:
<ide> conf.write(output)
<del> print(output.getvalue())
<add> code = output.getvalue()
<add> if should_use_colors(args):
<add> code = pygments.highlight(
<add> code=code, formatter=TerminalFormatter(), lexer=IniLexer()
<add> )
<add> print(code)
<ide><path>airflow/utils/cli.py
<ide> def sigquit_handler(sig, frame): # pylint: disable=unused-argument
<ide> if line:
<ide> code.append(" {}".format(line.strip()))
<ide> print("\n".join(code))
<add>
<add>
<add>def is_terminal_support_colors() -> bool:
<add> """"
<add> Try to determine if the current terminal supports colors.
<add> """
<add> if sys.platform == 'win32':
<add> return False
<add> if not hasattr(sys.stdout, 'isatty'):
<add> return False
<add> if not sys.stdout.isatty():
<add> return False
<add> if 'COLORTERM' in os.environ:
<add> return True
<add> term = os.environ.get('TERM', 'dumb').lower()
<add> if term in ('xterm', 'linux') or 'color' in term:
<add> return True
<add> return False
<add>
<add>
<add>class ColorMode:
<add> """
<add> Coloring modes. If `auto` is then automatically detected.
<add> """
<add> ON = "on"
<add> OFF = "off"
<add> AUTO = "auto"
<add>
<add>
<add>def should_use_colors(args) -> bool:
<add> """
<add> Processes arguments and decides whether to enable color in output
<add> """
<add> if args.color == ColorMode.ON:
<add> return True
<add> if args.color == ColorMode.OFF:
<add> return False
<add> return is_terminal_support_colors()
| 3
|
Javascript
|
Javascript
|
use all imports in a concatenated module
|
abff6b780579babd623824722a17f66246015a13
|
<ide><path>lib/optimize/ConcatenatedModule.js
<ide> const HarmonyExportImportedSpecifierDependency = require("../dependencies/Harmon
<ide> const HarmonyCompatibilityDependency = require("../dependencies/HarmonyCompatibilityDependency");
<ide> const HarmonyModulesHelpers = require("../dependencies/HarmonyModulesHelpers");
<ide>
<del>function findLastIndex(array, predicate) {
<del> for(let i = array.length - 1; i >= 0; i--) {
<del> if(predicate(array[i]))
<del> return i;
<del> }
<del> return -1;
<del>}
<del>
<ide> function ensureNsObjSource(info, moduleToInfoMap, requestShortener) {
<ide> if(!info.hasNamespaceObject) {
<ide> info.hasNamespaceObject = true;
<ide> const name = info.exportMap.get(true);
<ide> const nsObj = [`var ${name} = {};`];
<ide> for(const exportName of info.module.providedExports) {
<del> const finalName = getFinalName(info, exportName, moduleToInfoMap, requestShortener);
<add> const finalName = getFinalName(info, exportName, moduleToInfoMap, requestShortener, false);
<ide> nsObj.push(`__webpack_require__.d(${name}, ${JSON.stringify(exportName)}, function() { return ${finalName}; });`);
<ide> }
<ide> info.namespaceObjectSource = nsObj.join("\n") + "\n";
<ide> }
<ide> }
<ide>
<del>function getFinalName(info, exportName, moduleToInfoMap, requestShortener) {
<del> const directExport = info.exportMap.get(exportName);
<del> if(directExport) {
<del> if(exportName === true)
<del> ensureNsObjSource(info, moduleToInfoMap, requestShortener);
<del> const name = info.internalNames.get(directExport);
<del> if(!name)
<del> throw new Error(`The export "${directExport}" in "${info.module.readableIdentifier(requestShortener)}" has no internal name`);
<del> return name;
<del> }
<del> const reexport = info.reexportMap.get(exportName);
<del> if(reexport) {
<del> const refInfo = moduleToInfoMap.get(reexport.module);
<del> if(refInfo) {
<del> // module is in the concatenation
<del> return getFinalName(refInfo, reexport.exportName, moduleToInfoMap, requestShortener);
<del> } else {
<del> const dep = reexport.dependency;
<del> const importedModule = reexport.module;
<del> const exportName = reexport.exportName;
<del> const isHarmonyModule = importedModule && (!importedModule.meta || importedModule.meta.harmonyModule);
<del> const importedVar = dep.importedVar;
<del> const used = importedModule.isUsed(exportName);
<del> if(!used) return "/* unused reexport */undefined";
<del> if(!isHarmonyModule && exportName === "default") {
<del> return `${importedVar}_default.a`;
<add>function getExternalImport(importedModule, importedVar, exportName, asCall) {
<add> const isHarmonyModule = importedModule && (!importedModule.meta || importedModule.meta.harmonyModule);
<add> if(exportName === true) return importedVar;
<add> const used = importedModule.isUsed(exportName);
<add> if(!used) return "/* unused reexport */undefined";
<add> if(!isHarmonyModule && exportName === "default") {
<add> return asCall ? `${importedVar}_default()` : `${importedVar}_default.a`;
<add> }
<add> if(asCall)
<add> return `Object(${importedVar}[${JSON.stringify(used)}])`;
<add> return `${importedVar}[${JSON.stringify(used)}]`;
<add>}
<add>
<add>function getFinalName(info, exportName, moduleToInfoMap, requestShortener, asCall) {
<add> switch(info.type) {
<add> case "concatenated":
<add> {
<add> const directExport = info.exportMap.get(exportName);
<add> if(directExport) {
<add> if(exportName === true)
<add> ensureNsObjSource(info, moduleToInfoMap, requestShortener);
<add> const name = info.internalNames.get(directExport);
<add> if(!name)
<add> throw new Error(`The export "${directExport}" in "${info.module.readableIdentifier(requestShortener)}" has no internal name`);
<add> return name;
<add> }
<add> const reexport = info.reexportMap.get(exportName);
<add> if(reexport) {
<add> const refInfo = moduleToInfoMap.get(reexport.module);
<add> if(refInfo) {
<add> // module is in the concatenation
<add> return getFinalName(refInfo, reexport.exportName, moduleToInfoMap, requestShortener, asCall);
<add> } else {
<add> const dep = reexport.dependency;
<add> const importedModule = reexport.module;
<add> const exportName = reexport.exportName;
<add> const importedVar = dep.importedVar;
<add> return getExternalImport(importedModule, importedVar, exportName, asCall);
<add> }
<add> }
<add> throw new Error(`Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier(requestShortener)}"` +
<add> ` (known exports: ${Array.from(info.exportMap.keys()).join(" ")}, ` +
<add> `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`);
<add> }
<add> case "external":
<add> {
<add> const importedModule = info.module;
<add> return getExternalImport(importedModule, info.name, exportName, asCall);
<ide> }
<del> return `${importedVar}[${JSON.stringify(used)}]`;
<del> }
<ide> }
<del> throw new Error(`Cannot get final name for export "${exportName}" in "${info.module.readableIdentifier(requestShortener)}"` +
<del> ` (known exports: ${Array.from(info.exportMap.keys()).join(" ")}, ` +
<del> `known reexports: ${Array.from(info.reexportMap.keys()).join(" ")})`);
<ide> }
<ide>
<ide> function getSymbolsFromScope(s, untilScope) {
<ide> class ConcatenatedModule extends Module {
<ide>
<ide> _createOrderedConcatenationList(rootModule, modulesSet) {
<ide> const list = [];
<add> const set = new Set();
<ide>
<ide> function getConcatenatedImports(module) {
<ide> // TODO need changes when merging with the pure-module branch
<ide> const allDeps = module.dependencies
<ide> .filter(dep => dep instanceof HarmonyImportDependency && dep.module);
<ide>
<del> const lastConcatenatedItem = findLastIndex(allDeps, dep => modulesSet.has(dep.module));
<del>
<del> if(lastConcatenatedItem === -1) return [];
<del>
<del> return allDeps.slice(0, lastConcatenatedItem + 1).map(dep => dep.module);
<add> return allDeps.map(dep => dep.module);
<ide> }
<ide>
<ide> function enterModule(module) {
<add> if(set.has(module)) return;
<add> set.add(module);
<ide> if(modulesSet.has(module)) {
<ide> const imports = getConcatenatedImports(module);
<ide> imports.forEach(enterModule);
<ide> class ConcatenatedModule extends Module {
<ide> source(dependencyTemplates, outputOptions, requestShortener) {
<ide> const modulesSet = this._modulesSet;
<ide>
<del> const modules = this._orderedConcatenationList.filter(item => item.type === "concatenated").map(item => item.module);
<del>
<ide> // Metainfo for each module
<del> const modulesWithInfo = modules.map((m, idx) => {
<del> const exportMap = new Map();
<del> const reexportMap = new Map();
<del> m.dependencies.forEach(dep => {
<del> if(dep instanceof HarmonyExportSpecifierDependency) {
<del> exportMap.set(dep.name, dep.id);
<del> } else if(dep instanceof HarmonyExportExpressionDependency) {
<del> exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__");
<del> } else if(dep instanceof HarmonyExportImportedSpecifierDependency) {
<del> const exportName = dep.name;
<del> const importName = dep.id;
<del> const importModule = dep.importDependency.module;
<del> const innerReexport = modulesSet.has(importModule);
<del> if(exportName && importName) {
<del> reexportMap.set(exportName, {
<del> module: importModule,
<del> exportName: importName,
<del> dependency: dep
<del> });
<del> } else if(exportName) {
<del> reexportMap.set(exportName, {
<del> module: importModule,
<del> exportName: true,
<del> dependency: dep
<del> });
<del> } else if(Array.isArray(importModule.providedExports)) {
<del> var activeExports = new Set(HarmonyModulesHelpers.getActiveExports(dep.originModule, dep));
<del> importModule.providedExports.forEach(name => {
<del> if(activeExports.has(name) || name === "default")
<del> return;
<del> reexportMap.set(name, {
<del> module: importModule,
<del> exportName: name,
<del> dependency: dep
<del> });
<add> const modulesWithInfo = this._orderedConcatenationList.map((info, idx) => {
<add> switch(info.type) {
<add> case "concatenated":
<add> {
<add> const exportMap = new Map();
<add> const reexportMap = new Map();
<add> info.module.dependencies.forEach(dep => {
<add> if(dep instanceof HarmonyExportSpecifierDependency) {
<add> exportMap.set(dep.name, dep.id);
<add> } else if(dep instanceof HarmonyExportExpressionDependency) {
<add> exportMap.set("default", "__WEBPACK_MODULE_DEFAULT_EXPORT__");
<add> } else if(dep instanceof HarmonyExportImportedSpecifierDependency) {
<add> const exportName = dep.name;
<add> const importName = dep.id;
<add> const importModule = dep.importDependency.module;
<add> const innerReexport = modulesSet.has(importModule);
<add> if(exportName && importName) {
<add> reexportMap.set(exportName, {
<add> module: importModule,
<add> exportName: importName,
<add> dependency: dep
<add> });
<add> } else if(exportName) {
<add> reexportMap.set(exportName, {
<add> module: importModule,
<add> exportName: true,
<add> dependency: dep
<add> });
<add> } else if(Array.isArray(importModule.providedExports)) {
<add> var activeExports = new Set(HarmonyModulesHelpers.getActiveExports(dep.originModule, dep));
<add> importModule.providedExports.forEach(name => {
<add> if(activeExports.has(name) || name === "default")
<add> return;
<add> reexportMap.set(name, {
<add> module: importModule,
<add> exportName: name,
<add> dependency: dep
<add> });
<add> });
<add> } else if(innerReexport) {
<add> throw new Error(`Module "${importModule.readableIdentifier(requestShortener)}" doesn't provide static exports for "export *" in ${info.module.readableIdentifier(requestShortener)}`);
<add> }
<add> }
<ide> });
<del> } else if(innerReexport) {
<del> throw new Error(`Module "${importModule.readableIdentifier(requestShortener)}" doesn't provide static exports for "export *" in ${m.readableIdentifier(requestShortener)}`);
<add> return {
<add> type: "concatenated",
<add> module: info.module,
<add> index: idx,
<add> ast: undefined,
<add> source: undefined,
<add> globalScope: undefined,
<add> moduleScope: undefined,
<add> internalNames: new Map(),
<add> exportMap: exportMap,
<add> reexportMap: reexportMap,
<add> needCompatibilityFlag: false,
<add> hasNamespaceObject: false,
<add> namespaceObjectSource: null
<add> };
<ide> }
<del> }
<del> });
<del> return {
<del> module: m,
<del> index: idx,
<del> ast: undefined,
<del> source: undefined,
<del> globalScope: undefined,
<del> moduleScope: undefined,
<del> internalNames: new Map(),
<del> exportMap: exportMap,
<del> reexportMap: reexportMap,
<del> needCompatibilityFlag: false,
<del> hasNamespaceObject: false,
<del> namespaceObjectSource: null
<del> };
<add> case "external":
<add> return {
<add> type: "external",
<add> module: info.module,
<add> index: idx,
<add> name: undefined
<add> };
<add> default:
<add> throw new Error(`Unsupported concatenation entry type ${info.type}`);
<add> }
<ide> });
<ide>
<ide> // Create mapping from module to info
<ide> class ConcatenatedModule extends Module {
<ide> // Generate source code and analyse scopes
<ide> // Prepare a ReplaceSource for the final source
<ide> modulesWithInfo.forEach(info => {
<del> const m = info.module;
<del> const source = m.source(innerDependencyTemplates, outputOptions, requestShortener);
<del> const code = source.source();
<del> let ast;
<del> try {
<del> ast = acorn.parse(code, {
<del> ranges: true,
<del> locations: true,
<del> ecmaVersion: Parser.ECMA_VERSION,
<del> sourceType: "module"
<del> });
<del> } catch(err) {
<del> if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
<del> const lineNumber = err.loc.line;
<del> const lines = code.split("\n");
<del> err.message += "\n| " + lines.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
<add> if(info.type === "concatenated") {
<add> const m = info.module;
<add> const source = m.source(innerDependencyTemplates, outputOptions, requestShortener);
<add> const code = source.source();
<add> let ast;
<add> try {
<add> ast = acorn.parse(code, {
<add> ranges: true,
<add> locations: true,
<add> ecmaVersion: Parser.ECMA_VERSION,
<add> sourceType: "module"
<add> });
<add> } catch(err) {
<add> if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
<add> const lineNumber = err.loc.line;
<add> const lines = code.split("\n");
<add> err.message += "\n| " + lines.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
<add> }
<add> throw err;
<ide> }
<del> throw err;
<add> const scopeManager = escope.analyze(ast, {
<add> ecmaVersion: 6,
<add> sourceType: "module",
<add> optimistic: true,
<add> ignoreEval: true,
<add> impliedStrict: true
<add> });
<add> const globalScope = scopeManager.acquire(ast);
<add> const moduleScope = globalScope.childScopes[0];
<add> const resultSource = new ReplaceSource(source);
<add> info.ast = ast;
<add> info.source = resultSource;
<add> info.globalScope = globalScope;
<add> info.moduleScope = moduleScope;
<ide> }
<del> const scopeManager = escope.analyze(ast, {
<del> ecmaVersion: 6,
<del> sourceType: "module",
<del> optimistic: true,
<del> ignoreEval: true,
<del> impliedStrict: true
<del> });
<del> const globalScope = scopeManager.acquire(ast);
<del> const moduleScope = globalScope.childScopes[0];
<del> const resultSource = new ReplaceSource(source);
<del> info.ast = ast;
<del> info.source = resultSource;
<del> info.globalScope = globalScope;
<del> info.moduleScope = moduleScope;
<ide> });
<ide>
<ide> // List of all used names to avoid conflicts
<ide> const allUsedNames = new Set(["__WEBPACK_MODULE_DEFAULT_EXPORT__", "defaultExport", "Object"]);
<ide>
<ide> // get all global names
<ide> modulesWithInfo.forEach(info => {
<del> info.globalScope.through.forEach(reference => {
<del> const name = reference.identifier.name;
<del> if(/^__WEBPACK_MODULE_REFERENCE__\d+_(\d+|ns)__$/.test(name)) {
<del> for(const s of getSymbolsFromScope(reference.from, info.moduleScope)) {
<del> allUsedNames.add(s);
<add> if(info.globalScope) {
<add> info.globalScope.through.forEach(reference => {
<add> const name = reference.identifier.name;
<add> if(/^__WEBPACK_MODULE_REFERENCE__\d+_(\d+|ns)(_call)?__$/.test(name)) {
<add> for(const s of getSymbolsFromScope(reference.from, info.moduleScope)) {
<add> allUsedNames.add(s);
<add> }
<add> } else {
<add> allUsedNames.add(name);
<ide> }
<del> } else {
<del> allUsedNames.add(name);
<del> }
<del> });
<add> });
<add> }
<ide> });
<ide>
<add> // generate names for symbols
<ide> modulesWithInfo.forEach(info => {
<del> const namespaceObjectName = this.findNewName("namespaceObject", allUsedNames, null, info.module.readableIdentifier(requestShortener));
<del> allUsedNames.add(namespaceObjectName);
<del> info.internalNames.set(namespaceObjectName, namespaceObjectName);
<del> info.exportMap.set(true, namespaceObjectName);
<del> info.moduleScope.variables.forEach(variable => {
<del> const name = variable.name;
<del> if(allUsedNames.has(name)) {
<del> const references = getAllReferences(variable);
<del> const symbolsInReferences = references.map(ref => getSymbolsFromScope(ref.from, info.moduleScope)).reduce(reduceSet, new Set());
<del> const newName = this.findNewName(name, allUsedNames, symbolsInReferences, info.module.readableIdentifier(requestShortener));
<del> allUsedNames.add(newName);
<del> info.internalNames.set(name, newName);
<del> const source = info.source;
<del> const allIdentifiers = new Set(references.map(r => r.identifier).concat(variable.identifiers));
<del> for(const identifier of allIdentifiers) {
<del> const r = identifier.range;
<del> const path = getPathInAst(info.ast, identifier);
<del> if(path && path.length > 1 && path[1].type === "Property" && path[1].shorthand) {
<del> source.insert(r[1], `: ${newName}`);
<del> } else {
<del> source.replace(r[0], r[1] - 1, newName);
<del> }
<add> switch(info.type) {
<add> case "concatenated":
<add> {
<add> const namespaceObjectName = this.findNewName("namespaceObject", allUsedNames, null, info.module.readableIdentifier(requestShortener));
<add> allUsedNames.add(namespaceObjectName);
<add> info.internalNames.set(namespaceObjectName, namespaceObjectName);
<add> info.exportMap.set(true, namespaceObjectName);
<add> info.moduleScope.variables.forEach(variable => {
<add> const name = variable.name;
<add> if(allUsedNames.has(name)) {
<add> const references = getAllReferences(variable);
<add> const symbolsInReferences = references.map(ref => getSymbolsFromScope(ref.from, info.moduleScope)).reduce(reduceSet, new Set());
<add> const newName = this.findNewName(name, allUsedNames, symbolsInReferences, info.module.readableIdentifier(requestShortener));
<add> allUsedNames.add(newName);
<add> info.internalNames.set(name, newName);
<add> const source = info.source;
<add> const allIdentifiers = new Set(references.map(r => r.identifier).concat(variable.identifiers));
<add> for(const identifier of allIdentifiers) {
<add> const r = identifier.range;
<add> const path = getPathInAst(info.ast, identifier);
<add> if(path && path.length > 1 && path[1].type === "Property" && path[1].shorthand) {
<add> source.insert(r[1], `: ${newName}`);
<add> } else {
<add> source.replace(r[0], r[1] - 1, newName);
<add> }
<add> }
<add> } else {
<add> allUsedNames.add(name);
<add> info.internalNames.set(name, name);
<add> }
<add> });
<add> break;
<ide> }
<del> } else {
<del> allUsedNames.add(name);
<del> info.internalNames.set(name, name);
<del> }
<del> });
<add> case "external":
<add> {
<add> const externalName = this.findNewName("externalModule", allUsedNames, null, info.module.readableIdentifier(requestShortener));
<add> allUsedNames.add(externalName);
<add> info.name = externalName;
<add> break;
<add> }
<add> }
<ide> });
<ide>
<add> // Find and replace referenced to modules
<ide> modulesWithInfo.forEach(info => {
<del> info.globalScope.through.forEach(reference => {
<del> const name = reference.identifier.name;
<del> const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_(\d+|ns)__$/.exec(name);
<del> if(match) {
<del> const referencedModule = modulesWithInfo[+match[1]];
<del> let exportName;
<del> if(match[2] === "ns") {
<del> exportName = true;
<del> } else {
<del> const exportIdx = +match[2];
<del> exportName = referencedModule.module.providedExports[exportIdx];
<add> if(info.type === "concatenated") {
<add> info.globalScope.through.forEach(reference => {
<add> const name = reference.identifier.name;
<add> const match = /^__WEBPACK_MODULE_REFERENCE__(\d+)_(\d+|ns)(_call)?__$/.exec(name);
<add> if(match) {
<add> const referencedModule = modulesWithInfo[+match[1]];
<add> let exportName;
<add> if(match[2] === "ns") {
<add> exportName = true;
<add> } else {
<add> const exportIdx = +match[2];
<add> exportName = referencedModule.module.providedExports[exportIdx];
<add> }
<add> const asCall = !!match[3];
<add> const finalName = getFinalName(referencedModule, exportName, moduleToInfoMap, requestShortener, asCall);
<add> const r = reference.identifier.range;
<add> const source = info.source;
<add> source.replace(r[0], r[1] - 1, finalName);
<ide> }
<del> const finalName = getFinalName(referencedModule, exportName, moduleToInfoMap, requestShortener);
<del> const r = reference.identifier.range;
<del> const source = info.source;
<del> source.replace(r[0], r[1] - 1, finalName);
<del> }
<del> });
<add> });
<add> }
<ide> });
<ide>
<ide> const result = new ConcatSource();
<ide> if(moduleToInfoMap.get(this.rootModule).needCompatibilityFlag) {
<ide> result.add(`Object.defineProperty(${this.exportsArgument || "exports"}, "__esModule", { value: true });\n`);
<ide> }
<del> this._orderedConcatenationList.forEach(entry => {
<del> switch(entry.type) {
<add> modulesWithInfo.forEach(info => {
<add> switch(info.type) {
<ide> case "concatenated":
<del> {
<del> result.add(`\n// CONCATENATED MODULE: ${entry.module.readableIdentifier(requestShortener)}\n`);
<del> const info = moduleToInfoMap.get(entry.module);
<del> if(info.namespaceObjectSource) {
<del> result.add(info.namespaceObjectSource);
<del> }
<del> result.add(info.source);
<del> break;
<add> result.add(`\n// CONCATENATED MODULE: ${info.module.readableIdentifier(requestShortener)}\n`);
<add> if(info.namespaceObjectSource) {
<add> result.add(info.namespaceObjectSource);
<ide> }
<add> result.add(info.source);
<add> break;
<ide> case "external":
<del> result.add(`\n// EXTERNAL MODULE: ${entry.module.readableIdentifier(requestShortener)}\n__webpack_require__(${entry.module.id});\n`);
<add> result.add(`\n// EXTERNAL MODULE: ${info.module.readableIdentifier(requestShortener)}\n`);
<add> result.add(`var ${info.name} = __webpack_require__(${info.module.id});\n`);
<add> if(info.module.meta && !info.module.meta.harmonyModule) {
<add> result.add(`var ${info.name}_default = /*#__PURE__*/__webpack_require__.n(${info.name});\n`);
<add> }
<ide> break;
<ide> default:
<del> throw new Error(`Unsupported concatenation entry type ${entry.type}`);
<add> throw new Error(`Unsupported concatenation entry type ${info.type}`);
<ide> }
<ide> });
<ide>
<ide> class HarmonyImportSpecifierDependencyConcatenatedTemplate {
<ide> content = `__WEBPACK_MODULE_REFERENCE__${info.index}_ns__[${JSON.stringify(dep.id)}]`;
<ide> } else {
<ide> const exportIdx = (module.providedExports).indexOf(dep.id);
<del> content = exportIdx === -1 ? "undefined" : `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportIdx}__`;
<add> content = exportIdx === -1 ? "undefined" : `__WEBPACK_MODULE_REFERENCE__${info.index}_${exportIdx}${dep.call ? "_call" : ""}__`;
<ide> }
<ide> if(dep.shorthand) {
<ide> content = dep.name + ": " + content;
| 1
|
Javascript
|
Javascript
|
fix camerarollexample crash
|
2554f263874de792496fd566516bc36c3cc8c0c8
|
<ide><path>Examples/UIExplorer/js/CameraRollExample.js
<ide> const {
<ide> TouchableOpacity
<ide> } = ReactNative;
<ide>
<add>const invariant = require('invariant');
<add>
<ide> const CameraRollView = require('./CameraRollView');
<ide>
<ide> const AssetScaledImageExampleView = require('./AssetScaledImageExample');
<ide>
<del>const CAMERA_ROLL_VIEW = 'camera_roll_view';
<del>
<ide> class CameraRollExample extends React.Component {
<ide> state = {
<ide> groupTypes: 'SavedPhotos',
<ide> sliderValue: 1,
<ide> bigImages: true,
<ide> };
<del>
<add> _cameraRollView: ?CameraRollView;
<ide> render() {
<ide> return (
<ide> <View>
<ide> <Switch
<ide> onValueChange={this._onSwitchChange}
<del> value={this.state.bigImages} />
<add> value={this.state.bigImages}
<add> />
<ide> <Text>{(this.state.bigImages ? 'Big' : 'Small') + ' Images'}</Text>
<ide> <Slider
<ide> value={this.state.sliderValue}
<ide> onValueChange={this._onSliderChange}
<ide> />
<ide> <Text>{'Group Type: ' + this.state.groupTypes}</Text>
<ide> <CameraRollView
<del> ref={CAMERA_ROLL_VIEW}
<add> ref={(ref) => { this._cameraRollView = ref; }}
<ide> batchSize={20}
<ide> groupTypes={this.state.groupTypes}
<ide> renderImage={this._renderImage}
<ide> class CameraRollExample extends React.Component {
<ide> _renderImage = (asset) => {
<ide> const imageSize = this.state.bigImages ? 150 : 75;
<ide> const imageStyle = [styles.image, {width: imageSize, height: imageSize}];
<del> const location = asset.node.location.longitude ?
<del> JSON.stringify(asset.node.location) : 'Unknown location';
<add> const {location} = asset.node;
<add> const locationStr = location ? JSON.stringify(location) : 'Unknown location';
<ide> return (
<ide> <TouchableOpacity key={asset} onPress={ this.loadAsset.bind( this, asset ) }>
<ide> <View style={styles.row}>
<ide> class CameraRollExample extends React.Component {
<ide> />
<ide> <View style={styles.info}>
<ide> <Text style={styles.url}>{asset.node.image.uri}</Text>
<del> <Text>{location}</Text>
<add> <Text>{locationStr}</Text>
<ide> <Text>{asset.node.group_name}</Text>
<ide> <Text>{new Date(asset.node.timestamp).toString()}</Text>
<ide> </View>
<ide> class CameraRollExample extends React.Component {
<ide> };
<ide>
<ide> _onSwitchChange = (value) => {
<del> this.refs[CAMERA_ROLL_VIEW].rendererChanged();
<add> invariant(this._cameraRollView, 'ref should be set');
<add> this._cameraRollView.rendererChanged();
<ide> this.setState({ bigImages: value });
<ide> };
<ide> }
| 1
|
Ruby
|
Ruby
|
add xit to github_prerelease_allowlist
|
aad02c4524199f6e558609dc4b62860783da8d25
|
<ide><path>Library/Homebrew/utils/shared_audits.rb
<ide> def github_release_data(user, repo, tag)
<ide> "telegram-cli" => "1.3.1",
<ide> "toggl-track" => :all,
<ide> "volta" => "0.8.6",
<add> "xit" => :all,
<ide> }.freeze
<ide>
<ide> def github_release(user, repo, tag, formula: nil, cask: nil)
| 1
|
Javascript
|
Javascript
|
remove old css prefixes
|
39fc61d2c4aa2c7db9a0ede6aee1fd4264838bde
|
<ide><path>examples/js/renderers/CSS2DRenderer.js
<ide> THREE.CSS2DRenderer = function () {
<ide> vector.applyMatrix4( viewProjectionMatrix );
<ide>
<ide> var element = object.element;
<del> var style = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
<del>
<del> element.style.WebkitTransform = style;
<del> element.style.MozTransform = style;
<del> element.style.oTransform = style;
<del> element.style.transform = style;
<ide>
<add> element.style.transform = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
<ide> element.style.display = ( object.visible && vector.z >= - 1 && vector.z <= 1 ) ? '' : 'none';
<ide>
<ide> var objectData = {
<ide><path>examples/js/renderers/CSS3DRenderer.js
<ide> THREE.CSS3DRenderer = function () {
<ide>
<ide> var cameraElement = document.createElement( 'div' );
<ide>
<del> cameraElement.style.WebkitTransformStyle = 'preserve-3d';
<ide> cameraElement.style.transformStyle = 'preserve-3d';
<ide> cameraElement.style.pointerEvents = 'none';
<ide>
<ide> THREE.CSS3DRenderer = function () {
<ide>
<ide> if ( cachedObject === undefined || cachedObject.style !== style ) {
<ide>
<del> element.style.WebkitTransform = style;
<ide> element.style.transform = style;
<ide>
<ide> var objectData = { style: style };
<ide> THREE.CSS3DRenderer = function () {
<ide>
<ide> if ( cache.camera.fov !== fov ) {
<ide>
<del> if ( camera.isPerspectiveCamera ) {
<del>
<del> domElement.style.WebkitPerspective = fov + 'px';
<del> domElement.style.perspective = fov + 'px';
<del>
<del> } else {
<del>
<del> domElement.style.WebkitPerspective = '';
<del> domElement.style.perspective = '';
<del>
<del> }
<del>
<add> domElement.style.perspective = camera.isPerspectiveCamera ? fov + 'px' : '';
<ide> cache.camera.fov = fov;
<ide>
<ide> }
<ide> THREE.CSS3DRenderer = function () {
<ide>
<ide> if ( cache.camera.style !== style ) {
<ide>
<del> cameraElement.style.WebkitTransform = style;
<ide> cameraElement.style.transform = style;
<ide>
<ide> cache.camera.style = style;
<ide><path>examples/jsm/renderers/CSS2DRenderer.js
<ide> var CSS2DRenderer = function () {
<ide> vector.applyMatrix4( viewProjectionMatrix );
<ide>
<ide> var element = object.element;
<del> var style = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
<del>
<del> element.style.WebkitTransform = style;
<del> element.style.MozTransform = style;
<del> element.style.oTransform = style;
<del> element.style.transform = style;
<ide>
<add> element.style.transform = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
<ide> element.style.display = ( object.visible && vector.z >= - 1 && vector.z <= 1 ) ? '' : 'none';
<ide>
<ide> var objectData = {
<ide><path>examples/jsm/renderers/CSS3DRenderer.js
<ide> var CSS3DRenderer = function () {
<ide>
<ide> var cameraElement = document.createElement( 'div' );
<ide>
<del> cameraElement.style.WebkitTransformStyle = 'preserve-3d';
<ide> cameraElement.style.transformStyle = 'preserve-3d';
<ide> cameraElement.style.pointerEvents = 'none';
<ide>
<ide> var CSS3DRenderer = function () {
<ide>
<ide> if ( cachedObject === undefined || cachedObject.style !== style ) {
<ide>
<del> element.style.WebkitTransform = style;
<ide> element.style.transform = style;
<ide>
<ide> var objectData = { style: style };
<ide> var CSS3DRenderer = function () {
<ide>
<ide> if ( cache.camera.fov !== fov ) {
<ide>
<del> if ( camera.isPerspectiveCamera ) {
<del>
<del> domElement.style.WebkitPerspective = fov + 'px';
<del> domElement.style.perspective = fov + 'px';
<del>
<del> } else {
<del>
<del> domElement.style.WebkitPerspective = '';
<del> domElement.style.perspective = '';
<del>
<del> }
<del>
<add> domElement.style.perspective = camera.isPerspectiveCamera ? fov + 'px' : '';
<ide> cache.camera.fov = fov;
<ide>
<ide> }
<ide> var CSS3DRenderer = function () {
<ide>
<ide> if ( cache.camera.style !== style ) {
<ide>
<del> cameraElement.style.WebkitTransform = style;
<ide> cameraElement.style.transform = style;
<ide>
<ide> cache.camera.style = style;
| 4
|
Text
|
Text
|
update changelog for 2.16.0-beta.2
|
a9a36f4f8931488de40c64f4f190c0c3ce5be035
|
<ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### 2.16.0-beta.2 (October, 2, 2017)
<add>
<add>- [#15577](https://github.com/emberjs/ember.js/pull/15577) [BUGFIX] Include missing sourcemaps in vendorTree.
<add>- [#15552](https://github.com/emberjs/ember.js/pull/15552) [FEATURE] Update blueprints and tests to RFC #176.
<add>- [#15600](https://github.com/emberjs/ember.js/pull/15600) [BUGFIX] ensure “pause on exception” pauses in the right place.
<add>- [#15616](https://github.com/emberjs/ember.js/pull/15616) [DOC release] Improve documentation for RouterService and mount helper.
<add>- [#15600](https://github.com/emberjs/ember.js/pull/15600) [BUGFIX LTS] ensure “pause on exception” pauses in the right place.
<add>- [#15667](https://github.com/emberjs/ember.js/pull/15667) [BUGFIX] Allow `0` to work with `get` helper.
<add>- [#15676](https://github.com/emberjs/ember.js/pull/15676) [BUGFIX] Fix `<input type="range">` so that it can properly bind `min`, `max`, and `value`.
<add>- [#15689](https://github.com/emberjs/ember.js/pull/15689) [BUGFIX] Mark error as handled before transition for error routes and substates.
<add>
<add>
<ide> ### 2.16.0-beta.1 (August 31, 2017)
<ide>
<ide> - [#14764](https://github.com/emberjs/ember.js/pull/14764) Fixed string capitalize for accented characters.
| 1
|
Go
|
Go
|
improve error messages for loading tls keys
|
2ea6c2c264f0f43beb877a83aea3e6e6ad38ae5d
|
<ide><path>api/server/server.go
<ide> func lookupGidByName(nameOrGid string) (int, error) {
<ide> func setupTls(cert, key, ca string, l net.Listener) (net.Listener, error) {
<ide> tlsCert, err := tls.LoadX509KeyPair(cert, key)
<ide> if err != nil {
<del> return nil, fmt.Errorf("Couldn't load X509 key pair (%s, %s): %s. Key encrypted?",
<add> if os.IsNotExist(err) {
<add> return nil, fmt.Errorf("Could not load X509 key pair (%s, %s): %v", cert, key, err)
<add> }
<add> return nil, fmt.Errorf("Error reading X509 key pair (%s, %s): %q. Make sure the key is encrypted.",
<ide> cert, key, err)
<ide> }
<ide> tlsConfig := &tls.Config{
<ide> func setupTls(cert, key, ca string, l net.Listener) (net.Listener, error) {
<ide> certPool := x509.NewCertPool()
<ide> file, err := ioutil.ReadFile(ca)
<ide> if err != nil {
<del> return nil, fmt.Errorf("Couldn't read CA certificate: %s", err)
<add> return nil, fmt.Errorf("Could not read CA certificate: %v", err)
<ide> }
<ide> certPool.AppendCertsFromPEM(file)
<ide> tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
| 1
|
Javascript
|
Javascript
|
remove outdated element tests
|
f388ed3136a3b62f46e9f0e4c5ef96f175cc1670
|
<ide><path>test/specs/element.arc.tests.js
<ide> // Test the rectangle element
<ide>
<ide> describe('Arc element tests', function() {
<del> it ('Should be constructed', function() {
<del> var arc = new Chart.elements.Arc({
<del> _datasetIndex: 2,
<del> _index: 1
<del> });
<del>
<del> expect(arc).not.toBe(undefined);
<del> expect(arc._datasetIndex).toBe(2);
<del> expect(arc._index).toBe(1);
<del> });
<del>
<ide> it ('should determine if in range', function() {
<ide> // Mock out the arc as if the controller put it there
<ide> var arc = new Chart.elements.Arc({
<ide><path>test/specs/element.point.tests.js
<ide> describe('Chart.elements.Point', function() {
<ide> describe('auto', jasmine.fixture.specs('element.point'));
<ide>
<del> it ('Should be constructed', function() {
<del> var point = new Chart.elements.Point({
<del> _datasetIndex: 2,
<del> _index: 1
<del> });
<del>
<del> expect(point).not.toBe(undefined);
<del> expect(point._datasetIndex).toBe(2);
<del> expect(point._index).toBe(1);
<del> });
<del>
<ide> it ('Should correctly identify as in range', function() {
<ide> // Mock out the point as if we were made by the controller
<ide> var point = new Chart.elements.Point({
<ide><path>test/specs/element.rectangle.tests.js
<ide> // Test the rectangle element
<ide>
<ide> describe('Rectangle element tests', function() {
<del> it('Should be constructed', function() {
<del> var rectangle = new Chart.elements.Rectangle({
<del> _datasetIndex: 2,
<del> _index: 1
<del> });
<del>
<del> expect(rectangle).not.toBe(undefined);
<del> expect(rectangle._datasetIndex).toBe(2);
<del> expect(rectangle._index).toBe(1);
<del> });
<del>
<ide> it('Should correctly identify as in range', function() {
<ide> var rectangle = new Chart.elements.Rectangle({
<ide> base: 0,
| 3
|
PHP
|
PHP
|
add ssl support back to mysql driver
|
ade1d087ee13d1d963c2e1f562d4804294d54308
|
<ide><path>Cake/Database/Driver/Mysql.php
<ide> public function connect() {
<ide> }
<ide>
<ide> $config['init'][] = sprintf("SET time_zone = '%s'", $config['timezone']);
<add>
<ide> $config['flags'] += [
<ide> PDO::ATTR_PERSISTENT => $config['persistent'],
<ide> PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true,
<ide> PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
<ide> PDO::MYSQL_ATTR_INIT_COMMAND => implode(';', (array)$config['init'])
<ide> ];
<ide>
<add> if (!empty($config['ssl_key']) && !empty($config['ssl_cert'])) {
<add> $config['flags'][PDO::MYSQL_ATTR_SSL_KEY] = $config['ssl_key'];
<add> $config['flags'][PDO::MYSQL_ATTR_SSL_CERT] = $config['ssl_cert'];
<add> }
<add> if (!empty($config['ssl_ca'])) {
<add> $config['flags'][PDO::MYSQL_ATTR_SSL_CA] = $config['ssl_ca'];
<add> }
<add>
<ide> if (empty($config['dsn'])) {
<ide> if (empty($config['unix_socket'])) {
<ide> $config['dsn'] = "mysql:host={$config['host']};port={$config['port']};dbname={$config['database']};charset={$config['encoding']}";
| 1
|
Javascript
|
Javascript
|
fix bufferattribute accessors
|
9757d97f67c70d6c85c828d0973aa85bab7a2b3c
|
<ide><path>src/core/BufferAttribute.js
<ide> function BufferAttribute( array, itemSize, normalized ) {
<ide>
<ide> }
<ide>
<add>Object.defineProperty( BufferAttribute.prototype, "needsUpdate", {
<add>
<add> set: function(value) { if ( value === true ) this.version ++; }
<add>
<add>});
<add>
<ide> Object.assign( BufferAttribute.prototype, {
<ide>
<ide> constructor: BufferAttribute,
| 1
|
Ruby
|
Ruby
|
fix rdoc markup in `connectionpool`. [ci skip]
|
809fd2b2737424762663dbebdc54e6ee5493df90
|
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> def initialize(spec)
<ide> # of the cache is to speed-up +connection+ method, it is not the authoritative
<ide> # registry of which thread owns which connection, that is tracked by
<ide> # +connection.owner+ attr on each +connection+ instance.
<del> # The invariant works like this: if there is mapping of +thread => conn+,
<add> # The invariant works like this: if there is mapping of <tt>thread => conn</tt>,
<ide> # then that +thread+ does indeed own that +conn+, however an absence of a such
<ide> # mapping does not mean that the +thread+ doesn't own the said connection, in
<ide> # that case +conn.owner+ attr should be consulted.
<ide> def initialize(spec)
<ide> @connections = []
<ide> @automatic_reconnect = true
<ide>
<del> # Connection pool allows for concurrent (outside the main `synchronize` section)
<add> # Connection pool allows for concurrent (outside the main +synchronize+ section)
<ide> # establishment of new connections. This variable tracks the number of threads
<ide> # currently in the process of independently establishing connections to the DB.
<ide> @now_connecting = 0
<ide> def connected?
<ide> # Raises:
<ide> # - +ExclusiveConnectionTimeoutError+ if unable to gain ownership of all
<ide> # connections in the pool within a timeout interval (default duration is
<del> # +spec.config[:checkout_timeout] * 2+ seconds).
<add> # <tt>spec.config[:checkout_timeout] * 2</tt> seconds).
<ide> def disconnect(raise_on_acquisition_timeout = true)
<ide> with_exclusively_acquired_all_connections(raise_on_acquisition_timeout) do
<ide> synchronize do
<ide> def disconnect(raise_on_acquisition_timeout = true)
<ide> #
<ide> # The pool first tries to gain ownership of all connections, if unable to
<ide> # do so within a timeout interval (default duration is
<del> # +spec.config[:checkout_timeout] * 2+ seconds), the pool is forcefully
<add> # <tt>spec.config[:checkout_timeout] * 2</tt> seconds), the pool is forcefully
<ide> # disconnected without any regard for other connection owning threads.
<ide> def disconnect!
<ide> disconnect(false)
<ide> def disconnect!
<ide> # Raises:
<ide> # - +ExclusiveConnectionTimeoutError+ if unable to gain ownership of all
<ide> # connections in the pool within a timeout interval (default duration is
<del> # +spec.config[:checkout_timeout] * 2+ seconds).
<add> # <tt>spec.config[:checkout_timeout] * 2</tt> seconds).
<ide> def clear_reloadable_connections(raise_on_acquisition_timeout = true)
<ide> num_new_conns_required = 0
<ide>
<ide> def clear_reloadable_connections(raise_on_acquisition_timeout = true)
<ide> #
<ide> # The pool first tries to gain ownership of all connections, if unable to
<ide> # do so within a timeout interval (default duration is
<del> # +spec.config[:checkout_timeout] * 2+ seconds), the pool forcefully
<add> # <tt>spec.config[:checkout_timeout] * 2</tt> seconds), the pool forcefully
<ide> # clears the cache and reloads connections without any regard for other
<ide> # connection owning threads.
<ide> def clear_reloadable_connections!
<ide> def attempt_to_checkout_all_existing_connections(raise_on_acquisition_timeout =
<ide> end
<ide> end
<ide> rescue ExclusiveConnectionTimeoutError
<del> # `raise_on_acquisition_timeout == false` means we are directed to ignore any
<add> # <tt>raise_on_acquisition_timeout == false</tt> means we are directed to ignore any
<ide> # timeouts and are expected to just give up: we've obtained as many connections
<ide> # as possible, note that in a case like that we don't return any of the
<del> # `newly_checked_out` connections.
<add> # +newly_checked_out+ connections.
<ide>
<ide> if raise_on_acquisition_timeout
<ide> release_newly_checked_out = true
<ide> def with_new_connections_blocked
<ide> # Implementation detail: the connection returned by +acquire_connection+
<ide> # will already be "+connection.lease+ -ed" to the current thread.
<ide> def acquire_connection(checkout_timeout)
<del> # NOTE: we rely on `@available.poll` and `try_to_checkout_new_connection` to
<del> # `conn.lease` the returned connection (and to do this in a `synchronized`
<add> # NOTE: we rely on +@available.poll+ and +try_to_checkout_new_connection+ to
<add> # +conn.lease+ the returned connection (and to do this in a +synchronized+
<ide> # section), this is not the cleanest implementation, as ideally we would
<del> # `synchronize { conn.lease }` in this method, but by leaving it to `@available.poll`
<del> # and `try_to_checkout_new_connection` we can piggyback on `synchronize` sections
<del> # of the said methods and avoid an additional `synchronize` overhead.
<add> # <tt>synchronize { conn.lease }</tt> in this method, but by leaving it to +@available.poll+
<add> # and +try_to_checkout_new_connection+ we can piggyback on +synchronize+ sections
<add> # of the said methods and avoid an additional +synchronize+ overhead.
<ide> if conn = @available.poll || try_to_checkout_new_connection
<ide> conn
<ide> else
| 1
|
Python
|
Python
|
fix typo in error message
|
e37bc579fce3f193fe1f097262db65dce7a684d4
|
<ide><path>utils/check_repo.py
<ide> def check_docstrings_are_in_md():
<ide> raise ValueError(
<ide> "The following files have docstrings written in rst:\n"
<ide> + "\n".join([f"- {f}" for f in files_with_rst])
<del> + "To fix this run `doc_builder convert path_to_py_file` after installing `doc_builder`\n"
<add> + "To fix this run `doc-builder convert path_to_py_file` after installing `doc-builder`\n"
<ide> "(`pip install git+https://github.com/huggingface/doc-builder`)"
<ide> )
<ide>
| 1
|
Javascript
|
Javascript
|
use example or module description
|
e48e63709c29a033b70b9c6279ff05a86dd71ba6
|
<ide><path>packages/rn-tester/js/components/ExamplePage.js
<del>/**
<del> * Copyright (c) Facebook, Inc. and its affiliates.
<del> *
<del> * This source code is licensed under the MIT license found in the
<del> * LICENSE file in the root directory of this source tree.
<del> *
<del> * @format
<del> * @flow
<del> */
<del>
<del>import * as React from 'react';
<del>import {StyleSheet, View, Text} from 'react-native';
<del>import {RNTesterThemeContext} from './RNTesterTheme';
<del>
<del>type Props = $ReadOnly<{|
<del> children?: React.Node,
<del> title: string,
<del> description?: ?string,
<del> category?: ?string,
<del> ios?: ?boolean,
<del> android?: ?boolean,
<del>|}>;
<del>
<del>export default function ExamplePage(props: Props): React.Node {
<del> const description = props.description ?? '';
<del> const theme = React.useContext(RNTesterThemeContext);
<del> return (
<del> <>
<del> <View
<del> style={[styles.titleView, {backgroundColor: theme.BackgroundColor}]}>
<del> <Text style={styles.title}>{props.title}</Text>
<del> <Text style={styles.description}>{description}</Text>
<del> </View>
<del> <View style={styles.examplesContainer}>{props.children}</View>
<del> </>
<del> );
<del>}
<del>
<del>const styles = StyleSheet.create({
<del> titleView: {
<del> paddingHorizontal: 25,
<del> paddingTop: 4,
<del> paddingBottom: 8,
<del> overflow: 'hidden',
<del> },
<del> title: {
<del> alignSelf: 'center',
<del> fontSize: 12,
<del> },
<del> description: {
<del> fontSize: 16,
<del> paddingTop: 4,
<del> },
<del> iconContainer: {
<del> flexDirection: 'row',
<del> justifyContent: 'flex-end',
<del> },
<del> examplesContainer: {
<del> flexGrow: 1,
<del> flex: 1,
<del> },
<del>});
<ide><path>packages/rn-tester/js/components/RNTesterExampleFilter.js
<ide> const styles = StyleSheet.create({
<ide> },
<ide> searchRow: {
<ide> paddingHorizontal: 20,
<del> paddingVertical: 10,
<add> paddingVertical: 6,
<ide> alignItems: 'center',
<ide> },
<ide> searchTextInput: {
<ide><path>packages/rn-tester/js/components/RNTesterModuleContainer.js
<ide> const RNTesterBlock = require('./RNTesterBlock');
<ide> const RNTesterExampleFilter = require('./RNTesterExampleFilter');
<ide> import RNTPressableRow from './RNTPressableRow';
<ide> import {RNTesterThemeContext} from './RNTesterTheme';
<del>import {StyleSheet, Platform} from 'react-native';
<add>import {View, Text, StyleSheet, Platform} from 'react-native';
<ide>
<del>const invariant = require('invariant');
<del>import ExamplePage from './ExamplePage';
<ide> import type {
<ide> RNTesterModule,
<ide> RNTesterModuleExample,
<ide> export default function RNTesterModuleContainer(props: Props): React.Node {
<ide> );
<ide> };
<ide>
<del> if (module.simpleExampleContainer) {
<del> invariant(
<del> module.examples.length === 1,
<del> 'If noExampleContainer is specified, only one example is allowed',
<del> );
<del> return (
<del> <ExamplePage
<del> title={module.title}
<del> description={module.description}
<del> android={!module.platform || module.platform === 'android'}
<del> ios={!module.platform || module.platform === 'ios'}
<del> documentationURL={module.documentationURL}
<del> category={module.category}>
<del> {module.examples[0].render()}
<del> </ExamplePage>
<del> );
<del> }
<del>
<ide> if (module.examples.length === 1) {
<add> const description = module.examples[0].description ?? module.description;
<ide> return (
<del> <ExamplePage
<del> title={module.testTitle || module.title}
<del> description={module.description}
<del> android={!module.platform || module.platform === 'android'}
<del> ios={!module.platform || module.platform === 'ios'}
<del> documentationURL={module.documentationURL}
<del> category={module.category}>
<add> <>
<add> <Header description={description} theme={theme} />
<ide> {module.examples[0].render()}
<del> </ExamplePage>
<add> </>
<ide> );
<ide> }
<ide>
<ide> export default function RNTesterModuleContainer(props: Props): React.Node {
<ide> ];
<ide>
<ide> return (
<del> <ExamplePage
<del> title={module.title}
<del> description={module.description}
<del> android={!module.platform || module.platform === 'android'}
<del> ios={!module.platform || module.platform === 'ios'}
<del> documentationURL={module.documentationURL}
<del> category={module.category}>
<add> <View style={styles.examplesContainer}>
<ide> {module.showIndividualExamples === true && example != null ? (
<ide> example.render()
<ide> ) : (
<del> <RNTesterExampleFilter
<del> testID="example_search"
<del> page="examples_page"
<del> hideFilterPills={true}
<del> sections={sections}
<del> filter={filter}
<del> render={({filteredSections}) =>
<del> filteredSections[0].data.map(renderExample)
<del> }
<del> />
<add> <>
<add> <Header
<add> description={module.description}
<add> noBottomPadding
<add> theme={theme}
<add> />
<add> <RNTesterExampleFilter
<add> testID="example_search"
<add> page="examples_page"
<add> hideFilterPills={true}
<add> sections={sections}
<add> filter={filter}
<add> render={({filteredSections}) =>
<add> filteredSections[0].data.map(renderExample)
<add> }
<add> />
<add> </>
<ide> )}
<del> </ExamplePage>
<add> </View>
<add> );
<add>}
<add>
<add>function Header(props: {
<add> description: string,
<add> theme: RNTesterTheme,
<add> noBottomPadding?: ?boolean,
<add>}) {
<add> return (
<add> <View
<add> style={[
<add> styles.headerContainer,
<add> props.noBottomPadding === true ? styles.headerNoBottomPadding : null,
<add> {backgroundColor: props.theme.BackgroundColor},
<add> ]}>
<add> <Text style={styles.headerDescription}>{props.description}</Text>
<add> </View>
<ide> );
<ide> }
<ide>
<ide> const styles = StyleSheet.create({
<add> headerContainer: {
<add> paddingHorizontal: Platform.OS === 'android' ? 15 : 6,
<add> paddingVertical: 6,
<add> alignItems: 'center',
<add> },
<add> headerDescription: {
<add> fontSize: 14,
<add> },
<add> headerNoBottomPadding: {
<add> paddingBottom: 0,
<add> },
<add> examplesContainer: {
<add> flexGrow: 1,
<add> flex: 1,
<add> },
<ide> separator: {
<ide> borderBottomWidth: Platform.select({
<ide> ios: StyleSheet.hairlineWidth,
<ide><path>packages/rn-tester/js/examples/FlatList/FlatListExample.js
<ide> exports.title = 'FlatList';
<ide> exports.category = 'ListView';
<ide> exports.documentationURL = 'https://reactnative.dev/docs/flatlist';
<ide> exports.description = 'Performant, scrollable list of data.';
<del>exports.simpleExampleContainer = true;
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple list of items',
<ide><path>packages/rn-tester/js/examples/PanResponder/PanResponderExample.js
<ide> exports.category = 'Basic';
<ide> exports.documentationURL = 'https://reactnative.dev/docs/panresponder';
<ide> exports.description =
<ide> 'Shows the Use of PanResponder to provide basic gesture handling';
<del>exports.simpleExampleContainer = true;
<ide> exports.examples = [
<ide> {
<ide> title: 'Basic gesture handling',
<ide><path>packages/rn-tester/js/examples/RefreshControl/RefreshControlExample.js
<ide> exports.title = 'RefreshControl';
<ide> exports.category = 'Basic';
<ide> exports.documentationURL = 'https://reactnative.dev/docs/refreshcontrol';
<ide> exports.description = 'Adds pull-to-refresh support to a scrollview.';
<del>exports.simpleExampleContainer = true;
<ide> exports.examples = [
<ide> {
<ide> title: 'Simple refresh',
<ide><path>packages/rn-tester/js/types/RNTesterTypes.js
<ide> export type RNTesterModule = $ReadOnly<{|
<ide> category?: ?string,
<ide> framework?: string,
<ide> examples: Array<RNTesterModuleExample>,
<del> simpleExampleContainer?: ?boolean,
<ide> category?: string,
<ide> documentationURL?: string,
<ide> showIndividualExamples?: boolean,
| 7
|
Ruby
|
Ruby
|
remove redundant conditional
|
cb0a90262d8914b749fadcede523ef2e0604cbd4
|
<ide><path>Library/Homebrew/download_strategy.rb
<ide> def _curl_args
<ide> "because we need it installed to download securely."
<ide> @insecure_warning_shown = true
<ide> end
<del> args += ["--insecure"] if meta[:insecure]
<add> args += ["--insecure"]
<ide> end
<ide>
<ide> args
| 1
|
Ruby
|
Ruby
|
fix variable name in guides markdown generator
|
c0ea4321b963970192f43a372906aa1fa8b85e72
|
<ide><path>guides/rails_guides/markdown/renderer.rb
<ide> def lexer_language(code_type)
<ide> when nil
<ide> "plaintext"
<ide> else
<del> ::Rouge::Lexer.find(language) ? code_type : "plaintext"
<add> ::Rouge::Lexer.find(code_type) ? code_type : "plaintext"
<ide> end
<ide> end
<ide>
| 1
|
PHP
|
PHP
|
add basic table creation + test cases
|
ec426afe8056508343c485a7f8b15efe98562f49
|
<ide><path>lib/Cake/Database/Schema/SqliteSchema.php
<ide> public function columnSql(Table $table, $name) {
<ide> if (isset($data['null']) && $data['null'] === false) {
<ide> $out .= ' NOT NULL';
<ide> }
<add> if (in_array($data['type'], ['integer']) && in_array($name, (array)$table->primaryKey())) {
<add> $out .= ' PRIMARY KEY AUTOINCREMENT';
<add> }
<ide> if (isset($data['null']) && $data['null'] === true) {
<ide> $out .= ' DEFAULT NULL';
<ide> unset($data['default']);
<ide> public function columnSql(Table $table, $name) {
<ide> /**
<ide> * Generate the SQL fragment for a single index in MySQL
<ide> *
<add> * Note integer primary keys will return ''. This is intentional as Sqlite requires
<add> * that integer primary keys be defined in the column definition.
<add> *
<ide> * @param Cake\Database\Schema\Table $table The table object the column is in.
<ide> * @param string $name The name of the column.
<ide> * @return string SQL fragment.
<ide> */
<ide> public function indexSql(Table $table, $name) {
<ide> $data = $table->index($name);
<add>
<add> if (
<add> count($data['columns']) === 1 &&
<add> $table->column($data['columns'][0])['type'] === 'integer'
<add> ) {
<add> return '';
<add> }
<add>
<ide> $out = 'CONSTRAINT ';
<ide> $out .= $this->_driver->quoteIdentifier($name);
<ide> if ($data['type'] === Table::INDEX_PRIMARY) {
<ide> public function indexSql(Table $table, $name) {
<ide> * @return string A complete CREATE TABLE statement
<ide> */
<ide> public function createTableSql($table, $lines) {
<del> $content = implode(",\n", $lines);
<add> $content = implode(",\n", array_filter($lines));
<ide> return sprintf("CREATE TABLE \"%s\" (\n%s\n);", $table, $content);
<ide> }
<ide> }
<ide><path>lib/Cake/Test/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> public function testColumnSql($name, $data, $expected) {
<ide> $this->assertEquals($expected, $schema->columnSql($table, $name));
<ide> }
<ide>
<add>/**
<add> * Test generating a column that is a primary key.
<add> *
<add> * @return void
<add> */
<add> public function testColumnSqlPrimaryKey() {
<add> $driver = $this->_getMockedDriver();
<add> $schema = new SqliteSchema($driver);
<add>
<add> $table = new Table('articles');
<add> $table->addColumn('id', [
<add> 'type' => 'integer',
<add> 'null' => false
<add> ])
<add> ->addIndex('primary', [
<add> 'type' => 'primary',
<add> 'columns' => ['id']
<add> ]);
<add> $result = $schema->columnSql($table, 'id');
<add> $this->assertEquals($result, '"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT');
<add>
<add> $result = $schema->indexSql($table, 'primary');
<add> $this->assertEquals('', $result, 'Integer primary keys are special in sqlite.');
<add> }
<add>
<ide> /**
<ide> * Provide data for testing indexSql
<ide> *
<ide> public function testIndexSql($name, $data, $expected) {
<ide> $this->assertEquals($expected, $schema->indexSql($table, $name));
<ide> }
<ide>
<add>/**
<add> * Integration test for converting a Schema\Table into MySQL table creates.
<add> *
<add> * @return void
<add> */
<add> public function testCreateTableSql() {
<add> $driver = $this->_getMockedDriver();
<add> $connection = $this->getMock('Cake\Database\Connection', array(), array(), '', false);
<add> $connection->expects($this->any())->method('driver')
<add> ->will($this->returnValue($driver));
<add>
<add> $table = (new Table('articles'))->addColumn('id', [
<add> 'type' => 'integer',
<add> 'null' => false
<add> ])
<add> ->addColumn('title', [
<add> 'type' => 'string',
<add> 'null' => false,
<add> ])
<add> ->addColumn('body', ['type' => 'text'])
<add> ->addColumn('created', 'datetime')
<add> ->addIndex('primary', [
<add> 'type' => 'primary',
<add> 'columns' => ['id']
<add> ]);
<add>
<add> $expected = <<<SQL
<add>CREATE TABLE "articles" (
<add>"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
<add>"title" VARCHAR NOT NULL,
<add>"body" TEXT,
<add>"created" DATETIME
<add>);
<add>SQL;
<add> $result = $table->createTableSql($connection);
<add> $this->assertEquals($expected, $result);
<add> }
<add>
<ide> /**
<ide> * Get a schema instance with a mocked driver/pdo instances
<ide> *
| 2
|
Ruby
|
Ruby
|
drop unnecessary parens
|
018aeb05ab74629f761741e51436a358db6feb9d
|
<ide><path>Library/Homebrew/cxxstdlib.rb
<ide> def initialize(type, compiler)
<ide> # libstdc++ is compatible across Apple compilers, but
<ide> # not between Apple and GNU compilers, or between GNU compiler versions
<ide> def compatible_with?(other)
<del> (type.nil? || other.type.nil?) || type == other.type
<add> type.nil? || other.type.nil? || type == other.type
<ide> end
<ide>
<ide> def check_dependencies(formula, deps)
| 1
|
Text
|
Text
|
fix a small typo
|
26c4dc954f350dc46cd774db9e441999ed912b09
|
<ide><path>docs/Installation.md
<ide> Just extract (or `git clone`) Homebrew wherever you want. Just avoid:
<ide> * `/tmp` subdirectories because Homebrew gets upset.
<ide> * `/sw` and `/opt/local` because build scripts get confused when Homebrew is there instead of Fink or MacPorts, respectively.
<ide>
<del>However do yourself a favour and install to `/usr/local` on macOS Intel, `/opt/homebrew` on macOS ARM
<del>and `.home/linuxbrew/.linuxbrew` on Linux. Some things may
<add>However do yourself a favour and install to `/usr/local` on macOS Intel, `/opt/homebrew` on macOS ARM,
<add>and `/home/linuxbrew/.linuxbrew` on Linux. Some things may
<ide> not build when installed elsewhere. One of the reasons Homebrew just
<ide> works relative to the competition is **because** we recommend installing
<ide> here. *Pick another prefix at your peril!*
| 1
|
PHP
|
PHP
|
remove unneeded variable
|
0f7c230eb3f792d8f8ccd35807f04967854e485a
|
<ide><path>src/Illuminate/Remote/RemoteManager.php
<ide> protected function makeConnection($name, array $config)
<ide> {
<ide> $this->setOutput($connection = new Connection(
<ide>
<del> $name, $config['host'], $config['username'], $this->getAuth($config), $keyphrase
<add> $name, $config['host'], $config['username'], $this->getAuth($config)
<ide>
<ide> ));
<ide>
| 1
|
Ruby
|
Ruby
|
add protected reader for version value
|
68c7e1e30cbb96eee50472c19f866414188a5d65
|
<ide><path>Library/Homebrew/version.rb
<ide> def detected_from_url?
<ide> end
<ide>
<ide> def head?
<del> @version == 'HEAD'
<add> version == "HEAD"
<ide> end
<ide>
<ide> def <=>(other)
<ide> def <=>(other)
<ide> alias_method :eql?, :==
<ide>
<ide> def hash
<del> @version.hash
<add> version.hash
<ide> end
<ide>
<ide> def to_s
<del> @version.dup
<add> version.dup
<ide> end
<ide> alias_method :to_str, :to_s
<ide>
<ide> protected
<ide>
<add> attr_reader :version
<add>
<ide> def begins_with_numeric?
<ide> tokens.first.numeric?
<ide> end
<ide> def tokens
<ide> end
<ide>
<ide> def tokenize
<del> @version.scan(SCAN_PATTERN).map! do |token|
<add> version.scan(SCAN_PATTERN).map! do |token|
<ide> case token
<ide> when /\A#{AlphaToken::PATTERN}\z/o then AlphaToken
<ide> when /\A#{BetaToken::PATTERN}\z/o then BetaToken
| 1
|
Javascript
|
Javascript
|
allow parsing of the "glued" commands
|
ec6c185cf5b5f8ac3af3f9e2f45f3bf40b32e22f
|
<ide><path>src/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide>
<ide> // Compatibility
<ide> BX: 'beginCompat',
<del> EX: 'endCompat'
<del> };
<del>
<del> function splitCombinedOperations(operations) {
<del> // Two or more operations can be combined together, trying to find which
<del> // operations were concatenated.
<del> var result = [];
<del> var opIndex = 0;
<del>
<del> if (!operations) {
<del> return null;
<del> }
<del>
<del> while (opIndex < operations.length) {
<del> var currentOp = '';
<del> for (var op in OP_MAP) {
<del> if (op == operations.substr(opIndex, op.length) &&
<del> op.length > currentOp.length) {
<del> currentOp = op;
<del> }
<del> }
<del>
<del> if (currentOp.length > 0) {
<del> result.push(operations.substr(opIndex, currentOp.length));
<del> opIndex += currentOp.length;
<del> } else {
<del> return null;
<del> }
<del> }
<add> EX: 'endCompat',
<ide>
<del> return result;
<del> }
<add> // (reserved partial commands for the lexer)
<add> BM: null,
<add> BD: null
<add> };
<ide>
<ide> PartialEvaluator.prototype = {
<ide> getOperatorList: function PartialEvaluator_getOperatorList(stream,
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> resources = resources || new Dict();
<ide> var xobjs = resources.get('XObject') || new Dict();
<ide> var patterns = resources.get('Pattern') || new Dict();
<del> var parser = new Parser(new Lexer(stream), false, xref);
<add> var parser = new Parser(new Lexer(stream, OP_MAP), false, xref);
<ide> var res = resources;
<del> var hasNextObj = false, nextObjs;
<ide> var args = [], obj;
<ide> var TILING_PATTERN = 1, SHADING_PATTERN = 2;
<ide>
<ide> while (true) {
<del> if (hasNextObj) {
<del> obj = nextObjs.pop();
<del> hasNextObj = (nextObjs.length > 0);
<del> } else {
<del> obj = parser.getObj();
<del> if (isEOF(obj))
<del> break;
<del> }
<add> obj = parser.getObj();
<add> if (isEOF(obj))
<add> break;
<ide>
<ide> if (isCmd(obj)) {
<ide> var cmd = obj.cmd;
<ide> var fn = OP_MAP[cmd];
<del> if (!fn) {
<del> // invalid content command, trying to recover
<del> var cmds = splitCombinedOperations(cmd);
<del> if (cmds) {
<del> cmd = cmds[0];
<del> fn = OP_MAP[cmd];
<del> // feeding other command on the next iteration
<del> hasNextObj = true;
<del> nextObjs = [];
<del> for (var idx = 1; idx < cmds.length; idx++) {
<del> nextObjs.push(Cmd.get(cmds[idx]));
<del> }
<del> }
<del> }
<ide> assertWellFormed(fn, 'Unknown command "' + cmd + '"');
<ide> // TODO figure out how to type-check vararg functions
<ide>
<ide><path>src/parser.js
<ide> var Parser = (function ParserClosure() {
<ide> })();
<ide>
<ide> var Lexer = (function LexerClosure() {
<del> function Lexer(stream) {
<add> function Lexer(stream, knownCommands) {
<ide> this.stream = stream;
<add> this.knownCommands = knownCommands;
<ide> }
<ide>
<ide> Lexer.isSpace = function Lexer_isSpace(ch) {
<ide> var Lexer = (function LexerClosure() {
<ide>
<ide> // command
<ide> var str = ch;
<add> var knownCommands = this.knownCommands;
<add> var knownCommandFound = knownCommands && (str in knownCommands);
<ide> while (!!(ch = stream.lookChar()) && !specialChars[ch.charCodeAt(0)]) {
<add> // stop if known command is found and next character does not make
<add> // the str a command
<add> if (knownCommandFound && !((str + ch) in knownCommands))
<add> break;
<ide> stream.skip();
<ide> if (str.length == 128)
<ide> error('Command token too long: ' + str.length);
<del>
<ide> str += ch;
<add> knownCommandFound = knownCommands && (str in knownCommands);
<ide> }
<ide> if (str == 'true')
<ide> return true;
<ide><path>test/unit/evaluator_spec.js
<ide> describe('evaluator', function() {
<ide> expect(result.fnArray[1]).toEqual('save');
<ide> expect(result.fnArray[2]).toEqual('save');
<ide> });
<add>
<add> it('should handle three glued operations #2', function() {
<add> var evaluator = new PartialEvaluator(new XrefMock(), new HandlerMock(),
<add> 'prefix');
<add> var resources = new ResourcesMock();
<add> resources.Res1 = {};
<add> var stream = new StringStream('B*BBMC');
<add> var result = evaluator.getOperatorList(stream, resources, []);
<add>
<add> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<add> expect(result.fnArray.length).toEqual(3);
<add> expect(result.fnArray[0]).toEqual('eoFillStroke');
<add> expect(result.fnArray[1]).toEqual('fillStroke');
<add> expect(result.fnArray[2]).toEqual('beginMarkedContent');
<add> });
<add>
<add> it('should handle glued operations and operands', function() {
<add> var evaluator = new PartialEvaluator(new XrefMock(), new HandlerMock(),
<add> 'prefix');
<add> var stream = new StringStream('q5 Ts');
<add> var result = evaluator.getOperatorList(stream, new ResourcesMock(), []);
<add>
<add> expect(!!result.fnArray && !!result.argsArray).toEqual(true);
<add> expect(result.fnArray.length).toEqual(2);
<add> expect(result.fnArray[0]).toEqual('save');
<add> expect(result.fnArray[1]).toEqual('setTextRise');
<add> expect(result.argsArray.length).toEqual(2);
<add> expect(result.argsArray[1].length).toEqual(1);
<add> expect(result.argsArray[1][0]).toEqual(5);
<add> });
<ide> });
<ide> });
<ide>
| 3
|
Java
|
Java
|
fix default values for translatex/y props
|
c6532a94a6b2710146b1b71244e6a283efafc3be
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/BaseViewManager.java
<ide> public void setScaleY(T view, float scaleY) {
<ide> }
<ide>
<ide> @Deprecated
<del> @ReactProp(name = PROP_TRANSLATE_X, defaultFloat = 1f)
<add> @ReactProp(name = PROP_TRANSLATE_X, defaultFloat = 0f)
<ide> public void setTranslateX(T view, float translateX) {
<ide> view.setTranslationX(PixelUtil.toPixelFromDIP(translateX));
<ide> }
<ide>
<ide> @Deprecated
<del> @ReactProp(name = PROP_TRANSLATE_Y, defaultFloat = 1f)
<add> @ReactProp(name = PROP_TRANSLATE_Y, defaultFloat = 0f)
<ide> public void setTranslateY(T view, float translateY) {
<ide> view.setTranslationY(PixelUtil.toPixelFromDIP(translateY));
<ide> }
| 1
|
Ruby
|
Ruby
|
test actual content of permanent cookie
|
e1579033100fe5a5738791c6f2fd4309c7ca3d78
|
<ide><path>actionpack/test/dispatch/cookies_test.rb
<ide> def test_setting_the_same_value_to_cookie
<ide> def test_setting_the_same_value_to_permanent_cookie
<ide> request.cookies[:user_name] = 'Jamie'
<ide> get :set_permanent_cookie
<del> assert response.cookies, 'user_name' => 'Jamie'
<add> assert_equal response.cookies, 'user_name' => 'Jamie'
<ide> end
<ide>
<ide> def test_setting_with_escapable_characters
| 1
|
Javascript
|
Javascript
|
run babel-node with inspect flag in debug
|
9fa10c9f3810b9bd4159ce18cc8aae22a5e2975f
|
<ide><path>gulpfile.js
<ide> function delRev(dest, manifestName) {
<ide>
<ide> gulp.task('serve', function(cb) {
<ide> let called = false;
<add> let execParams = path.normalize('node_modules/.bin/babel-node');
<add> // When in development we can spawn a node debugger
<add> // https://nodejs.org/en/docs/inspector/
<add> if (__DEV__) {
<add> execParams = execParams + ' --inspect';
<add> }
<ide> const monitor = nodemon({
<ide> script: paths.server,
<ide> ext: '.jsx .js .json',
<ide> ignore: paths.serverIgnore,
<del> exec: path.normalize('node_modules/.bin/babel-node'),
<add> exec: execParams,
<ide> env: {
<ide> NODE_ENV: process.env.NODE_ENV || 'development',
<ide> DEBUG: process.env.DEBUG || 'fcc:*',
| 1
|
Text
|
Text
|
fix import statement in od g3doc
|
9bf1fd02f6c44efbf0d4690d513e90fc77559746
|
<ide><path>research/object_detection/g3doc/using_your_own_dataset.md
<ide> Instead of writing all tf.Example protos to a single file as shown in
<ide>
<ide> ```python
<ide> import contextlib2
<del>from google3.third_party.tensorflow_models.object_detection.dataset_tools import tf_record_creation_util
<add>from object_detection.dataset_tools import tf_record_creation_util
<ide>
<ide> num_shards=10
<ide> output_filebase='/path/to/train_dataset.record'
| 1
|
Java
|
Java
|
clarify names during testing
|
2136f8f73175f193fd5fdd124d140b544a0f3ba3
|
<add><path>rxjava-core/src/main/java/rx/observers/SerializedObserverViaQueueAndCounter.java
<del><path>rxjava-core/src/main/java/rx/observers/SerializedObserver.java
<ide>
<ide> import rx.Observer;
<ide>
<del>public class SerializedObserver<T> implements Observer<T> {
<add>public class SerializedObserverViaQueueAndCounter<T> implements Observer<T> {
<ide> private final Observer<? super T> actual;
<ide> private final AtomicInteger count = new AtomicInteger();
<ide> private final ConcurrentLinkedQueue<Object> queue = new ConcurrentLinkedQueue<Object>();
<ide> private static class ErrorSentinel extends Sentinel {
<ide> }
<ide> }
<ide>
<del> public SerializedObserver(Observer<? super T> s) {
<add> public SerializedObserverViaQueueAndCounter(Observer<? super T> s) {
<ide> this.actual = s;
<ide> }
<ide>
<add><path>rxjava-core/src/test/java/rx/observers/SerializedObserverViaQueueAndCounterTest.java
<del><path>rxjava-core/src/test/java/rx/observers/SerializedObserverTest.java
<ide> import rx.Subscriber;
<ide> import rx.Subscription;
<ide>
<del>public class SerializedObserverTest {
<add>public class SerializedObserverViaQueueAndCounterTest {
<ide>
<ide> @Mock
<ide> Subscriber<String> observer;
<ide> public void testSingleThreadedBasic() {
<ide> TestSingleThreadedObservable onSubscribe = new TestSingleThreadedObservable(s, "one", "two", "three");
<ide> Observable<String> w = Observable.create(onSubscribe);
<ide>
<del> SerializedObserver<String> aw = new SerializedObserver<String>(observer);
<add> SerializedObserverViaQueueAndCounter<String> aw = new SerializedObserverViaQueueAndCounter<String>(observer);
<ide>
<ide> w.subscribe(aw);
<ide> onSubscribe.waitToFinish();
<ide> public void testMultiThreadedBasic() {
<ide> Observable<String> w = Observable.create(onSubscribe);
<ide>
<ide> BusyObserver busyObserver = new BusyObserver();
<del> SerializedObserver<String> aw = new SerializedObserver<String>(busyObserver);
<add> SerializedObserverViaQueueAndCounter<String> aw = new SerializedObserverViaQueueAndCounter<String>(busyObserver);
<ide>
<ide> w.subscribe(aw);
<ide> onSubscribe.waitToFinish();
<ide> public void testMultiThreadedWithNPE() throws InterruptedException {
<ide> Observable<String> w = Observable.create(onSubscribe);
<ide>
<ide> BusyObserver busyObserver = new BusyObserver();
<del> SerializedObserver<String> aw = new SerializedObserver<String>(busyObserver);
<add> SerializedObserverViaQueueAndCounter<String> aw = new SerializedObserverViaQueueAndCounter<String>(busyObserver);
<ide>
<ide> w.subscribe(aw);
<ide> onSubscribe.waitToFinish();
<ide> public void testMultiThreadedWithNPEinMiddle() {
<ide> Observable<String> w = Observable.create(onSubscribe);
<ide>
<ide> BusyObserver busyObserver = new BusyObserver();
<del> SerializedObserver<String> aw = new SerializedObserver<String>(busyObserver);
<add> SerializedObserverViaQueueAndCounter<String> aw = new SerializedObserverViaQueueAndCounter<String>(busyObserver);
<ide>
<ide> w.subscribe(aw);
<ide> onSubscribe.waitToFinish();
<ide> public void runOutOfOrderConcurrencyTest() {
<ide> try {
<ide> TestConcurrencyObserver tw = new TestConcurrencyObserver();
<ide> // we need Synchronized + SafeSubscriber to handle synchronization plus life-cycle
<del> SerializedObserver<String> w = new SerializedObserver<String>(new SafeSubscriber<String>(tw));
<add> SerializedObserverViaQueueAndCounter<String> w = new SerializedObserverViaQueueAndCounter<String>(new SafeSubscriber<String>(tw));
<ide>
<ide> Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
<ide> Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
<ide> public void runConcurrencyTest() {
<ide> try {
<ide> TestConcurrencyObserver tw = new TestConcurrencyObserver();
<ide> // we need Synchronized + SafeSubscriber to handle synchronization plus life-cycle
<del> SerializedObserver<String> w = new SerializedObserver<String>(new SafeSubscriber<String>(tw));
<add> SerializedObserverViaQueueAndCounter<String> w = new SerializedObserverViaQueueAndCounter<String>(new SafeSubscriber<String>(tw));
<ide>
<ide> Future<?> f1 = tp.submit(new OnNextThread(w, 12000));
<ide> Future<?> f2 = tp.submit(new OnNextThread(w, 5000));
<ide><path>rxjava-core/src/test/java/rx/observers/SerializedObserverViaStateMachineTest.java
<ide> package rx.observers;
<ide>
<del>public class SerializedObserverViaStateMachineTest extends SerializedObserverTest {
<add>public class SerializedObserverViaStateMachineTest extends SerializedObserverViaQueueAndCounterTest {
<ide>
<ide> }
| 3
|
Javascript
|
Javascript
|
show one hint at a time
|
ad83a2e3f4aaabfd2cd5efb086b6225376fa232c
|
<ide><path>client/src/templates/Challenges/classic/Editor.js
<ide> const propTypes = {
<ide> inAccessibilityMode: PropTypes.bool.isRequired,
<ide> initialEditorContent: PropTypes.string,
<ide> initialExt: PropTypes.string,
<del> output: PropTypes.string,
<add> output: PropTypes.arrayOf(PropTypes.string),
<ide> saveEditorContent: PropTypes.func.isRequired,
<ide> setAccessibilityMode: PropTypes.func.isRequired,
<ide> setEditorFocusability: PropTypes.func,
<ide> class Editor extends Component {
<ide> createOutputNode() {
<ide> if (this._outputNode) return this._outputNode;
<ide> const outputNode = document.createElement('div');
<del>
<del> outputNode.innerHTML = 'TESTS GO HERE';
<add> const statusNode = document.createElement('div');
<add> const hintNode = document.createElement('div');
<add> outputNode.appendChild(statusNode);
<add> outputNode.appendChild(hintNode);
<add> hintNode.setAttribute('id', 'test-output');
<add> statusNode.setAttribute('id', 'test-status');
<add> statusNode.innerHTML = '// tests';
<ide>
<ide> // TODO: does it?
<ide> // The z-index needs increasing as ViewZones default to below the lines.
<ide> class Editor extends Component {
<ide> }
<ide>
<ide> if (this._editor) {
<add> const { output } = this.props;
<ide> if (this.props.output !== prevProps.output && this._outputNode) {
<ide> // TODO: output gets wiped when the preview gets updated, keeping the
<ide> // display is an anti-pattern (the render should not ignore props!).
<ide> // The correct solution is probably to create a new redux variable
<ide> // (shownHint,maybe) and have that persist through previews. But, for
<ide> // now:
<del> if (this.props.output) {
<del> this._outputNode.innerHTML = this.props.output;
<add> if (output) {
<add> console.log('OUTPUT', output);
<add> if (output[0]) {
<add> document.getElementById('test-status').innerHTML = output[0];
<add> }
<add>
<add> if (output[1]) {
<add> document.getElementById('test-output').innerHTML = output[1];
<add> }
<add>
<ide> if (this.data[fileKey].startEditDecId) {
<ide> this.updateOutputZone();
<ide> }
| 1
|
Ruby
|
Ruby
|
decrease string allocations in url_options
|
83ee043c6834914607849ae9cd3b9eab6b41702c
|
<ide><path>actionpack/lib/action_controller/metal/url_for.rb
<ide> def url_options
<ide> if original_script_name
<ide> options[:original_script_name] = original_script_name
<ide> else
<del> options[:script_name] = same_origin ? request.script_name.dup : script_name
<add> if same_origin
<add> options[:script_name] = request.script_name.empty? ? "".freeze : request.script_name.dup
<add> else
<add> options[:script_name] = script_name
<add> end
<ide> end
<ide> options.freeze
<ide> else
| 1
|
PHP
|
PHP
|
fix mistake in merging changes from master
|
0a6e73cbc38458d487b0d42d828312020395cfa7
|
<ide><path>tests/TestCase/Shell/Task/AssetsTaskTest.php
<ide> public function testCopyOverwrite()
<ide> $this->assertFileEquals($path . DS . 'root.js', $pluginPath . DS . 'root.js');
<ide>
<ide> $folder = new Folder($path);
<add> $folder->delete();
<ide> }
<ide>
<ide> /**
| 1
|
Javascript
|
Javascript
|
optimize the logic of isaxioserror
|
6fca6a7027caeb4c0c7d0305ab4182bfd8a65536
|
<ide><path>lib/helpers/isAxiosError.js
<ide> 'use strict';
<ide>
<add>var utils = require('./../utils');
<add>
<ide> /**
<ide> * Determines whether the payload is an error thrown by Axios
<ide> *
<ide> * @param {*} payload The value to test
<ide> * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false
<ide> */
<ide> module.exports = function isAxiosError(payload) {
<del> return (typeof payload === 'object') && (payload.isAxiosError === true);
<add> return utils.isObject(payload) && (payload.isAxiosError === true);
<ide> };
<ide><path>test/specs/helpers/isAxiosError.spec.js
<ide> describe('helpers::isAxiosError', function () {
<ide> expect(isAxiosError(new Error('Boom!')))
<ide> .toBe(false);
<ide> });
<add>
<add> it('should return false if the error is null', function () {
<add> expect(isAxiosError(null))
<add> .toBe(false);
<add> });
<ide> });
| 2
|
Text
|
Text
|
add missing deprecation code
|
71cb829dca84d0bb49d5e67142512d3011aba40b
|
<ide><path>doc/api/deprecations.md
<ide> settings set when the Node.js binary was compiled. However, the property has
<ide> been mutable by user code making it impossible to rely on. The ability to
<ide> change the value has been deprecated and will be disabled in the future.
<ide>
<del>### DEP0XXX: Main index lookup and extension searching
<add>### DEP0151: Main index lookup and extension searching
<ide> <!-- YAML
<ide> changes:
<ide> - version: REPLACEME
| 1
|
Python
|
Python
|
add version string to libcloud
|
61bfc62937176b580b8b6ae12a90c5b76b00d50d
|
<ide><path>libcloud/__init__.py
<ide> """
<ide> libcloud provides a unified interface to the cloud computing resources.
<ide> """
<add>
<add>__version__ = "0.1.1-dev"
<ide>\ No newline at end of file
| 1
|
Ruby
|
Ruby
|
use short-style lambdas
|
783dbcc937b3f8afb79e7e8ff7cb6ff9f591746c
|
<ide><path>Library/Homebrew/cask/test/cask/artifact/alt_target_test.rb
<ide> let(:cask) { Hbc.load("with-alt-target") }
<ide>
<ide> let(:install_phase) {
<del> lambda { Hbc::Artifact::App.new(cask).install_phase }
<add> -> { Hbc::Artifact::App.new(cask).install_phase }
<ide> }
<ide>
<ide> let(:source_path) { cask.staged_path.join("Caffeine.app") }
<ide><path>Library/Homebrew/cask/test/cask/artifact/app_test.rb
<ide> let(:source_path) { cask.staged_path.join("Caffeine.app") }
<ide> let(:target_path) { Hbc.appdir.join("Caffeine.app") }
<ide>
<del> let(:install_phase) {
<del> lambda { app.install_phase }
<del> }
<del>
<del> let(:uninstall_phase) {
<del> lambda { app.uninstall_phase }
<del> }
<add> let(:install_phase) { -> { app.install_phase } }
<add> let(:uninstall_phase) { -> { app.uninstall_phase } }
<ide>
<ide> before do
<ide> TestHelper.install_without_artifacts(cask)
<ide><path>Library/Homebrew/cask/test/cask/artifact/generic_artifact_test.rb
<ide> let(:cask) { Hbc.load("with-generic-artifact") }
<ide>
<ide> let(:install_phase) {
<del> lambda { Hbc::Artifact::Artifact.new(cask).install_phase }
<add> -> { Hbc::Artifact::Artifact.new(cask).install_phase }
<ide> }
<ide>
<ide> let(:source_path) { cask.staged_path.join("Caffeine.app") }
<ide><path>Library/Homebrew/cask/test/cask/artifact/suite_test.rb
<ide> describe Hbc::Artifact::Suite do
<ide> let(:cask) { Hbc.load("with-suite") }
<ide>
<del> let(:install_phase) {
<del> lambda { Hbc::Artifact::Suite.new(cask).install_phase }
<del> }
<add> let(:install_phase) { -> { Hbc::Artifact::Suite.new(cask).install_phase } }
<ide>
<ide> let(:target_path) { Hbc.appdir.join("Caffeine") }
<ide> let(:source_path) { cask.staged_path.join("Caffeine") }
<ide><path>Library/Homebrew/cask/test/cask/artifact/two_apps_correct_test.rb
<ide> let(:cask) { Hbc.load("with-two-apps-correct") }
<ide>
<ide> let(:install_phase) {
<del> lambda { Hbc::Artifact::App.new(cask).install_phase }
<add> -> { Hbc::Artifact::App.new(cask).install_phase }
<ide> }
<ide>
<ide> let(:source_path_mini) { cask.staged_path.join("Caffeine Mini.app") }
| 5
|
Javascript
|
Javascript
|
use setimmediate for recursive deferral
|
a12c42ca2f8d5ce71c75cab334a53bd71bdaea09
|
<ide><path>test/fixtures/catch-stdout-error.js
<ide> function write() {
<ide> } catch (ex) {
<ide> throw new Error('this should never happen');
<ide> }
<del> process.nextTick(function() {
<add> setImmediate(function() {
<ide> write();
<ide> });
<ide> }
| 1
|
Java
|
Java
|
sanitize request url in resourceurlencodingfilter
|
0b9c3de320df81acd06dcfd927faadf72fb66409
|
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilter.java
<ide> public String encodeURL(String url) {
<ide> initIndexLookupPath(resourceUrlProvider);
<ide> if (url.length() >= this.indexLookupPath) {
<ide> String prefix = url.substring(0, this.indexLookupPath);
<del> String lookupPath = url.substring(this.indexLookupPath);
<add> int suffixIndex = getQueryParamsIndex(url);
<add> String suffix = url.substring(suffixIndex);
<add> String lookupPath = url.substring(this.indexLookupPath, suffixIndex);
<ide> lookupPath = resourceUrlProvider.getForLookupPath(lookupPath);
<ide> if (lookupPath != null) {
<del> return super.encodeURL(prefix + lookupPath);
<add> return super.encodeURL(prefix + lookupPath + suffix);
<ide> }
<ide> }
<ide> return super.encodeURL(url);
<ide> private void initIndexLookupPath(ResourceUrlProvider urlProvider) {
<ide> this.indexLookupPath = requestUri.lastIndexOf(lookupPath);
<ide> }
<ide> }
<add>
<add> private int getQueryParamsIndex(String url) {
<add> int index = url.indexOf("?");
<add> return index > 0 ? index : url.length();
<add> }
<ide> }
<ide>
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceUrlProvider.java
<ide> public final String getForRequestUrl(HttpServletRequest request, String requestU
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Getting resource URL for requestURL=" + requestUrl);
<ide> }
<del> int index = getLookupPathIndex(request);
<del> String prefix = requestUrl.substring(0, index);
<del> String lookupPath = requestUrl.substring(index);
<add> int prefixIndex = getLookupPathIndex(request);
<add> int suffixIndex = getQueryParamsIndex(requestUrl);
<add> String prefix = requestUrl.substring(0, prefixIndex);
<add> String suffix = requestUrl.substring(suffixIndex);
<add> String lookupPath = requestUrl.substring(prefixIndex, suffixIndex);
<ide> String resolvedLookupPath = getForLookupPath(lookupPath);
<del> return (resolvedLookupPath != null) ? prefix + resolvedLookupPath : null;
<add> return (resolvedLookupPath != null) ? prefix + resolvedLookupPath + suffix : null;
<ide> }
<ide>
<ide> private int getLookupPathIndex(HttpServletRequest request) {
<ide> private int getLookupPathIndex(HttpServletRequest request) {
<ide> return requestUri.indexOf(lookupPath);
<ide> }
<ide>
<add> private int getQueryParamsIndex(String lookupPath) {
<add> int index = lookupPath.indexOf("?");
<add> return index > 0 ? index : lookupPath.length();
<add> }
<add>
<ide> /**
<ide> * Compare the given path against configured resource handler mappings and
<ide> * if a match is found use the {@code ResourceResolver} chain of the matched
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlEncodingFilterTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void doFilter(ServletRequest request, ServletResponse response) throws IO
<ide> });
<ide> }
<ide>
<add> // SPR-13374
<add> @Test
<add> public void encodeURLWithRequestParams() throws Exception {
<add> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo");
<add> request.setContextPath("/");
<add> request.setAttribute(ResourceUrlProviderExposingInterceptor.RESOURCE_URL_PROVIDER_ATTR, this.resourceUrlProvider);
<add> MockHttpServletResponse response = new MockHttpServletResponse();
<add>
<add> this.filter.doFilterInternal(request, response, new FilterChain() {
<add> @Override
<add> public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
<add> String result = ((HttpServletResponse)response).encodeURL("/resources/bar.css?foo=bar&url=http://example.org");
<add> assertEquals("/resources/bar-11e16cf79faee7ac698c805cf28248d2.css?foo=bar&url=http://example.org", result);
<add> }
<add> });
<add> }
<add>
<ide> protected ResourceUrlProvider createResourceUrlProvider(List<ResourceResolver> resolvers) {
<ide> ResourceHttpRequestHandler handler = new ResourceHttpRequestHandler();
<ide> handler.setLocations(Arrays.asList(new ClassPathResource("test/", getClass())));
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/resource/ResourceUrlProviderTests.java
<ide> import org.springframework.context.annotation.Configuration;
<ide> import org.springframework.core.io.ClassPathResource;
<ide> import org.springframework.core.io.Resource;
<add>import org.springframework.mock.web.test.MockHttpServletRequest;
<ide> import org.springframework.mock.web.test.MockServletContext;
<ide> import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
<ide> import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
<ide> public void getStaticResourceUrl() {
<ide> assertEquals("/resources/foo.css", url);
<ide> }
<ide>
<add> // SPR-13374
<add> @Test
<add> public void getStaticResourceUrlRequestWithRequestParams() {
<add> initTranslator();
<add> MockHttpServletRequest request = new MockHttpServletRequest();
<add> request.setContextPath("/");
<add> request.setRequestURI("/");
<add>
<add> String url = this.translator.getForRequestUrl(request, "/resources/foo.css?foo=bar&url=http://example.org");
<add> assertEquals("/resources/foo.css?foo=bar&url=http://example.org", url);
<add> }
<add>
<ide> @Test
<ide> public void getFingerprintedResourceUrl() {
<ide> Map<String, VersionStrategy> versionStrategyMap = new HashMap<>();
| 4
|
Javascript
|
Javascript
|
update the loader so test pages always get jquery
|
14b393d0d64e119db7754b1075317a673810929c
|
<ide><path>test/jquery.js
<ide> ( function() {
<ide> /* global loadTests: false */
<ide>
<del> var src,
<del> path = window.location.pathname.split( "test" )[ 0 ],
<add> var path = window.location.pathname.split( "test" )[ 0 ],
<ide> QUnit = window.QUnit || parent.QUnit,
<del> require = window.require || parent.require;
<del>
<del> // iFrames won't load AMD (the iframe tests synchronously expect jQuery to be there)
<del> QUnit.config.urlConfig.push( {
<del> id: "amd",
<del> label: "Load with AMD",
<del> tooltip: "Load the AMD jQuery file (and its dependencies)"
<del> } );
<del>
<del> // If QUnit is on window, this is the main window
<del> // This detection allows AMD tests to be run in an iframe
<del> if ( QUnit.urlParams.amd && window.QUnit ) {
<add> require = window.require || parent.require,
<add>
<add> // Default to unminified jQuery for directly-opened iframes
<add> urlParams = QUnit ?
<add> QUnit.urlParams :
<add> { dev: true },
<add> src = urlParams.dev ?
<add> "dist/jquery.js" :
<add> "dist/jquery.min.js";
<add>
<add> // Define configuration parameters controlling how jQuery is loaded
<add> if ( QUnit ) {
<add> QUnit.config.urlConfig.push( {
<add> id: "amd",
<add> label: "Load with AMD",
<add> tooltip: "Load the AMD jQuery file (and its dependencies)"
<add> } );
<add> QUnit.config.urlConfig.push( {
<add> id: "dev",
<add> label: "Load unminified",
<add> tooltip: "Load the development (unminified) jQuery file"
<add> } );
<add> }
<add>
<add> // Honor AMD loading on the main window (detected by seeing QUnit on it).
<add> // This doesn't apply to iframes because they synchronously expect jQuery to be there.
<add> if ( urlParams.amd && window.QUnit ) {
<ide> require.config( {
<ide> baseUrl: path
<ide> } );
<ide> } else {
<ide> require( [ src ] );
<ide> }
<del> return;
<del> }
<ide>
<del> // Config parameter to use minified jQuery
<del> QUnit.config.urlConfig.push( {
<del> id: "dev",
<del> label: "Load unminified",
<del> tooltip: "Load the development (unminified) jQuery file"
<del> } );
<del> if ( QUnit.urlParams.dev ) {
<del> src = "dist/jquery.js";
<add> // Otherwise, load synchronously
<ide> } else {
<del> src = "dist/jquery.min.js";
<del> }
<del>
<del> // Load jQuery
<del> document.write( "<script id='jquery-js' src='" + path + src + "'><\x2Fscript>" );
<add> document.write( "<script id='jquery-js' src='" + path + src + "'><\x2Fscript>" );
<ide>
<del> // Synchronous-only tests
<del> // Other tests are loaded from the test page
<del> if ( typeof loadTests !== "undefined" ) {
<del> document.write( "<script src='" + path + "test/unit/ready.js'><\x2Fscript>" );
<add> // Synchronous-only tests (other tests are loaded from the test page)
<add> if ( typeof loadTests !== "undefined" ) {
<add> document.write( "<script src='" + path + "test/unit/ready.js'><\x2Fscript>" );
<add> }
<ide> }
<ide>
<ide> } )();
| 1
|
Javascript
|
Javascript
|
fix imports to avoid ember-htmlbars
|
8877657d5e6be741b5d21069847038bf05414448
|
<ide><path>packages/ember-application/tests/system/visit_test.js
<ide> import Application from 'ember-application/system/application';
<ide> import ApplicationInstance from 'ember-application/system/application-instance';
<ide> import Route from 'ember-routing/system/route';
<ide> import Router from 'ember-routing/system/router';
<del>import Component from 'ember-htmlbars/component';
<add>import Component from 'ember-templates/component';
<ide> import { compile } from 'ember-template-compiler/tests/utils/helpers';
<ide> import jQuery from 'ember-views/system/jquery';
<ide>
<ide><path>packages/ember-metal/tests/events_test.js
<ide> import { Mixin } from 'ember-metal/mixin';
<ide> import { meta } from 'ember-metal/meta';
<del>import Component from 'ember-htmlbars/component';
<add>import Component from 'ember-templates/component';
<ide>
<ide> import {
<ide> on,
<ide><path>packages/ember-views/tests/views/component_test.js
<ide> import run from 'ember-metal/run_loop';
<ide> import Service from 'ember-runtime/system/service';
<ide> import inject from 'ember-runtime/inject';
<ide>
<del>import Component from 'ember-htmlbars/component';
<add>import Component from 'ember-templates/component';
<ide>
<ide> import buildOwner from 'container/tests/test-helpers/build-owner';
<ide> import computed from 'ember-metal/computed';
<ide><path>packages/ember/tests/component_registration_test.js
<ide> import run from 'ember-metal/run_loop';
<ide>
<ide> import Application from 'ember-application/system/application';
<ide> import Router from 'ember-routing/system/router';
<del>import { compile } from 'ember-template-compiler/tests/utils/helpers';
<del>import helpers from 'ember-htmlbars/helpers';
<add>import { compile } from 'ember-template-compiler';
<ide> import Component from 'ember-templates/component';
<ide> import jQuery from 'ember-views/system/jquery';
<del>import { A as emberA } from 'ember-runtime/system/native_array';
<ide> import { setTemplates, set as setTemplate } from 'ember-templates/template_registry';
<ide> import isEnabled from 'ember-metal/features';
<ide> import require from 'require';
<ide> if (isEnabled('ember-glimmer')) {
<ide> }
<ide>
<ide> let App, appInstance;
<del>let originalHelpers;
<del>
<del>const { keys } = Object;
<ide>
<ide> function prepare() {
<ide> setTemplate('components/expand-it', compile('<p>hello {{yield}}</p>'));
<ide> setTemplate('application', compile('Hello world {{#expand-it}}world{{/expand-it}}'));
<del>
<del> originalHelpers = emberA(keys(helpers));
<ide> }
<ide>
<ide> function cleanup() {
<ide> function cleanup() {
<ide> App = appInstance = null;
<ide> } finally {
<ide> setTemplates({});
<del> cleanupHelpers();
<ide> }
<ide> });
<ide> }
<ide>
<del>function cleanupHelpers() {
<del> let included;
<del>
<del> keys(helpers).
<del> forEach(name => {
<del> if (isEnabled('ember-runtime-enumerable-includes')) {
<del> included = originalHelpers.includes(name);
<del> } else {
<del> included = originalHelpers.contains(name);
<del> }
<del>
<del> if (!included) {
<del> delete helpers[name];
<del> }
<del> });
<del>}
<del>
<ide> QUnit.module('Application Lifecycle - Component Registration', {
<ide> setup: prepare,
<ide> teardown: cleanup
<ide> QUnit.test('Late-registered components can be rendered with custom `layout` prop
<ide> });
<ide>
<ide> equal(jQuery('#wrapper').text(), 'there goes watch him as he GOES', 'The component is composed correctly');
<del> ok(!helpers['my-hero'], 'Component wasn\'t saved to global helpers hash');
<ide> });
<ide>
<ide> QUnit.test('Late-registered components can be rendered with template registered on the container', function() {
<ide> QUnit.test('Late-registered components can be rendered with template registered
<ide> });
<ide>
<ide> equal(jQuery('#wrapper').text(), 'hello world funkytowny-funkytowny!!!', 'The component is composed correctly');
<del> ok(!helpers['sally-rutherford'], 'Component wasn\'t saved to global helpers hash');
<ide> });
<ide>
<ide> QUnit.test('Late-registered components can be rendered with ONLY the template registered on the container', function() {
<ide> QUnit.test('Late-registered components can be rendered with ONLY the template re
<ide> });
<ide>
<ide> equal(jQuery('#wrapper').text(), 'hello world goodfreakingTIMES-goodfreakingTIMES!!!', 'The component is composed correctly');
<del> ok(!helpers['borf-snorlax'], 'Component wasn\'t saved to global helpers hash');
<ide> });
<ide>
<ide> QUnit.test('Assigning layoutName to a component should setup the template as a layout', function() {
| 4
|
Javascript
|
Javascript
|
add missing space in error message
|
9c5ded31897fabc40be073ff4bfab5c7fd8f2389
|
<ide><path>lib/internal/modules/cjs/loader.js
<ide> function createRequireFromPath(filename) {
<ide>
<ide> Module.createRequireFromPath = createRequireFromPath;
<ide>
<del>const createRequireError = 'must be a file URL object, file URL string, or' +
<add>const createRequireError = 'must be a file URL object, file URL string, or ' +
<ide> 'absolute path string';
<ide>
<ide> function createRequire(filename) {
<ide><path>test/parallel/test-module-create-require.js
<ide> assert.throws(() => {
<ide> assert.throws(() => {
<ide> createRequire({});
<ide> }, {
<del> code: 'ERR_INVALID_ARG_VALUE'
<add> code: 'ERR_INVALID_ARG_VALUE',
<add> message: 'The argument \'filename\' must be a file URL object, file URL ' +
<add> 'string, or absolute path string. Received {}'
<ide> });
| 2
|
Python
|
Python
|
fix max length in run_plm script
|
367f497dec8905ac37c2947be998f4469fdade6b
|
<ide><path>examples/language-modeling/run_plm.py
<ide> class DataTrainingArguments:
<ide> overwrite_cache: bool = field(
<ide> default=False, metadata={"help": "Overwrite the cached training and evaluation sets"}
<ide> )
<del> max_seq_length: Optional[int] = field(
<del> default=None,
<add> max_seq_length: int = field(
<add> default=512,
<ide> metadata={
<ide> "help": "The maximum total input sequence length after tokenization. Sequences longer "
<del> "than this will be truncated. Default to the max input length of the model."
<add> "than this will be truncated."
<ide> },
<ide> )
<ide> preprocessing_num_workers: Optional[int] = field(
<ide> def tokenize_function(examples):
<ide> load_from_cache_file=not data_args.overwrite_cache,
<ide> )
<ide>
<del> if data_args.max_seq_length is None:
<del> max_seq_length = tokenizer.model_max_length
<del> else:
<del> if data_args.max_seq_length > tokenizer.model_max_length:
<del> logger.warn(
<del> f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
<del> f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
<del> )
<del> max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
<add> if data_args.max_seq_length > tokenizer.model_max_length:
<add> logger.warn(
<add> f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the"
<add> f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."
<add> )
<add> max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length)
<ide>
<ide> # Main data processing function that will concatenate all texts from our dataset and generate chunks of
<ide> # max_seq_length.
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.