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 |
|---|---|---|---|---|---|
Mixed | Ruby | remove deprecated i18n scopes in active record | 00e3973a31181decc1b1574bf78bfa0226f0f04b | <ide><path>activerecord/CHANGELOG.md
<add>* Remove deprecated `activerecord.errors.messages.restrict_dependent_destroy.one` and
<add> `activerecord.errors.messages.restrict_dependent_destroy.many` i18n scopes.
<add>
<add> *Rafael Mendonça França*
<add>
<ide> * Allow passing extra flags to `db:structure:load` and `db:structure:dump`
<ide>
<ide> Introduces `ActiveRecord::Tasks::DatabaseTasks.structure_(load|dump)_flags` to customize the
<ide><path>activerecord/lib/active_record/associations/has_many_association.rb
<ide> def handle_dependency
<ide> when :restrict_with_error
<ide> unless empty?
<ide> record = owner.class.human_attribute_name(reflection.name).downcase
<del> message = owner.errors.generate_message(:base, :'restrict_dependent_destroy.many', record: record, raise: true) rescue nil
<del> if message
<del> ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
<del> The error key `:'restrict_dependent_destroy.many'` has been deprecated and will be removed in Rails 5.1.
<del> Please use `:'restrict_dependent_destroy.has_many'` instead.
<del> MESSAGE
<del> end
<del> owner.errors.add(:base, message || :'restrict_dependent_destroy.has_many', record: record)
<add> owner.errors.add(:base, :'restrict_dependent_destroy.has_many', record: record)
<ide> throw(:abort)
<ide> end
<ide>
<ide><path>activerecord/lib/active_record/associations/has_one_association.rb
<ide> def handle_dependency
<ide> when :restrict_with_error
<ide> if load_target
<ide> record = owner.class.human_attribute_name(reflection.name).downcase
<del> message = owner.errors.generate_message(:base, :'restrict_dependent_destroy.one', record: record, raise: true) rescue nil
<del> if message
<del> ActiveSupport::Deprecation.warn(<<-MESSAGE.squish)
<del> The error key `:'restrict_dependent_destroy.one'` has been deprecated and will be removed in Rails 5.1.
<del> Please use `:'restrict_dependent_destroy.has_one'` instead.
<del> MESSAGE
<del> end
<del> owner.errors.add(:base, message || :'restrict_dependent_destroy.has_one', record: record)
<add> owner.errors.add(:base, :'restrict_dependent_destroy.has_one', record: record)
<ide> throw(:abort)
<ide> end
<ide>
<ide><path>activerecord/test/cases/associations/has_many_associations_test.rb
<ide> def test_restrict_with_exception
<ide> assert firm.companies.exists?(name: "child")
<ide> end
<ide>
<del> def test_restrict_with_error_is_deprecated_using_key_many
<del> I18n.backend = I18n::Backend::Simple.new
<del> I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { many: "message for deprecated key" } } } }
<del>
<del> firm = RestrictedWithErrorFirm.create!(name: "restrict")
<del> firm.companies.create(name: "child")
<del>
<del> assert !firm.companies.empty?
<del>
<del> assert_deprecated { firm.destroy }
<del>
<del> assert !firm.errors.empty?
<del>
<del> assert_equal "message for deprecated key", firm.errors[:base].first
<del> assert RestrictedWithErrorFirm.exists?(name: "restrict")
<del> assert firm.companies.exists?(name: "child")
<del> ensure
<del> I18n.backend.reload!
<del> end
<del>
<ide> def test_restrict_with_error
<ide> firm = RestrictedWithErrorFirm.create!(name: "restrict")
<ide> firm.companies.create(name: "child")
<ide><path>activerecord/test/cases/associations/has_one_associations_test.rb
<ide> def test_restrict_with_exception
<ide> assert firm.account.present?
<ide> end
<ide>
<del> def test_restrict_with_error_is_deprecated_using_key_one
<del> I18n.backend = I18n::Backend::Simple.new
<del> I18n.backend.store_translations :en, activerecord: { errors: { messages: { restrict_dependent_destroy: { one: "message for deprecated key" } } } }
<del>
<del> firm = RestrictedWithErrorFirm.create!(name: "restrict")
<del> firm.create_account(credit_limit: 10)
<del>
<del> assert_not_nil firm.account
<del>
<del> assert_deprecated { firm.destroy }
<del>
<del> assert !firm.errors.empty?
<del> assert_equal "message for deprecated key", firm.errors[:base].first
<del> assert RestrictedWithErrorFirm.exists?(name: "restrict")
<del> assert firm.account.present?
<del> ensure
<del> I18n.backend.reload!
<del> end
<del>
<ide> def test_restrict_with_error
<ide> firm = RestrictedWithErrorFirm.create!(name: "restrict")
<ide> firm.create_account(credit_limit: 10) | 5 |
Javascript | Javascript | remove unnecessary double test in navigator | 9584480261b310843d1c2445078e8f4ae661d982 | <ide><path>Libraries/CustomComponents/Navigator/Navigator.js
<ide> var Navigator = React.createClass({
<ide> key={'scene_' + getRouteID(route)}
<ide> ref={'scene_' + i}
<ide> onStartShouldSetResponderCapture={() => {
<del> return (this.state.transitionFromIndex != null) || (this.state.transitionFromIndex != null);
<add> return (this.state.transitionFromIndex != null);
<ide> }}
<ide> pointerEvents={disabledScenePointerEvents}
<ide> style={[styles.baseScene, this.props.sceneStyle, disabledSceneStyle]}> | 1 |
Ruby | Ruby | use cp because install warns on empty arrays | d18c016a274ca6239fe0e3b736af3d6dc291ff3e | <ide><path>Library/Homebrew/formula.rb
<ide> def brew
<ide> # so load any deps before this point! And exit asap afterwards
<ide> yield self
<ide> ensure
<del> (HOMEBREW_LOGS+name).install Dir["config.log", "CMakeCache.txt"]
<add> cp Dir["config.log", "CMakeCache.txt"], HOMEBREW_LOGS+name
<ide> end
<ide> end
<ide> end | 1 |
PHP | PHP | use dropifexists instead of drop | 3ecc0e39ed3b6c3c1053a7a5454ebd751f69a0d4 | <ide><path>database/migrations/2014_10_12_000000_create_users_table.php
<ide> public function up()
<ide> */
<ide> public function down()
<ide> {
<del> Schema::drop('users');
<add> Schema::dropIfExists('users');
<ide> }
<ide> }
<ide><path>database/migrations/2014_10_12_100000_create_password_resets_table.php
<ide> public function up()
<ide> */
<ide> public function down()
<ide> {
<del> Schema::drop('password_resets');
<add> Schema::dropIfExists('password_resets');
<ide> }
<ide> } | 2 |
Javascript | Javascript | fix loading showing before `pastdelay` | e2944c0aca59c84ead1dd13ef12cdf9462dcdcd9 | <ide><path>packages/next-server/lib/dynamic.js
<ide> export default function dynamic (dynamicOptions, options) {
<ide> let loadableFn = Loadable
<ide> let loadableOptions = {
<ide> // A loading component is not required, so we default it
<del> loading: ({ error, isLoading }) => {
<add> loading: ({ error, isLoading, pastDelay }) => {
<add> if (!pastDelay) return null
<ide> if (process.env.NODE_ENV === 'development') {
<ide> if (isLoading) {
<ide> return <DefaultLoading />
<ide><path>test/integration/basic/test/dynamic.js
<ide> export default (context, render) => {
<ide> })
<ide> })
<ide> describe('ssr:false option', () => {
<del> it('should render loading on the server side', async () => {
<add> it('should not render loading on the server side', async () => {
<ide> const $ = await get$('/dynamic/no-ssr')
<ide> expect($('body').html()).not.toContain('"dynamicIds"')
<del> expect($('p').text()).toBe('loading...')
<add> expect($('body').text()).not.toMatch('loading...')
<ide> })
<ide>
<ide> it('should render the component on client side', async () => {
<ide><path>test/integration/production/test/dynamic.js
<ide> export default (context, render) => {
<ide> })
<ide> })
<ide> describe('ssr:false option', () => {
<del> it('should render loading on the server side', async () => {
<add> it('should not render loading on the server side', async () => {
<ide> const $ = await get$('/dynamic/no-ssr')
<del> expect($('p').text()).toBe('loading...')
<add> expect($('body').text()).not.toMatch('loading...')
<ide> })
<ide>
<ide> it('should render the component on client side', async () => { | 3 |
Go | Go | move "changes" to daemon/changes.go | 49e61f62ced4e111071cf9439e3264f06b008c6c | <ide><path>api/server/server.go
<ide> func getContainersChanges(eng *engine.Engine, version version.Version, w http.Re
<ide> if vars == nil {
<ide> return fmt.Errorf("Missing parameter")
<ide> }
<del> var job = eng.Job("changes", vars["name"])
<add> var job = eng.Job("container_changes", vars["name"])
<ide> streamJSON(job, w, false)
<ide>
<ide> return job.Run()
<ide><path>daemon/changes.go
<add>package daemon
<add>
<add>import (
<add> "github.com/docker/docker/engine"
<add>)
<add>
<add>func (daemon *Daemon) ContainerChanges(job *engine.Job) engine.Status {
<add> if n := len(job.Args); n != 1 {
<add> return job.Errorf("Usage: %s CONTAINER", job.Name)
<add> }
<add> name := job.Args[0]
<add> if container := daemon.Get(name); container != nil {
<add> outs := engine.NewTable("", 0)
<add> changes, err := container.Changes()
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> for _, change := range changes {
<add> out := &engine.Env{}
<add> if err := out.Import(change); err != nil {
<add> return job.Error(err)
<add> }
<add> outs.Add(out)
<add> }
<add> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<add> return job.Error(err)
<add> }
<add> } else {
<add> return job.Errorf("No such container: %s", name)
<add> }
<add> return engine.StatusOK
<add>}
<ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) Install(eng *engine.Engine) error {
<ide> if err := eng.Register("container_copy", daemon.ContainerCopy); err != nil {
<ide> return err
<ide> }
<add> if err := eng.Register("container_changes", daemon.ContainerChanges); err != nil {
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide><path>server/container.go
<ide> func (srv *Server) ContainerTop(job *engine.Job) engine.Status {
<ide> return job.Errorf("No such container: %s", name)
<ide> }
<ide>
<del>func (srv *Server) ContainerChanges(job *engine.Job) engine.Status {
<del> if n := len(job.Args); n != 1 {
<del> return job.Errorf("Usage: %s CONTAINER", job.Name)
<del> }
<del> name := job.Args[0]
<del> if container := srv.daemon.Get(name); container != nil {
<del> outs := engine.NewTable("", 0)
<del> changes, err := container.Changes()
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> for _, change := range changes {
<del> out := &engine.Env{}
<del> if err := out.Import(change); err != nil {
<del> return job.Error(err)
<del> }
<del> outs.Add(out)
<del> }
<del> if _, err := outs.WriteListTo(job.Stdout); err != nil {
<del> return job.Error(err)
<del> }
<del> } else {
<del> return job.Errorf("No such container: %s", name)
<del> }
<del> return engine.StatusOK
<del>}
<del>
<ide> func (srv *Server) Containers(job *engine.Job) engine.Status {
<ide> var (
<ide> foundBefore bool
<ide><path>server/init.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> "history": srv.ImageHistory,
<ide> "viz": srv.ImagesViz,
<ide> "log": srv.Log,
<del> "changes": srv.ContainerChanges,
<ide> "top": srv.ContainerTop,
<ide> "load": srv.ImageLoad,
<ide> "build": srv.Build, | 5 |
Ruby | Ruby | fix documentation of url_for module [ci skip] | e049319c778e638e090309e93daee3d2fe087b15 | <ide><path>actionpack/lib/action_controller/metal/url_for.rb
<ide> module ActionController
<ide> #
<ide> # In addition to <tt>AbstractController::UrlFor</tt>, this module accesses the HTTP layer to define
<ide> # url options like the +host+. In order to do so, this module requires the host class
<del> # to implement +env+ and +request+, which need to be a Rack-compatible.
<add> # to implement +env+ which needs to be Rack-compatible and +request+
<add> # which is either instance of +ActionDispatch::Request+ or an object
<add> # that responds to <tt>host</tt>, <tt>optional_port</tt>, <tt>protocol</tt> and
<add> # <tt>symbolized_path_parameter</tt> methods.
<ide> #
<ide> # class RootUrl
<ide> # include ActionController::UrlFor | 1 |
Text | Text | fix indentation 💇♀️ | 3d636bf5f649951cd26123962bc3b4ec8c30dd56 | <ide><path>activerecord/CHANGELOG.md
<ide> * Add database_exists? method to connection adapters to check if a database exists.
<ide>
<del> *Guilherme Mansur*
<add> *Guilherme Mansur*
<ide>
<ide> * Loading the schema for a model that has no `table_name` raises a `TableNotSpecified` error.
<ide> | 1 |
Javascript | Javascript | use validatestring in modules/esm | d695a019ae44da50e5d54e9fa8a42a3ae0abe3cd | <ide><path>lib/internal/modules/esm/loader.js
<ide> 'use strict';
<ide>
<ide> const {
<del> ERR_INVALID_ARG_TYPE,
<ide> ERR_INVALID_RETURN_PROPERTY,
<ide> ERR_INVALID_RETURN_PROPERTY_VALUE,
<ide> ERR_INVALID_RETURN_VALUE,
<ide> ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK,
<ide> ERR_UNKNOWN_MODULE_FORMAT
<ide> } = require('internal/errors').codes;
<ide> const { URL } = require('url');
<add>const { validateString } = require('internal/validators');
<ide> const ModuleMap = require('internal/modules/esm/module_map');
<ide> const ModuleJob = require('internal/modules/esm/module_job');
<ide> const defaultResolve = require('internal/modules/esm/default_resolve');
<ide> class Loader {
<ide>
<ide> async resolve(specifier, parentURL) {
<ide> const isMain = parentURL === undefined;
<del> if (!isMain && typeof parentURL !== 'string')
<del> throw new ERR_INVALID_ARG_TYPE('parentURL', 'string', parentURL);
<add> if (!isMain)
<add> validateString(parentURL, 'parentURL');
<ide>
<ide> const resolved = await this._resolve(specifier, parentURL, defaultResolve);
<ide>
<ide><path>lib/internal/modules/esm/module_map.js
<ide> const ModuleJob = require('internal/modules/esm/module_job');
<ide> const { SafeMap } = require('internal/safe_globals');
<ide> const debug = require('util').debuglog('esm');
<ide> const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes;
<add>const { validateString } = require('internal/validators');
<ide>
<ide> // Tracks the state of the loader-level module cache
<ide> class ModuleMap extends SafeMap {
<ide> get(url) {
<del> if (typeof url !== 'string') {
<del> throw new ERR_INVALID_ARG_TYPE('url', 'string', url);
<del> }
<add> validateString(url, 'url');
<ide> return super.get(url);
<ide> }
<ide> set(url, job) {
<del> if (typeof url !== 'string') {
<del> throw new ERR_INVALID_ARG_TYPE('url', 'string', url);
<del> }
<add> validateString(url, 'url');
<ide> if (job instanceof ModuleJob !== true) {
<ide> throw new ERR_INVALID_ARG_TYPE('job', 'ModuleJob', job);
<ide> }
<ide> debug(`Storing ${url} in ModuleMap`);
<ide> return super.set(url, job);
<ide> }
<ide> has(url) {
<del> if (typeof url !== 'string') {
<del> throw new ERR_INVALID_ARG_TYPE('url', 'string', url);
<del> }
<add> validateString(url, 'url');
<ide> return super.has(url);
<ide> }
<ide> } | 2 |
Text | Text | update readme with what files are needed | 494008eca0309a4e15e48065b98ad3b097d49c38 | <ide><path>README.md
<ide> You can also view all the test pdf files on the right side serving
<ide>
<ide> ## Building PDF.js
<ide>
<del>In order to bundle all `src/` files into a final `pdf.js` and build the generic
<add>In order to bundle all `src/` files into two productions scripts and build the generic
<ide> viewer, issue:
<ide>
<ide> $ node make generic
<ide>
<del>This will generate the file `build/generic/build/pdf.js` that can be included in
<del>your final project. The pdf.js file is large and should be minified for
<del>production. Also, if you would like to support more browsers than Firefox you'll
<del>also need to include `compatibility.js` from `build/generic/web/`.
<add>This will generate `pdf.js` and `pdf.worker.js` in the `build/generic/build/` directory.
<add>Both scripts are needed but only `pdf.js` needs to be included since `pdf.worker.js` will
<add>be loaded by `pdf.js`. If you want to support more browsers than Firefox you'll also need
<add>to include `compatibility.js` from `build/generic/web/`. The PDF.js files are large and
<add>should be minified for production.
<ide>
<ide> ## Learning
<ide> | 1 |
Text | Text | fix changelog for v10.8.0 | 9aebcc2b85720cccda1b6e50c337d8cde214bf52 | <ide><path>doc/changelogs/CHANGELOG_V10.md
<ide> </tr>
<ide> <tr>
<ide> <td>
<add><a href="#10.8.0">10.8.0</a><br/>
<ide> <a href="#10.7.0">10.7.0</a><br/>
<ide> <a href="#10.6.0">10.6.0</a><br/>
<ide> <a href="#10.5.0">10.5.0</a><br/> | 1 |
Javascript | Javascript | move git info into its own processor | 0b35521d8ffe9ff851c49801900381ec043962f0 | <ide><path>docs/config/index.js
<ide> module.exports = function(config) {
<ide> config = angularjsPackage(config);
<ide>
<ide> config.append('processing.processors', [
<add> require('./processors/git-data'),
<ide> require('./processors/keywords'),
<ide> require('./processors/versions-data'),
<ide> require('./processors/pages-data'),
<ide><path>docs/config/processors/git-data.js
<add>var gruntUtils = require('../../../lib/grunt/utils');
<add>
<add>module.exports = {
<add> name: 'git-data',
<add> runBefore: ['loading-files'],
<add> description: 'This processor adds information from the local git repository to the extraData injectable',
<add> init: function(config, injectables) {
<add> injectables.value('gitData', {
<add> version: gruntUtils.getVersion(),
<add> versions: gruntUtils.getPreviousVersions(),
<add> info: gruntUtils.getGitRepoInfo()
<add> });
<add> },
<add> process: function(extraData, gitData) {
<add> extraData.git = gitData;
<add> }
<add>};
<ide>\ No newline at end of file
<ide><path>docs/config/processors/versions-data.js
<ide> var _ = require('lodash');
<ide>
<del>var version;
<del>var versions;
<del>
<ide> module.exports = {
<ide> name: 'versions-data',
<ide> description: 'This plugin will create a new doc that will be rendered as an angularjs module ' +
<ide> 'which will contain meta information about the versions of angular',
<ide> runAfter: ['adding-extra-docs', 'pages-data'],
<ide> runBefore: ['extra-docs-added'],
<del> init: function(config) {
<del> version = config.source.currentVersion;
<del> versions = config.source.previousVersions;
<add> process: function(docs, gitData) {
<add>
<add> var version = gitData.version;
<add> var versions = gitData.versions;
<ide>
<ide> if ( !version ) {
<ide> throw new Error('Invalid configuration. Please provide a valid `source.currentVersion` property');
<ide> }
<ide> if ( !versions ) {
<ide> throw new Error('Invalid configuration. Please provide a valid `source.previousVersions` property');
<ide> }
<del> },
<del> process: function(docs) {
<ide>
<ide> var versionDoc = {
<ide> docType: 'versions-data',
<ide><path>docs/docs.config.js
<ide> var path = require('canonical-path');
<del>var gruntUtils = require('../lib/grunt/utils');
<ide> var basePath = __dirname;
<ide>
<ide> var basePackage = require('./config');
<ide> module.exports = function(config) {
<ide> { pattern: '**/*.ngdoc', basePath: path.resolve(basePath, 'content') }
<ide> ]);
<ide>
<del> var version = gruntUtils.getVersion();
<del> var versions = gruntUtils.getPreviousVersions();
<del> config.set('source.currentVersion', version);
<del> config.set('source.previousVersions', versions);
<del>
<ide> config.set('processing.examples.commonFiles', {
<ide> scripts: [ '../../../angular.js' ],
<ide> stylesheets: []
<ide> });
<ide>
<del> config.merge('rendering.extra', {
<del> git: gruntUtils.getGitRepoInfo(),
<del> version: version
<del> });
<del>
<ide> config.set('rendering.outputFolder', '../build/docs');
<ide>
<ide> config.set('logging.level', 'debug'); | 4 |
Ruby | Ruby | reject invalid characters | 9b725a58515f101caa9f1519bc9d5f48c28c18d7 | <ide><path>Library/Homebrew/cask/audit.rb
<ide> def check_version
<ide> return unless cask.version
<ide>
<ide> check_no_string_version_latest
<del> check_no_file_separator_in_version
<ide> end
<ide>
<ide> def check_no_string_version_latest
<ide> def check_no_string_version_latest
<ide> add_error "you should use version :latest instead of version 'latest'"
<ide> end
<ide>
<del> def check_no_file_separator_in_version
<del> odebug "Verifying version does not contain '#{File::SEPARATOR}'"
<del> return unless cask.version.raw_version.is_a?(String)
<del> return unless cask.version.raw_version.include?(File::SEPARATOR)
<del>
<del> add_error "version should not contain '#{File::SEPARATOR}'"
<del> end
<del>
<ide> def check_sha256
<ide> return unless cask.sha256
<ide>
<ide><path>Library/Homebrew/cask/dsl/version.rb
<ide> class Version < ::String
<ide>
<ide> MAJOR_MINOR_PATCH_REGEX = /^([^.,:]+)(?:.([^.,:]+)(?:.([^.,:]+))?)?/.freeze
<ide>
<del> INVALID_CHARACTERS = /[^0-9a-zA-Z.,:\-_]/.freeze
<add> INVALID_CHARACTERS = /[^0-9a-zA-Z.,:\-_+% ]/.freeze
<ide>
<ide> class << self
<ide> private
<ide> def conversion_method_name(left_divider, right_divider)
<ide> def initialize(raw_version)
<ide> @raw_version = raw_version
<ide> super(raw_version.to_s)
<add>
<add> invalid = invalid_characters
<add> raise TypeError, "#{raw_version} contains invalid characters: #{invalid.uniq.join}!" if invalid.present?
<ide> end
<ide>
<ide> def invalid_characters
<del> return [] if latest?
<add> return [] if raw_version.blank? || latest?
<ide>
<ide> raw_version.scan(INVALID_CHARACTERS)
<ide> end
<ide><path>Library/Homebrew/test/cask/audit_spec.rb
<ide> def tmp_cask(name, text)
<ide> expect(audit.cask.url.cookies).to eq "foo" => "bar"
<ide> end
<ide> end
<del>
<del> context "when the version contains a slash" do
<del> let(:cask_token) { "foo" }
<del> let(:cask) do
<del> tmp_cask cask_token.to_s, <<~RUBY
<del> cask '#{cask_token}' do
<del> version '0.1,../../directory/traversal'
<del> sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a'
<del> url 'https://brew.sh/foo.zip'
<del> name 'Audit'
<del> desc 'Audit Description'
<del> homepage 'https://brew.sh'
<del> app 'Audit.app'
<del> end
<del> RUBY
<del> end
<del>
<del> it { is_expected.to fail_with(%r{version should not contain '/'}) }
<del> end
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/cask/dsl/version_spec.rb
<ide>
<ide> let(:version) { described_class.new(raw_version) }
<ide>
<add> describe "#initialize" do
<add> it "raises an error when the version contains a slash" do
<add> expect {
<add> described_class.new("0.1,../../directory/traversal")
<add> }.to raise_error(TypeError, %r{invalid characters: /})
<add> end
<add> end
<add>
<ide> describe "#==" do
<ide> subject { version == other }
<ide> | 4 |
Javascript | Javascript | use object.assign in merge/mergeinto | 3818656f70d42232ab4b4c199107af0674a16e37 | <ide><path>src/utils/__tests__/LegacyImmutableObject-test.js
<ide> describe('LegacyImmutableObject', function() {
<ide> expect(window.__DEV__).toBe(true);
<ide> });
<ide>
<del> testDev('should require initial map to be an object', function() {
<add> testDev('should not require initial map to be an object', function() {
<add> // These won't throw because they're coerced
<add>
<ide> expect(function() {
<ide> new LegacyImmutableObject([1,2,3]);
<del> }).toThrow();
<add> }).not.toThrow();
<ide>
<ide> expect(function() {
<ide> new LegacyImmutableObject('asdf');
<del> }).toThrow();
<add> }).not.toThrow();
<ide>
<ide> expect(function() {
<ide> new LegacyImmutableObject({oldField: 'asdf', fieldTwo: null});
<ide><path>src/vendor/core/merge.js
<ide>
<ide> "use strict";
<ide>
<del>var mergeInto = require('mergeInto');
<del>
<ide> /**
<ide> * Shallow merges two structures into a return value, without mutating either.
<ide> *
<ide> var mergeInto = require('mergeInto');
<ide> */
<ide> var merge = function(one, two) {
<ide> var result = {};
<del> mergeInto(result, one);
<del> mergeInto(result, two);
<add> if (one != null) {
<add> Object.assign(result, one);
<add> }
<add> if (two != null) {
<add> Object.assign(result, two);
<add> }
<ide> return result;
<ide> };
<ide>
<ide><path>src/vendor/core/mergeInto.js
<ide>
<ide> "use strict";
<ide>
<del>var mergeHelpers = require('mergeHelpers');
<del>
<del>var checkMergeObjectArg = mergeHelpers.checkMergeObjectArg;
<del>var checkMergeIntoObjectArg = mergeHelpers.checkMergeIntoObjectArg;
<del>
<ide> /**
<ide> * Shallow merges two structures by mutating the first parameter.
<ide> *
<ide> * @param {object|function} one Object to be merged into.
<ide> * @param {?object} two Optional object with properties to merge from.
<add> * @return {object|function} The first argument coerced into an object.
<ide> */
<ide> function mergeInto(one, two) {
<del> checkMergeIntoObjectArg(one);
<ide> if (two != null) {
<del> checkMergeObjectArg(two);
<del> for (var key in two) {
<del> if (!two.hasOwnProperty(key)) {
<del> continue;
<del> }
<del> one[key] = two[key];
<del> }
<add> return Object.assign(one, two);
<add> } else {
<add> // This ensures that we throw the right error if one is of the wrong type
<add> return Object.assign(one);
<ide> }
<ide> }
<ide> | 3 |
Ruby | Ruby | handle system libraries on big sur | 9c4aaa9719c74b78ff5dca4667788b3426a48678 | <ide><path>Library/Homebrew/linkage_checker.rb
<ide> require "keg"
<ide> require "formula"
<ide> require "linkage_cache_store"
<add>require "fiddle"
<ide>
<ide> class LinkageChecker
<ide> attr_reader :undeclared_deps
<ide> def check_dylibs(rebuild_cache:)
<ide>
<ide> if (dep = dylib_to_dep(dylib))
<ide> @broken_deps[dep] |= [dylib]
<add> elsif MacOS.version >= :big_sur && dylib_found_via_dlopen(dylib)
<add> # If we cannot associate the dylib with a dependency, then it may be a system library.
<add> # In macOS Big Sur and later, system libraries do not exist on-disk and instead exist in a cache.
<add> # If dlopen finds the dylib, then the linkage is not broken.
<add> @system_dylibs << dylib
<ide> else
<ide> @broken_dylibs << dylib
<ide> end
<ide> def check_dylibs(rebuild_cache:)
<ide> end
<ide> alias generic_check_dylibs check_dylibs
<ide>
<add> def dylib_found_via_dlopen(dylib)
<add> Fiddle.dlopen(dylib).close
<add> true
<add> rescue Fiddle::DLError
<add> false
<add> end
<add>
<ide> def check_formula_deps
<ide> filter_out = proc do |dep|
<ide> next true if dep.build? | 1 |
Javascript | Javascript | use keydown/change events on ie9 instead of input | 49dfdf8f0238ef8c473fcb44694f6b5696ecde70 | <ide><path>src/ng/directive/input.js
<ide> function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
<ide> }
<ide> };
<ide>
<del> // if the browser does support "input" event, we are fine
<add> // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
<add> // input event on backspace, delete or cut
<ide> if ($sniffer.hasEvent('input')) {
<ide> element.bind('input', listener);
<ide> } else {
<ide><path>src/ng/sniffer.js
<ide> function $SnifferProvider() {
<ide> // IE8 compatible mode lies
<ide> (!$window.document.documentMode || $window.document.documentMode > 7),
<ide> hasEvent: function(event) {
<add> // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
<add> // it. In particular the event is not fired when backspace or delete key are pressed or
<add> // when cut operation is performed.
<add> if (event == 'input' && msie == 9) return false;
<add>
<ide> if (isUndefined(eventSupport[event])) {
<ide> var divElm = $window.document.createElement('div');
<ide> eventSupport[event] = 'on' + event in divElm;
<ide><path>test/ng/directive/inputSpec.js
<ide> describe('ngModel', function() {
<ide> expect(element.hasClass('ng-invalid-email')).toBe(true);
<ide>
<ide> element.val('invalid-again');
<del> browserTrigger(element, $sniffer.hasEvent('input') ? 'input' : 'change');
<add> browserTrigger(element, ($sniffer.hasEvent('input')) ? 'input' : 'change');
<ide> expect(element).toBeInvalid();
<ide> expect(element).toBeDirty();
<ide> expect(element.hasClass('ng-valid-email')).toBe(false);
<ide><path>test/ng/snifferSpec.js
<ide> describe('$sniffer', function() {
<ide> });
<ide>
<ide>
<del> it('should return true if "oninput" is present in a div element', function() {
<del> mockDivElement = {oninput: noop};
<add> it('should return true if "onchange" is present in a div element', function() {
<add> mockDivElement = {onchange: noop};
<ide>
<del> expect($sniffer.hasEvent('input')).toBe(true);
<add> expect($sniffer.hasEvent('change')).toBe(true);
<ide> });
<ide>
<ide>
<ide> describe('$sniffer', function() {
<ide> it('should only create the element once', function() {
<ide> mockDivElement = {};
<ide>
<del> $sniffer.hasEvent('input');
<del> $sniffer.hasEvent('input');
<del> $sniffer.hasEvent('input');
<add> $sniffer.hasEvent('change');
<add> $sniffer.hasEvent('change');
<add> $sniffer.hasEvent('change');
<ide>
<ide> expect(mockDocument.createElement).toHaveBeenCalledOnce();
<ide> });
<add>
<add>
<add> it('should claim that IE9 doesn\'t have support for "oninput"', function() {
<add> // IE9 implementation is fubared, so it's better to pretend that it doesn't have the support
<add> mockDivElement = {oninput: noop};
<add>
<add> expect($sniffer.hasEvent('input')).toBe((msie == 9) ? false : true);
<add> });
<ide> });
<ide> }); | 4 |
Text | Text | remove trailing whitespace from engines guide | fdf04fe7f6250d7cca8a62850396b8807cff0633 | <ide><path>guides/source/engines.md
<ide> The `--full` option tells the generator that you want to create an engine, inclu
<ide> end
<ide> ```
<ide> * A file at `lib/blorgh/engine.rb` which is identical in function to a standard Rails application's `config/application.rb` file:
<del>
<add>
<ide> ```ruby
<ide> module Blorgh
<ide> class Engine < ::Rails::Engine
<ide> The `--mountable` option tells the generator that you want to create a "mountabl
<ide> * A namespaced `ApplicationHelper` stub
<ide> * A layout view template for the engine
<ide> * Namespace isolation to `config/routes.rb`:
<del>
<add>
<ide> ```ruby
<ide> Blorgh::Engine.routes.draw do
<ide> end
<ide> ```
<del>
<add>
<ide> * Namespace isolation to `lib/blorgh/engine.rb`:
<ide>
<ide> ```ruby
<ide> module Blorgh::Concerns::Models::Post
<ide> extend ActiveSupport::Concern
<ide>
<ide> # 'included do' causes the included code to be evaluated in the
<del> # context where it is included (post.rb), rather than be
<add> # context where it is included (post.rb), rather than be
<ide> # executed in the module's context (blorgh/concerns/models/post).
<ide> included do
<ide> attr_accessor :author_name | 1 |
Python | Python | add tests and fix various bugs in modeloutput | ae736163d0d7a3a167ff0df3bf6c824437bbba2a | <ide><path>src/transformers/file_utils.py
<ide> def __post_init__(self):
<ide> setattr(self, element[0], element[1])
<ide> if element[1] is not None:
<ide> self[element[0]] = element[1]
<add> elif first_field is not None:
<add> self[class_fields[0].name] = first_field
<ide> else:
<ide> for field in class_fields:
<ide> v = getattr(self, field.name)
<ide> def __getitem__(self, k):
<ide> else:
<ide> return self.to_tuple()[k]
<ide>
<add> def __setattr__(self, name, value):
<add> if name in self.keys() and value is not None:
<add> # Don't call self.__setitem__ to avoid recursion errors
<add> super().__setitem__(name, value)
<add> super().__setattr__(name, value)
<add>
<add> def __setitem__(self, key, value):
<add> # Will raise a KeyException if needed
<add> super().__setitem__(key, value)
<add> # Don't call self.__setattr__ to avoid recursion errors
<add> super().__setattr__(key, value)
<add>
<ide> def to_tuple(self) -> Tuple[Any]:
<ide> """
<ide> Convert self to a tuple containing all the attributes/keys that are not ``None``.
<ide><path>tests/test_model_output.py
<add># coding=utf-8
<add># Copyright 2020 The Hugging Face Team.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>
<add>import unittest
<add>from dataclasses import dataclass
<add>from typing import Optional
<add>
<add>from transformers.file_utils import ModelOutput
<add>
<add>
<add>@dataclass
<add>class ModelOutputTest(ModelOutput):
<add> a: float
<add> b: Optional[float] = None
<add> c: Optional[float] = None
<add>
<add>
<add>class ModelOutputTester(unittest.TestCase):
<add> def test_get_attributes(self):
<add> x = ModelOutputTest(a=30)
<add> self.assertEqual(x.a, 30)
<add> self.assertIsNone(x.b)
<add> self.assertIsNone(x.c)
<add> with self.assertRaises(AttributeError):
<add> _ = x.d
<add>
<add> def test_index_with_ints_and_slices(self):
<add> x = ModelOutputTest(a=30, b=10)
<add> self.assertEqual(x[0], 30)
<add> self.assertEqual(x[1], 10)
<add> self.assertEqual(x[:2], (30, 10))
<add> self.assertEqual(x[:], (30, 10))
<add>
<add> x = ModelOutputTest(a=30, c=10)
<add> self.assertEqual(x[0], 30)
<add> self.assertEqual(x[1], 10)
<add> self.assertEqual(x[:2], (30, 10))
<add> self.assertEqual(x[:], (30, 10))
<add>
<add> def test_index_with_strings(self):
<add> x = ModelOutputTest(a=30, b=10)
<add> self.assertEqual(x["a"], 30)
<add> self.assertEqual(x["b"], 10)
<add> with self.assertRaises(KeyError):
<add> _ = x["c"]
<add>
<add> x = ModelOutputTest(a=30, c=10)
<add> self.assertEqual(x["a"], 30)
<add> self.assertEqual(x["c"], 10)
<add> with self.assertRaises(KeyError):
<add> _ = x["b"]
<add>
<add> def test_dict_like_properties(self):
<add> x = ModelOutputTest(a=30)
<add> self.assertEqual(list(x.keys()), ["a"])
<add> self.assertEqual(list(x.values()), [30])
<add> self.assertEqual(list(x.items()), [("a", 30)])
<add> self.assertEqual(list(x), ["a"])
<add>
<add> x = ModelOutputTest(a=30, b=10)
<add> self.assertEqual(list(x.keys()), ["a", "b"])
<add> self.assertEqual(list(x.values()), [30, 10])
<add> self.assertEqual(list(x.items()), [("a", 30), ("b", 10)])
<add> self.assertEqual(list(x), ["a", "b"])
<add>
<add> x = ModelOutputTest(a=30, c=10)
<add> self.assertEqual(list(x.keys()), ["a", "c"])
<add> self.assertEqual(list(x.values()), [30, 10])
<add> self.assertEqual(list(x.items()), [("a", 30), ("c", 10)])
<add> self.assertEqual(list(x), ["a", "c"])
<add>
<add> with self.assertRaises(Exception):
<add> x = x.update({"d": 20})
<add> with self.assertRaises(Exception):
<add> del x["a"]
<add> with self.assertRaises(Exception):
<add> _ = x.pop("a")
<add> with self.assertRaises(Exception):
<add> _ = x.setdefault("d", 32)
<add>
<add> def test_set_attributes(self):
<add> x = ModelOutputTest(a=30)
<add> x.a = 10
<add> self.assertEqual(x.a, 10)
<add> self.assertEqual(x["a"], 10)
<add>
<add> def test_set_keys(self):
<add> x = ModelOutputTest(a=30)
<add> x["a"] = 10
<add> self.assertEqual(x.a, 10)
<add> self.assertEqual(x["a"], 10) | 2 |
Javascript | Javascript | follow rfc6125 more stricly | 31583be04218c49d91440a58969dbfc4f5f7b472 | <ide><path>lib/tls.js
<ide> function checkServerIdentity(host, cert) {
<ide> // The same applies to hostname with more than one wildcard,
<ide> // if hostname has wildcard when wildcards are not allowed,
<ide> // or if there are less than two dots after wildcard (i.e. *.com or *d.com)
<del> if (/\*.*\*/.test(host) || !wildcards && /\*/.test(host) ||
<add> //
<add> // also
<add> //
<add> // "The client SHOULD NOT attempt to match a presented identifier in
<add> // which the wildcard character comprises a label other than the
<add> // left-most label (e.g., do not match bar.*.example.net)."
<add> // RFC6125
<add> if (!wildcards && /\*/.test(host) || /[\.\*].*\*/.test(host) ||
<ide> /\*/.test(host) && !/\*.*\..+\..+/.test(host)) {
<ide> return /$./;
<ide> }
<ide> function checkServerIdentity(host, cert) {
<ide> var dnsNames = [],
<ide> uriNames = [],
<ide> ips = [],
<add> matchCN = true,
<ide> valid = false;
<ide>
<ide> // There're several names to perform check against:
<ide> function checkServerIdentity(host, cert) {
<ide> //
<ide> // Walk through altnames and generate lists of those names
<ide> if (cert.subjectaltname) {
<add> matchCN = false;
<ide> cert.subjectaltname.split(/, /g).forEach(function(altname) {
<ide> if (/^DNS:/.test(altname)) {
<ide> dnsNames.push(altname.slice(4));
<ide> function checkServerIdentity(host, cert) {
<ide>
<ide> dnsNames = dnsNames.concat(uriNames);
<ide>
<del> // And only after check if hostname matches CN
<del> var commonNames = cert.subject.CN;
<del> if (Array.isArray(commonNames)) {
<del> for (var i = 0, k = commonNames.length; i < k; ++i) {
<del> dnsNames.push(regexpify(commonNames[i], true));
<add> if (dnsNames.length > 0) matchCN = false;
<add>
<add> // Match against Common Name (CN) only if altnames are not present.
<add> //
<add> // "As noted, a client MUST NOT seek a match for a reference identifier
<add> // of CN-ID if the presented identifiers include a DNS-ID, SRV-ID,
<add> // URI-ID, or any application-specific identifier types supported by the
<add> // client."
<add> // RFC6125
<add> if (matchCN) {
<add> var commonNames = cert.subject.CN;
<add> if (Array.isArray(commonNames)) {
<add> for (var i = 0, k = commonNames.length; i < k; ++i) {
<add> dnsNames.push(regexpify(commonNames[i], true));
<add> }
<add> } else {
<add> dnsNames.push(regexpify(commonNames, true));
<ide> }
<del> } else {
<del> dnsNames.push(regexpify(commonNames, true));
<ide> }
<ide>
<ide> valid = dnsNames.some(function(re) {
<ide><path>test/simple/test-tls-check-server-identity.js
<ide> var tests = [
<ide> { host: 'a.com', cert: { subject: { CN: 'b.com' } }, result: false },
<ide> { host: 'a.com', cert: { subject: { CN: 'a.com.' } }, result: true },
<ide>
<del> // No wildcards in CN
<del> { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } }, result: false },
<add> // Wildcards in CN
<add> { host: 'b.a.com', cert: { subject: { CN: '*.a.com' } }, result: true },
<add> { host: 'b.a.com', cert: {
<add> subjectaltname: 'DNS:omg.com',
<add> subject: { CN: '*.a.com' } },
<add> result: false
<add> },
<ide>
<ide> // Multiple CN fields
<ide> {
<ide> var tests = [
<ide> subjectaltname: 'DNS:*.a.com',
<ide> subject: { CN: 'a.com' }
<ide> },
<del> result: true
<add> result: false
<ide> },
<ide> {
<ide> host: 'a.com', cert: {
<ide> var tests = [
<ide> subjectaltname: 'DNS:a.com',
<ide> subject: { CN: 'localhost' }
<ide> },
<del> result: true
<add> result: false
<ide> },
<ide> ];
<ide> | 2 |
Python | Python | fix language.update for pipeline | 0acce0521b3768dce2029db28168b5ec79aac741 | <ide><path>spacy/language.py
<ide> def evaluate(self, docs_golds):
<ide> docs = list(docs)
<ide> golds = list(golds)
<ide> for pipe in self.pipeline:
<del> docs = pipe.pipe(docs)
<add> if not hasattr(pipe, 'pipe'):
<add> for doc in docs:
<add> pipe(doc)
<add> else:
<add> docs = list(pipe.pipe(docs))
<add> assert len(docs) == len(golds)
<ide> for doc, gold in zip(docs, golds):
<ide> scorer.score(doc, gold)
<ide> doc.tensor = None | 1 |
Javascript | Javascript | create plnkr examples with the correct version | b28f1fc3fb38da5d2fd26143b4a8133ebcdd9071 | <ide><path>docs/config/services/deployments/production.js
<ide> 'use strict';
<ide>
<ide> var versionInfo = require('../../../../lib/versions/version-info');
<del>var cdnUrl = '//ajax.googleapis.com/ajax/libs/angularjs/' + versionInfo.cdnVersion;
<add>
<add>var googleCdnUrl = '//ajax.googleapis.com/ajax/libs/angularjs/';
<add>var angularCodeUrl = '//code.angularjs.org/';
<add>
<add>var cdnUrl = googleCdnUrl + versionInfo.cdnVersion;
<add>
<add>// The plnkr examples must use the code.angularjs.org repo for the snapshot,
<add>// and the cdn for the tagged version and, if the build is not tagged, the currentVersion.
<add>//
<add>// The currentVersion may not be available on the cdn (e.g. if built locally, or hasn't been pushed
<add>// yet). This will lead to a 404, but this is preferable to loading a version with which the example
<add>// might not work (possibly in subtle ways).
<add>var examplesCdnUrl = versionInfo.isSnapshot ?
<add> (angularCodeUrl + 'snapshot') :
<add> (googleCdnUrl + (versionInfo.version || versionInfo.currentVersion));
<ide>
<ide> module.exports = function productionDeployment(getVersion) {
<ide> return {
<ide> name: 'production',
<ide> examples: {
<ide> commonFiles: {
<del> scripts: [cdnUrl + '/angular.min.js']
<add> scripts: [examplesCdnUrl + '/angular.min.js']
<ide> },
<del> dependencyPath: cdnUrl + '/'
<add> dependencyPath: examplesCdnUrl + '/'
<ide> },
<ide> scripts: [
<ide> cdnUrl + '/angular.min.js', | 1 |
Go | Go | fix devices in plugins | 6f00601c9fb7886547334f80a250bac5e226aad7 | <ide><path>plugin/v2/plugin.go
<ide> func (p *Plugin) InitPlugin() error {
<ide>
<ide> p.PluginObj.Settings.Mounts = make([]types.PluginMount, len(p.PluginObj.Config.Mounts))
<ide> copy(p.PluginObj.Settings.Mounts, p.PluginObj.Config.Mounts)
<del> p.PluginObj.Settings.Env = make([]string, 0, len(p.PluginObj.Config.Env))
<del> p.PluginObj.Settings.Devices = make([]types.PluginDevice, 0, len(p.PluginObj.Config.Linux.Devices))
<add> p.PluginObj.Settings.Devices = make([]types.PluginDevice, len(p.PluginObj.Config.Linux.Devices))
<ide> copy(p.PluginObj.Settings.Devices, p.PluginObj.Config.Linux.Devices)
<add> p.PluginObj.Settings.Env = make([]string, 0, len(p.PluginObj.Config.Env))
<ide> for _, env := range p.PluginObj.Config.Env {
<ide> if env.Value != nil {
<ide> p.PluginObj.Settings.Env = append(p.PluginObj.Settings.Env, fmt.Sprintf("%s=%s", env.Name, *env.Value)) | 1 |
Python | Python | fix image2test args forwarding | d3f4cef74d94d52e967e76a2918e8368ee2e3fe0 | <ide><path>src/transformers/pipelines/image_to_text.py
<ide> def __init__(self, *args, **kwargs):
<ide> TF_MODEL_FOR_VISION_2_SEQ_MAPPING if self.framework == "tf" else MODEL_FOR_VISION_2_SEQ_MAPPING
<ide> )
<ide>
<del> def _sanitize_parameters(self, **kwargs):
<del> return {}, {}, {}
<add> def _sanitize_parameters(self, max_new_tokens=None, generate_kwargs=None):
<add> forward_kwargs = {}
<add> if generate_kwargs is not None:
<add> forward_kwargs["generate_kwargs"] = generate_kwargs
<add> if max_new_tokens is not None:
<add> if "generate_kwargs" not in forward_kwargs:
<add> forward_kwargs["generate_kwargs"] = {}
<add> if "max_new_tokens" in forward_kwargs["generate_kwargs"]:
<add> raise ValueError(
<add> "'max_new_tokens' is defined twice, once in 'generate_kwargs' and once as a direct parameter,"
<add> " please use only one"
<add> )
<add> forward_kwargs["generate_kwargs"]["max_new_tokens"] = max_new_tokens
<add> return {}, forward_kwargs, {}
<ide>
<ide> def __call__(self, images: Union[str, List[str], "Image.Image", List["Image.Image"]], **kwargs):
<ide> """
<ide> def __call__(self, images: Union[str, List[str], "Image.Image", List["Image.Imag
<ide>
<ide> The pipeline accepts either a single image or a batch of images.
<ide>
<add> max_new_tokens (`int`, *optional*):
<add> The amount of maximum tokens to generate. By default it will use `generate` default.
<add>
<add> generate_kwargs (`Dict`, *optional*):
<add> Pass it to send all of these arguments directly to `generate` allowing full control of this function.
<add>
<ide> Return:
<ide> A list or a list of list of `dict`: Each result comes as a dictionary with the following key:
<ide>
<ide> def preprocess(self, image):
<ide> model_inputs = self.feature_extractor(images=image, return_tensors=self.framework)
<ide> return model_inputs
<ide>
<del> def _forward(self, model_inputs):
<add> def _forward(self, model_inputs, generate_kwargs=None):
<add> if generate_kwargs is None:
<add> generate_kwargs = {}
<ide> # FIXME: We need to pop here due to a difference in how `generation_utils.py` and `generation_tf_utils.py`
<ide> # parse inputs. In the Tensorflow version, `generate` raises an error if we don't use `input_ids` whereas
<ide> # the PyTorch version matches it with `self.model.main_input_name` or `self.model.encoder.main_input_name`
<ide> # in the `_prepare_model_inputs` method.
<ide> inputs = model_inputs.pop(self.model.main_input_name)
<del> model_outputs = self.model.generate(inputs, **model_inputs)
<add> model_outputs = self.model.generate(inputs, **model_inputs, **generate_kwargs)
<ide> return model_outputs
<ide>
<ide> def postprocess(self, model_outputs):
<ide><path>tests/pipelines/test_pipelines_image_to_text.py
<ide> def test_small_model_tf(self):
<ide> ],
<ide> )
<ide>
<add> outputs = pipe(image, max_new_tokens=1)
<add> self.assertEqual(
<add> outputs,
<add> [{"generated_text": "growth"}],
<add> )
<add>
<ide> @require_torch
<ide> def test_small_model_pt(self):
<ide> pipe = pipeline("image-to-text", model="hf-internal-testing/tiny-random-vit-gpt2") | 2 |
Ruby | Ruby | avoid chdir error in railties tests on ruby master | ae5ecfe26c8fdc194d5b3cd16fd13b64574bcfd3 | <ide><path>railties/test/application/rake/dbs_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "isolation/abstract_unit"
<add>require "chdir_helpers"
<ide> require "env_helpers"
<ide>
<ide> module ApplicationTests
<ide> module RakeTests
<ide> class RakeDbsTest < ActiveSupport::TestCase
<del> include ActiveSupport::Testing::Isolation, EnvHelpers
<add> include ActiveSupport::Testing::Isolation, ChdirHelpers, EnvHelpers
<ide>
<ide> def setup
<ide> build_app
<ide> def set_database_url
<ide> end
<ide>
<ide> def db_create_and_drop(expected_database, environment_loaded: true)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> output = rails("db:create")
<ide> assert_match(/Created database/, output)
<ide> assert File.exist?(expected_database)
<ide> def db_create_and_drop(expected_database, environment_loaded: true)
<ide> end
<ide>
<ide> def db_create_with_warning(expected_database)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> output = rails("db:create")
<ide> assert_match(/Rails couldn't infer whether you are using multiple databases/, output)
<ide> assert_match(/Created database/, output)
<ide> def db_create_with_warning(expected_database)
<ide> end
<ide>
<ide> def with_database_existing
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> set_database_url
<ide> rails "db:create"
<ide> yield
<ide> def with_database_existing
<ide> end
<ide>
<ide> def with_bad_permissions
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> skip "Can't avoid permissions as root" if Process.uid.zero?
<ide>
<ide> set_database_url
<ide> def with_bad_permissions
<ide> end
<ide>
<ide> test "db:truncate_all truncates all non-internal tables" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate"
<ide> require "#{app_path}/config/environment"
<ide> def with_bad_permissions
<ide>
<ide> test "db:truncate_all does not truncate any tables when environment is protected" do
<ide> with_rails_env "production" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate"
<ide> require "#{app_path}/config/environment"
<ide> def db_migrate_and_status(expected_database)
<ide> end
<ide>
<ide> def db_schema_dump
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> args = ["generate", "model", "book", "title:string"]
<ide> rails args
<ide> rails "db:migrate", "db:schema:dump"
<ide> def db_schema_dump
<ide> end
<ide>
<ide> def db_schema_cache_dump(filename = "db/schema_cache.yml")
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "db:schema:cache:dump"
<ide>
<ide> cache_size = lambda { rails("runner", "p ActiveRecord::Base.connection.schema_cache.size").strip }
<ide> def db_schema_cache_dump(filename = "db/schema_cache.yml")
<ide> end
<ide>
<ide> test "db:schema:cache:dump with custom filename" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> File.open("#{app_path}/config/database.yml", "w") do |f|
<ide> f.puts <<-YAML
<ide> default: &default
<ide> def db_schema_cache_dump(filename = "db/schema_cache.yml")
<ide> end
<ide>
<ide> test "db:schema:cache:dump first config wins" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> File.open("#{app_path}/config/database.yml", "w") do |f|
<ide> f.puts <<-YAML
<ide> default: &default
<ide> def db_schema_cache_dump(filename = "db/schema_cache.yml")
<ide> end
<ide>
<ide> def db_fixtures_load(expected_database)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> reload
<ide> rails "db:migrate", "db:fixtures:load"
<ide> def db_fixtures_load(expected_database)
<ide> end
<ide>
<ide> def db_structure_dump_and_load(expected_database)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate", "db:structure:dump"
<ide> structure_dump = File.read("db/structure.sql")
<ide> def db_structure_dump_and_load(expected_database)
<ide> end
<ide>
<ide> def db_test_load_structure
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate", "db:structure:dump", "db:test:load_structure"
<ide> ActiveRecord::Base.configurations = Rails.application.config.database_configuration
<ide> def db_test_load_structure
<ide> end
<ide>
<ide> test "db:seed:replant truncates all non-internal tables and loads the seeds" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate"
<ide> require "#{app_path}/config/environment"
<ide> def db_test_load_structure
<ide>
<ide> test "db:seed:replant does not truncate any tables and does not load the seeds when environment is protected" do
<ide> with_rails_env "production" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate"
<ide> require "#{app_path}/config/environment"
<ide> def db_test_load_structure
<ide> end
<ide>
<ide> test "db:prepare setup the database" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> output = rails("db:prepare")
<ide> assert_match(/CreateBooks: migrated/, output)
<ide> def db_test_load_structure
<ide> end
<ide>
<ide> test "db:prepare does not touch schema when dumping is disabled" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:create", "db:migrate"
<ide>
<ide><path>railties/test/application/rake/log_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "isolation/abstract_unit"
<add>require "chdir_helpers"
<ide>
<ide> module ApplicationTests
<ide> module RakeTests
<ide> class LogTest < ActiveSupport::TestCase
<del> include ActiveSupport::Testing::Isolation
<add> include ActiveSupport::Testing::Isolation, ChdirHelpers
<ide>
<ide> def setup
<ide> build_app
<ide> def teardown
<ide> end
<ide>
<ide> test "log:clear clear all environments log files by default" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> File.open("config/environments/staging.rb", "w")
<ide>
<ide> File.write("log/staging.log", "staging")
<ide><path>railties/test/application/rake/migrations_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "isolation/abstract_unit"
<add>require "chdir_helpers"
<ide>
<ide> module ApplicationTests
<ide> module RakeTests
<ide> class RakeMigrationsTest < ActiveSupport::TestCase
<add> include ChdirHelpers
<add>
<ide> def setup
<ide> build_app
<ide> FileUtils.rm_rf("#{app_path}/config/environments")
<ide> class TwoMigration < ActiveRecord::Migration::Current
<ide> end
<ide>
<ide> test "raise error on any move when current migration does not exist" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "user", "username:string", "password:string"
<ide> rails "generate", "migration", "add_email_to_users", "email:string"
<ide> rails "db:migrate"
<ide> class TwoMigration < ActiveRecord::Migration::Current
<ide> test "schema generation when dump_schema_after_migration is set" do
<ide> add_to_config("config.active_record.dump_schema_after_migration = false")
<ide>
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> output = rails("generate", "model", "author", "name:string")
<ide> version = output =~ %r{[^/]+db/migrate/(\d+)_create_authors\.rb} && $1
<ide> class TwoMigration < ActiveRecord::Migration::Current
<ide>
<ide> add_to_config("config.active_record.dump_schema_after_migration = true")
<ide>
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "reviews", "book_id:integer"
<ide> rails "db:migrate"
<ide>
<ide> class TwoMigration < ActiveRecord::Migration::Current
<ide> end
<ide>
<ide> test "default schema generation after migration" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "book", "title:string"
<ide> rails "db:migrate"
<ide>
<ide> class TwoMigration < ActiveRecord::Migration::Current
<ide> end
<ide>
<ide> test "migration status migrated file is deleted" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "generate", "model", "user", "username:string", "password:string"
<ide> rails "generate", "migration", "add_email_to_users", "email:string"
<ide> rails "db:migrate"
<ide><path>railties/test/application/rake/multi_dbs_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "isolation/abstract_unit"
<add>require "chdir_helpers"
<ide>
<ide> module ApplicationTests
<ide> module RakeTests
<ide> class RakeMultiDbsTest < ActiveSupport::TestCase
<del> include ActiveSupport::Testing::Isolation
<add> include ActiveSupport::Testing::Isolation, ChdirHelpers
<ide>
<ide> def setup
<ide> build_app(multi_db: true)
<ide> def teardown
<ide> end
<ide>
<ide> def db_create_and_drop(namespace, expected_database)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> output = rails("db:create")
<ide> assert_match(/Created database/, output)
<ide> assert_match_namespace(namespace, output)
<ide> def db_create_and_drop(namespace, expected_database)
<ide> end
<ide>
<ide> def db_create_and_drop_namespace(namespace, expected_database)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> output = rails("db:create:#{namespace}")
<ide> assert_match(/Created database/, output)
<ide> assert_match_namespace(namespace, output)
<ide> def assert_match_namespace(namespace, output)
<ide> end
<ide>
<ide> def db_migrate_and_migrate_status
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails "db:migrate"
<ide> output = rails "db:migrate:status"
<ide> def db_migrate_and_migrate_status
<ide> end
<ide>
<ide> def db_migrate_and_schema_cache_dump
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails "db:migrate"
<ide> rails "db:schema:cache:dump"
<ide> def db_migrate_and_schema_cache_dump
<ide> end
<ide>
<ide> def db_migrate_and_schema_cache_dump_and_schema_cache_clear
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails "db:migrate"
<ide> rails "db:schema:cache:dump"
<ide> def db_migrate_and_schema_dump_and_load(schema_format = "ruby")
<ide> add_to_config "config.active_record.schema_format = :#{schema_format}"
<ide> require "#{app_path}/config/environment"
<ide>
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails "db:migrate", "db:schema:dump"
<ide>
<ide> def db_migrate_and_schema_dump_and_load(schema_format = "ruby")
<ide> end
<ide>
<ide> def db_migrate_and_schema_dump_and_load_one_database(format, database)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails "db:migrate:#{database}", "db:#{format}:dump:#{database}"
<ide>
<ide> def db_migrate_name_dumps_the_schema(name, schema_format)
<ide> add_to_config "config.active_record.schema_format = :#{schema_format}"
<ide> require "#{app_path}/config/environment"
<ide>
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide>
<ide> assert_not(File.exist?("db/schema.rb"))
<ide> def db_test_prepare_name(name, schema_format)
<ide> add_to_config "config.active_record.schema_format = :#{schema_format}"
<ide> require "#{app_path}/config/environment"
<ide>
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide>
<ide> rails("db:migrate:#{name}", "db:schema:dump:#{name}")
<ide> def db_test_prepare_name(name, schema_format)
<ide> end
<ide>
<ide> def db_migrate_namespaced(namespace)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> output = rails("db:migrate:#{namespace}")
<ide> if namespace == "primary"
<ide> def db_migrate_namespaced(namespace)
<ide> end
<ide>
<ide> def db_migrate_status_namespaced(namespace)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> output = rails("db:migrate:status:#{namespace}")
<ide> if namespace == "primary"
<ide> def db_migrate_status_namespaced(namespace)
<ide> end
<ide>
<ide> def db_up_and_down(version, namespace = nil)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails("db:migrate")
<ide>
<ide> def db_up_and_down(version, namespace = nil)
<ide> end
<ide>
<ide> def db_migrate_and_rollback(namespace = nil)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails("db:migrate")
<ide>
<ide> def db_migrate_and_rollback(namespace = nil)
<ide> end
<ide>
<ide> def db_migrate_redo(namespace = nil)
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> rails("db:migrate")
<ide>
<ide> def db_migrate_redo(namespace = nil)
<ide> end
<ide>
<ide> def db_prepare
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> generate_models_for_animals
<ide> output = rails("db:prepare")
<ide>
<ide> def generate_models_for_animals
<ide> end
<ide>
<ide> test "db:migrate set back connection to its original state" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> dummy_task = <<~RUBY
<ide> task foo: :environment do
<ide> Book.first
<ide> def generate_models_for_animals
<ide> end
<ide>
<ide> test "db:migrate:name sets the connection back to its original state" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> dummy_task = <<~RUBY
<ide> task foo: :environment do
<ide> Book.first
<ide> class TwoMigration < ActiveRecord::Migration::Current
<ide>
<ide> test "db:prepare setups missing database without clearing existing one" do
<ide> require "#{app_path}/config/environment"
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> # Bug not visible on SQLite3. Can be simplified when https://github.com/rails/rails/issues/36383 resolved
<ide> use_postgresql(multi_db: true)
<ide> generate_models_for_animals
<ide><path>railties/test/application/rake/restart_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "isolation/abstract_unit"
<add>require "chdir_helpers"
<ide>
<ide> module ApplicationTests
<ide> module RakeTests
<ide> class RakeRestartTest < ActiveSupport::TestCase
<del> include ActiveSupport::Testing::Isolation
<add> include ActiveSupport::Testing::Isolation, ChdirHelpers
<ide>
<ide> def setup
<ide> build_app
<ide> def teardown
<ide> end
<ide>
<ide> test "rails restart touches tmp/restart.txt" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> rails "restart"
<ide> assert File.exist?("tmp/restart.txt")
<ide>
<ide> def teardown
<ide> end
<ide>
<ide> test "rails restart should work even if tmp folder does not exist" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> FileUtils.remove_dir("tmp")
<ide> rails "restart"
<ide> assert File.exist?("tmp/restart.txt")
<ide><path>railties/test/application/rake/tmp_test.rb
<ide> # frozen_string_literal: true
<ide>
<ide> require "isolation/abstract_unit"
<add>require "chdir_helpers"
<ide>
<ide> module ApplicationTests
<ide> module RakeTests
<ide> class TmpTest < ActiveSupport::TestCase
<del> include ActiveSupport::Testing::Isolation
<add> include ActiveSupport::Testing::Isolation, ChdirHelpers
<ide>
<ide> def setup
<ide> build_app
<ide> def teardown
<ide> end
<ide>
<ide> test "tmp:clear clear cache, socket and screenshot files" do
<del> Dir.chdir(app_path) do
<add> chdir(app_path) do
<ide> FileUtils.mkdir_p("tmp/cache")
<ide> FileUtils.touch("tmp/cache/cache_file")
<ide>
<ide><path>railties/test/chdir_helpers.rb
<add># frozen_string_literal: true
<add>
<add>module ChdirHelpers
<add> private
<add> def chdir(dir)
<add> pwd = Dir.pwd
<add> Dir.chdir(dir)
<add> yield
<add> ensure
<add> Dir.chdir(pwd)
<add> end
<add>end | 7 |
Javascript | Javascript | add note on algolia docsearch | 364113fa5ed03ba8287c665344014a4c01ce25e4 | <ide><path>website/src/react-native/versions.js
<ide> var versions = React.createClass({
<ide> return version.type === 'release';
<ide> });
<ide>
<add> // Note: Our Algolia DocSearch box supports version-specific queries. If you will be drastically changing the way versions are listed in this page, make sure https://github.com/algolia/docsearch-configs/blob/master/configs/react-native-versions.json is updated accordingly.
<add>
<ide> return (
<ide> <Site section="versions" title="React Native Versions">
<ide> <section className="content wrap documentationContent nosidebar"> | 1 |
Text | Text | remove gitter badge from readme | 19fdb54ffa656056a2694779e098db86b3927101 | <ide><path>README.md
<ide> </a>
<ide> </p>
<ide> <p align="center">
<del> <a title="Gitter" href="https://gitter.im/nodejs/node?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"><img src="https://badges.gitter.im/Join%20Chat.svg"></a>
<ide> <a title="CII Best Practices" href="https://bestpractices.coreinfrastructure.org/projects/29"><img src="https://bestpractices.coreinfrastructure.org/projects/29/badge"></a>
<ide> </p>
<ide> | 1 |
Python | Python | combine similar branches | ad1e3c118f378fd62883655a9a983dd0c682f968 | <ide><path>numpy/lib/function_base.py
<ide> def _ureduce(a, func, **kwargs):
<ide> # merge reduced axis
<ide> a = a.reshape(a.shape[:nkeep] + (-1,))
<ide> kwargs['axis'] = -1
<add> keepdim = tuple(keepdim)
<ide> else:
<del> keepdim = [1] * a.ndim
<add> keepdim = (1,) * a.ndim
<ide>
<ide> r = func(a, **kwargs)
<ide> return r, keepdim
<ide> def percentile(a, q, axis=None, out=None,
<ide> overwrite_input=overwrite_input,
<ide> interpolation=interpolation)
<ide> if keepdims:
<del> if q.ndim == 0:
<del> return r.reshape(k)
<del> else:
<del> return r.reshape([len(q)] + k)
<add> return r.reshape(q.shape + k)
<ide> else:
<ide> return r
<ide>
<ide><path>numpy/lib/nanfunctions.py
<ide> def nanpercentile(a, q, axis=None, out=None, overwrite_input=False,
<ide> overwrite_input=overwrite_input,
<ide> interpolation=interpolation)
<ide> if keepdims and keepdims is not np._NoValue:
<del> if q.ndim == 0:
<del> return r.reshape(k)
<del> else:
<del> return r.reshape([len(q)] + k)
<add> return r.reshape(q.shape + k)
<ide> else:
<ide> return r
<ide> | 2 |
Javascript | Javascript | set default for serverruntimeconfig | 0107051eaa6668e0a538af0237c88a0531a8be7c | <ide><path>server/index.js
<ide> export default class Server {
<ide> availableChunks: dev ? {} : getAvailableChunks(this.dir, this.dist)
<ide> }
<ide>
<del> const {serverRuntimeConfig, publicRuntimeConfig, assetPrefix} = this.nextConfig
<add> // Only serverRuntimeConfig needs the default
<add> // publicRuntimeConfig gets it's default in client/index.js
<add> const {serverRuntimeConfig = {}, publicRuntimeConfig, assetPrefix} = this.nextConfig
<ide>
<ide> // Only the `publicRuntimeConfig` key is exposed to the client side
<ide> // It'll be rendered as part of __NEXT_DATA__ on the client side | 1 |
Go | Go | remove unused rwmutex | 6b7e19ff42b8760a8992ed1b997903eccdecbbbd | <ide><path>libcontainerd/supervisor/remote_daemon.go
<ide> import (
<ide> "path/filepath"
<ide> "strconv"
<ide> "strings"
<del> "sync"
<ide> "time"
<ide>
<ide> "github.com/containerd/containerd"
<ide> const (
<ide> )
<ide>
<ide> type remote struct {
<del> sync.RWMutex
<ide> config.Config
<ide>
<ide> daemonPid int | 1 |
Python | Python | fix failing test_list_sizes test | 029a5d06f171ea1be8d0d89c4738830a84e9efa8 | <ide><path>libcloud/test/compute/test_ec2.py
<ide> def test_list_sizes(self):
<ide> names = [
<ide> ('ec2_us_east', 'us-east-1'),
<ide> ('ec2_us_west', 'us-west-1'),
<add> ('ec2_us_west', 'us-west-2'),
<ide> ('ec2_eu_west', 'eu-west-1'),
<ide> ('ec2_ap_southeast', 'ap-southeast-1'),
<ide> ('ec2_ap_northeast', 'ap-northeast-1'),
<ide> def test_list_sizes(self):
<ide> self.assertTrue('m2.4xlarge' in ids)
<ide>
<ide> if region_name == 'us-east-1':
<del> self.assertEqual(len(sizes), 53)
<add> self.assertEqual(len(sizes), 54)
<ide> self.assertTrue('cg1.4xlarge' in ids)
<ide> self.assertTrue('cc2.8xlarge' in ids)
<ide> self.assertTrue('cr1.8xlarge' in ids)
<add> self.assertTreu('x1.32xlarge' in ids)
<ide> elif region_name == 'us-west-1':
<ide> self.assertEqual(len(sizes), 45)
<ide> if region_name == 'us-west-2':
<del> self.assertEqual(len(sizes), 41)
<add> self.assertEqual(len(sizes), 52)
<ide> elif region_name == 'ap-southeast-1':
<del> self.assertEqual(len(sizes), 43)
<add> self.assertEqual(len(sizes), 44)
<ide> elif region_name == 'ap-southeast-2':
<del> self.assertEqual(len(sizes), 47)
<add> self.assertEqual(len(sizes), 48)
<ide> elif region_name == 'eu-west-1':
<del> self.assertEqual(len(sizes), 51)
<add> self.assertEqual(len(sizes), 52)
<ide>
<ide> self.driver.region_name = region_old
<ide> | 1 |
PHP | PHP | fix buildsession call for database handler | eec8a73e8ea13c7ca9a98942ec2a07aa84ffaf6d | <ide><path>src/Illuminate/Session/SessionManager.php
<ide> protected function createDatabaseDriver()
<ide>
<ide> $table = $connection->getTablePrefix().$this->app['config']['session.table'];
<ide>
<del> return $this->buildSession($connection, $table);
<add> return $this->buildSession(new DatabaseSessionHandler($connection, $table));
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | convert image to rgb for clip model | 6bc6797e04811176f4244a42c86f8a65a1e1c455 | <ide><path>src/transformers/models/clip/feature_extraction_clip.py
<ide> class CLIPFeatureExtractor(FeatureExtractionMixin, ImageFeatureExtractionMixin):
<ide> The sequence of means for each channel, to be used when normalizing images.
<ide> image_std (`List[int]`, defaults to `[0.229, 0.224, 0.225]`):
<ide> The sequence of standard deviations for each channel, to be used when normalizing images.
<add> convert_rgb (`bool`, defaults to `True`):
<add> Whether or not to convert `PIL.Image.Image` into `RGB` format
<ide> """
<ide>
<ide> model_input_names = ["pixel_values"]
<ide> def __init__(
<ide> do_normalize=True,
<ide> image_mean=None,
<ide> image_std=None,
<add> do_convert_rgb=True,
<ide> **kwargs
<ide> ):
<ide> super().__init__(**kwargs)
<ide> def __init__(
<ide> self.do_normalize = do_normalize
<ide> self.image_mean = image_mean if image_mean is not None else [0.48145466, 0.4578275, 0.40821073]
<ide> self.image_std = image_std if image_std is not None else [0.26862954, 0.26130258, 0.27577711]
<add> self.do_convert_rgb = do_convert_rgb
<ide>
<ide> def __call__(
<ide> self,
<ide> def __call__(
<ide> if not is_batched:
<ide> images = [images]
<ide>
<del> # transformations (resizing + center cropping + normalization)
<add> # transformations (convert rgb + resizing + center cropping + normalization)
<add> if self.do_convert_rgb:
<add> images = [self.convert_rgb(image) for image in images]
<ide> if self.do_resize and self.size is not None and self.resample is not None:
<ide> images = [self.resize(image=image, size=self.size, resample=self.resample) for image in images]
<ide> if self.do_center_crop and self.crop_size is not None:
<ide> def __call__(
<ide>
<ide> return encoded_inputs
<ide>
<add> def convert_rgb(self, image):
<add> """
<add> Converts `image` to RGB format. Note that this will trigger a conversion of `image` to a PIL Image.
<add>
<add> Args:
<add> image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
<add> The image to convert.
<add> """
<add> self._ensure_format_supported(image)
<add> if not isinstance(image, Image.Image):
<add> return image
<add>
<add> return image.convert("RGB")
<add>
<ide> def center_crop(self, image, size):
<ide> """
<ide> Crops `image` to the given size using a center crop. Note that if the image is too small to be cropped to the
<ide><path>tests/models/clip/test_feature_extraction_clip.py
<ide> def __init__(
<ide> do_normalize=True,
<ide> image_mean=[0.48145466, 0.4578275, 0.40821073],
<ide> image_std=[0.26862954, 0.26130258, 0.27577711],
<add> do_convert_rgb=True,
<ide> ):
<ide> self.parent = parent
<ide> self.batch_size = batch_size
<ide> def __init__(
<ide> self.do_normalize = do_normalize
<ide> self.image_mean = image_mean
<ide> self.image_std = image_std
<add> self.do_convert_rgb = do_convert_rgb
<ide>
<ide> def prepare_feat_extract_dict(self):
<ide> return {
<ide> def prepare_feat_extract_dict(self):
<ide> "do_normalize": self.do_normalize,
<ide> "image_mean": self.image_mean,
<ide> "image_std": self.image_std,
<add> "do_convert_rgb": self.do_convert_rgb,
<ide> }
<ide>
<ide> def prepare_inputs(self, equal_resolution=False, numpify=False, torchify=False):
<ide> def test_feat_extract_properties(self):
<ide> self.assertTrue(hasattr(feature_extractor, "do_normalize"))
<ide> self.assertTrue(hasattr(feature_extractor, "image_mean"))
<ide> self.assertTrue(hasattr(feature_extractor, "image_std"))
<add> self.assertTrue(hasattr(feature_extractor, "do_convert_rgb"))
<ide>
<ide> def test_batch_feature(self):
<ide> pass
<ide> def test_call_pytorch(self):
<ide> self.feature_extract_tester.crop_size,
<ide> ),
<ide> )
<add>
<add>
<add>@require_torch
<add>@require_vision
<add>class CLIPFeatureExtractionTestFourChannels(FeatureExtractionSavingTestMixin, unittest.TestCase):
<add>
<add> feature_extraction_class = CLIPFeatureExtractor if is_vision_available() else None
<add>
<add> def setUp(self):
<add> self.feature_extract_tester = CLIPFeatureExtractionTester(self, num_channels=4)
<add> self.expected_encoded_image_num_channels = 3
<add>
<add> @property
<add> def feat_extract_dict(self):
<add> return self.feature_extract_tester.prepare_feat_extract_dict()
<add>
<add> def test_feat_extract_properties(self):
<add> feature_extractor = self.feature_extraction_class(**self.feat_extract_dict)
<add> self.assertTrue(hasattr(feature_extractor, "do_resize"))
<add> self.assertTrue(hasattr(feature_extractor, "size"))
<add> self.assertTrue(hasattr(feature_extractor, "do_center_crop"))
<add> self.assertTrue(hasattr(feature_extractor, "center_crop"))
<add> self.assertTrue(hasattr(feature_extractor, "do_normalize"))
<add> self.assertTrue(hasattr(feature_extractor, "image_mean"))
<add> self.assertTrue(hasattr(feature_extractor, "image_std"))
<add> self.assertTrue(hasattr(feature_extractor, "do_convert_rgb"))
<add>
<add> def test_batch_feature(self):
<add> pass
<add>
<add> def test_call_pil_four_channels(self):
<add> # Initialize feature_extractor
<add> feature_extractor = self.feature_extraction_class(**self.feat_extract_dict)
<add> # create random PIL images
<add> image_inputs = self.feature_extract_tester.prepare_inputs(equal_resolution=False)
<add> for image in image_inputs:
<add> self.assertIsInstance(image, Image.Image)
<add>
<add> # Test not batched input
<add> encoded_images = feature_extractor(image_inputs[0], return_tensors="pt").pixel_values
<add> self.assertEqual(
<add> encoded_images.shape,
<add> (
<add> 1,
<add> self.expected_encoded_image_num_channels,
<add> self.feature_extract_tester.crop_size,
<add> self.feature_extract_tester.crop_size,
<add> ),
<add> )
<add>
<add> # Test batched
<add> encoded_images = feature_extractor(image_inputs, return_tensors="pt").pixel_values
<add> self.assertEqual(
<add> encoded_images.shape,
<add> (
<add> self.feature_extract_tester.batch_size,
<add> self.expected_encoded_image_num_channels,
<add> self.feature_extract_tester.crop_size,
<add> self.feature_extract_tester.crop_size,
<add> ),
<add> ) | 2 |
Text | Text | fix typos | dabef8ae8bf74e0720301beabb46236d4c2d1b86 | <ide><path>CHANGELOG.md
<ide> ## [v9.2.0 (2022-02-22)](https://github.com/laravel/framework/compare/v9.1.0...v9.2.0)
<ide>
<ide> ### Added
<del>- Added `Illuminate/Database/Eloquent/Casts/Attribute::make()` ([#41014](https://github.com/laravel/framework/pull/41014))
<del>- Added `Illuminate/Collections/Arr::keyBy()` ([#41029](https://github.com/laravel/framework/pull/41029))
<add>- Added `Illuminate\Database\Eloquent\Casts\Attribute::make()` ([#41014](https://github.com/laravel/framework/pull/41014))
<add>- Added `Illuminate\Collections\Arr::keyBy()` ([#41029](https://github.com/laravel/framework/pull/41029))
<ide> - Added expectsOutputToContain to the PendingCommand. ([#40984](https://github.com/laravel/framework/pull/40984))
<ide> - Added ability to supply HTTP client methods with JsonSerializable instances ([#41055](https://github.com/laravel/framework/pull/41055))
<del>- Added `Illuminate/Filesystem/AwsS3V3Adapter::getClient()` ([#41079](https://github.com/laravel/framework/pull/41079))
<add>- Added `Illuminate\Filesystem\AwsS3V3Adapter::getClient()` ([#41079](https://github.com/laravel/framework/pull/41079))
<ide> - Added Support for enum in Builder::whereRelation ([#41091](https://github.com/laravel/framework/pull/41091))
<ide> - Added X headers when using Mail::alwaysTo ([#41101](https://github.com/laravel/framework/pull/41101))
<ide> - Added of support Bitwise operators in query ([#41112](https://github.com/laravel/framework/pull/41112))
<ide> - Integrate Laravel CORS into framework ([#41137](https://github.com/laravel/framework/pull/41137))
<del>- Added `Illuminate/Support/Str::betweenFirst()` ([#41144](https://github.com/laravel/framework/pull/41144))
<add>- Added `Illuminate\Support\Str::betweenFirst()` ([#41144](https://github.com/laravel/framework/pull/41144))
<ide> - Allow specifiying custom messages for Rule objects ([#41145](https://github.com/laravel/framework/pull/41145))
<ide>
<ide> ### Fixed
<ide> - Cursor pagination: convert original column to expression ([#41003](https://github.com/laravel/framework/pull/41003))
<ide> - Cast $perPage to integer on Paginator ([#41073](https://github.com/laravel/framework/pull/41073))
<ide> - Restore S3 client extra options ([#41097](https://github.com/laravel/framework/pull/41097))
<del>- Use `latest()` within `notifications()` in `Illuminate/Notifications/HasDatabaseNotifications.php` ([#41095](https://github.com/laravel/framework/pull/41095))
<add>- Use `latest()` within `notifications()` in `Illuminate\Notifications\HasDatabaseNotifications.php` ([#41095](https://github.com/laravel/framework/pull/41095))
<ide> - Remove duplicate queries to find batch ([#41121](https://github.com/laravel/framework/pull/41121))
<ide> - Remove redundant check in FormRequest::validated() ([#41115](https://github.com/laravel/framework/pull/41115))
<ide> - Illuminate/Support/Facades/Storage::fake() changed ([#41113](https://github.com/laravel/framework/pull/41113)) | 1 |
Javascript | Javascript | create swipeable card demo | 7463f6d0fd105a2074db78b620b3895753b13cbf | <ide><path>packages/rn-tester/js/examples/SwipeableCardExample/SwipeableCardExample.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow strict-local
<add> * @format
<add> */
<add>
<add>import * as React from 'react';
<add>import {
<add> Animated,
<add> PanResponder,
<add> View,
<add> StyleSheet,
<add> FlatList,
<add> useWindowDimensions,
<add>} from 'react-native';
<add>
<add>module.exports = {
<add> displayName: 'SwipeableCardExample',
<add> framework: 'React',
<add> title: 'SwipeableCard',
<add> category: 'Basic',
<add> description:
<add> 'Example of a swipeable card with scrollable content to test PanResponder and JSResponderHandler interaction.',
<add> examples: [
<add> {
<add> title: 'SwipeableCardExample',
<add> description: ('This example creates a swipeable card using PanResponder. ' +
<add> 'Under the hood, JSResponderHandler should prevent scroll when the card is being swiped.': string),
<add> render: function(): React.Node {
<add> return <SwipeableCard />;
<add> },
<add> },
<add> ],
<add>};
<add>
<add>function SwipeableCard() {
<add> const movementX = React.useRef(new Animated.Value(0)).current;
<add>
<add> const panResponder = React.useRef(
<add> PanResponder.create({
<add> onMoveShouldSetPanResponderCapture: (e, gestureState) => {
<add> const {dx} = gestureState;
<add> return Math.abs(dx) > 5;
<add> },
<add> onPanResponderMove: (e, gestureState) => {
<add> Animated.event([null, {dx: movementX}], {
<add> useNativeDriver: false,
<add> })(e, gestureState);
<add> },
<add> onPanResponderEnd: (e, gestureState) => {
<add> Animated.timing(movementX, {
<add> toValue: 0,
<add> useNativeDriver: true,
<add> }).start();
<add> },
<add> }),
<add> ).current;
<add>
<add> const {width} = useWindowDimensions();
<add> const rotation = movementX.interpolate({
<add> inputRange: [-width / 2, 0, width / 2],
<add> outputRange: (['-5deg', '0deg', '5deg']: $ReadOnlyArray<string>),
<add> extrapolate: 'clamp',
<add> });
<add>
<add> return (
<add> <View style={styles.container}>
<add> <Animated.View
<add> {...panResponder.panHandlers}
<add> style={{
<add> transform: [{translateX: movementX}, {rotateZ: rotation}],
<add> flex: 1,
<add> }}>
<add> <Card />
<add> </Animated.View>
<add> </View>
<add> );
<add>}
<add>
<add>const cardData = Array(5);
<add>
<add>function Card(props) {
<add> const renderItem = ({item, index}) => (
<add> <View style={index % 2 === 0 ? styles.cardSectionA : styles.cardSectionB} />
<add> );
<add> return (
<add> <View style={styles.card}>
<add> <FlatList style={{flex: 1}} data={cardData} renderItem={renderItem} />
<add> </View>
<add> );
<add>}
<add>
<add>const styles = StyleSheet.create({
<add> container: {
<add> flex: 1,
<add> padding: 10,
<add> paddingTop: 30,
<add> },
<add> card: {
<add> flex: 1,
<add> margin: 5,
<add> },
<add> cardSectionA: {
<add> height: 200,
<add> backgroundColor: 'aquamarine',
<add> },
<add> cardSectionB: {
<add> height: 200,
<add> backgroundColor: 'pink',
<add> },
<add>});
<ide><path>packages/rn-tester/js/utils/RNTesterList.android.js
<ide> const ComponentExamples: Array<RNTesterExample> = [
<ide> category: 'UI',
<ide> module: require('../examples/StatusBar/StatusBarExample'),
<ide> },
<add> {
<add> key: 'SwipeableCardExample',
<add> category: 'UI',
<add> module: require('../examples/SwipeableCardExample/SwipeableCardExample'),
<add> },
<ide> {
<ide> key: 'SwitchExample',
<ide> category: 'UI',
<ide><path>packages/rn-tester/js/utils/RNTesterList.ios.js
<ide> const ComponentExamples: Array<RNTesterExample> = [
<ide> module: require('../examples/StatusBar/StatusBarExample'),
<ide> supportsTVOS: false,
<ide> },
<add> {
<add> key: 'SwipeableCardExample',
<add> module: require('../examples/SwipeableCardExample/SwipeableCardExample'),
<add> category: 'UI',
<add> supportsTVOS: false,
<add> },
<ide> {
<ide> key: 'SwitchExample',
<ide> module: require('../examples/Switch/SwitchExample'), | 3 |
Python | Python | use vine.utils.wraps to ensure __wrapped__ is set | fdf1a0f6a31fdb9d0b6c2a762f4d219ac718de0a | <ide><path>celery/app/base.py
<ide>
<ide> from collections import defaultdict, deque
<ide> from operator import attrgetter
<del>from functools import wraps
<ide>
<ide> from kombu import pools
<ide> from kombu.clocks import LamportClock
<ide> from kombu.common import oid_from
<ide> from kombu.utils import cached_property, register_after_fork, uuid
<ide> from vine import starpromise
<add>from vine.utils import wraps
<ide>
<ide> from celery import platforms
<ide> from celery import signals
<ide><path>celery/backends/database/__init__.py
<ide> import logging
<ide>
<ide> from contextlib import contextmanager
<del>from functools import wraps
<add>
<add>from vine.utils import wraps
<ide>
<ide> from celery import states
<ide> from celery.backends.base import BaseBackend
<ide><path>celery/tests/app/test_control.py
<ide> from __future__ import absolute_import, unicode_literals
<ide>
<del>from functools import wraps
<del>
<ide> from kombu.pidbox import Mailbox
<add>from vine.utils import wraps
<ide>
<ide> from celery.app import control
<ide> from celery.exceptions import DuplicateNodenameWarning
<ide><path>celery/tests/case.py
<ide>
<ide> from copy import deepcopy
<ide> from datetime import datetime, timedelta
<del>from functools import partial, wraps
<add>from functools import partial
<ide>
<ide> from kombu import Queue
<ide> from kombu.utils import symbol_by_name
<add>from vine.utils import wraps
<ide>
<ide> from celery import Celery
<ide> from celery.app import current_app
<ide><path>celery/tests/compat_modules/test_http.py
<ide> from __future__ import absolute_import, unicode_literals
<ide>
<ide> from contextlib import contextmanager
<del>from functools import wraps
<ide> try:
<ide> from urllib import addinfourl
<ide> except ImportError: # py3k
<ide> from urllib.request import addinfourl # noqa
<ide>
<ide> from kombu.utils.encoding import from_utf8
<ide> from kombu.utils.json import dumps
<add>from vine.utils import wraps
<ide>
<ide> from celery.five import WhateverIO, items
<ide> from celery.task import http
<ide><path>celery/utils/__init__.py
<ide> import datetime
<ide>
<ide> from collections import Callable
<del>from functools import partial, wraps
<add>from functools import partial
<ide> from pprint import pprint
<ide>
<ide> from kombu.entity import Exchange, Queue
<add>from vine.utils import wraps
<ide>
<ide> from celery.exceptions import CPendingDeprecationWarning, CDeprecationWarning
<ide> from celery.five import WhateverIO, items, reraise, string_t | 6 |
Javascript | Javascript | hoist final regexp | 987a9f3954b94dc50d672b584ca8205ebbbc05fd | <ide><path>lib/RequestShortener.js
<ide> const NORMALIZE_SLASH_DIRECTION_REGEXP = /\\/g;
<ide> const PATH_CHARS_REGEXP = /[-[\]{}()*+?.,\\^$|#\s]/g;
<ide> const SEPERATOR_REGEXP = /[\/\\]$/;
<ide> const FRONT_OR_BACK_BANG_REGEXP = /^!|!$/g;
<add>const INDEX_JS_REGEXP = /\/index.js(!|\?|\(query\))/g;
<ide>
<ide> const normalizeBackSlashDirection = (request) => {
<ide> return request.replace(NORMALIZE_SLASH_DIRECTION_REGEXP, "/");
<ide> class RequestShortener {
<ide> this.buildinsAsModule = buildinsAsModule;
<ide> this.buildinsRegExp = createRegExpForPath(buildins);
<ide> }
<del>
<del> this.indexJsRegExp = /\/index.js(!|\?|\(query\))/g;
<ide> }
<ide>
<ide> shorten(request) {
<ide> class RequestShortener {
<ide> request = request.replace(this.parentDirectoryRegExp, "!..");
<ide> if(!this.buildinsAsModule && this.buildinsRegExp)
<ide> request = request.replace(this.buildinsRegExp, "!(webpack)");
<del> request = request.replace(this.indexJsRegExp, "$1");
<add> request = request.replace(INDEX_JS_REGEXP, "$1");
<ide> return request.replace(FRONT_OR_BACK_BANG_REGEXP, "");
<ide> }
<ide> } | 1 |
Python | Python | add help to show/hide top menu | b3df5d7e1dd3baee45030b82887862d48100d28c | <ide><path>glances/plugins/glances_help.py
<ide> def generate_view_data(self):
<ide> self.view_data['enable_disable_quick_look'] = msg_col.format('3', 'Enable/disable quick look plugin')
<ide> self.view_data['show_hide_ip'] = msg_col2.format('I', 'Show/hide IP module')
<ide> self.view_data['diskio_iops'] = msg_col2.format('B', 'Count/rate for Disk I/O')
<add> self.view_data['show_hide_top_menu'] = msg_col2.format('5', 'Show/hide top menu (QL, CPU, MEM, SWAP and LOAD)')
<ide> self.view_data['edit_pattern_filter'] = 'ENTER: Edit the process filter pattern'
<ide>
<ide> def get_view_data(self, args=None):
<ide> def msg_curse(self, args=None):
<ide> ret.append(self.curse_add_line(self.view_data['diskio_iops']))
<ide> ret.append(self.curse_new_line())
<ide> ret.append(self.curse_add_line(self.view_data['enable_disable_top_extends_stats']))
<add> ret.append(self.curse_add_line(self.view_data['show_hide_top_menu']))
<ide> ret.append(self.curse_new_line())
<ide> ret.append(self.curse_add_line(self.view_data['enable_disable_short_processname']))
<ide> ret.append(self.curse_new_line()) | 1 |
Javascript | Javascript | create time service | 7dcfe5e03ee0943f92791a0e066ce42636ab1b58 | <ide><path>angularFiles.js
<ide> var angularFiles = {
<ide> 'src/ng/sniffer.js',
<ide> 'src/ng/templateRequest.js',
<ide> 'src/ng/testability.js',
<del> 'src/ng/date.js',
<ide> 'src/ng/timeout.js',
<ide> 'src/ng/urlUtils.js',
<ide> 'src/ng/window.js',
<ide><path>src/AngularPublic.js
<ide> $TemplateCacheProvider,
<ide> $TemplateRequestProvider,
<ide> $$TestabilityProvider,
<del> $TimeProvider,
<ide> $TimeoutProvider,
<ide> $$RAFProvider,
<ide> $WindowProvider,
<ide> function publishExternalAPI(angular) {
<ide> $templateCache: $TemplateCacheProvider,
<ide> $templateRequest: $TemplateRequestProvider,
<ide> $$testability: $$TestabilityProvider,
<del> $date: $DateProvider,
<ide> $timeout: $TimeoutProvider,
<ide> $window: $WindowProvider,
<ide> $$rAF: $$RAFProvider,
<ide><path>src/ng/date.js
<del>'use strict';
<del>
<del>/**
<del> * @ngdoc service
<del> * @name $date
<del> * @requires $window
<del> *
<del> * @description
<del> * Simple service for accessing date.
<del> *
<del> * The main purpose of this service is to simplify mocking date in tests.
<del> *
<del> * @example
<del> <example module="dateExample">
<del> <file name="script.js">
<del> angular.module('dateExample', [])
<del> .controller('TimeController', ['$scope', '$date', function($scope, $date) {
<del> $scope.now = $date.now();
<del> }]);
<del> </file>
<del> <file name="index.html">
<del> <div ng-controller="TimeController">
<del> <p>Time when the page was created: {{now | date}}</p>
<del> </div>
<del> </file>
<del> </example>
<del> */
<del>function $DateProvider() {
<del> var self = this;
<del>
<del> this.$get = ['$window', function($window) {
<del> return {
<del> /**
<del> * @ngdoc method
<del> * @name $date#now
<del> *
<del> * @description
<del> * Return Date object representing current date
<del> */
<del> now: function() {
<del> return $window.Date();
<del> }
<del> };
<del> }];
<del>}
<ide><path>test/ng/dateSpec.js
<del>/* global $TimeProvider: false */
<del>'use strict';
<del>
<del>describe('$date', function() {
<del> var $window;
<del>
<del> beforeEach(module(function($provide) {
<del> $window = {};
<del>
<del> $provide.value('$window', $window);
<del> }));
<del>
<del> it('should return Date.new() when $date.now() is called', inject(
<del> function() {
<del> $window.Date = function() {
<del> return Date(1418998923940);
<del> };
<del> },
<del> function($date) {
<del> var date = $date.now();
<del> expect(date).toEqual(Date(1418998923940));
<del> }
<del> ));
<del>
<del>}); | 4 |
Java | Java | remove getvalues() from some subjects/processors | 40087e95cfd4e24bbbe395b3b0cc099fe999e006 | <ide><path>src/main/java/io/reactivex/processors/AsyncProcessor.java
<ide> */
<ide> package io.reactivex.processors;
<ide>
<del>import java.util.Arrays;
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import org.reactivestreams.*;
<ide> * This {@code AsyncProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
<ide> * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the very last observed value -
<ide> * after this {@code AsyncProcessor} has been completed - in a non-blocking and thread-safe
<del> * manner via {@link #hasValue()}, {@link #getValue()}, {@link #getValues()} or {@link #getValues(Object[])}.
<add> * manner via {@link #hasValue()} or {@link #getValue()}.
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The {@code AsyncProcessor} honors the backpressure of the downstream {@code Subscriber}s and won't emit
<ide> public T getValue() {
<ide> return subscribers.get() == TERMINATED ? value : null;
<ide> }
<ide>
<del> /**
<del> * Returns an Object array containing snapshot all values of this processor.
<del> * <p>The method is thread-safe.
<del> * @return the array containing the snapshot of all values of this processor
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> public Object[] getValues() {
<del> T v = getValue();
<del> return v != null ? new Object[] { v } : new Object[0];
<del> }
<del>
<del> /**
<del> * Returns a typed array containing a snapshot of all values of this processor.
<del> * <p>The method follows the conventions of Collection.toArray by setting the array element
<del> * after the last value to null (if the capacity permits).
<del> * <p>The method is thread-safe.
<del> * @param array the target array to copy values into if it fits
<del> * @return the given array if the values fit into it or a new array containing all values
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> public T[] getValues(T[] array) {
<del> T v = getValue();
<del> if (v == null) {
<del> if (array.length != 0) {
<del> array[0] = null;
<del> }
<del> return array;
<del> }
<del> if (array.length == 0) {
<del> array = Arrays.copyOf(array, 1);
<del> }
<del> array[0] = v;
<del> if (array.length != 1) {
<del> array[1] = null;
<del> }
<del> return array;
<del> }
<del>
<ide> static final class AsyncSubscription<T> extends DeferredScalarSubscription<T> {
<ide> private static final long serialVersionUID = 5629876084736248016L;
<ide>
<ide><path>src/main/java/io/reactivex/processors/BehaviorProcessor.java
<ide>
<ide> package io.reactivex.processors;
<ide>
<del>import java.lang.reflect.Array;
<ide> import java.util.concurrent.atomic.*;
<ide> import java.util.concurrent.locks.*;
<ide>
<ide> * <p>
<ide> * This {@code BehaviorProcessor} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
<ide> * {@link #getThrowable()} and {@link #hasSubscribers()} as well as means to read the latest observed value
<del> * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()},
<del> * {@link #getValues()} or {@link #getValues(Object[])}.
<add> * in a non-blocking and thread-safe manner via {@link #hasValue()} or {@link #getValue()}.
<ide> * <p>
<ide> * Note that this processor signals {@code MissingBackpressureException} if a particular {@code Subscriber} is not
<ide> * ready to receive {@code onNext} events. To avoid this exception being signaled, use {@link #offer(Object)} to only
<ide> public T getValue() {
<ide> return NotificationLite.getValue(o);
<ide> }
<ide>
<del> /**
<del> * Returns an Object array containing snapshot all values of the BehaviorProcessor.
<del> * <p>The method is thread-safe.
<del> * @return the array containing the snapshot of all values of the BehaviorProcessor
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> public Object[] getValues() {
<del> @SuppressWarnings("unchecked")
<del> T[] a = (T[])EMPTY_ARRAY;
<del> T[] b = getValues(a);
<del> if (b == EMPTY_ARRAY) {
<del> return new Object[0];
<del> }
<del> return b;
<del>
<del> }
<del>
<del> /**
<del> * Returns a typed array containing a snapshot of all values of the BehaviorProcessor.
<del> * <p>The method follows the conventions of Collection.toArray by setting the array element
<del> * after the last value to null (if the capacity permits).
<del> * <p>The method is thread-safe.
<del> * @param array the target array to copy values into if it fits
<del> * @return the given array if the values fit into it or a new array containing all values
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> @SuppressWarnings("unchecked")
<del> public T[] getValues(T[] array) {
<del> Object o = value.get();
<del> if (o == null || NotificationLite.isComplete(o) || NotificationLite.isError(o)) {
<del> if (array.length != 0) {
<del> array[0] = null;
<del> }
<del> return array;
<del> }
<del> T v = NotificationLite.getValue(o);
<del> if (array.length != 0) {
<del> array[0] = v;
<del> if (array.length != 1) {
<del> array[1] = null;
<del> }
<del> } else {
<del> array = (T[])Array.newInstance(array.getClass().getComponentType(), 1);
<del> array[0] = v;
<del> }
<del> return array;
<del> }
<del>
<ide> @Override
<ide> public boolean hasComplete() {
<ide> Object o = value.get();
<ide><path>src/main/java/io/reactivex/subjects/AsyncSubject.java
<ide>
<ide> package io.reactivex.subjects;
<ide>
<del>import io.reactivex.annotations.Nullable;
<del>import io.reactivex.annotations.NonNull;
<del>import java.util.Arrays;
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide>
<ide> import io.reactivex.Observer;
<del>import io.reactivex.annotations.CheckReturnValue;
<add>import io.reactivex.annotations.*;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.internal.functions.ObjectHelper;
<ide> import io.reactivex.internal.observers.DeferredScalarDisposable;
<ide> * This {@code AsyncSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
<ide> * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the very last observed value -
<ide> * after this {@code AsyncSubject} has been completed - in a non-blocking and thread-safe
<del> * manner via {@link #hasValue()}, {@link #getValue()}, {@link #getValues()} or {@link #getValues(Object[])}.
<add> * manner via {@link #hasValue()} or {@link #getValue()}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code AsyncSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and
<ide> public T getValue() {
<ide> return subscribers.get() == TERMINATED ? value : null;
<ide> }
<ide>
<del> /**
<del> * Returns an Object array containing snapshot all values of the Subject.
<del> * <p>The method is thread-safe.
<del> * @return the array containing the snapshot of all values of the Subject
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> public Object[] getValues() {
<del> T v = getValue();
<del> return v != null ? new Object[] { v } : new Object[0];
<del> }
<del>
<del> /**
<del> * Returns a typed array containing a snapshot of all values of the Subject.
<del> * <p>The method follows the conventions of Collection.toArray by setting the array element
<del> * after the last value to null (if the capacity permits).
<del> * <p>The method is thread-safe.
<del> * @param array the target array to copy values into if it fits
<del> * @return the given array if the values fit into it or a new array containing all values
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> public T[] getValues(T[] array) {
<del> T v = getValue();
<del> if (v == null) {
<del> if (array.length != 0) {
<del> array[0] = null;
<del> }
<del> return array;
<del> }
<del> if (array.length == 0) {
<del> array = Arrays.copyOf(array, 1);
<del> }
<del> array[0] = v;
<del> if (array.length != 1) {
<del> array[1] = null;
<del> }
<del> return array;
<del> }
<del>
<ide> static final class AsyncDisposable<T> extends DeferredScalarDisposable<T> {
<ide> private static final long serialVersionUID = 5629876084736248016L;
<ide>
<ide><path>src/main/java/io/reactivex/subjects/BehaviorSubject.java
<ide>
<ide> package io.reactivex.subjects;
<ide>
<del>import io.reactivex.annotations.CheckReturnValue;
<del>import io.reactivex.annotations.Nullable;
<del>import io.reactivex.annotations.NonNull;
<del>import java.lang.reflect.Array;
<ide> import java.util.concurrent.atomic.AtomicReference;
<ide> import java.util.concurrent.locks.*;
<ide>
<ide> import io.reactivex.Observer;
<add>import io.reactivex.annotations.*;
<ide> import io.reactivex.disposables.Disposable;
<ide> import io.reactivex.internal.functions.ObjectHelper;
<ide> import io.reactivex.internal.util.*;
<ide> * <p>
<ide> * This {@code BehaviorSubject} supports the standard state-peeking methods {@link #hasComplete()}, {@link #hasThrowable()},
<ide> * {@link #getThrowable()} and {@link #hasObservers()} as well as means to read the latest observed value
<del> * in a non-blocking and thread-safe manner via {@link #hasValue()}, {@link #getValue()},
<del> * {@link #getValues()} or {@link #getValues(Object[])}.
<add> * in a non-blocking and thread-safe manner via {@link #hasValue()} or {@link #getValue()}.
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code BehaviorSubject} does not operate by default on a particular {@link io.reactivex.Scheduler} and
<ide> */
<ide> public final class BehaviorSubject<T> extends Subject<T> {
<ide>
<del> /** An empty array to avoid allocation in getValues(). */
<del> private static final Object[] EMPTY_ARRAY = new Object[0];
<del>
<ide> final AtomicReference<Object> value;
<ide>
<ide> final AtomicReference<BehaviorDisposable<T>[]> subscribers;
<ide> public T getValue() {
<ide> return NotificationLite.getValue(o);
<ide> }
<ide>
<del> /**
<del> * Returns an Object array containing snapshot all values of the Subject.
<del> * <p>The method is thread-safe.
<del> * @return the array containing the snapshot of all values of the Subject
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> public Object[] getValues() {
<del> @SuppressWarnings("unchecked")
<del> T[] a = (T[])EMPTY_ARRAY;
<del> T[] b = getValues(a);
<del> if (b == EMPTY_ARRAY) {
<del> return new Object[0];
<del> }
<del> return b;
<del>
<del> }
<del>
<del> /**
<del> * Returns a typed array containing a snapshot of all values of the Subject.
<del> * <p>The method follows the conventions of Collection.toArray by setting the array element
<del> * after the last value to null (if the capacity permits).
<del> * <p>The method is thread-safe.
<del> * @param array the target array to copy values into if it fits
<del> * @return the given array if the values fit into it or a new array containing all values
<del> * @deprecated in 2.1.14; put the result of {@link #getValue()} into an array manually, will be removed in 3.x
<del> */
<del> @Deprecated
<del> @SuppressWarnings("unchecked")
<del> public T[] getValues(T[] array) {
<del> Object o = value.get();
<del> if (o == null || NotificationLite.isComplete(o) || NotificationLite.isError(o)) {
<del> if (array.length != 0) {
<del> array[0] = null;
<del> }
<del> return array;
<del> }
<del> T v = NotificationLite.getValue(o);
<del> if (array.length != 0) {
<del> array[0] = v;
<del> if (array.length != 1) {
<del> array[1] = null;
<del> }
<del> } else {
<del> array = (T[])Array.newInstance(array.getClass().getComponentType(), 1);
<del> array[0] = v;
<del> }
<del> return array;
<del> }
<del>
<ide> @Override
<ide> public boolean hasComplete() {
<ide> Object o = value.get();
<ide><path>src/test/java/io/reactivex/processors/SerializedProcessorTest.java
<ide> public void testBasic() {
<ide> ts.assertValue("hello");
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testAsyncSubjectValueRelay() {
<ide> AsyncProcessor<Integer> async = AsyncProcessor.create();
<ide> public void testAsyncSubjectValueRelay() {
<ide> assertNull(serial.getThrowable());
<ide> assertEquals((Integer)1, async.getValue());
<ide> assertTrue(async.hasValue());
<del> assertArrayEquals(new Object[] { 1 }, async.getValues());
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testAsyncSubjectValueEmpty() {
<ide> AsyncProcessor<Integer> async = AsyncProcessor.create();
<ide> public void testAsyncSubjectValueEmpty() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testAsyncSubjectValueError() {
<ide> AsyncProcessor<Integer> async = AsyncProcessor.create();
<ide> public void testAsyncSubjectValueError() {
<ide> assertSame(te, serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<ide> @Test
<ide> public void testPublishSubjectValueError() {
<ide> assertSame(te, serial.getThrowable());
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectValueRelay() {
<ide> BehaviorProcessor<Integer> async = BehaviorProcessor.create();
<ide> public void testBehaviorSubjectValueRelay() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectValueRelayIncomplete() {
<ide> BehaviorProcessor<Integer> async = BehaviorProcessor.create();
<ide> public void testBehaviorSubjectValueRelayIncomplete() {
<ide> assertNull(serial.getThrowable());
<ide> assertEquals((Integer)1, async.getValue());
<ide> assertTrue(async.hasValue());
<del> assertArrayEquals(new Object[] { 1 }, async.getValues());
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectIncompleteEmpty() {
<ide> BehaviorProcessor<Integer> async = BehaviorProcessor.create();
<ide> public void testBehaviorSubjectIncompleteEmpty() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectEmpty() {
<ide> BehaviorProcessor<Integer> async = BehaviorProcessor.create();
<ide> public void testBehaviorSubjectEmpty() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectError() {
<ide> BehaviorProcessor<Integer> async = BehaviorProcessor.create();
<ide> public void testBehaviorSubjectError() {
<ide> assertSame(te, serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<ide> @Test
<ide><path>src/test/java/io/reactivex/subjects/SerializedSubjectTest.java
<ide> public void testBasic() {
<ide> to.assertValue("hello");
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testAsyncSubjectValueRelay() {
<ide> AsyncSubject<Integer> async = AsyncSubject.create();
<ide> public void testAsyncSubjectValueRelay() {
<ide> assertNull(serial.getThrowable());
<ide> assertEquals((Integer)1, async.getValue());
<ide> assertTrue(async.hasValue());
<del> assertArrayEquals(new Object[] { 1 }, async.getValues());
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testAsyncSubjectValueEmpty() {
<ide> AsyncSubject<Integer> async = AsyncSubject.create();
<ide> public void testAsyncSubjectValueEmpty() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testAsyncSubjectValueError() {
<ide> AsyncSubject<Integer> async = AsyncSubject.create();
<ide> public void testAsyncSubjectValueError() {
<ide> assertSame(te, serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<ide> @Test
<ide> public void testPublishSubjectValueError() {
<ide> assertSame(te, serial.getThrowable());
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectValueRelay() {
<ide> BehaviorSubject<Integer> async = BehaviorSubject.create();
<ide> public void testBehaviorSubjectValueRelay() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectValueRelayIncomplete() {
<ide> BehaviorSubject<Integer> async = BehaviorSubject.create();
<ide> public void testBehaviorSubjectValueRelayIncomplete() {
<ide> assertNull(serial.getThrowable());
<ide> assertEquals((Integer)1, async.getValue());
<ide> assertTrue(async.hasValue());
<del> assertArrayEquals(new Object[] { 1 }, async.getValues());
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { 1 }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { 1, null }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectIncompleteEmpty() {
<ide> BehaviorSubject<Integer> async = BehaviorSubject.create();
<ide> public void testBehaviorSubjectIncompleteEmpty() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectEmpty() {
<ide> BehaviorSubject<Integer> async = BehaviorSubject.create();
<ide> public void testBehaviorSubjectEmpty() {
<ide> assertNull(serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<del> @SuppressWarnings("deprecation")
<ide> @Test
<ide> public void testBehaviorSubjectError() {
<ide> BehaviorSubject<Integer> async = BehaviorSubject.create();
<ide> public void testBehaviorSubjectError() {
<ide> assertSame(te, serial.getThrowable());
<ide> assertNull(async.getValue());
<ide> assertFalse(async.hasValue());
<del> assertArrayEquals(new Object[] { }, async.getValues());
<del> assertArrayEquals(new Integer[] { }, async.getValues(new Integer[0]));
<del> assertArrayEquals(new Integer[] { null }, async.getValues(new Integer[] { 0 }));
<del> assertArrayEquals(new Integer[] { null, 0 }, async.getValues(new Integer[] { 0, 0 }));
<ide> }
<ide>
<ide> @Test | 6 |
Javascript | Javascript | do less manual conversion | cbd89e26fd05ed2f22b028c700ce1bc9a775d4ac | <ide><path>fonts.js
<ide> CFF.prototype = {
<ide> }
<ide> break;
<ide>
<del> case "div":
<del> var num2 = charstring[i - 1];
<del> var num1 = charstring[i - 2];
<del> charstring.splice(i - 2, 3, num1 / num2);
<del> i -= 2;
<del> break;
<del>
<ide> case "hsbw":
<del> var charWidthVector = charstring[i - 1];
<del> var leftSidebearing = charstring[i - 2];
<add> var charWidthVector = charstring[1];
<add> var leftSidebearing = charstring[0];
<ide>
<del> if (leftSidebearing)
<del> charstring.splice(i - 2, 3, charWidthVector, leftSidebearing, "hmoveto");
<del> else
<del> charstring.splice(i - 2, 3, charWidthVector);
<add> charstring.splice(i, 1, leftSidebearing, "hmoveto");
<add> charstring.splice(0, 1);
<ide> break;
<ide>
<ide> case "endchar":
<ide> CFF.prototype = {
<ide> } else {
<ide> charstring[j] = command;
<ide> }
<del> } else {
<del> charstring.splice(j, 1);
<del>
<del> // command has already been translated, just add them to the
<del> // charstring directly
<del> for (var k = 0; k < command.length; k++)
<del> charstring.splice(j + k, 0, command[k]);
<del> j+= command.length - 1;
<ide> }
<ide> }
<ide> return charstring; | 1 |
Go | Go | add missing package import | eca861a99d1a5abe91704b55d044eb8280adb8d1 | <ide><path>runtime.go
<ide> import (
<ide> "path"
<ide> "sort"
<ide> "strings"
<add> "time"
<ide> )
<ide>
<ide> var defaultDns = []string{"8.8.8.8", "8.8.4.4"} | 1 |
Java | Java | move error consumer helper to internal api. | f8c33a9b7d3edd01df38c9b2ed52fa10e1194a2a | <ide><path>src/main/java/io/reactivex/Flowable.java
<ide> public final void blockingSubscribe() {
<ide> * @since 2.0
<ide> */
<ide> public final void blockingSubscribe(Consumer<? super T> onNext) {
<del> FlowableBlockingSubscribe.subscribe(this, onNext, RxJavaPlugins.errorConsumer(), Functions.EMPTY_ACTION);
<add> FlowableBlockingSubscribe.subscribe(this, onNext, Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION);
<ide> }
<ide>
<ide> /**
<ide> public final Disposable forEach(Consumer<? super T> onNext) {
<ide> @BackpressureSupport(BackpressureKind.NONE)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Disposable forEachWhile(Predicate<? super T> onNext) {
<del> return forEachWhile(onNext, RxJavaPlugins.errorConsumer(), Functions.EMPTY_ACTION);
<add> return forEachWhile(onNext, Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION);
<ide> }
<ide>
<ide> /**
<ide> public final Flowable<T> startWithArray(T... values) {
<ide> @BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Disposable subscribe() {
<del> return subscribe(Functions.emptyConsumer(), RxJavaPlugins.errorConsumer(),
<add> return subscribe(Functions.emptyConsumer(), Functions.ERROR_CONSUMER,
<ide> Functions.EMPTY_ACTION, FlowableInternalHelper.requestMax());
<ide> }
<ide>
<ide> public final Disposable subscribe() {
<ide> @BackpressureSupport(BackpressureKind.UNBOUNDED_IN)
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Disposable subscribe(Consumer<? super T> onNext) {
<del> return subscribe(onNext, RxJavaPlugins.errorConsumer(),
<add> return subscribe(onNext, Functions.ERROR_CONSUMER,
<ide> Functions.EMPTY_ACTION, FlowableInternalHelper.requestMax());
<ide> }
<ide>
<ide><path>src/main/java/io/reactivex/Observable.java
<ide> public final void blockingSubscribe() {
<ide> * @since 2.0
<ide> */
<ide> public final void blockingSubscribe(Consumer<? super T> onNext) {
<del> ObservableBlockingSubscribe.subscribe(this, onNext, RxJavaPlugins.errorConsumer(), Functions.EMPTY_ACTION);
<add> ObservableBlockingSubscribe.subscribe(this, onNext, Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION);
<ide> }
<ide>
<ide> /**
<ide> public final Disposable forEach(Consumer<? super T> onNext) {
<ide> */
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Disposable forEachWhile(Predicate<? super T> onNext) {
<del> return forEachWhile(onNext, RxJavaPlugins.errorConsumer(), Functions.EMPTY_ACTION);
<add> return forEachWhile(onNext, Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION);
<ide> }
<ide>
<ide> /**
<ide> public final Observable<T> startWithArray(T... values) {
<ide> */
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Disposable subscribe() {
<del> return subscribe(Functions.emptyConsumer(), RxJavaPlugins.errorConsumer(), Functions.EMPTY_ACTION, Functions.emptyConsumer());
<add> return subscribe(Functions.emptyConsumer(), Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION, Functions.emptyConsumer());
<ide> }
<ide>
<ide> /**
<ide> public final Disposable subscribe() {
<ide> */
<ide> @SchedulerSupport(SchedulerSupport.NONE)
<ide> public final Disposable subscribe(Consumer<? super T> onNext) {
<del> return subscribe(onNext, RxJavaPlugins.errorConsumer(), Functions.EMPTY_ACTION, Functions.emptyConsumer());
<add> return subscribe(onNext, Functions.ERROR_CONSUMER, Functions.EMPTY_ACTION, Functions.emptyConsumer());
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/Single.java
<ide> public final void safeSubscribe(Subscriber<? super T> s) {
<ide> * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
<ide> */
<ide> public final Disposable subscribe() {
<del> return subscribe(Functions.emptyConsumer(), RxJavaPlugins.errorConsumer());
<add> return subscribe(Functions.emptyConsumer(), Functions.ERROR_CONSUMER);
<ide> }
<ide>
<ide> /**
<ide> public final Disposable subscribe(final BiConsumer<? super T, ? super Throwable>
<ide> * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX operators documentation: Subscribe</a>
<ide> */
<ide> public final Disposable subscribe(Consumer<? super T> onSuccess) {
<del> return subscribe(onSuccess, RxJavaPlugins.errorConsumer());
<add> return subscribe(onSuccess, Functions.ERROR_CONSUMER);
<ide> }
<ide>
<ide> /**
<ide><path>src/main/java/io/reactivex/internal/functions/Functions.java
<ide>
<ide> import io.reactivex.*;
<ide> import io.reactivex.functions.*;
<add>import io.reactivex.plugins.RxJavaPlugins;
<ide> import io.reactivex.schedulers.Timed;
<ide>
<ide> /**
<ide> public void accept(Object v) { }
<ide> public static <T> Consumer<T> emptyConsumer() {
<ide> return (Consumer<T>)EMPTY_CONSUMER;
<ide> }
<del>
<add>
<add> public static final Consumer<Throwable> ERROR_CONSUMER = new Consumer<Throwable>() {
<add> @Override
<add> public void accept(Throwable error) {
<add> RxJavaPlugins.onError(error);
<add> }
<add> };
<add>
<ide> public static final LongConsumer EMPTY_LONGCONSUMER = new LongConsumer() {
<ide> @Override
<ide> public void accept(long v) { }
<ide><path>src/main/java/io/reactivex/plugins/RxJavaPlugins.java
<ide> public static Completable onAssembly(Completable source) {
<ide> return source;
<ide> }
<ide>
<del> /** Singleton consumer that calls RxJavaPlugins.onError. */
<del> static final Consumer<Throwable> CONSUME_BY_RXJAVA_PLUGIN = new Consumer<Throwable>() {
<del> @Override
<del> public void accept(Throwable e) {
<del> RxJavaPlugins.onError(e);
<del> }
<del> };
<del>
<del> /**
<del> * Returns a consumer which relays the received Throwable to RxJavaPlugins.onError().
<del> * @return the consumer
<del> */
<del> public static Consumer<Throwable> errorConsumer() {
<del> return CONSUME_BY_RXJAVA_PLUGIN;
<del> }
<del>
<ide> /**
<ide> * Wraps the call to the function in try-catch and propagates thrown
<ide> * checked exceptions as runtimeexception. | 5 |
Ruby | Ruby | update command comparison to `*commands` vararg | ea4fb0fe09d033ca79bcaa908b2c0ad4baf25022 | <ide><path>Library/Homebrew/rubocops/lines.rb
<ide> def audit_formula(_node, _class_node, _parent_class_node, body_node)
<ide> return if offenses.blank?
<ide>
<ide> T.must(offenses[0...-1]).each_with_index do |node, i|
<del> # executable and subcmd have to be the same to be combined
<del> if node.arguments.first != offenses[i + 1].arguments.first ||
<del> node.arguments.second != offenses[i + 1].arguments.second
<add> # commands have to be the same to be combined
<add> # send_type? matches `bin/"foo"`, str_type? matches remaining command parts,
<add> # the rest are kwargs we need to filter out
<add> method_commands = node.arguments.filter { |arg| arg.send_type? || arg.str_type? }
<add> next_method_commands = offenses[i + 1].arguments.filter { |arg| arg.send_type? || arg.str_type? }
<add> unless method_commands == next_method_commands
<ide> shells.delete_at(i)
<ide> next
<ide> end | 1 |
Ruby | Ruby | fix svn test on older macos | a2f95125f0828e5c8801000ef459a6dc9e180ef1 | <ide><path>Library/Homebrew/test/os/mac/dependency_collector_spec.rb
<ide> specify "Resource dependency from a Subversion URL" do
<ide> resource = Resource.new
<ide> resource.url("svn://brew.sh/foo/bar")
<del> if MacOS.version < :catalina
<del> expect(collector.add(resource)).to be_nil
<del> else
<del> expect(collector.add(resource)).not_to be_nil
<del> end
<add> expect(collector.add(resource)).to eq(Dependency.new("subversion", [:build, :test]))
<ide> end
<ide> end | 1 |
Python | Python | fix typo in test_dag_run_schema.py | a1a312ee1bc8693afded31a90ad216e72697d2ee | <ide><path>tests/api_connexion/schemas/test_dag_run_schema.py
<ide> def tearDown(self) -> None:
<ide>
<ide> class TestDAGRunSchema(TestDAGRunBase):
<ide> @provide_session
<del> def test_serialze(self, session):
<add> def test_serialize(self, session):
<ide> dagrun_model = DagRun(
<ide> run_id="my-dag-run",
<ide> run_type=DagRunType.MANUAL.value, | 1 |
PHP | PHP | use assertcount(). | 520fb03d1fe8f019c79a4f49744ae36ab44bed51 | <ide><path>tests/Database/DatabaseEloquentHasManyTest.php
<ide> public function testModelsAreProperlyMatchedToParents()
<ide> $models = $relation->match([$model1, $model2, $model3], new Collection([$result1, $result2, $result3]), 'foo');
<ide>
<ide> $this->assertEquals(1, $models[0]->foo[0]->foreign_key);
<del> $this->assertEquals(1, count($models[0]->foo));
<add> $this->assertCount(1, $models[0]->foo);
<ide> $this->assertEquals(2, $models[1]->foo[0]->foreign_key);
<ide> $this->assertEquals(2, $models[1]->foo[1]->foreign_key);
<del> $this->assertEquals(2, count($models[1]->foo));
<add> $this->assertCount(2, $models[1]->foo);
<ide> $this->assertNull($models[2]->foo);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testBasicModelRetrieval()
<ide>
<ide> $collection = EloquentTestUser::find([]);
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection);
<del> $this->assertEquals(0, $collection->count());
<add> $this->assertCount(0, $collection);
<ide>
<ide> $collection = EloquentTestUser::find([1, 2, 3]);
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection);
<del> $this->assertEquals(2, $collection->count());
<add> $this->assertCount(2, $collection);
<ide>
<ide> $models = EloquentTestUser::where('id', 1)->cursor();
<ide> foreach ($models as $model) {
<ide> public function testBasicModelCollectionRetrieval()
<ide>
<ide> $models = EloquentTestUser::oldest('id')->get();
<ide>
<del> $this->assertEquals(2, $models->count());
<add> $this->assertCount(2, $models);
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $models);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[0]);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[1]);
<ide> public function testPaginatedModelCollectionRetrieval()
<ide> });
<ide> $models = EloquentTestUser::oldest('id')->paginate(2);
<ide>
<del> $this->assertEquals(2, $models->count());
<add> $this->assertCount(2, $models);
<ide> $this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $models);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[0]);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[1]);
<ide> public function testPaginatedModelCollectionRetrieval()
<ide> });
<ide> $models = EloquentTestUser::oldest('id')->paginate(2);
<ide>
<del> $this->assertEquals(1, $models->count());
<add> $this->assertCount(1, $models);
<ide> $this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $models);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[0]);
<ide> $this->assertEquals('foo@gmail.com', $models[0]->email);
<ide> public function testPaginatedModelCollectionRetrievalWhenNoElements()
<ide> });
<ide> $models = EloquentTestUser::oldest('id')->paginate(2);
<ide>
<del> $this->assertEquals(0, $models->count());
<add> $this->assertCount(0, $models);
<ide> $this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $models);
<ide>
<ide> Paginator::currentPageResolver(function () {
<ide> return 2;
<ide> });
<ide> $models = EloquentTestUser::oldest('id')->paginate(2);
<ide>
<del> $this->assertEquals(0, $models->count());
<add> $this->assertCount(0, $models);
<ide> }
<ide>
<ide> public function testPaginatedModelCollectionRetrievalWhenNoElementsAndDefaultPerPage()
<ide> {
<ide> $models = EloquentTestUser::oldest('id')->paginate();
<ide>
<del> $this->assertEquals(0, $models->count());
<add> $this->assertCount(0, $models);
<ide> $this->assertInstanceOf('Illuminate\Pagination\LengthAwarePaginator', $models);
<ide> }
<ide>
<ide> public function testOneToManyRelationship()
<ide> $post2 = $user->posts()->where('name', 'Second Post')->first();
<ide>
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $posts);
<del> $this->assertEquals(2, $posts->count());
<add> $this->assertCount(2, $posts);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPost', $posts[0]);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPost', $posts[1]);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPost', $post2);
<ide> public function testBasicModelHydration()
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[0]);
<ide> $this->assertEquals('abigailotwell@gmail.com', $models[0]->email);
<ide> $this->assertEquals('second_connection', $models[0]->getConnectionName());
<del> $this->assertEquals(1, $models->count());
<add> $this->assertCount(1, $models);
<ide> }
<ide>
<ide> public function testHasOnSelfReferencingBelongsToManyRelationship()
<ide> public function testBasicMorphManyRelationship()
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPhoto', $user->photos[0]);
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $post->photos);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPhoto', $post->photos[0]);
<del> $this->assertEquals(2, $user->photos->count());
<del> $this->assertEquals(2, $post->photos->count());
<add> $this->assertCount(2, $user->photos);
<add> $this->assertCount(2, $post->photos);
<ide> $this->assertEquals('Avatar 1', $user->photos[0]->name);
<ide> $this->assertEquals('Avatar 2', $user->photos[1]->name);
<ide> $this->assertEquals('Hero 1', $post->photos[0]->name);
<ide> public function testBasicMorphManyRelationship()
<ide> $photos = EloquentTestPhoto::orderBy('name')->get();
<ide>
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $photos);
<del> $this->assertEquals(4, $photos->count());
<add> $this->assertCount(4, $photos);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $photos[0]->imageable);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPost', $photos[2]->imageable);
<ide> $this->assertEquals('taylorotwell@gmail.com', $photos[1]->imageable->email);
<ide> public function testMorphMapIsUsedForCreatingAndFetchingThroughRelation()
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPhoto', $user->photos[0]);
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $post->photos);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestPhoto', $post->photos[0]);
<del> $this->assertEquals(2, $user->photos->count());
<del> $this->assertEquals(2, $post->photos->count());
<add> $this->assertCount(2, $user->photos);
<add> $this->assertCount(2, $post->photos);
<ide> $this->assertEquals('Avatar 1', $user->photos[0]->name);
<ide> $this->assertEquals('Avatar 2', $user->photos[1]->name);
<ide> $this->assertEquals('Hero 1', $post->photos[0]->name);
<ide><path>tests/Database/DatabaseEloquentIntegrationWithTablePrefixTest.php
<ide> public function testBasicModelHydration()
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $models);
<ide> $this->assertInstanceOf('Illuminate\Tests\Database\EloquentTestUser', $models[0]);
<ide> $this->assertEquals('abigailotwell@gmail.com', $models[0]->email);
<del> $this->assertEquals(1, $models->count());
<add> $this->assertCount(1, $models);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseEloquentPolymorphicRelationsIntegrationTest.php
<ide> public function testCreation()
<ide> $post->tags()->attach($tag2->id);
<ide> $image->tags()->attach($tag->id);
<ide>
<del> $this->assertEquals(2, $post->tags->count());
<del> $this->assertEquals(1, $image->tags->count());
<del> $this->assertEquals(1, $tag->posts->count());
<del> $this->assertEquals(1, $tag->images->count());
<del> $this->assertEquals(1, $tag2->posts->count());
<del> $this->assertEquals(0, $tag2->images->count());
<add> $this->assertCount(2, $post->tags);
<add> $this->assertCount(1, $image->tags);
<add> $this->assertCount(1, $tag->posts);
<add> $this->assertCount(1, $tag->images);
<add> $this->assertCount(1, $tag2->posts);
<add> $this->assertCount(0, $tag2->images);
<ide> }
<ide>
<ide> public function testEagerLoading()
<ide><path>tests/Database/DatabaseMySqlSchemaGrammarTest.php
<ide> public function testAddingComment()
<ide> $blueprint->string('foo')->comment("Escape ' when using words like it's");
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals("alter table `users` add `foo` varchar(255) not null comment 'Escape \\' when using words like it\\'s'", $statements[0]);
<ide> }
<ide>
<ide><path>tests/Integration/Database/EloquentDeleteTest.php
<ide> public function testOnlyDeleteWhatGiven()
<ide> }
<ide>
<ide> Post::latest('id')->limit(1)->delete();
<del> $this->assertEquals(9, Post::all()->count());
<add> $this->assertCount(9, Post::all());
<ide>
<ide> Post::join('comments', 'comments.post_id', '=', 'posts.id')->where('posts.id', '>', 1)->orderBy('posts.id')->limit(1)->delete();
<del> $this->assertEquals(8, Post::all()->count());
<add> $this->assertCount(8, Post::all());
<ide> }
<ide>
<ide> public function testForceDeletedEventIsFired()
<ide><path>tests/Integration/Database/EloquentUpdateTest.php
<ide> public function testBasicUpdate()
<ide>
<ide> TestUpdateModel1::where('title', 'Ms.')->delete();
<ide>
<del> $this->assertEquals(0, TestUpdateModel1::all()->count());
<add> $this->assertCount(0, TestUpdateModel1::all());
<ide> }
<ide>
<ide> public function testUpdateWithLimitsAndOrders()
<ide> public function testSoftDeleteWithJoins()
<ide> ->where('test_model1.title', '=', 'Mr.');
<ide> })->delete();
<ide>
<del> $this->assertEquals(0, TestUpdateModel2::all()->count());
<add> $this->assertCount(0, TestUpdateModel2::all());
<ide> }
<ide> }
<ide>
<ide><path>tests/Support/SupportViewErrorBagTest.php
<ide> public function testCount()
<ide> {
<ide> $viewErrorBag = new ViewErrorBag();
<ide> $viewErrorBag->put('default', new MessageBag(['message', 'second']));
<del> $this->assertEquals(2, $viewErrorBag->count());
<add> $this->assertCount(2, $viewErrorBag);
<ide> }
<ide>
<ide> public function testCountWithNoMessagesInMessageBag()
<ide> {
<ide> $viewErrorBag = new ViewErrorBag();
<ide> $viewErrorBag->put('default', new MessageBag());
<del> $this->assertEquals(0, $viewErrorBag->count());
<add> $this->assertCount(0, $viewErrorBag);
<ide> }
<ide>
<ide> public function testCountWithNoMessageBags()
<ide> {
<ide> $viewErrorBag = new ViewErrorBag();
<del> $this->assertEquals(0, $viewErrorBag->count());
<add> $this->assertCount(0, $viewErrorBag);
<ide> }
<ide>
<ide> public function testDynamicCallToDefaultMessageBag() | 8 |
Python | Python | fix leakyrelu return dtype | dd766c68d929c394cb17dd92b9cca20cbd7d32c4 | <ide><path>keras/layers/advanced_activations.py
<ide> class LeakyReLU(Layer):
<ide> '''
<ide> def __init__(self, alpha=0.3, **kwargs):
<ide> self.supports_masking = True
<del> self.alpha = K.cast_to_floatx(alpha)
<add> self.alpha = alpha
<ide> super(LeakyReLU, self).__init__(**kwargs)
<ide>
<ide> def call(self, x, mask=None):
<ide><path>keras/utils/test_utils.py
<ide> def get_test_data(nb_train=1000, nb_test=500, input_shape=(10,),
<ide>
<ide>
<ide> def layer_test(layer_cls, kwargs={}, input_shape=None, input_dtype=None,
<del> input_data=None, expected_output=None):
<add> input_data=None, expected_output=None, expected_output_dtype=None):
<ide> '''Test routine for a layer with a single input tensor
<ide> and single output tensor.
<ide> '''
<ide> def layer_test(layer_cls, kwargs={}, input_shape=None, input_dtype=None,
<ide> elif input_shape is None:
<ide> input_shape = input_data.shape
<ide>
<add> if expected_output_dtype is None:
<add> expected_output_dtype = input_dtype
<add>
<ide> # instantiation
<ide> layer = layer_cls(**kwargs)
<ide>
<ide> def layer_test(layer_cls, kwargs={}, input_shape=None, input_dtype=None,
<ide> # test in functional API
<ide> x = Input(shape=input_shape[1:], dtype=input_dtype)
<ide> y = layer(x)
<add> assert K.dtype(y) == expected_output_dtype
<add>
<ide> model = Model(input=x, output=y)
<ide> model.compile('rmsprop', 'mse')
<ide>
<ide><path>tests/keras/layers/test_embeddings.py
<ide> import pytest
<ide> from keras.utils.test_utils import layer_test
<ide> from keras.layers.embeddings import Embedding
<add>import keras.backend as K
<ide>
<ide>
<ide> def test_embedding():
<ide> layer_test(Embedding,
<ide> kwargs={'output_dim': 4., 'input_dim': 10, 'input_length': 2},
<ide> input_shape=(3, 2),
<del> input_dtype='int32')
<add> input_dtype='int32',
<add> expected_output_dtype=K.floatx())
<ide>
<ide>
<ide> if __name__ == '__main__': | 3 |
Python | Python | add flag to toggle gpu to dynet code | 8f053fd943e86011306403dff6b4bfbf93fd2f56 | <ide><path>examples/spacy_dynet_lstm.py
<ide> import random
<ide> from collections import Counter
<ide> import numpy as np
<add>import os
<ide>
<ide> from collections import defaultdict
<ide> from itertools import count
<ide>
<del>#import _gdynet as dynet
<del>#from _gdynet import cg
<del>import dynet
<del>from dynet import cg
<add>if os.environ.get('DYNET_GPU') == '1':
<add> import _gdynet as dynet
<add> from _gdynet import cg
<add>else:
<add> import dynet
<add> from dynet import cg
<ide>
<ide>
<ide> class Vocab:
<ide> def main(train_loc, dev_loc, model_dir):
<ide>
<ide> tagged = loss = 0
<ide>
<del> for ITER in xrange(50):
<add> for ITER in xrange(1):
<ide> random.shuffle(train)
<ide> for i, s in enumerate(train,1):
<ide> if i % 5000 == 0: | 1 |
Text | Text | add empty lines in catphotoapp project | 369db647f58b2646abe0e3394c1604091d3ee18a | <ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc1798ff86c76b9248c6eb3.md
<ide> assert(collection.indexOf('H1') < collection.indexOf('H2'));
<ide> <body>
<ide> --fcc-editable-region--
<ide> <h1>CatPhotoApp</h1>
<add>
<ide> --fcc-editable-region--
<ide> </body>
<ide> </html>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc17d3bf86c76b9248c6eb4.md
<ide> assert(collection.indexOf('H2') < collection.indexOf('P'));
<ide> <h1>CatPhotoApp</h1>
<ide> --fcc-editable-region--
<ide> <h2>Cat Photos</h2>
<add>
<ide> --fcc-editable-region--
<ide> </body>
<ide> </html>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc17dc8f86c76b9248c6eb5.md
<ide> assert(
<ide> <h2>Cat Photos</h2>
<ide> --fcc-editable-region--
<ide> <p>Click here to view more cat photos.</p>
<add>
<ide> --fcc-editable-region--
<ide> </body>
<ide> </html>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc2385ff86c76b9248c6eb7.md
<ide> assert(
<ide> <html>
<ide> <body>
<ide> --fcc-editable-region--
<add>
<ide> <h1>CatPhotoApp</h1>
<ide> <h2>Cat Photos</h2>
<ide> <!-- TODO: Add link to cat photos -->
<ide> <p>Click here to view more cat photos.</p>
<add>
<ide> --fcc-editable-region--
<ide> </body>
<ide> </html>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc23f9bf86c76b9248c6eba.md
<ide> assert(collection.indexOf('P') < collection.indexOf('IMG'));
<ide> <!-- TODO: Add link to cat photos -->
<ide> --fcc-editable-region--
<ide> <p>Click here to view more cat photos.</p>
<add>
<ide> --fcc-editable-region--
<ide> </main>
<ide> </body>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dc24614f86c76b9248c6ebd.md
<ide> assert(
<ide> <!-- TODO: Add link to cat photos -->
<ide> --fcc-editable-region--
<ide> <p>Click here to view more cat photos.</p>
<add>
<ide> --fcc-editable-region--
<ide> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back.">
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfa3589eacea3f48c6300ae.md
<ide> assert(
<ide> </section>
<ide> --fcc-editable-region--
<ide> <section>
<add>
<ide> </section>
<ide> --fcc-editable-region--
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfa371beacea3f48c6300af.md
<ide> assert(
<ide> --fcc-editable-region--
<ide> <section>
<ide> <h2>Cat Lists</h2>
<add>
<ide> </section>
<ide> --fcc-editable-region--
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfa37b9eacea3f48c6300b0.md
<ide> assert(secondSectionLastElemNode.nodeName === 'UL');
<ide> --fcc-editable-region--
<ide> <h2>Cat Lists</h2>
<ide> <h3>Things cats love:</h3>
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfb5ecbeacea3f48c6300b1.md
<ide> assert(
<ide> <h3>Things cats love:</h3>
<ide> --fcc-editable-region--
<ide> <ul>
<add>
<ide> </ul>
<ide> --fcc-editable-region--
<ide> </section>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfb6250eacea3f48c6300b2.md
<ide> assert(!/\<img\s+.+\s+src\s*=\s*https:\/\/cdn\.freecodecamp\.org\/curriculum\/ca
<ide> <li>laser pointers</li>
<ide> <li>lasagna</li>
<ide> </ul>
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfb655eeacea3f48c6300b3.md
<ide> assert(
<ide> <li>lasagna</li>
<ide> </ul>
<ide> --fcc-editable-region--
<add>
<ide> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/lasagna.jpg" alt="A slice of lasagna on a plate.">
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5dfb6a35eacea3f48c6300b4.md
<ide> assert(
<ide> --fcc-editable-region--
<ide> <figure>
<ide> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/lasagna.jpg" alt="A slice of lasagna on a plate.">
<add>
<ide> </figure>
<ide> --fcc-editable-region--
<ide> </section>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d1.md
<ide> assert(
<ide> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/lasagna.jpg" alt="A slice of lasagna on a plate.">
<ide> <figcaption>Cats <em>love</em> lasagna.</figcaption>
<ide> </figure>
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d2.md
<ide> assert.deepStrictEqual(
<ide> </figure>
<ide> --fcc-editable-region--
<ide> <h3>Top 3 things cats hate:</h3>
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d3.md
<ide> assert($('main > section')[1].lastElementChild.nodeName === 'FIGURE');
<ide> <li>thunder</li>
<ide> <li>other cats</li>
<ide> </ol>
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d4.md
<ide> assert(
<ide> <figure>
<ide> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/cats.jpg" alt="Five cats looking around a field.">
<ide> --fcc-editable-region--
<add>
<ide> <figcaption>Cats hate other cats.</figcaption>
<add>
<ide> --fcc-editable-region--
<ide> </figure>
<ide> </section>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d5.md
<ide> assert(
<ide> </section>
<ide> --fcc-editable-region--
<ide> <section>
<add>
<ide> </section>
<ide> --fcc-editable-region--
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d6.md
<ide> assert($('form')[0].innerHTML.trim().length === 0);
<ide> <section>
<ide> --fcc-editable-region--
<ide> <h2>Cat Form</h2>
<add>
<ide> --fcc-editable-region--
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804d8.md
<ide> assert(
<ide> <h2>Cat Form</h2>
<ide> --fcc-editable-region--
<ide> <form action="https://freecatphotoapp.com/submit-cat-photo">
<add>
<ide> </form>
<ide> --fcc-editable-region--
<ide> </section>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804da.md
<ide> assert(collection.indexOf('INPUT') < collection.indexOf('BUTTON'));
<ide> <form action="https://freecatphotoapp.com/submit-cat-photo">
<ide> --fcc-editable-region--
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<add>
<ide> --fcc-editable-region--
<ide> </form>
<ide> </section>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804dc.md
<ide> assert(
<ide> <h2>Cat Form</h2>
<ide> <form action="https://freecatphotoapp.com/submit-cat-photo">
<ide> --fcc-editable-region--
<del>
<add>
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<ide> --fcc-editable-region--
<ide> <button type="submit">Submit</button>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804e1.md
<ide> assert(
<ide> <h2>Cat Form</h2>
<ide> <form action="https://freecatphotoapp.com/submit-cat-photo">
<ide> --fcc-editable-region--
<add>
<ide> <label><input id="indoor" type="radio" name="indoor-outdoor" value="indoor"> Indoor</label>
<ide> <label><input id="outdoor" type="radio" name="indoor-outdoor" value="outdoor"> Outdoor</label>
<add>
<ide> --fcc-editable-region--
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<ide> <button type="submit">Submit</button>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804e2.md
<ide> assert(
<ide> <fieldset>
<ide> --fcc-editable-region--
<ide> <legend>What's your cat's personality?</legend>
<add>
<ide> --fcc-editable-region--
<ide> </fieldset>
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804e7.md
<ide> assert(document.querySelector('main').nextElementSibling.nodeName === 'FOOTER');
<ide> </section>
<ide> --fcc-editable-region--
<ide> </main>
<add>
<ide> </body>
<del></html>
<ide> --fcc-editable-region--
<add></html>
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804e8.md
<ide> assert(extraSpacesRemoved.match(/No Copyright - freeCodeCamp\.org$/i));
<ide> </main>
<ide> --fcc-editable-region--
<ide> <footer>
<add>
<ide> </footer>
<ide> --fcc-editable-region--
<ide> </body>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804ea.md
<ide> dashedName: step-65
<ide>
<ide> Notice that everything you've added to the page so far is inside the `body` element. All page content elements that should be rendered to the page go inside the `body` element. However, other important information goes inside the `head` element.
<ide>
<del>Add a `head` element just above the `body` element.
<add>Add a `head` element above the `body` element.
<ide>
<ide> # --hints--
<ide>
<ide> assert(noSpaces.match(/\<\/head\>\<body\>/));
<ide> ## --seed-contents--
<ide>
<ide> ```html
<del><html>
<ide> --fcc-editable-region--
<add><html>
<add>
<ide> <body>
<add>--fcc-editable-region--
<ide> <main>
<ide> <h1>CatPhotoApp</h1>
<ide> <section>
<ide> assert(noSpaces.match(/\<\/head\>\<body\>/));
<ide> </p>
<ide> </footer>
<ide> </body>
<del>--fcc-editable-region--
<ide> </html>
<ide> ```
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804eb.md
<ide> assert(document.title && document.title.toLowerCase() === 'catphotoapp');
<ide> <html>
<ide> --fcc-editable-region--
<ide> <head>
<add>
<ide> </head>
<ide> --fcc-editable-region--
<ide> <body>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5ef9b03c81a63668521804ee.md
<ide> assert(noSpaces.match(/^\<\!DOCTYPEhtml\>\<html/));
<ide>
<ide> ```html
<ide> --fcc-editable-region--
<add>
<ide> <html lang="en">
<add>--fcc-editable-region--
<ide> <head>
<ide> <title>CatPhotoApp</title>
<ide> </head>
<del>--fcc-editable-region--
<ide> <body>
<ide> <main>
<ide> <h1>CatPhotoApp</h1>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5efada803cbd2bbdab94e332.md
<ide> assert(!/\<img\s+.+\s+src\s*=\s*https:\/\/cdn\.freecodecamp\.org\/curriculum\/ca
<ide> </ol>
<ide> --fcc-editable-region--
<ide> <figure>
<add>
<ide> </figure>
<ide> --fcc-editable-region--
<ide> </section>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5efae0543cbd2bbdab94e333.md
<ide> dashedName: step-30
<ide>
<ide> # --description--
<ide>
<del>To improve accessibility of the image you just added, add an `alt` attribute with the text:
<add>To improve accessibility of the image you added, add an `alt` attribute with the text:
<ide>
<ide> `Five cats looking around a field.`
<ide>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5efae16e3cbd2bbdab94e334.md
<ide> assert(
<ide> <li>thunder</li>
<ide> <li>other cats</li>
<ide> </ol>
<del> <figure>
<ide> --fcc-editable-region--
<add> <figure>
<ide> <img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/cats.jpg" alt="Five cats looking around a field.">
<del>--fcc-editable-region--
<add>
<ide> </figure>
<add>--fcc-editable-region--
<ide> </section>
<ide> </main>
<ide> </body>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f05a1d8e233dff4a68508d8.md
<ide> assert(code.match(/<\/label>\s*<label\s*>\s*<input [^>]+>\s*Outdoor/i));
<ide> <form action="https://freecatphotoapp.com/submit-cat-photo">
<ide> --fcc-editable-region--
<ide> <label><input id="indoor" type="radio"> Indoor</label>
<add>
<ide> --fcc-editable-region--
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<ide> <button type="submit">Submit</button>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f07be6ef7412fbad0c5626b.md
<ide> assert.isFalse(includesH1);
<ide> <html>
<ide> <body>
<ide> --fcc-editable-region--
<add>
<ide> <main>
<ide> <h1>CatPhotoApp</h1>
<ide> <h2>Cat Photos</h2>
<ide> <!-- TODO: Add link to cat photos -->
<ide> <p>Click here to view more <a target="_blank" href="https://freecatphotoapp.com">cat photos</a>.</p>
<ide> <a href="https://freecatphotoapp.com"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>
<ide> </main>
<add>
<ide> --fcc-editable-region--
<ide> </body>
<ide> </html>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f07c98cdb9413cbd4b16750.md
<ide> assert(foundElems.length === 2);
<ide> <p>Click here to view more <a target="_blank" href="https://freecatphotoapp.com">cat photos</a>.</p>
<ide> <a href="https://freecatphotoapp.com"><img src="https://cdn.freecodecamp.org/curriculum/cat-photo-app/relaxing-cat.jpg" alt="A cute orange cat lying on its back."></a>
<ide> </section>
<add>
<ide> --fcc-editable-region--
<ide> </main>
<ide> </body>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f07fb1579dc934717801375.md
<ide> assert($('main > section')[2].children.length === 0);
<ide> <figcaption>Cats <strong>hate</strong> other cats.</figcaption>
<ide> </figure>
<ide> </section>
<add>
<ide> --fcc-editable-region--
<ide> </main>
<ide> </body>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f0d48e7b435f13ab6550051.md
<ide> assert(extraSpacesRemoved.match(/Is your cat an indoor or outdoor cat\??$/i));
<ide> <form action="https://freecatphotoapp.com/submit-cat-photo">
<ide> --fcc-editable-region--
<ide> <fieldset>
<add>
<ide> <label><input id="indoor" type="radio" name="indoor-outdoor" value="indoor"> Indoor</label>
<ide> <label><input id="outdoor" type="radio" name="indoor-outdoor" value="outdoor"> Outdoor</label>
<ide> </fieldset>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f0d4ab1b435f13ab6550052.md
<ide> assert(fieldsetChildren[0].length > fieldsetChildren[1].length);
<ide> <label><input id="indoor" type="radio" name="indoor-outdoor" value="indoor"> Indoor</label>
<ide> <label><input id="outdoor" type="radio" name="indoor-outdoor" value="outdoor"> Outdoor</label>
<ide> </fieldset>
<add>
<add>--fcc-editable-region--
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<ide> <button type="submit">Submit</button>
<del>--fcc-editable-region--
<ide> </form>
<ide> </section>
<ide> </main>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/5f0d4d04b435f13ab6550053.md
<ide> assert(
<ide> </fieldset>
<ide> --fcc-editable-region--
<ide> <fieldset>
<add>
<ide> </fieldset>
<ide> --fcc-editable-region--
<ide> <input type="text" name="catphotourl" placeholder="cat photo URL" required>
<ide><path>curriculum/challenges/english/14-responsive-web-design-22/learn-html-by-building-a-cat-photo-app/62bb4009e3458a128ff57d5d.md
<ide> assert.notMatch(code, /<\/meta\s*>?/i);
<ide> <html lang="en">
<ide> --fcc-editable-region--
<ide> <head>
<add>
<ide> <title>CatPhotoApp</title>
<ide> </head>
<ide> --fcc-editable-region-- | 40 |
Text | Text | fix mistakes in the codebase overview | 16ac141f44583bd59f95f5b420a66bfcef01865e | <ide><path>docs/contributing/codebase-overview.md
<ide> warning(
<ide>
<ide> **The warning is shown when the `warning` condition is `false`.**
<ide>
<del>One way to think about it is that the condition should reflect the normal situtation rather than the exceptional one.
<add>One way to think about it is that the condition should reflect the normal situation rather than the exceptional one.
<ide>
<ide> It is a good idea to avoid spamming the console with duplicate warnings:
<ide>
<ide> The code for React core is located in [`src/isomorphic`](https://github.com/face
<ide>
<ide> >**Note:**
<ide> >
<del>>Until very recently, `react` npm package and `react.js` standalone build contained all React code (inlcuding React DOM) rather than just the core. This was done for backwards compatibility and historical reasons. Since React 15.4.0, the core is better separated in the build output.
<add>>Until very recently, `react` npm package and `react.js` standalone build contained all React code (including React DOM) rather than just the core. This was done for backwards compatibility and historical reasons. Since React 15.4.0, the core is better separated in the build output.
<ide> >
<ide> >There is also an additional standalone browser build called `react-with-addons.js` which we will consider separately further below.
<ide> | 1 |
Text | Text | improve download section of readme | cd40d7afac2554ec2d2c213cdab31f0ac6398736 | <ide><path>README.md
<ide> Binaries, installers, and source tarballs are available at
<ide> <https://nodejs.org/en/download/>.
<ide>
<ide> #### Current and LTS Releases
<del>**Current** and **LTS** releases are available at
<del><https://nodejs.org/download/release/>, listed under their version strings.
<add><https://nodejs.org/download/release/>
<add>
<ide> The [latest](https://nodejs.org/download/release/latest/) directory is an
<del>alias for the latest Current release. The latest LTS release from an LTS
<del>line is available in the form: latest-_codename_. For example:
<del><https://nodejs.org/download/release/latest-argon>.
<add>alias for the latest Current release. The latest-_codename_ directory is an
<add>alias for the latest release from an LTS line. For example,
<add><https://nodejs.org/download/release/latest-carbon> is the latest Carbon
<add>(Node.js version 8) release.
<ide>
<ide> #### Nightly Releases
<del>**Nightly** builds are available at
<del><https://nodejs.org/download/nightly/>, listed under their version
<del>string which includes their date (in UTC time) and the commit SHA at
<del>the HEAD of the release.
<add><https://nodejs.org/download/nightly/>
<add>
<add>Listed under their version string which includes their date (in UTC time) and
<add>the commit SHA at the HEAD of the release.
<ide>
<ide> #### API Documentation
<del>**API documentation** is available in each release and nightly
<del>directory under _docs_. <https://nodejs.org/api/> points to the API
<del>documentation of the latest stable version.
<add><https://nodejs.org/api/>
<add>
<add>Points to the API documentation of the latest Current release.
<add>Version specific documentation are avalible in each release and nightly
<add>directory under _docs_ or at <https://nodejs.org/download/docs/>.
<add>
<ide>
<ide> ### Verifying Binaries
<ide> | 1 |
Go | Go | add etw logging hook | 92bf0a50460b7be1b7e0617ba7bf142f8d9fb680 | <ide><path>cmd/dockerd/docker.go
<ide> package main
<ide> import (
<ide> "fmt"
<ide> "os"
<del> "runtime"
<ide>
<ide> "github.com/docker/docker/cli"
<ide> "github.com/docker/docker/daemon/config"
<ide> func main() {
<ide> // Set terminal emulation based on platform as required.
<ide> _, stdout, stderr := term.StdStreams()
<ide>
<del> // @jhowardmsft - maybe there is a historic reason why on non-Windows, stderr is used
<del> // here. However, on Windows it makes no sense and there is no need.
<del> if runtime.GOOS == "windows" {
<del> logrus.SetOutput(stdout)
<del> } else {
<del> logrus.SetOutput(stderr)
<del> }
<add> initLogging(stdout, stderr)
<ide>
<ide> onError := func(err error) {
<ide> fmt.Fprintf(stderr, "%s\n", err)
<ide><path>cmd/dockerd/docker_unix.go
<ide>
<ide> package main
<ide>
<add>import (
<add> "io"
<add>
<add> "github.com/sirupsen/logrus"
<add>)
<add>
<ide> func runDaemon(opts *daemonOptions) error {
<ide> daemonCli := NewDaemonCli()
<ide> return daemonCli.start(opts)
<ide> }
<add>
<add>func initLogging(_, stderr io.Writer) {
<add> logrus.SetOutput(stderr)
<add>}
<ide><path>cmd/dockerd/docker_windows.go
<ide> package main
<ide>
<ide> import (
<add> "io"
<ide> "path/filepath"
<ide>
<add> "github.com/Microsoft/go-winio/pkg/etwlogrus"
<ide> _ "github.com/docker/docker/autogen/winresources/dockerd"
<ide> "github.com/sirupsen/logrus"
<ide> )
<ide> func runDaemon(opts *daemonOptions) error {
<ide> notifyShutdown(err)
<ide> return err
<ide> }
<add>
<add>func initLogging(stdout, _ io.Writer) {
<add> // Maybe there is a historic reason why on non-Windows, stderr is used
<add> // for output. However, on Windows it makes no sense and there is no need.
<add> logrus.SetOutput(stdout)
<add>
<add> // Provider ID: {6996f090-c5de-5082-a81e-5841acc3a635}
<add> // Hook isn't closed explicitly, as it will exist until process exit.
<add> // GUID is generated based on name - see Microsoft/go-winio/tools/etw-provider-gen.
<add> if hook, err := etwlogrus.NewHook("Moby"); err == nil {
<add> logrus.AddHook(hook)
<add> }
<add> return
<add>} | 3 |
Ruby | Ruby | ignore gemfile.lock in the release task | 1576f47c23f6be58b9ceb527b265800be21f6593 | <ide><path>tasks/release.rb
<ide> task :push => FRAMEWORKS.map { |f| "#{f}:push" } + ['rails:push']
<ide>
<ide> task :ensure_clean_state do
<del> unless `git status -s | grep -v 'RAILS_VERSION\\|CHANGELOG'`.strip.empty?
<add> unless `git status -s | grep -v 'RAILS_VERSION\\|CHANGELOG\\|Gemfile.lock'`.strip.empty?
<ide> abort "[ABORTING] `git status` reports a dirty tree. Make sure all changes are committed"
<ide> end
<ide> | 1 |
PHP | PHP | fix api docblocks for behaviors | 0b4ba0b049b3b03c7eb8ae935854de963c570bf8 | <ide><path>lib/Cake/Model/Behavior/AclBehavior.php
<ide> class AclBehavior extends ModelBehavior {
<ide> /**
<ide> * Sets up the configuration for the model, and loads ACL models if they haven't been already
<ide> *
<del> * @param Model $model
<del> * @param array $config
<add> * @param Model $model Model using this behavior.
<add> * @param array $config Configuration options.
<ide> * @return void
<ide> */
<ide> public function setup(Model $model, $config = array()) {
<ide> public function setup(Model $model, $config = array()) {
<ide> /**
<ide> * Retrieves the Aro/Aco node for this model
<ide> *
<del> * @param Model $model
<add> * @param Model $model Model using this behavior.
<ide> * @param string|array|Model $ref Array with 'model' and 'foreign_key', model object, or string value
<ide> * @param string $type Only needed when Acl is set up as 'both', specify 'Aro' or 'Aco' to get the correct node
<ide> * @return array
<ide> public function node(Model $model, $ref = null, $type = null) {
<ide> /**
<ide> * Creates a new ARO/ACO node bound to this record
<ide> *
<del> * @param Model $model
<add> * @param Model $model Model using this behavior.
<ide> * @param boolean $created True if this is a new record
<ide> * @param array $options Options passed from Model::save().
<ide> * @return void
<ide> public function afterSave(Model $model, $created, $options = array()) {
<ide> /**
<ide> * Destroys the ARO/ACO node bound to the deleted record
<ide> *
<del> * @param Model $model
<add> * @param Model $model Model using this behavior.
<ide> * @return void
<ide> */
<ide> public function afterDelete(Model $model) {
<ide><path>lib/Cake/Model/Behavior/TranslateBehavior.php
<ide> public function beforeSave(Model $Model, $options = array()) {
<ide> * and to allow translations to be persisted even when validation
<ide> * is disabled.
<ide> *
<del> * @param Model $Model
<add> * @param Model $Model Model using this behavior.
<ide> * @return void
<ide> */
<ide> protected function _setRuntimeData(Model $Model) {
<ide> protected function _setRuntimeData(Model $Model) {
<ide> * Restores model data to the original data.
<ide> * This solves issues with saveAssociated and validate = first.
<ide> *
<del> * @param Model $model
<add> * @param Model $Model Model using this behavior.
<ide> * @return void
<ide> */
<ide> public function afterValidate(Model $Model) {
<ide> public function afterSave(Model $Model, $created, $options = array()) {
<ide> * Prepares the data to be saved for translated records.
<ide> * Add blank fields, and populates data for multi-locale saves.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param array $data The sparse data that was provided.
<ide> * @return array The fully populated data to save.
<ide> */
<ide> public function translateModel(Model $Model) {
<ide> * *Note* You should avoid binding translations that overlap existing model properties.
<ide> * This can cause un-expected and un-desirable behavior.
<ide> *
<del> * @param Model $Model instance of model
<add> * @param Model $Model using this behavior of model
<ide> * @param string|array $fields string with field or array(field1, field2=>AssocName, field3)
<ide> * @param boolean $reset Leave true to have the fields only modified for the next operation.
<ide> * if false the field will be added for all future queries.
<ide> public function bindTranslation(Model $Model, $fields, $reset = true) {
<ide> /**
<ide> * Update runtime setting for a given field.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param string $field The field to update.
<ide> * @return void
<ide> */
<ide> protected function _removeField(Model $Model, $field) {
<ide> * Unbind translation for fields, optionally unbinds hasMany association for
<ide> * fake field
<ide> *
<del> * @param Model $Model instance of model
<add> * @param Model $Model using this behavior of model
<ide> * @param string|array $fields string with field, or array(field1, field2=>AssocName, field3), or null for
<ide> * unbind all original translations
<ide> * @return boolean
<ide><path>lib/Cake/Model/Behavior/TreeBehavior.php
<ide> class TreeBehavior extends ModelBehavior {
<ide> /**
<ide> * Initiate Tree behavior
<ide> *
<del> * @param Model $Model instance of model
<add> * @param Model $Model using this behavior of model
<ide> * @param array $config array of configuration settings.
<ide> * @return void
<ide> */
<ide> public function setup(Model $Model, $config = array()) {
<ide> * Overridden to transparently manage setting the lft and rght fields if and only if the parent field is included in the
<ide> * parameters to be saved.
<ide> *
<del> * @param Model $Model Model instance.
<add> * @param Model $Model Model using this behavior.
<ide> * @param boolean $created indicates whether the node just saved was created or updated
<ide> * @param array $options Options passed from Model::save().
<ide> * @return boolean true on success, false on failure
<ide> public function beforeFind(Model $Model, $query) {
<ide> *
<ide> * This is used to delete child nodes in the afterDelete.
<ide> *
<del> * @param Model $Model Model instance
<del> * @param boolean $cascade
<add> * @param Model $Model Model using this behavior.
<add> * @param boolean $cascade If true records that depend on this record will also be deleted
<ide> * @return boolean
<ide> */
<ide> public function beforeDelete(Model $Model, $cascade = true) {
<ide> public function beforeDelete(Model $Model, $cascade = true) {
<ide> *
<ide> * Will delete the current node and all children using the deleteAll method and sync the table
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @return boolean true to continue, false to abort the delete
<ide> */
<ide> public function afterDelete(Model $Model) {
<ide> public function afterDelete(Model $Model) {
<ide> * parameters to be saved. For newly created nodes with NO parent the left and right field values are set directly by
<ide> * this method bypassing the setParent logic.
<ide> *
<del> * @since 1.2
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param array $options Options passed from Model::save().
<ide> * @return boolean true to continue, false to abort the save
<ide> * @see Model::save()
<ide> public function beforeSave(Model $Model, $options = array()) {
<ide> * If the direct parameter is set to true, only the direct children are counted (based upon the parent_id field)
<ide> * If false is passed for the id parameter, all top level nodes are counted, or all nodes are counted.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string|boolean $id The ID of the record to read or false to read all top level nodes
<ide> * @param boolean $direct whether to count direct, or all, children
<ide> * @return integer number of child nodes
<ide> public function childCount(Model $Model, $id = null, $direct = false) {
<ide> * If the direct parameter is set to true, only the direct children are returned (based upon the parent_id field)
<ide> * If false is passed for the id parameter, top level, or all (depending on direct parameter appropriate) are counted.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string $id The ID of the record to read
<ide> * @param boolean $direct whether to return only the direct, or all, children
<ide> * @param string|array $fields Either a single string of a field name, or an array of field names
<ide> public function children(Model $Model, $id = null, $direct = false, $fields = nu
<ide> /**
<ide> * A convenience method for returning a hierarchical array used for HTML select boxes
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param string|array $conditions SQL conditions as a string or as an array('field' =>'value',...)
<ide> * @param string $keyPath A string path to the key, i.e. "{n}.Post.id"
<ide> * @param string $valuePath A string path to the value, i.e. "{n}.Post.title"
<ide> public function generateTreeList(Model $Model, $conditions = null, $keyPath = nu
<ide> *
<ide> * reads the parent id and returns this node
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string $id The ID of the record to read
<del> * @param string|array $fields
<add> * @param string|array $fields Fields to get
<ide> * @param integer $recursive The number of levels deep to fetch associated records
<ide> * @return array|boolean Array of data for the parent node
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::getParentNode
<ide> public function getParentNode(Model $Model, $id = null, $fields = null, $recursi
<ide> /**
<ide> * Get the path to the given node
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string $id The ID of the record to read
<ide> * @param string|array $fields Either a single string of a field name, or an array of field names
<ide> * @param integer $recursive The number of levels deep to fetch associated records
<ide> public function getPath(Model $Model, $id = null, $fields = null, $recursive = n
<ide> *
<ide> * If the node is the last child, or is a top level node with no subsequent node this method will return false
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string $id The ID of the record to move
<ide> * @param integer|boolean $number how many places to move the node or true to move to last position
<ide> * @return boolean true on success, false on failure
<ide> public function moveDown(Model $Model, $id = null, $number = 1) {
<ide> *
<ide> * If the node is the first child, or is a top level node with no previous node this method will return false
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string $id The ID of the record to move
<ide> * @param integer|boolean $number how many places to move the node, or true to move to first position
<ide> * @return boolean true on success, false on failure
<ide> public function moveUp(Model $Model, $id = null, $number = 1) {
<ide> * 'parent' the values of the parent_id field will be used to populate the left and right fields. The missingParentAction
<ide> * parameter only applies to "parent" mode and determines what to do if the parent field contains an id that is not present.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param string $mode parent or tree
<ide> * @param string|integer $missingParentAction 'return' to do nothing and return, 'delete' to
<ide> * delete, or the id of the parent to set as the parent_id
<ide> public function recover(Model $Model, $mode = 'parent', $missingParentAction = n
<ide> *
<ide> * Recursive helper function used by recover
<ide> *
<del> * @param Model $Model
<del> * @param integer $counter
<del> * @param mixed $parentId
<add> * @param Model $Model Model instance.
<add> * @param integer $counter Counter
<add> * @param mixed $parentId Parent record Id
<ide> * @return integer $counter
<ide> */
<ide> protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = null) {
<ide> protected function _recoverByParentId(Model $Model, $counter = 1, $parentId = nu
<ide> * - 'order' Direction to order either DESC or ASC (defaults to ASC)
<ide> * - 'verify' Whether or not to verify the tree before reorder. defaults to true.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param array $options array of options to use in reordering.
<ide> * @return boolean true on success, false on failure
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::reorder
<ide> public function reorder(Model $Model, $options = array()) {
<ide> * If the parameter delete is false, the node will become a new top level node. Otherwise the node will be deleted
<ide> * after the children are reparented.
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @param integer|string $id The ID of the record to remove
<ide> * @param boolean $delete whether to delete the node after reparenting children (if any)
<ide> * @return boolean true on success, false on failure
<ide> public function removeFromTree(Model $Model, $id = null, $delete = false) {
<ide> *
<ide> * Returns true if the tree is valid otherwise an array of (type, incorrect left/right index, message)
<ide> *
<del> * @param Model $Model Model instance
<add> * @param Model $Model Model using this behavior
<ide> * @return mixed true if the tree is valid or empty, otherwise an array of (error type [index, node],
<ide> * [incorrect left/right index,node id], message)
<ide> * @link http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.html#TreeBehavior::verify
<ide> public function verify(Model $Model) {
<ide> * of recovering a corrupted table, or creating new nodes. Otherwise it should always be false. In reality this
<ide> * method could be private, since calling save with parent_id set also calls setParent
<ide> *
<del> * @param Model $Model Model instance
<del> * @param integer|string $parentId
<del> * @param boolean $created
<add> * @param Model $Model Model using this behavior
<add> * @param integer|string $parentId Parent record Id
<add> * @param boolean $created True if newly created record else false.
<ide> * @return boolean true on success, false on failure
<ide> */
<ide> protected function _setParent(Model $Model, $parentId = null, $created = false) {
<ide> protected function _setParent(Model $Model, $parentId = null, $created = false)
<ide> /**
<ide> * get the maximum index value in the table.
<ide> *
<del> * @param Model $Model
<del> * @param string $scope
<del> * @param string $right
<del> * @param integer $recursive
<del> * @param boolean $created
<add> * @param Model $Model Model Instance.
<add> * @param string $scope Scoping conditions.
<add> * @param string $right Right value
<add> * @param integer $recursive Recursive find value.
<add> * @param boolean $created Whether it's a new record.
<ide> * @return integer
<ide> */
<ide> protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $created = false) {
<ide> protected function _getMax(Model $Model, $scope, $right, $recursive = -1, $creat
<ide> /**
<ide> * get the minimum index value in the table.
<ide> *
<del> * @param Model $Model
<del> * @param string $scope
<del> * @param string $left
<del> * @param integer $recursive
<add> * @param Model $Model Model instance.
<add> * @param string $scope Scoping conditions.
<add> * @param string $left Left value.
<add> * @param integer $recursive Recurursive find value.
<ide> * @return integer
<ide> */
<ide> protected function _getMin(Model $Model, $scope, $left, $recursive = -1) {
<ide> protected function _getMin(Model $Model, $scope, $left, $recursive = -1) {
<ide> *
<ide> * Handles table sync operations, Taking account of the behavior scope.
<ide> *
<del> * @param Model $Model
<del> * @param integer $shift
<del> * @param string $dir
<del> * @param array $conditions
<del> * @param boolean $created
<del> * @param string $field
<add> * @param Model $Model Model instance.
<add> * @param integer $shift Shift by.
<add> * @param string $dir Direction.
<add> * @param array $conditions Conditions.
<add> * @param boolean $created Wheter it's a new record.
<add> * @param string $field Field type.
<ide> * @return void
<ide> */
<ide> protected function _sync(Model $Model, $shift, $dir = '+', $conditions = array(), $created = false, $field = 'both') { | 3 |
Javascript | Javascript | remove unnecessary `inject()` from tests | fd28edfc5097febbf2b01119ab013832eaa96fe5 | <ide><path>test/ngAnimate/ngAnimateSwapSpec.js
<ide> describe('ngAnimateSwap', function() {
<ide> }));
<ide>
<ide>
<del> it('should render a new container when the expression changes', inject(function() {
<add> it('should render a new container when the expression changes', function() {
<ide> element = $compile('<div><div ng-animate-swap="exp">{{ exp }}</div></div>')($rootScope);
<ide> $rootScope.$digest();
<ide>
<ide> describe('ngAnimateSwap', function() {
<ide> expect(third.textContent).toBe('super');
<ide> expect(third).not.toEqual(second);
<ide> expect(second.parentNode).toBeFalsy();
<del> }));
<add> });
<ide>
<del> it('should render a new container only when the expression property changes', inject(function() {
<add> it('should render a new container only when the expression property changes', function() {
<ide> element = $compile('<div><div ng-animate-swap="exp.prop">{{ exp.value }}</div></div>')($rootScope);
<ide> $rootScope.exp = {
<ide> prop: 'hello',
<ide> describe('ngAnimateSwap', function() {
<ide> var three = element.find('div')[0];
<ide> expect(three.textContent).toBe('planet');
<ide> expect(three).not.toBe(two);
<del> }));
<add> });
<ide>
<del> it('should watch the expression as a collection', inject(function() {
<add> it('should watch the expression as a collection', function() {
<ide> element = $compile('<div><div ng-animate-swap="exp">{{ exp.a }} {{ exp.b }} {{ exp.c }}</div></div>')($rootScope);
<ide> $rootScope.exp = {
<ide> a: 1,
<ide> describe('ngAnimateSwap', function() {
<ide> var four = element.find('div')[0];
<ide> expect(four.textContent.trim()).toBe('4');
<ide> expect(four).not.toEqual(three);
<del> }));
<add> });
<ide>
<ide> they('should consider $prop as a falsy value', [false, undefined, null], function(value) {
<del> inject(function() {
<del> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope);
<del> $rootScope.value = true;
<del> $rootScope.$digest();
<add> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope);
<add> $rootScope.value = true;
<add> $rootScope.$digest();
<ide>
<del> var one = element.find('div')[0];
<del> expect(one).toBeTruthy();
<add> var one = element.find('div')[0];
<add> expect(one).toBeTruthy();
<ide>
<del> $rootScope.value = value;
<del> $rootScope.$digest();
<add> $rootScope.value = value;
<add> $rootScope.$digest();
<ide>
<del> var two = element.find('div')[0];
<del> expect(two).toBeFalsy();
<del> });
<add> var two = element.find('div')[0];
<add> expect(two).toBeFalsy();
<ide> });
<ide>
<del> it('should consider "0" as a truthy value', inject(function() {
<add> it('should consider "0" as a truthy value', function() {
<ide> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope);
<ide> $rootScope.$digest();
<ide>
<ide> describe('ngAnimateSwap', function() {
<ide>
<ide> var two = element.find('div')[0];
<ide> expect(two).toBeTruthy();
<del> }));
<add> });
<ide>
<del> it('should create a new (non-isolate) scope for each inserted clone', inject(function() {
<add> it('should create a new (non-isolate) scope for each inserted clone', function() {
<ide> var parentScope = $rootScope.$new();
<ide> parentScope.foo = 'bar';
<ide>
<ide> describe('ngAnimateSwap', function() {
<ide> expect(scopeTwo.foo).toBe('bar');
<ide>
<ide> expect(scopeOne).not.toBe(scopeTwo);
<del> }));
<add> });
<ide>
<del> it('should destroy the previous scope when removing the element', inject(function() {
<add> it('should destroy the previous scope when removing the element', function() {
<ide> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope);
<ide>
<ide> $rootScope.$apply('value = 1');
<ide> describe('ngAnimateSwap', function() {
<ide> // Removing the old element (without inserting a new one).
<ide> $rootScope.$apply('value = null');
<ide> expect(scopeTwo.$$destroyed).toBe(true);
<del> }));
<add> });
<ide>
<del> it('should destroy the previous scope when swapping elements', inject(function() {
<add> it('should destroy the previous scope when swapping elements', function() {
<ide> element = $compile('<div><div ng-animate-swap="value">{{ value }}</div></div>')($rootScope);
<ide>
<ide> $rootScope.$apply('value = 1');
<ide> describe('ngAnimateSwap', function() {
<ide>
<ide> $rootScope.$apply('value = 2');
<ide> expect(scopeOne.$$destroyed).toBe(true);
<del> }));
<add> });
<ide>
<ide>
<ide> describe('animations', function() {
<del> it('should trigger a leave animation followed by an enter animation upon swap',
<del> inject(function() {
<del>
<add> it('should trigger a leave animation followed by an enter animation upon swap',function() {
<ide> element = $compile('<div><div ng-animate-swap="exp">{{ exp }}</div></div>')($rootScope);
<ide> $rootScope.exp = 1;
<ide> $rootScope.$digest();
<ide> describe('ngAnimateSwap', function() {
<ide> var forth = $animate.queue.shift();
<ide> expect(forth.event).toBe('leave');
<ide> expect($animate.queue.length).toBe(0);
<del> }));
<add> });
<ide> });
<ide> }); | 1 |
Javascript | Javascript | remove pipes from object literal flow types | 00cfb0f919207fcdc8fe8b6c3b7d76591447b91d | <ide><path>packages/react-native-codegen/src/CodegenSchema.js
<ide>
<ide> export type PlatformType = 'iOS' | 'android';
<ide>
<del>export type SchemaType = $ReadOnly<{|
<del> modules: $ReadOnly<{|
<add>export type SchemaType = $ReadOnly<{
<add> modules: $ReadOnly<{
<ide> [hasteModuleName: string]: ComponentSchema | NativeModuleSchema,
<del> |}>,
<del>|}>;
<add> }>,
<add>}>;
<ide>
<ide> /**
<ide> * Component Type Annotations
<ide> */
<del>export type DoubleTypeAnnotation = $ReadOnly<{|
<add>export type DoubleTypeAnnotation = $ReadOnly<{
<ide> type: 'DoubleTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type FloatTypeAnnotation = $ReadOnly<{|
<add>export type FloatTypeAnnotation = $ReadOnly<{
<ide> type: 'FloatTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type BooleanTypeAnnotation = $ReadOnly<{|
<add>export type BooleanTypeAnnotation = $ReadOnly<{
<ide> type: 'BooleanTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type Int32TypeAnnotation = $ReadOnly<{|
<add>export type Int32TypeAnnotation = $ReadOnly<{
<ide> type: 'Int32TypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type StringTypeAnnotation = $ReadOnly<{|
<add>export type StringTypeAnnotation = $ReadOnly<{
<ide> type: 'StringTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type StringEnumTypeAnnotation = $ReadOnly<{|
<add>export type StringEnumTypeAnnotation = $ReadOnly<{
<ide> type: 'StringEnumTypeAnnotation',
<ide> options: $ReadOnlyArray<string>,
<del>|}>;
<add>}>;
<ide>
<del>export type VoidTypeAnnotation = $ReadOnly<{|
<add>export type VoidTypeAnnotation = $ReadOnly<{
<ide> type: 'VoidTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>type ObjectTypeAnnotation<+T> = $ReadOnly<{|
<add>type ObjectTypeAnnotation<+T> = $ReadOnly<{
<ide> type: 'ObjectTypeAnnotation',
<ide> properties: $ReadOnlyArray<NamedShape<T>>,
<del>|}>;
<add>}>;
<ide>
<del>type FunctionTypeAnnotation<+P, +R> = $ReadOnly<{|
<add>type FunctionTypeAnnotation<+P, +R> = $ReadOnly<{
<ide> type: 'FunctionTypeAnnotation',
<ide> params: $ReadOnlyArray<NamedShape<P>>,
<ide> returnTypeAnnotation: R,
<del>|}>;
<add>}>;
<ide>
<ide> export type NamedShape<+T> = $ReadOnly<{
<ide> name: string,
<ide> optional: boolean,
<ide> typeAnnotation: T,
<ide> }>;
<ide>
<del>export type ComponentSchema = $ReadOnly<{|
<add>export type ComponentSchema = $ReadOnly<{
<ide> type: 'Component',
<del> components: $ReadOnly<{|
<add> components: $ReadOnly<{
<ide> [componentName: string]: ComponentShape,
<del> |}>,
<del>|}>;
<add> }>,
<add>}>;
<ide>
<del>export type ComponentShape = $ReadOnly<{|
<add>export type ComponentShape = $ReadOnly<{
<ide> ...OptionsShape,
<ide> extendsProps: $ReadOnlyArray<ExtendsPropsShape>,
<ide> events: $ReadOnlyArray<EventTypeShape>,
<ide> props: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<ide> commands: $ReadOnlyArray<NamedShape<CommandTypeAnnotation>>,
<del>|}>;
<add>}>;
<ide>
<del>export type OptionsShape = $ReadOnly<{|
<add>export type OptionsShape = $ReadOnly<{
<ide> interfaceOnly?: boolean,
<ide>
<ide> // Use for components with no current paper rename in progress
<ide> export type OptionsShape = $ReadOnly<{|
<ide> // Use for components currently being renamed in paper
<ide> // Will use new name if it is available and fallback to this name
<ide> paperComponentNameDeprecated?: string,
<del>|}>;
<add>}>;
<ide>
<del>export type ExtendsPropsShape = $ReadOnly<{|
<add>export type ExtendsPropsShape = $ReadOnly<{
<ide> type: 'ReactNativeBuiltInType',
<ide> knownTypeName: 'ReactNativeCoreViewProps',
<del>|}>;
<add>}>;
<ide>
<del>export type EventTypeShape = $ReadOnly<{|
<add>export type EventTypeShape = $ReadOnly<{
<ide> name: string,
<ide> bubblingType: 'direct' | 'bubble',
<ide> optional: boolean,
<ide> paperTopLevelNameDeprecated?: string,
<del> typeAnnotation: $ReadOnly<{|
<add> typeAnnotation: $ReadOnly<{
<ide> type: 'EventTypeAnnotation',
<ide> argument?: ObjectTypeAnnotation<EventTypeAnnotation>,
<del> |}>,
<del>|}>;
<add> }>,
<add>}>;
<ide>
<ide> export type EventTypeAnnotation =
<ide> | BooleanTypeAnnotation
<ide> export type EventTypeAnnotation =
<ide> | ObjectTypeAnnotation<EventTypeAnnotation>;
<ide>
<ide> export type PropTypeAnnotation =
<del> | $ReadOnly<{|
<add> | $ReadOnly<{
<ide> type: 'BooleanTypeAnnotation',
<ide> default: boolean | null,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> type: 'StringTypeAnnotation',
<ide> default: string | null,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> type: 'DoubleTypeAnnotation',
<ide> default: number,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> type: 'FloatTypeAnnotation',
<ide> default: number | null,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> type: 'Int32TypeAnnotation',
<ide> default: number,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> type: 'StringEnumTypeAnnotation',
<ide> default: string,
<ide> options: $ReadOnlyArray<string>,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> type: 'Int32EnumTypeAnnotation',
<ide> default: number,
<ide> options: $ReadOnlyArray<number>,
<del> |}>
<add> }>
<ide> | ReservedPropTypeAnnotation
<ide> | ObjectTypeAnnotation<PropTypeAnnotation>
<del> | $ReadOnly<{|
<add> | $ReadOnly<{
<ide> type: 'ArrayTypeAnnotation',
<ide> elementType:
<ide> | BooleanTypeAnnotation
<ide> | StringTypeAnnotation
<ide> | DoubleTypeAnnotation
<ide> | FloatTypeAnnotation
<ide> | Int32TypeAnnotation
<del> | $ReadOnly<{|
<add> | $ReadOnly<{
<ide> type: 'StringEnumTypeAnnotation',
<ide> default: string,
<ide> options: $ReadOnlyArray<string>,
<del> |}>
<add> }>
<ide> | ObjectTypeAnnotation<PropTypeAnnotation>
<ide> | ReservedPropTypeAnnotation
<del> | $ReadOnly<{|
<add> | $ReadOnly<{
<ide> type: 'ArrayTypeAnnotation',
<ide> elementType: ObjectTypeAnnotation<PropTypeAnnotation>,
<del> |}>,
<del> |}>;
<add> }>,
<add> }>;
<ide>
<del>type ReservedPropTypeAnnotation = $ReadOnly<{|
<add>type ReservedPropTypeAnnotation = $ReadOnly<{
<ide> type: 'ReservedPropTypeAnnotation',
<ide> name:
<ide> | 'ColorPrimitive'
<ide> | 'ImageSourcePrimitive'
<ide> | 'PointPrimitive'
<ide> | 'EdgeInsetsPrimitive',
<del>|}>;
<add>}>;
<ide>
<ide> export type CommandTypeAnnotation = FunctionTypeAnnotation<
<ide> CommandParamTypeAnnotation,
<ide> export type CommandParamTypeAnnotation =
<ide> | FloatTypeAnnotation
<ide> | StringTypeAnnotation;
<ide>
<del>export type ReservedTypeAnnotation = $ReadOnly<{|
<add>export type ReservedTypeAnnotation = $ReadOnly<{
<ide> type: 'ReservedTypeAnnotation',
<ide> name: 'RootTag', // Union with more custom types.
<del>|}>;
<add>}>;
<ide>
<ide> /**
<ide> * NativeModule Types
<ide> export type Nullable<+T: NativeModuleTypeAnnotation> =
<ide> | NullableTypeAnnotation<T>
<ide> | T;
<ide>
<del>export type NullableTypeAnnotation<
<del> +T: NativeModuleTypeAnnotation,
<del>> = $ReadOnly<{|
<add>export type NullableTypeAnnotation<+T: NativeModuleTypeAnnotation> = $ReadOnly<{
<ide> type: 'NullableTypeAnnotation',
<ide> typeAnnotation: T,
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleSchema = $ReadOnly<{|
<add>export type NativeModuleSchema = $ReadOnly<{
<ide> type: 'NativeModule',
<ide> aliases: NativeModuleAliasMap,
<ide> spec: NativeModuleSpec,
<ide> export type NativeModuleSchema = $ReadOnly<{|
<ide> // TODO: It's clearer to define `restrictedToPlatforms` instead, but
<ide> // `excludedPlatforms` is used here to be consistent with ComponentSchema.
<ide> excludedPlatforms?: $ReadOnlyArray<PlatformType>,
<del>|}>;
<add>}>;
<ide>
<del>type NativeModuleSpec = $ReadOnly<{|
<add>type NativeModuleSpec = $ReadOnly<{
<ide> properties: $ReadOnlyArray<NativeModulePropertyShape>,
<del>|}>;
<add>}>;
<ide>
<ide> export type NativeModulePropertyShape = NamedShape<
<ide> Nullable<NativeModuleFunctionTypeAnnotation>,
<ide> >;
<ide>
<del>export type NativeModuleAliasMap = $ReadOnly<{|
<add>export type NativeModuleAliasMap = $ReadOnly<{
<ide> [aliasName: string]: NativeModuleObjectTypeAnnotation,
<del>|}>;
<add>}>;
<ide>
<ide> export type NativeModuleFunctionTypeAnnotation = FunctionTypeAnnotation<
<ide> Nullable<NativeModuleParamTypeAnnotation>,
<ide> export type NativeModuleObjectTypeAnnotation = ObjectTypeAnnotation<
<ide>
<ide> export type NativeModuleArrayTypeAnnotation<
<ide> +T: Nullable<NativeModuleBaseTypeAnnotation>,
<del>> = $ReadOnly<{|
<add>> = $ReadOnly<{
<ide> type: 'ArrayTypeAnnotation',
<ide> /**
<ide> * TODO(T72031674): Migrate all our NativeModule specs to not use
<ide> * invalid Array ElementTypes. Then, make the elementType required.
<ide> */
<ide> elementType?: T,
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleStringTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleStringTypeAnnotation = $ReadOnly<{
<ide> type: 'StringTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleNumberTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleNumberTypeAnnotation = $ReadOnly<{
<ide> type: 'NumberTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleInt32TypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleInt32TypeAnnotation = $ReadOnly<{
<ide> type: 'Int32TypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleDoubleTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleDoubleTypeAnnotation = $ReadOnly<{
<ide> type: 'DoubleTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleFloatTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleFloatTypeAnnotation = $ReadOnly<{
<ide> type: 'FloatTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleBooleanTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleBooleanTypeAnnotation = $ReadOnly<{
<ide> type: 'BooleanTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleGenericObjectTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleGenericObjectTypeAnnotation = $ReadOnly<{
<ide> type: 'GenericObjectTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModuleTypeAliasTypeAnnotation = $ReadOnly<{|
<add>export type NativeModuleTypeAliasTypeAnnotation = $ReadOnly<{
<ide> type: 'TypeAliasTypeAnnotation',
<ide> name: string,
<del>|}>;
<add>}>;
<ide>
<del>export type NativeModulePromiseTypeAnnotation = $ReadOnly<{|
<add>export type NativeModulePromiseTypeAnnotation = $ReadOnly<{
<ide> type: 'PromiseTypeAnnotation',
<del>|}>;
<add>}>;
<ide>
<ide> export type NativeModuleBaseTypeAnnotation =
<ide> | NativeModuleStringTypeAnnotation
<ide><path>packages/react-native-codegen/src/generators/RNCodegen.js
<ide> const schemaValidator = require('../SchemaValidator.js');
<ide>
<ide> import type {SchemaType} from '../CodegenSchema';
<ide>
<del>type Options = $ReadOnly<{|
<add>type Options = $ReadOnly<{
<ide> libraryName: string,
<ide> schema: SchemaType,
<ide> outputDirectory: string,
<ide> moduleSpecName: string,
<ide> packageName?: string, // Some platforms have a notion of package, which should be configurable.
<del>|}>;
<add>}>;
<ide>
<ide> type Generators =
<ide> | 'descriptors'
<ide> type Generators =
<ide> | 'modulesCxx'
<ide> | 'modulesIOS';
<ide>
<del>type Config = $ReadOnly<{|
<add>type Config = $ReadOnly<{
<ide> generators: Array<Generators>,
<ide> test?: boolean,
<del>|}>;
<add>}>;
<ide>
<ide> const GENERATORS = {
<ide> descriptors: [generateComponentDescriptorH.generate],
<ide><path>packages/react-native-codegen/src/generators/components/GenerateTests.js
<ide> const {getImports, toSafeCppString} = require('./CppHelpers');
<ide> type FilesOutput = Map<string, string>;
<ide> type PropValueType = string | number | boolean;
<ide>
<del>type TestCase = $ReadOnly<{|
<add>type TestCase = $ReadOnly<{
<ide> propName: string,
<ide> propValue: ?PropValueType,
<ide> testName?: string,
<ide> raw?: boolean,
<del>|}>;
<add>}>;
<ide>
<ide> const fileTemplate = `
<ide> /**
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleCpp.js
<ide> const ModuleTemplate = ({
<ide> hostFunctions,
<ide> moduleName,
<ide> methods,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> hostFunctions: $ReadOnlyArray<string>,
<ide> moduleName: string,
<del> methods: $ReadOnlyArray<
<del> $ReadOnly<{|methodName: string, paramCount: number|}>,
<del> >,
<del>|}>) => {
<add> methods: $ReadOnlyArray<$ReadOnly<{methodName: string, paramCount: number}>>,
<add>}>) => {
<ide> return `${hostFunctions.join('\n')}
<ide>
<ide> ${hasteModuleName}CxxSpecJSI::${hasteModuleName}CxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker)
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleH.js
<ide> type FilesOutput = Map<string, string>;
<ide> const ModuleClassDeclarationTemplate = ({
<ide> hasteModuleName,
<ide> moduleProperties,
<del>}: $ReadOnly<{|hasteModuleName: string, moduleProperties: string|}>) => {
<add>}: $ReadOnly<{hasteModuleName: string, moduleProperties: string}>) => {
<ide> return `class JSI_EXPORT ${hasteModuleName}CxxSpecJSI : public TurboModule {
<ide> protected:
<ide> ${hasteModuleName}CxxSpecJSI(std::shared_ptr<CallInvoker> jsInvoker);
<ide> ${moduleProperties}
<ide>
<ide> const FileTemplate = ({
<ide> modules,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> modules: string,
<del>|}>) => {
<add>}>) => {
<ide> return `/**
<ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates.
<ide> *
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleJavaSpec.js
<ide> const {unwrapNullable} = require('../../parsers/flow/modules/utils');
<ide> type FilesOutput = Map<string, string>;
<ide>
<ide> function FileTemplate(
<del> config: $ReadOnly<{|
<add> config: $ReadOnly<{
<ide> packageName: string,
<ide> className: string,
<ide> methods: string,
<ide> imports: string,
<del> |}>,
<add> }>,
<ide> ): string {
<ide> const {packageName, className, methods, imports} = config;
<ide> return `
<ide> ${methods}
<ide> }
<ide>
<ide> function MethodTemplate(
<del> config: $ReadOnly<{|
<add> config: $ReadOnly<{
<ide> abstract: boolean,
<ide> methodBody: ?string,
<ide> methodJavaAnnotation: string,
<ide> methodName: string,
<ide> translatedReturnType: string,
<ide> traversedArgs: Array<string>,
<del> |}>,
<add> }>,
<ide> ): string {
<ide> const {
<ide> abstract,
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleJniCpp.js
<ide> const HostFunctionTemplate = ({
<ide> propertyName,
<ide> jniSignature,
<ide> jsReturnType,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> propertyName: string,
<ide> jniSignature: string,
<ide> jsReturnType: JSReturnType,
<del>|}>) => {
<add>}>) => {
<ide> return `static facebook::jsi::Value __hostFunction_${hasteModuleName}SpecJSI_${propertyName}(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
<ide> return static_cast<JavaTurboModule &>(turboModule).invokeJavaMethod(rt, ${jsReturnType}, "${propertyName}", "${jniSignature}", args, count);
<ide> }`;
<ide> const HostFunctionTemplate = ({
<ide> const ModuleClassConstructorTemplate = ({
<ide> hasteModuleName,
<ide> methods,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<del> methods: $ReadOnlyArray<{|
<add> methods: $ReadOnlyArray<{
<ide> propertyName: string,
<ide> argCount: number,
<del> |}>,
<del>|}>) => {
<add> }>,
<add>}>) => {
<ide> return `
<ide> ${hasteModuleName}SpecJSI::${hasteModuleName}SpecJSI(const JavaTurboModule::InitParams ¶ms)
<ide> : JavaTurboModule(params) {
<ide> ${methods
<ide> const ModuleLookupTemplate = ({
<ide> moduleName,
<ide> hasteModuleName,
<del>}: $ReadOnly<{|moduleName: string, hasteModuleName: string|}>) => {
<add>}: $ReadOnly<{moduleName: string, hasteModuleName: string}>) => {
<ide> return ` if (moduleName == "${moduleName}") {
<ide> return std::make_shared<${hasteModuleName}SpecJSI>(params);
<ide> }`;
<ide> const FileTemplate = ({
<ide> include,
<ide> modules,
<ide> moduleLookups,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> libraryName: string,
<ide> include: string,
<ide> modules: string,
<ide> moduleLookups: $ReadOnlyArray<
<del> $ReadOnly<{|
<add> $ReadOnly<{
<ide> hasteModuleName: string,
<ide> moduleName: string,
<del> |}>,
<add> }>,
<ide> >,
<del>|}>) => {
<add>}>) => {
<ide> return `
<ide> /**
<ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates.
<ide> module.exports = {
<ide> }
<ide> return 0;
<ide> })
<del> .flatMap<{|moduleName: string, hasteModuleName: string|}>(
<add> .flatMap<{moduleName: string, hasteModuleName: string}>(
<ide> (hasteModuleName: string) => {
<ide> const {moduleNames} = nativeModules[hasteModuleName];
<ide> return moduleNames.map(moduleName => ({
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleJniH.js
<ide> const {getModules} = require('./Utils');
<ide>
<ide> const ModuleClassDeclarationTemplate = ({
<ide> hasteModuleName,
<del>}: $ReadOnly<{|hasteModuleName: string|}>) => {
<add>}: $ReadOnly<{hasteModuleName: string}>) => {
<ide> return `/**
<ide> * JNI C++ class for module '${hasteModuleName}'
<ide> */
<ide> public:
<ide> const HeaderFileTemplate = ({
<ide> modules,
<ide> libraryName,
<del>}: $ReadOnly<{|modules: string, libraryName: string|}>) => {
<add>}: $ReadOnly<{modules: string, libraryName: string}>) => {
<ide> return `
<ide> /**
<ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates.
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/StructCollector.js
<ide> const {
<ide>
<ide> type StructContext = 'CONSTANTS' | 'REGULAR';
<ide>
<del>export type RegularStruct = $ReadOnly<{|
<add>export type RegularStruct = $ReadOnly<{
<ide> context: 'REGULAR',
<ide> name: string,
<ide> properties: $ReadOnlyArray<StructProperty>,
<del>|}>;
<add>}>;
<ide>
<del>export type ConstantsStruct = $ReadOnly<{|
<add>export type ConstantsStruct = $ReadOnly<{
<ide> context: 'CONSTANTS',
<ide> name: string,
<ide> properties: $ReadOnlyArray<StructProperty>,
<del>|}>;
<add>}>;
<ide>
<ide> export type Struct = RegularStruct | ConstantsStruct;
<ide>
<del>export type StructProperty = $ReadOnly<{|
<add>export type StructProperty = $ReadOnly<{
<ide> name: string,
<ide> optional: boolean,
<ide> typeAnnotation: Nullable<StructTypeAnnotation>,
<del>|}>;
<add>}>;
<ide>
<ide> export type StructTypeAnnotation =
<ide> | NativeModuleStringTypeAnnotation
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js
<ide> const StructTemplate = ({
<ide> hasteModuleName,
<ide> structName,
<ide> builderInputProps,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> structName: string,
<ide> builderInputProps: string,
<del>|}>) => `namespace JS {
<add>}>) => `namespace JS {
<ide> namespace ${hasteModuleName} {
<ide> struct ${structName} {
<ide>
<ide> const MethodTemplate = ({
<ide> hasteModuleName,
<ide> structName,
<ide> properties,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> structName: string,
<ide> properties: string,
<del>|}>) => `inline JS::${hasteModuleName}::${structName}::Builder::Builder(const Input i) : _factory(^{
<add>}>) => `inline JS::${hasteModuleName}::${structName}::Builder::Builder(const Input i) : _factory(^{
<ide> NSMutableDictionary *d = [NSMutableDictionary new];
<ide> ${properties}
<ide> return d;
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeRegularStruct.js
<ide> const StructTemplate = ({
<ide> hasteModuleName,
<ide> structName,
<ide> structProperties,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> structName: string,
<ide> structProperties: string,
<del>|}>) => `namespace JS {
<add>}>) => `namespace JS {
<ide> namespace ${hasteModuleName} {
<ide> struct ${structName} {
<ide> ${structProperties}
<ide> const MethodTemplate = ({
<ide> hasteModuleName,
<ide> structName,
<ide> propertyName,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> returnType: string,
<ide> returnValue: string,
<ide> hasteModuleName: string,
<ide> structName: string,
<ide> propertyName: string,
<del>|}>) => `inline ${returnType}JS::${hasteModuleName}::${structName}::${propertyName}() const
<add>}>) => `inline ${returnType}JS::${hasteModuleName}::${structName}::${propertyName}() const
<ide> {
<ide> id const p = _v[@"${propertyName}"];
<ide> return ${returnValue};
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeStruct.js
<ide> import type {Struct} from '../StructCollector';
<ide> const {serializeConstantsStruct} = require('./serializeConstantsStruct');
<ide> const {serializeRegularStruct} = require('./serializeRegularStruct');
<ide>
<del>export type StructSerilizationOutput = $ReadOnly<{|
<add>export type StructSerilizationOutput = $ReadOnly<{
<ide> methods: string,
<ide> declaration: string,
<del>|}>;
<add>}>;
<ide>
<ide> function serializeStruct(
<ide> hasteModuleName: string,
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/index.js
<ide> const ModuleDeclarationTemplate = ({
<ide> hasteModuleName,
<ide> structDeclarations,
<ide> protocolMethods,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> structDeclarations: string,
<ide> protocolMethods: string,
<del>|}>) => `${structDeclarations}
<add>}>) => `${structDeclarations}
<ide> @protocol ${hasteModuleName}Spec <RCTBridgeModule, RCTTurboModule>
<ide>
<ide> ${protocolMethods}
<ide> namespace facebook {
<ide> const HeaderFileTemplate = ({
<ide> moduleDeclarations,
<ide> structInlineMethods,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> moduleDeclarations: string,
<ide> structInlineMethods: string,
<del>|}>) => `/**
<add>}>) => `/**
<ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates.
<ide> *
<ide> * This source code is licensed under the MIT license found in the
<ide> ${structInlineMethods}
<ide> const SourceFileTemplate = ({
<ide> headerFileName,
<ide> moduleImplementations,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> headerFileName: string,
<ide> moduleImplementations: string,
<del>|}>) => `/**
<add>}>) => `/**
<ide> * ${'C'}opyright (c) Facebook, Inc. and its affiliates.
<ide> *
<ide> * This source code is licensed under the MIT license found in the
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/serializeMethod.js
<ide> const ProtocolMethodTemplate = ({
<ide> returnObjCType,
<ide> methodName,
<ide> params,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> returnObjCType: string,
<ide> methodName: string,
<ide> params: string,
<del>|}>) => `- (${returnObjCType})${methodName}${params};`;
<add>}>) => `- (${returnObjCType})${methodName}${params};`;
<ide>
<del>export type StructParameterRecord = $ReadOnly<{|
<add>export type StructParameterRecord = $ReadOnly<{
<ide> paramIndex: number,
<ide> structName: string,
<del>|}>;
<add>}>;
<ide>
<ide> type ReturnJSType =
<ide> | 'VoidKind'
<ide> type ReturnJSType =
<ide> | 'NumberKind'
<ide> | 'StringKind';
<ide>
<del>export type MethodSerializationOutput = $ReadOnly<{|
<add>export type MethodSerializationOutput = $ReadOnly<{
<ide> methodName: string,
<ide> protocolMethod: string,
<ide> selector: string,
<ide> structParamRecords: $ReadOnlyArray<StructParameterRecord>,
<ide> returnJSType: ReturnJSType,
<ide> argCount: number,
<del>|}>;
<add>}>;
<ide>
<ide> function serializeMethod(
<ide> hasteModuleName: string,
<ide> function serializeMethod(
<ide> );
<ide> }
<ide>
<del> const methodParams: Array<{|paramName: string, objCType: string|}> = [];
<add> const methodParams: Array<{paramName: string, objCType: string}> = [];
<ide> const structParamRecords: Array<StructParameterRecord> = [];
<ide>
<ide> params.forEach((param, index) => {
<ide> function getParamObjCType(
<ide> structName: string,
<ide> structCollector: StructCollector,
<ide> resolveAlias: AliasResolver,
<del>): $ReadOnly<{|objCType: string, isStruct: boolean|}> {
<add>): $ReadOnly<{objCType: string, isStruct: boolean}> {
<ide> const {name: paramName, typeAnnotation: nullableTypeAnnotation} = param;
<ide> const [typeAnnotation, nullable] = unwrapNullable(nullableTypeAnnotation);
<ide> const notRequired = param.optional || nullable;
<ide> function getParamObjCType(
<ide> *
<ide> * For example:
<ide> * Array<number> => NSArray<NSNumber *>
<del> * type Animal = {||};
<add> * type Animal = {};
<ide> * Array<Animal> => NSArray<JS::NativeSampleTurboModule::Animal *>, etc.
<ide> */
<ide> return notStruct(wrapIntoNullableIfNeeded('NSArray *'));
<ide> function serializeConstantsProtocolMethods(
<ide> const {returnTypeAnnotation} = propertyTypeAnnotation;
<ide> if (returnTypeAnnotation.type !== 'ObjectTypeAnnotation') {
<ide> throw new Error(
<del> `${hasteModuleName}.getConstants() may only return an object literal: {|...|}.`,
<add> `${hasteModuleName}.getConstants() may only return an object literal: {...}.`,
<ide> );
<ide> }
<ide>
<ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/source/serializeModule.js
<ide> const ModuleTemplate = ({
<ide> hasteModuleName,
<ide> structs,
<ide> methodSerializationOutputs,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> structs: $ReadOnlyArray<Struct>,
<ide> methodSerializationOutputs: $ReadOnlyArray<MethodSerializationOutput>,
<del>|}>) => `${structs
<add>}>) => `${structs
<ide> .map(struct =>
<ide> RCTCxxConvertCategoryTemplate({hasteModuleName, structName: struct.name}),
<ide> )
<ide> namespace facebook {
<ide> const RCTCxxConvertCategoryTemplate = ({
<ide> hasteModuleName,
<ide> structName,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> structName: string,
<del>|}>) => `@implementation RCTCxxConvert (${hasteModuleName}_${structName})
<add>}>) => `@implementation RCTCxxConvert (${hasteModuleName}_${structName})
<ide> + (RCTManagedPointer *)JS_${hasteModuleName}_${structName}:(id)json
<ide> {
<ide> return facebook::react::managedPointer<JS::${hasteModuleName}::${structName}>(json);
<ide> const InlineHostFunctionTemplate = ({
<ide> methodName,
<ide> returnJSType,
<ide> selector,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> methodName: string,
<ide> returnJSType: string,
<ide> selector: string,
<del>|}>) => `
<add>}>) => `
<ide> static facebook::jsi::Value __hostFunction_${hasteModuleName}SpecJSI_${methodName}(facebook::jsi::Runtime& rt, TurboModule &turboModule, const facebook::jsi::Value* args, size_t count) {
<ide> return static_cast<ObjCTurboModule&>(turboModule).invokeObjCMethod(rt, ${returnJSType}, "${methodName}", ${selector}, args, count);
<ide> }`;
<ide> const MethodMapEntryTemplate = ({
<ide> methodName,
<ide> structParamRecords,
<ide> argCount,
<del>}: $ReadOnly<{|
<add>}: $ReadOnly<{
<ide> hasteModuleName: string,
<ide> methodName: string,
<ide> structParamRecords: $ReadOnlyArray<StructParameterRecord>,
<ide> argCount: number,
<del>|}>) => `
<add>}>) => `
<ide> methodMap_["${methodName}"] = MethodMetadata {${argCount}, __hostFunction_${hasteModuleName}SpecJSI_${methodName}};
<ide> ${structParamRecords
<ide> .map(({paramIndex, structName}) => {
<ide><path>packages/react-native-codegen/src/generators/modules/Utils.js
<ide> function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver {
<ide>
<ide> function getModules(
<ide> schema: SchemaType,
<del>): $ReadOnly<{|[hasteModuleName: string]: NativeModuleSchema|}> {
<del> return Object.keys(schema.modules).reduce<{|[string]: NativeModuleSchema|}>(
<add>): $ReadOnly<{[hasteModuleName: string]: NativeModuleSchema}> {
<add> return Object.keys(schema.modules).reduce<{[string]: NativeModuleSchema}>(
<ide> (modules, hasteModuleName: string) => {
<ide> const module = schema.modules[hasteModuleName];
<ide> if (module == null || module.type === 'Component') {
<ide><path>packages/react-native-codegen/src/parsers/flow/components/options.js
<ide> import type {OptionsShape} from '../../../CodegenSchema.js';
<ide> // $FlowFixMe there's no flowtype for ASTs
<ide> type OptionsAST = Object;
<ide>
<del>export type CommandOptions = $ReadOnly<{|
<add>export type CommandOptions = $ReadOnly<{
<ide> supportedCommands: $ReadOnlyArray<string>,
<del>|}>;
<add>}>;
<ide>
<ide> function getCommandOptions(
<ide> commandOptionsExpression: OptionsAST,
<ide><path>packages/react-native-codegen/src/parsers/flow/components/schema.js
<ide> import type {
<ide> OptionsShape,
<ide> } from '../../../CodegenSchema.js';
<ide>
<del>export type ComponentSchemaBuilderConfig = $ReadOnly<{|
<add>export type ComponentSchemaBuilderConfig = $ReadOnly<{
<ide> filename: string,
<ide> componentName: string,
<ide> extendsProps: $ReadOnlyArray<ExtendsPropsShape>,
<ide> events: $ReadOnlyArray<EventTypeShape>,
<ide> props: $ReadOnlyArray<NamedShape<PropTypeAnnotation>>,
<ide> commands: $ReadOnlyArray<NamedShape<CommandTypeAnnotation>>,
<ide> options?: ?OptionsShape,
<del>|}>;
<add>}>;
<ide>
<ide> function wrapComponentSchema({
<ide> filename,
<ide><path>packages/react-native-codegen/src/parsers/flow/modules/__tests__/module-parser-e2e-test.js
<ide> const RESERVED_FUNCTION_VALUE_TYPE_NAME: $ReadOnlyArray<'RootTag'> = [
<ide> const MODULE_NAME = 'NativeFoo';
<ide>
<ide> const TYPE_ALIAS_DECLARATIONS = `
<del>type Animal = {|
<add>type Animal = {
<ide> name: string,
<del>|};
<add>};
<ide>
<ide> type AnimalPointer = Animal;
<ide> `;
<ide> describe('Flow Module Parser', () => {
<ide> expectAnimalTypeAliasToExist(module);
<ide> });
<ide>
<del> it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<{|foo: ?string|}>'`, () => {
<add> it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter of type 'Array<{foo: ?string}>'`, () => {
<ide> const [elementType] = parseParamArrayElementType(
<ide> 'arg',
<del> '{|foo: ?string|}',
<add> '{foo: ?string}',
<ide> );
<ide> expect(elementType).not.toBe(null);
<ide>
<ide> describe('Flow Module Parser', () => {
<ide> import type {TurboModule} from 'RCTExport';
<ide> import * as TurboModuleRegistry from 'TurboModuleRegistry';
<ide>
<del> type Animal = ?{|
<add> type Animal = ?{
<ide> name: string,
<del> |};
<add> };
<ide>
<ide> type AnimalPointer = Animal;
<ide>
<ide> describe('Flow Module Parser', () => {
<ide> ] {
<ide> const [paramTypeAnnotation, module] = parseParamType(
<ide> 'arg',
<del> `{|${annotateProp(propName, propType)}|}`,
<add> `{${annotateProp(propName, propType)}}`,
<ide> );
<ide>
<ide> expect(paramTypeAnnotation.type).toBe('ObjectTypeAnnotation');
<ide> describe('Flow Module Parser', () => {
<ide> expectAnimalTypeAliasToExist(module);
<ide> });
<ide>
<del> it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of 'Array<{|foo: ?string|}>'`, () => {
<add> it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of 'Array<{foo: ?string}>'`, () => {
<ide> const [elementType] = parseArrayElementType(
<ide> 'prop',
<del> '{|foo: ?string|}',
<add> '{foo: ?string}',
<ide> );
<ide>
<ide> expect(elementType.type).toBe('ObjectTypeAnnotation');
<ide> describe('Flow Module Parser', () => {
<ide> });
<ide> });
<ide>
<del> it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type '{|foo: ?string|}'`, () => {
<add> it(`should parse methods that have ${PARAM_TYPE_DESCRIPTION} parameter type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type '{foo: ?string}'`, () => {
<ide> const [property] = parseParamTypeObjectLiteralProp(
<ide> 'prop',
<del> '{|foo: ?string|}',
<add> '{foo: ?string}',
<ide> );
<ide>
<ide> expect(property.typeAnnotation.type).toBe(
<ide> describe('Flow Module Parser', () => {
<ide> describe(
<ide> IS_RETURN_TYPE_NULLABLE ? 'Nullable Returns' : 'Non-Nullable Returns',
<ide> () => {
<del> ['Promise<void>', 'Promise<{||}>', 'Promise<*>'].forEach(
<add> ['Promise<void>', 'Promise<{}>', 'Promise<*>'].forEach(
<ide> promiseFlowType => {
<ide> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type '${promiseFlowType}'`, () => {
<ide> const [returnTypeAnnotation] = parseReturnType(promiseFlowType);
<ide> describe('Flow Module Parser', () => {
<ide> expectAnimalTypeAliasToExist(module);
<ide> });
<ide>
<del> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<{|foo: ?string|}>'`, () => {
<add> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return of type 'Array<{foo: ?string}>'`, () => {
<ide> const [elementType] = parseArrayElementReturnType(
<del> '{|foo: ?string|}',
<add> '{foo: ?string}',
<ide> );
<ide> expect(elementType.type).toBe('ObjectTypeAnnotation');
<ide> invariant(elementType.type === 'ObjectTypeAnnotation', '');
<ide> describe('Flow Module Parser', () => {
<ide> // TODO: Inexact vs exact object literals?
<ide>
<ide> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an empty object literal`, () => {
<del> const [returnTypeAnnotation] = parseReturnType('{||}');
<add> const [returnTypeAnnotation] = parseReturnType('{}');
<ide> expect(returnTypeAnnotation.type).toBe('ObjectTypeAnnotation');
<ide> invariant(
<ide> returnTypeAnnotation.type === 'ObjectTypeAnnotation',
<ide> describe('Flow Module Parser', () => {
<ide> NativeModuleSchema,
<ide> ] {
<ide> const [returnTypeAnnotation, module] = parseReturnType(
<del> `{|${annotateProp(propName, propType)}|}`,
<add> `{${annotateProp(propName, propType)}}`,
<ide> );
<ide> expect(returnTypeAnnotation.type).toBe('ObjectTypeAnnotation');
<ide> invariant(
<ide> describe('Flow Module Parser', () => {
<ide> expectAnimalTypeAliasToExist(module);
<ide> });
<ide>
<del> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<{|foo: ?string|}>'`, () => {
<add> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of type 'Array<{foo: ?string}>'`, () => {
<ide> const [elementType] = parseArrayElementType(
<ide> 'prop',
<del> '{|foo: ?string|}',
<add> '{foo: ?string}',
<ide> );
<ide> expect(elementType.type).toBe('ObjectTypeAnnotation');
<ide> invariant(
<ide> describe('Flow Module Parser', () => {
<ide> });
<ide> });
<ide>
<del> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of '{|foo: ?string|}'`, () => {
<add> it(`should parse methods that have ${RETURN_TYPE_DESCRIPTION} return type of an object literal with ${PROP_TYPE_DESCRIPTION} prop of '{foo: ?string}'`, () => {
<ide> const [property] = parseObjectLiteralReturnTypeProp(
<ide> 'prop',
<del> '{|foo: ?string|}',
<add> '{foo: ?string}',
<ide> );
<ide>
<ide> expect(property.typeAnnotation.type).toBe(
<ide><path>packages/react-native-codegen/src/parsers/flow/modules/index.js
<ide> function translateTypeAnnotation(
<ide> *
<ide> * Consider this case:
<ide> *
<del> * type Animal = ?{|
<add> * type Animal = ?{
<ide> * name: string,
<del> * |};
<add> * };
<ide> *
<ide> * type B = Animal
<ide> *
<ide> * export interface Spec extends TurboModule {
<ide> * +greet: (animal: B) => void;
<ide> * }
<ide> *
<del> * In this case, we follow B to Animal, and then Animal to ?{|name: string|}.
<add> * In this case, we follow B to Animal, and then Animal to ?{name: string}.
<ide> *
<ide> * We:
<ide> * 1. Replace `+greet: (animal: B) => void;` with `+greet: (animal: ?Animal) => void;`,
<del> * 2. Pretend that Animal = {|name: string|}.
<add> * 2. Pretend that Animal = {name: string}.
<ide> *
<ide> * Why do we do this?
<ide> * 1. In ObjC, we need to generate a struct called Animal, not B.
<ide> function buildModuleSchema(
<ide> const declaration = types[moduleInterfaceName];
<ide> return (declaration.body.properties: $ReadOnlyArray<$FlowFixMe>)
<ide> .filter(property => property.type === 'ObjectTypeProperty')
<del> .map<?{|
<add> .map<?{
<ide> aliasMap: NativeModuleAliasMap,
<ide> propertyShape: NativeModulePropertyShape,
<del> |}>(property => {
<add> }>(property => {
<ide> const aliasMap: {...NativeModuleAliasMap} = {};
<ide>
<ide> return guard(() => ({
<ide><path>packages/react-native-codegen/src/parsers/flow/utils.js
<ide> const {ParserError} = require('./errors');
<ide> *
<ide> * TODO(T71778680): Flow type AST Nodes
<ide> */
<del>export type TypeDeclarationMap = {|[declarationName: string]: $FlowFixMe|};
<add>export type TypeDeclarationMap = {[declarationName: string]: $FlowFixMe};
<ide>
<ide> function getTypes(ast: $FlowFixMe): TypeDeclarationMap {
<ide> return ast.body.reduce((types, node) => {
<ide> export type ASTNode = Object;
<ide> const invariant = require('invariant');
<ide>
<ide> type TypeAliasResolutionStatus =
<del> | $ReadOnly<{|
<add> | $ReadOnly<{
<ide> successful: true,
<ide> aliasName: string,
<del> |}>
<del> | $ReadOnly<{|
<add> }>
<add> | $ReadOnly<{
<ide> successful: false,
<del> |}>;
<add> }>;
<ide>
<ide> function resolveTypeAnnotation(
<ide> // TODO(T71778680): This is an Flow TypeAnnotation. Flow-type this | 21 |
Python | Python | fix failing test for router with no trailing slash | 1c935cd3d271efd06f1621c9dddb9e1cd0333e20 | <ide><path>rest_framework/tests/test_routers.py
<ide> class NoteViewSet(viewsets.ModelViewSet):
<ide> self.urls = self.router.urls
<ide>
<ide> def test_urls_can_have_trailing_slash_removed(self):
<del> expected = ['^notes$', '^notes/(?P<pk>[^/]+)$']
<add> expected = ['^notes$', '^notes/(?P<pk>[^/.]+)$']
<ide> for idx in range(len(expected)):
<ide> self.assertEqual(expected[idx], self.urls[idx].regex.pattern)
<ide> | 1 |
Python | Python | clarify error on repr failure in assert_equal | 91a86f6715604183741f84d429a3a5c2fc7d7e9e | <ide><path>numpy/testing/tests/test_utils.py
<ide> def test_complex(self):
<ide> self._assert_func(x, x)
<ide> self._test_not_equal(x, y)
<ide>
<add> def test_error_message(self):
<add> try:
<add> self._assert_func(np.array([1, 2]), np.matrix([1, 2]))
<add> except AssertionError as e:
<add> self.assertEqual(
<add> str(e),
<add> "\nArrays are not equal\n\n"
<add> "(shapes (2,), (1, 2) mismatch)\n"
<add> " x: array([1, 2])\n"
<add> " y: [repr failed for <matrix>: The truth value of an array "
<add> "with more than one element is ambiguous. Use a.any() or "
<add> "a.all()]")
<add>
<ide>
<ide> class TestArrayAlmostEqual(_GenericTest, unittest.TestCase):
<ide>
<ide><path>numpy/testing/utils.py
<ide> def build_err_msg(arrays, err_msg, header='Items are not equal:',
<ide>
<ide> try:
<ide> r = r_func(a)
<del> except:
<del> r = '[repr failed]'
<add> except Exception as exc:
<add> r = '[repr failed for <{}>: {}]'.format(type(a).__name__, exc)
<ide> if r.count('\n') > 3:
<ide> r = '\n'.join(r.splitlines()[:3])
<ide> r += '...' | 2 |
Javascript | Javascript | add missing test description | a8fd8e5ec6fba42b6493c48a6bb127c4119cce79 | <ide><path>test/cases/parsing/issue-3238/index.js
<del>it("should pass", function() {
<add>it("supports empty element in destructuring", function() {
<ide> const second = ([, x]) => x;
<ide> second([1, 2]).should.eql(2);
<ide> }); | 1 |
Go | Go | remove mount spec backport | 4e025b54d57894331a0e8a0ff89f424cbfb43bc1 | <ide><path>daemon/daemon.go
<ide> func (daemon *Daemon) restore() error {
<ide>
<ide> log := logrus.WithField("container", c.ID)
<ide>
<del> daemon.backportMountSpec(c)
<ide> if err := daemon.checkpointAndSave(c); err != nil {
<ide> log.WithError(err).Error("error saving backported mountspec to disk")
<ide> }
<ide><path>daemon/volumes.go
<ide> import (
<ide> "context"
<ide> "os"
<ide> "path/filepath"
<del> "reflect"
<ide> "strings"
<ide> "time"
<ide>
<ide> func (daemon *Daemon) lazyInitializeVolume(containerID string, m *volumemounts.M
<ide> return nil
<ide> }
<ide>
<del>// backportMountSpec resolves mount specs (introduced in 1.13) from pre-1.13
<del>// mount configurations
<del>// The container lock should not be held when calling this function.
<del>// Changes are only made in-memory and may make changes to containers referenced
<del>// by `container.HostConfig.VolumesFrom`
<del>func (daemon *Daemon) backportMountSpec(container *container.Container) {
<del> container.Lock()
<del> defer container.Unlock()
<del>
<del> maybeUpdate := make(map[string]bool)
<del> for _, mp := range container.MountPoints {
<del> if mp.Spec.Source != "" && mp.Type != "" {
<del> continue
<del> }
<del> maybeUpdate[mp.Destination] = true
<del> }
<del> if len(maybeUpdate) == 0 {
<del> return
<del> }
<del>
<del> mountSpecs := make(map[string]bool, len(container.HostConfig.Mounts))
<del> for _, m := range container.HostConfig.Mounts {
<del> mountSpecs[m.Target] = true
<del> }
<del>
<del> parser := volumemounts.NewParser()
<del> binds := make(map[string]*volumemounts.MountPoint, len(container.HostConfig.Binds))
<del> for _, rawSpec := range container.HostConfig.Binds {
<del> mp, err := parser.ParseMountRaw(rawSpec, container.HostConfig.VolumeDriver)
<del> if err != nil {
<del> logrus.WithError(err).Error("Got unexpected error while re-parsing raw volume spec during spec backport")
<del> continue
<del> }
<del> binds[mp.Destination] = mp
<del> }
<del>
<del> volumesFrom := make(map[string]volumemounts.MountPoint)
<del> for _, fromSpec := range container.HostConfig.VolumesFrom {
<del> from, _, err := parser.ParseVolumesFrom(fromSpec)
<del> if err != nil {
<del> logrus.WithError(err).WithField("id", container.ID).Error("Error reading volumes-from spec during mount spec backport")
<del> continue
<del> }
<del> fromC, err := daemon.GetContainer(from)
<del> if err != nil {
<del> logrus.WithError(err).WithField("from-container", from).Error("Error looking up volumes-from container")
<del> continue
<del> }
<del>
<del> // make sure from container's specs have been backported
<del> daemon.backportMountSpec(fromC)
<del>
<del> fromC.Lock()
<del> for t, mp := range fromC.MountPoints {
<del> volumesFrom[t] = *mp
<del> }
<del> fromC.Unlock()
<del> }
<del>
<del> needsUpdate := func(containerMount, other *volumemounts.MountPoint) bool {
<del> if containerMount.Type != other.Type || !reflect.DeepEqual(containerMount.Spec, other.Spec) {
<del> return true
<del> }
<del> return false
<del> }
<del>
<del> // main
<del> for _, cm := range container.MountPoints {
<del> if !maybeUpdate[cm.Destination] {
<del> continue
<del> }
<del> // nothing to backport if from hostconfig.Mounts
<del> if mountSpecs[cm.Destination] {
<del> continue
<del> }
<del>
<del> if mp, exists := binds[cm.Destination]; exists {
<del> if needsUpdate(cm, mp) {
<del> cm.Spec = mp.Spec
<del> cm.Type = mp.Type
<del> }
<del> continue
<del> }
<del>
<del> if cm.Name != "" {
<del> if mp, exists := volumesFrom[cm.Destination]; exists {
<del> if needsUpdate(cm, &mp) {
<del> cm.Spec = mp.Spec
<del> cm.Type = mp.Type
<del> }
<del> continue
<del> }
<del>
<del> if cm.Type != "" {
<del> // probably specified via the hostconfig.Mounts
<del> continue
<del> }
<del>
<del> // anon volume
<del> cm.Type = mounttypes.TypeVolume
<del> cm.Spec.Type = mounttypes.TypeVolume
<del> } else {
<del> if cm.Type != "" {
<del> // already updated
<del> continue
<del> }
<del>
<del> cm.Type = mounttypes.TypeBind
<del> cm.Spec.Type = mounttypes.TypeBind
<del> cm.Spec.Source = cm.Source
<del> if cm.Propagation != "" {
<del> cm.Spec.BindOptions = &mounttypes.BindOptions{
<del> Propagation: cm.Propagation,
<del> }
<del> }
<del> }
<del>
<del> cm.Spec.Target = cm.Destination
<del> cm.Spec.ReadOnly = !cm.RW
<del> }
<del>}
<del>
<ide> // VolumesService is used to perform volume operations
<ide> func (daemon *Daemon) VolumesService() *service.VolumesService {
<ide> return daemon.volumes
<ide><path>daemon/volumes_unix_test.go
<del>//go:build !windows
<del>// +build !windows
<del>
<del>package daemon // import "github.com/docker/docker/daemon"
<del>
<del>import (
<del> "encoding/json"
<del> "fmt"
<del> "reflect"
<del> "testing"
<del>
<del> containertypes "github.com/docker/docker/api/types/container"
<del> mounttypes "github.com/docker/docker/api/types/mount"
<del> "github.com/docker/docker/container"
<del> volumemounts "github.com/docker/docker/volume/mounts"
<del>)
<del>
<del>func TestBackportMountSpec(t *testing.T) {
<del> d := Daemon{containers: container.NewMemoryStore()}
<del>
<del> c := &container.Container{
<del> State: &container.State{},
<del> MountPoints: map[string]*volumemounts.MountPoint{
<del> "/apple": {Destination: "/apple", Source: "/var/lib/docker/volumes/12345678", Name: "12345678", RW: true, CopyData: true}, // anonymous volume
<del> "/banana": {Destination: "/banana", Source: "/var/lib/docker/volumes/data", Name: "data", RW: true, CopyData: true}, // named volume
<del> "/cherry": {Destination: "/cherry", Source: "/var/lib/docker/volumes/data", Name: "data", CopyData: true}, // RO named volume
<del> "/dates": {Destination: "/dates", Source: "/var/lib/docker/volumes/data", Name: "data"}, // named volume nocopy
<del> "/elderberry": {Destination: "/elderberry", Source: "/var/lib/docker/volumes/data", Name: "data"}, // masks anon vol
<del> "/fig": {Destination: "/fig", Source: "/data", RW: true}, // RW bind
<del> "/guava": {Destination: "/guava", Source: "/data", RW: false, Propagation: "shared"}, // RO bind + propagation
<del> "/kumquat": {Destination: "/kumquat", Name: "data", RW: false, CopyData: true}, // volumes-from
<del>
<del> // partially configured mountpoint due to #32613
<del> // specifically, `mp.Spec.Source` is not set
<del> "/honeydew": {
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/honeydew",
<del> Name: "data",
<del> Source: "/var/lib/docker/volumes/data",
<del> Spec: mounttypes.Mount{Type: mounttypes.TypeVolume, Target: "/honeydew", VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true}},
<del> },
<del>
<del> // from hostconfig.Mounts
<del> "/jambolan": {
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/jambolan",
<del> Source: "/var/lib/docker/volumes/data",
<del> RW: true,
<del> Name: "data",
<del> Spec: mounttypes.Mount{Type: mounttypes.TypeVolume, Target: "/jambolan", Source: "data"},
<del> },
<del> },
<del> HostConfig: &containertypes.HostConfig{
<del> Binds: []string{
<del> "data:/banana",
<del> "data:/cherry:ro",
<del> "data:/dates:ro,nocopy",
<del> "data:/elderberry:ro,nocopy",
<del> "/data:/fig",
<del> "/data:/guava:ro,shared",
<del> "data:/honeydew:nocopy",
<del> },
<del> VolumesFrom: []string{"1:ro"},
<del> Mounts: []mounttypes.Mount{
<del> {Type: mounttypes.TypeVolume, Target: "/jambolan"},
<del> },
<del> },
<del> Config: &containertypes.Config{Volumes: map[string]struct{}{
<del> "/apple": {},
<del> "/elderberry": {},
<del> }},
<del> }
<del>
<del> d.containers.Add("1", &container.Container{
<del> State: &container.State{},
<del> ID: "1",
<del> MountPoints: map[string]*volumemounts.MountPoint{
<del> "/kumquat": {Destination: "/kumquat", Name: "data", RW: false, CopyData: true},
<del> },
<del> HostConfig: &containertypes.HostConfig{
<del> Binds: []string{
<del> "data:/kumquat:ro",
<del> },
<del> },
<del> })
<del>
<del> type expected struct {
<del> mp *volumemounts.MountPoint
<del> comment string
<del> }
<del>
<del> pretty := func(mp *volumemounts.MountPoint) string {
<del> b, err := json.MarshalIndent(mp, "\t", " ")
<del> if err != nil {
<del> return fmt.Sprintf("%#v", mp)
<del> }
<del> return string(b)
<del> }
<del>
<del> mpc := *c.MountPoints["/jambolan"]
<del>
<del> for _, x := range []expected{
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/apple",
<del> RW: true,
<del> Name: "12345678",
<del> Source: "/var/lib/docker/volumes/12345678",
<del> CopyData: true,
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "",
<del> Target: "/apple",
<del> },
<del> },
<del> comment: "anonymous volume",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/banana",
<del> RW: true,
<del> Name: "data",
<del> Source: "/var/lib/docker/volumes/data",
<del> CopyData: true,
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "data",
<del> Target: "/banana",
<del> },
<del> },
<del> comment: "named volume",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/cherry",
<del> Name: "data",
<del> Source: "/var/lib/docker/volumes/data",
<del> CopyData: true,
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "data",
<del> Target: "/cherry",
<del> ReadOnly: true,
<del> },
<del> },
<del> comment: "read-only named volume",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/dates",
<del> Name: "data",
<del> Source: "/var/lib/docker/volumes/data",
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "data",
<del> Target: "/dates",
<del> ReadOnly: true,
<del> VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true},
<del> },
<del> },
<del> comment: "named volume with nocopy",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/elderberry",
<del> Name: "data",
<del> Source: "/var/lib/docker/volumes/data",
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "data",
<del> Target: "/elderberry",
<del> ReadOnly: true,
<del> VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true},
<del> },
<del> },
<del> comment: "masks an anonymous volume",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeBind,
<del> Destination: "/fig",
<del> Source: "/data",
<del> RW: true,
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeBind,
<del> Source: "/data",
<del> Target: "/fig",
<del> },
<del> },
<del> comment: "bind mount with read/write",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeBind,
<del> Destination: "/guava",
<del> Source: "/data",
<del> RW: false,
<del> Propagation: "shared",
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeBind,
<del> Source: "/data",
<del> Target: "/guava",
<del> ReadOnly: true,
<del> BindOptions: &mounttypes.BindOptions{Propagation: "shared"},
<del> },
<del> },
<del> comment: "bind mount with read/write + shared propagation",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/honeydew",
<del> Source: "/var/lib/docker/volumes/data",
<del> RW: true,
<del> Propagation: "shared",
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "data",
<del> Target: "/honeydew",
<del> VolumeOptions: &mounttypes.VolumeOptions{NoCopy: true},
<del> },
<del> },
<del> comment: "partially configured named volume caused by #32613",
<del> },
<del> {
<del> mp: &mpc,
<del> comment: "volume defined in mounts API",
<del> },
<del> {
<del> mp: &volumemounts.MountPoint{
<del> Type: mounttypes.TypeVolume,
<del> Destination: "/kumquat",
<del> Source: "/var/lib/docker/volumes/data",
<del> RW: false,
<del> Name: "data",
<del> Spec: mounttypes.Mount{
<del> Type: mounttypes.TypeVolume,
<del> Source: "data",
<del> Target: "/kumquat",
<del> ReadOnly: true,
<del> },
<del> },
<del> comment: "partially configured named volume caused by #32613",
<del> },
<del> } {
<del>
<del> mp := c.MountPoints[x.mp.Destination]
<del> d.backportMountSpec(c)
<del>
<del> if !reflect.DeepEqual(mp.Spec, x.mp.Spec) {
<del> t.Fatalf("%s\nexpected:\n\t%s\n\ngot:\n\t%s", x.comment, pretty(x.mp), pretty(mp))
<del> }
<del> }
<del>} | 3 |
Python | Python | fix lint issues | 06e1d4f76ffa9890196c464f29ff625f1186ff7f | <ide><path>libcloud/compute/drivers/openstack.py
<ide> def _to_routers(self, obj):
<ide> return [self._to_router(router) for router in routers]
<ide>
<ide> def _to_router(self, obj):
<del> extra={}
<add> extra = {}
<ide> extra['external_gateway_info'] = obj['external_gateway_info']
<ide> extra['routes'] = obj['routes']
<ide> return OpenStack_2_Router(id=obj['id'],
<ide> def ex_delete_router(self, router):
<ide> '/v2.0/routers', router.id), method='DELETE')
<ide> return resp.status in (httplib.NO_CONTENT, httplib.ACCEPTED)
<ide>
<add>
<ide> class OpenStack_1_1_FloatingIpPool(object):
<ide> """
<ide> Floating IP Pool info.
<ide> def __repr__(self):
<ide> self.name,
<ide> self.cidr)
<ide>
<add>
<ide> class OpenStack_2_Router(object):
<ide> """
<ide> A Virtual Router.
<ide> def __repr__(self):
<ide> return '<OpenStack_2_Router id="%s" name="%s">' % (self.id,
<ide> self.name)
<ide>
<add>
<ide> class OpenStack_2_PortInterface(UuidMixin):
<ide> """
<ide> Port Interface info. Similar in functionality to a floating IP (can be | 1 |
Ruby | Ruby | normalize use of macos_version | 8e0c96c45de35f25c79957763de04235e7e5d48d | <ide><path>Library/Homebrew/utils.rb
<ide> def macports_or_fink_installed?
<ide> false
<ide> end
<ide>
<add> def leopard?
<add> 10.5 == MACOS_VERSION
<add> end
<add>
<add> def snow_leopard?
<add> 10.6 <= MACOS_VERSION # Actually Snow Leopard or newer
<add> end
<add>
<ide> def prefer_64_bit?
<del> MACOS_VERSION >= 10.6 and Hardware.is_64_bit?
<add> Hardware.is_64_bit? and 10.6 <= MACOS_VERSION
<ide> end
<ide> end
<ide> | 1 |
Python | Python | fix typo in examples/run_squad.py | 6d5049a24d5906ece3fd9b68fb3abe1a0b6bb049 | <ide><path>examples/run_squad.py
<ide> def main():
<ide> parser.add_argument("--do_train", action="store_true", help="Whether to run training.")
<ide> parser.add_argument("--do_eval", action="store_true", help="Whether to run eval on the dev set.")
<ide> parser.add_argument(
<del> "--evaluate_during_training", action="store_true", help="Rul evaluation during training at each logging step."
<add> "--evaluate_during_training", action="store_true", help="Run evaluation during training at each logging step."
<ide> )
<ide> parser.add_argument(
<ide> "--do_lower_case", action="store_true", help="Set this flag if you are using an uncased model." | 1 |
Javascript | Javascript | fix inconsistency in dynamic tests | 33067a58621e1c937bbf2fd11d1b9f7fc3bab212 | <ide><path>test/integration/basic/test/dynamic.js
<ide> export default (context, render) => {
<ide> browser.close()
<ide> })
<ide> })
<del>
<del> // describe('with browser', () => {
<del>
<del> // describe('with bundle', () => {
<del>
<del> // })
<ide> })
<ide> }
<ide><path>test/integration/production/test/dynamic.js
<add>/* global describe, it, expect */
<add>import webdriver from 'next-webdriver'
<add>import cheerio from 'cheerio'
<add>import { waitFor, check } from 'next-test-utils'
<add>
<add>// These tests are similar to ../../basic/test/dynamic.js
<add>export default (context, render) => {
<add> async function get$ (path, query) {
<add> const html = await render(path, query)
<add> return cheerio.load(html)
<add> }
<add> describe('Dynamic import', () => {
<add> describe('default behavior', () => {
<add> it('should render dynamic import components', async () => {
<add> const $ = await get$('/dynamic/ssr')
<add> expect($('body').text()).toMatch(/Hello World 1/)
<add> })
<add>
<add> it('should render even there are no physical chunk exists', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(context.appPort, '/dynamic/no-chunk')
<add> await check(() => browser.elementByCss('body').text(), /Welcome, normal/)
<add> await check(() => browser.elementByCss('body').text(), /Welcome, dynamic/)
<add> } finally {
<add> if (browser) {
<add> browser.close()
<add> }
<add> }
<add> })
<add> })
<add> describe('ssr:false option', () => {
<add> it('Should render loading on the server side', async () => {
<add> const $ = await get$('/dynamic/no-ssr')
<add> expect($('p').text()).toBe('loading...')
<add> })
<add>
<add> it('should render the component on client side', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(context.appPort, '/dynamic/no-ssr')
<add> await check(() => browser.elementByCss('body').text(), /Hello World 1/)
<add> } finally {
<add> if (browser) {
<add> browser.close()
<add> }
<add> }
<add> })
<add> })
<add>
<add> describe('custom loading', () => {
<add> it('should render custom loading on the server side when `ssr:false` and `loading` is provided', async () => {
<add> const $ = await get$('/dynamic/no-ssr-custom-loading')
<add> expect($('p').text()).toBe('LOADING')
<add> })
<add>
<add> it('should render the component on client side', async () => {
<add> let browser
<add> try {
<add> browser = await webdriver(context.appPort, '/dynamic/no-ssr-custom-loading')
<add> await check(() => browser.elementByCss('body').text(), /Hello World 1/)
<add> } finally {
<add> if (browser) {
<add> browser.close()
<add> }
<add> }
<add> })
<add> })
<add>
<add> describe('Import mapping', () => {
<add> it('should render dynamic imports bundle', async () => {
<add> const $ = await get$('/dynamic/bundle')
<add> const bodyText = $('body').text()
<add> expect(/Dynamic Bundle/.test(bodyText)).toBe(true)
<add> expect(/Hello World 1/.test(bodyText)).toBe(true)
<add> expect(/Hello World 2/.test(bodyText)).toBe(false)
<add> })
<add>
<add> it('should render dynamic imports bundle with additional components', async () => {
<add> const $ = await get$('/dynamic/bundle?showMore=1')
<add> const bodyText = $('body').text()
<add> expect(/Dynamic Bundle/.test(bodyText)).toBe(true)
<add> expect(/Hello World 1/.test(bodyText)).toBe(true)
<add> expect(/Hello World 2/.test(bodyText)).toBe(true)
<add> })
<add>
<add> it('should render components', async () => {
<add> const browser = await webdriver(context.appPort, '/dynamic/bundle')
<add>
<add> while (true) {
<add> const bodyText = await browser
<add> .elementByCss('body').text()
<add> if (
<add> /Dynamic Bundle/.test(bodyText) &&
<add> /Hello World 1/.test(bodyText) &&
<add> !(/Hello World 2/.test(bodyText))
<add> ) break
<add> await waitFor(1000)
<add> }
<add>
<add> browser.close()
<add> })
<add>
<add> it('should render support React context', async () => {
<add> const browser = await webdriver(context.appPort, '/dynamic/bundle')
<add>
<add> while (true) {
<add> const bodyText = await browser
<add> .elementByCss('body').text()
<add> if (
<add> /ZEIT Rocks/.test(bodyText)
<add> ) break
<add> await waitFor(1000)
<add> }
<add>
<add> browser.close()
<add> })
<add>
<add> it('should load new components and render for prop changes', async () => {
<add> const browser = await webdriver(context.appPort, '/dynamic/bundle')
<add>
<add> await browser
<add> .waitForElementByCss('#toggle-show-more')
<add> .elementByCss('#toggle-show-more').click()
<add>
<add> while (true) {
<add> const bodyText = await browser
<add> .elementByCss('body').text()
<add> if (
<add> /Dynamic Bundle/.test(bodyText) &&
<add> /Hello World 1/.test(bodyText) &&
<add> /Hello World 2/.test(bodyText)
<add> ) break
<add> await waitFor(1000)
<add> }
<add>
<add> browser.close()
<add> })
<add> })
<add> })
<add>}
<ide><path>test/integration/production/test/index.test.js
<ide> import {
<ide> } from 'next-test-utils'
<ide> import webdriver from 'next-webdriver'
<ide> import fetch from 'node-fetch'
<del>import dynamicImportTests from '../../basic/test/dynamic'
<add>import dynamicImportTests from './dynamic'
<ide> import security from './security'
<ide> import {BUILD_MANIFEST, REACT_LOADABLE_MANIFEST} from 'next/constants'
<ide>
<ide><path>test/lib/next-test-utils.js
<ide> export async function startStaticServer (dir) {
<ide>
<ide> export async function check (contentFn, regex) {
<ide> let found = false
<del> setTimeout(() => {
<add> setTimeout(async () => {
<ide> if (found) {
<ide> return
<ide> }
<del> console.error('TIMED OUT CHECK: ', regex)
<del> throw new Error('TIMED OUT')
<add> let content
<add> try {
<add> content = await contentFn()
<add> } catch (err) {
<add> console.error('Error while getting content', {regex})
<add> }
<add> console.error('TIMED OUT CHECK: ', {regex, content})
<add> throw new Error('TIMED OUT: ' + regex + '\n\n' + content)
<ide> }, 1000 * 30)
<ide> while (!found) {
<ide> try { | 4 |
Javascript | Javascript | use sync fs.mkdir | d2817f48a1146b469d544ee78015251551d358c3 | <ide><path>local-cli/library/library.js
<ide> function library(argv, config, args) {
<ide> const source = path.resolve('node_modules', 'react-native', 'Libraries', 'Sample');
<ide>
<ide> if (!fs.existsSync(libraries)) {
<del> fs.mkdir(libraries);
<add> fs.mkdirSync(libraries);
<ide> }
<ide>
<ide> if (fs.existsSync(libraryDest)) { | 1 |
Ruby | Ruby | remove errant debug code | d6b9f8410c990b3d68d1970f1461a1d385d098d7 | <ide><path>actionpack/lib/action_dispatch/http/mime_type.rb
<ide> def ===(list)
<ide> def ==(mime_type)
<ide> return false if mime_type.blank?
<ide> (@synonyms + [ self ]).any? do |synonym|
<del> require "ruby-debug"
<del> debugger if mime_type.is_a?(Array)
<ide> synonym.to_s == mime_type.to_s || synonym.to_sym == mime_type.to_sym
<ide> end
<ide> end | 1 |
Text | Text | fix small typo in v0.10.0 release article | 598b5e4593bf39c71416183c36372d97e97852f5 | <ide><path>doc/blog/release/v0.10.0.md
<ide> infrastructure specializing in real-time web and mobile applications.
<ide> Joyent uses Node extensively throughout their stack, and provides
<ide> impressive [post-mortem debugging and real-time performance analysis
<ide> tools](http://dtrace.org/blogs/dap/2012/05/31/debugging-node-js-in-production-fluent-slides/)
<del>for Node.js applications. They are my also employer, so I'd probably
<add>for Node.js applications. They are also by employer, so I'd probably
<ide> have to get a "real" job if they weren't sponsoring Node :)
<ide>
<ide> ## Next Up: v0.12 | 1 |
Javascript | Javascript | remove node shallow builds | 739f20beda56a28a9212e3478571c866babee118 | <ide><path>packages/react-test-renderer/npm/shallow.js
<ide> 'use strict';
<ide>
<del>if (process.env.NODE_ENV === 'production') {
<del> module.exports = require('./cjs/react-test-renderer-shallow.production.min.js');
<del>} else {
<del> module.exports = require('./cjs/react-test-renderer-shallow.development.js');
<del>}
<add>module.exports = require('react-shallow-renderer');
<ide><path>scripts/rollup/bundles.js
<ide> const bundles = [
<ide> }),
<ide> },
<ide> {
<del> bundleTypes: [NODE_DEV, NODE_PROD, UMD_DEV, UMD_PROD],
<add> bundleTypes: [UMD_DEV, UMD_PROD],
<ide> moduleType: NON_FIBER_RENDERER,
<ide> entry: 'react-test-renderer/shallow',
<ide> global: 'ReactShallowRenderer', | 2 |
Ruby | Ruby | fix an error message | fb797ad1f1c3b0d96968c5feef783a2b8fe07eed | <ide><path>lib/action_cable/connection/base.rb
<ide> def process_message(message)
<ide> if @subscriptions[message['identifier']]
<ide> @subscriptions[message['identifier']].receive_data(ActiveSupport::JSON.decode message['data'])
<ide> else
<del> logger.error "[ActionCable] Unable to process message because no subscription found (#{message.inspect})"
<add> logger.error "[ActionCable] Unable to process message because no subscription was found (#{message.inspect})"
<ide> end
<ide> rescue Exception => e
<ide> logger.error "[ActionCable] Could not process message (#{data.inspect})" | 1 |
PHP | PHP | remove useless condition. | 0d7ca93b5647792c2882b3fc96ad8f3d5cf35f1f | <ide><path>src/Illuminate/Broadcasting/BroadcastManager.php
<ide> public function socket($request = null)
<ide>
<ide> $request = $request ?: $this->app['request'];
<ide>
<del> if ($request->hasHeader('X-Socket-ID')) {
<del> return $request->header('X-Socket-ID');
<del> }
<add> return $request->header('X-Socket-ID');
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | fix unused ignoreexception in nose_tools/utils.py | 2f4cc792492ed4acbe956e737daa7c1318e05ee7 | <ide><path>numpy/testing/nose_tools/utils.py
<ide> def _gen_alignment_data(dtype=float32, type='binary', max_size=24):
<ide>
<ide> class IgnoreException(Exception):
<ide> "Ignoring this exception due to disabled feature"
<add> pass
<ide>
<ide>
<ide> @contextlib.contextmanager | 1 |
Javascript | Javascript | remove save to user on return individual user | b2d04ec7c501d71901622dba5a24a0babff6fb8c | <ide><path>server/boot/challenge.js
<ide> module.exports = function(app) {
<ide> return Observable.just('/challenges/' + dasherize(challenge.name));
<ide> }
<ide>
<del> if (challenge) {
<del> if (req.user) {
<del> req.user.currentChallenge = {
<del> challengeId: challenge.id,
<del> challengeName: challenge.name,
<del> dashedName: challenge.dashedName
<del> };
<del> }
<del>
<del> // save user does nothing if user does not exist
<del> return saveUser(req.user)
<del> .map(() => ({
<del> title: challenge.name,
<del> dashedName: origChallengeName,
<del> name: challenge.name,
<del> details: challenge.description,
<del> tests: challenge.tests,
<del> challengeSeed: challenge.challengeSeed,
<del> verb: utils.randomVerb(),
<del> phrase: utils.randomPhrase(),
<del> compliment: utils.randomCompliment(),
<del> challengeId: challenge.id,
<del> challengeType: challenge.challengeType,
<del> // video challenges
<del> video: challenge.challengeSeed[0],
<del> // bonfires specific
<del> difficulty: Math.floor(+challenge.difficulty),
<del> bonfires: challenge,
<del> MDNkeys: challenge.MDNlinks,
<del> MDNlinks: getMDNLinks(challenge.MDNlinks),
<del> // htmls specific
<del> environment: utils.whichEnvironment()
<del> }));
<del> }
<add> // save user does nothing if user does not exist
<add> return Observable.just({
<add> title: challenge.name,
<add> dashedName: origChallengeName,
<add> name: challenge.name,
<add> details: challenge.description,
<add> tests: challenge.tests,
<add> challengeSeed: challenge.challengeSeed,
<add> verb: utils.randomVerb(),
<add> phrase: utils.randomPhrase(),
<add> compliment: utils.randomCompliment(),
<add> challengeId: challenge.id,
<add> challengeType: challenge.challengeType,
<add> // video challenges
<add> video: challenge.challengeSeed[0],
<add> // bonfires specific
<add> difficulty: Math.floor(+challenge.difficulty),
<add> bonfires: challenge,
<add> MDNkeys: challenge.MDNlinks,
<add> MDNlinks: getMDNLinks(challenge.MDNlinks),
<add> // htmls specific
<add> environment: utils.whichEnvironment()
<add> });
<ide> })
<ide> .subscribe(
<ide> function(data) { | 1 |
Javascript | Javascript | propagate controller keyword for outlets | 5a33e9c00b025152e3ed30981f245738c02fd52c | <ide><path>packages/ember-htmlbars/lib/hooks/bind-self.js
<ide> export default function bindSelf(env, scope, _self) {
<ide> }
<ide>
<ide> newStream(scope, 'self', self, null, true);
<add>
<add> if (!scope.locals.controller) {
<add> scope.locals.controller = scope.self;
<add> }
<ide> }
<ide>
<ide> function newStream(scope, key, newValue, renderNode, isSelf) {
<ide><path>packages/ember-htmlbars/lib/node-managers/component-node-manager.js
<ide> ComponentNodeManager.create = function(renderNode, env, options) {
<ide> if (attrs.viewName) { createOptions.viewName = getValue(attrs.viewName); }
<ide>
<ide> if (component.create && parentScope && parentScope.self) {
<del> options._context = getValue(parentScope.self);
<add> createOptions._context = getValue(parentScope.self);
<add> }
<add>
<add> if (parentScope.locals.controller) {
<add> createOptions._controller = getValue(parentScope.locals.controller);
<ide> }
<ide>
<ide> component = createOrUpdateComponent(component, createOptions, renderNode, env, attrs);
<ide><path>packages/ember-views/lib/views/component.js
<ide> var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, {
<ide> @default null
<ide> */
<ide> targetObject: computed('parentView', function(key) {
<add> if (this._controller) { return this._controller; }
<ide> var parentView = get(this, 'parentView');
<ide> return parentView ? get(parentView, 'controller') : null;
<ide> }),
<ide><path>packages/ember/tests/helpers/link_to_test.js
<ide> QUnit.test("The non-block form {{link-to}} helper updates the link text when it
<ide> equal(Ember.$('#contact-link:contains(Robert)', '#qunit-fixture').length, 1, "The link title is correctly updated when the route changes");
<ide> });
<ide>
<del>QUnit.skip("The non-block form {{link-to}} helper moves into the named route with context", function() {
<add>QUnit.test("The non-block form {{link-to}} helper moves into the named route with context", function() {
<ide> expect(5);
<ide> Router.map(function(match) {
<ide> this.route("item", { path: "/item/:id" });
<ide><path>packages/ember/tests/template_scope_test.js
<ide> QUnit.module("Template scoping examples", {
<ide> }
<ide> });
<ide>
<del>QUnit.skip("Actions inside an outlet go to the associated controller", function() {
<add>QUnit.test("Actions inside an outlet go to the associated controller", function() {
<ide> expect(1);
<ide>
<ide> templates.index = compile("{{component-with-action action='componentAction'}}"); | 5 |
Ruby | Ruby | use proper default | 2d6c79413d01f48df11ef76e65ba45673dcf580c | <ide><path>lib/action_mailroom/test_helper.rb
<ide> def create_inbound_email_from_mail(status: :processing, **mail_options)
<ide> create_inbound_email(StringIO.new(Mail.new(mail_options).to_s), status: status)
<ide> end
<ide>
<del> def create_inbound_email(io, filename: 'mail.eml', status: status)
<add> def create_inbound_email(io, filename: 'mail.eml', status: :processing)
<ide> ActionMailroom::InboundEmail.create! status: status, raw_email:
<ide> ActiveStorage::Blob.create_after_upload!(io: io, filename: filename, content_type: 'message/rfc822')
<ide> end | 1 |
Python | Python | update create_balancer method in the gogrid driver | b54687f1f294b15eb2dd0ce08725b9fae780b181 | <ide><path>libcloud/loadbalancer/drivers/gogrid.py
<ide> from libcloud.utils import reverse_dict
<ide> from libcloud.common.gogrid import GoGridConnection, BaseGoGridDriver
<ide> from libcloud.loadbalancer.base import LoadBalancer, Member, Driver, Algorithm
<del>from libcloud.loadbalancer.base import DEFAULT_ALGORITHM
<add>from libcloud.loadbalancer.base import DEFAULT_ALGORITHM
<ide> from libcloud.loadbalancer.types import Provider, State, LibcloudLBImmutableError
<ide>
<ide>
<ide> class GoGridLBDriver(BaseGoGridDriver, Driver):
<ide> }
<ide> _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)
<ide>
<add> def list_protocols(self):
<add> # GoGrid only supports http
<add> return [ 'http' ]
<add>
<ide> def list_balancers(self):
<ide> return self._to_balancers(
<ide> self.connection.request('/api/grid/loadbalancer/list').object)
<ide>
<del> def ex_create_balancer_nowait(self, name, port, algorithm, members):
<del> if not algorithm:
<del> algorithm = DEFAULT_ALGORITHM
<del> else:
<del> algorithm = self._algorithm_to_value(algorithm)
<add> def ex_create_balancer_nowait(self, name, members, protocol='http', port=80,
<add> algorithm=Algorithm.ROUND_ROBIN):
<add> algorithm = self._algorithm_to_value(algorithm)
<ide>
<ide> params = {'name': name,
<ide> 'loadbalancer.type': algorithm,
<ide> def ex_create_balancer_nowait(self, name, port, algorithm, members):
<ide> params=params)
<ide> return self._to_balancers(resp.object)[0]
<ide>
<del> def create_balancer(self, name, port, algorithm, members):
<del> balancer = self.ex_create_balancer_nowait(name, port, algorithm, members)
<add> def create_balancer(self, name, members, protocol='http', port=80,
<add> algorithm=Algorithm.ROUND_ROBIN):
<add> balancer = self.ex_create_balancer_nowait(name, members, protocol,
<add> port, algorithm)
<ide>
<ide> timeout = 60 * 20
<ide> waittime = 0
<ide><path>libcloud/loadbalancer/drivers/rackspace.py
<ide> except ImportError:
<ide> import simplejson as json
<ide>
<add>from libcloud.utils import reverse_dict
<ide> from libcloud.common.base import Response
<del>from libcloud.loadbalancer.base import LoadBalancer, Member, Driver
<add>from libcloud.loadbalancer.base import LoadBalancer, Member, Driver, Algorithm
<ide> from libcloud.loadbalancer.types import Provider, State
<ide> from libcloud.common.rackspace import (AUTH_HOST_US,
<ide> RackspaceBaseConnection)
<ide> class RackspaceLBDriver(Driver):
<ide>
<ide> LB_STATE_MAP = { 'ACTIVE': State.RUNNING,
<ide> 'BUILD': State.PENDING }
<add> _VALUE_TO_ALGORITHM_MAP = {
<add> 'RANDOM': Algorithm.RANDOM,
<add> 'ROUND_ROBIN': Algorithm.ROUND_ROBIN,
<add> 'LEAST_CONNECTIONS': Algorithm.LEAST_CONNECTIONS
<add> }
<add> _ALGORITHM_TO_VALUE_MAP = reverse_dict(_VALUE_TO_ALGORITHM_MAP)
<ide>
<ide> def list_balancers(self):
<ide> return self._to_balancers(
<ide> self.connection.request('/loadbalancers').object)
<ide>
<del> def create_balancer(self, **kwargs):
<del> name = kwargs['name']
<del> port = kwargs['port']
<del> members = kwargs['members']
<add> def create_balancer(self, name, port, algorithm, members):
<add> if not algorithm:
<add> algorithm = DEFAULT_ALGORITHM
<add> else:
<add> algorithm = self._algorithm_to_value(algorithm)
<ide>
<ide> balancer_object = {"loadBalancer":
<ide> {"name": name,
<ide> "port": port,
<add> "algorithm": algorithm,
<ide> "protocol": "HTTP",
<ide> "virtualIps": [{"type": "PUBLIC"}],
<ide> "nodes": [{"address": member.ip,
<ide><path>test/loadbalancer/test_gogrid.py
<ide> def setUp(self):
<ide> GoGridLBMockHttp.type = None
<ide> self.driver = GoGridLBDriver('user', 'key')
<ide>
<add> def test_list_protocols(self):
<add> protocols = self.driver.list_protocols()
<add>
<add> self.assertEqual(len(protocols), 1)
<add> self.assertEqual(protocols[0], 'http')
<add>
<ide> def test_list_balancers(self):
<ide> balancers = self.driver.list_balancers()
<ide>
<ide> def test_list_balancers(self):
<ide> def test_create_balancer(self):
<ide> balancer = self.driver.create_balancer(name='test2',
<ide> port=80,
<add> protocol='http',
<ide> algorithm=Algorithm.ROUND_ROBIN,
<ide> members=(Member(None, '10.1.0.10', 80),
<del> Member(None, '10.1.0.11', 80))
<add> Member(None, '10.1.0.11', 80))
<ide> )
<ide>
<ide> self.assertEquals(balancer.name, 'test2')
<ide><path>test/loadbalancer/test_rackspace.py
<ide> import sys
<ide> import unittest
<ide>
<del>from libcloud.loadbalancer.base import Member
<add>from libcloud.loadbalancer.base import Member, Algorithm
<ide> from libcloud.loadbalancer.drivers.rackspace import RackspaceLBDriver
<ide>
<ide> from test import MockHttp, MockRawResponse
<ide> def test_list_balancers(self):
<ide> def test_create_balancer(self):
<ide> balancer = self.driver.create_balancer(name='test2',
<ide> port=80,
<add> algorithm=Algorithm.ROUND_ROBIN,
<ide> members=(Member(None, '10.1.0.10', 80),
<ide> Member(None, '10.1.0.11', 80))
<ide> ) | 4 |
PHP | PHP | use model@hydrate in builder@getmodels | 5165d44c7741dd901d71ca3e9a40b14e4170d7c1 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function onDelete(Closure $callback)
<ide> */
<ide> public function getModels($columns = array('*'))
<ide> {
<del> // First, we will simply get the raw results from the query builders which we
<del> // can use to populate an array with Eloquent models. We will pass columns
<del> // that should be selected as well, which are typically just everything.
<ide> $results = $this->query->get($columns);
<ide>
<ide> $connection = $this->model->getConnectionName();
<ide>
<del> $models = array();
<del>
<del> // Once we have the results, we can spin through them and instantiate a fresh
<del> // model instance for each records we retrieved from the database. We will
<del> // also set the proper connection name for the model after we create it.
<del> foreach ($results as $result)
<del> {
<del> $models[] = $model = $this->model->newFromBuilder($result);
<del>
<del> $model->setConnection($connection);
<del> }
<del>
<del> return $models;
<add> return $this->model->hydrate($results, $connection)->all();
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Database/Eloquent/Model.php
<ide> public function newInstance($attributes = array(), $exists = false)
<ide> * Create a new model instance that is existing.
<ide> *
<ide> * @param array $attributes
<add> * @param string|null $connection
<ide> * @return static
<ide> */
<del> public function newFromBuilder($attributes = array())
<add> public function newFromBuilder($attributes = array(), $connection = null)
<ide> {
<del> $instance = $this->newInstance(array(), true);
<add> $model = $this->newInstance(array(), true);
<ide>
<del> $instance->setRawAttributes((array) $attributes, true);
<add> $model->setRawAttributes((array) $attributes, true);
<ide>
<del> return $instance;
<add> $model->setConnection($connection ?: $this->connection);
<add>
<add> return $model;
<ide> }
<ide>
<ide> /**
<ide> * Create a collection of models from plain arrays.
<ide> *
<ide> * @param array $items
<del> * @param string $connection
<add> * @param string|null $connection
<ide> * @return \Illuminate\Database\Eloquent\Collection
<ide> */
<ide> public static function hydrate(array $items, $connection = null)
<ide> {
<del> $collection = with($instance = new static)->newCollection();
<del>
<del> foreach ($items as $item)
<del> {
<del> $model = $instance->newFromBuilder($item);
<del>
<del> if ( ! is_null($connection))
<del> {
<del> $model->setConnection($connection);
<del> }
<add> $instance = (new static)->setConnection($connection);
<ide>
<del> $collection->push($model);
<del> }
<add> $collection = $instance->newCollection($items);
<ide>
<del> return $collection;
<add> return $collection->map(function ($item) use ($instance)
<add> {
<add> return $instance->newFromBuilder($item);
<add> });
<ide> }
<ide>
<ide> /**
<ide> * Create a collection of models from a raw query.
<ide> *
<ide> * @param string $query
<ide> * @param array $bindings
<del> * @param string $connection
<add> * @param string|null $connection
<ide> * @return \Illuminate\Database\Eloquent\Collection
<ide> */
<ide> public static function hydrateRaw($query, $bindings = array(), $connection = null)
<ide> {
<del> $instance = new static;
<del>
<del> if ( ! is_null($connection))
<del> {
<del> $instance->setConnection($connection);
<del> }
<add> $instance = (new static)->setConnection($connection);
<ide>
<ide> $items = $instance->getConnection()->select($query, $bindings);
<ide>
<ide> public static function query()
<ide> /**
<ide> * Begin querying the model on a given connection.
<ide> *
<del> * @param string $connection
<add> * @param string|null $connection
<ide> * @return \Illuminate\Database\Eloquent\Builder
<ide> */
<ide> public static function on($connection = null)
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php
<ide> public function testGetModelsProperlyHydratesModels()
<ide> $records[] = array('name' => 'taylor', 'age' => 26);
<ide> $records[] = array('name' => 'dayle', 'age' => 28);
<ide> $builder->getQuery()->shouldReceive('get')->once()->with(array('foo'))->andReturn($records);
<del> $model = m::mock('Illuminate\Database\Eloquent\Model[getTable,getConnectionName,newInstance]');
<add> $model = m::mock('Illuminate\Database\Eloquent\Model[getTable,getConnectionName,hydrate]');
<ide> $model->shouldReceive('getTable')->once()->andReturn('foo_table');
<ide> $builder->setModel($model);
<ide> $model->shouldReceive('getConnectionName')->once()->andReturn('foo_connection');
<del> $model->shouldReceive('newInstance')->andReturnUsing(function() { return new EloquentBuilderTestModelStub; });
<add> $model->shouldReceive('hydrate')->once()->with($records, 'foo_connection')->andReturn(new Collection(['hydrated']));
<ide> $models = $builder->getModels(array('foo'));
<ide>
<del> $this->assertEquals('taylor', $models[0]->name);
<del> $this->assertEquals($models[0]->getAttributes(), $models[0]->getOriginal());
<del> $this->assertEquals('dayle', $models[1]->name);
<del> $this->assertEquals($models[1]->getAttributes(), $models[1]->getOriginal());
<del> $this->assertEquals('foo_connection', $models[0]->getConnectionName());
<del> $this->assertEquals('foo_connection', $models[1]->getConnectionName());
<add> $this->assertEquals($models, ['hydrated']);
<ide> }
<ide>
<ide>
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testOneToManyRelationship()
<ide> }
<ide>
<ide>
<add> public function testBasicModelHydration()
<add> {
<add> EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<add> EloquentTestUser::create(['email' => 'abigailotwell@gmail.com']);
<add>
<add> $models = EloquentTestUser::hydrateRaw('SELECT * FROM users WHERE email = ?', ['abigailotwell@gmail.com'], 'foo_connection');
<add>
<add> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $models);
<add> $this->assertInstanceOf('EloquentTestUser', $models[0]);
<add> $this->assertEquals('abigailotwell@gmail.com', $models[0]->email);
<add> $this->assertEquals('foo_connection', $models[0]->getConnectionName());
<add> $this->assertEquals(1, $models->count());
<add> }
<add>
<add>
<ide> public function testHasOnSelfReferencingBelongsToManyRelationship()
<ide> {
<ide> $user = EloquentTestUser::create(['email' => 'taylorotwell@gmail.com']);
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testNewInstanceReturnsNewInstanceWithAttributesSet()
<ide> public function testHydrateCreatesCollectionOfModels()
<ide> {
<ide> $data = array(array('name' => 'Taylor'), array('name' => 'Otwell'));
<del> $collection = EloquentModelStub::hydrate($data);
<add> $collection = EloquentModelStub::hydrate($data, 'foo_connection');
<ide>
<ide> $this->assertInstanceOf('Illuminate\Database\Eloquent\Collection', $collection);
<ide> $this->assertCount(2, $collection);
<ide> $this->assertInstanceOf('EloquentModelStub', $collection[0]);
<ide> $this->assertInstanceOf('EloquentModelStub', $collection[1]);
<add> $this->assertEquals($collection[0]->getAttributes(), $collection[0]->getOriginal());
<add> $this->assertEquals($collection[1]->getAttributes(), $collection[1]->getOriginal());
<ide> $this->assertEquals('Taylor', $collection[0]->name);
<ide> $this->assertEquals('Otwell', $collection[1]->name);
<add> $this->assertEquals('foo_connection', $collection[0]->getConnectionName());
<add> $this->assertEquals('foo_connection', $collection[1]->getConnectionName());
<ide> }
<ide>
<ide> | 5 |
Ruby | Ruby | add explicit require for `symbol#start_with?` | 64c254017eba5357606d1dbb84cdbda1138d5b10 | <ide><path>actiontext/lib/action_text/attribute.rb
<ide> # frozen_string_literal: true
<ide>
<add>require "active_support/core_ext/symbol/starts_ends_with"
<add>
<ide> module ActionText
<ide> module Attribute
<ide> extend ActiveSupport::Concern | 1 |
Javascript | Javascript | add spec for keyboardobserver | 905e3fc5bd3e68a88167a9faa28bf604e6c3697c | <ide><path>Libraries/Components/Keyboard/Keyboard.js
<ide> const LayoutAnimation = require('../../LayoutAnimation/LayoutAnimation');
<ide> const invariant = require('invariant');
<ide> const NativeEventEmitter = require('../../EventEmitter/NativeEventEmitter');
<del>const KeyboardObserver = require('../../BatchedBridge/NativeModules')
<del> .KeyboardObserver;
<ide> const dismissKeyboard = require('../../Utilities/dismissKeyboard');
<del>const KeyboardEventEmitter = new NativeEventEmitter(KeyboardObserver);
<add>
<add>import NativeKeyboardObserver from './NativeKeyboardObserver';
<add>const KeyboardEventEmitter = new NativeEventEmitter(NativeKeyboardObserver);
<ide>
<ide> export type KeyboardEventName =
<ide> | 'keyboardWillShow'
<ide><path>Libraries/Components/Keyboard/NativeKeyboardObserver.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import type {TurboModule} from 'RCTExport';
<add>import * as TurboModuleRegistry from 'TurboModuleRegistry';
<add>
<add>export interface Spec extends TurboModule {
<add> +addListener: (eventName: string) => void;
<add> +removeListeners: (count: number) => void;
<add>}
<add>
<add>export default TurboModuleRegistry.get<Spec>('KeyboardObserver'); | 2 |
Text | Text | alter some lines to get better results on students | 90d615351c77d5126b56b27df700d7279a718ff8 | <ide><path>curriculum/challenges/spanish/01-responsive-web-design/basic-html-and-html5/check-radio-buttons-and-checkboxes-by-default.spanish.md
<ide> localeTitle: Comprobar botones de radio y casillas de verificación por defecto
<ide> ---
<ide>
<ide> ## Description
<del><section id="description"> Puede configurar una casilla de verificación o un botón de opción para que se marque de forma predeterminada utilizando el atributo <code>checked</code> . Para hacer esto, simplemente agregue la palabra "marcado" al interior de un elemento de entrada. Por ejemplo: <code><input type="radio" name="test-name" checked></code> </section>
<add><section id="description"> Puede configurar una casilla de verificación (<code>checkbox</code>) o un botón de opción (<code>radio button</code>) para que se marque de forma predeterminada utilizando el atributo <code>checked</code>. Para hacer esto, simplemente agregue la palabra "checked" al interior de un elemento <code>input</code>. Por ejemplo: <code><input type="radio" name="test-name" checked></code> </section>
<ide>
<ide> ## Instructions
<ide> <section id="instructions"> Configure el primero de sus <code>radio buttons</code> y el primero de sus <code>checkboxes</code> para que ambos estén marcados de forma predeterminada. </section>
<ide> localeTitle: Comprobar botones de radio y casillas de verificación por defecto
<ide>
<ide> ```yml
<ide> tests:
<del> - text: Su primer botón de radio en su formulario debe ser verificado por defecto.
<add> - text: El primer <code>radio button</code> en su formulario debe estar marcado por defecto.
<ide> testString: 'assert($("input[type="radio"]").prop("checked"), "Your first radio button on your form should be checked by default.");'
<del> - text: Su primera casilla de verificación en su formulario debe estar marcada por defecto.
<add> - text: El primer <code>checkbox</code> en su formulario debe estar marcado por defecto.
<ide> testString: 'assert($("input[type="checkbox"]").prop("checked"), "Your first checkbox on your form should be checked by default.");'
<ide>
<ide> ``` | 1 |
Python | Python | allow nested tensors in predicted logits | 0270256b275d75432d61633dfa39da1f20f987ca | <ide><path>src/transformers/trainer.py
<ide> distributed_broadcast_scalars,
<ide> distributed_concat,
<ide> nested_concat,
<add> nested_detach,
<ide> nested_numpify,
<ide> nested_xla_mesh_reduce,
<ide> set_seed,
<ide> def prediction_step(
<ide> logits = outputs[:]
<ide> if self.args.past_index >= 0:
<ide> self._past = outputs[self.args.past_index if has_labels else self.args.past_index - 1]
<add> # Remove the past from the logits.
<add> logits = logits[: self.args.past_index - 1] + logits[self.args.past_index :]
<ide>
<ide> if prediction_loss_only:
<ide> return (loss, None, None)
<ide>
<del> logits = tuple(logit.detach() for logit in logits)
<add> logits = nested_detach(logits)
<ide> if len(logits) == 1:
<ide> logits = logits[0]
<ide>
<ide> if has_labels:
<del> labels = tuple(inputs.get(name).detach() for name in self.label_names)
<add> labels = nested_detach(tuple(inputs.get(name) for name in self.label_names))
<ide> if len(labels) == 1:
<ide> labels = labels[0]
<ide> else:
<ide><path>src/transformers/trainer_utils.py
<ide> def nested_concat(tensors, new_tensors, dim=0):
<ide> raise ImportError("Torch must be installed to use `nested_concat`")
<ide>
<ide>
<add>def nested_deatch(tensors):
<add> "Detach `tensors` (even if it's a nested list/tuple of tensors)."
<add> if isinstance(tensors, (list, tuple)):
<add> return type(tensors)(nested_detach(t) for t in tensors)
<add> return tensors.detach()
<add>
<add>
<ide> def nested_numpify(tensors):
<ide> "Numpify `tensors` (even if it's a nested list/tuple of tensors)."
<ide> if isinstance(tensors, (list, tuple)): | 2 |
Javascript | Javascript | remove focus event on editor | 457bd4de171e8e47e0f344cd7e8722b1c433758b | <ide><path>client/src/templates/Challenges/classic/Editor.js
<ide> class Editor extends Component {
<ide> this._editor = null;
<ide> }
<ide>
<del> componentWillUnmount() {
<del> document.removeEventListener('keyup', this.focusEditor);
<del> }
<del>
<ide> editorWillMount = monaco => {
<ide> defineMonacoThemes(monaco);
<ide> };
<ide>
<ide> editorDidMount = (editor, monaco) => {
<ide> this._editor = editor;
<ide> this._editor.focus();
<del> document.addEventListener('keyup', this.focusEditor);
<ide> this._editor.addAction({
<ide> id: 'execute-challenge',
<ide> label: 'Run tests',
<ide> class Editor extends Component {
<ide> });
<ide> };
<ide>
<del> focusEditor = e => {
<del> // e key to focus editor
<del> if (e.keyCode === 69) {
<del> this._editor.focus();
<del> }
<del> };
<del>
<ide> onChange = editorValue => {
<ide> const { updateFile, fileKey } = this.props;
<ide> updateFile({ key: fileKey, editorValue }); | 1 |
Java | Java | remove minnumshakes from reactinstanemanager | cfa2bbf2f692d0bc5600d7e369a9a91272930ca6 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java
<ide> public interface ReactInstanceEventListener {
<ide> private final @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler;
<ide> private final boolean mLazyNativeModulesEnabled;
<ide> private final boolean mDelayViewManagerClassLoadsEnabled;
<del> private final int mMinNumShakes;
<ide>
<ide> private class ReactContextInitParams {
<ide> private final JavaScriptExecutorFactory mJsExecutorFactory;
<ide> public static ReactInstanceManagerBuilder builder() {
<ide> mNativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler;
<ide> mLazyNativeModulesEnabled = lazyNativeModulesEnabled;
<ide> mDelayViewManagerClassLoadsEnabled = delayViewManagerClassLoadsEnabled;
<del> mMinNumShakes = minNumShakes;
<ide> synchronized (mPackages) {
<ide> PrinterHolder.getPrinter()
<ide> .logMessage(ReactDebugOverlayTags.RN_CORE, "RNCore: Use Split Packages");
<ide> public LifecycleState getLifecycleState() {
<ide> return mLifecycleState;
<ide> }
<ide>
<del> public int getMinNumShakes() {
<del> return mMinNumShakes;
<del> }
<del>
<ide> @ThreadConfined(UI)
<ide> private void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) {
<ide> Log.d(ReactConstants.TAG, "ReactInstanceManager.onReloadWithJSDebugger()"); | 1 |
Python | Python | improve docstrings, ux of common user mistakes | 30118bbab0a90f77acd7d366d04c49375fa85aae | <ide><path>keras/constraints.py
<ide> def __call__(self, p):
<ide> return p
<ide>
<ide> def get_config(self):
<del> return {"name": self.__class__.__name__}
<add> return {'name': self.__class__.__name__}
<ide>
<ide>
<ide> class MaxNorm(Constraint):
<ide> def __call__(self, p):
<ide> return p
<ide>
<ide> def get_config(self):
<del> return {"name": self.__class__.__name__,
<del> "m": self.m,
<del> "axis": self.axis}
<add> return {'name': self.__class__.__name__,
<add> 'm': self.m,
<add> 'axis': self.axis}
<ide>
<ide>
<ide> class NonNeg(Constraint):
<ide> def __call__(self, p):
<ide> return p / (K.epsilon() + K.sqrt(K.sum(K.square(p), axis=self.axis, keepdims=True)))
<ide>
<ide> def get_config(self):
<del> return {"name": self.__class__.__name__,
<del> "axis": self.axis}
<add> return {'name': self.__class__.__name__,
<add> 'axis': self.axis}
<ide>
<ide>
<ide> maxnorm = MaxNorm
<ide><path>keras/engine/topology.py
<ide> def assert_input_compatibility(self, input):
<ide> raise Exception('Input ' + str(input_index) +
<ide> ' is incompatible with layer ' +
<ide> self.name + ': expected ndim >= ' +
<del> str(ndim) + ' found ndim=' +
<add> str(ndim) + ', found ndim=' +
<ide> str(K.ndim(x)))
<ide> else:
<ide> if K.ndim(x) != spec.ndim:
<ide> raise Exception('Input ' + str(input_index) +
<ide> ' is incompatible with layer ' +
<ide> self.name + ': expected ndim=' +
<del> str(spec.ndim), ' found ndim=' +
<add> str(spec.ndim) + ', found ndim=' +
<ide> str(K.ndim(x)))
<ide> if spec.dtype is not None:
<ide> if K.dtype(x) != spec.dtype:
<ide> raise Exception('Input ' + str(input_index) +
<ide> ' is incompatible with layer ' +
<ide> self.name + ': expected dtype=' +
<del> str(spec.dtype), ' found dtype=' +
<add> str(spec.dtype) + ', found dtype=' +
<ide> str(K.dtype(x)))
<ide> if spec.shape is not None:
<ide> if hasattr(x, '_keras_shape'):
<ide> def __call__(self, x, mask=None):
<ide> mask: tensor or list/tuple of tensors.
<ide> '''
<ide> if not self.built:
<add> # raise exceptions in case the input is not compatible
<add> # with the input_spec specified in the layer constructor
<add> self.assert_input_compatibility(x)
<add>
<ide> # collect input shapes to build layer
<ide> input_shapes = []
<ide> for x_elem in to_list(x):
<ide> def __call__(self, x, mask=None):
<ide> self.build(input_shapes)
<ide> self.built = True
<ide>
<del> # raise exceptions in case the input is not compatible with the layer
<add> # raise exceptions in case the input is not compatible
<add> # with the input_spec set at build time
<ide> self.assert_input_compatibility(x)
<ide> # build and connect layer
<ide> input_added = False
<ide><path>keras/engine/training.py
<del>'''TODO: docstrings
<del>'''
<ide> from __future__ import print_function
<ide> from __future__ import absolute_import
<ide>
<ide> def check_array_lengths(X, Y, W):
<ide> str(list(set_w)[0]) + ' target samples.')
<ide>
<ide>
<add>def check_loss_and_target_compatibility(targets, losses, output_shapes):
<add> assert len(targets) == len(losses) == len(output_shapes)
<add> key_losses = {'mean_square_error',
<add> 'binary_crossentropy',
<add> 'categorical_crossentropy'}
<add> for y, loss, shape in zip(targets, losses, output_shapes):
<add> if loss.__name__ == 'categorical_crossentropy':
<add> if y.shape[1] == 1:
<add> raise Exception('You are passing a target array of shape ' + str(y.shape) +
<add> ' while using as loss `categorical_crossentropy`. '
<add> '`categorical_crossentropy` expects '
<add> 'targets to be binary matrices (1s and 0s) '
<add> 'of shape (samples, classes). '
<add> 'If your targets are integer classes, '
<add> 'you can convert them to the expected format via:\n'
<add> '```\n'
<add> 'from keras.utils.np_utils import to_categorical\n'
<add> 'y_binary = to_categorical(y_int)\n'
<add> '```\n'
<add> '\n'
<add> 'Alternatively, you can use the loss function '
<add> '`sparse_categorical_crossentropy` instead, '
<add> 'which does expect integer targets.')
<add> if loss.__name__ in key_losses and y.shape[1] != shape[1]:
<add> raise Exception('A target array with shape ' + str(y.shape) +
<add> ' was passed for an output of shape ' + str(shape) +
<add> ' while using as loss `' + loss.__name__ + '`. '
<add> 'This loss expects '
<add> 'targets to have the same shape '
<add> 'as the output.')
<add>
<add>
<ide> def collect_metrics(metrics, output_names):
<ide> if not metrics:
<ide> return [[] for _ in output_names]
<ide> def weighted(y_true, y_pred, weights, mask=None):
<ide>
<ide> def standardize_weights(y, sample_weight=None, class_weight=None,
<ide> sample_weight_mode=None):
<del> '''Weight input validation and standardization to a single sample-wise
<del> (or timestep-wise) weight array.
<add> '''Performs weight input validation and standardization
<add> to a single sample-wise (or timestep-wise) weight array.
<ide> '''
<ide> if sample_weight_mode is not None:
<ide> if sample_weight_mode != 'temporal':
<ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None,
<ide> else:
<ide> loss_function = objectives.get(loss)
<ide> loss_functions = [loss_function for _ in range(len(self.outputs))]
<add> self.loss_functions = loss_functions
<ide> weighted_losses = [weighted_objective(fn) for fn in loss_functions]
<ide>
<ide> # prepare output masks
<ide> def compile(self, optimizer, loss, metrics=[], loss_weights=None,
<ide>
<ide> # prepare targets of model
<ide> self.targets = []
<del> for y, shape, name in zip(self.outputs, self.internal_output_shapes, self.output_names):
<add> for i in range(len(self.outputs)):
<add> shape = self.internal_output_shapes[i]
<add> name = self.output_names[i]
<ide> self.targets.append(K.placeholder(ndim=len(shape), name=name + '_target'))
<ide>
<ide> # compute total loss
<ide> def _standardize_user_data(self, x, y,
<ide> for (ref, sw, cw, mode)
<ide> in zip(y, sample_weights, class_weights, self.sample_weight_modes)]
<ide> check_array_lengths(x, y, sample_weights)
<add> check_loss_and_target_compatibility(y, self.loss_functions, self.internal_output_shapes)
<ide> if self.stateful and batch_size:
<ide> if x[0].shape[0] % batch_size != 0:
<ide> raise Exception('In a stateful network, '
<ide> def _standardize_user_data(self, x, y,
<ide> def fit(self, x, y, batch_size=32, nb_epoch=10, verbose=1, callbacks=[],
<ide> validation_split=0., validation_data=None, shuffle=True,
<ide> class_weight=None, sample_weight=None):
<del> '''
<add> '''Trains the model for a fixed number of epochs (iterations on a dataset).
<add>
<add> # Arguments
<add> x: Numpy array of training data,
<add> or list of Numpy arrays if the model has multiple inputs.
<add> If all inputs in the model are named, you can also pass a dictionary
<add> mapping input names to Numpy arrays.
<add> y: Numpy array of target data,
<add> or list of Numpy arrays if the model has multiple outputs.
<add> If all outputs in the model are named, you can also pass a dictionary
<add> mapping output names to Numpy arrays.
<add> batch_size: integer. Number of samples per gradient update.
<add> nb_epoch: integer, the number of times to iterate over the training data arrays.
<add> verbose: 0, 1, or 2. Verbosity mode. 0 = silent, 1 = verbose, 2 = one log line per epoch.
<add> callbacks: list of callbacks to be called during training.
<add> See [callbacks](callbacks.md).
<add> validation_split: float between 0 and 1:
<add> fraction of the training data to be used as validation data.
<add> The model will set apart this fraction of the training data,
<add> will not train on it, and will evaluate the loss and any model metrics
<add> on this data at the end of each epoch.
<add> validation_data: data on which to evaluate the loss and any model metrics
<add> at the end of each epoch. The model will not be trained on this data.
<add> This could be a tuple (x_val, y_val) or a tuple (val_x, val_y, val_sample_weights).
<add> shuffle: boolean, whether to shuffle the training data before each epoch.
<add> class_weight: optional dictionary mapping classe indices (integers) to
<add> a weight (float) to apply to the model's loss for the samples
<add> from this class during training.
<add> This can be useful to tell the model to "pay more attention" to
<add> samples from an under-represented class.
<add> sample_weight: optional array of the same length as x, containing
<add> weights to apply to the model's loss for each sample.
<add> In the case of temporal data, you can pass a 2D array
<add> with shape (samples, sequence_length),
<add> to apply a different weight to every timestep of every sample.
<add> In this case you should make sure to specify sample_weight_mode="temporal" in compile().
<add>
<add>
<add> # Returns
<add> A `History` instance. Its `history` attribute contains
<add> all information collected during training.
<ide> '''
<ide> # validate user data
<ide> x, y, sample_weights = self._standardize_user_data(x, y,
<ide> def evaluate(self, x, y, batch_size=32, verbose=1, sample_weight=None):
<ide> in test mode. Computation in done in batches.
<ide>
<ide> # Arguments
<del> TODO
<add> x: Numpy array of test data,
<add> or list of Numpy arrays if the model has multiple inputs.
<add> If all inputs in the model are named, you can also pass a dictionary
<add> mapping input names to Numpy arrays.
<add> y: Numpy array of target data,
<add> or list of Numpy arrays if the model has multiple outputs.
<add> If all outputs in the model are named, you can also pass a dictionary
<add> mapping output names to Numpy arrays.
<add> batch_size: integer. Number of samples per gradient update.
<ide>
<ide> # Returns
<ide> Scalar test loss (if the model has a single output and no metrics)
<ide> def predict(self, x, batch_size=32, verbose=0):
<ide> batch_size=batch_size, verbose=verbose)
<ide>
<ide> def train_on_batch(self, x, y, sample_weight=None, class_weight=None):
<del> '''
<add> '''Runs a single gradient update on a single batch of data.
<add>
<add> # Arguments
<add> x: Numpy array of training data,
<add> or list of Numpy arrays if the model has multiple inputs.
<add> If all inputs in the model are named, you can also pass a dictionary
<add> mapping input names to Numpy arrays.
<add> y: Numpy array of target data,
<add> or list of Numpy arrays if the model has multiple outputs.
<add> If all outputs in the model are named, you can also pass a dictionary
<add> mapping output names to Numpy arrays.
<add> sample_weight: optional array of the same length as x, containing
<add> weights to apply to the model's loss for each sample.
<add> In the case of temporal data, you can pass a 2D array
<add> with shape (samples, sequence_length),
<add> to apply a different weight to every timestep of every sample.
<add> In this case you should make sure to specify sample_weight_mode="temporal" in compile().
<add> class_weight: optional dictionary mapping classe indices (integers) to
<add> a weight (float) to apply to the model's loss for the samples
<add> from this class during training.
<add> This can be useful to tell the model to "pay more attention" to
<add> samples from an under-represented class.
<add>
<add> # Returns
<add> Scalar training loss (if the model has a single output and no metrics)
<add> or list of scalars (if the model has multiple outputs
<add> and/or metrics). The attribute `model.metrics_names` will give you
<add> the display labels for the scalar outputs.
<ide> '''
<ide> x, y, sample_weights = self._standardize_user_data(x, y,
<ide> sample_weight=sample_weight,
<ide> def train_on_batch(self, x, y, sample_weight=None, class_weight=None):
<ide> return outputs
<ide>
<ide> def test_on_batch(self, x, y, sample_weight=None):
<del> '''
<add> '''Test the model on a single batch of samples.
<add>
<add> # Arguments
<add> x: Numpy array of test data,
<add> or list of Numpy arrays if the model has multiple inputs.
<add> If all inputs in the model are named, you can also pass a dictionary
<add> mapping input names to Numpy arrays.
<add> y: Numpy array of target data,
<add> or list of Numpy arrays if the model has multiple outputs.
<add> If all outputs in the model are named, you can also pass a dictionary
<add> mapping output names to Numpy arrays.
<add> sample_weight: optional array of the same length as x, containing
<add> weights to apply to the model's loss for each sample.
<add> In the case of temporal data, you can pass a 2D array
<add> with shape (samples, sequence_length),
<add> to apply a different weight to every timestep of every sample.
<add> In this case you should make sure to specify sample_weight_mode="temporal" in compile().
<add>
<add> # Returns
<add> Scalar test loss (if the model has a single output and no metrics)
<add> or list of scalars (if the model has multiple outputs
<add> and/or metrics). The attribute `model.metrics_names` will give you
<add> the display labels for the scalar outputs.
<ide> '''
<ide> x, y, sample_weights = self._standardize_user_data(x, y,
<ide> sample_weight=sample_weight,
<ide><path>keras/layers/advanced_activations.py
<ide> class LeakyReLU(Layer):
<ide> '''Special version of a Rectified Linear Unit
<ide> that allows a small gradient when the unit is not active:
<del> `f(x) = alpha*x for x < 0`.
<add> `f(x) = alpha * x for x < 0`,
<add> `f(x) = x for x >= 0`.
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> def get_config(self):
<ide>
<ide>
<ide> class PReLU(Layer):
<del> '''Parametric Rectified Linear Unit.
<add> '''Parametric Rectified Linear Unit:
<add> `f(x) = alphas * x for x < 0`,
<add> `f(x) = x for x >= 0`,
<add> where `alphas` is a learned array with the same shape as x.
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> class PReLU(Layer):
<ide> init: initialization function for the weights.
<ide> weights: initial weights, as a list of a single numpy array.
<ide>
<del> # References:
<add> # References
<ide> - [Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification](http://arxiv.org/pdf/1502.01852v1.pdf)
<ide> '''
<ide> def __init__(self, init='zero', weights=None, **kwargs):
<ide> def get_config(self):
<ide>
<ide>
<ide> class ELU(Layer):
<del> '''Exponential Linear Unit.
<add> '''Exponential Linear Unit:
<add> `f(x) = alpha * (exp(x) - 1.) for x < 0`,
<add> `f(x) = x for x >= 0`.
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> def get_config(self):
<ide>
<ide>
<ide> class ParametricSoftplus(Layer):
<del> '''Parametric Softplus of the form: alpha * log(1 + exp(beta * X))
<add> '''Parametric Softplus:
<add> `alpha * log(1 + exp(beta * x))`
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> class ParametricSoftplus(Layer):
<ide> beta_init: float. Initial values of the beta weights.
<ide> weights: initial weights, as a list of 2 numpy arrays.
<ide>
<del> # References:
<add> # References
<ide> - [Inferring Nonlinear Neuronal Computation Based on Physiologically Plausible Inputs](http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1003143)
<ide> '''
<ide> def __init__(self, alpha_init=0.2, beta_init=5.0,
<ide> def get_config(self):
<ide> return dict(list(base_config.items()) + list(config.items()))
<ide>
<ide>
<del>class ThresholdedLinear(Layer):
<del> '''Thresholded Linear Activation.
<del>
<del> # Input shape
<del> Arbitrary. Use the keyword argument `input_shape`
<del> (tuple of integers, does not include the samples axis)
<del> when using this layer as the first layer in a model.
<del>
<del> # Output shape
<del> Same shape as the input.
<del>
<del> # Arguments
<del> theta: float >= 0. Threshold location of activation.
<del>
<del> # References
<del> [Zero-Bias Autoencoders and the Benefits of Co-Adapting Features](http://arxiv.org/pdf/1402.3337.pdf)
<del> '''
<del> def __init__(self, theta=1.0, **kwargs):
<del> self.supports_masking = True
<del> self.theta = K.cast_to_floatx(theta)
<del> super(ThresholdedLinear, self).__init__(**kwargs)
<del>
<del> def call(self, x, mask=None):
<del> return x * K.cast(x > self.theta, K.floatx())
<del>
<del> def get_config(self):
<del> config = {'theta': self.theta}
<del> base_config = super(ThresholdedLinear, self).get_config()
<del> return dict(list(base_config.items()) + list(config.items()))
<del>
<del>
<ide> class ThresholdedReLU(Layer):
<del> '''Thresholded Rectified Linear Unit.
<add> '''Thresholded Rectified Linear Unit:
<add> `f(x) = x for x > theta`
<add> `f(x) = 0 otherwise`.
<ide>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> class ThresholdedReLU(Layer):
<ide> theta: float >= 0. Threshold location of activation.
<ide>
<ide> # References
<del> [Zero-Bias Autoencoders and the Benefits of Co-Adapting Features](http://arxiv.org/pdf/1402.3337.pdf)
<add> - [Zero-Bias Autoencoders and the Benefits of Co-Adapting Features](http://arxiv.org/pdf/1402.3337.pdf)
<ide> '''
<ide> def __init__(self, theta=1.0, **kwargs):
<ide> self.supports_masking = True
<ide> class SReLU(Layer):
<ide> a_right_init: initialization function for the right part slope
<ide>
<ide> # References
<del> [Deep Learning with S-shaped Rectified Linear Activation Units](http://arxiv.org/abs/1512.07030)
<add> - [Deep Learning with S-shaped Rectified Linear Activation Units](http://arxiv.org/abs/1512.07030)
<ide> '''
<ide> def __init__(self, t_left_init='zero', a_left_init='glorot_uniform',
<ide> t_right_init='glorot_uniform', a_right_init='one', **kwargs):
<ide><path>keras/layers/convolutional.py
<ide> class Convolution1D(Layer):
<ide> or `input_shape` (tuple of integers, e.g. (10, 128) for sequences
<ide> of 10 vectors of 128-dimensional vectors).
<ide>
<del> # Input shape
<del> 3D tensor with shape: `(samples, steps, input_dim)`.
<add> # Example
<ide>
<del> # Output shape
<del> 3D tensor with shape: `(samples, new_steps, nb_filter)`.
<del> `steps` value might have changed due to padding.
<add> ```python
<add> # apply a convolution 1d of length 3 to a sequence with 10 timesteps,
<add> # with 64 output filters
<add> model = Sequential()
<add> model.add(Convolution1D(64, 3, border_mode='same', input_shape=(10, 32)))
<add> # now model.output_shape == (None, 10, 64)
<add>
<add> # add a new conv1d on top
<add> model.add(Convolution1D(32, 3, border_mode='same'))
<add> # now model.output_shape == (None, 10, 32)
<add> ```
<ide>
<ide> # Arguments
<ide> nb_filter: Number of convolution kernels to use
<ide> class Convolution1D(Layer):
<ide> This argument is required if you are going to connect
<ide> `Flatten` then `Dense` layers upstream
<ide> (without it, the shape of the dense outputs cannot be computed).
<add>
<add> # Input shape
<add> 3D tensor with shape: `(samples, steps, input_dim)`.
<add>
<add> # Output shape
<add> 3D tensor with shape: `(samples, new_steps, nb_filter)`.
<add> `steps` value might have changed due to padding.
<ide> '''
<ide> def __init__(self, nb_filter, filter_length,
<ide> init='uniform', activation='linear', weights=None,
<ide> class Convolution2D(Layer):
<ide> (tuple of integers, does not include the sample axis),
<ide> e.g. `input_shape=(3, 128, 128)` for 128x128 RGB pictures.
<ide>
<del> # Input shape
<del> 4D tensor with shape:
<del> `(samples, channels, rows, cols)` if dim_ordering='th'
<del> or 4D tensor with shape:
<del> `(samples, rows, cols, channels)` if dim_ordering='tf'.
<add> # Examples
<ide>
<del> # Output shape
<del> 4D tensor with shape:
<del> `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th'
<del> or 4D tensor with shape:
<del> `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'.
<del> `rows` and `cols` values might have changed due to padding.
<add> ```python
<add> # apply a 3x3 convolution with 64 output filters on a 256x256 image:
<add> model = Sequential()
<add> model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 256, 256)))
<add> # now model.output_shape == (None, 64, 256, 256)
<ide>
<add> # add a 3x3 convolution on top, with 32 output filters:
<add> model.add(Convolution2D(32, 3, 3, border_mode='same'))
<add> # now model.output_shape == (None, 32, 256, 256)
<add> ```
<ide>
<ide> # Arguments
<ide> nb_filter: Number of convolution filters to use.
<ide> class Convolution2D(Layer):
<ide> applied to the bias.
<ide> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<ide> (the depth) is at index 1, in 'tf' mode is it at index 3.
<add>
<add> # Input shape
<add> 4D tensor with shape:
<add> `(samples, channels, rows, cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, rows, cols, channels)` if dim_ordering='tf'.
<add>
<add> # Output shape
<add> 4D tensor with shape:
<add> `(samples, nb_filter, new_rows, new_cols)` if dim_ordering='th'
<add> or 4D tensor with shape:
<add> `(samples, new_rows, new_cols, nb_filter)` if dim_ordering='tf'.
<add> `rows` and `cols` values might have changed due to padding.
<ide> '''
<ide> def __init__(self, nb_filter, nb_row, nb_col,
<ide> init='glorot_uniform', activation='linear', weights=None,
<ide> class Convolution3D(Layer):
<ide>
<ide> Note: this layer will only work with Theano for the time being.
<ide>
<del> # Input shape
<del> 5D tensor with shape:
<del> `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if dim_ordering='th'
<del> or 5D tensor with shape:
<del> `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if dim_ordering='tf'.
<del>
<del> # Output shape
<del> 5D tensor with shape:
<del> `(samples, nb_filter, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if dim_ordering='th'
<del> or 5D tensor with shape:
<del> `(samples, new_conv_dim1, new_conv_dim2, new_conv_dim3, nb_filter)` if dim_ordering='tf'.
<del> `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding.
<del>
<ide> # Arguments
<ide> nb_filter: Number of convolution filters to use.
<ide> kernel_dim1: Length of the first dimension in the covolution kernel.
<ide> class Convolution3D(Layer):
<ide> applied to the bias.
<ide> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<ide> (the depth) is at index 1, in 'tf' mode is it at index 4.
<add>
<add> # Input shape
<add> 5D tensor with shape:
<add> `(samples, channels, conv_dim1, conv_dim2, conv_dim3)` if dim_ordering='th'
<add> or 5D tensor with shape:
<add> `(samples, conv_dim1, conv_dim2, conv_dim3, channels)` if dim_ordering='tf'.
<add>
<add> # Output shape
<add> 5D tensor with shape:
<add> `(samples, nb_filter, new_conv_dim1, new_conv_dim2, new_conv_dim3)` if dim_ordering='th'
<add> or 5D tensor with shape:
<add> `(samples, new_conv_dim1, new_conv_dim2, new_conv_dim3, nb_filter)` if dim_ordering='tf'.
<add> `new_conv_dim1`, `new_conv_dim2` and `new_conv_dim3` values might have changed due to padding.
<ide> '''
<ide>
<ide> def __init__(self, nb_filter, kernel_dim1, kernel_dim2, kernel_dim3,
<ide> def _pooling_function(self, inputs, pool_size, strides,
<ide> class AveragePooling1D(_Pooling1D):
<ide> '''Average pooling for temporal data.
<ide>
<del> # Input shape
<del> 3D tensor with shape: `(samples, steps, features)`.
<del>
<del> # Output shape
<del> 3D tensor with shape: `(samples, downsampled_steps, features)`.
<del>
<ide> # Arguments
<ide> pool_length: factor by which to downscale. 2 will halve the input.
<ide> stride: integer or None. Stride value.
<ide> border_mode: 'valid' or 'same'.
<ide> Note: 'same' will only work with TensorFlow for the time being.
<add>
<add> # Input shape
<add> 3D tensor with shape: `(samples, steps, features)`.
<add>
<add> # Output shape
<add> 3D tensor with shape: `(samples, downsampled_steps, features)`.
<ide> '''
<ide>
<ide> def __init__(self, pool_length=2, stride=None,
<ide> def get_config(self):
<ide> class MaxPooling2D(_Pooling2D):
<ide> '''Max pooling operation for spatial data.
<ide>
<add> # Arguments
<add> pool_size: tuple of 2 integers,
<add> factors by which to downscale (vertical, horizontal).
<add> (2, 2) will halve the image in each dimension.
<add> strides: tuple of 2 integers, or None. Strides values.
<add> border_mode: 'valid' or 'same'.
<add> Note: 'same' will only work with TensorFlow for the time being.
<add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<add> (the depth) is at index 1, in 'tf' mode is it at index 3.
<add>
<ide> # Input shape
<ide> 4D tensor with shape:
<ide> `(samples, channels, rows, cols)` if dim_ordering='th'
<ide> class MaxPooling2D(_Pooling2D):
<ide> `(nb_samples, channels, pooled_rows, pooled_cols)` if dim_ordering='th'
<ide> or 4D tensor with shape:
<ide> `(samples, pooled_rows, pooled_cols, channels)` if dim_ordering='tf'.
<del>
<del> # Arguments
<del> pool_size: tuple of 2 integers,
<del> factors by which to downscale (vertical, horizontal).
<del> (2, 2) will halve the image in each dimension.
<del> strides: tuple of 2 integers, or None. Strides values.
<del> border_mode: 'valid' or 'same'.
<del> Note: 'same' will only work with TensorFlow for the time being.
<del> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<del> (the depth) is at index 1, in 'tf' mode is it at index 3.
<ide> '''
<ide>
<ide> def __init__(self, pool_size=(2, 2), strides=None, border_mode='valid',
<ide> def _pooling_function(self, inputs, pool_size, strides,
<ide> class AveragePooling2D(_Pooling2D):
<ide> '''Average pooling operation for spatial data.
<ide>
<add> # Arguments
<add> pool_size: tuple of 2 integers,
<add> factors by which to downscale (vertical, horizontal).
<add> (2, 2) will halve the image in each dimension.
<add> strides: tuple of 2 integers, or None. Strides values.
<add> border_mode: 'valid' or 'same'.
<add> Note: 'same' will only work with TensorFlow for the time being.
<add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<add> (the depth) is at index 1, in 'tf' mode is it at index 3.
<add>
<ide> # Input shape
<ide> 4D tensor with shape:
<ide> `(samples, channels, rows, cols)` if dim_ordering='th'
<ide> class AveragePooling2D(_Pooling2D):
<ide> `(nb_samples, channels, pooled_rows, pooled_cols)` if dim_ordering='th'
<ide> or 4D tensor with shape:
<ide> `(samples, pooled_rows, pooled_cols, channels)` if dim_ordering='tf'.
<del>
<del> # Arguments
<del> pool_size: tuple of 2 integers,
<del> factors by which to downscale (vertical, horizontal).
<del> (2, 2) will halve the image in each dimension.
<del> strides: tuple of 2 integers, or None. Strides values.
<del> border_mode: 'valid' or 'same'.
<del> Note: 'same' will only work with TensorFlow for the time being.
<del> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<del> (the depth) is at index 1, in 'tf' mode is it at index 3.
<ide> '''
<ide>
<ide> def __init__(self, pool_size=(2, 2), strides=None, border_mode='valid',
<ide> class MaxPooling3D(_Pooling3D):
<ide>
<ide> Note: this layer will only work with Theano for the time being.
<ide>
<add> # Arguments
<add> pool_size: tuple of 3 integers,
<add> factors by which to downscale (dim1, dim2, dim3).
<add> (2, 2, 2) will halve the size of the 3D input in each dimension.
<add> strides: tuple of 3 integers, or None. Strides values.
<add> border_mode: 'valid' or 'same'.
<add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<add> (the depth) is at index 1, in 'tf' mode is it at index 4.
<add>
<ide> # Input shape
<ide> 5D tensor with shape:
<ide> `(samples, channels, len_pool_dim1, len_pool_dim2, len_pool_dim3)` if dim_ordering='th'
<ide> class MaxPooling3D(_Pooling3D):
<ide> `(nb_samples, channels, pooled_dim1, pooled_dim2, pooled_dim3)` if dim_ordering='th'
<ide> or 5D tensor with shape:
<ide> `(samples, pooled_dim1, pooled_dim2, pooled_dim3, channels)` if dim_ordering='tf'.
<del>
<del> # Arguments
<del> pool_size: tuple of 3 integers,
<del> factors by which to downscale (dim1, dim2, dim3).
<del> (2, 2, 2) will halve the size of the 3D input in each dimension.
<del> strides: tuple of 3 integers, or None. Strides values.
<del> border_mode: 'valid' or 'same'.
<del> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<del> (the depth) is at index 1, in 'tf' mode is it at index 4.
<ide> '''
<ide>
<ide> def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid',
<ide> class AveragePooling3D(_Pooling3D):
<ide>
<ide> Note: this layer will only work with Theano for the time being.
<ide>
<add> # Arguments
<add> pool_size: tuple of 3 integers,
<add> factors by which to downscale (dim1, dim2, dim3).
<add> (2, 2, 2) will halve the size of the 3D input in each dimension.
<add> strides: tuple of 3 integers, or None. Strides values.
<add> border_mode: 'valid' or 'same'.
<add> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<add> (the depth) is at index 1, in 'tf' mode is it at index 4.
<add>
<ide> # Input shape
<ide> 5D tensor with shape:
<ide> `(samples, channels, len_pool_dim1, len_pool_dim2, len_pool_dim3)` if dim_ordering='th'
<ide> class AveragePooling3D(_Pooling3D):
<ide> `(nb_samples, channels, pooled_dim1, pooled_dim2, pooled_dim3)` if dim_ordering='th'
<ide> or 5D tensor with shape:
<ide> `(samples, pooled_dim1, pooled_dim2, pooled_dim3, channels)` if dim_ordering='tf'.
<del>
<del> # Arguments
<del> pool_size: tuple of 3 integers,
<del> factors by which to downscale (dim1, dim2, dim3).
<del> (2, 2, 2) will halve the size of the 3D input in each dimension.
<del> strides: tuple of 3 integers, or None. Strides values.
<del> border_mode: 'valid' or 'same'.
<del> dim_ordering: 'th' or 'tf'. In 'th' mode, the channels dimension
<del> (the depth) is at index 1, in 'tf' mode is it at index 4.
<ide> '''
<ide>
<ide> def __init__(self, pool_size=(2, 2, 2), strides=None, border_mode='valid',
<ide> def _pooling_function(self, inputs, pool_size, strides,
<ide> class UpSampling1D(Layer):
<ide> '''Repeat each temporal step `length` times along the time axis.
<ide>
<add> # Arguments:
<add> length: integer. Upsampling factor.
<add>
<ide> # Input shape
<ide> 3D tensor with shape: `(samples, steps, features)`.
<ide>
<ide> # Output shape
<ide> 3D tensor with shape: `(samples, upsampled_steps, features)`.
<del>
<del> # Arguments:
<del> length: integer. Upsampling factor.
<ide> '''
<ide>
<ide> def __init__(self, length=2, **kwargs):
<ide> class UpSampling2D(Layer):
<ide> '''Repeat the rows and columns of the data
<ide> by size[0] and size[1] respectively.
<ide>
<add> # Arguments
<add> size: tuple of 2 integers. The upsampling factors for rows and columns.
<add> dim_ordering: 'th' or 'tf'.
<add> In 'th' mode, the channels dimension (the depth)
<add> is at index 1, in 'tf' mode is it at index 3.
<add>
<ide> # Input shape
<ide> 4D tensor with shape:
<ide> `(samples, channels, rows, cols)` if dim_ordering='th'
<ide> class UpSampling2D(Layer):
<ide> `(samples, channels, upsampled_rows, upsampled_cols)` if dim_ordering='th'
<ide> or 4D tensor with shape:
<ide> `(samples, upsampled_rows, upsampled_cols, channels)` if dim_ordering='tf'.
<del>
<del> # Arguments
<del> size: tuple of 2 integers. The upsampling factors for rows and columns.
<del> dim_ordering: 'th' or 'tf'.
<del> In 'th' mode, the channels dimension (the depth)
<del> is at index 1, in 'tf' mode is it at index 3.
<ide> '''
<ide>
<ide> def __init__(self, size=(2, 2), dim_ordering='th', **kwargs):
<ide> class UpSampling3D(Layer):
<ide>
<ide> Note: this layer will only work with Theano for the time being.
<ide>
<add> # Arguments
<add> size: tuple of 3 integers. The upsampling factors for dim1, dim2 and dim3.
<add> dim_ordering: 'th' or 'tf'.
<add> In 'th' mode, the channels dimension (the depth)
<add> is at index 1, in 'tf' mode is it at index 4.
<add>
<ide> # Input shape
<ide> 5D tensor with shape:
<ide> `(samples, channels, dim1, dim2, dim3)` if dim_ordering='th'
<ide> class UpSampling3D(Layer):
<ide> `(samples, channels, upsampled_dim1, upsampled_dim2, upsampled_dim3)` if dim_ordering='th'
<ide> or 5D tensor with shape:
<ide> `(samples, upsampled_dim1, upsampled_dim2, upsampled_dim3, channels)` if dim_ordering='tf'.
<del>
<del> # Arguments
<del> size: tuple of 3 integers. The upsampling factors for dim1, dim2 and dim3.
<del> dim_ordering: 'th' or 'tf'.
<del> In 'th' mode, the channels dimension (the depth)
<del> is at index 1, in 'tf' mode is it at index 4.
<ide> '''
<ide>
<ide> def __init__(self, size=(2, 2, 2), dim_ordering='th', **kwargs):
<ide> def get_config(self):
<ide> class ZeroPadding1D(Layer):
<ide> '''Zero-padding layer for 1D input (e.g. temporal sequence).
<ide>
<add> # Arguments
<add> padding: int
<add> How many zeros to add at the beginning and end of
<add> the padding dimension (axis 1).
<add>
<ide> # Input shape
<ide> 3D tensor with shape (samples, axis_to_pad, features)
<ide>
<ide> # Output shape
<ide> 3D tensor with shape (samples, padded_axis, features)
<del>
<del> # Arguments
<del> padding: int
<del> How many zeros to add at the beginning and end of
<del> the padding dimension (axis 1).
<ide> '''
<ide>
<ide> def __init__(self, padding=1, **kwargs):
<ide> def get_config(self):
<ide> class ZeroPadding2D(Layer):
<ide> '''Zero-padding layer for 2D input (e.g. picture).
<ide>
<add> # Arguments
<add> padding: tuple of int (length 2)
<add> How many zeros to add at the beginning and end of
<add> the 2 padding dimensions (axis 3 and 4).
<add>
<ide> # Input shape
<ide> 4D tensor with shape:
<ide> (samples, depth, first_axis_to_pad, second_axis_to_pad)
<ide>
<ide> # Output shape
<ide> 4D tensor with shape:
<ide> (samples, depth, first_padded_axis, second_padded_axis)
<del>
<del> # Arguments
<del> padding: tuple of int (length 2)
<del> How many zeros to add at the beginning and end of
<del> the 2 padding dimensions (axis 3 and 4).
<ide> '''
<ide>
<ide> def __init__(self, padding=(1, 1), dim_ordering='th', **kwargs):
<ide> class ZeroPadding3D(Layer):
<ide>
<ide> Note: this layer will only work with Theano for the time being.
<ide>
<add> # Arguments
<add> padding: tuple of int (length 3)
<add> How many zeros to add at the beginning and end of
<add> the 3 padding dimensions (axis 3, 4 and 5).
<add>
<ide> # Input shape
<ide> 5D tensor with shape:
<ide> (samples, depth, first_axis_to_pad, second_axis_to_pad, third_axis_to_pad)
<ide>
<ide> # Output shape
<ide> 5D tensor with shape:
<ide> (samples, depth, first_padded_axis, second_padded_axis, third_axis_to_pad)
<del>
<del> # Arguments
<del> padding: tuple of int (length 3)
<del> How many zeros to add at the beginning and end of
<del> the 3 padding dimensions (axis 3, 4 and 5).
<ide> '''
<ide>
<ide> def __init__(self, padding=(1, 1, 1), dim_ordering='th', **kwargs):
<ide><path>keras/layers/core.py
<ide> class Reshape(Layer):
<ide>
<ide> # Output shape
<ide> `(batch_size,) + target_shape`
<add>
<add> # Example
<add>
<add> ```python
<add> # as first layer in a Sequential model
<add> model = Sequential()
<add> model.add(Reshape((3, 4), input_shape=(12,)))
<add> # now: model.output_shape == (None, 3, 4)
<add> # note: `None` is the batch dimension
<add>
<add> # as intermediate layer in a Sequential model
<add> model.add(Reshape((6, 2)))
<add> # now: model.output_shape == (None, 6, 2)
<add> ```
<ide> '''
<ide> def __init__(self, target_shape, **kwargs):
<ide> super(Reshape, self).__init__(**kwargs)
<ide> class Permute(Layer):
<ide>
<ide> Useful for e.g. connecting RNNs and convnets together.
<ide>
<add> # Example
<add>
<add> ```python
<add> model = Sequential()
<add> model.add(Permute((2, 1), input_shape=(10, 64)))
<add> # now: model.output_shape == (None, 64, 10)
<add> # note: `None` is the batch dimension
<add> ```
<add>
<ide> # Arguments
<ide> dims: Tuple of integers. Permutation pattern, does not include the
<ide> samples dimension. Indexing starts at 1.
<ide> def get_config(self):
<ide> class Flatten(Layer):
<ide> '''Flattens the input. Does not affect the batch size.
<ide>
<add> # Example
<add>
<add> ```python
<add> model = Sequential()
<add> model.add(Convolution2D(64, 3, 3, border_mode='same', input_shape=(3, 32, 32)))
<add> # now: model.output_shape == (None, 64, 32, 32)
<add>
<add> model.add(Flatten())
<add> # now: model.output_shape == (None, 65536)
<add> ```
<add>
<ide> # Input shape
<ide> Arbitrary, although all dimensions in the input shape must be fixed.
<ide> Use the keyword argument `input_shape`
<ide> def call(self, x, mask=None):
<ide>
<ide>
<ide> class RepeatVector(Layer):
<del> '''Repeat the input n times.
<add> '''Repeats the input n times.
<add>
<add> # Example
<add>
<add> ```python
<add> model = Sequential()
<add> model.add(Dense(32, input_dim=32))
<add> # now: model.output_shape == (None, 32)
<add> # note: `None` is the batch dimension
<add>
<add> model.add(RepeatVector(3))
<add> # now: model.output_shape == (None, 3, 32)
<add> ```
<ide>
<ide> # Arguments
<ide> n: integer, repetition factor.
<ide> class Lambda(Layer):
<ide> '''Used for evaluating an arbitrary Theano / TensorFlow expression
<ide> on the output of the previous layer.
<ide>
<del> # Arguments
<del> function: The function to be evaluated.
<del> Takes one argument: the output of previous layer
<del> output_shape: Expected output shape from function.
<del> Could be a tuple or a function of the shape of the input
<del> arguments: optional dictionary of keyword arguments to be passed
<del> to the function.
<del>
<del> # Input shape
<del> Arbitrary. Use the keyword argument input_shape
<del> (tuple of integers, does not include the samples axis)
<del> when using this layer as the first layer in a model.
<del>
<del> # Output shape
<del> Specified by `output_shape` argument.
<del>
<ide> # Examples
<ide>
<ide> ```python
<ide> def antirectifier_output_shape(input_shape):
<ide>
<ide> model.add(Lambda(antirectifier, output_shape=antirectifier_output_shape))
<ide> ```
<add>
<add> # Arguments
<add> function: The function to be evaluated.
<add> Takes one argument: the output of previous layer
<add> output_shape: Expected output shape from function.
<add> Could be a tuple or a function of the shape of the input
<add> arguments: optional dictionary of keyword arguments to be passed
<add> to the function.
<add>
<add> # Input shape
<add> Arbitrary. Use the keyword argument input_shape
<add> (tuple of integers, does not include the samples axis)
<add> when using this layer as the first layer in a model.
<add>
<add> # Output shape
<add> Specified by `output_shape` argument.
<ide> '''
<ide> def __init__(self, function, output_shape=None, arguments={}, **kwargs):
<ide> self.function = function
<ide> def from_config(cls, config):
<ide> class Dense(Layer):
<ide> '''Just your regular fully connected NN layer.
<ide>
<add> # Example
<add>
<add> ```python
<add> # as first layer in a sequential model:
<add> model = Sequential(Dense(32, input_dim=16))
<add> # now the model will take as input arrays of shape (*, 16)
<add> # and output arrays of shape (*, 32)
<add>
<add> # this is equivalent to the above:
<add> model = Sequential(Dense(32, input_shape=(16,)))
<add>
<add> # after the first layer, you don't need to specify
<add> # the size of the input anymore:
<add> model.add(Dense(32))
<add> ```
<add>
<ide> # Arguments
<ide> output_dim: int > 0.
<ide> init: name of initialization function for the weights of the layer
<ide> def get_config(self):
<ide> class TimeDistributedDense(Layer):
<ide> '''Apply a same Dense layer for each dimension[1] (time_dimension) input.
<ide> Especially useful after a recurrent network with 'return_sequence=True'.
<add>
<add> Note: this layer is deprecated, prefer using the `TimeDistributed` wrapper:
<add> ```python
<add> model.add(TimeDistributed(Dense(32)))
<add> ```
<add>
<ide> # Input shape
<ide> 3D tensor with shape `(nb_sample, time_dimension, input_dim)`.
<ide> # Output shape
<ide><path>keras/layers/embeddings.py
<ide> class Embedding(Layer):
<ide>
<ide> This layer can only be used as the first layer in a model.
<ide>
<del> # Input shape
<del> 2D tensor with shape: `(nb_samples, sequence_length)`.
<add> # Example
<ide>
<del> # Output shape
<del> 3D tensor with shape: `(nb_samples, sequence_length, output_dim)`.
<add> ```python
<add> model = Sequential()
<add> model.add(Embedding(1000, 64, input_length=10))
<add> # the model will take as input an integer matrix of size (batch, input_length).
<add> # the largest integer (i.e. word index) in the input should be no larger than 1000 (vocabulary size).
<add> # now model.output_shape == (None, 10, 64), where None is the batch dimension.
<add>
<add> input_array = np.random.randint(1000, size=(32, 10))
<add>
<add> model.compile('rmsprop', 'mse')
<add> output_array = model.predict(input_array)
<add> assert output_array.shape == (32, 10, 64)
<add> ```
<ide>
<ide> # Arguments
<ide> input_dim: int >= 0. Size of the vocabulary, ie.
<ide> class Embedding(Layer):
<ide> (without it, the shape of the dense outputs cannot be computed).
<ide> dropout: float between 0 and 1. Fraction of the embeddings to drop.
<ide>
<add> # Input shape
<add> 2D tensor with shape: `(nb_samples, sequence_length)`.
<add>
<add> # Output shape
<add> 3D tensor with shape: `(nb_samples, sequence_length, output_dim)`.
<add>
<ide> # References
<ide> - [A Theoretically Grounded Application of Dropout in Recurrent Neural Networks](http://arxiv.org/abs/1512.05287)
<ide> '''
<ide><path>keras/layers/noise.py
<ide> class GaussianNoise(Layer):
<ide>
<ide> As it is a regularization layer, it is only active at training time.
<ide>
<add> # Arguments
<add> sigma: float, standard deviation of the noise distribution.
<add>
<ide> # Input shape
<ide> Arbitrary. Use the keyword argument `input_shape`
<ide> (tuple of integers, does not include the samples axis)
<ide> when using this layer as the first layer in a model.
<ide>
<ide> # Output shape
<ide> Same shape as input.
<del>
<del> # Arguments
<del> sigma: float, standard deviation of the noise distribution.
<ide> '''
<ide> def __init__(self, sigma, **kwargs):
<ide> self.supports_masking = True
<ide> class GaussianDropout(Layer):
<ide> # Arguments
<ide> p: float, drop probability (as with `Dropout`).
<ide>
<add> # Input shape
<add> Arbitrary. Use the keyword argument `input_shape`
<add> (tuple of integers, does not include the samples axis)
<add> when using this layer as the first layer in a model.
<add>
<add> # Output shape
<add> Same shape as input.
<add>
<ide> # References:
<ide> [Dropout: A Simple Way to Prevent Neural Networks from Overfitting Srivastava, Hinton, et al. 2014](http://www.cs.toronto.edu/~rsalakhu/papers/srivastava14a.pdf)
<ide> '''
<ide><path>keras/layers/normalization.py
<ide> class BatchNormalization(Layer):
<ide> i.e. applies a transformation that maintains the mean activation
<ide> close to 0 and the activation standard deviation close to 1.
<ide>
<del> # Input shape
<del> Arbitrary. Use the keyword argument `input_shape`
<del> (tuple of integers, does not include the samples axis)
<del> when using this layer as the first layer in a model.
<del>
<del> # Output shape
<del> Same shape as input.
<del>
<ide> # Arguments
<ide> epsilon: small float > 0. Fuzz parameter.
<ide> mode: integer, 0 or 1.
<ide> class BatchNormalization(Layer):
<ide> [initializations](../initializations.md)), or alternatively,
<ide> Theano/TensorFlow function to use for weights initialization.
<ide> This parameter is only relevant if you don't pass a `weights` argument.
<add>
<add> # Input shape
<add> Arbitrary. Use the keyword argument `input_shape`
<add> (tuple of integers, does not include the samples axis)
<add> when using this layer as the first layer in a model.
<add>
<add> # Output shape
<add> Same shape as input.
<add>
<ide> # References
<ide> - [Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift](http://arxiv.org/pdf/1502.03167v3.pdf)
<ide> '''
<ide><path>keras/layers/recurrent.py
<ide> class Recurrent(Layer):
<ide> follow the specifications of this class and accept
<ide> the keyword arguments listed below.
<ide>
<add> # Example
<add>
<add> ```python
<add> # as the first layer in a Sequential model
<add> model = Sequential()
<add> model.add(LSTM(32, input_shape=(10, 64)))
<add> # now model.output_shape == (None, 10, 32)
<add> # note: `None` is the batch dimension.
<add>
<add> # the following is identical:
<add> model = Sequential()
<add> model.add(LSTM(32, input_dim=64, input_length=10))
<add>
<add> # for subsequent layers, not need to specify the input size:
<add> model.add(LSTM(16))
<add> ```
<add>
<ide> # Arguments
<ide> weights: list of numpy arrays to set as initial weights.
<ide> The list should have 3 elements, of shapes:
<ide><path>keras/layers/wrappers.py
<ide> class TimeDistributed(Wrapper):
<ide>
<ide> You can then use `TimeDistributed` to apply a `Dense` layer to each of the 10 timesteps, independently:
<ide> ```python
<add> # as the first layer in a model
<ide> model = Sequential()
<ide> model.add(TimeDistributed(Dense(8), input_shape=(10, 16)))
<add> # now model.output_shape == (None, 10, 8)
<add>
<add> # subsequent layers: no need for input_shape
<add> model.add(TimeDistributed(Dense(32)))
<add> # now model.output_shape == (None, 10, 32)
<ide> ```
<ide>
<ide> The output will then have shape `(32, 10, 8)`.
<ide><path>keras/models.py
<ide> def constraints(self):
<ide> return self._gather_dict_attr('constraints')
<ide>
<ide> def get_weights(self):
<add> '''Returns the weights of the model,
<add> as a flat list of Numpy arrays.
<add> '''
<ide> # support for legacy behavior
<ide> weights = []
<ide> for layer in self.flattened_layers:
<ide> weights += layer.get_weights()
<ide> return weights
<ide>
<ide> def set_weights(self, weights):
<add> '''Sets the weights of the model.
<add> The `weights` argument should be a list
<add> of Numpy arrays with shapes and types matching
<add> the output of `model.get_weights()`.
<add> '''
<ide> # support for legacy behavior
<ide> for layer in self.flattened_layers:
<ide> nb_param = len(layer.get_weights())
<ide> def evaluate(self, x, y, batch_size=32, verbose=1,
<ide> sample_weight=sample_weight)
<ide>
<ide> def predict(self, x, batch_size=32, verbose=0):
<add> '''Generates output predictions for the input samples,
<add> processing the samples in a batched way.
<add>
<add> # Arguments
<add> x: the input data, as a Numpy array.
<add> batch_size: integer.
<add> verbose: verbosity mode, 0 or 1.
<add>
<add> # Returns
<add> A Numpy array of predictions.
<add> '''
<ide> return self.model.predict(x, batch_size=batch_size, verbose=verbose)
<ide>
<ide> def predict_on_batch(self, x):
<add> '''Returns predictions for a single batch of samples.
<add> '''
<ide> return self.model.predict_on_batch(x)
<ide>
<ide> def train_on_batch(self, x, y, class_weight=None,
<ide> def evaluate_generator(self, generator, val_samples,
<ide> val_samples)
<ide>
<ide> def get_config(self):
<del> '''
<del> how to handle Merge layers:
<del> encoding:
<del> if first layer is Merge:
<del> - get merge config (no connectivity)
<del> - get config of Merge input layers
<del> - insert into merge config as 'layers' (for backwards compatibility)
<del> decoding:
<del> if first layer is Merge:
<del> - get config['layers']
<del> - instantiate input layers
<del> - merge them
<add> '''Returns the model configuration
<add> as a Python dictionary.
<ide> '''
<ide> config = []
<ide> if self.layers[0].__class__.__name__ == 'Merge': | 12 |
Text | Text | remove repl.it links arabic challenge articles | 5747442193daf86cf6ec64db5231a971bb18a679 | <ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/find-the-symmetric-difference/index.md
<ide> Deem كتابة دالة مساعد تقوم بإرجاع الفرق المتم
<ide> }
<ide> `](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)
<ide>
<del> [](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) [تشغيل الكود](https://repl.it/C4II/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> Deem كتابة دالة مساعد تقوم بإرجاع الفرق المتم
<ide> sym([1, 2, 3], [5, 2, 1, 4]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLoc/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> Deem كتابة دالة مساعد تقوم بإرجاع الفرق المتم
<ide> sym([1, 2, 3], [5, 2, 1, 4]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/@ashenm/Symmetric-Difference)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/implement-bubble-sort/index.md
<ide> localeTitle: تنفيذ فرز الفقاعة
<ide>
<ide> `js function bubbleSort(array) { for (let i = 0; i < array.length; i++){ for (let j = 0; j < array.length-1-i; j++){ if (array[j] > array[j+1]) [array[j], array[j+1]] = [array[j+1], array[j]]; // Using ES6 array destructuring to swap } } return array; }`
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Bubble-Sort)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/implement-insertion-sort/index.md
<ide> localeTitle: تنفيذ فرز الإدراج
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Insertion-Sort)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/implement-merge-sort/index.md
<ide> localeTitle: تنفيذ فرز دمج
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Merge-Sort)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/implement-quick-sort/index.md
<ide> localeTitle: تنفيذ فرز سريع
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Quick-Sort)
<ide>
<ide> ### مرجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/inventory-update/index.md
<ide> localeTitle: تحديث المخزون
<ide> updateInventory(curInv, newInv);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLok/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: تحديث المخزون
<ide> updateInventory(curInv, newInv);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLol/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: تحديث المخزون
<ide> updateInventory(curInv, newInv);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/MQvv/latest)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/algorithms/no-repeats-please/index.md
<ide> localeTitle: لا يتكرر من فضلك
<ide> permAlone('aab');
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLop/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-1-multiples-of-3-and-5/index.md
<ide> localeTitle: مضاعفات 3 و 5
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Project-Euler-Problem-1-Multiples-of-3-and-5)
<ide>
<ide> ### مرجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-2-even-fibonacci-numbers/index.md
<ide> localeTitle: حتى أرقام فيبوناتشي
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Project-Euler-Problem-2-Even-Fibonacci-Numbers)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-3-largest-prime-factor/index.md
<ide> localeTitle: أكبر عامل رئيسي
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Problem-3-Largest-prime-factor)
<ide>
<ide> ### مصادر:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-4-largest-palindrome-product/index.md
<ide> localeTitle: أكبر منتج متناظر
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Problem-4-Largest-palindrome-product)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-5-smallest-multiple/index.md
<ide> localeTitle: أصغر متعددة
<ide> }
<ide> `
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Problem-5-Smallest-multiple)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-6-sum-square-difference/index.md
<ide> localeTitle: اختلاف مربع الفراغ
<ide> }
<ide> ``
<ide>
<del>* [تشغيل الكود](https://repl.it/@ezioda004/Problem-6-Sum-square-difference)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/coding-interview-prep/project-euler/problem-7-10001st-prime/index.md
<ide> localeTitle: 10001st
<ide> }
<ide> `
<ide>
<del>\- [تشغيل الكود](https://repl.it/@ezioda004/Project-Euler-Problem-7-10001st-prime)
<ide>
<ide> ### المراجع:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/boo-who/index.md
<ide> localeTitle: بو من
<ide> booWho(null);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnK/0)
<ide>
<ide> # شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/chunky-monkey/index.md
<ide> localeTitle: قرد مكتنز
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/24)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: قرد مكتنز
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/Cj9x/3)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: قرد مكتنز
<ide> chunkArrayInGroups(["a", "b", "c", "d"], 2);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/26)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: قرد مكتنز
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/579)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: قرد مكتنز
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/579)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/confirm-the-ending/index.md
<ide> localeTitle: تأكيد الانتهاء
<ide> confirmEnding("He has to give me a new name", "name");
<ide> `
<ide>
<del>#### 🚀 [تشغيل الكود](https://repl.it/repls/SardonicRoundAfkgaming)
<ide>
<ide> # شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/factorialize-a-number/index.md
<ide> localeTitle: Factorialize عدد
<ide> factorialize(5);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/1)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/falsy-bouncer/index.md
<ide> Falsy هو شيء يتم تقييمه لـ FALSE. لا يوجد سوى ستة ق
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/32)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/find-the-longest-word-in-a-string/index.md
<ide> localeTitle: ابحث عن أطول كلمة في سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/5)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: ابحث عن أطول كلمة في سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/6)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: ابحث عن أطول كلمة في سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/7)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/mutations/index.md
<ide> localeTitle: الطفرات
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/30)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الطفرات
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/31)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/repeat-a-string-repeat-a-string/index.md
<ide> localeTitle: كرر سلسلة يكرر سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/19)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: كرر سلسلة يكرر سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/21)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: كرر سلسلة يكرر سلسلة
<ide> repeatStringNumTimes("abc", 3);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/85)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays/index.md
<ide> localeTitle: أكبر عدد من المصفوفات في المصفوفة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/734)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أكبر عدد من المصفوفات في المصفوفة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/733)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أكبر عدد من المصفوفات في المصفوفة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/17)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string/index.md
<ide> localeTitle: عكس سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/slice-and-splice/index.md
<ide> localeTitle: شريحة و لصق
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/title-case-a-sentence/index.md
<ide> localeTitle: العنوان حالة الجملة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/8)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: العنوان حالة الجملة
<ide> titleCase("I'm a little tea pot");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/9)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: العنوان حالة الجملة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/14)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string/index.md
<ide> localeTitle: اقتطاع سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/55)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: اقتطاع سلسلة
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/54)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong/index.md
<ide> localeTitle: إلى أين أنتمي
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/36)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide> localeTitle: إلى أين أنتمي
<ide> getIndexToIns([40, 60], 50);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/2547)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide> localeTitle: إلى أين أنتمي
<ide> getIndexToIns([40, 60], 50);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/4135)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide> localeTitle: إلى أين أنتمي
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/EB10/1)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide> localeTitle: إلى أين أنتمي
<ide> getIndexToIns([40, 60], 500);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/63)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide> localeTitle: إلى أين أنتمي
<ide> getIndexToIns([1,3,4],2);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/IUJE/0)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/chaining-if-else-statements/index.md
<ide> _`num < 5` - عودة "صغيرة" `num < 10` - عودة "صغير" `num < 15` -
<ide> }
<ide> `
<ide>
<del>تشغيل الكود في [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Chaining-ifelse-statements)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/comparison-with-the-equality-operator/index.md
<ide> _أضف عامل المساواة إلى الخط المحدد بحيث تقوم
<ide> testEqual(10);
<ide> `
<ide>
<del>[تشغيل الكود في repl.it](https://repl.it/@AdrianSkar/Basic-JS-Equality-operator)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/comparisons-with-the-logical-and-operator/index.md
<ide> localeTitle: مقارنات مع عامل التشغيل && (المنطقية AN
<ide> testLogicalAnd(10);
<ide> `
<ide>
<del>[تشغيل الكود في repl.it](https://repl.it/@AdrianSkar/Basic-JS-Comparison-with-the-and-operator)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/counting-cards/index.md
<ide> localeTitle: عد بطاقات
<ide> }
<ide> `
<ide>
<del>تشغيل الكود في [repl.it.](https://repl.it/@AdrianSkar/Basic-JS-Counting-cards)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/golf-code/index.md
<ide> par + 2 | "بوجيه مزدوج" > = par + 3 | "اذهب للمنزل!"
<ide> golfScore(5, 4);
<ide> `
<ide>
<del>· تشغيل في [repl.it](https://repl.it/@AdrianSkar/Basic-JS-Golf-code)
<ide>
<ide> \## شرح الكود نظرًا لأن لدينا بالفعل صفيفًا محددًا في `names` المتغيرات ، فيمكننا الاستفادة منه واستخدامه في عبارات الإرجاع باستخدام الفهارس (على سبيل المثال: `names[0] is the first one` ). بهذه الطريقة ، إذا احتجت في أي وقت إلى تغيير نتيجة معينة فلن تحتاج إلى البحث عنها داخل الوظيفة ، فستكون في البداية ، في الصفيف الخاص بك.
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-if-statements/index.md
<ide> localeTitle: إدخال آخر إذا البيانات
<ide> testElseIf(7);
<ide> `
<ide>
<del>: صاروخ: [تشغيل الكود](https://repl.it/@RyanPisuena/GoldenWorriedRuntime) ## شرح الكود بنية **آخر، إذا تدفق المنطق** هو أولي `if` البيان، أكثر واحد `if-else` التصريحات، ونهائي واحد `else` بيان.
<add>## شرح الكود بنية **آخر، إذا تدفق المنطق** هو أولي `if` البيان، أكثر واحد `if-else` التصريحات، ونهائي واحد `else` بيان.
<ide>
<ide> ### مصادر
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/introducing-else-statements/index.md
<ide> localeTitle: إدخال بيانات أخرى
<ide> testElse(4);
<ide> `
<ide>
<del>[تشغيل الكود في repl.it](https://repl.it/@AdrianSkar/Introducing-else-statements)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/multiple-identical-options-in-switch-statements/index.md
<ide> _ملحوظة: ستحتاج إلى بيان حالة لكل رقم في النط
<ide> sequentialSizes(1);
<ide> `
<ide>
<del>تشغيل الكود في [repl.it.](https://repl.it/@AdrianSkar/Basic-JS-Multiple-opts-in-switch)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/record-collection/index.md
<ide> localeTitle: جمع السجلات
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/C2AZ/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/returning-boolean-values-from-functions/index.md
<ide> _فيكس وظيفة هو `isLess` من إزالة العبارة `if...else` ._
<ide> isLess(10, 15);
<ide> `
<ide>
<del>تشغيل الكود في [repl.it.](https://repl.it/@AdrianSkar/Basic-Js-Returning-boolean-from-function)
<ide>
<ide> ### مصادر
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/selecting-from-many-options-with-switch-statements/index.md
<ide> _اكتب عبارة التبديل التي تختبر `val` `answer` عن ال
<ide> caseInSwitch(1);
<ide> `
<ide>
<del>تشغيل الكود في [repl.it.](https://repl.it/@AdrianSkar/Basic-JS-Switch-statements)
<ide>
<ide> ### تفسير الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/basic-javascript/using-objects-for-lookups/index.md
<ide> localeTitle: استخدام كائنات لعمليات البحث
<ide>
<ide> جافا سكريبت result = lookup \[val\]؛ \`\` \`
<ide>
<del>تشغيل الكود في [repl.it.](https://repl.it/@AdrianSkar/Using-objects-for-lookups)
<ide>
<ide> ### مصادر
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/es6/set-default-parameters-for-your-functions/index.md
<ide> localeTitle: تعيين المعلمات الافتراضية لوظائفك
<ide> console.log(increment(5)); // returns NaN
<ide> `
<ide>
<del>: صاروخ: [تشغيل التعليمات البرمجية](https://repl.it/@RyanPisuena/PleasingFumblingThings)
<ide>
<ide> ## شرح الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/arguments-optional/index.md
<ide> localeTitle: الحجج اختياري
<ide> addTogether(2,3);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnz/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الحجج اختياري
<ide> addTogether(2,3);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLoA/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الحجج اختياري
<ide> addTogether(2,3);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLoB/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents/index.md
<ide> localeTitle: الوكلاء الثنائيين
<ide> binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnm/0)
<ide>
<ide> # شرح الشفرة:
<ide>
<ide> localeTitle: الوكلاء الثنائيين
<ide> binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLno/0)
<ide>
<ide> # شرح الشفرة
<ide>
<ide> localeTitle: الوكلاء الثنائيين
<ide> binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnp/0)
<ide>
<ide> # شرح الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities/index.md
<ide> localeTitle: تحويل كيانات HTML
<ide> * [arr.join ()](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
<ide> * [بيان التبديل](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/switch)
<ide>
<del> [تشغيل الكود](https://repl.it/CLnP/0)
<ide>
<ide> ##  حل الشفرة المتوسطة:
<ide>
<ide> localeTitle: تحويل كيانات HTML
<ide> convertHTML("Dolce & Gabbana");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnQ/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: تحويل كيانات HTML
<ide> convertHTML("Dolce & Gabbana");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnR/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/diff-two-arrays/index.md
<ide> localeTitle: الفرق صفيفتين
<ide> diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLme/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الفرق صفيفتين
<ide> diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CNYb/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الفرق صفيفتين
<ide> diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CNYU/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing/index.md
<ide> localeTitle: دنا الاقتران
<ide> pairElement("GCG");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmz/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: دنا الاقتران
<ide> pairElement("GCG");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/repls/ThoroughSphericalComputeranimation)
<ide>
<ide> ## شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it/index.md
<ide> localeTitle: أسقطها
<ide> dropElements([1, 2, 3, 4], function(n) {return n >= 3;})
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLna/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أسقطها
<ide> dropElements([1, 2, 3, 4], function(n) {return n >= 3;});
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnc/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أسقطها
<ide> dropElements([1, 2, 3, 4], function(n) {return n >= 3;});
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnf/0)
<ide>
<ide> ### شرح الشفرة
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true/index.md
<ide> localeTitle: كل شيء يكون حقيقة
<ide> truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnw/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: كل شيء يكون حقيقة
<ide> truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLny/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: كل شيء يكون حقيقة
<ide> truthCheck([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}, {"user": "Laa-Laa", "sex": "female"}, {"user": "Po", "sex": "female"}], "sex");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/E2u6/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person/index.md
<ide> localeTitle: اصنع شخصا
<ide> bob.getFullName();
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLov/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/map-the-debris/index.md
<ide> localeTitle: رسم خريطة الحطام
<ide> orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLow/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: رسم خريطة الحطام
<ide> orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLoy/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: رسم خريطة الحطام
<ide> orbitalPeriod([{name : "sputnik", avgAlt : 35873.5553}]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLoz/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters/index.md
<ide> localeTitle: حروف ناقصة
<ide> fearNotLetter("abce");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnD/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: حروف ناقصة
<ide> fearNotLetter("abce");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnE/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: حروف ناقصة
<ide> fearNotLetter("abce");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnG/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/pig-latin/index.md
<ide> localeTitle: خنزير اللاتينية
<ide> translatePigLatin("consonant");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmt/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: خنزير اللاتينية
<ide> translatePigLatin("consonant");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmw/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: خنزير اللاتينية
<ide> translatePigLatin("consonant");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmv/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/search-and-replace/index.md
<ide> localeTitle: بحث واستبدال
<ide> myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmo/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: بحث واستبدال
<ide> myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmp/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: بحث واستبدال
<ide> myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmq/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: بحث واستبدال
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/@kr3at0/SearchAndReplace)
<ide>
<ide> ##  حل رمز متقدم البديل 2:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/seek-and-destroy/index.md
<ide> localeTitle: تسعى وتدمر
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/95)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: تسعى وتدمر
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/Ck2m/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/smallest-common-multiple/index.md
<ide> localeTitle: أصغر مشترك متعددة
<ide> smallestCommons([1,5]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLn2/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أصغر مشترك متعددة
<ide> smallestCommons([1,5]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLn4/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أصغر مشترك متعددة
<ide> smallestCommons([1,5]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/MR9P/latest)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sorted-union/index.md
<ide> localeTitle: الاتحاد الفرز
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnM/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الاتحاد الفرز
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnO/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الاتحاد الفرز
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnN/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: الاتحاد الفرز
<ide> uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CcWk/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/spinal-tap-case/index.md
<ide> localeTitle: حنفية شبكية
<ide> spinalCase('This Is Spinal Tap');
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnS/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: حنفية شبكية
<ide> spinalCase('This Is Spinal Tap');
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnT/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: حنفية شبكية
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/EUZV)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller/index.md
<ide> localeTitle: أجاز
<ide> steamrollArray([1, [2], [3, [[4]]]]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnh/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أجاز
<ide> flattenArray([1, [2], [3, [[4]]]]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLni/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: أجاز
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CpDy/4)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-numbers-in-a-range/index.md
<ide> localeTitle: مجموع كل الأرقام في المدى
<ide> sumAll([1, 4]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLm6/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: مجموع كل الأرقام في المدى
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLm7/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: مجموع كل الأرقام في المدى
<ide> sumAll([1, 4]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLm8/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers/index.md
<ide> localeTitle: Sum All Odd Fibonacci Numbers
<ide> sumFibs(4);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnV/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: Sum All Odd Fibonacci Numbers
<ide> sumFibs(4);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/repls/ImpassionedFineConnection)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes/index.md
<ide> localeTitle: مجموع كل الأعداد
<ide> sumPrimes(10);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLnZ/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: مجموع كل الأعداد
<ide> sumPrimes(10);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLn0/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: مجموع كل الأعداد
<ide> sumPrimes(977);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/DoOo/3)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou/index.md
<ide> localeTitle: ولهذا السبب انت الفن
<ide> whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmh/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: ولهذا السبب انت الفن
<ide> whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmi/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: ولهذا السبب انت الفن
<ide> whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmj/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher/index.md
<ide> localeTitle: قيصر تشفير
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/38)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: قيصر تشفير
<ide> * [رجإكس](https://forum.freecodecamp.com/t/regular-expressions-resources/15931)
<ide> * [Regex.test](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test)
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/39)
<ide>
<ide> ##  الحل المتقدم للكود:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register/index.md
<ide> localeTitle: ماكينة تسجيل المدفوعات النقدية
<ide> checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/@scissorsneedfoo/cash-register-example)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker/index.md
<ide> localeTitle: Palindrome المدقق
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/2)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: Palindrome المدقق
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/3)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: Palindrome المدقق
<ide> }
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLjU/4)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter/index.md
<ide> localeTitle: تحويل الأرقام الرومانية
<ide> convertToRoman(36);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLmf/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: تحويل الأرقام الرومانية
<ide> convertToRoman(97);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/C1YV)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: تحويل الأرقام الرومانية
<ide> convertToRoman(36);
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/C1YV)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide><path>guide/arabic/certifications/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator/index.md
<ide> localeTitle: مدقق رقم الهاتف
<ide> telephoneCheck("555-555-5555");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLo9/0)
<ide>
<ide> ### شرح الشفرة:
<ide>
<ide> localeTitle: مدقق رقم الهاتف
<ide> telephoneCheck("555-555-5555");
<ide> `
<ide>
<del> [تشغيل الكود](https://repl.it/CLoa/0)
<ide>
<ide> ### شرح الشفرة:
<ide> | 67 |
Text | Text | add hashrocket logo | f4810280f768ee71ece1ab37cc356081420dd5b4 | <ide><path>SUPPORTERS.md
<ide> until then.
<ide>
<ide> These mindblowing people supported our Kickstarter by giving us £450 or more:
<ide>
<del>* [Hashrocket](http://hashrocket.com/)
<add>[](http://hashrocket.com/)
<ide>
<ide> These spectacular people supported our Kickstarter by giving us £400 or more:
<ide> | 1 |
Javascript | Javascript | remove cachekeys in favor of simply a cachekey | 179d09e8e08be323eac115d6b86659793d1a479a | <ide><path>packages/next/build/webpack/plugins/terser-webpack-plugin/src/TaskRunner.js
<ide> import { join } from 'path';
<ide> import minify from './minify';
<del>import murmur from 'imurmurhash';
<ide> import { promisify } from 'util';
<ide> import workerFarm from 'worker-farm';
<ide> import { writeFile, readFile } from 'fs';
<ide> export default class TaskRunner {
<ide> tasks.forEach((task, index) => {
<ide> const cachePath = join(
<ide> this.cacheDir,
<del> murmur(serialize(task.cacheKeys)).result()+''
<add> task.cacheKey
<ide> )
<ide>
<ide> const enqueue = () => {
<ide><path>packages/next/build/webpack/plugins/terser-webpack-plugin/src/index.js
<ide> export class TerserPlugin {
<ide> };
<ide>
<ide> if (this.options.cache) {
<del> task.cacheKeys = {
<del> terser: '3.16.1',
<del> // eslint-disable-next-line global-require
<del> 'next-minifier': '1.2.2',
<del> 'next-minifier-options': this.options,
<del> hash: murmur(input).result()
<del> }
<add> // increment 'a' to invalidate previous caches from different options
<add> task.cacheKey = 'a' + murmur(input).result()
<add> if (this.options.sourceMap) task.cacheKey += 's'
<ide> }
<ide>
<ide> tasks.push(task); | 2 |
Python | Python | fix docs of url_for(..., _external=true) | d23b160e6df5d13e7db7a5e53afab6db306efe3c | <ide><path>flask/helpers.py
<ide> def external_url_handler(error, endpoint, values):
<ide> :param values: the variable arguments of the URL rule
<ide> :param _external: if set to ``True``, an absolute URL is generated. Server
<ide> address can be changed via ``SERVER_NAME`` configuration variable which
<del> defaults to `localhost`.
<add> falls back to the `Host` header, then to the IP and port of the request.
<ide> :param _scheme: a string specifying the desired URL scheme. The `_external`
<ide> parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
<ide> behavior uses the same scheme as the current request, or | 1 |
Python | Python | fix tests for history features | 6c79841c0dce58cff859dfd37c44824cd267d8ea | <ide><path>spacy/tests/parser/test_neural_parser.py
<ide> def parser(vocab, arc_eager):
<ide>
<ide> @pytest.fixture
<ide> def model(arc_eager, tok2vec):
<del> return Parser.Model(arc_eager.n_moves, token_vector_width=tok2vec.nO)[0]
<add> return Parser.Model(arc_eager.n_moves, token_vector_width=tok2vec.nO,
<add> hist_size=0)[0]
<ide>
<ide> @pytest.fixture
<ide> def doc(vocab):
<ide> def test_can_init_nn_parser(parser):
<ide>
<ide>
<ide> def test_build_model(parser):
<del> parser.model = Parser.Model(parser.moves.n_moves)[0]
<add> parser.model = Parser.Model(parser.moves.n_moves, hist_size=0)[0]
<ide> assert parser.model is not None
<ide>
<ide> | 1 |
Ruby | Ruby | add new command | ca2abb2be6686a8f2e7c64f5d334ab70be97a1b7 | <ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<add># Creates a pull request with the new version of a formula.
<add>#
<add># Usage: brew bump [options...] <formula-name>
<add>#
<add># Requires either `--url` and `--sha256` or `--tag` and `--revision`.
<add>#
<add># Options:
<add># --dry-run: Print what would be done rather than doing it.
<add># --devel: Bump a `devel` rather than `stable` version.
<add># --url: The new formula URL.
<add># --sha256: The new formula SHA-256.
<add># --tag: The new formula's `tag`
<add># --revision: The new formula's `revision`.
<add>
<add>require "formula"
<add>
<add>module Homebrew
<add> def bump_formula_pr
<add> formula = ARGV.formulae.first
<add> odie "No formula found!" unless formula
<add>
<add> requested_spec, formula_spec = if ARGV.include?("--devel")
<add> devel_message = " (devel)"
<add> [:devel, formula.devel]
<add> else
<add> [:stable, formula.stable]
<add> end
<add> odie "#{formula}: no #{requested_spec} specification found!" unless formula
<add>
<add> hash_type, old_hash = if (checksum = formula_spec.checksum)
<add> [checksum.hash_type.to_s, checksum.hexdigest]
<add> end
<add>
<add> new_url = ARGV.value("url")
<add> new_hash = ARGV.value(hash_type)
<add> new_tag = ARGV.value("tag")
<add> new_revision = ARGV.value("revision")
<add> new_url_hash = if new_url && new_hash
<add> true
<add> elsif new_tag && new_revision
<add> false
<add> elsif !hash_type
<add> odie "#{formula}: no tag/revision specified!"
<add> else
<add> odie "#{formula}: no url/#{hash_type} specified!"
<add> end
<add>
<add> if ARGV.dry_run?
<add> ohai "brew update"
<add> else
<add> safe_system "brew", "update"
<add> end
<add>
<add> Utils::Inreplace.inreplace(formula.path) do |s|
<add> if new_url_hash
<add> old_url = formula_spec.url
<add> if ARGV.dry_run?
<add> ohai "replace '#{old_url}' with '#{new_url}'"
<add> ohai "replace '#{old_hash}' with '#{new_hash}'"
<add> else
<add> s.gsub!(old_url, new_url)
<add> s.gsub!(old_hash, new_hash)
<add> end
<add> else
<add> resource_specs = formula_spec.specs
<add> old_tag = resource_specs[:tag]
<add> old_revision = resource_specs[:revision]
<add> if ARGV.dry_run?
<add> ohai "replace '#{old_tag}' with '#{new_tag}'"
<add> ohai "replace '#{old_revision}' with '#{new_revision}'"
<add> else
<add> s.gsub!(/['"]#{old_tag}['"]/, "\"#{new_tag}\"")
<add> s.gsub!(old_revision, new_revision)
<add> end
<add> end
<add> end
<add>
<add> new_formula = Formulary.load_formula_from_path(formula.name, formula.path)
<add> new_formula_version = new_formula.version
<add>
<add> unless Formula["hub"].any_version_installed?
<add> if ARGV.dry_run?
<add> ohai "brew install hub"
<add> else
<add> safe_system "brew", "install", "hub"
<add> end
<add> end
<add>
<add> formula.path.parent.cd do
<add> branch = "#{formula.name}-#{new_formula_version}"
<add> if ARGV.dry_run?
<add> ohai "git checkout -b #{branch} origin/master"
<add> ohai "git commit --no-edit --verbose --message='#{formula.name} #{new_formula_version}#{devel_message}' -- #{formula.path}"
<add> ohai "hub fork --no-remote"
<add> ohai "hub fork"
<add> ohai "hub fork (to read $HUB_REMOTE)"
<add> ohai "git push $HUB_REMOTE #{branch}:#{branch}"
<add> ohai "hub pull-request --browse -m '#{formula.name} #{new_formula_version}#{devel_message}'"
<add> else
<add> safe_system "git", "checkout", "-b", branch, "origin/master"
<add> safe_system "git", "commit", "--no-edit", "--verbose",
<add> "--message=#{formula.name} #{new_formula_version}#{devel_message}",
<add> "--", formula.path
<add> safe_system "hub", "fork", "--no-remote"
<add> quiet_system "hub", "fork"
<add> remote = Utils.popen_read("hub fork 2>&1")[/fatal: remote (.+) already exists./, 1]
<add> odie "cannot get remote from 'hub'!" if remote.to_s.empty?
<add> safe_system "git", "push", remote, "#{branch}:#{branch}"
<add> safe_system "hub", "pull-request", "--browse", "-m",
<add> "#{formula.name} #{new_formula_version}#{devel_message}\n\nCreated with `brew bump-formula-pr`."
<add> end
<add> end
<add> end
<add>end | 1 |
PHP | PHP | add basic single table updates | 4a6e65adc92c47cfd313be67205d76e840bf9a48 | <ide><path>lib/Cake/Model/Datasource/Database/Query.php
<ide> class Query implements Expression, IteratorAggregate {
<ide> protected $_parts = [
<ide> 'delete' => true,
<ide> 'select' => [],
<add> 'update' => [],
<ide> 'distinct' => false,
<ide> 'from' => [],
<ide> 'join' => [],
<ide> class Query implements Expression, IteratorAggregate {
<ide> */
<ide> protected $_templates = [
<ide> 'delete' => 'DELETE',
<add> 'update' => 'UPDATE %s',
<ide> 'where' => ' WHERE %s',
<ide> 'group' => ' GROUP BY %s ',
<ide> 'having' => ' HAVING %s ',
<ide> protected function _traverseDelete(callable $visitor) {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Helper function that iterates the query parts needed for UPDATE statements.
<add> *
<add> * @param callable $visitor A callable to execute for each part of the query.
<add> * @return void
<add> */
<add> protected function _traverseUpdate(callable $visitor) {
<add> $parts = ['update', 'set', 'where'];
<add> foreach ($parts as $name) {
<add> $visitor($this->_parts[$name], $name);
<add> }
<add> }
<add>
<ide> /**
<ide> * Adds new fields to be returned by a SELECT statement when this query is
<ide> * executed. Fields can be passed as an array of strings, array of expression
<ide> protected function _buildJoinPart($parts) {
<ide> return $joins;
<ide> }
<ide>
<add>/**
<add> * Helper function to generate SQL for SET expressions.
<add> *
<add> * @param array $parts List of keys & values to set.
<add> * @return string
<add> */
<add> protected function _buildSetPart($parts) {
<add> $set = [];
<add> foreach ($parts as $part) {
<add> // TODO Hacking around with string values is a bit dirty.
<add> if ($part[0] === '(') {
<add> $part = substr($part, 1, -1);
<add> }
<add> $set[] = $part;
<add> }
<add> return ' SET ' . implode('', $set);
<add> }
<add>
<ide> /**
<ide> * Adds a condition or set of conditions to be used in the WHERE clause for this
<ide> * query. Conditions can be expressed as an array of fields as keys with
<ide> protected function _buildJoinPart($parts) {
<ide> * ->where(['title !=' => 'Hello World'])
<ide> * ->where(function($exp, $query) {
<ide> * $or = $exp->or_(['id' => 1]);
<del> $and = $exp->and_(['id >' => 2, 'id <' => 10]);
<del> return $or->add($and);
<add> * $and = $exp->and_(['id >' => 2, 'id <' => 10]);
<add> * return $or->add($and);
<ide> * });
<ide> * }}}
<ide> *
<ide> public function insert() {
<ide> return $this;
<ide> }
<ide>
<del> public function update() {
<add>/**
<add> * Create an update query.
<add> *
<add> * Can be combined with set() and where() methods to create update queries.
<add> *
<add> * @param string $table The table you want to update.
<add> * @return Query
<add> */
<add> public function update($table) {
<add> $this->_dirty = true;
<add> $this->_type = 'update';
<add> $this->_parts['update'][] = $table;
<ide> return $this;
<ide> }
<ide>
<ide> /**
<del> * Convert the query into a delete query.
<add> * Set one or many fields to update.
<add> *
<add> * @param string|array $key The key or array of keys + values to set.
<add> * @param mixed $value The value to update $key to.
<add> * @return Query
<add> */
<add> public function set($key, $value = null) {
<add> if (empty($this->_parts['set'])) {
<add> $this->_parts['set'] = new QueryExpression([], [], ',');
<add> }
<add> $set = $key;
<add> if (!is_array($key) && !($key instanceof QueryExpression)) {
<add> $set = [$key => $value];
<add> }
<add> $this->_parts['set']->add($set, []);
<add> return $this;
<add> }
<add>
<add>/**
<add> * Create a delete query.
<ide> *
<ide> * Can be combined with from(), where() and other methods to
<ide> * create delete queries with specific conditions.
<ide> protected function _decorateResults($statement) {
<ide> return $statement;
<ide> }
<ide>
<del>
<ide> /**
<ide> * Helper function used to build conditions by composing QueryExpression objects
<ide> *
<ide><path>lib/Cake/Model/Datasource/Database/SqlDialect.php
<ide> protected function _deleteQueryTranslator($query) {
<ide> return $query;
<ide> }
<ide>
<add>/**
<add> * Apply translation steps to update queries.
<add> *
<add> * @param Query $query The query to translate
<add> * @return Query The modified query
<add> */
<add> protected function _updateQueryTranslator($query) {
<add> return $query;
<add> }
<add>
<ide> }
<ide><path>lib/Cake/Test/TestCase/Model/Datasource/Database/QueryTest.php
<ide> public function testSelectAndDeleteOnSameQuery() {
<ide> $this->assertContains('authors WHERE 1 = 1', $result);
<ide> }
<ide>
<add>/**
<add> * Test a simple update.
<add> *
<add> * @return void
<add> */
<add> public function testUpdateSimple() {
<add> $this->_insertTwoRecords();
<add> $query = new Query($this->connection);
<add> $query->update('authors')
<add> ->set('name', 'mark')
<add> ->where(['id' => 1]);
<add> $result = $query->sql(false);
<add> $this->assertContains('UPDATE authors SET name = :', $result);
<add>
<add> $result = $query->execute();
<add> $this->assertCount(1, $result);
<add> }
<add>
<add>/**
<add> * Test update with multiple fields.
<add> *
<add> * @return void
<add> */
<add> public function testUpdateMultipleFields() {
<add> $this->_insertTwoRecords();
<add> $query = new Query($this->connection);
<add> $query->update('articles')
<add> ->set('title', 'mark')
<add> ->set('body', 'some text')
<add> ->where(['id' => 1]);
<add> $result = $query->sql(false);
<add>
<add> $this->assertRegExp(
<add> '/UPDATE articles SET title = :[0-9a-z]+ , body = :[0-9a-z]+/',
<add> $result
<add> );
<add> $this->assertContains('WHERE id = :', $result);
<add>
<add> $result = $query->execute();
<add> $this->assertCount(1, $result);
<add> }
<add>
<add>/**
<add> * Test updating multiple fields with an array.
<add> *
<add> * @return void
<add> */
<add> public function testUpdateMultipleFieldsArray() {
<add> $this->_insertTwoRecords();
<add> $query = new Query($this->connection);
<add> $query->update('articles')
<add> ->set([
<add> 'title' => 'mark',
<add> 'body' => 'some text'
<add> ])
<add> ->where(['id' => 1]);
<add> $result = $query->sql(false);
<add>
<add> $this->assertRegExp(
<add> '/UPDATE articles SET title = :[0-9a-z]+ , body = :[0-9a-z]+/',
<add> $result
<add> );
<add> $this->assertContains('WHERE id = :', $result);
<add>
<add> $result = $query->execute();
<add> $this->assertCount(1, $result);
<add> }
<add>
<add> public function testUpdateWithExpression() {
<add> $this->_insertTwoRecords();
<add> $query = new Query($this->connection);
<add>
<add> $expr = $query->newExpr();
<add> $expr->add('title = author_id');
<add>
<add> $query->update('articles')
<add> ->set($expr)
<add> ->where(['id' => 1]);
<add> $result = $query->sql(false);
<add>
<add> $this->assertContains(
<add> 'UPDATE articles SET title = author_id WHERE id = :',
<add> $result
<add> );
<add>
<add> $result = $query->execute();
<add> $this->assertCount(1, $result);
<add> }
<add>
<ide> } | 3 |
Text | Text | fix some redirect loops and problems | a1f55dca21c4ee9f38ed2aeba535cdba3bb2f790 | <ide><path>docs/extend/config.md
<ide> ---
<del>aliases: [
<del>"/engine/extend/"
<del>]
<ide> title: "Plugin config"
<ide> description: "How develop and use a plugin with the managed plugin system"
<ide> keywords: "API, Usage, plugins, documentation, developer"
<ide><path>docs/extend/index.md
<ide> ---
<del>aliases:
<del>- /engine/extend/
<ide> description: Develop and use a plugin with the managed plugin system
<ide> keywords: "API, Usage, plugins, documentation, developer"
<ide> title: Managed plugin system
<ide><path>docs/extend/legacy_plugins.md
<ide> ---
<del>aliases: "/engine/extend/plugins/"
<add>redirect_from:
<add>- "/engine/extend/plugins/"
<ide> title: "Use Docker Engine plugins"
<ide> description: "How to add additional functionality to Docker with plugins extensions"
<ide> keywords: "Examples, Usage, plugins, docker, documentation, user guide"
<ide><path>docs/extend/menu.md
<del>---
<del>title: "Implement plugins"
<del>description: "Develop plugins and use existing plugins for Docker Engine"
<del>keywords: ["extend, plugins, docker, documentation, developer"]
<del>type: "menu"
<del>identifier: "engine_extend"
<del>---
<del>
<del><!-- This file is maintained within the docker/docker Github
<del> repository at https://github.com/docker/docker/. Make all
<del> pull requests against that repo. If you see this file in
<del> another repository, consider it read-only there, as it will
<del> periodically be overwritten by the definitive file. Pull
<del> requests which include edits to this file in other repositories
<del> will be rejected.
<del>-->
<del>
<del><!--menu page not rendered-->
<ide><path>docs/extend/plugins_authorization.md
<ide> title: "Access authorization plugin"
<ide> description: "How to create authorization plugins to manage access control to your Docker daemon."
<ide> keywords: "security, authorization, authentication, docker, documentation, plugin, extend"
<del>aliases: ["/engine/extend/authorization/"]
<add>redirect_from:
<add>- "/engine/extend/authorization/"
<ide> ---
<ide>
<ide> <!-- This file is maintained within the docker/docker Github | 5 |
Javascript | Javascript | add fd into listen2 debug info | cd60ff03281a7e5a2cf0f7a2349303f1d44bb778 | <ide><path>lib/net.js
<ide> var createServerHandle = exports._createServerHandle =
<ide>
<ide>
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<del> debug('listen2', address, port, addressType, backlog);
<add> debug('listen2', address, port, addressType, backlog, fd);
<ide> var self = this;
<ide>
<ide> // If there is not yet a handle, we need to create one and bind. | 1 |
Javascript | Javascript | set devicegray as initial value for color space | 0c321466dce4377f58a038515260c66a0f74603b | <ide><path>pdf.js
<ide> var CanvasExtraState = (function canvasExtraState() {
<ide> this.strokeColor = '#000000';
<ide>
<ide> this.old = old;
<add>
<add> this.fillColorSpace = new DeviceGrayCS;
<add> this.strokeColorSpace = new DeviceGrayCS;
<ide> }
<ide>
<ide> constructor.prototype = { | 1 |
Javascript | Javascript | fix subgroup sorting in chord layout | 59c32fc669875fe77b1767113009dfa477450e98 | <ide><path>d3.js
<del>(function(){d3 = {version: "1.0.2"}; // semver
<add>(function(){d3 = {version: "1.0.3"}; // semver
<ide> if (!Date.now) Date.now = function() {
<ide> return +new Date();
<ide> };
<ide><path>d3.layout.js
<ide> d3.layout.chord = function() {
<ide> x = 0, i = -1; while (++i < n) {
<ide> x0 = x, j = -1; while (++j < n) {
<ide> var di = groupIndex[i],
<del> dj = subgroupIndex[di][j],
<add> dj = subgroupIndex[i][j],
<ide> v = matrix[di][dj];
<del> subgroups[i + "-" + j] = {
<add> subgroups[di + "-" + dj] = {
<ide> "index": di,
<ide> "subindex": dj,
<ide> "startAngle": x,
<ide><path>d3.layout.min.js
<ide> (function(){function z(a){return a.reduce(A,0)}function B(a){for(var h=1,d=0,c=a[0].y,i,f=a.length;h<f;++h)if((i=a[h].y)>c){d=h;c=i}return d}function A(a,h){return a+h.y}d3.layout={};d3.layout.chord=function(){function a(){var g={},m=[],s=d3.range(b),o=[],p,k,v,n,q;c=[];i=[];p=0;for(n=-1;++n<b;){k=0;for(q=-1;++q<b;)k+=f[n][q];m.push(k);o.push(d3.range(b));p+=k}j&&s.sort(function(w,t){return j(m[w],m[t])});l&&o.forEach(function(w,t){w.sort(function(C,D){return l(f[t][C],f[t][D])})});p=(2*Math.PI-e*
<del>b)/p;k=0;for(n=-1;++n<b;){v=k;for(q=-1;++q<b;){var u=s[n],x=o[u][q],y=f[u][x];g[n+"-"+q]={index:u,subindex:x,startAngle:k,endAngle:k+=y*p,value:y}}i.push({index:u,startAngle:v,endAngle:k,value:(k-v)/p});k+=e}for(n=-1;++n<b;)for(q=n-1;++q<b;){s=g[n+"-"+q];o=g[q+"-"+n];if(s.value||o.value)c.push({source:s,target:o})}r&&h()}function h(){c.sort(function(g,m){g=Math.min(g.source.value,g.target.value);m=Math.min(m.source.value,m.target.value);return r(g,m)})}var d={},c,i,f,b,e=0,j,l,r;d.matrix=function(g){if(!arguments.length)return f;
<add>b)/p;k=0;for(n=-1;++n<b;){v=k;for(q=-1;++q<b;){var u=s[n],x=o[n][q],y=f[u][x];g[u+"-"+x]={index:u,subindex:x,startAngle:k,endAngle:k+=y*p,value:y}}i.push({index:u,startAngle:v,endAngle:k,value:(k-v)/p});k+=e}for(n=-1;++n<b;)for(q=n-1;++q<b;){s=g[n+"-"+q];o=g[q+"-"+n];if(s.value||o.value)c.push({source:s,target:o})}r&&h()}function h(){c.sort(function(g,m){g=Math.min(g.source.value,g.target.value);m=Math.min(m.source.value,m.target.value);return r(g,m)})}var d={},c,i,f,b,e=0,j,l,r;d.matrix=function(g){if(!arguments.length)return f;
<ide> b=(f=g)&&f.length;c=i=null;return d};d.padding=function(g){if(!arguments.length)return e;e=g;c=i=null;return d};d.sortGroups=function(g){if(!arguments.length)return j;j=g;c=i=null;return d};d.sortSubgroups=function(g){if(!arguments.length)return l;l=g;c=null;return d};d.sortChords=function(g){if(!arguments.length)return r;r=g;c&&h();return d};d.chords=function(){c||a();return c};d.groups=function(){i||a();return i};return d};d3.layout.stack=function(){function a(c){var i=c.length,f=c[0].length,b,
<ide> e,j,l=E[h](c);F[d](c,l);for(e=0;e<f;++e){b=1;for(j=c[l[0]][e].y0;b<i;++b)c[l[b]][e].y0=j+=c[l[b-1]][e].y}return c}var h="default",d="zero";a.order=function(c){if(!arguments.length)return h;h=c;return a};a.offset=function(c){if(!arguments.length)return d;d=c;return a};return a};var E={"inside-out":function(a){var h=a.length,d,c=a.map(B),i=a.map(z),f=d3.range(h).sort(function(r,g){return c[r]-c[g]}),b=0,e=0,j=[],l=[];for(a=0;a<h;a++){d=f[a];if(b<e){b+=i[d];j.push(d)}else{e+=i[d];l.push(d)}}return l.reverse().concat(j)},
<ide> reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},F={silhouette:function(a,h){var d=a.length,c=a[0].length,i=[],f=0,b,e,j;for(e=0;e<c;++e){for(j=b=0;b<d;b++)j+=a[b][e].y;if(j>f)f=j;i.push(j)}e=0;for(b=h[0];e<c;++e)a[b][e].y0=(f-i[e])/2},wiggle:function(a,h){var d=a.length,c=a[0],i=c.length,f,b,e,j,l,r=h[0],g,m,s,o,p,k;a[r][0].y0=p=k=0;for(b=1;b<i;++b){for(g=f=0;f<d;++f)g+=a[f][b].y;m=f=0;for(o=c[b].x-c[b-1].x;f<d;++f){e=0;j=h[f];for(s=(a[j][b].y-
<ide><path>d3.min.js
<ide> c.delay=b;f=true}else{var i=c.then+c.delay;if(i<e)e=i}c=c.next}f||(F={callback:a
<ide> function Z(a,b,d,f){var e=[],c=-1,i=b.length,h=typeof d=="function",g=typeof f=="function",k;if(h&&g)for(;++c<i;)e.push([d.call(a,k=b[c],c),f.call(a,k,c)]);else if(h)for(;++c<i;)e.push([d.call(a,b[c],c),f]);else if(g)for(;++c<i;)e.push([d,f.call(a,b[c],c)]);else for(;++c<i;)e.push([d,f]);return e}function la(a){return a[0]}function ma(a){return a[1]}function H(a){var b=[],d=0,f=a.length,e=a[0];for(b.push(e[0],",",e[1]);++d<f;)b.push("L",(e=a[d])[0],",",e[1]);return b.join("")}function na(a,b){if(b.length<
<ide> 1||a.length!=b.length&&a.length!=b.length+2)return H(a);var d=a.length!=b.length,f="",e=a[0],c=a[1],i=b[0],h=i,g=1;if(d){f+="Q"+(c[0]-i[0]*2/3)+","+(c[1]-i[1]*2/3)+","+c[0]+","+c[1];e=a[1];g=2}if(b.length>1){h=b[1];c=a[g];g++;f+="C"+(e[0]+i[0])+","+(e[1]+i[1])+","+(c[0]-h[0])+","+(c[1]-h[1])+","+c[0]+","+c[1];for(e=2;e<b.length;e++,g++){c=a[g];h=b[e];f+="S"+(c[0]-h[0])+","+(c[1]-h[1])+","+c[0]+","+c[1]}}if(d){d=a[g];f+="Q"+(c[0]+h[0]*2/3)+","+(c[1]+h[1]*2/3)+","+d[0]+","+d[1]}return f}function oa(a,
<ide> b){for(var d=[],f=(1-b)/2,e=a[0],c=a[1],i=a[2],h=2,g=a.length;++h<g;){d.push([f*(i[0]-e[0]),f*(i[1]-e[1])]);e=c;c=i;i=a[h]}d.push([f*(i[0]-e[0]),f*(i[1]-e[1])]);return d}function B(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function K(a,b,d){a.push("C",B(pa,b),",",B(pa,d),",",B(qa,b),",",B(qa,d),",",B(L,b),",",B(L,d))}function Na(){return 0}function Oa(a){return a.source}function Pa(a){return a.target}function Qa(a){return a.radius}function Ra(){return 64}function Sa(){return"circle"}d3=
<del>{version:"1.0.2"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};var M=function(a){return Array.prototype.slice.call(a)};try{M(document.documentElement.childNodes)}catch(eb){M=ua}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.min=function(a,b){var d=0,f=a.length,e=a[0],c;if(arguments.length==1)for(;++d<f;){if(e>(c=a[d]))e=c}else for(e=b(a[0]);++d<f;)if(e>
<add>{version:"1.0.3"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};var M=function(a){return Array.prototype.slice.call(a)};try{M(document.documentElement.childNodes)}catch(eb){M=ua}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.min=function(a,b){var d=0,f=a.length,e=a[0],c;if(arguments.length==1)for(;++d<f;){if(e>(c=a[d]))e=c}else for(e=b(a[0]);++d<f;)if(e>
<ide> (c=b(a[d])))e=c;return e};d3.max=function(a,b){var d=0,f=a.length,e=a[0],c;if(arguments.length==1)for(;++d<f;){if(e<(c=a[d]))e=c}else for(e=b(e);++d<f;)if(e<(c=b(a[d])))e=c;return e};d3.nest=function(){function a(c,i){if(c>=d.length)return e?e.call(b,i):f?i.sort(f):i;for(var h=-1,g=i.length,k=d[c],j,o=[],p,m={};++h<g;)if((j=k(p=i[h]))in m)m[j].push(p);else{m[j]=[p];o.push(j)}c++;h=-1;for(g=o.length;++h<g;){p=m[j=o[h]];m[j]=a(c,p)}return m}var b={},d=[],f,e;b.map=function(c){return a(0,c)};b.key=function(c){d.push(c);
<ide> return b};b.sortKeys=function(){return b};b.sortValues=function(c){f=c;return b};b.rollup=function(c){e=c;return b};return b};d3.keys=function(a){var b=[],d;for(d in a)b.push(d);return b};d3.values=function(a){var b=[],d;for(d in a)b.push(a[d]);return b};d3.entries=function(a){var b=[],d;for(d in a)b.push({key:d,value:a[d]});return b};d3.merge=function(a){return Array.prototype.concat.apply([],a)};d3.split=function(a,b){var d=[],f=[],e,c=-1,i=a.length;if(arguments.length<2)b=va;for(;++c<i;)if(b.call(f,
<ide> e=a[c],c))f=[];else{f.length||d.push(f);f.push(e)}return d};d3.range=function(a,b,d){if(arguments.length==1){b=a;a=0}if(d==null)d=1;if((b-a)/d==Infinity)throw Error("infinite range");var f=[],e=-1,c;if(d<0)for(;(c=a+d*++e)>b;)f.push(c);else for(;(c=a+d*++e)<b;)f.push(c);return f};d3.requote=function(a){return a.replace(Ta,"\\$&")};var Ta=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,d){var f=new XMLHttpRequest;if(arguments.length<3)d=b;else b&&f.overrideMimeType(b);f.open("GET",a,true);f.onreadystatechange=
<ide><path>src/core/core.js
<del>d3 = {version: "1.0.2"}; // semver
<add>d3 = {version: "1.0.3"}; // semver
<ide><path>src/layout/chord.js
<ide> d3.layout.chord = function() {
<ide> x = 0, i = -1; while (++i < n) {
<ide> x0 = x, j = -1; while (++j < n) {
<ide> var di = groupIndex[i],
<del> dj = subgroupIndex[di][j],
<add> dj = subgroupIndex[i][j],
<ide> v = matrix[di][dj];
<del> subgroups[i + "-" + j] = {
<add> subgroups[di + "-" + dj] = {
<ide> "index": di,
<ide> "subindex": dj,
<ide> "startAngle": x, | 6 |
PHP | PHP | implement diff and intersect on support\collection | d64e3a7faaa38c52223133b6340a0f4a621afc70 | <ide><path>src/Illuminate/Support/Collection.php
<ide> public function merge($items)
<ide> return new static($results);
<ide> }
<ide>
<add> /**
<add> * Diff items with the collection items.
<add> *
<add> * @param \Illuminate\Support\Collection|\Illuminate\Support\Contracts\ArrayableInterface|array $items
<add> * @return \Illuminate\Support\Collection
<add> */
<add> public function diff($items)
<add> {
<add> if ($items instanceof Collection)
<add> {
<add> $items = $items->all();
<add> }
<add> elseif ($items instanceof ArrayableInterface)
<add> {
<add> $items = $items->toArray();
<add> }
<add>
<add> $results = array_diff($this->items, $items);
<add>
<add> return new static($results);
<add> }
<add>
<add> /**
<add> * Intersect items with the collection items.
<add> *
<add> * @param \Illuminate\Support\Collection|\Illuminate\Support\Contracts\ArrayableInterface|array $items
<add> * @return \Illuminate\Support\Collection
<add> */
<add> public function intersect($items)
<add> {
<add> if ($items instanceof Collection)
<add> {
<add> $items = $items->all();
<add> }
<add> elseif ($items instanceof ArrayableInterface)
<add> {
<add> $tiems = $items->toArray();
<add> }
<add>
<add> $results = array_intersect($this->items, $items);
<add>
<add> return new static($results);
<add> }
<add>
<ide> /**
<ide> * Slice the underlying collection array.
<ide> *
<ide><path>tests/Support/SupportCollectionTest.php
<ide> public function testMergeCollection()
<ide> }
<ide>
<ide>
<add> public function testDiffCollection()
<add> {
<add> $c = new Collection(array('id' => 1, 'first_word' => 'Hello'));
<add> $this->assertEquals(array('id' => 1), $c->diff(new Collection(array('first_word' => 'Hello', 'last_word' => 'World')))->all());
<add> }
<add>
<add>
<add> public function testIntersectCollection()
<add> {
<add> $c = new Collection(array('id' => 1, 'first_word' => 'Hello'));
<add> $this->assertEquals(array('first_word' => 'Hello'), $c->intersect(new Collection(array('first_world' => 'Hello', 'last_word' => 'World')))->all());
<add> }
<add>
<add>
<ide> public function testCollapse()
<ide> {
<ide> $data = new Collection(array(array($object1 = new StdClass), array($object2 = new StdClass))); | 2 |
Python | Python | add vocab for new german distilbert model | f21dfe36baaf316675a4d2f8c918e9e8afc11db2 | <ide><path>transformers/tokenization_distilbert.py
<ide> {
<ide> 'distilbert-base-uncased': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-vocab.txt",
<ide> 'distilbert-base-uncased-distilled-squad': "https://s3.amazonaws.com/models.huggingface.co/bert/bert-large-uncased-vocab.txt",
<add> 'distilbert-base-german-cased': "https://s3.amazonaws.com/models.huggingface.co/bert/distilbert-base-german-cased-vocab.txt"
<ide> }
<ide> }
<ide> | 1 |
PHP | PHP | remove noise hint | dba46f7ece3ed0bdd0a9d589347f72df143a6049 | <ide><path>src/TestSuite/ConsoleIntegrationTestTrait.php
<ide> public function exec(string $command, array $input = []): void
<ide> *
<ide> * @return void
<ide> */
<del> public function tearDown(): void
<add> public function tearDown()
<ide> {
<ide> parent::tearDown();
<ide> | 1 |
Python | Python | add tests for eager retry without throw | 92c8bc2a58f8fedf9fe98083febb8c338cbda09f | <ide><path>t/unit/tasks/test_tasks.py
<ide> def retry_task_noargs(self, **kwargs):
<ide>
<ide> self.retry_task_noargs = retry_task_noargs
<ide>
<add> @self.app.task(bind=True, max_retries=3, iterations=0, shared=False)
<add> def retry_task_without_throw(self, **kwargs):
<add> self.iterations += 1
<add> try:
<add> if self.request.retries >= 3:
<add> return 42
<add> else:
<add> raise Exception("random code exception")
<add> except Exception as exc:
<add> return self.retry(exc=exc, throw=False)
<add>
<add> self.retry_task_without_throw = retry_task_without_throw
<add>
<ide> @self.app.task(bind=True, max_retries=3, iterations=0,
<ide> base=MockApplyTask, shared=False)
<ide> def retry_task_mockapply(self, arg1, arg2, kwarg=1):
<ide> def test_retry_kwargs_can_be_empty(self):
<ide> finally:
<ide> self.retry_task_mockapply.pop_request()
<ide>
<add> def test_retry_eager(self):
<add> assert self.retry_task_without_throw.apply().get() == 42
<add>
<ide> def test_retry_not_eager(self):
<ide> self.retry_task_mockapply.push_request()
<ide> try: | 1 |
Text | Text | add holimetrix in user list | 1b869db30304fb1847bb310114d5a96e5c0f6b95 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> * [Cotap](https://github.com/cotap/) [[@maraca](https://github.com/maraca) & [@richardchew](https://github.com/richardchew)]
<ide> * Easy Taxi [[@caique-lima](https://github.com/caique-lima)]
<ide> * [FreshBooks](https://github.com/freshbooks) [[@DinoCow](https://github.com/DinoCow)]
<add>* [Holimetrix](http://holimetrix.com/) [[@KettererThib](https://github.com/thibault-ketterer)]
<ide> * [Handy](http://www.handy.com/careers/73115?gh_jid=73115&gh_src=o5qcxn) [[@marcintustin](https://github.com/marcintustin) / [@mtustin-handy](https://github.com/mtustin-handy)]
<ide> * [Jampp](https://github.com/jampp)
<ide> * [LingoChamp](http://www.liulishuo.com/) [[@haitaoyao](https://github.com/haitaoyao)] | 1 |
Ruby | Ruby | add tests for duration multiplication and division | 376b687cb70d7cd8d84bd5f7c2acc45153359985 | <ide><path>activesupport/test/core_ext/duration_test.rb
<ide> def test_date_added_with_multiplied_duration
<ide> assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 1.day * 2
<ide> end
<ide>
<add> def test_date_added_with_multiplied_duration_larger_than_one_month
<add> assert_equal Date.civil(2017, 2, 15), Date.civil(2017, 1, 1) + 1.day * 45
<add> end
<add>
<add> def test_date_added_with_divided_duration
<add> assert_equal Date.civil(2017, 1, 3), Date.civil(2017, 1, 1) + 4.days / 2
<add> end
<add>
<add> def test_date_added_with_divided_duration_larger_than_one_month
<add> assert_equal Date.civil(2017, 2, 15), Date.civil(2017, 1, 1) + 90.days / 2
<add> end
<add>
<ide> def test_plus_with_time
<ide> assert_equal 1 + 1.second, 1.second + 1, "Duration + Numeric should == Numeric + Duration"
<ide> end | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.