content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
remove unused architectures variable
4dbfc815d468bbf17207083932a11a6e29579a8d
<ide><path>tools/openblas_support.py <ide> OPENBLAS_LONG = 'v0.3.13-62-gaf2b0d02' <ide> BASE_LOC = 'https://anaconda.org/multibuild-wheels-staging/openblas-libs' <ide> BASEURL = f'{BASE_LOC}/{OPENBLAS_LONG}/download' <del>ARCHITECTURES = ['arm64', 'aarch64', 'x86_64', 'i686', 'ppc64le', 's390x'] <ide> SUPPORTED_PLATFORMS = [ <ide> 'linux-aarch64', <ide> 'linux-x86_64',
1
Ruby
Ruby
add libiconv to uses_from_macos whitelist
d6cf14fd1e9a8a4804947a616b50770f58816720
<ide><path>Library/Homebrew/rubocops/uses_from_macos.rb <ide> class UsesFromMacos < FormulaCop <ide> krb5 <ide> libedit <ide> libffi <add> libiconv <ide> libpcap <ide> libxml2 <ide> libxslt
1
Mixed
Ruby
remove deprecated constants from action controller
4b97ce5eb16cc20207516387fba98bf577e2e281
<ide><path>actionpack/CHANGELOG.md <add>* Remove deprecated constants from Action Controller: <add> <add> ActionController::AbstractRequest => ActionDispatch::Request <add> ActionController::Request => ActionDispatch::Request <add> ActionController::AbstractResponse => ActionDispatch::Response <add> ActionController::Response => ActionDispatch::Response <add> ActionController::Routing => ActionDispatch::Routing <add> ActionController::Integration => ActionDispatch::Integration <add> ActionController::IntegrationTest => ActionDispatch::IntegrationTest <add> <add> *Carlos Antonio da Silva* <add> <ide> * Fix `Mime::Type.parse` when bad accepts header is looked up. Previously it <ide> was setting `request.formats` with an array containing a `nil` value, which <ide> raised an error when setting the controller formats. <ide><path>actionpack/lib/action_controller/deprecated.rb <del>ActionController::AbstractRequest = ActionController::Request = ActionDispatch::Request <del>ActionController::AbstractResponse = ActionController::Response = ActionDispatch::Response <del>ActionController::Routing = ActionDispatch::Routing <del> <del>ActiveSupport::Deprecation.warn 'ActionController::AbstractRequest and ActionController::Request are deprecated and will be removed, use ActionDispatch::Request instead.' <del>ActiveSupport::Deprecation.warn 'ActionController::AbstractResponse and ActionController::Response are deprecated and will be removed, use ActionDispatch::Response instead.' <del>ActiveSupport::Deprecation.warn 'ActionController::Routing is deprecated and will be removed, use ActionDispatch::Routing instead.' <ide>\ No newline at end of file <ide><path>actionpack/lib/action_controller/deprecated/integration_test.rb <del>ActionController::Integration = ActionDispatch::Integration <del>ActionController::IntegrationTest = ActionDispatch::IntegrationTest <del> <del>ActiveSupport::Deprecation.warn 'ActionController::Integration is deprecated and will be removed, use ActionDispatch::Integration instead.' <del>ActiveSupport::Deprecation.warn 'ActionController::IntegrationTest is deprecated and will be removed, use ActionDispatch::IntegrationTest instead.'
3
Text
Text
add opus interactive to inthewild
a99e9b544a4834759c9fa410336260304b2eb9af
<ide><path>INTHEWILD.md <ide> Currently, **officially** using Airflow: <ide> 1. [Opensignal](https://www.opensignal.com) [@harrisjoseph](https://github.com/harrisjoseph) <ide> 1. [OpenSlate](https://openslate.com) [@marcusianlevine](https://github.com/marcusianlevine) <ide> 1. [Optum](https://www.optum.com/) - [UnitedHealthGroup](https://www.unitedhealthgroup.com/) [[@fhoda](https://github.com/fhoda), [@ianstanton](https://github.com/ianstanton), [@nilaybhatt](https://github.com/NilayBhatt),[@hiteshrd](https://github.com/hiteshrd)] <add>1. [Opus Interactive](https://www.opusinteractive.com/) [[@Opus-Interactive](https://github.com/Opus-Interactive)] <ide> 1. [OrangeBank](https://www.orangebank.fr/) [[@HamzaBoukraa](https://github.com/HamzaBoukraa)] <ide> 1. [Outcome Health](https://www.outcomehealth.com/) [[@mikethoun](https://github.com/mikethoun), [@rolandotribo](https://github.com/rolandotribo)] <ide> 1. [Overstock](https://www.github.com/overstock) [[@mhousley](https://github.com/mhousley) & [@mct0006](https://github.com/mct0006)]
1
Ruby
Ruby
make i18n date/time tests timezone independent
0ac342fbe5727c22dbce58e375e9b42dd2a92ef5
<ide><path>activesupport/test/i18n_test.rb <ide> def setup <ide> uses_mocha 'I18nTimeZoneTest' do <ide> def test_time_zone_localization_with_default_format <ide> Time.zone.stubs(:now).returns Time.local(2000) <del> assert_equal "Sat, 01 Jan 2000 00:00:00 +0100", I18n.localize(Time.zone.now) <add> assert_equal Time.zone.now.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(Time.zone.now) <ide> end <ide> end <ide> <ide> def test_date_localization_should_use_default_format <del> assert_equal "2008-07-02", I18n.localize(@date) <add> assert_equal @date.strftime("%Y-%m-%d"), I18n.localize(@date) <ide> end <ide> <ide> def test_date_localization_with_default_format <del> assert_equal "2008-07-02", I18n.localize(@date, :format => :default) <add> assert_equal @date.strftime("%Y-%m-%d"), I18n.localize(@date, :format => :default) <ide> end <ide> <ide> def test_date_localization_with_short_format <del> assert_equal "Jul 02", I18n.localize(@date, :format => :short) <add> assert_equal @date.strftime("%b %d"), I18n.localize(@date, :format => :short) <ide> end <ide> <ide> def test_date_localization_with_long_format <del> assert_equal "July 02, 2008", I18n.localize(@date, :format => :long) <add> assert_equal @date.strftime("%B %d, %Y"), I18n.localize(@date, :format => :long) <ide> end <ide> <del> def test_time_localization_should_use_default_format <del> assert_equal "Wed, 02 Jul 2008 16:47:01 +0100", I18n.localize(@time) <add> def test_time_localization_should_use_default_format <add> assert_equal @time.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(@time) <ide> end <ide> <ide> def test_time_localization_with_default_format <del> assert_equal "Wed, 02 Jul 2008 16:47:01 +0100", I18n.localize(@time, :format => :default) <add> assert_equal @time.strftime("%a, %d %b %Y %H:%M:%S %z"), I18n.localize(@time, :format => :default) <ide> end <ide> <ide> def test_time_localization_with_short_format <del> assert_equal "02 Jul 16:47", I18n.localize(@time, :format => :short) <add> assert_equal @time.strftime("%d %b %H:%M"), I18n.localize(@time, :format => :short) <ide> end <ide> <ide> def test_time_localization_with_long_format <del> assert_equal "July 02, 2008 16:47", I18n.localize(@time, :format => :long) <add> assert_equal @time.strftime("%B %d, %Y %H:%M"), I18n.localize(@time, :format => :long) <ide> end <ide> <ide> def test_day_names
1
Text
Text
add pwd to bash guide, very common
b3368db4e3b1a95833ca111a312ecdcc0ae4aeba
<ide><path>guide/english/bash/bash-pwd/index.md <add>--- <add>title: Bash pwd <add>--- <add> <add>## Bash pwd <add> <add>`pwd` or 'print working directory' is a command on Unix-like operating systems to show you which directory you are currently in. <add> <add>### Usage <add> <add>```bash <add>pwd <add>``` <add>You can see the directory you are in. <add> <add>Most used options: <add>It is normally used without any options. <add> <add>### Example: <add>Determine which directory you are in. <add> <add>```bash <add>$ pwd <add>/users/username <add>``` <add>It looks like we are in the home directory. <add> <add>#### More Information: <add> <add>* [Wikipedia](https://en.wikipedia.org/wiki/Pwd) <add>* [Shapeshed](https://shapeshed.com/unix-pwd/)
1
PHP
PHP
expand doc blocks
85a906c0fc92a3a68d6fdb512cd85d33416205bc
<ide><path>lib/Cake/Network/Email/CakeEmail.php <ide> public function message($type = null) { <ide> /** <ide> * Configuration to use when send email <ide> * <add> * ### Usage <add> * <add> * Load configuration from `app/Config/email.php`: <add> * <add> * `$email->config('default');` <add> * <add> * Merge an array of configuration into the instance: <add> * <add> * `$email->config(array('to' => 'bill@example.com'));` <add> * <ide> * @param string|array $config String with configuration name (from email.php), array with config or null to return current config <ide> * @return string|array|CakeEmail <ide> */
1
PHP
PHP
remove optimize call
44c61252b5762ff53ad181ed416e3006c50a6a9b
<ide><path>src/Illuminate/Foundation/Console/AppNameCommand.php <ide> public function fire() <ide> $this->info('Application namespace set!'); <ide> <ide> $this->composer->dumpAutoloads(); <del> <del> $this->call('clear-compiled'); <ide> <del> $this->call('optimize'); <add> $this->call('clear-compiled'); <ide> } <ide> <ide> /**
1
Python
Python
add an execv template for stress tests
dca18a30184497eea480b473b0a1337a71f408a7
<ide><path>funtests/stress/stress/templates.py <ide> class events(default): <ide> CELERY_SEND_EVENTS = True <ide> CELERY_SEND_TASK_SENT_EVENT = True <ide> <add> <ide> @template() <ide> class smallcache(default): <ide> CELERY_MAX_CACHED_RESULTS = 10 <add> <add> <add>@template() <add>class execv(default): <add> CELERYD_FORCE_EXECV = True
1
Text
Text
remove react as we will cover it in walkthrough
ec6ddb8eebd01ed481a908660ffe25a6271b24d5
<ide><path>SUMMARY.md <ide> * [Next Steps](/docs/advanced/NextSteps.md) <ide> * [Recipes](/docs/recipes/README.md) <ide> * [Reducing Boilerplate](/docs/recipes/ReducingBoilerplate.md) <del> * [Usage with React](/docs/recipes/UsageWithReact.md) <ide> * [Server Rendering](/docs/recipes/ServerRendering.md) <ide> * [Writing Tests](/docs/recipes/WritingTests.md) <ide> * [Troubleshooting](docs/Troubleshooting.md)
1
Java
Java
update copyright date
5220410768381c2a16a06b5d323942798bba116b
<ide><path>spring-test/src/main/java/org/springframework/test/context/DynamicPropertySource.java <ide> /* <del> * Copyright 2002-2020 the original author or authors. <add> * Copyright 2002-2022 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License.
1
Mixed
Python
update backend strings
205c61178d10089cbe0fbc90950dbe0cb9d380dc
<ide><path>docs/templates/activations.md <ide> This is equivalent to: <ide> model.add(Dense(64, activation='tanh')) <ide> ``` <ide> <del>You can also pass an element-wise Tensorflow/Theano function as an activation: <add>You can also pass an element-wise TensorFlow/Theano/CNTK function as an activation: <ide> <ide> ```python <ide> from keras import backend as K <ide> model.add(Activation(K.tanh)) <ide> <ide> ## On "Advanced Activations" <ide> <del>Activations that are more complex than a simple Tensorflow/Theano function (eg. learnable activations, which maintain a state) are available as [Advanced Activation layers](layers/advanced-activations.md), and can be found in the module `keras.layers.advanced_activations`. These include `PReLU` and `LeakyReLU`. <add>Activations that are more complex than a simple TensorFlow/Theano/CNTK function (eg. learnable activations, which maintain a state) are available as [Advanced Activation layers](layers/advanced-activations.md), and can be found in the module `keras.layers.advanced_activations`. These include `PReLU` and `LeakyReLU`. <ide><path>keras/applications/mobilenet.py <ide> ------------------------------------------------------------------------ <ide> <ide> The weights for all 16 models are obtained and translated <del>from Tensorflow checkpoints found at <add>from TensorFlow checkpoints found at <ide> https://github.com/tensorflow/models/blob/master/slim/nets/mobilenet_v1.md <ide> <ide> # Reference <ide> def MobileNet(input_shape=None, <ide> """ <ide> <ide> if K.backend() != 'tensorflow': <del> raise RuntimeError('Only Tensorflow backend is currently supported, ' <add> raise RuntimeError('Only TensorFlow backend is currently supported, ' <ide> 'as other backends do not support ' <ide> 'depthwise convolution.') <ide> <ide><path>keras/backend/tensorflow_backend.py <ide> def is_keras_tensor(x): <ide> ```python <ide> >>> from keras import backend as K <ide> >>> np_var = numpy.array([1, 2]) <del> >>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic yensor. <add> >>> K.is_keras_tensor(np_var) # A numpy array is not a symbolic tensor. <ide> ValueError <ide> >>> k_var = tf.placeholder('float32', shape=(1,1)) <del> >>> K.is_keras_tensor(k_var) # A variable created directly from tensorflow/theano is not a Keras tensor. <add> >>> K.is_keras_tensor(k_var) # A variable indirectly created outside of keras is not a Keras tensor. <ide> False <ide> >>> keras_var = K.variable(np_var) <ide> >>> K.is_keras_tensor(keras_var) # A variable created with the keras backend is a Keras tensor. <ide> def function(inputs, outputs, updates=None, **kwargs): <ide> if kwargs: <ide> for key in kwargs: <ide> if not (has_arg(tf.Session.run, key, True) or has_arg(Function.__init__, key, True)): <del> msg = 'Invalid argument "%s" passed to K.function with Tensorflow backend' % key <add> msg = 'Invalid argument "%s" passed to K.function with TensorFlow backend' % key <ide> raise ValueError(msg) <ide> return Function(inputs, outputs, updates=updates, **kwargs) <ide> <ide> def conv2d(x, kernel, strides=(1, 1), padding='valid', <ide> strides: strides tuple. <ide> padding: string, `"same"` or `"valid"`. <ide> data_format: string, `"channels_last"` or `"channels_first"`. <del> Whether to use Theano or TensorFlow data format <add> Whether to use Theano or TensorFlow/CNTK data format <ide> for inputs/kernels/outputs. <ide> dilation_rate: tuple of 2 integers. <ide> <ide> def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), <ide> strides: strides tuple. <ide> padding: string, `"same"` or `"valid"`. <ide> data_format: string, `"channels_last"` or `"channels_first"`. <del> Whether to use Theano or TensorFlow data format <add> Whether to use Theano or TensorFlow/CNTK data format <ide> for inputs/kernels/outputs. <ide> <ide> # Returns <ide> def conv3d(x, kernel, strides=(1, 1, 1), padding='valid', <ide> strides: strides tuple. <ide> padding: string, `"same"` or `"valid"`. <ide> data_format: string, `"channels_last"` or `"channels_first"`. <del> Whether to use Theano or TensorFlow data format <add> Whether to use Theano or TensorFlow/CNTK data format <ide> for inputs/kernels/outputs. <ide> dilation_rate: tuple of 3 integers. <ide> <ide> def conv3d_transpose(x, kernel, output_shape, strides=(1, 1, 1), <ide> strides: strides tuple. <ide> padding: string, "same" or "valid". <ide> data_format: string, `"channels_last"` or `"channels_first"`. <del> Whether to use Theano or TensorFlow data format <add> Whether to use Theano or TensorFlow/CNTK data format <ide> for inputs/kernels/outputs. <ide> <ide> # Returns <ide><path>keras/backend/theano_backend.py <ide> def conv2d_transpose(x, kernel, output_shape, strides=(1, 1), <ide> <ide> if padding == 'same' and kernel_shape[0] % 2 == 0: <ide> raise ValueError('In `Conv2DTranspose`, with padding mode `same`, ' <del> 'even kernel sizes are only supported with Tensorflow. ' <del> 'With Theano, set `kernel_size` to an odd number.') <add> 'even kernel sizes are not supported with Theano. ' <add> 'You can set `kernel_size` to an odd number.') <ide> <ide> kernel_shape = _preprocess_conv2d_filter_shape(kernel_shape, data_format) <ide> <ide> def conv3d_transpose(x, kernel, output_shape, strides=(1, 1, 1), <ide> <ide> if padding == 'same' and kernel_shape[0] % 2 == 0: <ide> raise ValueError('In `Conv3DTranspose`, with padding mode `same`, ' <del> 'even kernel sizes are only supported with Tensorflow. ' <del> 'With Theano, set `kernel_size` to an odd number.') <add> 'even kernel sizes are not supported with Theano. ' <add> 'You can set `kernel_size` to an odd number.') <ide> <ide> kernel_shape = _preprocess_conv3d_filter_shape(kernel_shape, data_format) <ide> <ide><path>keras/engine/training.py <ide> def compile(self, optimizer, loss, metrics=None, loss_weights=None, <ide> If the model has multiple outputs, you can use a different <ide> `sample_weight_mode` on each output by passing a <ide> dictionary or a list of modes. <del> **kwargs: when using the Theano backend, these arguments <del> are passed into K.function. When using the Tensorflow backend, <add> **kwargs: when using the Theano/CNTK backends, these arguments <add> are passed into K.function. When using the TensorFlow backend, <ide> these arguments are passed into `tf.Session.run`. <ide> <ide> # Raises <ide><path>keras/models.py <ide> def compile(self, optimizer, loss, <ide> sample_weight_mode: if you need to do timestep-wise <ide> sample weighting (2D weights), set this to "temporal". <ide> "None" defaults to sample-wise weights (1D). <del> **kwargs: for Theano backend, these are passed into K.function. <del> When using the Tensorflow backend, these are passed into <del> `tf.Session.run`. <add> **kwargs: for Theano/CNTK backends, these are passed into <add> K.function. When using the TensorFlow backend, these are <add> passed into `tf.Session.run`. <ide> <ide> # Example <ide> ```python <ide><path>tests/keras/applications/applications_test.py <ide> def test_inceptionv3_pooling(): <ide> <ide> @keras_test <ide> @pytest.mark.skipif((K.backend() != 'tensorflow'), <del> reason="MobileNets are supported only on Tensorflow") <add> reason="MobileNets are supported only on TensorFlow") <ide> def test_mobilenet(): <ide> model = applications.MobileNet(weights=None) <ide> assert model.output_shape == (None, 1000) <ide> <ide> <ide> @keras_test <ide> @pytest.mark.skipif((K.backend() != 'tensorflow'), <del> reason="MobileNets are supported only on Tensorflow") <add> reason="MobileNets are supported only on TensorFlow") <ide> def test_mobilenet_no_top(): <ide> model = applications.MobileNet(weights=None, include_top=False) <ide> assert model.output_shape == (None, None, None, 1024) <ide> <ide> <ide> @keras_test <ide> @pytest.mark.skipif((K.backend() != 'tensorflow'), <del> reason="MobileNets are supported only on Tensorflow") <add> reason="MobileNets are supported only on TensorFlow") <ide> def test_mobilenet_pooling(): <ide> model = applications.MobileNet(weights=None, include_top=False, pooling='avg') <ide> assert model.output_shape == (None, 1024) <ide><path>tests/keras/backend/backend_test.py <ide> def test_ctc(self): <ide> label_lens = np.expand_dims(np.asarray([5, 4]), 1) <ide> input_lens = np.expand_dims(np.asarray([5, 5]), 1) # number of timesteps <ide> <del> # the Theano and Tensorflow CTC code use different methods to ensure <add> # the Theano and TensorFlow CTC code use different methods to ensure <ide> # numerical stability. The Theano code subtracts out the max <ide> # before the final log, so the results are different but scale <ide> # identically and still train properly
8
Javascript
Javascript
delete dead code in sourcemap
f2ec64fbcff03753a3e1afd9f5fc9bffd805263d
<ide><path>lib/internal/source_map/source_map.js <ide> class StringCharIterator { <ide> */ <ide> class SourceMap { <ide> #payload; <del> #reverseMappingsBySourceURL = []; <ide> #mappings = []; <ide> #sources = {}; <ide> #sourceContentByURL = {}; <ide> class SourceMap { <ide> this.#mappings.push([lineNumber, columnNumber, sourceURL, <ide> sourceLineNumber, sourceColumnNumber]); <ide> } <del> <del> for (let i = 0; i < this.#mappings.length; ++i) { <del> const mapping = this.#mappings[i]; <del> const url = mapping[2]; <del> if (!url) <del> continue; <del> if (!this.#reverseMappingsBySourceURL[url]) <del> this.#reverseMappingsBySourceURL[url] = []; <del> const reverseMappings = this.#reverseMappingsBySourceURL[url]; <del> const sourceLine = mapping[3]; <del> if (!reverseMappings[sourceLine]) <del> reverseMappings[sourceLine] = [mapping[0], mapping[1]]; <del> } <ide> }; <ide> } <ide>
1
Python
Python
improve __repr__ if script didn't run yet
6d922eb88c9f86b2a3df33133c8530c3bcb63078
<ide><path>libcloud/compute/deployment.py <ide> def __repr__(self): <ide> stdout = self.stdout[:30] + '...' <ide> stderr = self.stderr[:30] + '...' <ide> else: <add> exit_status = 'script didn\'t run yet' <ide> stdout = None <ide> stderr = None <ide> return ("<ScriptDeployment script=%s, exit_status=%s, stdout=%s, "
1
Javascript
Javascript
adjust browser class name
b05f4da9b5c7cca4f1badc021a8ebb0183380906
<ide><path>bin/run-tests-browser-runner.js <ide> const puppeteer = require('puppeteer'); <ide> const chalk = require('chalk'); <ide> const fs = require('fs'); <ide> <del>module.exports = class BroswerRunner { <add>module.exports = class BrowserRunner { <ide> constructor() { <ide> this.resolveTest = undefined; <ide> this.rejectTest = undefined; <ide><path>bin/run-tests.js <ide> let browserRunner; <ide> function getBrowserRunner() { <ide> if (browserRunner === undefined) { <ide> // requires new node <del> let BroswerRunner = require('./run-tests-browser-runner'); <del> browserRunner = new BroswerRunner(); <add> let BrowserRunner = require('./run-tests-browser-runner'); <add> browserRunner = new BrowserRunner(); <ide> } <ide> return browserRunner; <ide> }
2
Javascript
Javascript
document the init function for ember.coreobject
aedbf8b2092fb03e1e71105054ce3c5a010e7cd2
<ide><path>packages/ember-runtime/lib/system/core_object.js <ide> CoreObject.PrototypeMixin = Mixin.create({ <ide> <ide> isInstance: true, <ide> <add> /** <add> An overridable method called when objects are instantiated. By default, <add> does nothing unless it is overridden during class definition. <add> <add> Example: <add> <add> ```javascript <add> App.Person = Ember.Object.extend({ <add> init: function() { <add> alert('Name is ' + this.get('name')); <add> } <add> }); <add> <add> var steve = App.Person.create({ <add> name: "Steve" <add> }); <add> <add> // alerts 'Name is Steve'. <add> ``` <add> <add> NOTE: If you do end override init for a framework class like `Ember.View` or <add> `Ember.ArrayController`, be sure to call `this._super()` in your <add> `init` declaration! If you don't, Ember may not have an opportunity to <add> do important setup work, and you'll see strange behavior in your <add> application. <add> <add> ```javascript <add> App.PersonController = Ember.ArrayController.extend({ <add> // called when Ember sets up an instance of your PersonController, <add> // or when created using App.PersonController.create() <add> init: function(){ <add> this._super(); <add> alert('This is how you override init'); <add> } <add> }); <add> ``` <add> <add> @method init <add> */ <ide> init: function() {}, <ide> <ide> /**
1
Python
Python
handle raw_input vs input in python 2 and 3
a6c036180344899471c715ad5798b78c116fdee5
<ide><path>spacy/util.py <ide> basestring = str <ide> <ide> <add>try: <add> raw_input <add>except NameError: # Python 3 <add> raw_input = input <add> <add> <ide> LANGUAGES = {} <ide> _data_path = pathlib.Path(__file__).parent / 'data' <ide>
1
Ruby
Ruby
remove overzealous exceptions
4738974a78a010bda35f7647e9160732cb82af92
<ide><path>Library/Homebrew/extend/pathname.rb <ide> def ensure_writable <ide> end <ide> <ide> def install_info <del> unless self.symlink? <del> raise "Cannot install info entry for unbrewed info file '#{self}'" <del> end <ide> system '/usr/bin/install-info', '--quiet', self.to_s, (self.dirname+'dir').to_s <ide> end <ide> <ide> def uninstall_info <del> unless self.symlink? <del> raise "Cannot uninstall info entry for unbrewed info file '#{self}'" <del> end <ide> system '/usr/bin/install-info', '--delete', '--quiet', self.to_s, (self.dirname+'dir').to_s <ide> end <ide>
1
Text
Text
fix image paths
9a14613f4183575079edf10e2c7645c578048ce2
<ide><path>docs/api-guide/filtering.md <ide> If you are using the browsable API or admin API you may also want to install `cr <ide> <ide> With crispy forms installed, the browsable API will present a filtering control for `DjangoFilterBackend`, like so: <ide> <del>![Django Filter](../../docs/img/django-filter.png) <add>![Django Filter](../img/django-filter.png) <ide> <ide> #### Specifying filter fields <ide> <ide> The `SearchFilter` class supports simple single query parameter based searching, <ide> <ide> When in use, the browsable API will include a `SearchFilter` control: <ide> <del>![Search Filter](../../docs/img/search-filter.png) <add>![Search Filter](../img/search-filter.png) <ide> <ide> The `SearchFilter` class will only be applied if the view has a `search_fields` attribute set. The `search_fields` attribute should be a list of names of text type fields on the model, such as `CharField` or `TextField`. <ide> <ide> For more details, see the [Django documentation][search-django-admin]. <ide> <ide> The `OrderingFilter` class supports simple query parameter controlled ordering of results. <ide> <del>![Ordering Filter](../../docs/img/ordering-filter.png) <add>![Ordering Filter](../img/ordering-filter.png) <ide> <ide> By default, the query parameter is named `'ordering'`, but this may by overridden with the `ORDERING_PARAM` setting. <ide>
1
Text
Text
add 2.6.0 to changelog
7b226e94b3fa2ca2bef57ff8720acdd195a38e6a
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <del>### 2.6.0-beta.4 (May 09, 2016) <add>### 2.6.0 (June 8, 2016) <ide> <add>- [#13520](https://github.com/emberjs/ember.js/pull/13520) [BUGFIX] Fixes issues with `baseURL` and `rootURL` in `Ember.HistoryLocation` and ensures that `Ember.NoneLocation` properly handles `rootURL`. <add>- [#13590](https://github.com/emberjs/ember.js/pull/13590) [BUGFIX] Avoid `_lazyInjections` in production builds. <ide> - [#13442](https://github.com/emberjs/ember.js/pull/13442) [BUGFIX] Revert `Ember.Handlebars.SafeString` deprecation. <ide> - [#13449](https://github.com/emberjs/ember.js/pull/13449) [BUGFIX] Ensure that `Ember.get(null, 'foo')` returns `undefined`. <ide> - [#13465](https://github.com/emberjs/ember.js/pull/13465) [BUGFIX] Propagate loc information for inline link-to transform. <ide> - [#13461](https://github.com/emberjs/ember.js/pull/13461) [BUGFIX] Prevent `Ember.get` from attempting to retrieve properties on primitive objects. <del> <del>### 2.6.0-beta.3 (May 02, 2016) <del> <ide> - [#13418](https://github.com/emberjs/ember.js/pull/13418) [BUGFIX] Ensure that passing `run.later` a timeout value of `NaN` does not break all future <ide> timers. <ide> - [#13435](https://github.com/emberjs/ember.js/pull/13435) [BUGFIX] Fix positional parameters when used with component helper. <ide> - [#13438](https://github.com/emberjs/ember.js/pull/13438) [BUGFIX] Ensure custom components extending from `Ember.LinkComponent` can operate <ide> in both block and inline form. <del> <del>### 2.6.0-beta.2 (April 27, 2016) <del> <ide> - [#13356](https://github.com/emberjs/ember.js/pull/13356) [BUGFIX] Update `Registry#has` to always return true/false. <ide> - [#13359](https://github.com/emberjs/ember.js/pull/13359) [BUGFIX] Fix `{{if}}` and `{{unless}}` subexpression sometimes not updating. <ide> - [#13344](https://github.com/emberjs/ember.js/pull/13344) [BUGFIX] Revert `Ember.merge` deprecation. <ide> - [#13315](https://github.com/emberjs/ember.js/pull/13315) [CLEANUP] Remove legacy view related exports. <ide> - [#13310](https://github.com/emberjs/ember.js/pull/13310) [BUGFIX] Fix `mouseenter` typo in ember-testing helpers. <ide> - [#13314](https://github.com/emberjs/ember.js/pull/13314) [CLEANUP] Remove Metamorph view and mixin. <del> <del>### 2.6.0-beta.1 (April 11, 2016) <del> <ide> - [#13144](https://github.com/emberjs/ember.js/pull/13144) / [#13195](https://github.com/emberjs/ember.js/pull/13195) / [#13193](https://github.com/emberjs/ember.js/pull/13193) [CLEANUP] Remove support for `ember-legacy-views` addon. <ide> - [#13192](https://github.com/emberjs/ember.js/pull/13192) [CLEANUP] Remove support for `ember-legacy-controllers` addon. <ide> - [#13295](https://github.com/emberjs/ember.js/pull/13295) [CLEANUP] Disable `render` helper in block form.
1
Javascript
Javascript
fix collada transparency handling.
92bb9158efc0d52fb95d12bf474dc857e8e3c639
<ide><path>examples/jsm/loaders/ColladaLoader.js <ide> class ColladaLoader extends Loader { <ide> break; <ide> case 'transparent': <ide> data[ child.nodeName ] = { <del> opaque: child.getAttribute( 'opaque' ), <add> opaque: child.hasAttribute( 'opaque' ) ? child.getAttribute( 'opaque' ) : 'A_ONE', <ide> data: parseEffectParameter( child ) <ide> }; <ide> break; <ide> class ColladaLoader extends Loader { <ide> material.opacity = color[ 0 ] * transparency.float; <ide> break; <ide> default: <del> material.opacity = 1 - transparency.float; <ide> console.warn( 'THREE.ColladaLoader: Invalid opaque type "%s" of transparent tag.', transparent.opaque ); <ide> <ide> }
1
Javascript
Javascript
fix remaining linting warnings
97d2d7fb8b69566eab0b26d3971665aced9665ec
<ide><path>src/text-editor-component.js <ide> function objectsEqual (a, b) { <ide> if (!a && b) return false <ide> if (a && !b) return false <ide> if (a && b) { <del> for (key in a) { <add> for (const key in a) { <ide> if (a[key] !== b[key]) return false <ide> } <del> for (key in b) { <add> for (const key in b) { <ide> if (a[key] !== b[key]) return false <ide> } <ide> }
1
Text
Text
fix typo in fs.md
88b497a11bec6c85496e1273f5ff2acefa62df11
<ide><path>doc/api/fs.md <ide> a string, a {Buffer}, or a {URL} object using the `file:` protocol. <ide> <ide> #### String paths <ide> <del>String form paths are interpreted as UTF-8 character sequences identifying <add>String from paths are interpreted as UTF-8 character sequences identifying <ide> the absolute or relative filename. Relative paths will be resolved relative <ide> to the current working directory as determined by calling `process.cwd()`. <ide>
1
Ruby
Ruby
make predicate builder about 2x faster
a1d236e93110a91d5fd7555cf8f84c8a98680cc3
<ide><path>activerecord/lib/active_record/relation/predicate_builder.rb <ide> def initialize(table) <ide> @handlers = [] <ide> <ide> register_handler(BasicObject, BasicObjectHandler.new(self)) <del> register_handler(Base, BaseHandler.new(self)) <ide> register_handler(Range, RangeHandler.new(self)) <ide> register_handler(Relation, RelationHandler.new) <ide> register_handler(Array, ArrayHandler.new(self)) <ide> def register_handler(klass, handler) <ide> end <ide> <ide> def build(attribute, value) <add> value = value.id if value.is_a?(Base) <ide> if table.type(attribute.name).force_equality?(value) <ide> bind = build_bind_attribute(attribute.name, value) <ide> attribute.eq(bind) <ide> def handler_for(object) <ide> end <ide> <ide> require "active_record/relation/predicate_builder/array_handler" <del>require "active_record/relation/predicate_builder/base_handler" <ide> require "active_record/relation/predicate_builder/basic_object_handler" <ide> require "active_record/relation/predicate_builder/range_handler" <ide> require "active_record/relation/predicate_builder/relation_handler" <ide><path>activerecord/lib/active_record/relation/predicate_builder/base_handler.rb <del># frozen_string_literal: true <del> <del>module ActiveRecord <del> class PredicateBuilder <del> class BaseHandler # :nodoc: <del> def initialize(predicate_builder) <del> @predicate_builder = predicate_builder <del> end <del> <del> def call(attribute, value) <del> predicate_builder.build(attribute, value.id) <del> end <del> <del> private <del> attr_reader :predicate_builder <del> end <del> end <del>end
2
PHP
PHP
add diffkeys() method
7f73bd2bc1eeefab73e38503f4f2d9419ecbefb6
<ide><path>src/Illuminate/Support/Collection.php <ide> public function diff($items) <ide> return new static(array_diff($this->items, $this->getArrayableItems($items))); <ide> } <ide> <add> /** <add> * Get the items in the collection whose keys are not present in the given items. <add> * <add> * @param mixed $items <add> * @return static <add> */ <add> public function diffKeys($items) <add> { <add> return new static(array_diff_key($this->items, $this->getArrayableItems($items))); <add> } <add> <ide> /** <ide> * Execute a callback over each item. <ide> *
1
Java
Java
fix wrong reference check in flatteniterable
4c7e62cfe92990ba5fd8d954cbd4364f291b986e
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java <ide> <ide> import org.reactivestreams.*; <ide> <del>import io.reactivex.functions.*; <add>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.QueueSubscription; <ide> import io.reactivex.internal.queue.SpscArrayQueue; <ide> public void onSubscribe(Subscription s) { <ide> @Override <ide> public void onNext(T t) { <ide> if (fusionMode != ASYNC && !queue.offer(t)) { <del> onError(new IllegalStateException("Queue is full?!")); <add> onError(new MissingBackpressureException("Queue is full?!")); <ide> return; <ide> } <ide> drain(); <ide> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, Queue<?> q) { <ide> return true; <ide> } <ide> if (d) { <del> if (error != null) { <del> Throwable e = Exceptions.terminate(error); <add> Throwable ex = error.get(); <add> if (ex != null) { <add> ex = Exceptions.terminate(error); <ide> <ide> current = null; <ide> q.clear(); <ide> <del> a.onError(e); <add> a.onError(ex); <ide> return true; <ide> } else <ide> if (empty) { <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterableTest.java <add>/** <add> * Copyright 2016 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.flowable; <add> <add>import java.util.Arrays; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.Flowable; <add>import io.reactivex.functions.*; <add>import io.reactivex.subscribers.TestSubscriber; <add> <add>public class FlowableFlattenIterableTest { <add> <add> @Test <add> public void normal() { <add> <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> <add> Flowable.range(1, 2) <add> .reduce(new BiFunction<Integer, Integer, Integer>() { <add> @Override <add> public Integer apply(Integer a, Integer b) { <add> return Math.max(a, b); <add> } <add> }) <add> .flatMapIterable(new Function<Integer, Iterable<Integer>>() { <add> @Override <add> public Iterable<Integer> apply(Integer v) { <add> return Arrays.asList(v, v + 1); <add> } <add> }) <add> .subscribe(ts); <add> <add> ts.assertValues(2, 3) <add> .assertNoErrors() <add> .assertComplete(); <add> } <add>}
2
Javascript
Javascript
add check for resilience to trailing slashes, etc
4f937bda18bd577febcb29e3969fe72b400d1a61
<ide><path>test/e2e/docsAppE2E.js <ide> describe('docs.angularjs.org', function () { <ide> var code = element(by.css('tt')); <ide> expect(code.getText()).toContain('guest!!!'); <ide> }); <add> <add> it('should be resilient to trailing slashes', function() { <add> browser.get('index-debug.html#!/api/ng/function/angular.noop/'); <add> var pageBody = element(by.css('h1')); <add> expect(pageBody.getText()).toEqual('angular.noop'); <add> }); <add> <add> it('should be resilient to trailing "index"', function() { <add> browser.get('index-debug.html#!/api/ng/function/angular.noop/index'); <add> var pageBody = element(by.css('h1')); <add> expect(pageBody.getText()).toEqual('angular.noop'); <add> }); <add> <add> it('should be resilient to trailing "index/"', function() { <add> browser.get('index-debug.html#!/api/ng/function/angular.noop/index/'); <add> var pageBody = element(by.css('h1')); <add> expect(pageBody.getText()).toEqual('angular.noop'); <add> }); <ide> }); <ide> }); <ide>\ No newline at end of file
1
Ruby
Ruby
update caveats documentation
99ed23347abb7a13af38e5af52487d36975550c3
<ide><path>Library/Homebrew/formula.rb <ide> def run_post_install <ide> @prefix_returns_versioned_prefix = false <ide> end <ide> <del> # Tell the user about any Homebrew-specific caveats or locations regarding <del> # this package. These should not contain setup instructions that would apply <del> # to installation through a different package manager on a different OS. <add> # Warn the user about any Homebrew-specific issues or quirks for this package <add> # These should not contain setup instructions that would apply to installation <add> # through a different package manager on a different OS. <ide> # @return [String] <ide> # <pre>def caveats <ide> # <<~EOS <del> # Are optional. Something the user should know? <add> # Are optional. Something the user must be warned about? <ide> # EOS <ide> # end</pre> <ide> #
1
Ruby
Ruby
improve tests (closes ) [zackchandler]
953de118db423fe678b5e4c55209f0fcd0b53bbf
<ide><path>activesupport/test/core_ext/blank_test.rb <ide> require File.dirname(__FILE__) + '/../abstract_unit' <ide> <add>class EmptyTrue <add> def empty?() true; end <add>end <add> <add>class EmptyFalse <add> def empty?() false; end <add>end <add> <add>class EmptyStripNotEmpty <add> def empty?() true; end <add> def strip() 'foo'; end <add>end <add> <add>class EmptyStripEmpty <add> def empty?() true; end <add> def strip() ''; end <add>end <add> <add>class NotEmptyStripNotEmpty <add> def empty?() false; end <add> def strip() 'foo'; end <add>end <add> <add>class NotEmptyStripEmpty <add> def empty?() false; end <add> def strip() ''; end <add>end <add> <ide> class BlankTest < Test::Unit::TestCase <del> BLANK = [nil, false, '', ' ', " \n\t \r ", [], {}] <del> NOT = [true, 0, 1, 'a', [nil], { nil => 0 }] <add> BLANK = [ EmptyTrue.new, EmptyStripNotEmpty.new, EmptyStripEmpty.new, <add> NotEmptyStripEmpty.new, nil, false, '', ' ', " \n\t \r ", <add> [], {} ] <add> NOT = [ EmptyFalse.new, NotEmptyStripNotEmpty.new, Object.new, true, <add> 0, 1, 'a', [nil], { nil => 0 } ] <ide> <ide> class EmptyObject <ide> def empty?
1
Mixed
Javascript
limit interactions to chartarea (+/-0.5px)
f1677b6652328f449c1995f3e551c1b666eb2c8f
<ide><path>docs/getting-started/v3-migration.md <ide> Chart.js 3.0 introduces a number of breaking changes. Chart.js 2.0 was released <ide> <ide> ### Interactions <ide> <add>* `interactions` are now limited to the chart area <ide> * `{mode: 'label'}` was replaced with `{mode: 'index'}` <ide> * `{mode: 'single'}` was replaced with `{mode: 'nearest', intersect: true}` <ide> * `modes['X-axis']` was replaced with `{mode: 'index', intersect: false}` <ide> Animation system was completely rewritten in Chart.js v3. Each property can now <ide> * `Element._view` <ide> * `TimeScale._getPixelForOffset` <ide> * `TimeScale.getLabelWidth` <add>* `Tooltip._lastActive` <ide> <ide> ### Renamed <ide> <ide><path>src/controllers/controller.horizontalBar.js <ide> defaults._set('horizontalBar', { <ide> scales: { <ide> x: { <ide> type: 'linear', <del> position: 'bottom' <add> position: 'bottom', <add> beginAtZero: true <ide> }, <ide> y: { <ide> type: 'category', <ide><path>src/core/core.interaction.js <ide> <ide> import helpers from '../helpers/index'; <ide> import {isNumber} from '../helpers/helpers.math'; <add>import {_isPointInArea} from '../helpers/helpers.canvas'; <ide> <ide> /** <ide> * Helper function to get relative position for an event <ide> function evaluateAllVisibleItems(chart, handler) { <ide> /** <ide> * Helper function to check the items at the hovered index on the index scale <ide> * @param {Chart} chart - the chart <add> * @param {string} axis - the axis mode. x|y|xy <add> * @param {object} position - the point to be nearest to <ide> * @param {function} handler - the callback to execute for each visible item <ide> * @return whether all scales were of a suitable type <ide> */ <ide> function getDistanceMetricForAxis(axis) { <ide> <ide> /** <ide> * Helper function to get the items that intersect the event position <del> * @param {ChartElement[]} items - elements to filter <add> * @param {Chart} chart - the chart <ide> * @param {object} position - the point to be nearest to <add> * @param {string} axis - the axis mode. x|y|xy <ide> * @return {ChartElement[]} the nearest items <ide> */ <ide> function getIntersectItems(chart, position, axis) { <ide> const items = []; <ide> <add> if (!_isPointInArea(position, chart.chartArea)) { <add> return items; <add> } <add> <ide> const evaluationFunc = function(element, datasetIndex, index) { <ide> if (element.inRange(position.x, position.y)) { <ide> items.push({element, datasetIndex, index}); <ide> function getNearestItems(chart, position, axis, intersect) { <ide> let minDistance = Number.POSITIVE_INFINITY; <ide> let items = []; <ide> <add> if (!_isPointInArea(position, chart.chartArea)) { <add> return items; <add> } <add> <ide> const evaluationFunc = function(element, datasetIndex, index) { <ide> if (intersect && !element.inRange(position.x, position.y)) { <ide> return; <ide><path>src/core/core.tooltip.js <ide> function createTooltipItem(chart, item) { <ide> const {label, value} = chart.getDatasetMeta(datasetIndex).controller._getLabelAndValue(index); <ide> <ide> return { <del> label: label, <del> value: value, <del> index: index, <del> datasetIndex: datasetIndex <add> label, <add> value, <add> index, <add> datasetIndex <ide> }; <ide> } <ide> <ide> class Tooltip extends Element { <ide> const me = this; <ide> me.opacity = 0; <ide> me._active = []; <del> me._lastActive = []; <ide> me.initialize(); <ide> } <ide> <ide> class Tooltip extends Element { <ide> * @returns {boolean} true if the tooltip changed <ide> */ <ide> handleEvent(e) { <del> var me = this; <del> var options = me.options; <del> var changed = false; <del> <del> me._lastActive = me._lastActive || []; <add> const me = this; <add> const options = me.options; <add> const lastActive = me._active || []; <add> let changed = false; <add> let active = []; <ide> <ide> // Find Active Elements for tooltips <del> if (e.type === 'mouseout') { <del> me._active = []; <del> } else { <del> me._active = me._chart.getElementsAtEventForMode(e, options.mode, options); <add> if (e.type !== 'mouseout') { <add> active = me._chart.getElementsAtEventForMode(e, options.mode, options); <ide> if (options.reverse) { <del> me._active.reverse(); <add> active.reverse(); <ide> } <ide> } <ide> <ide> // Remember Last Actives <del> changed = !helpers._elementsEqual(me._active, me._lastActive); <add> changed = !helpers._elementsEqual(active, lastActive); <ide> <ide> // Only handle target event on tooltip change <ide> if (changed) { <del> me._lastActive = me._active; <add> me._active = active; <ide> <ide> if (options.enabled || options.custom) { <ide> me._eventPosition = { <ide> class Tooltip extends Element { <ide> }; <ide> <ide> me.update(true); <del> // me.pivot(); <ide> } <ide> } <ide> <ide><path>src/helpers/helpers.canvas.js <ide> export function drawPoint(ctx, style, radius, x, y, rotation) { <ide> * @private <ide> */ <ide> export function _isPointInArea(point, area) { <del> var epsilon = 1e-6; // 1e-6 is margin in pixels for accumulated error. <add> const epsilon = 0.5; // margin - to match rounded decimals <ide> <ide> return point.x > area.left - epsilon && point.x < area.right + epsilon && <ide> point.y > area.top - epsilon && point.y < area.bottom + epsilon; <ide><path>test/specs/controller.line.tests.js <ide> describe('Chart.controllers.line', function() { <ide> }] <ide> }, <ide> options: { <add> scales: { <add> x: { <add> offset: true <add> } <add> }, <ide> elements: { <ide> point: { <ide> backgroundColor: 'rgb(100, 150, 200)', <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> var tooltip = chart.tooltip; <ide> <ide> expect(chart.lastActive[0].element).toEqual(point); <del> expect(tooltip._lastActive[0].element).toEqual(point); <add> expect(tooltip._active[0].element).toEqual(point); <ide> <ide> // Update and confirm tooltip is updated <ide> chart.update(); <ide> expect(chart.lastActive[0].element).toEqual(point); <del> expect(tooltip._lastActive[0].element).toEqual(point); <add> expect(tooltip._active[0].element).toEqual(point); <ide> }); <ide> <ide> it ('should update the metadata', function() { <ide><path>test/specs/core.interaction.tests.js <ide> describe('Core.Interaction', function() { <ide> type: 'click', <ide> chart: chart, <ide> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <add> x: chart.chartArea.left, <add> y: chart.chartArea.top <ide> }; <ide> <ide> var elements = Chart.Interaction.modes.index(chart, evt, {intersect: false}).map(item => item.element); <ide> describe('Core.Interaction', function() { <ide> type: 'click', <ide> chart: chart, <ide> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <add> x: chart.chartArea.left, <add> y: chart.chartArea.top <ide> }; <ide> <ide> var elements = Chart.Interaction.modes.index(chart, evt, {axis: 'xy', intersect: false}).map(item => item.element); <ide> describe('Core.Interaction', function() { <ide> type: 'click', <ide> chart: chart, <ide> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <add> x: chart.chartArea.left, <add> y: chart.chartArea.top <ide> }; <ide> <ide> var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'x', intersect: false}); <ide> describe('Core.Interaction', function() { <ide> type: 'click', <ide> chart: chart, <ide> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <add> x: chart.chartArea.left, <add> y: chart.chartArea.top <ide> }; <ide> <ide> var elements = Chart.Interaction.modes.dataset(chart, evt, {axis: 'y', intersect: false}); <ide> describe('Core.Interaction', function() { <ide> type: 'click', <ide> chart: chart, <ide> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <add> x: chart.chartArea.left, <add> y: chart.chartArea.top <ide> }; <ide> <ide> var elements = Chart.Interaction.modes.dataset(chart, evt, {intersect: false}); <ide> describe('Core.Interaction', function() { <ide> type: 'click', <ide> chart: chart, <ide> native: true, // needed otherwise things its a DOM event <del> x: 0, <del> y: 0 <add> x: chart.chartArea.left, <add> y: chart.chartArea.top <ide> }; <ide> <ide> // Nearest to 0,0 (top left) will be first point of dataset 2 <ide><path>test/specs/core.tooltip.tests.js <ide> describe('Core.Tooltip', function() { <ide> bubbles: true, <ide> cancelable: true, <ide> clientX: rect.left + point.x, <del> clientY: 0 <add> clientY: rect.top + chart.chartArea.top + 5 // +5 to make tests work consistently <ide> }); <ide> <ide> // Manually trigger rather than having an async test <ide><path>test/specs/helpers.canvas.tests.js <ide> describe('Chart.helpers.canvas', function() { <ide> expect(isPointInArea({x: -1e-12, y: -1e-12}, area)).toBe(true); <ide> expect(isPointInArea({x: 512, y: 256}, area)).toBe(true); <ide> expect(isPointInArea({x: 512 + 1e-12, y: 256 + 1e-12}, area)).toBe(true); <del> expect(isPointInArea({x: -1e-3, y: 0}, area)).toBe(false); <del> expect(isPointInArea({x: 0, y: 256 + 1e-3}, area)).toBe(false); <add> expect(isPointInArea({x: -0.5, y: 0}, area)).toBe(false); <add> expect(isPointInArea({x: 0, y: 256.5}, area)).toBe(false); <ide> }); <ide> }); <ide> });
10
Ruby
Ruby
fix redirect with block example
8d2487d9d458914bebb83fc74a6957f56dc0a8b5
<ide><path>actionpack/lib/action_dispatch/routing/redirection.rb <ide> module Redirection <ide> # params, depending of how many arguments your block accepts. A string is required as a <ide> # return value. <ide> # <del> # match 'jokes/:number', :to => redirect do |params, request| <add> # match 'jokes/:number', :to => redirect { |params, request| <ide> # path = (params[:number].to_i.even? ? "/wheres-the-beef" : "/i-love-lamp") <del> # "http://#{request.host_with_port}/#{path}" <del> # end <add> # "http://#{request.host_with_port}#{path}" <add> # } <ide> # <ide> # The options version of redirect allows you to supply only the parts of the url which need <ide> # to change, it also supports interpolation of the path similar to the first example.
1
Go
Go
fix broken json support in cli/command/formatter
3a32b587922eca87d1ab23689f407b75a8603ccb
<ide><path>cli/command/formatter/container.go <ide> type containerContext struct { <ide> c types.Container <ide> } <ide> <add>func (c *containerContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *containerContext) ID() string { <ide> c.AddHeader(containerIDHeader) <ide> if c.trunc { <ide><path>cli/command/formatter/container_test.go <ide> package formatter <ide> <ide> import ( <ide> "bytes" <add> "encoding/json" <ide> "fmt" <ide> "strings" <ide> "testing" <ide> func TestContainerContextWriteWithNoContainers(t *testing.T) { <ide> out.Reset() <ide> } <ide> } <add> <add>func TestContainerContextWriteJSON(t *testing.T) { <add> unix := time.Now().Add(-65 * time.Second).Unix() <add> containers := []types.Container{ <add> {ID: "containerID1", Names: []string{"/foobar_baz"}, Image: "ubuntu", Created: unix}, <add> {ID: "containerID2", Names: []string{"/foobar_bar"}, Image: "ubuntu", Created: unix}, <add> } <add> expectedCreated := time.Unix(unix, 0).String() <add> expectedJSONs := []map[string]interface{}{ <add> {"Command": "\"\"", "CreatedAt": expectedCreated, "ID": "containerID1", "Image": "ubuntu", "Labels": "", "LocalVolumes": "0", "Mounts": "", "Names": "foobar_baz", "Ports": "", "RunningFor": "About a minute", "Size": "0 B", "Status": ""}, <add> {"Command": "\"\"", "CreatedAt": expectedCreated, "ID": "containerID2", "Image": "ubuntu", "Labels": "", "LocalVolumes": "0", "Mounts": "", "Names": "foobar_bar", "Ports": "", "RunningFor": "About a minute", "Size": "0 B", "Status": ""}, <add> } <add> out := bytes.NewBufferString("") <add> err := ContainerWrite(Context{Format: "{{json .}}", Output: out}, containers) <add> if err != nil { <add> t.Fatal(err) <add> } <add> for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { <add> t.Logf("Output: line %d: %s", i, line) <add> var m map[string]interface{} <add> if err := json.Unmarshal([]byte(line), &m); err != nil { <add> t.Fatal(err) <add> } <add> assert.DeepEqual(t, m, expectedJSONs[i]) <add> } <add>} <add> <add>func TestContainerContextWriteJSONField(t *testing.T) { <add> containers := []types.Container{ <add> {ID: "containerID1", Names: []string{"/foobar_baz"}, Image: "ubuntu"}, <add> {ID: "containerID2", Names: []string{"/foobar_bar"}, Image: "ubuntu"}, <add> } <add> out := bytes.NewBufferString("") <add> err := ContainerWrite(Context{Format: "{{json .ID}}", Output: out}, containers) <add> if err != nil { <add> t.Fatal(err) <add> } <add> for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { <add> t.Logf("Output: line %d: %s", i, line) <add> var s string <add> if err := json.Unmarshal([]byte(line), &s); err != nil { <add> t.Fatal(err) <add> } <add> assert.Equal(t, s, containers[i].ID) <add> } <add>} <ide><path>cli/command/formatter/network.go <ide> type networkContext struct { <ide> n types.NetworkResource <ide> } <ide> <add>func (c *networkContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *networkContext) ID() string { <ide> c.AddHeader(networkIDHeader) <ide> if c.trunc { <ide><path>cli/command/formatter/network_test.go <ide> package formatter <ide> <ide> import ( <ide> "bytes" <add> "encoding/json" <ide> "strings" <ide> "testing" <ide> <ide> foobar_bar <ide> } <ide> } <ide> } <add> <add>func TestNetworkContextWriteJSON(t *testing.T) { <add> networks := []types.NetworkResource{ <add> {ID: "networkID1", Name: "foobar_baz"}, <add> {ID: "networkID2", Name: "foobar_bar"}, <add> } <add> expectedJSONs := []map[string]interface{}{ <add> {"Driver": "", "ID": "networkID1", "IPv6": "false", "Internal": "false", "Labels": "", "Name": "foobar_baz", "Scope": ""}, <add> {"Driver": "", "ID": "networkID2", "IPv6": "false", "Internal": "false", "Labels": "", "Name": "foobar_bar", "Scope": ""}, <add> } <add> <add> out := bytes.NewBufferString("") <add> err := NetworkWrite(Context{Format: "{{json .}}", Output: out}, networks) <add> if err != nil { <add> t.Fatal(err) <add> } <add> for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { <add> t.Logf("Output: line %d: %s", i, line) <add> var m map[string]interface{} <add> if err := json.Unmarshal([]byte(line), &m); err != nil { <add> t.Fatal(err) <add> } <add> assert.DeepEqual(t, m, expectedJSONs[i]) <add> } <add>} <add> <add>func TestNetworkContextWriteJSONField(t *testing.T) { <add> networks := []types.NetworkResource{ <add> {ID: "networkID1", Name: "foobar_baz"}, <add> {ID: "networkID2", Name: "foobar_bar"}, <add> } <add> out := bytes.NewBufferString("") <add> err := NetworkWrite(Context{Format: "{{json .ID}}", Output: out}, networks) <add> if err != nil { <add> t.Fatal(err) <add> } <add> for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { <add> t.Logf("Output: line %d: %s", i, line) <add> var s string <add> if err := json.Unmarshal([]byte(line), &s); err != nil { <add> t.Fatal(err) <add> } <add> assert.Equal(t, s, networks[i].ID) <add> } <add>} <ide><path>cli/command/formatter/reflect.go <add>package formatter <add> <add>import ( <add> "encoding/json" <add> "fmt" <add> "reflect" <add> "unicode" <add>) <add> <add>func marshalJSON(x interface{}) ([]byte, error) { <add> m, err := marshalMap(x) <add> if err != nil { <add> return nil, err <add> } <add> return json.Marshal(m) <add>} <add> <add>// marshalMap marshals x to map[string]interface{} <add>func marshalMap(x interface{}) (map[string]interface{}, error) { <add> val := reflect.ValueOf(x) <add> if val.Kind() != reflect.Ptr { <add> return nil, fmt.Errorf("expected a pointer to a struct, got %v", val.Kind()) <add> } <add> if val.IsNil() { <add> return nil, fmt.Errorf("expxected a pointer to a struct, got nil pointer") <add> } <add> valElem := val.Elem() <add> if valElem.Kind() != reflect.Struct { <add> return nil, fmt.Errorf("expected a pointer to a struct, got a pointer to %v", valElem.Kind()) <add> } <add> typ := val.Type() <add> m := make(map[string]interface{}) <add> for i := 0; i < val.NumMethod(); i++ { <add> k, v, err := marshalForMethod(typ.Method(i), val.Method(i)) <add> if err != nil { <add> return nil, err <add> } <add> if k != "" { <add> m[k] = v <add> } <add> } <add> return m, nil <add>} <add> <add>var unmarshallableNames = map[string]struct{}{"FullHeader": {}} <add> <add>// marshalForMethod returns the map key and the map value for marshalling the method. <add>// It returns ("", nil, nil) for valid but non-marshallable parameter. (e.g. "unexportedFunc()") <add>func marshalForMethod(typ reflect.Method, val reflect.Value) (string, interface{}, error) { <add> if val.Kind() != reflect.Func { <add> return "", nil, fmt.Errorf("expected func, got %v", val.Kind()) <add> } <add> name, numIn, numOut := typ.Name, val.Type().NumIn(), val.Type().NumOut() <add> _, blackListed := unmarshallableNames[name] <add> // FIXME: In text/template, (numOut == 2) is marshallable, <add> // if the type of the second param is error. <add> marshallable := unicode.IsUpper(rune(name[0])) && !blackListed && <add> numIn == 0 && numOut == 1 <add> if !marshallable { <add> return "", nil, nil <add> } <add> result := val.Call(make([]reflect.Value, numIn)) <add> intf := result[0].Interface() <add> return name, intf, nil <add>} <ide><path>cli/command/formatter/reflect_test.go <add>package formatter <add> <add>import ( <add> "reflect" <add> "testing" <add>) <add> <add>type dummy struct { <add>} <add> <add>func (d *dummy) Func1() string { <add> return "Func1" <add>} <add> <add>func (d *dummy) func2() string { <add> return "func2(should not be marshalled)" <add>} <add> <add>func (d *dummy) Func3() (string, int) { <add> return "Func3(should not be marshalled)", -42 <add>} <add> <add>func (d *dummy) Func4() int { <add> return 4 <add>} <add> <add>type dummyType string <add> <add>func (d *dummy) Func5() dummyType { <add> return dummyType("Func5") <add>} <add> <add>func (d *dummy) FullHeader() string { <add> return "FullHeader(should not be marshalled)" <add>} <add> <add>var dummyExpected = map[string]interface{}{ <add> "Func1": "Func1", <add> "Func4": 4, <add> "Func5": dummyType("Func5"), <add>} <add> <add>func TestMarshalMap(t *testing.T) { <add> d := dummy{} <add> m, err := marshalMap(&d) <add> if err != nil { <add> t.Fatal(err) <add> } <add> if !reflect.DeepEqual(dummyExpected, m) { <add> t.Fatalf("expected %+v, got %+v", <add> dummyExpected, m) <add> } <add>} <add> <add>func TestMarshalMapBad(t *testing.T) { <add> if _, err := marshalMap(nil); err == nil { <add> t.Fatal("expected an error (argument is nil)") <add> } <add> if _, err := marshalMap(dummy{}); err == nil { <add> t.Fatal("expected an error (argument is non-pointer)") <add> } <add> x := 42 <add> if _, err := marshalMap(&x); err == nil { <add> t.Fatal("expected an error (argument is a pointer to non-struct)") <add> } <add>} <ide><path>cli/command/formatter/service.go <ide> type serviceInspectContext struct { <ide> subContext <ide> } <ide> <add>func (ctx *serviceInspectContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(ctx) <add>} <add> <ide> func (ctx *serviceInspectContext) ID() string { <ide> return ctx.Service.ID <ide> } <ide><path>cli/command/formatter/volume.go <ide> type volumeContext struct { <ide> v types.Volume <ide> } <ide> <add>func (c *volumeContext) MarshalJSON() ([]byte, error) { <add> return marshalJSON(c) <add>} <add> <ide> func (c *volumeContext) Name() string { <ide> c.AddHeader(nameHeader) <ide> return c.v.Name <ide><path>cli/command/formatter/volume_test.go <ide> package formatter <ide> <ide> import ( <ide> "bytes" <add> "encoding/json" <ide> "strings" <ide> "testing" <ide> <ide> foobar_bar <ide> } <ide> } <ide> } <add> <add>func TestVolumeContextWriteJSON(t *testing.T) { <add> volumes := []*types.Volume{ <add> {Driver: "foo", Name: "foobar_baz"}, <add> {Driver: "bar", Name: "foobar_bar"}, <add> } <add> expectedJSONs := []map[string]interface{}{ <add> {"Driver": "foo", "Labels": "", "Links": "N/A", "Mountpoint": "", "Name": "foobar_baz", "Scope": "", "Size": "N/A"}, <add> {"Driver": "bar", "Labels": "", "Links": "N/A", "Mountpoint": "", "Name": "foobar_bar", "Scope": "", "Size": "N/A"}, <add> } <add> out := bytes.NewBufferString("") <add> err := VolumeWrite(Context{Format: "{{json .}}", Output: out}, volumes) <add> if err != nil { <add> t.Fatal(err) <add> } <add> for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { <add> t.Logf("Output: line %d: %s", i, line) <add> var m map[string]interface{} <add> if err := json.Unmarshal([]byte(line), &m); err != nil { <add> t.Fatal(err) <add> } <add> assert.DeepEqual(t, m, expectedJSONs[i]) <add> } <add>} <add> <add>func TestVolumeContextWriteJSONField(t *testing.T) { <add> volumes := []*types.Volume{ <add> {Driver: "foo", Name: "foobar_baz"}, <add> {Driver: "bar", Name: "foobar_bar"}, <add> } <add> out := bytes.NewBufferString("") <add> err := VolumeWrite(Context{Format: "{{json .Name}}", Output: out}, volumes) <add> if err != nil { <add> t.Fatal(err) <add> } <add> for i, line := range strings.Split(strings.TrimSpace(out.String()), "\n") { <add> t.Logf("Output: line %d: %s", i, line) <add> var s string <add> if err := json.Unmarshal([]byte(line), &s); err != nil { <add> t.Fatal(err) <add> } <add> assert.Equal(t, s, volumes[i].Name) <add> } <add>} <ide><path>cli/command/service/inspect_test.go <ide> package service <ide> <ide> import ( <ide> "bytes" <add> "encoding/json" <ide> "strings" <ide> "testing" <ide> "time" <ide> <ide> "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/cli/command/formatter" <add> "github.com/docker/docker/pkg/testutil/assert" <ide> ) <ide> <del>func TestPrettyPrintWithNoUpdateConfig(t *testing.T) { <add>func formatServiceInspect(t *testing.T, format formatter.Format, now time.Time) string { <ide> b := new(bytes.Buffer) <ide> <ide> endpointSpec := &swarm.EndpointSpec{ <ide> func TestPrettyPrintWithNoUpdateConfig(t *testing.T) { <ide> ID: "de179gar9d0o7ltdybungplod", <ide> Meta: swarm.Meta{ <ide> Version: swarm.Version{Index: 315}, <del> CreatedAt: time.Now(), <del> UpdatedAt: time.Now(), <add> CreatedAt: now, <add> UpdatedAt: now, <ide> }, <ide> Spec: swarm.ServiceSpec{ <ide> Annotations: swarm.Annotations{ <ide> func TestPrettyPrintWithNoUpdateConfig(t *testing.T) { <ide> }, <ide> }, <ide> UpdateStatus: swarm.UpdateStatus{ <del> StartedAt: time.Now(), <del> CompletedAt: time.Now(), <add> StartedAt: now, <add> CompletedAt: now, <ide> }, <ide> } <ide> <ide> ctx := formatter.Context{ <ide> Output: b, <del> Format: formatter.NewServiceFormat("pretty"), <add> Format: format, <ide> } <ide> <ide> err := formatter.ServiceInspectWrite(ctx, []string{"de179gar9d0o7ltdybungplod"}, func(ref string) (interface{}, []byte, error) { <ide> func TestPrettyPrintWithNoUpdateConfig(t *testing.T) { <ide> if err != nil { <ide> t.Fatal(err) <ide> } <add> return b.String() <add>} <ide> <del> if strings.Contains(b.String(), "UpdateStatus") { <add>func TestPrettyPrintWithNoUpdateConfig(t *testing.T) { <add> s := formatServiceInspect(t, formatter.NewServiceFormat("pretty"), time.Now()) <add> if strings.Contains(s, "UpdateStatus") { <ide> t.Fatal("Pretty print failed before parsing UpdateStatus") <ide> } <ide> } <add> <add>func TestJSONFormatWithNoUpdateConfig(t *testing.T) { <add> now := time.Now() <add> // s1: [{"ID":..}] <add> // s2: {"ID":..} <add> s1 := formatServiceInspect(t, formatter.NewServiceFormat(""), now) <add> t.Log("// s1") <add> t.Logf("%s", s1) <add> s2 := formatServiceInspect(t, formatter.NewServiceFormat("{{json .}}"), now) <add> t.Log("// s2") <add> t.Logf("%s", s2) <add> var m1Wrap []map[string]interface{} <add> if err := json.Unmarshal([]byte(s1), &m1Wrap); err != nil { <add> t.Fatal(err) <add> } <add> if len(m1Wrap) != 1 { <add> t.Fatalf("strange s1=%s", s1) <add> } <add> m1 := m1Wrap[0] <add> t.Logf("m1=%+v", m1) <add> var m2 map[string]interface{} <add> if err := json.Unmarshal([]byte(s2), &m2); err != nil { <add> t.Fatal(err) <add> } <add> t.Logf("m2=%+v", m2) <add> assert.DeepEqual(t, m2, m1) <add>} <ide><path>pkg/testutil/assert/assert.go <ide> package assert <ide> import ( <ide> "fmt" <ide> "path/filepath" <add> "reflect" <ide> "runtime" <ide> "strings" <ide> ) <ide> func NilError(t TestingT, err error) { <ide> } <ide> } <ide> <add>// DeepEqual compare the actual value to the expected value and fails the test if <add>// they are not "deeply equal". <add>func DeepEqual(t TestingT, actual, expected interface{}) { <add> if !reflect.DeepEqual(actual, expected) { <add> fatal(t, "Expected '%v' (%T) got '%v' (%T)", expected, expected, actual, actual) <add> } <add>} <add> <ide> // Error asserts that error is not nil, and contains the expected text, <ide> // otherwise it fails the test. <ide> func Error(t TestingT, err error, contains string) {
11
Python
Python
use json boolean and fix redundancy
545fcb2eeb111a8a61c25534baaf82ee73681887
<ide><path>airflow/hooks/hdfs_hook.py <ide> def get_conn(self): <ide> ''' When using HAClient, proxy_user must be the same, so is ok to always take the first ''' <ide> effective_user = self.proxy_user or connections[0].login <ide> if len(connections) == 1: <del> autoconfig = connections[0].extra_dejson.get('autoconfig', 'false') <del> if autoconfig == 'true': <add> autoconfig = connections[0].extra_dejson.get('autoconfig', False) <add> if autoconfig: <ide> client = AutoConfigClient(effective_user=effective_user, use_sasl=use_sasl) <ide> else: <ide> client = Client(connections[0].host, connections[0].port, <ide> effective_user=effective_user, use_sasl=use_sasl) <ide> elif len(connections) > 1: <ide> nn = [Namenode(conn.host, conn.port) for conn in connections] <ide> client = HAClient(nn, effective_user=effective_user, use_sasl=use_sasl) <del> elif len(connections) > 1: <del> nn = [Namenode(conn.host, conn.port) for conn in connections] <del> client = HAClient(nn, use_sasl=use_sasl, effective_user=effective_user) <ide> else: <ide> raise HDFSHookException("conn_id doesn't exist in the repository") <ide>
1
Text
Text
remove personal pronoun from worker_threads
623206c2d6e7bb1cb35afeafd457cecedf0b7c3d
<ide><path>doc/api/worker_threads.md <ide> added: v10.5.0 <ide> --> <ide> <ide> Disables further sending of messages on either side of the connection. <del>This method can be called once you know that no further communication <del>will happen over this `MessagePort`. <add>This method can be called when no further communication will happen over this <add>`MessagePort`. <ide> <ide> ### port.postMessage(value[, transferList]) <ide> <!-- YAML <ide> to have completed. <ide> <ide> **Warning**: Currently, not all code in the internals of Node.js is prepared to <ide> expect termination at arbitrary points in time and may crash if it encounters <del>that condition. Consequently, you should currently only call `.terminate()` if <del>it is known that the Worker thread is not accessing Node.js core modules other <del>than what is exposed in the `worker` module. <add>that condition. Consequently, only call `.terminate()` if it is known that the <add>Worker thread is not accessing Node.js core modules other than what is exposed <add>in the `worker` module. <ide> <ide> ### worker.threadId <ide> <!-- YAML
1
Python
Python
change occurrences of str.format to f-strings
61f3119467584de53a2f4395e3c03a8e12d67d30
<ide><path>ciphers/rsa_cipher.py <ide> def encryptAndWriteToFile( <ide> for i in range(len(encryptedBlocks)): <ide> encryptedBlocks[i] = str(encryptedBlocks[i]) <ide> encryptedContent = ",".join(encryptedBlocks) <del> encryptedContent = "{}_{}_{}".format(len(message), blockSize, encryptedContent) <add> encryptedContent = f"{len(message)}_{blockSize}_{encryptedContent}" <ide> with open(messageFilename, "w") as fo: <ide> fo.write(encryptedContent) <ide> return encryptedContent <ide><path>ciphers/rsa_key_generator.py <ide> def makeKeyFiles(name: int, keySize: int) -> None: <ide> publicKey, privateKey = generateKey(keySize) <ide> print("\nWriting public key to file %s_pubkey.txt..." % name) <ide> with open("%s_pubkey.txt" % name, "w") as out_file: <del> out_file.write("{},{},{}".format(keySize, publicKey[0], publicKey[1])) <add> out_file.write(f"{keySize},{publicKey[0]},{publicKey[1]}") <ide> <ide> print("Writing private key to file %s_privkey.txt..." % name) <ide> with open("%s_privkey.txt" % name, "w") as out_file: <del> out_file.write("{},{},{}".format(keySize, privateKey[0], privateKey[1])) <add> out_file.write(f"{keySize},{privateKey[0]},{privateKey[1]}") <ide> <ide> <ide> if __name__ == "__main__": <ide><path>compression/burrows_wheeler.py <ide> def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: <ide> entry_msg = "Provide a string that I will generate its BWT transform: " <ide> s = input(entry_msg).strip() <ide> result = bwt_transform(s) <del> bwt_output_msg = "Burrows Wheeler transform for string '{}' results in '{}'" <del> print(bwt_output_msg.format(s, result["bwt_string"])) <add> print( <add> f"Burrows Wheeler transform for string '{s}' results " <add> f"in '{result['bwt_string']}'" <add> ) <ide> original_string = reverse_bwt(result["bwt_string"], result["idx_original_string"]) <del> fmt = ( <del> "Reversing Burrows Wheeler transform for entry '{}' we get original" <del> " string '{}'" <add> print( <add> f"Reversing Burrows Wheeler transform for entry '{result['bwt_string']}' " <add> f"we get original string '{original_string}'" <ide> ) <del> print(fmt.format(result["bwt_string"], original_string)) <ide><path>data_structures/binary_tree/non_recursive_segment_tree.py <ide> def __init__(self, arr: list[T], fnc: Callable[[T, T], T]) -> None: <ide> :param arr: list of elements for the segment tree <ide> :param fnc: commutative function for combine two elements <ide> <del> >>> SegmentTree(['a', 'b', 'c'], lambda a, b: '{}{}'.format(a, b)).query(0, 2) <add> >>> SegmentTree(['a', 'b', 'c'], lambda a, b: f'{a}{b}').query(0, 2) <ide> 'abc' <ide> >>> SegmentTree([(1, 2), (2, 3), (3, 4)], <ide> ... lambda a, b: (a[0] + b[0], a[1] + b[1])).query(0, 2) <ide><path>data_structures/binary_tree/red_black_tree.py <ide> def __repr__(self) -> str: <ide> from pprint import pformat <ide> <ide> if self.left is None and self.right is None: <del> return "'{} {}'".format(self.label, (self.color and "red") or "blk") <add> return f"'{self.label} {(self.color and 'red') or 'blk'}'" <ide> return pformat( <ide> { <del> "%s %s" <del> % (self.label, (self.color and "red") or "blk"): (self.left, self.right) <add> f"{self.label} {(self.color and 'red') or 'blk'}": ( <add> self.left, <add> self.right, <add> ) <ide> }, <ide> indent=1, <ide> ) <ide><path>data_structures/linked_list/deque_doubly.py <ide> def __init__(self, link_p, element, link_n): <ide> self._next = link_n <ide> <ide> def has_next_and_prev(self): <del> return " Prev -> {}, Next -> {}".format( <del> self._prev is not None, self._next is not None <add> return ( <add> f" Prev -> {self._prev is not None}, Next -> {self._next is not None}" <ide> ) <ide> <ide> def __init__(self): <ide><path>dynamic_programming/climbing_stairs.py <ide> def climb_stairs(n: int) -> int: <ide> ... <ide> AssertionError: n needs to be positive integer, your input -7 <ide> """ <del> fmt = "n needs to be positive integer, your input {}" <del> assert isinstance(n, int) and n > 0, fmt.format(n) <add> assert ( <add> isinstance(n, int) and n > 0 <add> ), f"n needs to be positive integer, your input {n}" <ide> if n == 1: <ide> return 1 <ide> dp = [0] * (n + 1) <ide><path>dynamic_programming/iterating_through_submasks.py <ide> def list_of_submasks(mask: int) -> list[int]: <ide> <ide> """ <ide> <del> fmt = "mask needs to be positive integer, your input {}" <del> assert isinstance(mask, int) and mask > 0, fmt.format(mask) <add> assert ( <add> isinstance(mask, int) and mask > 0 <add> ), f"mask needs to be positive integer, your input {mask}" <ide> <ide> """ <ide> first submask iterated will be mask itself then operation will be performed <ide><path>machine_learning/knn_sklearn.py <ide> prediction = knn.predict(X_new) <ide> <ide> print( <del> "\nNew array: \n {}" <del> "\n\nTarget Names Prediction: \n {}".format(X_new, iris["target_names"][prediction]) <add> f"\nNew array: \n {X_new}\n\nTarget Names Prediction: \n" <add> f" {iris['target_names'][prediction]}" <ide> ) <ide><path>maths/3n_plus_1.py <ide> def n31(a: int) -> tuple[list[int], int]: <ide> """ <ide> <ide> if not isinstance(a, int): <del> raise TypeError("Must be int, not {}".format(type(a).__name__)) <add> raise TypeError(f"Must be int, not {type(a).__name__}") <ide> if a < 1: <ide> raise ValueError(f"Given integer must be greater than 1, not {a}") <ide> <ide><path>maths/quadratic_equations_complex_numbers.py <ide> def quadratic_roots(a: int, b: int, c: int) -> tuple[complex, complex]: <ide> <ide> <ide> def main(): <del> solutions = quadratic_roots(a=5, b=6, c=1) <del> print("The solutions are: {} and {}".format(*solutions)) <add> solution1, solution2 = quadratic_roots(a=5, b=6, c=1) <add> print(f"The solutions are: {solution1} and {solution2}") <ide> <ide> <ide> if __name__ == "__main__": <ide><path>matrix/nth_fibonacci_using_matrix_exponentiation.py <ide> def nth_fibonacci_bruteforce(n): <ide> <ide> <ide> def main(): <del> fmt = ( <del> "{} fibonacci number using matrix exponentiation is {} and using bruteforce " <del> "is {}\n" <del> ) <ide> for ordinal in "0th 1st 2nd 3rd 10th 100th 1000th".split(): <ide> n = int("".join(c for c in ordinal if c in "0123456789")) # 1000th --> 1000 <del> print(fmt.format(ordinal, nth_fibonacci_matrix(n), nth_fibonacci_bruteforce(n))) <add> print( <add> f"{ordinal} fibonacci number using matrix exponentiation is " <add> f"{nth_fibonacci_matrix(n)} and using bruteforce is " <add> f"{nth_fibonacci_bruteforce(n)}\n" <add> ) <ide> # from timeit import timeit <ide> # print(timeit("nth_fibonacci_matrix(1000000)", <ide> # "from main import nth_fibonacci_matrix", number=5)) <ide><path>matrix/sherman_morrison.py <ide> def __mul__(self, another): <ide> result[r, c] += self[r, i] * another[i, c] <ide> return result <ide> else: <del> raise TypeError( <del> "Unsupported type given for another ({})".format(type(another)) <del> ) <add> raise TypeError(f"Unsupported type given for another ({type(another)})") <ide> <ide> def transpose(self): <ide> """ <ide> def test1(): <ide> print(f"v is {v}") <ide> print("uv^T is %s" % (u * v.transpose())) <ide> # Sherman Morrison <del> print("(a + uv^T)^(-1) is {}".format(ainv.ShermanMorrison(u, v))) <add> print(f"(a + uv^T)^(-1) is {ainv.ShermanMorrison(u, v)}") <ide> <ide> def test2(): <ide> import doctest <ide><path>strings/levenshtein_distance.py <ide> def levenshtein_distance(first_word: str, second_word: str) -> int: <ide> second_word = input("Enter the second word:\n").strip() <ide> <ide> result = levenshtein_distance(first_word, second_word) <del> print( <del> "Levenshtein distance between {} and {} is {}".format( <del> first_word, second_word, result <del> ) <del> ) <add> print(f"Levenshtein distance between {first_word} and {second_word} is {result}")
14
Go
Go
move quota package out of graphdriver
c677e4cc8793384d711cf0fc75b1578bb423d4f9
<ide><path>daemon/graphdriver/graphtest/graphtest_unix.go <ide> import ( <ide> "unsafe" <ide> <ide> "github.com/docker/docker/daemon/graphdriver" <del> "github.com/docker/docker/daemon/graphdriver/quota" <ide> "github.com/docker/docker/pkg/stringid" <add> "github.com/docker/docker/quota" <ide> units "github.com/docker/go-units" <ide> "golang.org/x/sys/unix" <ide> "gotest.tools/v3/assert" <ide><path>daemon/graphdriver/overlay2/overlay.go <ide> import ( <ide> "github.com/containerd/containerd/sys" <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/daemon/graphdriver/overlayutils" <del> "github.com/docker/docker/daemon/graphdriver/quota" <ide> "github.com/docker/docker/pkg/archive" <ide> "github.com/docker/docker/pkg/chrootarchive" <ide> "github.com/docker/docker/pkg/containerfs" <ide> import ( <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/system" <add> "github.com/docker/docker/quota" <ide> units "github.com/docker/go-units" <ide> "github.com/moby/locker" <ide> "github.com/moby/sys/mount" <ide><path>daemon/graphdriver/vfs/driver.go <ide> import ( <ide> "path/filepath" <ide> <ide> "github.com/docker/docker/daemon/graphdriver" <del> "github.com/docker/docker/daemon/graphdriver/quota" <ide> "github.com/docker/docker/errdefs" <ide> "github.com/docker/docker/pkg/containerfs" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/parsers" <ide> "github.com/docker/docker/pkg/system" <add> "github.com/docker/docker/quota" <ide> units "github.com/docker/go-units" <ide> "github.com/opencontainers/selinux/go-selinux/label" <ide> "github.com/pkg/errors" <ide><path>daemon/graphdriver/vfs/quota_linux.go <ide> package vfs // import "github.com/docker/docker/daemon/graphdriver/vfs" <ide> <ide> import ( <del> "github.com/docker/docker/daemon/graphdriver/quota" <add> "github.com/docker/docker/quota" <ide> "github.com/sirupsen/logrus" <ide> ) <ide> <ide><path>daemon/graphdriver/vfs/quota_unsupported.go <ide> <ide> package vfs // import "github.com/docker/docker/daemon/graphdriver/vfs" <ide> <del>import "github.com/docker/docker/daemon/graphdriver/quota" <add>import "github.com/docker/docker/quota" <ide> <ide> type driverQuota struct { <ide> } <add><path>quota/errors.go <del><path>daemon/graphdriver/quota/errors.go <del>package quota // import "github.com/docker/docker/daemon/graphdriver/quota" <add>package quota // import "github.com/docker/docker/quota" <ide> <ide> import "github.com/docker/docker/errdefs" <ide> <add><path>quota/projectquota.go <del><path>daemon/graphdriver/quota/projectquota.go <ide> // for both xfs/ext4 for kernel version >= v4.5 <ide> // <ide> <del>package quota // import "github.com/docker/docker/daemon/graphdriver/quota" <add>package quota // import "github.com/docker/docker/quota" <ide> <ide> /* <ide> #include <stdlib.h> <add><path>quota/projectquota_test.go <del><path>daemon/graphdriver/quota/projectquota_test.go <ide> // +build linux <ide> <del>package quota // import "github.com/docker/docker/daemon/graphdriver/quota" <add>package quota // import "github.com/docker/docker/quota" <ide> <ide> import ( <ide> "io" <add><path>quota/projectquota_unsupported.go <del><path>daemon/graphdriver/quota/projectquota_unsupported.go <ide> // +build linux,exclude_disk_quota linux,!cgo !linux <ide> <del>package quota // import "github.com/docker/docker/daemon/graphdriver/quota" <add>package quota // import "github.com/docker/docker/quota" <ide> <ide> func NewControl(basePath string) (*Control, error) { <ide> return nil, ErrQuotaNotSupported <add><path>quota/types.go <del><path>daemon/graphdriver/quota/types.go <del>package quota // import "github.com/docker/docker/daemon/graphdriver/quota" <add>package quota // import "github.com/docker/docker/quota" <ide> <ide> import "sync" <ide>
10
Text
Text
add a note about importing server only modules
5a650d74df7453b6f76256740058f2e517159037
<ide><path>readme.md <ide> For the initial page load, `getInitialProps` will execute on the server only. `g <ide> <ide> _Note: `getInitialProps` can **not** be used in children components. Only in `pages`._ <ide> <add><br/> <add>> If you are using some server only modules inside `getInitialProps`, make sure to [import them properly](https://arunoda.me/blog/ssr-and-server-only-modules). <add>> Otherwise, it'll slow down your app. <add><br/> <add> <ide> You can also define the `getInitialProps` lifecycle method for stateless components: <ide> <ide> ```jsx
1
PHP
PHP
fix typeerror on php 8
77060314756913ee0bf50e6d56ba87f97eee4c85
<ide><path>src/Utility/Text.php <ide> public static function insert(string $str, array $data, array $options = []): st <ide> <ide> $dataKeys = array_keys($data); <ide> $hashKeys = array_map('crc32', $dataKeys); <del> /** @var array<string, string> $tempData */ <add> /** @var array<string, string|int> $tempData */ <ide> $tempData = array_combine($dataKeys, $hashKeys); <ide> krsort($tempData); <ide> <ide> foreach ($tempData as $key => $hashVal) { <ide> $key = sprintf($format, preg_quote($key, '/')); <del> $str = preg_replace($key, $hashVal, $str); <add> $str = preg_replace($key, (string)$hashVal, $str); <ide> } <ide> /** @var array<string, mixed> $dataReplacements */ <ide> $dataReplacements = array_combine($hashKeys, array_values($data));
1
Javascript
Javascript
add spec for permissionsandroid
82fe1b05210fd703381c0a053bd3310bf12a4f1a
<ide><path>Libraries/PermissionsAndroid/NativePermissionsAndroid.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> * @format <add> * @flow strict-local <add> */ <add> <add>'use strict'; <add> <add>import type {TurboModule} from 'RCTExport'; <add>import * as TurboModuleRegistry from 'TurboModuleRegistry'; <add> <add>// TODO: Use proper enum types. <add>export type PermissionStatus = string; <add>export type PermissionType = string; <add>/* <add>export type PermissionStatus = 'granted' | 'denied' | 'never_ask_again'; <add>export type PermissionType = <add> | 'android.permission.READ_CALENDAR' <add> | 'android.permission.WRITE_CALENDAR' <add> | 'android.permission.CAMERA' <add> | 'android.permission.READ_CONTACTS' <add> | 'android.permission.WRITE_CONTACTS' <add> | 'android.permission.GET_ACCOUNTS' <add> | 'android.permission.ACCESS_FINE_LOCATION' <add> | 'android.permission.ACCESS_COARSE_LOCATION' <add> | 'android.permission.RECORD_AUDIO' <add> | 'android.permission.READ_PHONE_STATE' <add> | 'android.permission.CALL_PHONE' <add> | 'android.permission.READ_CALL_LOG' <add> | 'android.permission.WRITE_CALL_LOG' <add> | 'com.android.voicemail.permission.ADD_VOICEMAIL' <add> | 'android.permission.USE_SIP' <add> | 'android.permission.PROCESS_OUTGOING_CALLS' <add> | 'android.permission.BODY_SENSORS' <add> | 'android.permission.SEND_SMS' <add> | 'android.permission.RECEIVE_SMS' <add> | 'android.permission.READ_SMS' <add> | 'android.permission.RECEIVE_WAP_PUSH' <add> | 'android.permission.RECEIVE_MMS' <add> | 'android.permission.READ_EXTERNAL_STORAGE' <add> | 'android.permission.WRITE_EXTERNAL_STORAGE'; <add>*/ <add> <add>export interface Spec extends TurboModule { <add> +checkPermission: (permission: PermissionType) => Promise<boolean>; <add> +requestPermission: (permission: PermissionType) => Promise<PermissionStatus>; <add> +shouldShowRequestPermissionRationale: ( <add> permission: string, <add> ) => Promise<boolean>; <add> +requestMultiplePermissions: ( <add> permissions: Array<PermissionType>, <add> ) => Promise<{[permission: PermissionType]: PermissionStatus}>; <add>} <add> <add>export default TurboModuleRegistry.getEnforcing<Spec>('PermissionsAndroid'); <ide><path>Libraries/PermissionsAndroid/PermissionsAndroid.js <ide> <ide> import NativeDialogManagerAndroid from '../NativeModules/specs/NativeDialogManagerAndroid'; <ide> const NativeModules = require('../BatchedBridge/NativeModules'); <add>const Platform = require('../Utilities/Platform'); <add>import NativePermissionsAndroid from './NativePermissionsAndroid'; <add> <add>import type { <add> PermissionStatus, <add> PermissionType, <add>} from './NativePermissionsAndroid'; <ide> <ide> export type Rationale = { <ide> title: string, <ide> export type Rationale = { <ide> buttonNeutral?: string, <ide> }; <ide> <del>type PermissionStatus = 'granted' | 'denied' | 'never_ask_again'; <add>const PERMISSION_REQUEST_RESULT = Object.freeze({ <add> GRANTED: 'granted', <add> DENIED: 'denied', <add> NEVER_ASK_AGAIN: 'never_ask_again', <add>}); <add> <add>const PERMISSIONS = Object.freeze({ <add> READ_CALENDAR: 'android.permission.READ_CALENDAR', <add> WRITE_CALENDAR: 'android.permission.WRITE_CALENDAR', <add> CAMERA: 'android.permission.CAMERA', <add> READ_CONTACTS: 'android.permission.READ_CONTACTS', <add> WRITE_CONTACTS: 'android.permission.WRITE_CONTACTS', <add> GET_ACCOUNTS: 'android.permission.GET_ACCOUNTS', <add> ACCESS_FINE_LOCATION: 'android.permission.ACCESS_FINE_LOCATION', <add> ACCESS_COARSE_LOCATION: 'android.permission.ACCESS_COARSE_LOCATION', <add> RECORD_AUDIO: 'android.permission.RECORD_AUDIO', <add> READ_PHONE_STATE: 'android.permission.READ_PHONE_STATE', <add> CALL_PHONE: 'android.permission.CALL_PHONE', <add> READ_CALL_LOG: 'android.permission.READ_CALL_LOG', <add> WRITE_CALL_LOG: 'android.permission.WRITE_CALL_LOG', <add> ADD_VOICEMAIL: 'com.android.voicemail.permission.ADD_VOICEMAIL', <add> USE_SIP: 'android.permission.USE_SIP', <add> PROCESS_OUTGOING_CALLS: 'android.permission.PROCESS_OUTGOING_CALLS', <add> BODY_SENSORS: 'android.permission.BODY_SENSORS', <add> SEND_SMS: 'android.permission.SEND_SMS', <add> RECEIVE_SMS: 'android.permission.RECEIVE_SMS', <add> READ_SMS: 'android.permission.READ_SMS', <add> RECEIVE_WAP_PUSH: 'android.permission.RECEIVE_WAP_PUSH', <add> RECEIVE_MMS: 'android.permission.RECEIVE_MMS', <add> READ_EXTERNAL_STORAGE: 'android.permission.READ_EXTERNAL_STORAGE', <add> WRITE_EXTERNAL_STORAGE: 'android.permission.WRITE_EXTERNAL_STORAGE', <add>}); <add> <ide> /** <ide> * `PermissionsAndroid` provides access to Android M's new permissions model. <ide> * <ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html <ide> */ <ide> <ide> class PermissionsAndroid { <del> PERMISSIONS: Object; <del> RESULTS: Object; <del> <del> constructor() { <del> /** <del> * A list of specified "dangerous" permissions that require prompting the user <del> */ <del> this.PERMISSIONS = { <del> READ_CALENDAR: 'android.permission.READ_CALENDAR', <del> WRITE_CALENDAR: 'android.permission.WRITE_CALENDAR', <del> CAMERA: 'android.permission.CAMERA', <del> READ_CONTACTS: 'android.permission.READ_CONTACTS', <del> WRITE_CONTACTS: 'android.permission.WRITE_CONTACTS', <del> GET_ACCOUNTS: 'android.permission.GET_ACCOUNTS', <del> ACCESS_FINE_LOCATION: 'android.permission.ACCESS_FINE_LOCATION', <del> ACCESS_COARSE_LOCATION: 'android.permission.ACCESS_COARSE_LOCATION', <del> RECORD_AUDIO: 'android.permission.RECORD_AUDIO', <del> READ_PHONE_STATE: 'android.permission.READ_PHONE_STATE', <del> CALL_PHONE: 'android.permission.CALL_PHONE', <del> READ_CALL_LOG: 'android.permission.READ_CALL_LOG', <del> WRITE_CALL_LOG: 'android.permission.WRITE_CALL_LOG', <del> ADD_VOICEMAIL: 'com.android.voicemail.permission.ADD_VOICEMAIL', <del> USE_SIP: 'android.permission.USE_SIP', <del> PROCESS_OUTGOING_CALLS: 'android.permission.PROCESS_OUTGOING_CALLS', <del> BODY_SENSORS: 'android.permission.BODY_SENSORS', <del> SEND_SMS: 'android.permission.SEND_SMS', <del> RECEIVE_SMS: 'android.permission.RECEIVE_SMS', <del> READ_SMS: 'android.permission.READ_SMS', <del> RECEIVE_WAP_PUSH: 'android.permission.RECEIVE_WAP_PUSH', <del> RECEIVE_MMS: 'android.permission.RECEIVE_MMS', <del> READ_EXTERNAL_STORAGE: 'android.permission.READ_EXTERNAL_STORAGE', <del> WRITE_EXTERNAL_STORAGE: 'android.permission.WRITE_EXTERNAL_STORAGE', <del> }; <del> <del> this.RESULTS = { <del> GRANTED: 'granted', <del> DENIED: 'denied', <del> NEVER_ASK_AGAIN: 'never_ask_again', <del> }; <del> } <add> PERMISSIONS = PERMISSIONS; <add> RESULTS = PERMISSION_REQUEST_RESULT; <ide> <ide> /** <ide> * DEPRECATED - use check <ide> class PermissionsAndroid { <ide> * <ide> * @deprecated <ide> */ <del> checkPermission(permission: string): Promise<boolean> { <add> checkPermission(permission: PermissionType): Promise<boolean> { <ide> console.warn( <ide> '"PermissionsAndroid.checkPermission" is deprecated. Use "PermissionsAndroid.check" instead', <ide> ); <del> return NativeModules.PermissionsAndroid.checkPermission(permission); <add> if (Platform.OS !== 'android') { <add> console.warn( <add> '"PermissionsAndroid" module works only for Android platform.', <add> ); <add> return Promise.resolve(false); <add> } <add> <add> return NativePermissionsAndroid.checkPermission(permission); <ide> } <ide> <ide> /** <ide> class PermissionsAndroid { <ide> * <ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html#check <ide> */ <del> check(permission: string): Promise<boolean> { <del> return NativeModules.PermissionsAndroid.checkPermission(permission); <add> check(permission: PermissionType): Promise<boolean> { <add> if (Platform.OS !== 'android') { <add> console.warn( <add> '"PermissionsAndroid" module works only for Android platform.', <add> ); <add> return Promise.resolve(false); <add> } <add> return NativePermissionsAndroid.checkPermission(permission); <ide> } <ide> <ide> /** <ide> class PermissionsAndroid { <ide> * @deprecated <ide> */ <ide> async requestPermission( <del> permission: string, <add> permission: PermissionType, <ide> rationale?: Rationale, <ide> ): Promise<boolean> { <ide> console.warn( <ide> '"PermissionsAndroid.requestPermission" is deprecated. Use "PermissionsAndroid.request" instead', <ide> ); <add> if (Platform.OS !== 'android') { <add> console.warn( <add> '"PermissionsAndroid" module works only for Android platform.', <add> ); <add> return Promise.resolve(false); <add> } <add> <ide> const response = await this.request(permission, rationale); <ide> return response === this.RESULTS.GRANTED; <ide> } <ide> class PermissionsAndroid { <ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html#request <ide> */ <ide> async request( <del> permission: string, <add> permission: PermissionType, <ide> rationale?: Rationale, <ide> ): Promise<PermissionStatus> { <add> if (Platform.OS !== 'android') { <add> console.warn( <add> '"PermissionsAndroid" module works only for Android platform.', <add> ); <add> return Promise.resolve(this.RESULTS.DENIED); <add> } <add> <ide> if (rationale) { <del> const shouldShowRationale = await NativeModules.PermissionsAndroid.shouldShowRequestPermissionRationale( <add> const shouldShowRationale = await NativePermissionsAndroid.shouldShowRequestPermissionRationale( <ide> permission, <ide> ); <ide> <ide> class PermissionsAndroid { <ide> options, <ide> () => reject(new Error('Error showing rationale')), <ide> () => <del> resolve( <del> NativeModules.PermissionsAndroid.requestPermission(permission), <del> ), <add> resolve(NativePermissionsAndroid.requestPermission(permission)), <ide> ); <ide> }); <ide> } <ide> } <del> return NativeModules.PermissionsAndroid.requestPermission(permission); <add> return NativePermissionsAndroid.requestPermission(permission); <ide> } <ide> <ide> /** <ide> class PermissionsAndroid { <ide> * See https://facebook.github.io/react-native/docs/permissionsandroid.html#requestmultiple <ide> */ <ide> requestMultiple( <del> permissions: Array<string>, <del> ): Promise<{[permission: string]: PermissionStatus}> { <del> return NativeModules.PermissionsAndroid.requestMultiplePermissions( <del> permissions, <del> ); <add> permissions: Array<PermissionType>, <add> ): Promise<{[permission: PermissionType]: PermissionStatus}> { <add> if (Platform.OS !== 'android') { <add> console.warn( <add> '"PermissionsAndroid" module works only for Android platform.', <add> ); <add> return Promise.resolve({}); <add> } <add> <add> return NativePermissionsAndroid.requestMultiplePermissions(permissions); <ide> } <ide> } <ide>
2
Javascript
Javascript
use nested module api
0d8e395974a7db430c9dbe74ebac8792d1bd67be
<ide><path>packages/internal-test-helpers/lib/module-for.js <ide> import getAllPropertyNames from './get-all-property-names'; <ide> import { all } from 'rsvp'; <ide> <ide> export default function moduleFor(description, TestClass, ...mixins) { <del> QUnit.module(description, { <del> beforeEach: function(assert) { <add> QUnit.module(description, function(hooks) { <add> hooks.beforeEach(function(assert) { <ide> let instance = new TestClass(assert); <ide> this.instance = instance; <ide> if (instance.beforeEach) { <ide> return instance.beforeEach(assert); <ide> } <del> }, <add> }); <ide> <del> afterEach: function() { <add> hooks.afterEach(function() { <ide> let promises = []; <ide> let instance = this.instance; <ide> this.instance = null; <ide> export default function moduleFor(description, TestClass, ...mixins) { <ide> } <ide> <ide> return all(promises); <del> }, <del> }); <add> }); <ide> <del> if (mixins.length > 0) { <del> applyMixins(TestClass, ...mixins); <del> } <add> if (mixins.length > 0) { <add> applyMixins(TestClass, ...mixins); <add> } <ide> <del> let properties = getAllPropertyNames(TestClass); <del> properties.forEach(generateTest); <add> let properties = getAllPropertyNames(TestClass); <add> properties.forEach(generateTest); <add> }); <ide> <ide> function shouldTest(features) { <ide> return features.every(feature => {
1
PHP
PHP
add no-op method to base class
128c719bd01bc66e3a59b88c2edb287b0bf482b0
<ide><path>lib/Cake/Model/Datasource/DataSource.php <ide> public function getSchemaName() { <ide> return null; <ide> } <ide> <add>/** <add> * Close the connection to the datasource. <add> * <add> * @return void <add> */ <add> public function close() { <add> } <add> <ide> /** <ide> * Closes the current datasource. <ide> *
1
Javascript
Javascript
fix minor typo in listviewexample.js
83336130ef6823f0c462f8ddb92f79fa59bdc7f6
<ide><path>Examples/UIExplorer/js/ListViewExample.js <ide> var ListViewSimpleExample = React.createClass({ <ide> dataSource={this.state.dataSource} <ide> renderRow={this._renderRow} <ide> renderScrollComponent={props => <RecyclerViewBackedScrollView {...props} />} <del> renderSeparator={this._renderSeperator} <add> renderSeparator={this._renderSeparator} <ide> /> <ide> </UIExplorerPage> <ide> ); <ide> var ListViewSimpleExample = React.createClass({ <ide> )}); <ide> }, <ide> <del> _renderSeperator: function(sectionID: number, rowID: number, adjacentRowHighlighted: bool) { <add> _renderSeparator: function(sectionID: number, rowID: number, adjacentRowHighlighted: bool) { <ide> return ( <ide> <View <ide> key={`${sectionID}-${rowID}`}
1
Python
Python
avoid distutils.sysconfig in runtests.py
334428c4d10b778fd74fc3919f3dc9a3b1959875
<ide><path>runtests.py <ide> def build_project(args): <ide> '--single-version-externally-managed', <ide> '--record=' + dst_dir + 'tmp_install_log.txt'] <ide> <del> from distutils.sysconfig import get_python_lib <del> site_dir = get_python_lib(prefix=dst_dir, plat_specific=True) <del> site_dir_noarch = get_python_lib(prefix=dst_dir, plat_specific=False) <add> py_v_s = sysconfig.get_config_var('py_version_short') <add> platlibdir = getattr(sys, 'platlibdir', '') # Python3.9+ <add> site_dir_template = sysconfig.get_path('platlib', expand=False) <add> site_dir = site_dir_template.format(platbase=dst_dir, <add> py_version_short=py_v_s, <add> platlibdir=platlibdir, <add> ) <add> noarch_template = sysconfig.get_path('purelib', expand=False) <add> site_dir_noarch = noarch_template.format(base=dst_dir, <add> py_version_short=py_v_s, <add> platlibdir=platlibdir, <add> ) <add> <ide> # easy_install won't install to a path that Python by default cannot see <ide> # and isn't on the PYTHONPATH. Plus, it has to exist. <ide> if not os.path.exists(site_dir):
1
Ruby
Ruby
add missing require
0a2d004ba110f0f94fb9660bd1c81bb34699a6c3
<ide><path>railties/lib/rails/application.rb <ide> require 'fileutils' <ide> require 'active_support/core_ext/object/blank' <ide> require 'active_support/key_generator' <add>require 'active_support/message_verifier' <ide> require 'rails/engine' <ide> <ide> module Rails
1
Javascript
Javascript
add unit tests
9e6b4b413bd8f4dc782ef9a4b4fa6c9c722fba31
<ide><path>spec/tooltip-manager-spec.js <ide> describe('TooltipManager', () => { <ide> <ide> disposables.dispose() <ide> }) <add> <add> it('hides the tooltip on keydown events', () => { <add> const disposable = manager.add(element, { title: 'Title', trigger: 'hover' }) <add> hover(element, function () { <add> expect(document.body.querySelector('.tooltip')).not.toBeNull() <add> window.dispatchEvent(new CustomEvent('keydown', { <add> bubbles: true <add> })) <add> expect(document.body.querySelector('.tooltip')).toBeNull() <add> disposable.dispose() <add> }) <add> }) <ide> }) <ide> <ide> describe("when the trigger is 'manual'", () => <ide> describe('TooltipManager', () => { <ide> }) <ide> ) <ide> <add> it('does not hide the tooltip on keyboard input', () => { <add> manager.add(element, {title: 'Title', trigger: 'click'}) <add> element.click() <add> expect(document.body.querySelector('.tooltip')).not.toBeNull() <add> window.dispatchEvent(new CustomEvent('keydown', { <add> bubbles: true <add> })) <add> expect(document.body.querySelector('.tooltip')).not.toBeNull() <add> }) <add> <ide> it('allows a custom item to be specified for the content of the tooltip', () => { <ide> const tooltipElement = document.createElement('div') <ide> manager.add(element, {item: {element: tooltipElement}}) <ide> describe('TooltipManager', () => { <ide> }) <ide> ) <ide> <del> describe('when a user types', () => <del> it('hides the tooltips', () => { <del> const disposable = manager.add(element, { title: 'Title' }) <del> hover(element, function () { <del> expect(document.body.querySelector('.tooltip')).not.toBeNull() <del> window.dispatchEvent(new CustomEvent('keydown', { <del> bubbles: true <del> })) <del> expect(document.body.querySelector('.tooltip')).toBeNull() <del> disposable.dispose() <del> }) <del> }) <del> ) <del> <ide> describe('findTooltips', () => { <ide> it('adds and remove tooltips correctly', () => { <ide> expect(manager.findTooltips(element).length).toBe(0)
1
Text
Text
upgrade all http links to https
c8837dcbda055a3b145a84113fc5e4e193dc286b
<ide><path>docs/deployment.md <ide> The easiest way to deploy Next.js to production is to use the **[Vercel platform <ide> <ide> ### Getting started <ide> <del>If you haven’t already done so, push your Next.js app to a Git provider of your choice: [GitHub](http://github.com/), [GitLab](https://gitlab.com/), or [BitBucket](https://bitbucket.org/). Your repository can be private or public. <add>If you haven’t already done so, push your Next.js app to a Git provider of your choice: [GitHub](https://github.com/), [GitLab](https://gitlab.com/), or [BitBucket](https://bitbucket.org/). Your repository can be private or public. <ide> <ide> Then, follow these steps: <ide> <ide><path>examples/custom-server-koa/README.md <ide> <ide> Most of the times the default Next server will be enough but sometimes you want to run your own server to customize routes or other kind of the app behavior. Next provides a [Custom server and routing](https://nextjs.org/docs/advanced-features/custom-server) so you can customize as much as you want. <ide> <del>Because the Next.js server is just a node.js module you can combine it with any other part of the node.js ecosystem. in this case we are using [Koa](http://koajs.com/) to build a custom router on top of Next. <add>Because the Next.js server is just a node.js module you can combine it with any other part of the node.js ecosystem. in this case we are using [Koa](https://koajs.com/) to build a custom router on top of Next. <ide> <ide> The example shows a server that serves the component living in `pages/a.js` when the route `/b` is requested and `pages/b.js` when the route `/a` is accessed. This is obviously a non-standard routing strategy. You can see how this custom routing is being made inside `server.js`. <ide> <ide><path>examples/with-ant-design-less/README.md <ide> # Ant Design example <ide> <del>This example shows how to use Next.js along with [Ant Design of React](http://ant.design). This is intended to show the integration of this UI toolkit with the Framework. <add>This example shows how to use Next.js along with [Ant Design of React](https://ant.design). This is intended to show the integration of this UI toolkit with the Framework. <ide> <ide> ## Deploy your own <ide> <ide><path>examples/with-ant-design/README.md <ide> # Ant Design example <ide> <del>This example shows how to use Next.js along with [Ant Design of React](http://ant.design). This is intended to show the integration of this UI toolkit with the Framework. <add>This example shows how to use Next.js along with [Ant Design of React](https://ant.design). This is intended to show the integration of this UI toolkit with the Framework. <ide> <ide> ## Deploy your own <ide> <ide><path>examples/with-carbon-components/README.md <ide> # Example app with carbon-components-react <ide> <del>This example features how you use IBM's [carbon-components-react](https://github.com/IBM/carbon-components-react) [(Carbon Design System)](http://www.carbondesignsystem.com/components/overview) with Next.js. <add>This example features how you use IBM's [carbon-components-react](https://github.com/IBM/carbon-components-react) [(Carbon Design System)](https://www.carbondesignsystem.com/components/overview) with Next.js. <ide> <del>Create your own theme with Carbon Design System's [theming tools](http://themes.carbondesignsystem.com/) and put it all together as demonstrated in `static/myCustomTheme.scss` <add>Create your own theme with Carbon Design System's [theming tools](https://themes.carbondesignsystem.com/) and put it all together as demonstrated in `static/myCustomTheme.scss` <ide> <ide> ## Deploy your own <ide> <ide><path>examples/with-knex/README.md <ide> ## Example app using Knex <ide> <del>[Knex](http://knexjs.org/) is a SQL query builder that works with a variety of SQL databases including Postgres and MySQL. This example shows you how to use Knex with Next.js to connect and query a Postgres database. The same code can also connect to all other databases supported by Knex. <add>[Knex](https://knexjs.org/) is a SQL query builder that works with a variety of SQL databases including Postgres and MySQL. This example shows you how to use Knex with Next.js to connect and query a Postgres database. The same code can also connect to all other databases supported by Knex. <ide> <ide> ## Deploy your own <ide> <ide><path>examples/with-rebass/README.md <ide> # Example app with Rebass <ide> <del>This example features how you use [Rebass](http://jxnblk.com/rebass/) functional UI library with Next.js. <add>This example features how you use [Rebass](https://jxnblk.com/rebass/) functional UI library with Next.js. <ide> <ide> ![Screenshot](https://cloud.githubusercontent.com/assets/304265/22472564/b2e04ff0-e7de-11e6-921e-d0c9833ac805.png) <ide> <ide><path>examples/with-redux-saga/README.md <ide> Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&ut <ide> <ide> In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one. <ide> <del>![](http://i.imgur.com/JCxtWSj.gif) <add>![](https://i.imgur.com/JCxtWSj.gif) <ide> <ide> Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `next-redux-wrapper`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required. <ide> <ide><path>examples/with-redux-wrapper/README.md <ide> Deploy it to the cloud with [Vercel](https://vercel.com/import?filter=next.js&ut <ide> <ide> In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color than the client one. <ide> <del>![](http://i.imgur.com/JCxtWSj.gif) <add>![](https://i.imgur.com/JCxtWSj.gif) <ide> <ide> Our page is located at `pages/index.js` so it will map the route `/`. To get the initial data for rendering we are implementing the static method `getInitialProps`, initializing the redux store and dispatching the required actions until we are ready to return the initial state to be rendered. Since the component is wrapped with `next-redux-wrapper`, the component is automatically connected to Redux and wrapped with `react-redux Provider`, that allows us to access redux state immediately and send the store down to children components so they can access to the state when required. <ide> <ide><path>examples/with-semantic-ui/README.md <ide> # Semantic UI example <ide> <del>This example shows how to use Next.js along with [Semantic UI React](http://react.semantic-ui.com) including handling of external styles and assets. This is intended to show the integration of this UI toolkit with the Framework. <add>This example shows how to use Next.js along with [Semantic UI React](https://react.semantic-ui.com) including handling of external styles and assets. This is intended to show the integration of this UI toolkit with the Framework. <ide> <ide> ## Deploy your own <ide> <ide><path>examples/with-stomp/README.md <ide> # Stomp example <ide> <del>This example show how to use [STOMP](http://stomp.github.io/) inside a Next.js application. <add>This example show how to use [STOMP](https://stomp.github.io/) inside a Next.js application. <ide> <ide> STOMP is a simple text-orientated messaging protocol. It defines an interoperable wire format so that any of the available STOMP clients can communicate with any STOMP message broker. <ide> <ide><path>examples/with-videojs/README.md <ide> # video.js example <ide> <del>This example shows how to use Next.js along with [Video.js](http://videojs.com) including handling of default styles. <add>This example shows how to use Next.js along with [Video.js](https://videojs.com) including handling of default styles. <ide> <ide> ## Deploy your own <ide>
12
Javascript
Javascript
update error message for json.parse
b68827b1d1c20d0f3e0592734e845b87967a72bc
<ide><path>test/parallel/test-repl.js <ide> function error_test() { <ide> expect: /^SyntaxError: Unexpected number/ }, <ide> // should throw <ide> { client: client_unix, send: 'JSON.parse(\'{\');', <del> expect: /^SyntaxError: Unexpected end of input/ }, <add> expect: /^SyntaxError: Unexpected end of JSON input/ }, <ide> // invalid RegExps are a special case of syntax error, <ide> // should throw <ide> { client: client_unix, send: '/(/;',
1
Java
Java
use findannotationattributes() where appropriate
bccd59e6c8845c6521d3b325bea89bcbcbe4d833
<ide><path>spring-test/src/main/java/org/springframework/test/context/jdbc/MergedSqlConfig.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> private static String getString(AnnotationAttributes attributes, String attribut <ide> Assert.notNull(testClass, "testClass must not be null"); <ide> <ide> // Get global attributes, if any. <del> AnnotationAttributes attributes = AnnotatedElementUtils.getAnnotationAttributes(testClass, <add> AnnotationAttributes attributes = AnnotatedElementUtils.findAnnotationAttributes(testClass, <ide> SqlConfig.class.getName()); <ide> <ide> // Override global attributes with local attributes. <ide><path>spring-test/src/main/java/org/springframework/test/context/junit4/SpringJUnit4ClassRunner.java <ide> protected long getJUnitTimeout(FrameworkMethod frameworkMethod) { <ide> * @return the timeout, or {@code 0} if none was specified <ide> */ <ide> protected long getSpringTimeout(FrameworkMethod frameworkMethod) { <del> AnnotationAttributes annAttrs = AnnotatedElementUtils.getAnnotationAttributes(frameworkMethod.getMethod(), <add> AnnotationAttributes annAttrs = AnnotatedElementUtils.findAnnotationAttributes(frameworkMethod.getMethod(), <ide> Timed.class.getName()); <ide> if (annAttrs == null) { <ide> return 0; <ide><path>spring-test/src/main/java/org/springframework/test/context/support/DirtiesContextTestExecutionListener.java <ide> private void beforeOrAfterTestMethod(TestContext testContext, String phase, Meth <ide> Assert.notNull(testMethod, "The test method of the supplied TestContext must not be null"); <ide> <ide> final String annotationType = DirtiesContext.class.getName(); <del> AnnotationAttributes methodAnnAttrs = AnnotatedElementUtils.getAnnotationAttributes(testMethod, annotationType); <del> AnnotationAttributes classAnnAttrs = AnnotatedElementUtils.getAnnotationAttributes(testClass, annotationType); <add> AnnotationAttributes methodAnnAttrs = AnnotatedElementUtils.findAnnotationAttributes(testMethod, annotationType); <add> AnnotationAttributes classAnnAttrs = AnnotatedElementUtils.findAnnotationAttributes(testClass, annotationType); <ide> boolean methodAnnotated = methodAnnAttrs != null; <ide> boolean classAnnotated = classAnnAttrs != null; <ide> MethodMode methodMode = methodAnnotated ? methodAnnAttrs.<MethodMode> getEnum("methodMode") : null; <ide> private void beforeOrAfterTestClass(TestContext testContext, String phase, Class <ide> Assert.notNull(testClass, "The test class of the supplied TestContext must not be null"); <ide> <ide> final String annotationType = DirtiesContext.class.getName(); <del> AnnotationAttributes classAnnAttrs = AnnotatedElementUtils.getAnnotationAttributes(testClass, annotationType); <add> AnnotationAttributes classAnnAttrs = AnnotatedElementUtils.findAnnotationAttributes(testClass, annotationType); <ide> boolean classAnnotated = classAnnAttrs != null; <ide> ClassMode classMode = classAnnotated ? classAnnAttrs.<ClassMode> getEnum("classMode") : null; <ide> <ide><path>spring-test/src/main/java/org/springframework/test/context/transaction/TransactionalTestExecutionListener.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> TransactionConfigurationAttributes retrieveConfigurationAttributes(TestContext t <ide> if (this.configurationAttributes == null) { <ide> Class<?> clazz = testContext.getTestClass(); <ide> <del> AnnotationAttributes annAttrs = AnnotatedElementUtils.getAnnotationAttributes(clazz, <add> AnnotationAttributes annAttrs = AnnotatedElementUtils.findAnnotationAttributes(clazz, <ide> TransactionConfiguration.class.getName()); <ide> if (logger.isDebugEnabled()) { <ide> logger.debug(String.format("Retrieved @TransactionConfiguration attributes [%s] for test class [%s].",
4
Javascript
Javascript
use fewer multiplications in convertyccktorgb
5fcf3d37a72904c6dc027e1174a99611fef6b3b3
<ide><path>src/core/jpg.js <ide> var JpegImage = (function jpegImage() { <ide> <ide> // stage 3 <ide> // Shift v0 by 128.5 << 5 here, so we don't need to shift p0...p7 when <del> // converting to UInt8 range later. <add> // converting to UInt8 range later. <ide> v0 = ((v0 + v1 + 1) >> 1) + 4112; <ide> v1 = v0 - v1; <ide> t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12; <ide> var JpegImage = (function jpegImage() { <ide> }, <ide> <ide> _convertYcckToRgb: function convertYcckToRgb(data) { <del> var Y, Cb, Cr, k, CbCb, CbCr, CbY, Cbk, CrCr, Crk, CrY, YY, Yk, kk; <add> var Y, Cb, Cr, k; <ide> var offset = 0; <ide> for (var i = 0, length = data.length; i < length; i += 4) { <ide> Y = data[i]; <ide> Cb = data[i + 1]; <ide> Cr = data[i + 2]; <ide> k = data[i + 3]; <ide> <del> CbCb = Cb * Cb; <del> CbCr = Cb * Cr; <del> CbY = Cb * Y; <del> Cbk = Cb * k; <del> CrCr = Cr * Cr; <del> Crk = Cr * k; <del> CrY = Cr * Y; <del> YY = Y * Y; <del> Yk = Y * k; <del> kk = k * k; <del> <del> var r = - 122.67195406894 - <del> 6.60635669420364e-5 * CbCb + 0.000437130475926232 * CbCr - <del> 5.4080610064599e-5* CbY + 0.00048449797120281* Cbk - <del> 0.154362151871126 * Cb - 0.000957964378445773 * CrCr + <del> 0.000817076911346625 * CrY - 0.00477271405408747 * Crk + <del> 1.53380253221734 * Cr + 0.000961250184130688 * YY - <del> 0.00266257332283933 * Yk + 0.48357088451265 * Y - <del> 0.000336197177618394 * kk + 0.484791561490776 * k; <add> var r = -122.67195406894 + <add> Cb * (-6.60635669420364e-5 * Cb + 0.000437130475926232 * Cr - <add> 5.4080610064599e-5 * Y + 0.00048449797120281 * k - <add> 0.154362151871126) + <add> Cr * (-0.000957964378445773 * Cr + 0.000817076911346625 * Y - <add> 0.00477271405408747 * k + 1.53380253221734) + <add> Y * (0.000961250184130688 * Y - 0.00266257332283933 * k + <add> 0.48357088451265) + <add> k * (-0.000336197177618394 * k + 0.484791561490776); <ide> <ide> var g = 107.268039397724 + <del> 2.19927104525741e-5 * CbCb - 0.000640992018297945 * CbCr + <del> 0.000659397001245577* CbY + 0.000426105652938837* Cbk - <del> 0.176491792462875 * Cb - 0.000778269941513683 * CrCr + <del> 0.00130872261408275 * CrY + 0.000770482631801132 * Crk - <del> 0.151051492775562 * Cr + 0.00126935368114843 * YY - <del> 0.00265090189010898 * Yk + 0.25802910206845 * Y - <del> 0.000318913117588328 * kk - 0.213742400323665 * k; <del> <del> var b = - 20.810012546947 - <del> 0.000570115196973677 * CbCb - 2.63409051004589e-5 * CbCr + <del> 0.0020741088115012* CbY - 0.00288260236853442* Cbk + <del> 0.814272968359295 * Cb - 1.53496057440975e-5 * CrCr - <del> 0.000132689043961446 * CrY + 0.000560833691242812 * Crk - <del> 0.195152027534049 * Cr + 0.00174418132927582 * YY - <del> 0.00255243321439347 * Yk + 0.116935020465145 * Y - <del> 0.000343531996510555 * kk + 0.24165260232407 * k; <add> Cb * (2.19927104525741e-5 * Cb - 0.000640992018297945 * Cr + <add> 0.000659397001245577 * Y + 0.000426105652938837 * k - <add> 0.176491792462875) + <add> Cr * (-0.000778269941513683 * Cr + 0.00130872261408275 * Y + <add> 0.000770482631801132 * k - 0.151051492775562) + <add> Y * (0.00126935368114843 * Y - 0.00265090189010898 * k + <add> 0.25802910206845) + <add> k * (-0.000318913117588328 * k - 0.213742400323665); <add> <add> var b = -20.810012546947 + <add> Cb * (-0.000570115196973677 * Cb - 2.63409051004589e-5 * Cr + <add> 0.0020741088115012 * Y - 0.00288260236853442 * k + <add> 0.814272968359295) + <add> Cr * (-1.53496057440975e-5 * Cr - 0.000132689043961446 * Y + <add> 0.000560833691242812 * k - 0.195152027534049) + <add> Y * (0.00174418132927582 * Y - 0.00255243321439347 * k + <add> 0.116935020465145) + <add> k * (-0.000343531996510555 * k + 0.24165260232407); <ide> <ide> data[offset++] = clamp0to255(r); <ide> data[offset++] = clamp0to255(g);
1
PHP
PHP
clarify documentation of collection diff method
b5f48a89525550a6ece15c52af0e4758c0cc90a8
<ide><path>src/Illuminate/Support/Collection.php <ide> public function contains($key, $value = null) <ide> } <ide> <ide> /** <del> * Diff the collection with the given items. <add> * Get the items in the collection that are not present in the given items. <ide> * <ide> * @param mixed $items <ide> * @return static
1
Javascript
Javascript
add test for loading read-only modules
3ba81e34e86a5c32658e218cb6e65b13e8326bc5
<ide><path>test/parallel/test-module-readonly.js <add>'use strict'; <add> <add>const common = require('../common'); <add> <add>if (!common.isWindows) { <add> // TODO: Similar checks on *nix-like systems (e.g using chmod or the like) <add> common.skip('test only runs on Windows'); <add>} <add> <add>const assert = require('assert'); <add>const fs = require('fs'); <add>const path = require('path'); <add>const cp = require('child_process'); <add> <add>const tmpdir = require('../common/tmpdir'); <add>tmpdir.refresh(); <add> <add>// Create readOnlyMod.js and set to read only <add>const readOnlyMod = path.join(tmpdir.path, 'readOnlyMod'); <add>const readOnlyModRelative = path.relative(__dirname, readOnlyMod); <add>const readOnlyModFullPath = `${readOnlyMod}.js`; <add> <add>fs.writeFileSync(readOnlyModFullPath, 'module.exports = 42;'); <add> <add>// Removed any inherited ACEs, and any explicitly granted ACEs for the <add>// current user <add>cp.execSync( <add> `icacls.exe "${readOnlyModFullPath}" /inheritance:r /remove "%USERNAME%"`); <add> <add>// Grant the current user read & execute only <add>cp.execSync(`icacls.exe "${readOnlyModFullPath}" /grant "%USERNAME%":RX`); <add> <add>let except = null; <add>try { <add> // Attempt to load the module. Will fail if write access is required <add> require(readOnlyModRelative); <add>} catch (err) { <add> except = err; <add>} <add> <add>// Remove the expliclty granted rights, and reenable inheritance <add>cp.execSync( <add> `icacls.exe "${readOnlyModFullPath}" /remove "%USERNAME%" /inheritance:e`); <add> <add>// Delete the test module (note: tmpdir should get cleaned anyway) <add>fs.unlinkSync(readOnlyModFullPath); <add> <add>assert.ifError(except);
1
PHP
PHP
remove deprecated code from marshaller
481cb50cad7d9915d4e9fbde6a6bc89853966ddb
<ide><path>src/ORM/Marshaller.php <ide> protected function _buildPropertyMap($data, $options) <ide> * - validate: Set to false to disable validation. Can also be a string of the validator ruleset to be applied. <ide> * Defaults to true/default. <ide> * - associated: Associations listed here will be marshalled as well. Defaults to null. <del> * - fieldList: (deprecated) Since 3.4.0. Use fields instead. <ide> * - fields: A whitelist of fields to be assigned to the entity. If not present, <ide> * the accessible fields list in the entity will be used. Defaults to null. <ide> * - accessibleFields: A list of fields to allow or deny in entity accessible fields. Defaults to null <ide> protected function _prepareDataAndOptions($data, $options) <ide> { <ide> $options += ['validate' => true]; <ide> <del> if (!isset($options['fields']) && isset($options['fieldList'])) { <del> deprecationWarning( <del> 'The `fieldList` option for marshalling is deprecated. Use the `fields` option instead.' <del> ); <del> $options['fields'] = $options['fieldList']; <del> unset($options['fieldList']); <del> } <del> <ide> $tableName = $this->_table->getAlias(); <ide> if (isset($data[$tableName])) { <ide> $data += $data[$tableName]; <ide> protected function _marshalAssociation($assoc, $value, $options) <ide> * - validate: Set to false to disable validation. Can also be a string of the validator ruleset to be applied. <ide> * Defaults to true/default. <ide> * - associated: Associations listed here will be marshalled as well. Defaults to null. <del> * - fieldList: (deprecated) Since 3.4.0. Use fields instead <ide> * - fields: A whitelist of fields to be assigned to the entity. If not present, <ide> * the accessible fields list in the entity will be used. Defaults to null. <ide> * - accessibleFields: A list of fields to allow or deny in entity accessible fields. Defaults to null <ide> protected function _loadAssociatedByIds($assoc, $ids) <ide> return $target->find()->where($filter)->toArray(); <ide> } <ide> <del> /** <del> * Loads a list of belongs to many from ids. <del> * <del> * @param \Cake\ORM\Association $assoc The association class for the belongsToMany association. <del> * @param array $ids The list of ids to load. <del> * @return \Cake\Datasource\EntityInterface[] An array of entities. <del> * @deprecated Use _loadAssociatedByIds() <del> */ <del> protected function _loadBelongsToMany($assoc, $ids) <del> { <del> deprecationWarning( <del> 'Marshaller::_loadBelongsToMany() is deprecated. Use _loadAssociatedByIds() instead.' <del> ); <del> <del> return $this->_loadAssociatedByIds($assoc, $ids); <del> } <del> <ide> /** <ide> * Merges `$data` into `$entity` and recursively does the same for each one of <ide> * the association names passed in `$options`. When merging associations, if an <ide> protected function _loadBelongsToMany($assoc, $ids) <ide> * - associated: Associations listed here will be marshalled as well. <ide> * - validate: Whether or not to validate data before hydrating the entities. Can <ide> * also be set to a string to use a specific validator. Defaults to true/default. <del> * - fieldList: (deprecated) Since 3.4.0. Use fields instead <ide> * - fields: A whitelist of fields to be assigned to the entity. If not present <ide> * the accessible fields list in the entity will be used. <ide> * - accessibleFields: A list of fields to allow or deny in entity accessible fields. <ide> public function merge(EntityInterface $entity, array $data, array $options = []) <ide> * - validate: Whether or not to validate data before hydrating the entities. Can <ide> * also be set to a string to use a specific validator. Defaults to true/default. <ide> * - associated: Associations listed here will be marshalled as well. <del> * - fieldList: (deprecated) Since 3.4.0. Use fields instead <ide> * - fields: A whitelist of fields to be assigned to the entity. If not present, <ide> * the accessible fields list in the entity will be used. <ide> * - accessibleFields: A list of fields to allow or deny in entity accessible fields. <ide><path>tests/TestCase/ORM/MarshallerTest.php <ide> public function testMergeComplexType() <ide> $this->assertEquals('2014-02-14', $entity->created->format('Y-m-d')); <ide> } <ide> <del> /** <del> * Tests that it is possible to pass a fields option to the marshaller <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testOneWithFieldList() <del> { <del> $this->deprecated(function () { <del> $data = [ <del> 'title' => 'My title', <del> 'body' => 'My content', <del> 'author_id' => null <del> ]; <del> $marshall = new Marshaller($this->articles); <del> $result = $marshall->one($data, ['fieldList' => ['title', 'author_id']]); <del> <del> $this->assertInstanceOf('Cake\ORM\Entity', $result); <del> unset($data['body']); <del> $this->assertEquals($data, $result->toArray()); <del> }); <del> } <del> <ide> /** <ide> * Tests that it is possible to pass a fields option to the marshaller <ide> * <ide> public function testOneWithTranslations() <ide> $this->assertEquals($data['_translations']['en'], $translations['en']->toArray()); <ide> } <ide> <del> /** <del> * Tests that it is possible to pass a fields option to the merge method <del> * <del> * @group deprecated <del> * @return void <del> */ <del> public function testMergeWithFieldList() <del> { <del> $this->deprecated(function () { <del> $data = [ <del> 'title' => 'My title', <del> 'body' => null, <del> 'author_id' => 1 <del> ]; <del> $marshall = new Marshaller($this->articles); <del> $entity = new Entity([ <del> 'title' => 'Foo', <del> 'body' => 'My content', <del> 'author_id' => 2 <del> ]); <del> $entity->setAccess('*', false); <del> $entity->isNew(false); <del> $entity->clean(); <del> $result = $marshall->merge($entity, $data, ['fieldList' => ['title', 'body']]); <del> <del> $expected = [ <del> 'title' => 'My title', <del> 'body' => null, <del> 'author_id' => 2 <del> ]; <del> <del> $this->assertSame($entity, $result); <del> $this->assertEquals($expected, $result->toArray()); <del> $this->assertFalse($entity->isAccessible('*')); <del> }); <del> } <del> <ide> /** <ide> * Tests that it is possible to pass a fields option to the merge method <ide> *
2
Javascript
Javascript
check statements in path for asi safe
f000854cee3caae71b0a6397c1c5ccf13302675a
<ide><path>lib/javascript/JavascriptParser.js <ide> class JavascriptParser extends Parser { <ide> * @returns {boolean} true when a semicolon has been inserted before this position, false if not <ide> */ <ide> isAsiPosition(pos) { <del> const currentStatement = this.statementPath[this.statementPath.length - 1]; <del> if (currentStatement === undefined) throw new Error("Not in statement"); <add> const len = this.statementPath.length; <add> <add> if (len === 0) throw new Error("Not in statement"); <add> <add> const currentStatement = this.statementPath[len - 1]; <add> <add> // check for statements with one child statement <add> // that current statement is a child <add> if (len !== 1) { <add> const prevStatementInPath = this.statementPath[len - 2]; <add> switch (prevStatementInPath.type) { <add> case "IfStatement": <add> if ( <add> prevStatementInPath.consequent === currentStatement || <add> prevStatementInPath.alternate === currentStatement <add> ) <add> return false; <add> break; <add> case "ThrowStatement": <add> if (prevStatementInPath.argument === currentStatement) return false; <add> break; <add> case "ForStatement": <add> case "ForInStatement": <add> case "ForOfStatement": <add> case "WhileStatement": <add> case "DoWhileStatement": <add> case "WithStatement": <add> if (prevStatementInPath.body === currentStatement) return false; <add> break; <add> } <add> } <add> <ide> return ( <ide> (currentStatement.range[1] === pos && this.semicolons.has(pos)) || <ide> (currentStatement.range[0] === pos && <ide><path>test/cases/parsing/asi/a.js <ide> export function a() {} <add> <add>let count = 0; <add> <add>export function callme() { <add> count++; <add>} <add> <add>export function getCount() { <add> return count; <add>} <ide><path>test/cases/parsing/asi/index.js <del>import {a as b} from "./a"; <add>import {a as b, callme, getCount} from "./a"; <ide> import * as c from "./b"; <ide> <ide> function donotcallme() { <ide> it("should respect asi flag", () => { <ide> b(); <ide> (donotcallme) <ide> c; <add> <add> let i = 0; <add> for (;i < 1;i++) callme() <add> for (;i < 2;i++) { <add> (donotcallme) <add> b(); <add> } <add> if (i++) callme() <add> if (false) {} else callme() <add> while (i++ < 4) callme() <add> <add> expect(getCount()).toBe(4) <ide> });
3
Go
Go
add ps -s
bd04d7d475e6497070b3144e6526566b066674cf
<ide><path>api.go <ide> func getContainersJSON(srv *Server, version float64, w http.ResponseWriter, r *h <ide> if err != nil { <ide> return err <ide> } <add> size, err := getBoolParam(r.Form.Get("size")) <add> if err != nil { <add> return err <add> } <ide> since := r.Form.Get("since") <ide> before := r.Form.Get("before") <ide> n, err := strconv.Atoi(r.Form.Get("limit")) <ide> if err != nil { <ide> n = -1 <ide> } <ide> <del> outs := srv.Containers(all, n, since, before) <add> outs := srv.Containers(all, size, n, since, before) <ide> b, err := json.Marshal(outs) <ide> if err != nil { <ide> return err <ide><path>commands.go <ide> func (cli *DockerCli) CmdImages(args ...string) error { <ide> func (cli *DockerCli) CmdPs(args ...string) error { <ide> cmd := Subcmd("ps", "[OPTIONS]", "List containers") <ide> quiet := cmd.Bool("q", false, "Only display numeric IDs") <add> size := cmd.Bool("s", false, "Display sizes") <ide> all := cmd.Bool("a", false, "Show all containers. Only running containers are shown by default.") <ide> noTrunc := cmd.Bool("notrunc", false, "Don't truncate output") <ide> nLatest := cmd.Bool("l", false, "Show only the latest created container, include non-running ones.") <ide> func (cli *DockerCli) CmdPs(args ...string) error { <ide> if *before != "" { <ide> v.Set("before", *before) <ide> } <add> if *size { <add> v.Set("size", "1") <add> } <ide> <ide> body, _, err := cli.call("GET", "/containers/json?"+v.Encode(), nil) <ide> if err != nil { <ide> func (cli *DockerCli) CmdPs(args ...string) error { <ide> } <ide> w := tabwriter.NewWriter(os.Stdout, 20, 1, 3, ' ', 0) <ide> if !*quiet { <del> fmt.Fprintln(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS\tSIZE") <add> fmt.Fprint(w, "ID\tIMAGE\tCOMMAND\tCREATED\tSTATUS\tPORTS") <add> if *size { <add> fmt.Fprintln(w, "\tSIZE") <add> } else { <add> fmt.Fprint(w, "\n") <add> } <ide> } <ide> <ide> for _, out := range outs { <ide> func (cli *DockerCli) CmdPs(args ...string) error { <ide> } else { <ide> fmt.Fprintf(w, "%s\t%s\t%s\t%s ago\t%s\t%s\t", utils.TruncateID(out.ID), out.Image, utils.Trunc(out.Command, 20), utils.HumanDuration(time.Now().Sub(time.Unix(out.Created, 0))), out.Status, out.Ports) <ide> } <del> if out.SizeRootFs > 0 { <del> fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs)) <add> if *size { <add> if out.SizeRootFs > 0 { <add> fmt.Fprintf(w, "%s (virtual %s)\n", utils.HumanSize(out.SizeRw), utils.HumanSize(out.SizeRootFs)) <add> } else { <add> fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw)) <add> } <ide> } else { <del> fmt.Fprintf(w, "%s\n", utils.HumanSize(out.SizeRw)) <add> fmt.Fprint(w, "\n") <ide> } <ide> } else { <ide> if *noTrunc { <ide><path>server.go <ide> func (srv *Server) ContainerChanges(name string) ([]Change, error) { <ide> return nil, fmt.Errorf("No such container: %s", name) <ide> } <ide> <del>func (srv *Server) Containers(all bool, n int, since, before string) []APIContainers { <add>func (srv *Server) Containers(all, size bool, n int, since, before string) []APIContainers { <ide> var foundBefore bool <ide> var displayed int <ide> retContainers := []APIContainers{} <ide> func (srv *Server) Containers(all bool, n int, since, before string) []APIContai <ide> c.Created = container.Created.Unix() <ide> c.Status = container.State.String() <ide> c.Ports = container.NetworkSettings.PortMappingHuman() <del> c.SizeRw, c.SizeRootFs = container.GetSize() <del> <add> if size { <add> c.SizeRw, c.SizeRootFs = container.GetSize() <add> } <ide> retContainers = append(retContainers, c) <ide> } <ide> return retContainers
3
Javascript
Javascript
fix lint 2
f71be559274857e6ea00f6513f61bd8d3255733a
<ide><path>src/main-process/atom-window.js <ide> module.exports = class AtomWindow extends EventEmitter { <ide> this.browserWindow.webContents.on( <ide> 'render-process-gone', <ide> async (event, { reason }) => { <del> if (reason === "crashed") { <add> if (reason === 'crashed') { <ide> if (this.headless) { <ide> console.log('Renderer process crashed, exiting'); <ide> this.atomApplication.exit(100);
1
Go
Go
fix error message for non-buildkit
b1942bc015f0ec6258c39748032171c09bf562ab
<ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildDockerignoringBadExclusion(c *check.C) { <ide> build.WithFile(".dockerignore", "!\n"), <ide> )).Assert(c, icmd.Expected{ <ide> ExitCode: 1, <del> Err: `: illegal exclusion pattern: "!"`, <add> Err: `illegal exclusion pattern: "!"`, <ide> }) <ide> } <ide>
1
Javascript
Javascript
give unified name to vmd animation
0e1a70097f027a536c0d51a4c1cb808093459e8a
<ide><path>examples/js/loaders/MMDLoader.js <ide> THREE.MMDLoader.prototype.mergeVmds = function ( vmds ) { <ide> <ide> }; <ide> <del>THREE.MMDLoader.prototype.pourVmdIntoModel = function ( mesh, vmd ) { <add>THREE.MMDLoader.prototype.pourVmdIntoModel = function ( mesh, vmd, name ) { <ide> <del> this.createAnimation( mesh, vmd ); <add> this.createAnimation( mesh, vmd, name ); <ide> <ide> }; <ide> <del>THREE.MMDLoader.prototype.pourVmdIntoCamera = function ( camera, vmd ) { <add>THREE.MMDLoader.prototype.pourVmdIntoCamera = function ( camera, vmd, name ) { <ide> <ide> var helper = new THREE.MMDLoader.DataCreationHelper(); <ide> <ide> THREE.MMDLoader.prototype.pourVmdIntoCamera = function ( camera, vmd ) { <ide> <ide> } <ide> <del> camera.animations.push( new THREE.AnimationClip( 'cameraAnimation', -1, tracks ) ); <add> camera.animations.push( new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name, -1, tracks ) ); <ide> <ide> }; <ide> <ide> THREE.MMDLoader.prototype.createMesh = function ( model, texturePath, onProgress <ide> <ide> }; <ide> <del>THREE.MMDLoader.prototype.createAnimation = function ( mesh, vmd ) { <add>THREE.MMDLoader.prototype.createAnimation = function ( mesh, vmd, name ) { <ide> <ide> var scope = this; <ide> <ide> THREE.MMDLoader.prototype.createAnimation = function ( mesh, vmd ) { <ide> var orderedMotions = helper.createOrderedMotionArrays( bones, vmd.motions, 'boneName' ); <ide> <ide> var animation = { <del> name: 'Action', <add> name: name === undefined ? THREE.Math.generateUUID() : name, <ide> fps: 30, <ide> length: 0.0, <ide> hierarchy: [] <ide> THREE.MMDLoader.prototype.createAnimation = function ( mesh, vmd ) { <ide> <ide> } <ide> <del> mesh.geometry.morphAnimations.push( new THREE.AnimationClip( 'morphAnimation', -1, tracks ) ); <add> mesh.geometry.morphAnimations.push( new THREE.AnimationClip( name === undefined ? THREE.Math.generateUUID() : name + 'Morph', -1, tracks ) ); <ide> <ide> }; <ide> <ide> THREE.MMDHelper.prototype = { <ide> <ide> if ( mesh.geometry.animations !== undefined ) { <ide> <del> mesh.mixer.clipAction( mesh.geometry.animations[ 0 ] ).play(); <add> for ( var i = 0; i < mesh.geometry.animations.length; i++ ) { <add> <add> var action = mesh.mixer.clipAction( mesh.geometry.animations[ i ] ); <add> <add> if ( i === 0 ) { <add> <add> action.play(); <add> <add> } <add> <add> } <ide> <ide> } <ide> <ide> if ( mesh.geometry.morphAnimations !== undefined ) { <ide> <del> mesh.mixer.clipAction( mesh.geometry.morphAnimations[ 0 ] ).play() ; <add> for ( var i = 0; i < mesh.geometry.morphAnimations.length; i++ ) { <add> <add> var action = mesh.mixer.clipAction( mesh.geometry.morphAnimations[ i ] ); <add> <add> if ( i === 0 ) { <add> <add> action.play(); <add> <add> } <add> <add> } <ide> <ide> } <ide>
1
Java
Java
add doafterterminate callback to the single type.
7bfecccedd8641027a17438192a1ff30fd1addb8
<ide><path>src/main/java/io/reactivex/Single.java <ide> public final Single<T> doAfterSuccess(Consumer<? super T> onAfterSuccess) { <ide> return RxJavaPlugins.onAssembly(new SingleDoAfterSuccess<T>(this, onAfterSuccess)); <ide> } <ide> <add> /** <add> * Registers an {@link Action} to be called after this Single invokes either onSuccess or onError. <add> * * <p>Note that the {@code doAfterSuccess} action is shared between subscriptions and as such <add> * should be thread-safe.</p> <add> * <p> <add> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/doAfterTerminate.png" alt=""> <add> * <dl> <add> * <dt><b>Scheduler:</b></dt> <add> * <dd>{@code doAfterTerminate} does not operate by default on a particular {@link Scheduler}.</dd> <add> * </dl> <add> * <add> * @param onAfterTerminate <add> * an {@link Action} to be invoked when the source Single finishes <add> * @return a Single that emits the same items as the source Single, then invokes the <add> * {@link Action} <add> * @see <a href="http://reactivex.io/documentation/operators/do.html">ReactiveX operators documentation: Do</a> <add> * @since 2.0.6 - experimental <add> */ <add> @CheckReturnValue <add> @SchedulerSupport(SchedulerSupport.NONE) <add> @Experimental <add> public final Single<T> doAfterTerminate(Action onAfterTerminate) { <add> ObjectHelper.requireNonNull(onAfterTerminate, "onAfterTerminate is null"); <add> return RxJavaPlugins.onAssembly(new SingleDoAfterTerminate<T>(this, onAfterTerminate)); <add> } <add> <ide> /** <ide> * Calls the specified action after this Single signals onSuccess or onError or gets disposed by <ide> * the downstream. <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleDoAfterTerminate.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.single; <add> <add>import io.reactivex.Single; <add>import io.reactivex.SingleObserver; <add>import io.reactivex.SingleSource; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <add>import io.reactivex.functions.Action; <add>import io.reactivex.internal.disposables.DisposableHelper; <add>import io.reactivex.plugins.RxJavaPlugins; <add> <add>/** <add> * Calls an action after pushing the current item or an error to the downstream. <add> * @param <T> the value type <add> * @since 2.0.6 - experimental <add> */ <add>public final class SingleDoAfterTerminate<T> extends Single<T> { <add> <add> final SingleSource<T> source; <add> <add> final Action onAfterTerminate; <add> <add> public SingleDoAfterTerminate(SingleSource<T> source, Action onAfterTerminate) { <add> this.source = source; <add> this.onAfterTerminate = onAfterTerminate; <add> } <add> <add> @Override <add> protected void subscribeActual(SingleObserver<? super T> s) { <add> source.subscribe(new DoAfterTerminateObserver<T>(s, onAfterTerminate)); <add> } <add> <add> static final class DoAfterTerminateObserver<T> implements SingleObserver<T>, Disposable { <add> <add> final SingleObserver<? super T> actual; <add> <add> final Action onAfterTerminate; <add> <add> Disposable d; <add> <add> DoAfterTerminateObserver(SingleObserver<? super T> actual, Action onAfterTerminate) { <add> this.actual = actual; <add> this.onAfterTerminate = onAfterTerminate; <add> } <add> <add> @Override <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.validate(this.d, d)) { <add> this.d = d; <add> <add> actual.onSubscribe(this); <add> } <add> } <add> <add> @Override <add> public void onSuccess(T t) { <add> actual.onSuccess(t); <add> <add> onAfterTerminate(); <add> } <add> <add> @Override <add> public void onError(Throwable e) { <add> actual.onError(e); <add> <add> onAfterTerminate(); <add> } <add> <add> @Override <add> public void dispose() { <add> d.dispose(); <add> } <add> <add> @Override <add> public boolean isDisposed() { <add> return d.isDisposed(); <add> } <add> <add> private void onAfterTerminate() { <add> try { <add> onAfterTerminate.run(); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <add> RxJavaPlugins.onError(ex); <add> } <add> } <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/single/SingleDoAfterTerminateTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.single; <add> <add>import io.reactivex.Single; <add>import io.reactivex.SingleSource; <add>import io.reactivex.TestHelper; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Action; <add>import io.reactivex.functions.Function; <add>import io.reactivex.internal.functions.Functions; <add>import io.reactivex.observers.TestObserver; <add>import io.reactivex.plugins.RxJavaPlugins; <add>import io.reactivex.subjects.PublishSubject; <add>import org.junit.Test; <add> <add>import java.util.List; <add> <add>import static org.junit.Assert.assertEquals; <add> <add>public class SingleDoAfterTerminateTest { <add> <add> private final int[] call = { 0 }; <add> <add> private final Action afterTerminate = new Action() { <add> @Override <add> public void run() throws Exception { <add> call[0]++; <add> } <add> }; <add> <add> private final TestObserver<Integer> ts = new TestObserver<Integer>(); <add> <add> @Test <add> public void just() { <add> Single.just(1) <add> .doAfterTerminate(afterTerminate) <add> .subscribeWith(ts) <add> .assertResult(1); <add> <add> assertAfterTerminateCalledOnce(); <add> } <add> <add> @Test <add> public void error() { <add> Single.<Integer>error(new TestException()) <add> .doAfterTerminate(afterTerminate) <add> .subscribeWith(ts) <add> .assertFailure(TestException.class); <add> <add> assertAfterTerminateCalledOnce(); <add> } <add> <add> @Test(expected = NullPointerException.class) <add> public void afterTerminateActionNull() { <add> Single.just(1).doAfterTerminate(null); <add> } <add> <add> @Test <add> public void justConditional() { <add> Single.just(1) <add> .doAfterTerminate(afterTerminate) <add> .filter(Functions.alwaysTrue()) <add> .subscribeWith(ts) <add> .assertResult(1); <add> <add> assertAfterTerminateCalledOnce(); <add> } <add> <add> @Test <add> public void errorConditional() { <add> Single.<Integer>error(new TestException()) <add> .doAfterTerminate(afterTerminate) <add> .filter(Functions.alwaysTrue()) <add> .subscribeWith(ts) <add> .assertFailure(TestException.class); <add> <add> assertAfterTerminateCalledOnce(); <add> } <add> <add> @Test <add> public void actionThrows() { <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> Single.just(1) <add> .doAfterTerminate(new Action() { <add> @Override <add> public void run() throws Exception { <add> throw new TestException(); <add> } <add> }) <add> .test() <add> .assertResult(1); <add> <add> TestHelper.assertUndeliverable(errors, 0, TestException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void dispose() { <add> TestHelper.checkDisposed(PublishSubject.<Integer>create().singleOrError().doAfterTerminate(afterTerminate)); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Integer>, SingleSource<Integer>>() { <add> @Override <add> public SingleSource<Integer> apply(Single<Integer> m) throws Exception { <add> return m.doAfterTerminate(afterTerminate); <add> } <add> }); <add> } <add> <add> private void assertAfterTerminateCalledOnce() { <add> assertEquals(1, call[0]); <add> } <add>}
3
Javascript
Javascript
add regression test for
0d3fc9de1019fcc69d3be0add555ea47f364059c
<ide><path>packages/react-dom/src/__tests__/DOMPropertyOperations-test.js <ide> describe('DOMPropertyOperations', () => { <ide> ReactDOM.render(<progress value="30" />, container); <ide> expect(container.firstChild.setAttribute).toHaveBeenCalledTimes(2); <ide> }); <add> <add> it('should return the progress to intermediate state on null value', () => { <add> const container = document.createElement('div'); <add> ReactDOM.render(<progress value={30} />, container); <add> ReactDOM.render(<progress value={null} />, container); <add> // Ensure we move progress back to an indeterminate state. <add> // Regression test for https://github.com/facebook/react/issues/6119 <add> expect(container.firstChild.hasAttribute('value')).toBe(false); <add> }); <ide> }); <ide> <ide> describe('deleteValueForProperty', () => {
1
Javascript
Javascript
fix cancelchildanimations throwing exception
b9557b0a86206d938a738ea470736d011dff7e1a
<ide><path>src/ngAnimate/animate.js <ide> angular.module('ngAnimate', ['ng']) <ide> var forEach = angular.forEach; <ide> var selectors = $animateProvider.$$selectors; <ide> <add> var ELEMENT_NODE = 1; <ide> var NG_ANIMATE_STATE = '$$ngAnimateState'; <ide> var NG_ANIMATE_CLASS_NAME = 'ng-animate'; <ide> var rootAnimateState = {running:true}; <ide> angular.module('ngAnimate', ['ng']) <ide> } <ide> <ide> function cancelChildAnimations(element) { <del> angular.forEach(element[0].querySelectorAll('.' + NG_ANIMATE_CLASS_NAME), function(element) { <add> var node = element[0]; <add> if(node.nodeType != ELEMENT_NODE) { <add> return; <add> } <add> <add> angular.forEach(node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME), function(element) { <ide> element = angular.element(element); <ide> var data = element.data(NG_ANIMATE_STATE); <ide> if(data) { <ide> angular.module('ngAnimate', ['ng']) <ide> var durationKey = 'Duration', <ide> propertyKey = 'Property', <ide> delayKey = 'Delay', <del> animationIterationCountKey = 'IterationCount', <del> ELEMENT_NODE = 1; <add> animationIterationCountKey = 'IterationCount'; <ide> <ide> var NG_ANIMATE_PARENT_KEY = '$ngAnimateKey'; <ide> var lookupCache = {};
1
Javascript
Javascript
remove the monkeypatch of watchpack (#580)
8d543bd1485a65d7a2cb6c96ad04ff201249cae7
<ide><path>server/build/plugins/watch-remove-event-plugin.js <ide> export default class WatchRemoveEventPlugin { <ide> }, callbackUndelayed) <ide> <ide> const watchpack = watchFileSystem.watcher <del> watchpack.fileWatchers.forEach((w) => { <del> w.on('remove', this.onRemove.bind(this, watchpack, w.path)) <add> watchpack.on('remove', (file) => { <add> this.removedFiles.push(file) <ide> }) <ide> return result <ide> } <ide> } <del> <del> onRemove (watchpack, file) { <del> this.removedFiles.push(file) <del> watchpack.emit('remove', file) <del> watchpack._onChange(file) <del> } <del>} <del> <del>// monkeypatching watchpack module to fix <del>// https://github.com/webpack/watchpack/pull/33 <del> <del>let DirectoryWatcher <del>try { <del> DirectoryWatcher = require('webpack/node_modules/watchpack/lib/DirectoryWatcher') <del>} catch (err) { <del> DirectoryWatcher = require('watchpack/lib/DirectoryWatcher') <del>} <del> <del>/* eslint-disable */ <del>var FS_ACCURENCY = 10000; <del> <del>function withoutCase(str) { <del> return str.toLowerCase(); <ide> } <del> <del>DirectoryWatcher.prototype.setFileTime = function setFileTime(filePath, mtime, initial, type) { <del> var now = Date.now(); <del> var old = this.files[filePath]; <del> <del> this.files[filePath] = [initial ? Math.min(now, mtime) : now, mtime]; <del> <del> // we add the fs accurency to reach the maximum possible mtime <del> if(mtime) <del> mtime = mtime + FS_ACCURENCY; <del> <del> if(!old) { <del> if(mtime) { <del> if(this.watchers[withoutCase(filePath)]) { <del> this.watchers[withoutCase(filePath)].forEach(function(w) { <del> if(!initial || w.checkStartTime(mtime, initial)) { <del> w.emit("change", mtime); <del> } <del> }); <del> } <del> } <del> } else if(!initial && mtime && type !== "add") { <del> if(this.watchers[withoutCase(filePath)]) { <del> this.watchers[withoutCase(filePath)].forEach(function(w) { <del> w.emit("change", mtime); <del> }); <del> } <del> } else if(!initial && !mtime) { <del> delete this.files[filePath]; <del> if(this.watchers[withoutCase(filePath)]) { <del> this.watchers[withoutCase(filePath)].forEach(function(w) { <del> w.emit("remove"); <del> }); <del> } <del> } <del> if(this.watchers[withoutCase(this.path)]) { <del> this.watchers[withoutCase(this.path)].forEach(function(w) { <del> if(!initial || w.checkStartTime(mtime, initial)) { <del> w.emit("change", filePath, mtime); <del> } <del> }); <del> } <del>}; <del>/* eslint-enable */
1
Python
Python
add docstrings in callbacks, models, optimizers
9a93fc51cf50bb557c30678ba1c75826860a1425
<ide><path>keras/callbacks.py <ide> def on_train_end(self, logs={}): <ide> <ide> <ide> class Callback(object): <del> <add> '''Abstract base class used to build new callbacks. <add> <add> # Properties <add> params: dict. Training parameters <add> (eg. verbosity, batch size, number of epochs...). <add> model: instance of `keras.models.Model`. <add> Reference of the model being trained. <add> <add> The `logs` dictionary that callback methods <add> take as argument will contain keys for quantities relevant to <add> the current batch or epoch. <add> <add> Currently, the `.fit()` method of the `Sequential` model class <add> will include the following quantities in the `logs` that <add> it passes to its callbacks: <add> <add> on_epoch_end: logs optionally include `val_loss` <add> (if validation is enabled in `fit`), and `val_acc` <add> (if validation and accuracy monitoring are enabled). <add> on_batch_begin: logs include `size`, <add> the number of samples in the current batch. <add> on_batch_end: logs include `loss`, and optionally `acc` <add> (if accuracy monitoring is enabled). <add> ''' <ide> def __init__(self): <ide> pass <ide> <ide> def on_train_end(self, logs={}): <ide> <ide> <ide> class BaseLogger(Callback): <add> '''Callback that prints events to the standard output. <add> <add> This callback is automatically applied to <add> every Keras model (it is the basis of the verbosity modes <add> in models). <add> ''' <ide> def on_train_begin(self, logs={}): <ide> self.verbose = self.params['verbose'] <ide> self.nb_epoch = self.params['nb_epoch'] <ide> def on_batch_end(self, batch, logs={}): <ide> if k in logs: <ide> self.log_values.append((k, logs[k])) <ide> <del> # skip progbar update for the last batch; will be handled by on_epoch_end <add> # skip progbar update for the last batch; <add> # will be handled by on_epoch_end <ide> if self.verbose and self.seen < self.params['nb_sample']: <ide> self.progbar.update(self.seen, self.log_values) <ide> <ide> def on_epoch_end(self, epoch, logs={}): <ide> <ide> <ide> class History(Callback): <add> '''Callback that records events <add> into a `History` object. <ide> <add> This callback is automatically applied to <add> every Keras model. The `History` object <add> gets returned by the `fit` method of models. <add> ''' <ide> def on_train_begin(self, logs={}): <ide> self.epoch = [] <ide> self.history = {} <ide> def on_epoch_end(self, epoch, logs={}): <ide> <ide> <ide> class ModelCheckpoint(Callback): <del> def __init__(self, filepath, monitor='val_loss', verbose=0, save_best_only=False, mode='auto'): <add> '''Save the model after every epoch. <add> <add> `filepath` can contain named formatting options, <add> which will be filled the value of `epoch` and <add> keys in `logs` (passed in `on_epoch_end`). <add> <add> For example: if `filepath` is `weights.{epoch:02d}-{val_loss:.2f}.hdf5`, <add> then multiple files will be save with the epoch number and <add> the validation loss. <add> <add> # Arguments <add> filepath: string, path to save the model file. <add> monitor: quantity to monitor. <add> verbose: verbosity mode, 0 or 1. <add> save_best_only: if `save_best_only=True`, <add> the latest best model according to <add> the validation loss will not be overwritten. <add> mode: one of {auto, min, max}. <add> If `save_best_only=True`, the decision <add> to overwrite the current save file is made <add> based on either the maximization or the <add> minization of the monitored. For `val_acc`, <add> this should be `max`, for `val_loss` this should <add> be `min`, etc. In `auto` mode, the direction is <add> automatically inferred from the name of the monitored quantity. <add> <add> ''' <add> def __init__(self, filepath, monitor='val_loss', verbose=0, <add> save_best_only=False, mode='auto'): <ide> <ide> super(Callback, self).__init__() <ide> self.monitor = monitor <ide> self.verbose = verbose <ide> self.filepath = filepath <ide> self.save_best_only = save_best_only <del> <add> <ide> if mode not in ['auto', 'min', 'max']: <del> warnings.warn("ModelCheckpoint mode %s is unknown, fallback to auto mode" % (self.mode), RuntimeWarning) <add> warnings.warn('ModelCheckpoint mode %s is unknown, ' <add> 'fallback to auto mode' % (self.mode), RuntimeWarning) <ide> mode = 'auto' <del> <del> if mode == "min": <add> <add> if mode == 'min': <ide> self.monitor_op = np.less <ide> self.best = np.Inf <del> elif mode == "max": <add> elif mode == 'max': <ide> self.monitor_op = np.greater <ide> self.best = -np.Inf <ide> else: <del> if "acc" in self.monitor: <add> if 'acc' in self.monitor: <ide> self.monitor_op = np.greater <ide> self.best = -np.Inf <ide> else: <ide> def on_epoch_end(self, epoch, logs={}): <ide> if self.save_best_only: <ide> current = logs.get(self.monitor) <ide> if current is None: <del> warnings.warn("Can save best model only with %s available, skipping." % (self.monitor), RuntimeWarning) <add> warnings.warn('Can save best model only with %s available, ' <add> 'skipping.' % (self.monitor), RuntimeWarning) <ide> else: <ide> if self.monitor_op(current, self.best): <ide> if self.verbose > 0: <del> print("Epoch %05d: %s improved from %0.5f to %0.5f, saving model to %s" <del> % (epoch, self.monitor, self.best, current, filepath)) <add> print('Epoch %05d: %s improved from %0.5f to %0.5f, ' + <add> 'saving model to %s' <add> % (epoch, self.monitor, self.best, <add> current, filepath)) <ide> self.best = current <ide> self.model.save_weights(filepath, overwrite=True) <ide> else: <ide> if self.verbose > 0: <del> print("Epoch %05d: %s did not improve" % (epoch, self.monitor)) <add> print('Epoch %05d: %s did not improve' % <add> (epoch, self.monitor)) <ide> else: <ide> if self.verbose > 0: <del> print("Epoch %05d: saving model to %s" % (epoch, filepath)) <add> print('Epoch %05d: saving model to %s' % (epoch, filepath)) <ide> self.model.save_weights(filepath, overwrite=True) <ide> <ide> <ide> class EarlyStopping(Callback): <add> '''Stop training when a monitored quantity has stopped improving. <add> <add> # Arguments <add> monitor: quantity to be monitored. <add> patience: number of epochs with no improvement <add> after which training will be stopped. <add> verbose: verbosity mode. <add> ''' <ide> def __init__(self, monitor='val_loss', patience=0, verbose=0): <ide> super(Callback, self).__init__() <ide> <ide> def __init__(self, monitor='val_loss', patience=0, verbose=0): <ide> def on_epoch_end(self, epoch, logs={}): <ide> current = logs.get(self.monitor) <ide> if current is None: <del> warnings.warn("Early stopping requires %s available!" % (self.monitor), RuntimeWarning) <add> warnings.warn('Early stopping requires %s available!' % <add> (self.monitor), RuntimeWarning) <ide> <ide> if current < self.best: <ide> self.best = current <ide> self.wait = 0 <ide> else: <ide> if self.wait >= self.patience: <ide> if self.verbose > 0: <del> print("Epoch %05d: early stopping" % (epoch)) <add> print('Epoch %05d: early stopping' % (epoch)) <ide> self.model.stop_training = True <ide> self.wait += 1 <ide> <ide> <ide> class RemoteMonitor(Callback): <add> '''Experimental callback used to stream events to a server. <add> <add> Requires the `requests` library. <add> ''' <ide> def __init__(self, root='http://localhost:9000'): <ide> self.root = root <ide> <ide> def on_epoch_end(self, epoch, logs={}): <ide> send[k] = v <ide> <ide> try: <del> r = requests.post(self.root + '/publish/epoch/end/', {'data': json.dumps(send)}) <add> requests.post(self.root + '/publish/epoch/end/', <add> {'data': json.dumps(send)}) <ide> except: <del> print('Warning: could not reach RemoteMonitor root server at ' + str(self.root)) <add> print('Warning: could not reach RemoteMonitor ' <add> 'root server at ' + str(self.root)) <ide> <ide> <ide> class LearningRateScheduler(Callback): <del> '''LearningRateScheduler <del> schedule is a function that gets an epoch number as input and returns a new <del> learning rate as output. <add> '''Learning rate scheduler. <add> <add> # Arguments <add> schedule: a function that gets an epoch index as input <add> (integer, indexed from 0) and returns a new <add> learning rate as output. <ide> ''' <ide> def __init__(self, schedule): <ide> super(LearningRateScheduler, self).__init__() <ide><path>keras/layers/core.py <ide> class Layer(object): <ide> '''Abstract base layer class. <ide> <ide> All Keras layers accept certain keyword arguments: <add> <ide> trainable: boolean. Set to "False" before model compilation <ide> to freeze layer weights (they won't be updated further <ide> during training). <ide><path>keras/models.py <ide> from __future__ import print_function <ide> import numpy as np <ide> import warnings <del>import time <del>import copy <ide> import pprint <ide> from six.moves import range <ide> import six <ide> <ide> from . import backend as K <ide> from . import optimizers <ide> from . import objectives <del>from . import regularizers <del>from . import constraints <ide> from . import callbacks as cbks <del>from .utils.layer_utils import container_from_config, model_summary <del>from .utils.generic_utils import Progbar, printv <add>from .utils.layer_utils import container_from_config <add>from .utils.layer_utils import model_summary <add>from .utils.generic_utils import Progbar <ide> from .layers import containers <ide> <ide> <ide> def standardize_X(X): <ide> <ide> <ide> def slice_X(X, start=None, stop=None): <add> ''' <add> ''' <ide> if type(X) == list: <ide> if hasattr(start, '__len__'): <ide> # hdf5 dataset only support list object as indices <ide> def slice_X(X, start=None, stop=None): <ide> <ide> def weighted_objective(fn): <ide> def weighted(y_true, y_pred, weights, mask=None): <del> '''To be called only with non-zero weights. <del> <del> mask: binary <add> ''' <ide> ''' <ide> # score_array has ndim >= 2 <ide> score_array = fn(y_true, y_pred) <ide> def weighted(y_true, y_pred, weights, mask=None): <ide> <ide> <ide> def standardize_weights(y, sample_weight=None, class_weight=None): <add> ''' <add> ''' <ide> if sample_weight is not None: <ide> assert len(sample_weight) == len(y) <ide> return sample_weight.flatten() <ide> elif isinstance(class_weight, dict): <ide> if len(y.shape) > 2: <del> raise Exception('class_weight not supported for 3+ dimensional targets.') <add> raise Exception('class_weight not supported for ' <add> '3+ dimensional targets.') <ide> if y.shape[1] > 1: <ide> y_classes = y.argmax(axis=1) <ide> elif y.shape[1] == 1: <ide> def model_from_json(json_string, custom_objects={}): <ide> <ide> <ide> def model_from_config(config, custom_objects={}): <add> ''' <add> ''' <ide> model_name = config.get('name') <ide> if model_name not in {'Graph', 'Sequential'}: <ide> raise Exception('Unrecognized model:', model_name) <ide> def model_from_config(config, custom_objects={}): <ide> # if it has an optimizer, the model is assumed to be compiled <ide> loss = config.get('loss') <ide> class_mode = config.get('class_mode') <del> theano_mode = config.get('theano_mode') <ide> <ide> optimizer_params = dict([(k, v) for k, v in config.get('optimizer').items()]) <ide> optimizer_name = optimizer_params.pop('name') <ide> optimizer = optimizers.get(optimizer_name, optimizer_params) <ide> <ide> if model_name == 'Sequential': <ide> model.compile(loss=loss, optimizer=optimizer, <del> class_mode=class_mode, theano_mode=theano_mode) <add> class_mode=class_mode) <ide> elif model_name == 'Graph': <del> model.compile(loss=loss, optimizer=optimizer, <del> theano_mode=theano_mode) <add> model.compile(loss=loss, optimizer=optimizer) <ide> return model <ide> <ide> <ide> def get_function_name(o): <ide> <ide> <ide> class Model(object): <add> '''Abstract base model class. <add> ''' <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, <ide> nb_epoch=100, verbose=1, callbacks=[], <ide> val_f=None, val_ins=None, shuffle=True, metrics=[]): <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, <ide> if val_f and val_ins: <ide> do_validation = True <ide> if verbose: <del> print("Train on %d samples, validate on %d samples" % (len(ins[0]), len(val_ins[0]))) <add> print('Train on %d samples, validate on %d samples' % <add> (len(ins[0]), len(val_ins[0]))) <ide> <ide> nb_train_sample = len(ins[0]) <ide> index_array = np.arange(nb_train_sample) <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, <ide> try: <ide> ins_batch = slice_X(ins, batch_ids) <ide> except TypeError: <del> raise Exception('TypeError while preparing batch. \ <del> If using HDF5 input data, pass shuffle="batch".\n') <del> <add> raise Exception('TypeError while preparing batch. ' <add> 'If using HDF5 input data, ' <add> 'pass shuffle="batch".') <ide> batch_logs = {} <ide> batch_logs['batch'] = batch_index <ide> batch_logs['size'] = len(batch_ids) <ide> def _fit(self, f, ins, out_labels=[], batch_size=128, <ide> return history <ide> <ide> def _predict_loop(self, f, ins, batch_size=128, verbose=0): <del> ''' <del> Abstract method to loop over some data in batches. <add> '''Abstract method to loop over some data in batches. <ide> ''' <ide> nb_sample = len(ins[0]) <ide> outs = [] <ide> def _predict_loop(self, f, ins, batch_size=128, verbose=0): <ide> return outs <ide> <ide> def _test_loop(self, f, ins, batch_size=128, verbose=0): <del> ''' <del> Abstract method to loop over some data in batches. <add> '''Abstract method to loop over some data in batches. <ide> ''' <ide> nb_sample = len(ins[0]) <ide> outs = [] <ide> def _test_loop(self, f, ins, batch_size=128, verbose=0): <ide> return outs <ide> <ide> def get_config(self, verbose=0): <add> '''Return the configuration of the model <add> as a dictionary. <add> <add> To load a model from its configuration, use <add> `keras.models.model_from_config(config, custom_objects={})`. <add> ''' <ide> config = super(Model, self).get_config() <del> for p in ['class_mode', 'theano_mode']: <add> for p in ['class_mode']: <ide> if hasattr(self, p): <ide> config[p] = getattr(self, p) <ide> if hasattr(self, 'optimizer'): <ide> def get_config(self, verbose=0): <ide> return config <ide> <ide> def to_yaml(self, **kwargs): <del> # dump model configuration to yaml string <add> '''Return a yaml string containing the model configuration. <add> <add> To load a model from a yaml save file, use <add> `keras.models.from_yaml(yaml_string, custom_objects={})`. <add> <add> `custom_objects` should be a dictionary mapping <add> the names of custom losses / layers / etc to the corresponding <add> functions / classes. <add> ''' <ide> import yaml <ide> config = self.get_config() <ide> return yaml.dump(config, **kwargs) <ide> <ide> def to_json(self, **kwargs): <del> # dump model configuration to json string <add> '''Return a JSON string containing the model configuration. <add> <add> To load a model from a JSON save file, use <add> `keras.models.from_json(json_string, custom_objects={})`. <add> ''' <ide> import json <ide> config = self.get_config() <ide> return json.dumps(config, **kwargs) <ide> <ide> def summary(self): <add> '''Print out a summary of the model architecture, <add> include parameter count information. <add> ''' <ide> model_summary(self) <ide> <ide> <ide> class Sequential(Model, containers.Sequential): <del> ''' <del> Inherits from Model the following methods: <del> - _fit <del> - _predict <del> - _evaluate <del> Inherits from containers.Sequential the following methods: <del> - __init__ <del> - add <del> - get_output <del> - get_input <del> - get_weights <del> - set_weights <del> ''' <add> '''Linear stack of layers. <ide> <add> Inherits from containers.Sequential. <add> ''' <ide> def compile(self, optimizer, loss, <del> class_mode="categorical", theano_mode=None): <add> class_mode="categorical"): <add> '''Configure the learning process. <add> <add> # Arguments <add> optimizer: str (name of optimizer) or optimizer object. <add> See [optimizers](optimizers.md). <add> loss: str (name of objective function) or objective function. <add> See [objectives](objectives.md). <add> class_mode: one of "categorical", "binary". <add> This is only used for computing classification accuracy or <add> using the predict_classes method. <add> ''' <ide> self.optimizer = optimizers.get(optimizer) <ide> <ide> self.loss = objectives.get(loss) <ide> def compile(self, optimizer, loss, <ide> else: <ide> raise Exception("Invalid class mode:" + str(class_mode)) <ide> self.class_mode = class_mode <del> self.theano_mode = theano_mode <ide> <ide> for r in self.regularizers: <ide> train_loss = r(train_loss) <ide> def compile(self, optimizer, loss, <ide> self._test = K.function(test_ins, [test_loss]) <ide> self._test_with_acc = K.function(test_ins, [test_loss, test_accuracy]) <ide> <del> def train_on_batch(self, X, y, accuracy=False, <del> class_weight=None, sample_weight=None): <del> X = standardize_X(X) <del> y = standardize_y(y) <del> sample_weight = standardize_weights(y, class_weight=class_weight, <del> sample_weight=sample_weight) <del> ins = X + [y, sample_weight] <del> if accuracy: <del> return self._train_with_acc(ins) <del> else: <del> return self._train(ins) <del> <del> def test_on_batch(self, X, y, accuracy=False, sample_weight=None): <del> X = standardize_X(X) <del> y = standardize_y(y) <del> sample_weight = standardize_weights(y, sample_weight=sample_weight) <del> <del> ins = X + [y, sample_weight] <del> if accuracy: <del> return self._test_with_acc(ins) <del> else: <del> return self._test(ins) <del> <del> def predict_on_batch(self, X): <del> ins = standardize_X(X) <del> return self._predict(ins) <del> <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> validation_split=0., validation_data=None, shuffle=True, <ide> show_accuracy=False, class_weight=None, sample_weight=None): <del> <add> '''Train the model for a fixed number of epochs. <add> <add> Returns a history object. It `history` attribute is a record of <add> training loss values at successive epochs, <add> as well as validation loss values (if applicable). <add> <add> # Arguments <add> X: data, as a numpy array. <add> y: labels, as a numpy array. <add> batch_size: int. Number of samples per gradient update. <add> nb_epoch: int. <add> verbose: 0 for no logging to stdout, <add> 1 for progress bar logging, 2 for one log line per epoch. <add> callbacks: `keras.callbacks.Callback` list. <add> List of callbacks to apply during training. <add> See [callbacks](callbacks.md). <add> validation_split: float (0. < x < 1). <add> Fraction of the data to use as held-out validation data. <add> validation_data: tuple (X, y) to be used as held-out <add> validation data. Will override validation_split. <add> shuffle: boolean or str (for 'batch'). <add> Whether to shuffle the samples at each epoch. <add> 'batch' is a special option for dealing with the <add> limitations of HDF5 data; it shuffles in batch-sized chunks. <add> show_accuracy: boolean. Whether to display <add> class accuracy in the logs to stdout at each epoch. <add> class_weight: dictionary mapping classes to a weight value, <add> used for scaling the loss function (during training only). <add> sample_weight: list or numpy array with 1:1 mapping to <add> the training samples, used for scaling the loss function <add> (during training only). For time-distributed data, <add> there is one weight per sample *per timestep*, <add> i.e. if your output data is shaped <add> `(nb_samples, timesteps, output_dim)`, <add> your mask should be of shape `(nb_samples, timesteps, 1)`. <add> This allows you to mask out or reweight individual <add> output timesteps, which is useful <add> in sequence to sequence learning. <add> ''' <ide> X = standardize_X(X) <ide> y = standardize_y(y) <ide> <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> sample_weight_val = standardize_weights(y_val, <ide> sample_weight=sample_weight_val) <ide> else: <del> raise Exception("Invalid format for validation data; provide a tuple (X_val, y_val) or (X_val, y_val, sample_weight). \ <del> X_val may be a numpy array or a list of numpy arrays depending on your model input.") <add> raise Exception('Invalid format for validation data; ' <add> 'provide a tuple (X_val, y_val) or ' <add> '(X_val, y_val, sample_weight). ' <add> 'X_val may be a numpy array or a list of ' <add> 'numpy arrays depending on your model input.') <ide> val_ins = X_val + [y_val, sample_weight_val] <ide> <ide> elif 0 < validation_split < 1: <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> y, y_val = (slice_X(y, 0, split_at), slice_X(y, split_at)) <ide> if sample_weight is not None: <ide> sample_weight, sample_weight_val = (slice_X(sample_weight, 0, split_at), slice_X(sample_weight, split_at)) <del> sample_weight_val = standardize_weights(y_val, sample_weight=sample_weight_val) <add> sample_weight_val = standardize_weights(y_val, <add> sample_weight=sample_weight_val) <ide> else: <ide> sample_weight_val = standardize_weights(y_val) <ide> val_ins = X_val + [y_val, sample_weight_val] <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> f = self._train <ide> out_labels = ['loss'] <ide> <del> sample_weight = standardize_weights(y, class_weight=class_weight, sample_weight=sample_weight) <add> sample_weight = standardize_weights(y, class_weight=class_weight, <add> sample_weight=sample_weight) <ide> ins = X + [y, sample_weight] <ide> metrics = ['loss', 'acc', 'val_loss', 'val_acc'] <ide> return self._fit(f, ins, out_labels=out_labels, <ide> def fit(self, X, y, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> shuffle=shuffle, metrics=metrics) <ide> <ide> def predict(self, X, batch_size=128, verbose=0): <add> '''Generate output predictions for the input samples <add> batch by batch. <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> X = standardize_X(X) <ide> return self._predict_loop(self._predict, X, batch_size, verbose)[0] <ide> <ide> def predict_proba(self, X, batch_size=128, verbose=1): <add> '''Generate class probability predictions for the input samples <add> batch by batch. <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 probability predictions. <add> ''' <ide> preds = self.predict(X, batch_size, verbose) <ide> if preds.min() < 0 or preds.max() > 1: <del> warnings.warn("Network returning invalid probability values.") <add> warnings.warn('Network returning invalid probability values.') <ide> return preds <ide> <ide> def predict_classes(self, X, batch_size=128, verbose=1): <add> '''Generate class predictions for the input samples <add> batch by batch. <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 class predictions. <add> ''' <ide> proba = self.predict(X, batch_size=batch_size, verbose=verbose) <del> if self.class_mode == "categorical": <add> if self.class_mode == 'categorical': <ide> return proba.argmax(axis=-1) <ide> else: <ide> return (proba > 0.5).astype('int32') <ide> <ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, <ide> verbose=1, sample_weight=None): <add> '''Compute the loss on some input data, batch by batch. <add> <add> # Arguments <add> X: input data, as a numpy array. <add> y: labels, as a numpy array. <add> batch_size: integer. <add> show_accuracy: boolean. <add> verbose: verbosity mode, 0 or 1. <add> sample_weight: sample weights, as a numpy array. <add> ''' <ide> X = standardize_X(X) <ide> y = standardize_y(y) <ide> sample_weight = standardize_weights(y, sample_weight=sample_weight) <ide> def evaluate(self, X, y, batch_size=128, show_accuracy=False, <ide> else: <ide> return outs[0] <ide> <add> def train_on_batch(self, X, y, accuracy=False, <add> class_weight=None, sample_weight=None): <add> '''Single gradient update over one batch of samples. <add> <add> Returns the loss over the data, <add> or a tuple `(loss, accuracy)` if `accuracy=True`. <add> <add> Arguments: see `fit` method. <add> ''' <add> X = standardize_X(X) <add> y = standardize_y(y) <add> sample_weight = standardize_weights(y, class_weight=class_weight, <add> sample_weight=sample_weight) <add> ins = X + [y, sample_weight] <add> if accuracy: <add> return self._train_with_acc(ins) <add> else: <add> return self._train(ins) <add> <add> def test_on_batch(self, X, y, accuracy=False, sample_weight=None): <add> '''Returns the loss over a single batch of samples, <add> or a tuple `(loss, accuracy)` if `accuracy=True`. <add> <add> Arguments: see `fit` method. <add> ''' <add> X = standardize_X(X) <add> y = standardize_y(y) <add> sample_weight = standardize_weights(y, sample_weight=sample_weight) <add> <add> ins = X + [y, sample_weight] <add> if accuracy: <add> return self._test_with_acc(ins) <add> else: <add> return self._test(ins) <add> <add> def predict_on_batch(self, X): <add> '''Returns predictions for a single batch of samples. <add> ''' <add> ins = standardize_X(X) <add> return self._predict(ins) <add> <ide> def save_weights(self, filepath, overwrite=False): <del> # Save weights from all layers to HDF5 <add> '''Dump all layer weights to a HDF5 file. <add> ''' <ide> import h5py <ide> import os.path <ide> # if file exists and should not be overwritten <ide> def save_weights(self, filepath, overwrite=False): <ide> get_input = input <ide> if sys.version_info[:2] <= (2, 7): <ide> get_input = raw_input <del> overwrite = get_input('[WARNING] %s already exists - overwrite? [y/n]' % (filepath)) <add> overwrite = get_input('[WARNING] %s already exists - overwrite? ' <add> '[y/n]' % (filepath)) <ide> while overwrite not in ['y', 'n']: <ide> overwrite = get_input('Enter "y" (overwrite) or "n" (cancel).') <ide> if overwrite == 'n': <ide> def save_weights(self, filepath, overwrite=False): <ide> g.attrs['nb_params'] = len(weights) <ide> for n, param in enumerate(weights): <ide> param_name = 'param_{}'.format(n) <del> param_dset = g.create_dataset(param_name, param.shape, dtype=param.dtype) <add> param_dset = g.create_dataset(param_name, param.shape, <add> dtype=param.dtype) <ide> param_dset[:] = param <ide> f.flush() <ide> f.close() <ide> <ide> def load_weights(self, filepath): <add> '''Load all layer weights from a HDF5 save file. <ide> ''' <del> This method does not make use of Sequential.set_weights() <del> for backwards compatibility. <del> ''' <del> # Loads weights from HDF5 file <ide> import h5py <ide> f = h5py.File(filepath) <ide> for k in range(f.attrs['nb_layers']): <add> # This method does not make use of Sequential.set_weights() <add> # for backwards compatibility. <ide> g = f['layer_{}'.format(k)] <ide> weights = [g['param_{}'.format(p)] for p in range(g.attrs['nb_params'])] <ide> self.layers[k].set_weights(weights) <ide> f.close() <ide> <ide> <ide> class Graph(Model, containers.Graph): <del> def compile(self, optimizer, loss, theano_mode=None): <del> # loss is a dictionary mapping output name to loss functions <add> '''Arbitrary connection graph. <add> It can have any number of inputs and outputs, <add> with each output trained with its own loss function. <add> The quantity being optimized by a Graph model is <add> the sum of all loss functions over the different outputs. <add> <add> Inherits from `containers.Graph`. <add> ''' <add> def compile(self, optimizer, loss): <add> '''Configure the learning process. <add> <add> # Arguments <add> optimizer: str (name of optimizer) or optimizer object. <add> See [optimizers](optimizers.md). <add> loss: dictionary mapping the name(s) of the output(s) to <add> a loss function (string name of objective function or <add> objective function. See [objectives](objectives.md)). <add> ''' <ide> ys = [] <ide> ys_train = [] <ide> ys_test = [] <ide> def compile(self, optimizer, loss, theano_mode=None): <ide> for r in self.regularizers: <ide> train_loss = r(train_loss) <ide> self.optimizer = optimizers.get(optimizer) <del> updates = self.optimizer.get_updates(self.params, self.constraints, train_loss) <add> updates = self.optimizer.get_updates(self.params, <add> self.constraints, <add> train_loss) <ide> updates += self.updates <del> self.theano_mode = theano_mode <ide> self.loss = loss <ide> <ide> self._train = K.function(train_ins, [train_loss], updates=updates) <ide> self._test = K.function(test_ins, [test_loss]) <del> self._predict = K.function(inputs=ins, outputs=ys_test, updates=self.state_updates) <del> <del> def train_on_batch(self, data, class_weight={}, sample_weight={}): <del> # data is a dictionary mapping output and input names to arrays <del> sample_weight = [standardize_weights(data[name], <del> sample_weight=sample_weight.get(name), <del> class_weight=class_weight.get(name)) for name in self.output_order] <del> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <del> return self._train(ins) <del> <del> def test_on_batch(self, data, sample_weight={}): <del> # data is a dictionary mapping input names to arrays <del> sample_weight = [standardize_weights(data[name], <del> sample_weight=sample_weight.get(name)) for name in self.output_order] <del> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <del> return self._test(ins) <del> <del> def predict_on_batch(self, data): <del> # data is a dictionary mapping input names to arrays <del> ins = [data[name] for name in self.input_order] <del> return self._predict(ins) <add> self._predict = K.function(inputs=ins, outputs=ys_test, <add> updates=self.state_updates) <ide> <ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> validation_split=0., validation_data=None, shuffle=True, <ide> class_weight={}, sample_weight={}): <add> '''Train the model for a fixed number of epochs. <add> <add> Returns a history object. It `history` attribute is a record of <add> training loss values at successive epochs, <add> as well as validation loss values (if applicable). <add> <add> # Arguments <add> data: dictionary mapping input names and outputs names to <add> appropriate numpy arrays. All arrays should contain <add> the same number of samples. <add> batch_size: int. Number of samples per gradient update. <add> nb_epoch: int. <add> verbose: 0 for no logging to stdout, <add> 1 for progress bar logging, 2 for one log line per epoch. <add> callbacks: `keras.callbacks.Callback` list. List of callbacks <add> to apply during training. See [callbacks](callbacks.md). <add> validation_split: float (0. < x < 1). Fraction of the data to <add> use as held-out validation data. <add> validation_data: dictionary mapping input names and outputs names <add> to appropriate numpy arrays to be used as <add> held-out validation data. <add> All arrays should contain the same number of samples. <add> Will override validation_split. <add> shuffle: boolean. Whether to shuffle the samples at each epoch. <add> class_weight: dictionary mapping output names to <add> class weight dictionaries. <add> sample_weight: dictionary mapping output names to <add> numpy arrays of sample weights. <add> ''' <ide> X = [data[name] for name in self.input_order] <ide> y = [standardize_y(data[name]) for name in self.output_order] <ide> <ide> def fit(self, data, batch_size=128, nb_epoch=100, verbose=1, callbacks=[], <ide> sample_weight=sample_weight_list[i], <ide> class_weight=class_weight_list[i]) for i in range(len(self.output_order))] <ide> ins = X + y + sample_weight_list <del> history = self._fit(f, ins, out_labels=out_labels, batch_size=batch_size, nb_epoch=nb_epoch, <add> history = self._fit(f, ins, out_labels=out_labels, <add> batch_size=batch_size, nb_epoch=nb_epoch, <ide> verbose=verbose, callbacks=callbacks, <ide> val_f=val_f, val_ins=val_ins, <ide> shuffle=shuffle, metrics=metrics) <ide> return history <ide> <ide> def evaluate(self, data, batch_size=128, verbose=0, sample_weight={}): <add> '''Compute the loss on some input data, batch by batch. <add> <add> Arguments: see `fit` method. <add> ''' <ide> sample_weight = [standardize_weights(data[name], <ide> sample_weight=sample_weight.get(name)) for name in self.output_order] <ide> <ide> def evaluate(self, data, batch_size=128, verbose=0, sample_weight={}): <ide> return outs[0] <ide> <ide> def predict(self, data, batch_size=128, verbose=0): <add> '''Generate output predictions for the input samples <add> batch by batch. <add> <add> Arguments: see `fit` method. <add> ''' <ide> ins = [data[name] for name in self.input_order] <ide> outs = self._predict_loop(self._predict, ins, batch_size, verbose) <ide> return dict(zip(self.output_order, outs)) <ide> <add> def train_on_batch(self, data, class_weight={}, sample_weight={}): <add> '''Single gradient update on a batch of samples. <add> <add> Arguments: see `fit` method. <add> ''' <add> sample_weight = [standardize_weights(data[name], <add> sample_weight=sample_weight.get(name), <add> class_weight=class_weight.get(name)) for name in self.output_order] <add> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <add> return self._train(ins) <add> <add> def test_on_batch(self, data, sample_weight={}): <add> '''Compute the loss on a single batch of samples. <add> <add> Arguments: see `fit` method. <add> ''' <add> sample_weight = [standardize_weights(data[name], <add> sample_weight=sample_weight.get(name)) for name in self.output_order] <add> ins = [data[name] for name in self.input_order] + [standardize_y(data[name]) for name in self.output_order] + sample_weight <add> return self._test(ins) <add> <add> def predict_on_batch(self, data): <add> '''Generate predictions for a single batch of samples. <add> ''' <add> ins = [data[name] for name in self.input_order] <add> return self._predict(ins) <add> <ide> def save_weights(self, filepath, overwrite=False): <del> # Save weights from all layers to HDF5 <add> '''Save weights from all layers to a HDF5 files. <add> ''' <ide> import h5py <ide> import os.path <ide> # if file exists and should not be overwritten <ide> def save_weights(self, filepath, overwrite=False): <ide> get_input = input <ide> if sys.version_info[:2] <= (2, 7): <ide> get_input = raw_input <del> overwrite = get_input('[WARNING] %s already exists - overwrite? [y/n]' % (filepath)) <add> overwrite = get_input('[WARNING] %s already exists - overwrite? ' <add> '[y/n]' % (filepath)) <ide> while overwrite not in ['y', 'n']: <ide> overwrite = get_input('Enter "y" (overwrite) or "n" (cancel).') <ide> if overwrite == 'n': <ide> def save_weights(self, filepath, overwrite=False): <ide> g.attrs['nb_params'] = len(weights) <ide> for n, param in enumerate(weights): <ide> param_name = 'param_{}'.format(n) <del> param_dset = g.create_dataset(param_name, param.shape, dtype=param.dtype) <add> param_dset = g.create_dataset(param_name, param.shape, <add> dtype=param.dtype) <ide> param_dset[:] = param <ide> f.flush() <ide> f.close() <ide> <ide> def load_weights(self, filepath): <del> # Loads weights from HDF5 file <add> '''Load weights from a HDF5 file. <add> ''' <ide> import h5py <ide> f = h5py.File(filepath) <ide> g = f['graph'] <ide><path>keras/optimizers.py <ide> def kl_divergence(p, p_hat): <ide> <ide> <ide> class Optimizer(object): <add> '''Abstract optimizer base class. <add> <add> Note: this is the parent class of all optimizers, not an actual optimizer <add> that can be used for training models. <add> <add> All Keras optimizers support the following keyword arguments: <add> <add> clipnorm: float >= 0. Gradients will be clipped <add> when their L2 norm exceeds this value. <add> clipvalue: float >= 0. Gradients will be clipped <add> when their absolute value exceeds this value. <add> ''' <ide> def __init__(self, **kwargs): <ide> self.__dict__.update(kwargs) <ide> self.updates = [] <ide> def get_config(self): <ide> <ide> <ide> class SGD(Optimizer): <del> <add> '''Stochastic gradient descent, with support for momentum, <add> decay, and Nesterov momentum. <add> <add> # Arguments <add> lr: float >= 0. Learning rate. <add> momentum: float >= 0. Parameter updates momentum. <add> decay: float >= 0. Learning rate decay over each update. <add> nesterov: boolean. Whether to apply Nesterov momentum. <add> ''' <ide> def __init__(self, lr=0.01, momentum=0., decay=0., nesterov=False, <ide> *args, **kwargs): <ide> super(SGD, self).__init__(**kwargs) <ide> def get_config(self): <ide> <ide> <ide> class RMSprop(Optimizer): <add> '''RMSProp optimizer. <add> <add> It is recommended to leave the parameters of this optimizer <add> at their default values. <add> <add> This optimizer is usually a good choice for recurrent <add> neural networks. <add> <add> # Arguments <add> lr: float >= 0. Learning rate. <add> rho: float >= 0. <add> epsilon: float >= 0. Fuzz factor. <add> ''' <ide> def __init__(self, lr=0.001, rho=0.9, epsilon=1e-6, *args, **kwargs): <ide> super(RMSprop, self).__init__(**kwargs) <ide> self.__dict__.update(locals()) <ide> def get_config(self): <ide> <ide> <ide> class Adagrad(Optimizer): <add> '''Adagrad optimizer. <add> <add> It is recommended to leave the parameters of this optimizer <add> at their default values. <add> <add> # Arguments <add> lr: float >= 0. Learning rate. <add> epsilon: float >= 0. <add> ''' <ide> def __init__(self, lr=0.01, epsilon=1e-6, *args, **kwargs): <ide> super(Adagrad, self).__init__(**kwargs) <ide> self.__dict__.update(locals()) <ide> def get_config(self): <ide> <ide> <ide> class Adadelta(Optimizer): <del> ''' <del> Reference: http://arxiv.org/abs/1212.5701 <add> '''Adadelta optimizer. <add> <add> It is recommended to leave the parameters of this optimizer <add> at their default values. <add> <add> # Arguments <add> lr: float >= 0. Learning rate. It is recommended to leave it at the default value. <add> rho: float >= 0. <add> epsilon: float >= 0. Fuzz factor. <add> <add> # References <add> - [Adadelta - an adaptive learning rate method](http://arxiv.org/abs/1212.5701) <ide> ''' <ide> def __init__(self, lr=1.0, rho=0.95, epsilon=1e-6, *args, **kwargs): <ide> super(Adadelta, self).__init__(**kwargs) <ide> def get_config(self): <ide> <ide> <ide> class Adam(Optimizer): <del> ''' <del> Reference: http://arxiv.org/abs/1412.6980v8 <add> '''Adam optimizer. <add> <add> Default parameters follow those provided in the original paper. <add> <add> # Arguments <add> lr: float >= 0. Learning rate. <add> beta_1/beta_2: floats, 0 < beta < 1. Generally close to 1. <add> epsilon: float >= 0. Fuzz factor. <ide> <del> Default parameters follow those provided in the original paper. <add> # References <add> - [Adam - A Method for Stochastic Optimization](http://arxiv.org/abs/1412.6980v8) <ide> ''' <ide> def __init__(self, lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-8, <ide> *args, **kwargs):
4
Javascript
Javascript
move filter tests to proper location
0ced30e3190b6fe2714d8f01ebf92d7eb48d424b
<ide><path>test/unit/traversing.js <ide> test("is(jQuery)", function() { <ide> ok( !jQuery("#simon").is( jQuery(".blogTest")[0] ), "Check for multiple classes: Expected classes 'blog' and 'link', but not 'blogTest'" ); <ide> }); <ide> <del>test("filter() with positional selectors", function() { <del> expect(19); <del> <del> var html = jQuery('' + <del> '<p id="posp">' + <del> '<a class="firsta" href="#">' + <del> '<em>first</em>' + <del> '</a>' + <del> '<a class="seconda" href="#">' + <del> '<b>test</b>' + <del> '</a>' + <del> '<em></em>' + <del> '</p>').appendTo( "body" ), <del> filterit = function(sel, filter, length) { <del> equal( jQuery( sel ).filter( filter ).length, length, "jQuery( " + sel + " ).filter( " + filter + " )" ); <del> }; <del> <del> filterit( "#posp", "#posp:first", 1); <del> filterit( "#posp", "#posp:eq(2)", 0 ); <del> filterit( "#posp", "#posp a:first", 0 ); <del> <del> // Keep in mind this is within the selection and <del> // not in relation to other elements (.is() is a different story) <del> filterit( "#posp .firsta", "#posp a:first", 1 ); <del> filterit( "#posp .firsta", "#posp a:last", 1 ); <del> filterit( "#posp .firsta", "#posp a:last-child", 0 ); <del> filterit( "#posp .firsta", "#posp a:even", 1 ); <del> filterit( "#posp .firsta", "#posp a:odd", 0 ); <del> filterit( "#posp .firsta", "#posp a:eq(0)", 1 ); <del> filterit( "#posp .firsta", "#posp a:eq(9)", 0 ); <del> filterit( "#posp .firsta", "#posp em:eq(0)", 0 ); <del> filterit( "#posp .firsta", "#posp em:first", 0 ); <del> filterit( "#posp .firsta", "#posp:first", 0 ); <del> <del> filterit( "#posp .seconda", "#posp a:first", 1 ); <del> filterit( "#posp .seconda", "#posp em:first", 0 ); <del> filterit( "#posp .seconda", "#posp a:last", 1 ); <del> filterit( "#posp .seconda", "#posp a:gt(0)", 0 ); <del> filterit( "#posp .seconda", "#posp a:lt(5)", 1 ); <del> filterit( "#posp .seconda", "#posp a:lt(1)", 1 ); <del> html.remove(); <del>}); <del> <ide> test("index()", function() { <ide> expect( 2 ); <ide> <ide> test("filter(jQuery)", function() { <ide> <ide> var elements = jQuery("#text1"); <ide> same( jQuery("#form input").filter(elements).get(), q("text1"), "filter(Element)" ); <del>}) <add>}); <add> <add> <add>test("filter() with positional selectors", function() { <add> expect(19); <add> <add> var html = jQuery('' + <add> '<p id="posp">' + <add> '<a class="firsta" href="#">' + <add> '<em>first</em>' + <add> '</a>' + <add> '<a class="seconda" href="#">' + <add> '<b>test</b>' + <add> '</a>' + <add> '<em></em>' + <add> '</p>').appendTo( "body" ), <add> filterit = function(sel, filter, length) { <add> equal( jQuery( sel ).filter( filter ).length, length, "jQuery( " + sel + " ).filter( " + filter + " )" ); <add> }; <add> <add> filterit( "#posp", "#posp:first", 1); <add> filterit( "#posp", "#posp:eq(2)", 0 ); <add> filterit( "#posp", "#posp a:first", 0 ); <add> <add> // Keep in mind this is within the selection and <add> // not in relation to other elements (.is() is a different story) <add> filterit( "#posp .firsta", "#posp a:first", 1 ); <add> filterit( "#posp .firsta", "#posp a:last", 1 ); <add> filterit( "#posp .firsta", "#posp a:last-child", 0 ); <add> filterit( "#posp .firsta", "#posp a:even", 1 ); <add> filterit( "#posp .firsta", "#posp a:odd", 0 ); <add> filterit( "#posp .firsta", "#posp a:eq(0)", 1 ); <add> filterit( "#posp .firsta", "#posp a:eq(9)", 0 ); <add> filterit( "#posp .firsta", "#posp em:eq(0)", 0 ); <add> filterit( "#posp .firsta", "#posp em:first", 0 ); <add> filterit( "#posp .firsta", "#posp:first", 0 ); <add> <add> filterit( "#posp .seconda", "#posp a:first", 1 ); <add> filterit( "#posp .seconda", "#posp em:first", 0 ); <add> filterit( "#posp .seconda", "#posp a:last", 1 ); <add> filterit( "#posp .seconda", "#posp a:gt(0)", 0 ); <add> filterit( "#posp .seconda", "#posp a:lt(5)", 1 ); <add> filterit( "#posp .seconda", "#posp a:lt(1)", 1 ); <add> html.remove(); <add>}); <ide> <ide> test("closest()", function() { <ide> expect(13);
1
Text
Text
fix typo in stream.md
4d5ae3022c96d6e3f23788fe0ad4cb1333763bcf
<ide><path>doc/api/stream.md <ide> user programs. <ide> <ide> `transform._transform()` is never called in parallel; streams implement a <ide> queue mechanism, and to receive the next chunk, `callback` must be <del>called, either synchronously or asychronously. <add>called, either synchronously or asynchronously. <ide> <ide> #### Class: stream.PassThrough <ide>
1
Javascript
Javascript
add a basic embedded cmap reader
0197697d1f23391360052b74ff555251d48d3f35
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> if (!encoding) <ide> error("Unknown font encoding"); <ide> <del> var firstChar = xref.fetchIfRef(fontDict.get("FirstChar")); <del> <ide> var index = 0; <ide> for (var j = 0; j < encoding.length; j++) { <ide> encodingMap[index++] = GlyphsUnicode[encoding[j]]; <ide> } <ide> <add> var firstChar = xref.fetchIfRef(fontDict.get("FirstChar")); <ide> var widths = xref.fetchIfRef(fontDict.get("Widths")); <ide> assertWellFormed(IsArray(widths) && IsInt(firstChar), <ide> "invalid font Widths or FirstChar"); <ide> var CanvasGraphics = (function() { <ide> } <ide> } <ide> } else if (fontDict.has("ToUnicode")) { <del> TODO("ToUnicode stream translation not implemented"); <del> } <add> var cmapObj = xref.fetchIfRef(fontDict.get("ToUnicode")); <add> if (IsName(cmapObj)) { <add> error("ToUnicode basic cmap translation not implemented"); <add> encodingMap = {}; <add> } else if (IsStream(cmapObj)) { <add> var tokens = []; <add> var token = ""; <add> <add> var cmap = cmapObj.getBytes(cmapObj.length); <add> for (var i =0; i < cmap.length; i++) { <add> var byte = cmap[i]; <add> if (byte == 0x20 || byte == 0x0A || byte == 0x3C || byte == 0x3E) { <add> switch (token) { <add> case "useCMap": <add> error("useCMap is not implemented"); <add> break; <add> <add> case "begincodespacerange": <add> case "beginbfrange": <add> token = ""; <add> tokens = []; <add> break; <add> <add> case "endcodespacerange": <add> TODO("Support CMap ranges"); <add> break; <add> <add> case "endbfrange": <add> for (var j = 0; j < tokens.length; j+=3) { <add> var startRange = parseInt("0x" + tokens[j]); <add> var endRange = parseInt("0x" + tokens[j+1]); <add> var code = parseInt("0x" + tokens[j+2]); <add> <add> for (var k = startRange; k <= endRange; k++) { <add> encodingMap[k] = code; <add> charset.push(code++); <add> } <add> } <add> break; <add> <add> case "beginfbchar": <add> case "endfbchar": <add> error("fbchar parsing is not implemented"); <add> break; <add> <add> default: <add> if (token.length) { <add> tokens.push(token); <add> token = ""; <add> } <add> break; <add> } <add> } else if (byte == 0x5B || byte == 0x5D) { <add> error("CMAP list parsing is not implemented"); <add> } else { <add> token += String.fromCharCode(byte); <add> } <add> } <add> } <add> } <ide> <ide> var subType = fontDict.get("Subtype"); <ide> var bbox = descriptor.get("FontBBox");
1
Javascript
Javascript
use fixture files
22a9e7f50f0c909aee8175d9cb7d04ea2c47bdbc
<ide><path>node-tests/blueprints/instance-initializer-test-test.js <ide> const modifyPackages = blueprintHelpers.modifyPackages; <ide> const chai = require('ember-cli-blueprint-test-helpers/chai'); <ide> const expect = chai.expect; <ide> <add>const fixture = require('../helpers/fixture'); <add> <ide> describe('Blueprint: instance-initializer-test', function() { <ide> setupTestHooks(this); <ide> <ide> describe('Blueprint: instance-initializer-test', function() { <ide> it('instance-initializer-test foo', function() { <ide> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => { <ide> expect(_file('tests/unit/instance-initializers/foo-test.js')) <del> .to.contain("import { initialize } from 'my-app/instance-initializers/foo';") <del> .to.contain("module('Unit | Instance Initializer | foo'") <del> .to.contain("application = Application.create();") <del> .to.contain("this.appInstance = this.application.buildInstance();") <del> .to.contain("initialize(this.appInstance);"); <add> .to.equal(fixture('instance-initializer-test/default.js')); <ide> }); <ide> }); <ide> <ide> describe('Blueprint: instance-initializer-test', function() { <ide> it('instance-initializer-test foo for mocha', function() { <ide> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => { <ide> expect(_file('tests/unit/instance-initializers/foo-test.js')) <del> .to.contain("import { initialize } from 'my-app/instance-initializers/foo';") <del> .to.contain("describe('Unit | Instance Initializer | foo', function() {") <del> .to.contain("application = Application.create();") <del> .to.contain("appInstance = application.buildInstance();") <del> .to.contain("initialize(appInstance);"); <add> .to.equal(fixture('instance-initializer-test/mocha.js')); <ide> }); <ide> }); <ide> }); <ide> describe('Blueprint: instance-initializer-test', function() { <ide> it('instance-initializer-test foo', function() { <ide> return emberGenerateDestroy(['instance-initializer-test', 'foo'], _file => { <ide> expect(_file('tests/unit/instance-initializers/foo-test.js')) <del> .to.contain("import { initialize } from 'dummy/instance-initializers/foo';") <del> .to.contain("module('Unit | Instance Initializer | foo'") <del> .to.contain("application = Application.create();") <del> .to.contain("this.appInstance = this.application.buildInstance();") <del> .to.contain("initialize(this.appInstance);"); <add> .to.equal(fixture('instance-initializer-test/dummy.js')); <ide> }); <ide> }); <ide> }); <ide><path>node-tests/fixtures/instance-initializer-test/default.js <add>import Application from '@ember/application'; <add>import { run } from '@ember/runloop'; <add>import { initialize } from 'my-app/instance-initializers/foo'; <add>import { module, test } from 'qunit'; <add>import destroyApp from '../../helpers/destroy-app'; <add> <add>module('Unit | Instance Initializer | foo', { <add> beforeEach() { <add> run(() => { <add> this.application = Application.create(); <add> this.appInstance = this.application.buildInstance(); <add> }); <add> }, <add> afterEach() { <add> run(this.appInstance, 'destroy'); <add> destroyApp(this.application); <add> } <add>}); <add> <add>// Replace this with your real tests. <add>test('it works', function(assert) { <add> initialize(this.appInstance); <add> <add> // you would normally confirm the results of the initializer here <add> assert.ok(true); <add>}); <ide><path>node-tests/fixtures/instance-initializer-test/dummy.js <add>import Application from '@ember/application'; <add>import { run } from '@ember/runloop'; <add>import { initialize } from 'dummy/instance-initializers/foo'; <add>import { module, test } from 'qunit'; <add>import destroyApp from '../../helpers/destroy-app'; <add> <add>module('Unit | Instance Initializer | foo', { <add> beforeEach() { <add> run(() => { <add> this.application = Application.create(); <add> this.appInstance = this.application.buildInstance(); <add> }); <add> }, <add> afterEach() { <add> run(this.appInstance, 'destroy'); <add> destroyApp(this.application); <add> } <add>}); <add> <add>// Replace this with your real tests. <add>test('it works', function(assert) { <add> initialize(this.appInstance); <add> <add> // you would normally confirm the results of the initializer here <add> assert.ok(true); <add>}); <ide><path>node-tests/fixtures/instance-initializer-test/mocha.js <add>import { expect } from 'chai'; <add>import { describe, it, beforeEach } from 'mocha'; <add>import Application from '@ember/application'; <add>import { run } from '@ember/runloop'; <add>import { initialize } from 'my-app/instance-initializers/foo'; <add>import destroyApp from '../../helpers/destroy-app'; <add> <add>describe('Unit | Instance Initializer | foo', function() { <add> let application, appInstance; <add> <add> beforeEach(function() { <add> run(function() { <add> application = Application.create(); <add> appInstance = application.buildInstance(); <add> }); <add> }); <add> <add> afterEach(function() { <add> run(appInstance, 'destroy'); <add> destroyApp(application); <add> }); <add> <add> // Replace this with your real tests. <add> it('works', function() { <add> initialize(appInstance); <add> <add> // you would normally confirm the results of the initializer here <add> expect(true).to.be.ok; <add> }); <add>});
4
Text
Text
add comments to example in readme
d6086b32202fff584452570967530e6b64fd271b
<ide><path>README.md <ide> has changed. <ide> ```javascript <ide> var map1 = Immutable.Map({a:1, b:2, c:3}); <ide> var map2 = map1.set('b', 2); <del>assert(map1 === map2); <add>assert(map1 === map2); // no change <ide> var map3 = map1.set('b', 50); <del>assert(map1 !== map3); <add>assert(map1 !== map3); // change <ide> ``` <ide> <ide> If an object is immutable, it can be "copied" simply by making another reference
1
Python
Python
add multitask evaluation
bbe3df01844b2e7eab1f9fe0d67fa3572a192b3d
<ide><path>official/modeling/multitask/__init__.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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> <ide><path>official/modeling/multitask/base_model.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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># Lint as: python3 <add># Copyright 2020 The TensorFlow Authors. All Rights Reserved. <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>"""Abstraction of multi-task model.""" <add>from typing import Text, Dict <add> <add>import tensorflow as tf <add> <add> <add>class MultiTaskBaseModel(tf.Module): <add> """Base class that holds multi-task model computation.""" <add> <add> def __init__(self, **kwargs): <add> super().__init__(**kwargs) <add> self._sub_tasks = self._instantiate_sub_tasks() <add> <add> def _instantiate_sub_tasks(self) -> Dict[Text, tf.keras.Model]: <add> """Abstract function that sets up the computation for each sub-task. <add> <add> Returns: <add> A map from task name (as string) to a tf.keras.Model object that <add> represents the sub-task in the multi-task pool. <add> """ <add> raise NotImplementedError( <add> "_instantiate_sub_task_models() is not implemented.") <add> <add> @property <add> def sub_tasks(self): <add> """Fetch a map of task name (string) to task model (tf.keras.Model).""" <add> return self._sub_tasks <add> <add> def initialize(self): <add> """Optional function that loads a pre-train checkpoint.""" <add> return <ide><path>official/modeling/multitask/configs.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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>"""Configuration definitions for multi-task training.""" <add>from typing import Optional, Tuple <add> <add>import dataclasses <add> <add>from official.core import config_definitions as cfg <add>from official.modeling.hyperparams import base_config <add> <add> <add>@dataclasses.dataclass <add>class TaskRoutine(base_config.Config): <add> task_name: str = "" <add> task_config: cfg.TaskConfig = None <add> mixing_steps: int = 1 <add> eval_steps: Optional[int] = None <add> task_weight: Optional[float] = None <add> <add> <add>@dataclasses.dataclass <add>class MultiTaskConfig(base_config.Config): <add> init_checkpoint: str = "" <add> model: base_config.Config = None <add> task_routines: Tuple[TaskRoutine, ...] = () <add> <add> <add>@dataclasses.dataclass <add>class MultiEvalExperimentConfig(base_config.Config): <add> """An experiment config for single-task training and multi-task evaluation. <add> <add> Attributes: <add> task: the single-stream training task. <add> eval_tasks: individual evaluation tasks. <add> trainer: the trainer configuration. <add> runtime: the runtime configuration. <add> """ <add> task: cfg.TaskConfig = cfg.TaskConfig() <add> eval_tasks: MultiTaskConfig = MultiTaskConfig() <add> trainer: cfg.TrainerConfig = cfg.TrainerConfig() <add> runtime: cfg.RuntimeConfig = cfg.RuntimeConfig() <ide><path>official/modeling/multitask/evaluator.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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>"""Multitask Evaluator implementation. <add> <add>The evaluator implements the Orbit `AbstractEvaluator` interface. <add>""" <add>from typing import Optional, Union <add>import gin <add>import orbit <add>import tensorflow as tf <add> <add>from official.modeling.multitask import base_model <add>from official.modeling.multitask import multitask <add> <add> <add>@gin.configurable <add>class MultiTaskEvaluator(orbit.AbstractEvaluator): <add> """Implements the common trainer shared for TensorFlow models.""" <add> <add> def __init__(self, <add> task: multitask.MultiTask, <add> model: Union[tf.keras.Model, base_model.MultiTaskBaseModel], <add> global_step: Optional[tf.Variable] = None): <add> """Initialize common trainer for TensorFlow models. <add> <add> Args: <add> task: A multitask.MultiTask instance. <add> model: tf.keras.Model instance. <add> global_step: the global step variable. <add> """ <add> # Gets the current distribution strategy. If not inside any strategy scope, <add> # it gets a single-replica no-op strategy. <add> self._strategy = tf.distribute.get_strategy() <add> self._task = task <add> self._model = model <add> self._global_step = global_step or orbit.utils.create_global_step() <add> # TODO(hongkuny): Define a more robust way to handle the training/eval <add> # checkpoint loading. <add> if hasattr(self.model, "checkpoint_items"): <add> # Each evaluation task can have different models and load a subset of <add> # components from the training checkpoint. This is assuming the <add> # checkpoint items are able to load the weights of the evaluation model. <add> checkpoint_items = self.model.checkpoint_items <add> else: <add> # This is assuming the evaluation model is exactly the training model. <add> checkpoint_items = dict(model=self.model) <add> self._checkpoint = tf.train.Checkpoint( <add> global_step=self.global_step, <add> **checkpoint_items) <add> <add> self._validation_losses = None <add> self._validation_metrics = None <add> <add> # Builds per-task datasets. <add> self.eval_datasets = {} <add> for name, task in self.task.tasks.items(): <add> self.eval_datasets[name] = orbit.utils.make_distributed_dataset( <add> self.strategy, task.build_inputs, task.task_config.validation_data) <add> <add> # Builds per-task validation loops. <add> def get_function(task_name, task): <add> <add> task_metrics = self.validation_metrics[task_name] <add> task_loss = self.validation_losses[task_name] <add> if isinstance(self.model, base_model.MultiTaskBaseModel): <add> model = self.model.sub_tasks[task_name] <add> else: <add> model = self.model <add> <add> def step_fn(inputs): <add> logs = task.validation_step(inputs, model=model, metrics=task_metrics) <add> task_loss.update_state(logs[task.loss]) <add> return logs <add> <add> @tf.function <add> def eval_step_fn(iterator): <add> distributed_outputs = self.strategy.run(step_fn, args=(next(iterator),)) <add> return tf.nest.map_structure(self.strategy.experimental_local_results, <add> distributed_outputs) <add> <add> return orbit.utils.create_loop_fn(eval_step_fn) <add> <add> self.task_fns = { <add> name: get_function(name, task) <add> for name, task in self.task.tasks.items() <add> } <add> <add> @property <add> def strategy(self): <add> return self._strategy <add> <add> @property <add> def task(self): <add> return self._task <add> <add> @property <add> def model(self): <add> return self._model <add> <add> @property <add> def global_step(self): <add> return self._global_step <add> <add> @property <add> def validation_losses(self): <add> """Accesses the validation loss metric object.""" <add> if self._validation_losses is None: <add> # Builds the per-task metrics and losses. <add> self._validation_losses = {} <add> for name in self.task.tasks: <add> self._validation_losses[name] = tf.keras.metrics.Mean( <add> "validation_loss", dtype=tf.float32) <add> return self._validation_losses <add> <add> @property <add> def validation_metrics(self): <add> """Accesses all validation metric metric objects.""" <add> if self._validation_metrics is None: <add> # Builds the per-task metrics and losses. <add> self._validation_metrics = {} <add> for name, task in self.task.tasks.items(): <add> self._validation_metrics[name] = task.build_metrics(training=False) <add> return self._validation_metrics <add> <add> @property <add> def checkpoint(self): <add> """Accesses the training checkpoint.""" <add> return self._checkpoint <add> <add> def evaluate(self, num_steps: tf.Tensor): <add> """Performs evaluation for each `EvalTask`.""" <add> for metric in self.validation_losses.values(): <add> metric.reset_states() <add> for metrics in self.validation_metrics.values(): <add> for metric in metrics: <add> metric.reset_states() <add> results = {} <add> eval_iters = tf.nest.map_structure(iter, self.eval_datasets) <add> <add> for name, task_eval_loop in self.task_fns.items(): <add> outputs = None <add> eval_iter = eval_iters[name] <add> task = self.task.tasks[name] <add> task_eval_steps = self.task.task_eval_steps(name) or num_steps <add> outputs = task_eval_loop( <add> eval_iter, <add> task_eval_steps, <add> state=outputs, <add> reduce_fn=task.aggregate_logs) <add> task_metrics = self.validation_metrics[name] <add> task_loss = self.validation_losses[name] <add> logs = {} <add> for metric in task_metrics + [task_loss]: <add> logs[metric.name] = metric.result() <add> if outputs: <add> metrics = task.reduce_aggregated_logs(outputs) <add> logs.update(metrics) <add> results[name] = logs <add> return results <ide><path>official/modeling/multitask/evaluator_test.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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>"""Tests for multitask.evaluator.""" <add>from absl.testing import parameterized <add>import numpy as np <add>import tensorflow as tf <add> <add>from tensorflow.python.distribute import combinations <add>from tensorflow.python.distribute import strategy_combinations <add>from official.core import base_task <add>from official.core import config_definitions as cfg <add>from official.modeling.multitask import evaluator <add>from official.modeling.multitask import multitask <add> <add> <add>def all_strategy_combinations(): <add> return combinations.combine( <add> distribution=[ <add> strategy_combinations.default_strategy, <add> strategy_combinations.cloud_tpu_strategy, <add> strategy_combinations.one_device_strategy_gpu, <add> ], <add> mode="eager", <add> ) <add> <add> <add>class MockModel(tf.keras.Model): <add> <add> def __init__(self, *args, **kwargs): <add> super().__init__(*args, **kwargs) <add> self.dense = tf.keras.layers.Dense(1) <add> <add> def call(self, inputs): <add> print(inputs, type(inputs)) <add> if "y" in inputs: <add> self.add_loss(tf.zeros((1,), dtype=tf.float32)) <add> else: <add> self.add_loss(tf.ones((1,), dtype=tf.float32)) <add> return self.dense(inputs["x"]) <add> <add> <add>class MockTask(base_task.Task): <add> """Mock task object for testing.""" <add> <add> def build_metrics(self, training: bool = True): <add> del training <add> return [tf.keras.metrics.Accuracy(name="acc")] <add> <add> def build_inputs(self, params): <add> <add> def generate_data(_): <add> x = tf.zeros(shape=(2,), dtype=tf.float32) <add> label = tf.zeros([1], dtype=tf.int32) <add> if self.name == "bar": <add> return dict(x=x, y=x), label <add> else: <add> return dict(x=x), label <add> <add> dataset = tf.data.Dataset.range(1) <add> dataset = dataset.repeat() <add> dataset = dataset.map( <add> generate_data, num_parallel_calls=tf.data.experimental.AUTOTUNE) <add> return dataset.prefetch(buffer_size=1).batch(2, drop_remainder=True) <add> <add> def validation_step(self, inputs, model: tf.keras.Model, metrics=None): <add> logs = super().validation_step(inputs, model, metrics) <add> logs["counter"] = tf.ones((1,), dtype=tf.float32) <add> return logs <add> <add> def aggregate_logs(self, state, step_outputs): <add> if state is None: <add> state = {} <add> for key, value in step_outputs.items(): <add> if key not in state: <add> state[key] = [] <add> state[key].append( <add> np.concatenate([np.expand_dims(v.numpy(), axis=0) for v in value])) <add> return state <add> <add> def reduce_aggregated_logs(self, aggregated_logs): <add> for k, v in aggregated_logs.items(): <add> aggregated_logs[k] = np.sum(np.stack(v, axis=0)) <add> return aggregated_logs <add> <add> <add>class EvaluatorTest(tf.test.TestCase, parameterized.TestCase): <add> <add> @combinations.generate(all_strategy_combinations()) <add> def test_multitask_evaluator(self, distribution): <add> with distribution.scope(): <add> tasks = [ <add> MockTask(params=cfg.TaskConfig(), name="bar"), <add> MockTask(params=cfg.TaskConfig(), name="foo") <add> ] <add> test_multitask = multitask.MultiTask(tasks=tasks) <add> model = MockModel() <add> test_evaluator = evaluator.MultiTaskEvaluator( <add> task=test_multitask, model=model) <add> results = test_evaluator.evaluate(tf.convert_to_tensor(1, dtype=tf.int32)) <add> self.assertContainsSubset(["validation_loss", "acc"], results["bar"].keys()) <add> self.assertContainsSubset(["validation_loss", "acc"], results["foo"].keys()) <add> self.assertEqual(results["bar"]["validation_loss"], 0.0) <add> self.assertEqual(results["foo"]["validation_loss"], 1.0) <add> <add> @combinations.generate(all_strategy_combinations()) <add> def test_multitask_evaluator_numpy_metrics(self, distribution): <add> with distribution.scope(): <add> tasks = [ <add> MockTask(params=cfg.TaskConfig(), name="bar"), <add> MockTask(params=cfg.TaskConfig(), name="foo") <add> ] <add> test_multitask = multitask.MultiTask(tasks=tasks) <add> model = MockModel() <add> test_evaluator = evaluator.MultiTaskEvaluator( <add> task=test_multitask, model=model) <add> results = test_evaluator.evaluate(tf.convert_to_tensor(5, dtype=tf.int32)) <add> self.assertEqual(results["bar"]["counter"], <add> 5. * distribution.num_replicas_in_sync) <add> self.assertEqual(results["foo"]["counter"], <add> 5. * distribution.num_replicas_in_sync) <add> <add> <add>if __name__ == "__main__": <add> tf.test.main() <ide><path>official/modeling/multitask/multitask.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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>"""Experimental MultiTask base class for multi-task training/evaluation.""" <add>import abc <add>from typing import Dict, List, Optional, Text, Union <add> <add>import tensorflow as tf <add>from official.core import base_task <add>from official.core import config_definitions <add>from official.core import task_factory <add>from official.modeling import optimization <add>from official.modeling import performance <add>from official.modeling.multitask import configs <add> <add>TrainerConfig = config_definitions.TrainerConfig <add>RuntimeConfig = config_definitions.RuntimeConfig <add> <add> <add>class MultiTask(tf.Module, metaclass=abc.ABCMeta): <add> """A multi-task class to manage multiple tasks.""" <add> <add> def __init__(self, <add> tasks: Union[Dict[Text, base_task.Task], List[base_task.Task]], <add> task_mixing_steps: Optional[Dict[str, int]] = None, <add> task_weights: Optional[Dict[str, float]] = None, <add> task_eval_steps: Optional[Dict[str, int]] = None, <add> name: Optional[str] = None): <add> """MultiTask initialization. <add> <add> Args: <add> tasks: a list or a flat dict of Task. <add> task_mixing_steps: a dict of (task, mixing steps). <add> task_weights: a dict of (task, loss weight). <add> task_eval_steps: a dict of (task, eval steps). <add> name: the instance name of a MultiTask object. <add> """ <add> super().__init__(name=name) <add> if isinstance(tasks, list): <add> self._tasks = {} <add> for task in tasks: <add> if task.name in self._tasks: <add> raise ValueError("Duplicated tasks found, task.name is %s" % <add> task.name) <add> self._tasks[task.name] = task <add> elif isinstance(tasks, dict): <add> self._tasks = tasks <add> else: <add> raise ValueError("The tasks argument has an invalid type: %s" % <add> type(tasks)) <add> self._task_eval_steps = task_eval_steps or {} <add> self._task_eval_steps = dict([ <add> (name, self._task_eval_steps.get(name, None)) for name in self.tasks <add> ]) <add> self._task_mixing_steps = task_mixing_steps or {} <add> self._task_mixing_steps = dict([ <add> (name, self._task_mixing_steps.get(name, 1)) for name in self.tasks <add> ]) <add> self._task_weights = task_weights or {} <add> self._task_weights = dict([ <add> (name, self._task_weights.get(name, None)) for name in self.tasks <add> ]) <add> <add> @classmethod <add> def from_config(cls, config: configs.MultiTaskConfig, logging_dir=None): <add> tasks = {} <add> task_eval_steps = {} <add> task_mixing_steps = {} <add> task_weights = {} <add> for task_routine in config.task_routines: <add> task_name = task_routine.task_name <add> tasks[task_name] = task_factory.get_task( <add> task_routine.task_config, logging_dir=logging_dir) <add> task_eval_steps[task_name] = task_routine.eval_steps <add> task_mixing_steps[task_name] = task_routine.mixing_steps <add> task_weights[task_name] = task_routine.task_weight <add> return cls( <add> tasks, <add> task_mixing_steps=task_mixing_steps, <add> task_eval_steps=task_eval_steps, <add> task_weights=task_weights) <add> <add> @property <add> def tasks(self): <add> return self._tasks <add> <add> def task_eval_steps(self, task_name): <add> return self._task_eval_steps[task_name] <add> <add> def task_mixing_steps(self, task_name): <add> return self._task_mixing_steps[task_name] <add> <add> def task_weight(self, task_name): <add> return self._task_weights[task_name] <add> <add> @classmethod <add> def create_optimizer(cls, trainer_config: TrainerConfig, <add> runtime_config: Optional[RuntimeConfig] = None): <add> """Creates an TF optimizer from configurations. <add> <add> Args: <add> trainer_config: the parameters of the trainer. <add> runtime_config: the parameters of the runtime. <add> <add> Returns: <add> A tf.optimizers.Optimizer object. <add> """ <add> opt_factory = optimization.OptimizerFactory(trainer_config.optimizer_config) <add> optimizer = opt_factory.build_optimizer(opt_factory.build_learning_rate()) <add> # Configuring optimizer when loss_scale is set in runtime config. This helps <add> # avoiding overflow/underflow for float16 computations. <add> if runtime_config and runtime_config.loss_scale: <add> optimizer = performance.configure_optimizer( <add> optimizer, <add> use_float16=runtime_config.mixed_precision_dtype == "float16", <add> loss_scale=runtime_config.loss_scale) <add> <add> return optimizer <add> <add> def joint_train_step(self, task_inputs, multi_task_model, optimizer, <add> task_metrics): <add> """The joint train step. <add> <add> Args: <add> task_inputs: a dictionary of task names and per-task features. <add> multi_task_model: a MultiTaskModel instance. <add> optimizer: a tf.optimizers.Optimizer. <add> task_metrics: a dictionary of task names and per-task metrics. <add> Returns: <add> A dictionary of losses, inculding per-task losses and their weighted sum. <add> """ <add> losses = {} <add> with tf.GradientTape() as tape: <add> total_loss = 0.0 <add> for name, model in multi_task_model.sub_tasks.items(): <add> inputs = task_inputs[name] <add> if isinstance(inputs, tuple) and len(inputs) == 2: <add> features, labels = inputs <add> elif isinstance(inputs, dict): <add> features, labels = inputs, inputs <add> else: <add> raise ValueError("The iterator output is neither a tuple nor a " <add> "dictionary. It is not implemented to support " <add> "such outputs.") <add> outputs = model(features, training=True) <add> task_loss = self.tasks[name].build_losses(labels, outputs) <add> task_weight = self.task_weight(name) <add> total_loss += task_weight * task_loss <add> losses[name] = task_loss <add> self.tasks[name].process_metrics(task_metrics[name], labels, outputs) <add> <add> # Scales loss as the default gradients allreduce performs sum inside <add> # the optimizer. <add> scaled_loss = total_loss / tf.distribute.get_strategy( <add> ).num_replicas_in_sync <add> tvars = multi_task_model.trainable_variables <add> grads = tape.gradient(scaled_loss, tvars) <add> optimizer.apply_gradients(list(zip(grads, tvars))) <add> losses["total_loss"] = total_loss <add> return losses <ide><path>official/modeling/multitask/train_lib.py <add># Copyright 2021 The TensorFlow Authors. All Rights Reserved. <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>"""Multitask training driver library.""" <add># pytype: disable=attribute-error <add>import os <add>from absl import logging <add>import orbit <add>import tensorflow as tf <add>from official.core import base_task <add>from official.core import base_trainer as core_lib <add>from official.modeling.multitask import configs <add>from official.modeling.multitask import evaluator as evaluator_lib <add>from official.modeling.multitask import multitask <add> <add> <add>def run_experiment_wtih_multitask_eval( <add> *, <add> distribution_strategy: tf.distribute.Strategy, train_task: base_task.Task, <add> eval_tasks: multitask.MultiTask, mode: str, <add> params: configs.MultiEvalExperimentConfig, <add> model_dir: str) -> tf.keras.Model: <add> """Runs train/eval configured by the experiment params. <add> <add> Args: <add> distribution_strategy: A distribution distribution_strategy. <add> train_task: A base_task.Task instance. <add> eval_tasks: A multitask.MultiTask with evaluation tasks. <add> mode: A 'str', specifying the mode. Can be 'train', 'eval', 'train_and_eval' <add> or 'continuous_eval'. <add> params: MultiEvalExperimentConfig instance. <add> model_dir: A 'str', a path to store model checkpoints and summaries. <add> <add> Returns: <add> model: `tf.keras.Model` instance. <add> """ <add> <add> is_training = 'train' in mode <add> is_eval = 'eval' in mode <add> with distribution_strategy.scope(): <add> optimizer = train_task.create_optimizer(params.trainer, params.runtime) <add> model = train_task.build_model() <add> if is_training: <add> trainer = core_lib.Trainer( <add> config=params, <add> task=train_task, <add> model=model, <add> optimizer=optimizer, <add> train=True, <add> evaluate=False) <add> else: <add> trainer = None <add> if is_eval: <add> evaluator = evaluator_lib.MultiTaskEvaluator( <add> task=eval_tasks, <add> model=model, <add> global_step=trainer.global_step if is_training else None) <add> else: <add> evaluator = None <add> <add> if trainer: <add> checkpoint = trainer.checkpoint <add> global_step = trainer.global_step <add> else: <add> checkpoint = evaluator.checkpoint <add> global_step = evaluator.global_step <add> <add> checkpoint_manager = tf.train.CheckpointManager( <add> checkpoint, <add> directory=model_dir, <add> max_to_keep=params.trainer.max_to_keep, <add> step_counter=global_step, <add> checkpoint_interval=params.trainer.checkpoint_interval, <add> init_fn=trainer.initialize if trainer else None) <add> <add> controller = orbit.Controller( <add> strategy=distribution_strategy, <add> trainer=trainer, <add> evaluator=evaluator, <add> global_step=global_step, <add> steps_per_loop=params.trainer.steps_per_loop, <add> checkpoint_manager=checkpoint_manager, <add> summary_dir=os.path.join(model_dir, 'train'), <add> eval_summary_dir=os.path.join(model_dir, 'validation'), <add> summary_interval=params.trainer.summary_interval) <add> <add> logging.info('Starts to execute mode: %s', mode) <add> with distribution_strategy.scope(): <add> if mode == 'train': <add> controller.train(steps=params.trainer.train_steps) <add> elif mode == 'train_and_eval': <add> controller.train_and_evaluate( <add> train_steps=params.trainer.train_steps, <add> eval_steps=params.trainer.validation_steps, <add> eval_interval=params.trainer.validation_interval) <add> elif mode == 'eval': <add> controller.evaluate(steps=params.trainer.validation_steps) <add> elif mode == 'continuous_eval': <add> <add> def timeout_fn(): <add> if evaluator.global_step.numpy() >= params.trainer.train_steps: <add> return True <add> return False <add> <add> controller.evaluate_continuously( <add> steps=params.trainer.validation_steps, <add> timeout=params.trainer.continuous_eval_timeout, <add> timeout_fn=timeout_fn) <add> else: <add> raise NotImplementedError('The mode is not implemented: %s' % mode) <add> <add> return model
7
Text
Text
update example of nested data
e6308155dd01a5ac51d2c6b7266db04c244c7976
<ide><path>docs/topics/writable-nested-serializers.md <ide> Some example output from our serializer. <ide> <ide> { <ide> 'title': 'Leaving party preperations', <del> 'items': { <add> 'items': [ <ide> {'text': 'Compile playlist', 'is_completed': True}, <ide> {'text': 'Send invites', 'is_completed': False}, <ide> {'text': 'Clean house', 'is_completed': False} <del> } <add> ] <ide> } <ide> <ide> Let's take a look at updating our nested one-to-many data structure.
1
Go
Go
remove unused stuff
59648fc1e9d99cae7f4c5f692fe25a73d0651a71
<ide><path>builder/dockerfile/internals_unix.go <del>// +build !windows <del> <del>package dockerfile <del> <del>import ( <del> "os" <del> "path/filepath" <del>) <del> <del>func fixPermissions(source, destination string, uid, gid int, destExisted bool) error { <del> // If the destination didn't already exist, or the destination isn't a <del> // directory, then we should Lchown the destination. Otherwise, we shouldn't <del> // Lchown the destination. <del> destStat, err := os.Stat(destination) <del> if err != nil { <del> // This should *never* be reached, because the destination must've already <del> // been created while untar-ing the context. <del> return err <del> } <del> doChownDestination := !destExisted || !destStat.IsDir() <del> <del> // We Walk on the source rather than on the destination because we don't <del> // want to change permissions on things we haven't created or modified. <del> return filepath.Walk(source, func(fullpath string, info os.FileInfo, err error) error { <del> // Do not alter the walk root iff. it existed before, as it doesn't fall under <del> // the domain of "things we should chown". <del> if !doChownDestination && (source == fullpath) { <del> return nil <del> } <del> <del> // Path is prefixed by source: substitute with destination instead. <del> cleaned, err := filepath.Rel(source, fullpath) <del> if err != nil { <del> return err <del> } <del> <del> fullpath = filepath.Join(destination, cleaned) <del> return os.Lchown(fullpath, uid, gid) <del> }) <del>} <ide><path>builder/dockerfile/internals_windows.go <del>// +build windows <del> <del>package dockerfile <del> <del>func fixPermissions(source, destination string, uid, gid int, destExisted bool) error { <del> // chown is not supported on Windows <del> return nil <del>} <ide><path>container/container.go <ide> func (container *Container) ConfigPath() (string, error) { <ide> return container.GetRootResourcePath(configFileName) <ide> } <ide> <del>// Returns true if the container exposes a certain port <del>func (container *Container) exposes(p nat.Port) bool { <del> _, exists := container.Config.ExposedPorts[p] <del> return exists <del>} <del> <ide> // StartLogger starts a new logger driver for the container. <ide> func (container *Container) StartLogger(cfg containertypes.LogConfig) (logger.Logger, error) { <ide> c, err := logger.GetLogDriver(cfg.Type) <ide><path>layer/filestore_test.go <ide> func assertNotDirectoryError(t *testing.T, err error) { <ide> } <ide> } <ide> <del>func assertPermissionError(t *testing.T, err error) { <del> perr, ok := err.(*os.PathError) <del> if !ok { <del> t.Fatalf("Unexpected error %#v, expected path error", err) <del> } <del> <del> if perr.Err != syscall.EACCES { <del> t.Fatalf("Unexpected error %s, expected %s", perr.Err, syscall.EACCES) <del> } <del>} <del> <ide> func TestCommitFailure(t *testing.T) { <ide> fms, td, cleanup := newFileMetadataStore(t) <ide> defer cleanup()
4
Python
Python
fix minor bug in ncf data creation cleanup code
d6117ed15d8529b2ef20ac295f06b75eb24a7b4d
<ide><path>official/recommendation/data_pipeline.py <ide> def __init__( <ide> self._shuffle_with_forkpool = not stream_files <ide> if stream_files: <ide> self._shard_root = epoch_dir or tempfile.mkdtemp(prefix="ncf_") <del> atexit.register(tf.io.gfile.rmtree, dirname=self._shard_root) <add> atexit.register(tf.io.gfile.rmtree, self._shard_root) <ide> else: <ide> self._shard_root = None <ide>
1
Text
Text
add links to selector articles
52616477d39b2761681badf751ee139c193946a8
<ide><path>docs/faq/CodeStructure.md <ide> While it ultimately doesn't matter how you lay out your code on disk, it's impor <ide> - [A Better File Structure for React/Redux Applications](http://marmelab.com/blog/2015/12/17/react-directory-structure.html) <ide> - [Organizing Large React Applications](http://engineering.kapost.com/2016/01/organizing-large-react-applications/) <ide> - [Four Strategies for Organizing Code](https://medium.com/@msandin/strategies-for-organizing-code-2c9d690b6f33) <add>- [Encapsulating the Redux State Tree](http://randycoulman.com/blog/2016/09/13/encapsulating-the-redux-state-tree/) <add>- [Redux Reducer/Selector Asymmetry](http://randycoulman.com/blog/2016/09/20/redux-reducer-selector-asymmetry/) <add>- [Modular Reducers and Selectors](http://randycoulman.com/blog/2016/09/27/modular-reducers-and-selectors/) <ide> - [React/Redux Links: Architecture - Project File Structure](https://github.com/markerikson/react-redux-links/blob/master/react-redux-architecture.md#project-file-structure) <ide> <ide> **Discussions** <ide><path>docs/faq/Performance.md <ide> As for architecture, anecdotal evidence is that Redux works well for varying pro <ide> - [How to Scale React Applications](https://www.smashingmagazine.com/2016/09/how-to-scale-react-applications/) (accompanying talk: [Scaling React Applications](https://vimeo.com/168648012)) <ide> - [High-Performance Redux](http://somebody32.github.io/high-performance-redux/) <ide> - [Improving React and Redux Perf with Reselect](http://blog.rangle.io/react-and-redux-performance-with-reselect/) <add>- [Encapsulating the Redux State Tree](http://randycoulman.com/blog/2016/09/13/encapsulating-the-redux-state-tree/) <ide> - [React/Redux Links: Performance - Redux](https://github.com/markerikson/react-redux-links/blob/master/react-performance.md#redux-performance) <ide> <ide> **Discussions** <ide><path>docs/faq/ReactRedux.md <ide> For non-connected components, you may want to check what props are being passed <ide> - [A Deep Dive into React Perf Debugging](http://benchling.engineering/deep-dive-react-perf-debugging/) <ide> - [React.js pure render performance anti-pattern](https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f) <ide> - [Improving React and Redux Performance with Reselect](http://blog.rangle.io/react-and-redux-performance-with-reselect/) <add>- [Encapsulating the Redux State Tree](http://randycoulman.com/blog/2016/09/13/encapsulating-the-redux-state-tree/) <ide> - [React/Redux Links: React/Redux Performance](https://github.com/markerikson/react-redux-links/blob/master/react-performance.md) <ide> <ide> **Discussions**
3
Text
Text
fix typos, consistent styling w/ english version
914e7a4fe471ec884be9245d8a1033b9428dca8c
<ide><path>curriculum/challenges/spanish/01-responsive-web-design/applied-accessibility/wrap-radio-buttons-in-a-fieldset-element-for-better-accessibility.spanish.md <ide> id: 587d778b367417b2b2512aa7 <ide> title: Wrap Radio Buttons in a fieldset Element for Better Accessibility <ide> challengeType: 0 <ide> videoUrl: '' <del>localeTitle: Agrupe los botones de radio en un elemento fieldset para una mejor accesibilidad <add>localeTitle: Envolver los botones de radio en un elemento fieldset para mejorar la accesibilidad <ide> --- <ide> <ide> ## Description <del><section id="description"> El siguiente tema de formulario cubre la accesibilidad de los botones de radio. A cada opción se le asigna un <code>label</code> con un atributo <code>for</code> vinculado con el <code>id</code> del elemento correspondiente, tal como se describe en el último desafío. Dado que los botones de radio a menudo vienen en un grupo del cuál el usuario debe elegir uno, hay una manera de mostrar semánticamente que las opciones son parte de un conjunto. La etiqueta <code>fieldset</code> rodea todo el grupo de botones de radio para lograrlo. A menudo utiliza una etiqueta de <code>legend</code> para proporcionar una descripción de la agrupación, que los lectores de pantalla leen para cada opción en el elemento <code>fieldset</code> . El <code>fieldset</code> y la etiqueta de <code>legend</code> no son necesarios cuando las opciones se explican por sí mismas, como una selección de género. Usando un <code>label</code> con el atributo <code>for</code> para cada botón de radio es suficiente. <del> <del><br>Aquí hay un ejemplo: <blockquote> &lt;form&gt; <br> &lt;fieldset&gt; <br> &lt;legend&gt; Elija uno de estos tres elementos: &lt;/legend&gt; <br> &lt;input id = &quot;one&quot; type = &quot;radio&quot; name = &quot;items&quot; value = &quot;one&quot;&gt; <br> &lt;label for = &quot;one&quot;&gt; Choice One &lt;/label&gt; &lt;br&gt; <br> &lt;input id = &quot;two&quot; type = &quot;radio&quot; name = &quot;items&quot; value = &quot;two&quot;&gt; <br> &lt;label for = &quot;two&quot;&gt; Choice Two &lt;/label&gt; &lt;br&gt; <br> &lt;input id = &quot;three&quot; type = &quot;radio&quot; name = &quot;items&quot; value = &quot;three&quot;&gt; <br> &lt;label for = &quot;three&quot;&gt; Choice Three &lt;/label&gt; <br> &lt;/fieldset&gt; <br> &lt;/form&gt; <br></blockquote></section> <add><section id="description"> <add>El siguiente tema sobre formularios trata la accesibilidad de los botones de radio. A cada opción se le asigna un <code>label</code> con un atributo <code>for</code> vinculado con el <code>id</code> del elemento correspondiente, tal como se describe en el último desafío. Dado que los botones de radio a menudo vienen en un grupo en que el usuario debe elegir uno, hay una manera de mostrar semánticamente que las opciones son parte de un conjunto. <add>La etiqueta <code>fieldset</code> rodea todo el grupo de botones de radio para lograrlo. A menudo utiliza una etiqueta de <code>legend</code> para proporcionar una descripción de la agrupación, que los lectores de pantalla leen para cada opción en el elemento <code>fieldset</code>. El <code>fieldset</code> y la etiqueta de <code>legend</code> no son necesarios cuando las opciones se explican por sí mismas, como una selección de género. Usando un <code>label</code> con el atributo <code>for</code> para cada botón de radio es suficiente. <add>Aquí hay un ejemplo: <add><blockquote> &lt;form&gt; <br> &lt;fieldset&gt; <br> &lt;legend&gt; Elija uno de estos tres elementos: &lt;/legend&gt; <br> &lt;input id = &quot;one&quot; type = &quot;radio&quot; name = &quot;items&quot; value = &quot;one&quot;&gt; <br> &lt;label for = &quot;one&quot;&gt; Opción Uno &lt;/label&gt; &lt;br&gt; <br> &lt;input id = &quot;two&quot; type = &quot;radio&quot; name = &quot;items&quot; value = &quot;two&quot;&gt; <br> &lt;label for = &quot;two&quot;&gt; Opción Dos &lt;/label&gt; &lt;br&gt; <br> &lt;input id = &quot;three&quot; type = &quot;radio&quot; name = &quot;items&quot; value = &quot;three&quot;&gt; <br> &lt;label for = &quot;three&quot;&gt; Opción Tres &lt;/label&gt; <br> &lt;/fieldset&gt; <br> &lt;/form&gt; <br></blockquote> <add></section> <ide> <ide> ## Instructions <del><section id="instructions"> Camper Cat desea información sobre el nivel de ninja de sus usuarios cuando se registran en su lista de correo electrónico. Él ha añadido un conjunto de botones de radio y aprendió de nuestra lección anterior a utilizar etiquetas con el atributo <code>for</code> para cada elección. ¡Vamos gato campista! Sin embargo, su código todavía necesita ayuda. Cambie la etiqueta <code>div</code> que rodea a los botones de radio por una etiqueta <code>fieldset</code> y cambie la etiqueta <code>p</code> dentro de una <code>legend</code> . </section> <add><section id="instructions"> <add>Camper Cat quiere información sobre el nivel ninja de sus usuarios cuando se registran en su lista de correo electrónico. Él ha añadido un conjunto de botones de radio y aprendió a utilizar etiquetas con el atributo <code>for</code> de nuestra lección anterior para cada opción. ¡Sigue así, Camper Cat! Sin embargo, su código todavía necesita algo de ayuda. Cambia la etiqueta <code>div</code> que rodea a los botones de radio por una etiqueta <code>fieldset</code> y cambia la etiqueta <code>p</code> que está dentro a <code>legend</code>. <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> localeTitle: Agrupe los botones de radio en un elemento fieldset para una mejor <ide> tests: <ide> - text: Tu código debe tener una etiqueta <code>fieldset</code> en todo el grupo de botones de radio. <ide> testString: 'assert($("fieldset").length == 1, "Your code should have a <code>fieldset</code> tag around the radio button set.");' <del> - text: Asegúrese de que su elemento <code>fieldset</code> tenga una etiqueta de cierre. <add> - text: Asegúrate de que tu elemento <code>fieldset</code> tenga una etiqueta de cierre. <ide> testString: 'assert(code.match(/<\/fieldset>/g) && code.match(/<\/fieldset>/g).length === code.match(/<fieldset>/g).length, "Make sure your <code>fieldset</code> element has a closing tag.");' <del> - text: Tu código debe tener una etiqueta de <code>legend</code> alrededor del texto que pregunta qué nivel de ninja es un usuario. <add> - text: Tu código debe tener una etiqueta de <code>legend</code> alrededor del texto que pregunta qué nivel ninja es un usuario. <ide> testString: 'assert($("legend").length == 1, "Your code should have a <code>legend</code> tag around the text asking what level ninja a user is.");' <ide> - text: Tu código no debe tener ninguna etiqueta <code>div</code> . <ide> testString: 'assert($("div").length == 0, "Your code should not have any <code>div</code> tags.");'
1
PHP
PHP
apply fixes from styleci
458e66e7e5e659f6a27aec7c907be97946a11679
<ide><path>tests/Database/DatabaseConnectionFactoryTest.php <ide> use ReflectionProperty; <ide> use InvalidArgumentException; <ide> use PHPUnit\Framework\TestCase; <del>use Illuminate\Database\Connection; <ide> use Illuminate\Database\Capsule\Manager as DB; <ide> use Illuminate\Database\Connectors\ConnectionFactory; <ide>
1
Text
Text
fix captioning example in docs
eb8b40cccdfff5e9782c33192ac021f5e7c9bc78
<ide><path>docs/templates/examples.md <ide> image_model.add(RepeatVector(max_caption_len)) <ide> <ide> # the output of both models will be tensors of shape (samples, max_caption_len, 128). <ide> # let's concatenate these 2 vector sequences. <del>model = Merge([image_model, language_model], mode='concat', concat_axis=-1) <add>model = Sequential() <add>model.add(Merge([image_model, language_model], mode='concat', concat_axis=-1)) <ide> # let's encode this vector sequence into a single vector <del>model.add(GRU(256, 256, return_sequences=False)) <add>model.add(GRU(256, return_sequences=False)) <ide> # which will be used to compute a probability <ide> # distribution over what the next word in the caption should be! <ide> model.add(Dense(vocab_size))
1
Javascript
Javascript
replace fixturedir with fixtures module
56c0e7d10f32b6a7e6010cf38d164e2fbabe93f7
<ide><path>test/parallel/test-http2-respond-file-push.js <ide> const common = require('../common'); <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <add> <add>const fixtures = require('../common/fixtures'); <add> <ide> const http2 = require('http2'); <ide> const assert = require('assert'); <del>const path = require('path'); <ide> const fs = require('fs'); <ide> <ide> const { <ide> const { <ide> HTTP2_HEADER_LAST_MODIFIED <ide> } = http2.constants; <ide> <del>const fname = path.resolve(common.fixturesDir, 'elipses.txt'); <add>const fname = fixtures.path('elipses.txt'); <ide> const data = fs.readFileSync(fname); <ide> const stat = fs.statSync(fname); <ide> const fd = fs.openSync(fname, 'r');
1
Mixed
Java
add flag to enable lazy view managers
1296cb29ebf4e47333047897051bf084cf158e22
<ide><path>Libraries/Utilities/UIManager.js <ide> if (Platform.OS === 'ios') { <ide> }); <ide> } <ide> }); <add>} else if (Platform.OS === 'android' && UIManager.AndroidLazyViewManagersEnabled) { <add> // TODO fill this out <ide> } <ide> <ide> module.exports = UIManager; <ide><path>ReactAndroid/src/main/java/com/facebook/react/CoreModulesPackage.java <ide> private final UIImplementationProvider mUIImplementationProvider; <ide> <ide> CoreModulesPackage( <del> ReactInstanceManager reactInstanceManager, <del> DefaultHardwareBackBtnHandler hardwareBackBtnHandler, <del> UIImplementationProvider uiImplementationProvider) { <add> ReactInstanceManager reactInstanceManager, <add> DefaultHardwareBackBtnHandler hardwareBackBtnHandler, <add> UIImplementationProvider uiImplementationProvider) { <ide> mReactInstanceManager = reactInstanceManager; <ide> mHardwareBackBtnHandler = hardwareBackBtnHandler; <ide> mUIImplementationProvider = uiImplementationProvider; <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public static class Builder { <ide> protected @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler; <ide> protected @Nullable RedBoxHandler mRedBoxHandler; <ide> protected boolean mLazyNativeModulesEnabled; <add> protected boolean mLazyViewManagersEnabled; <ide> <ide> protected Builder() { <ide> } <ide> public Builder setLazyNativeModulesEnabled(boolean lazyNativeModulesEnabled) { <ide> return this; <ide> } <ide> <add> public Builder setLazyViewManagersEnabled(boolean lazyViewManagersEnabled) { <add> mLazyViewManagersEnabled = lazyViewManagersEnabled; <add> return this; <add> } <add> <ide> /** <ide> * Instantiates a new {@link ReactInstanceManagerImpl}. <ide> * Before calling {@code build}, the following must be called: <ide> public ReactInstanceManager build() { <ide> mNativeModuleCallExceptionHandler, <ide> mJSCConfig, <ide> mRedBoxHandler, <del> mLazyNativeModulesEnabled); <add> mLazyNativeModulesEnabled, <add> mLazyViewManagersEnabled); <ide> } <ide> } <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/XReactInstanceManagerImpl.java <ide> import static com.facebook.react.bridge.ReactMarkerConstants.CREATE_VIEW_MANAGERS_START; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_PACKAGES_END; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.PROCESS_PACKAGES_START; <del>import static com.facebook.react.bridge.ReactMarkerConstants.RUN_JS_BUNDLE_END; <del>import static com.facebook.react.bridge.ReactMarkerConstants.RUN_JS_BUNDLE_START; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_END; <ide> import static com.facebook.react.bridge.ReactMarkerConstants.SETUP_REACT_CONTEXT_START; <ide> import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; <ide> private final @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler; <ide> private final JSCConfig mJSCConfig; <ide> private final boolean mLazyNativeModulesEnabled; <add> private final boolean mLazyViewManagersEnabled; <ide> <ide> private final ReactInstanceDevCommandsHandler mDevInterface = <ide> new ReactInstanceDevCommandsHandler() { <ide> public T get() throws Exception { <ide> NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler, <ide> JSCConfig jscConfig, <ide> @Nullable RedBoxHandler redBoxHandler, <del> boolean lazyNativeModulesEnabled) { <add> boolean lazyNativeModulesEnabled, <add> boolean lazyViewManagersEnabled) { <ide> <ide> initializeSoLoaderIfNecessary(applicationContext); <ide> <ide> public T get() throws Exception { <ide> mNativeModuleCallExceptionHandler = nativeModuleCallExceptionHandler; <ide> mJSCConfig = jscConfig; <ide> mLazyNativeModulesEnabled = lazyNativeModulesEnabled; <add> mLazyViewManagersEnabled = lazyViewManagersEnabled; <ide> } <ide> <ide> @Override <ide> private ReactApplicationContext createReactContext( <ide> "createAndProcessCoreModulesPackage"); <ide> try { <ide> CoreModulesPackage coreModulesPackage = <del> new CoreModulesPackage(this, mBackBtnHandler, mUIImplementationProvider); <add> new CoreModulesPackage(this, mBackBtnHandler, mUIImplementationProvider); <ide> processPackage( <ide> coreModulesPackage, <ide> reactContext,
4
PHP
PHP
use string concat instead of double quotes
89a72113cfbd8b3b031ab38bb62afe6fbf276b46
<ide><path>src/Controller/Component/FlashComponent.php <ide> public function set($message, array $options = []) { <ide> $message = $message->getMessage(); <ide> } <ide> <del> $this->_session->write("Flash.{$opts['key']}", [ <add> $this->_session->write('Flash.' . $opts['key'], [ <ide> 'message' => $message, <ide> 'key' => $opts['key'], <ide> 'element' => $opts['element'],
1
PHP
PHP
replace deprecated methods
b5bd087bc5c8fc8ca635ffb2b54cb6bbdc86dd47
<ide><path>lib/Cake/Test/Case/Model/Behavior/ContainableBehaviorTest.php <ide> public function setUp() { <ide> 'hasAndBelongsToMany' => array('Article') <ide> ), false); <ide> <del> $this->User->Behaviors->attach('Containable'); <del> $this->Article->Behaviors->attach('Containable'); <del> $this->Tag->Behaviors->attach('Containable'); <add> $this->User->Behaviors->load('Containable'); <add> $this->Article->Behaviors->load('Containable'); <add> $this->Tag->Behaviors->load('Containable'); <ide> } <ide> <ide> /** <ide> public function testInvalidContainments() { <ide> * @return void <ide> */ <ide> public function testInvalidContainmentsNoNotices() { <del> $this->Article->Behaviors->attach('Containable', array('notices' => false)); <add> $this->Article->Behaviors->load('Containable', array('notices' => false)); <ide> $this->_containments($this->Article, array('Comment', 'InvalidBinding')); <ide> } <ide> <ide> public function testOtherFinds() { <ide> * @return void <ide> */ <ide> public function testOriginalAssociations() { <del> $this->Article->Comment->Behaviors->attach('Containable'); <add> $this->Article->Comment->Behaviors->load('Containable'); <ide> <ide> $options = array( <ide> 'conditions' => array( <ide> public function testResetAddedAssociation() { <ide> $this->JoinB = ClassRegistry::init('JoinB'); <ide> $this->JoinC = ClassRegistry::init('JoinC'); <ide> <del> $this->JoinA->Behaviors->attach('Containable'); <del> $this->JoinB->Behaviors->attach('Containable'); <del> $this->JoinC->Behaviors->attach('Containable'); <add> $this->JoinA->Behaviors->load('Containable'); <add> $this->JoinB->Behaviors->load('Containable'); <add> $this->JoinC->Behaviors->load('Containable'); <ide> <ide> $this->JoinA->JoinB->find('all', array('contain' => array('JoinA'))); <ide> $this->JoinA->bindModel(array('hasOne' => array('JoinAsJoinC' => array('joinTable' => 'as_cs'))), false); <ide> public function testResetAddedAssociation() { <ide> * <ide> */ <ide> public function testResetAssociation() { <del> $this->Article->Behaviors->attach('Containable'); <del> $this->Article->Comment->Behaviors->attach('Containable'); <del> $this->Article->User->Behaviors->attach('Containable'); <add> $this->Article->Behaviors->load('Containable'); <add> $this->Article->Comment->Behaviors->load('Containable'); <add> $this->Article->User->Behaviors->load('Containable'); <ide> <ide> $initialOptions = array( <ide> 'conditions' => array( <ide><path>lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php <ide> public function testTranslateModel() { <ide> $this->loadFixtures('TranslateTable', 'Tag', 'TranslatedItem', 'Translate', 'User', 'TranslatedArticle', 'TranslateArticle'); <ide> $TestModel = new Tag(); <ide> $TestModel->translateTable = 'another_i18n'; <del> $TestModel->Behaviors->attach('Translate', array('title')); <add> $TestModel->Behaviors->load('Translate', array('title')); <ide> $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); <ide> $this->assertEquals('I18nModel', $translateModel->name); <ide> $this->assertEquals('another_i18n', $translateModel->useTable); <ide> <ide> $TestModel = new User(); <del> $TestModel->Behaviors->attach('Translate', array('title')); <add> $TestModel->Behaviors->load('Translate', array('title')); <ide> $translateModel = $TestModel->Behaviors->Translate->translateModel($TestModel); <ide> $this->assertEquals('I18nModel', $translateModel->name); <ide> $this->assertEquals('i18n', $translateModel->useTable); <ide> public function testAttachDetach() { <ide> $expected = array('Title', 'Content'); <ide> $this->assertEquals($expected, $result); <ide> <del> $TestModel->Behaviors->detach('Translate'); <add> $TestModel->Behaviors->unload('Translate'); <ide> $result = array_keys($TestModel->hasMany); <ide> $expected = array(); <ide> $this->assertEquals($expected, $result); <ide> public function testAttachDetach() { <ide> $result = isset($Behavior->runtime[$TestModel->alias]); <ide> $this->assertFalse($result); <ide> <del> $TestModel->Behaviors->attach('Translate', array('title' => 'Title', 'content' => 'Content')); <add> $TestModel->Behaviors->load('Translate', array('title' => 'Title', 'content' => 'Content')); <ide> $result = array_keys($TestModel->hasMany); <ide> $expected = array('Title', 'Content'); <ide> $this->assertEquals($expected, $result); <ide> public function testUnbindTranslationInfinteLoop() { <ide> $this->loadFixtures('Translate', 'TranslatedItem'); <ide> <ide> $TestModel = new TranslatedItem(); <del> $TestModel->Behaviors->detach('Translate'); <add> $TestModel->Behaviors->unload('Translate'); <ide> $TestModel->actsAs = array(); <del> $TestModel->Behaviors->attach('Translate'); <add> $TestModel->Behaviors->load('Translate'); <ide> $TestModel->bindTranslation(array('title', 'content'), true); <ide> $result = $TestModel->unbindTranslation(); <ide> <ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorNumberTest.php <ide> public function testArraySyntax() { <ide> public function testFindThreaded() { <ide> $Model = new Person(); <ide> $Model->recursive = -1; <del> $Model->Behaviors->attach('Tree', array('parent' => 'mother_id')); <add> $Model->Behaviors->load('Tree', array('parent' => 'mother_id')); <ide> <ide> $result = $Model->find('threaded'); <ide> $expected = array( <ide><path>lib/Cake/Test/Case/Model/Behavior/TreeBehaviorScopedTest.php <ide> public function testStringScope() { <ide> ); <ide> $this->assertEquals($expected, $result); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); <add> $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); <ide> $this->assertEquals(array(), $this->Tree->children()); <ide> <ide> $this->Tree->id = 1; <del> $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); <add> $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); <ide> <ide> $result = $this->Tree->children(); <ide> $expected = array(array('FlagTree' => array('id' => '2', 'name' => '1.1', 'parent_id' => '1', 'lft' => '2', 'rght' => '9', 'flag' => '1'))); <ide> public function testArrayScope() { <ide> ); <ide> $this->assertEquals($expected, $result); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> $this->assertEquals(array(), $this->Tree->children()); <ide> <ide> $this->Tree->id = 1; <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> <ide> $result = $this->Tree->children(); <ide> $expected = array(array('FlagTree' => array('id' => '2', 'name' => '1.1', 'parent_id' => '1', 'lft' => '2', 'rght' => '9', 'flag' => '1'))); <ide> public function testArrayScope() { <ide> public function testMoveUpWithScope() { <ide> $this->Ad = new Ad(); <ide> $this->Ad->order = null; <del> $this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign')); <add> $this->Ad->Behaviors->load('Tree', array('scope' => 'Campaign')); <ide> $this->Ad->moveUp(6); <ide> <ide> $this->Ad->id = 4; <ide> public function testMoveUpWithScope() { <ide> public function testMoveDownWithScope() { <ide> $this->Ad = new Ad(); <ide> $this->Ad->order = null; <del> $this->Ad->Behaviors->attach('Tree', array('scope' => 'Campaign')); <add> $this->Ad->Behaviors->load('Tree', array('scope' => 'Campaign')); <ide> $this->Ad->moveDown(6); <ide> <ide> $this->Ad->id = 4; <ide> public function testTranslatingTree() { <ide> $this->Tree = new FlagTree(); <ide> $this->Tree->order = null; <ide> $this->Tree->cacheQueries = false; <del> $this->Tree->Behaviors->attach('Translate', array('title')); <add> $this->Tree->Behaviors->load('Translate', array('title')); <ide> <ide> //Save <ide> $this->Tree->create(); <ide> public function testAliasesWithScopeInTwoTreeAssociations() { <ide> ) <ide> ) <ide> )); <del> $this->TreeTwo->Behaviors->attach('Tree', array( <add> $this->TreeTwo->Behaviors->load('Tree', array( <ide> 'scope' => 'FirstTree' <ide> )); <ide> <ide> public function testGenerateTreeListWithScope() { <ide> $this->Tree->id = 2; <ide> $this->Tree->saveField('flag', 1); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> <ide> $result = $this->Tree->generateTreeList(); <ide> $expected = array( <ide> public function testGenerateTreeListWithScope() { <ide> $this->assertEquals($expected, $result); <ide> <ide> // As string. <del> $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); <add> $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); <ide> <ide> $result = $this->Tree->generateTreeList(); <ide> $this->assertEquals($expected, $result); <ide> public function testRecoverUsingParentMode() { <ide> $this->Tree->order = null; <ide> $this->Tree->initialize(2, 3); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => 'FlagTree.flag = 1')); <add> $this->Tree->Behaviors->load('Tree', array('scope' => 'FlagTree.flag = 1')); <ide> $this->Tree->Behaviors->disable('Tree'); <ide> <ide> $this->Tree->create(); <ide> public function testRecoverFromMissingParent() { <ide> $this->Tree->id = 2; <ide> $this->Tree->saveField('flag', 1); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> <ide> $result = $this->Tree->findByName('1.1'); <ide> $this->Tree->updateAll(array($parentField => 999999), array('id' => $result[$modelClass]['id'])); <ide> public function testDetectInvalidParents() { <ide> $this->Tree->id = 2; <ide> $this->Tree->saveField('flag', 1); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> <ide> $this->Tree->updateAll(array($parentField => null)); <ide> <ide> public function testDetectInvalidLftsRghts() { <ide> $this->Tree->id = 2; <ide> $this->Tree->saveField('flag', 1); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> <ide> $this->Tree->updateAll(array($leftField => 0, $rightField => 0)); <ide> <ide> public function testDetectEqualLftsRghts() { <ide> $this->Tree->id = 2; <ide> $this->Tree->saveField('flag', 1); <ide> <del> $this->Tree->Behaviors->attach('Tree', array('scope' => array('FlagTree.flag' => 1))); <add> $this->Tree->Behaviors->load('Tree', array('scope' => array('FlagTree.flag' => 1))); <ide> <ide> $result = $this->Tree->findByName('1.1'); <ide> $this->Tree->updateAll(array($rightField => $result[$modelClass][$leftField]), array('id' => $result[$modelClass]['id'])); <ide><path>lib/Cake/Test/Case/Model/BehaviorCollectionTest.php <ide> public function testBehaviorBinding() { <ide> $Apple = new Apple(); <ide> $this->assertSame(array(), $Apple->Behaviors->loaded()); <ide> <del> $Apple->Behaviors->attach('Test', array('key' => 'value')); <add> $Apple->Behaviors->load('Test', array('key' => 'value')); <ide> $this->assertSame(array('Test'), $Apple->Behaviors->loaded()); <ide> $this->assertEquals('testbehavior', strtolower(get_class($Apple->Behaviors->Test))); <ide> $expected = array('beforeFind' => 'on', 'afterFind' => 'off', 'key' => 'value'); <ide> $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); <ide> $this->assertEquals(array('priority', 'Apple'), array_keys($Apple->Behaviors->Test->settings)); <ide> <ide> $this->assertSame($Apple->Sample->Behaviors->loaded(), array()); <del> $Apple->Sample->Behaviors->attach('Test', array('key2' => 'value2')); <add> $Apple->Sample->Behaviors->load('Test', array('key2' => 'value2')); <ide> $this->assertSame($Apple->Sample->Behaviors->loaded(), array('Test')); <ide> $this->assertEquals(array('beforeFind' => 'on', 'afterFind' => 'off', 'key2' => 'value2'), $Apple->Sample->Behaviors->Test->settings['Sample']); <ide> <ide> public function testBehaviorBinding() { <ide> ); <ide> $this->assertNotSame($Apple->Behaviors->Test->settings['Apple'], $Apple->Sample->Behaviors->Test->settings['Sample']); <ide> <del> $Apple->Behaviors->attach('Test', array('key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); <del> $Apple->Sample->Behaviors->attach('Test', array('key' => 'value', 'key3' => 'value3', 'beforeFind' => 'off')); <add> $Apple->Behaviors->load('Test', array('key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); <add> $Apple->Sample->Behaviors->load('Test', array('key' => 'value', 'key3' => 'value3', 'beforeFind' => 'off')); <ide> $this->assertEquals(array('beforeFind' => 'off', 'afterFind' => 'off', 'key' => 'value', 'key2' => 'value2', 'key3' => 'value3'), $Apple->Behaviors->Test->settings['Apple']); <ide> $this->assertEquals($Apple->Behaviors->Test->settings['Apple'], $Apple->Sample->Behaviors->Test->settings['Sample']); <ide> <ide> $this->assertFalse(isset($Apple->Child->Behaviors->Test)); <del> $Apple->Child->Behaviors->attach('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); <add> $Apple->Child->Behaviors->load('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); <ide> $this->assertEquals($Apple->Child->Behaviors->Test->settings['Child'], $Apple->Sample->Behaviors->Test->settings['Sample']); <ide> <ide> $this->assertFalse(isset($Apple->Parent->Behaviors->Test)); <del> $Apple->Parent->Behaviors->attach('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); <add> $Apple->Parent->Behaviors->load('Test', array('key' => 'value', 'key2' => 'value2', 'key3' => 'value3', 'beforeFind' => 'off')); <ide> $this->assertEquals($Apple->Parent->Behaviors->Test->settings['Parent'], $Apple->Sample->Behaviors->Test->settings['Sample']); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('key' => 'value', 'key2' => 'value', 'key3' => 'value', 'beforeFind' => 'off')); <add> $Apple->Parent->Behaviors->load('Test', array('key' => 'value', 'key2' => 'value', 'key3' => 'value', 'beforeFind' => 'off')); <ide> $this->assertNotEquals($Apple->Parent->Behaviors->Test->settings['Parent'], $Apple->Sample->Behaviors->Test->settings['Sample']); <ide> <del> $Apple->Behaviors->attach('Plugin.Test', array('key' => 'new value')); <add> $Apple->Behaviors->load('Plugin.Test', array('key' => 'new value')); <ide> $expected = array( <ide> 'beforeFind' => 'off', 'afterFind' => 'off', 'key' => 'new value', <ide> 'key2' => 'value2', 'key3' => 'value3' <ide> public function testBehaviorBinding() { <ide> <ide> $current = $Apple->Behaviors->Test->settings['Apple']; <ide> $expected = array_merge($current, array('mangle' => 'trigger mangled')); <del> $Apple->Behaviors->attach('Test', array('mangle' => 'trigger')); <add> $Apple->Behaviors->load('Test', array('mangle' => 'trigger')); <ide> $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); <ide> <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> $expected = array_merge($current, array('mangle' => 'trigger mangled mangled')); <ide> <ide> $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); <del> $Apple->Behaviors->attach('Test', array('mangle' => 'trigger')); <add> $Apple->Behaviors->load('Test', array('mangle' => 'trigger')); <ide> $expected = array_merge($current, array('mangle' => 'trigger mangled')); <ide> $this->assertEquals($expected, $Apple->Behaviors->Test->settings['Apple']); <ide> } <ide> public function testBehaviorBinding() { <ide> */ <ide> public function testDetachWithPluginNames() { <ide> $Apple = new Apple(); <del> $Apple->Behaviors->attach('Plugin.Test'); <add> $Apple->Behaviors->load('Plugin.Test'); <ide> $this->assertTrue(isset($Apple->Behaviors->Test), 'Missing behavior'); <ide> $this->assertEquals(array('Test'), $Apple->Behaviors->loaded()); <ide> <del> $Apple->Behaviors->detach('Plugin.Test'); <add> $Apple->Behaviors->unload('Plugin.Test'); <ide> $this->assertEquals(array(), $Apple->Behaviors->loaded()); <ide> <del> $Apple->Behaviors->attach('Plugin.Test'); <add> $Apple->Behaviors->load('Plugin.Test'); <ide> $this->assertTrue(isset($Apple->Behaviors->Test), 'Missing behavior'); <ide> $this->assertEquals(array('Test'), $Apple->Behaviors->loaded()); <ide> <del> $Apple->Behaviors->detach('Test'); <add> $Apple->Behaviors->unload('Test'); <ide> $this->assertEquals(array(), $Apple->Behaviors->loaded()); <ide> } <ide> <ide> public function testDetachWithPluginNames() { <ide> */ <ide> public function testInvalidBehaviorCausingCakeError() { <ide> $Apple = new Apple(); <del> $Apple->Behaviors->attach('NoSuchBehavior'); <add> $Apple->Behaviors->load('NoSuchBehavior'); <ide> } <ide> <ide> /** <ide> public function testBehaviorToggling() { <ide> $this->assertSame(array('Test'), $Apple->Behaviors->loaded()); <ide> $this->assertSame($Apple->Behaviors->enabled(), array()); <ide> <del> $Apple->Sample->Behaviors->attach('Test'); <add> $Apple->Sample->Behaviors->load('Test'); <ide> $this->assertTrue($Apple->Sample->Behaviors->enabled('Test')); <ide> $this->assertSame($Apple->Behaviors->enabled(), array()); <ide> <ide> public function testBehaviorToggling() { <ide> <ide> $Apple->Behaviors->disable('Test'); <ide> $this->assertSame($Apple->Behaviors->enabled(), array()); <del> $Apple->Behaviors->attach('Test', array('enabled' => true)); <add> $Apple->Behaviors->load('Test', array('enabled' => true)); <ide> $this->assertSame($Apple->Behaviors->enabled(), array('Test')); <del> $Apple->Behaviors->attach('Test', array('enabled' => false)); <add> $Apple->Behaviors->load('Test', array('enabled' => false)); <ide> $this->assertSame($Apple->Behaviors->enabled(), array()); <del> $Apple->Behaviors->detach('Test'); <add> $Apple->Behaviors->unload('Test'); <ide> $this->assertSame($Apple->Behaviors->enabled(), array()); <ide> } <ide> <ide> public function testBehaviorFindCallbacks() { <ide> $Apple = new Apple(); <ide> $expected = $Apple->find('all'); <ide> <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> $this->assertNull($Apple->find('all')); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeFind' => 'off')); <add> $Apple->Behaviors->load('Test', array('beforeFind' => 'off')); <ide> $this->assertSame($expected, $Apple->find('all')); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeFind' => 'test')); <add> $Apple->Behaviors->load('Test', array('beforeFind' => 'test')); <ide> $this->assertSame($expected, $Apple->find('all')); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeFind' => 'modify')); <add> $Apple->Behaviors->load('Test', array('beforeFind' => 'modify')); <ide> $expected2 = array( <ide> array('Apple' => array('id' => '1', 'name' => 'Red Apple 1', 'mytime' => '22:57:17')), <ide> array('Apple' => array('id' => '2', 'name' => 'Bright Red Apple', 'mytime' => '22:57:17')), <ide> public function testBehaviorFindCallbacks() { <ide> $result = $Apple->find('all'); <ide> $this->assertEquals($expected, $result); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeFind' => 'off', 'afterFind' => 'on')); <add> $Apple->Behaviors->load('Test', array('beforeFind' => 'off', 'afterFind' => 'on')); <ide> $this->assertSame($Apple->find('all'), array()); <ide> <del> $Apple->Behaviors->attach('Test', array('afterFind' => 'off')); <add> $Apple->Behaviors->load('Test', array('afterFind' => 'off')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Behaviors->attach('Test', array('afterFind' => 'test')); <add> $Apple->Behaviors->load('Test', array('afterFind' => 'test')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Behaviors->attach('Test', array('afterFind' => 'test2')); <add> $Apple->Behaviors->load('Test', array('afterFind' => 'test2')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Behaviors->attach('Test', array('afterFind' => 'modify')); <add> $Apple->Behaviors->load('Test', array('afterFind' => 'modify')); <ide> $expected = array( <ide> array('id' => '1', 'apple_id' => '2', 'color' => 'Red 1', 'name' => 'Red Apple 1', 'created' => '2006-11-22 10:38:58', 'date' => '1951-01-04', 'modified' => '2006-12-01 13:31:26', 'mytime' => '22:57:17'), <ide> array('id' => '2', 'apple_id' => '1', 'color' => 'Bright Red 1', 'name' => 'Bright Red Apple', 'created' => '2006-11-22 10:43:13', 'date' => '2014-01-01', 'modified' => '2006-11-30 18:38:10', 'mytime' => '22:57:17'), <ide> public function testBehaviorHasManyFindCallbacks() { <ide> <ide> $Apple->unbindModel(array('hasMany' => array('Child'))); <ide> $wellBehaved = $Apple->find('all'); <del> $Apple->Child->Behaviors->attach('Test', array('afterFind' => 'modify')); <add> $Apple->Child->Behaviors->load('Test', array('afterFind' => 'modify')); <ide> $Apple->unbindModel(array('hasMany' => array('Child'))); <ide> $this->assertSame($Apple->find('all'), $wellBehaved); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('before' => 'off')); <add> $Apple->Child->Behaviors->load('Test', array('before' => 'off')); <ide> $this->assertSame($expected, $Apple->find('all')); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('before' => 'test')); <add> $Apple->Child->Behaviors->load('Test', array('before' => 'test')); <ide> $this->assertSame($expected, $Apple->find('all')); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('before' => 'modify')); <add> $Apple->Child->Behaviors->load('Test', array('before' => 'modify')); <ide> $result = $Apple->find('all', array('fields' => array('Apple.id'), 'conditions' => array('Apple.id <' => '4'))); <ide> <ide> $Apple->Child->Behaviors->disable('Test'); <ide> $result = $Apple->find('all'); <ide> $this->assertEquals($expected, $result); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('before' => 'off', 'after' => 'on')); <add> $Apple->Child->Behaviors->load('Test', array('before' => 'off', 'after' => 'on')); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('after' => 'off')); <add> $Apple->Child->Behaviors->load('Test', array('after' => 'off')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('after' => 'test')); <add> $Apple->Child->Behaviors->load('Test', array('after' => 'test')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Child->Behaviors->attach('Test', array('after' => 'test2')); <add> $Apple->Child->Behaviors->load('Test', array('after' => 'test2')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> } <ide> <ide> public function testBehaviorHasOneFindCallbacks() { <ide> <ide> $Apple->unbindModel(array('hasOne' => array('Sample'))); <ide> $wellBehaved = $Apple->find('all'); <del> $Apple->Sample->Behaviors->attach('Test'); <add> $Apple->Sample->Behaviors->load('Test'); <ide> $Apple->unbindModel(array('hasOne' => array('Sample'))); <ide> $this->assertSame($Apple->find('all'), $wellBehaved); <ide> <del> $Apple->Sample->Behaviors->attach('Test', array('before' => 'off')); <add> $Apple->Sample->Behaviors->load('Test', array('before' => 'off')); <ide> $this->assertSame($expected, $Apple->find('all')); <ide> <del> $Apple->Sample->Behaviors->attach('Test', array('before' => 'test')); <add> $Apple->Sample->Behaviors->load('Test', array('before' => 'test')); <ide> $this->assertSame($expected, $Apple->find('all')); <ide> <ide> $Apple->Sample->Behaviors->disable('Test'); <ide> $result = $Apple->find('all'); <ide> $this->assertEquals($expected, $result); <ide> <del> $Apple->Sample->Behaviors->attach('Test', array('after' => 'off')); <add> $Apple->Sample->Behaviors->load('Test', array('after' => 'off')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Sample->Behaviors->attach('Test', array('after' => 'test')); <add> $Apple->Sample->Behaviors->load('Test', array('after' => 'test')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> <del> $Apple->Sample->Behaviors->attach('Test', array('after' => 'test2')); <add> $Apple->Sample->Behaviors->load('Test', array('after' => 'test2')); <ide> $this->assertEquals($expected, $Apple->find('all')); <ide> } <ide> <ide> public function testBehaviorBelongsToFindCallbacks() { <ide> <ide> $Apple->unbindModel(array('belongsTo' => array('Parent'))); <ide> $wellBehaved = $Apple->find('all', $conditions); <del> $Apple->Parent->Behaviors->attach('Test'); <add> $Apple->Parent->Behaviors->load('Test'); <ide> $Apple->unbindModel(array('belongsTo' => array('Parent'))); <ide> $this->assertSame($Apple->find('all', $conditions), $wellBehaved); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('before' => 'off')); <add> $Apple->Parent->Behaviors->load('Test', array('before' => 'off')); <ide> $this->assertSame($expected, $Apple->find('all', $conditions)); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('before' => 'test')); <add> $Apple->Parent->Behaviors->load('Test', array('before' => 'test')); <ide> $this->assertSame($expected, $Apple->find('all', $conditions)); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('before' => 'modify')); <add> $Apple->Parent->Behaviors->load('Test', array('before' => 'modify')); <ide> $expected2 = array( <ide> array( <ide> 'Apple' => array('id' => 1), <ide> public function testBehaviorBelongsToFindCallbacks() { <ide> $result = $Apple->find('all', $conditions); <ide> $this->assertEquals($expected, $result); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('after' => 'off')); <add> $Apple->Parent->Behaviors->load('Test', array('after' => 'off')); <ide> $this->assertEquals($expected, $Apple->find('all', $conditions)); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('after' => 'test')); <add> $Apple->Parent->Behaviors->load('Test', array('after' => 'test')); <ide> $this->assertEquals($expected, $Apple->find('all', $conditions)); <ide> <del> $Apple->Parent->Behaviors->attach('Test', array('after' => 'test2')); <add> $Apple->Parent->Behaviors->load('Test', array('after' => 'test2')); <ide> $this->assertEquals($expected, $Apple->find('all', $conditions)); <ide> } <ide> <ide> public function testBehaviorSaveCallbacks() { <ide> $Sample = new Sample(); <ide> $record = array('Sample' => array('apple_id' => 6, 'name' => 'sample99')); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'on')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'on')); <ide> $Sample->create(); <ide> $this->assertSame(false, $Sample->save($record)); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'off')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'off')); <ide> $Sample->create(); <ide> $result = $Sample->save($record); <ide> $expected = $record; <ide> $expected['Sample']['id'] = $Sample->id; <ide> $this->assertSame($expected, $result); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'test')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'test')); <ide> $Sample->create(); <ide> $result = $Sample->save($record); <ide> $expected = $record; <ide> $expected['Sample']['id'] = $Sample->id; <ide> $this->assertSame($expected, $result); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'modify')); <ide> $expected = Hash::insert($record, 'Sample.name', 'sample99 modified before'); <ide> $Sample->create(); <ide> $result = $Sample->save($record); <ide> public function testBehaviorSaveCallbacks() { <ide> $Sample->Behaviors->disable('Test'); <ide> $this->assertSame($record, $Sample->save($record)); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'on')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'off', 'afterSave' => 'on')); <ide> $expected = Hash::merge($record, array('Sample' => array('aftersave' => 'modified after on create'))); <ide> $Sample->create(); <ide> $result = $Sample->save($record); <ide> $expected['Sample']['id'] = $Sample->id; <ide> $this->assertEquals($expected, $result); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'modify', 'afterSave' => 'modify')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'modify', 'afterSave' => 'modify')); <ide> $expected = Hash::merge($record, array('Sample' => array('name' => 'sample99 modified before modified after on create'))); <ide> $Sample->create(); <ide> $result = $Sample->save($record); <ide> $expected['Sample']['id'] = $Sample->id; <ide> $this->assertSame($expected, $result); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeSave' => 'off', 'afterSave' => 'test')); <add> $Sample->Behaviors->load('Test', array('beforeSave' => 'off', 'afterSave' => 'test')); <ide> $Sample->create(); <ide> $expected = $record; <ide> unset($expected['Sample']['name']); <ide> $result = $Sample->save($record); <ide> $expected['Sample']['id'] = $Sample->id; <ide> $this->assertSame($expected, $result); <ide> <del> $Sample->Behaviors->attach('Test', array('afterSave' => 'test2')); <add> $Sample->Behaviors->load('Test', array('afterSave' => 'test2')); <ide> $Sample->create(); <ide> $expected = $record; <ide> $result = $Sample->save($record); <ide> $expected['Sample']['id'] = $Sample->id; <ide> $this->assertSame($expected, $result); <ide> <del> $Sample->Behaviors->attach('Test', array('beforeFind' => 'off', 'afterFind' => 'off')); <add> $Sample->Behaviors->load('Test', array('beforeFind' => 'off', 'afterFind' => 'off')); <ide> $Sample->recursive = -1; <ide> $record2 = $Sample->read(null, 1); <ide> <del> $Sample->Behaviors->attach('Test', array('afterSave' => 'on')); <add> $Sample->Behaviors->load('Test', array('afterSave' => 'on')); <ide> $expected = Hash::merge($record2, array('Sample' => array('aftersave' => 'modified after'))); <ide> $Sample->create(); <ide> $this->assertSame($expected, $Sample->save($record2)); <ide> <del> $Sample->Behaviors->attach('Test', array('afterSave' => 'modify')); <add> $Sample->Behaviors->load('Test', array('afterSave' => 'modify')); <ide> $expected = Hash::merge($record2, array('Sample' => array('name' => 'sample1 modified after'))); <ide> $Sample->create(); <ide> $this->assertSame($expected, $Sample->save($record2)); <ide> public function testBehaviorSaveCallbacks() { <ide> public function testBehaviorDeleteCallbacks() { <ide> $Apple = new Apple(); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeFind' => 'off', 'beforeDelete' => 'off')); <add> $Apple->Behaviors->load('Test', array('beforeFind' => 'off', 'beforeDelete' => 'off')); <ide> $this->assertTrue($Apple->delete(6)); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeDelete' => 'on')); <add> $Apple->Behaviors->load('Test', array('beforeDelete' => 'on')); <ide> $this->assertFalse($Apple->delete(4)); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeDelete' => 'test2')); <add> $Apple->Behaviors->load('Test', array('beforeDelete' => 'test2')); <ide> <ide> ob_start(); <ide> $results = $Apple->delete(4); <ide> public function testBehaviorDeleteCallbacks() { <ide> $this->assertSame(trim(ob_get_clean()), 'beforeDelete success'); <ide> $this->assertTrue($results); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeDelete' => 'off', 'afterDelete' => 'on')); <add> $Apple->Behaviors->load('Test', array('beforeDelete' => 'off', 'afterDelete' => 'on')); <ide> ob_start(); <ide> $results = $Apple->delete(2, false); <ide> $this->assertSame(trim(ob_get_clean()), 'afterDelete success'); <ide> public function testBehaviorDeleteCallbacks() { <ide> public function testBehaviorOnErrorCallback() { <ide> $Apple = new Apple(); <ide> <del> $Apple->Behaviors->attach('Test', array('beforeFind' => 'off', 'onError' => 'on')); <add> $Apple->Behaviors->load('Test', array('beforeFind' => 'off', 'onError' => 'on')); <ide> ob_start(); <ide> $Apple->Behaviors->Test->onError($Apple, ''); <ide> $this->assertSame(trim(ob_get_clean()), 'onError trigger success'); <ide> public function testBehaviorOnErrorCallback() { <ide> public function testBehaviorValidateCallback() { <ide> $Apple = new Apple(); <ide> <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> $this->assertTrue($Apple->validates()); <ide> <del> $Apple->Behaviors->attach('Test', array('validate' => 'on')); <add> $Apple->Behaviors->load('Test', array('validate' => 'on')); <ide> $this->assertFalse($Apple->validates()); <ide> $this->assertSame($Apple->validationErrors, array('name' => array(true))); <ide> <del> $Apple->Behaviors->attach('Test', array('validate' => 'stop')); <add> $Apple->Behaviors->load('Test', array('validate' => 'stop')); <ide> $this->assertFalse($Apple->validates()); <ide> $this->assertSame($Apple->validationErrors, array('name' => array(true, true))); <ide> <del> $Apple->Behaviors->attach('Test', array('validate' => 'whitelist')); <add> $Apple->Behaviors->load('Test', array('validate' => 'whitelist')); <ide> $Apple->validates(); <ide> $this->assertSame($Apple->whitelist, array()); <ide> <ide> public function testBehaviorValidateCallback() { <ide> public function testBehaviorValidateAfterCallback() { <ide> $Apple = new Apple(); <ide> <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> $this->assertTrue($Apple->validates()); <ide> <del> $Apple->Behaviors->attach('Test', array('afterValidate' => 'on')); <add> $Apple->Behaviors->load('Test', array('afterValidate' => 'on')); <ide> $this->assertTrue($Apple->validates()); <ide> $this->assertSame($Apple->validationErrors, array()); <ide> <del> $Apple->Behaviors->attach('Test', array('afterValidate' => 'test')); <add> $Apple->Behaviors->load('Test', array('afterValidate' => 'test')); <ide> $Apple->data = array('bar'); <ide> $Apple->validates(); <ide> $this->assertEquals(array('foo'), $Apple->data); <ide> public function testBehaviorValidateAfterCallback() { <ide> */ <ide> public function testBehaviorValidateMethods() { <ide> $Apple = new Apple(); <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> $Apple->validate['color'] = 'validateField'; <ide> <ide> $result = $Apple->save(array('name' => 'Genetically Modified Apple', 'color' => 'Orange')); <ide> public function testBehaviorValidateMethods() { <ide> */ <ide> public function testBehaviorMethodDispatching() { <ide> $Apple = new Apple(); <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> <ide> $expected = 'working'; <ide> $this->assertEquals($expected, $Apple->testMethod()); <ide> public function testBehaviorMethodDispatching() { <ide> */ <ide> public function testBehaviorMethodDispatchingWithData() { <ide> $Apple = new Apple(); <del> $Apple->Behaviors->attach('Test'); <add> $Apple->Behaviors->load('Test'); <ide> <ide> $Apple->set('field', 'value'); <ide> $this->assertTrue($Apple->testData()); <ide> public function testBindModelCallsInBehaviors() { <ide> $result = $Article->find('first'); <ide> $this->assertFalse(array_key_exists('Comment', $result)); <ide> <del> $Article->Behaviors->attach('Test4'); <add> $Article->Behaviors->load('Test4'); <ide> $result = $Article->find('first'); <ide> $this->assertTrue(array_key_exists('Comment', $result)); <ide> <ide> public function testBindModelCallsInBehaviors() { <ide> $result = $Article->find('first'); <ide> $this->assertFalse(array_key_exists('User', $result)); <ide> <del> $Article->Behaviors->attach('Test5'); <add> $Article->Behaviors->load('Test5'); <ide> $result = $Article->find('first'); <ide> $this->assertTrue(array_key_exists('User', $result)); <ide> <ide> public function testBindModelCallsInBehaviors() { <ide> $result = $Article->find('first'); <ide> $this->assertFalse(array_key_exists('Tag', $result)); <ide> <del> $Article->Behaviors->attach('Test6'); <add> $Article->Behaviors->load('Test6'); <ide> $result = $Article->find('first'); <ide> $this->assertTrue(array_key_exists('Comment', $result)); <ide> <ide> public function testBindModelCallsInBehaviors() { <ide> $result = $Comment->find('first'); <ide> $this->assertFalse(array_key_exists('Attachment', $result)); <ide> <del> $Comment->Behaviors->attach('Test7'); <add> $Comment->Behaviors->load('Test7'); <ide> $result = $Comment->find('first'); <ide> $this->assertTrue(array_key_exists('Attachment', $result)); <ide> } <ide> public function testBehaviorAttachAndDetach() { <ide> $Sample = new Sample(); <ide> $Sample->actsAs = array('Test3' => array('bar'), 'Test2' => array('foo', 'bar')); <ide> $Sample->Behaviors->init($Sample->alias, $Sample->actsAs); <del> $Sample->Behaviors->attach('Test2'); <del> $Sample->Behaviors->detach('Test3'); <add> $Sample->Behaviors->load('Test2'); <add> $Sample->Behaviors->unload('Test3'); <ide> <ide> $Sample->Behaviors->trigger('beforeTest', array(&$Sample)); <ide> } <ide><path>lib/Cake/Test/Case/Model/ModelIntegrationTest.php <ide> public function testDynamicBehaviorAttachment() { <ide> $TestModel = new Apple(); <ide> $this->assertEquals(array(), $TestModel->Behaviors->loaded()); <ide> <del> $TestModel->Behaviors->attach('Tree', array('left' => 'left_field', 'right' => 'right_field')); <add> $TestModel->Behaviors->load('Tree', array('left' => 'left_field', 'right' => 'right_field')); <ide> $this->assertTrue(is_object($TestModel->Behaviors->Tree)); <ide> $this->assertEquals(array('Tree'), $TestModel->Behaviors->loaded()); <ide> <ide> public function testDynamicBehaviorAttachment() { <ide> ); <ide> $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); <ide> <del> $TestModel->Behaviors->attach('Tree', array('enabled' => false)); <add> $TestModel->Behaviors->load('Tree', array('enabled' => false)); <ide> $this->assertEquals($expected, $TestModel->Behaviors->Tree->settings['Apple']); <ide> $this->assertEquals(array('Tree'), $TestModel->Behaviors->loaded()); <ide> <del> $TestModel->Behaviors->detach('Tree'); <add> $TestModel->Behaviors->unload('Tree'); <ide> $this->assertEquals(array(), $TestModel->Behaviors->loaded()); <ide> $this->assertFalse(isset($TestModel->Behaviors->Tree)); <ide> } <ide><path>lib/Cake/Test/Case/Model/ModelValidationTest.php <ide> public function testGetMethodsRefresh() { <ide> $expected = array_map('strtolower', get_class_methods('Article')); <ide> $this->assertEquals($expected, array_keys($result)); <ide> <del> $TestModel->Behaviors->attach('Containable'); <add> $TestModel->Behaviors->load('Containable'); <ide> $newList = array( <ide> 'contain', <ide> 'resetbindings', <ide> public function testGetMethodsRefresh() { <ide> ); <ide> $this->assertEquals(array_merge($expected, $newList), array_keys($Validator->getMethods())); <ide> <del> $TestModel->Behaviors->detach('Containable'); <add> $TestModel->Behaviors->unload('Containable'); <ide> $this->assertEquals($expected, array_keys($Validator->getMethods())); <ide> } <ide>
7
Javascript
Javascript
remove some debugging informations
d26969a85fc1cd43d7d623515605463afa19c25f
<ide><path>web/viewer.js <ide> var TextLayerBuilder = function textLayerBuilder(textLayerDiv) { <ide> textDiv.style.top = (text.geom.y - fontHeight) + 'px'; <ide> <ide> // The content of the div is set in the `setTextContent` function. <del> // For debug reasons, do the bidi thing here to compare it later once the <del> // text from the getTextContent function comes in. <del> var bidiText = PDFJS.bidi(text.str, -1); <del> textDiv.textContent = bidiText.content; <del> textDiv.dir = bidiText.direction; <ide> <del> var idx = this.textDivs.push(textDiv) - 1; <add> this.textDivs.push(textDiv); <ide> }; <ide> <ide> this.setTextContent = function textLayerBuilderSetTextContent(textContent) { <ide> // When calling this function, we assume rendering the textDivs has finished <del> <ide> var textDivs = this.textDivs; <ide> <del> console.log(textContent); <del> <ide> for (var i = 0; i < textContent.length; i++) { <ide> var textDiv = textDivs[i]; <ide> var bidiText = PDFJS.bidi(textContent[i], -1); <ide> <del> // console.log("divL #%d: text=%s, bidi=%s, dir=%s", i, textContent[i], textDiv.textContent, textDiv.dir); <del> <ide> textDiv.textContent = bidiText.content; <ide> textDiv.dir = bidiText.direction; <del> // console.log("divC #%d: text=%s, bidi=%s, dir=%s", i, textContent[i], bidiText.content, bidiText.direction); <ide> } <ide> <ide> this.setupRenderLayoutTimer();
1
Java
Java
improve decoding support for multipart filename
bb684ce60b82bb2d3a81828a6780800c51bb4e33
<ide><path>spring-web/src/main/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequest.java <ide> import java.io.IOException; <ide> import java.io.InputStream; <ide> import java.io.Serializable; <del>import java.nio.charset.Charset; <del>import java.nio.charset.StandardCharsets; <add>import java.io.UnsupportedEncodingException; <ide> import java.nio.file.Files; <ide> import java.util.ArrayList; <ide> import java.util.Collection; <ide> import java.util.LinkedHashSet; <ide> import java.util.Map; <ide> import java.util.Set; <add>import javax.mail.internet.MimeUtility; <ide> import javax.servlet.http.HttpServletRequest; <ide> import javax.servlet.http.Part; <ide> <add>import org.springframework.http.ContentDisposition; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.FileCopyUtils; <ide> */ <ide> public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest { <ide> <del> private static final String CONTENT_DISPOSITION = "content-disposition"; <del> <del> private static final String FILENAME_KEY = "filename="; <del> <del> private static final String FILENAME_WITH_CHARSET_KEY = "filename*="; <del> <del> <ide> @Nullable <ide> private Set<String> multipartParameterNames; <ide> <ide> private void parseRequest(HttpServletRequest request) { <ide> this.multipartParameterNames = new LinkedHashSet<>(parts.size()); <ide> MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<>(parts.size()); <ide> for (Part part : parts) { <del> String disposition = part.getHeader(CONTENT_DISPOSITION); <del> String filename = extractFilename(disposition); <del> if (filename == null) { <del> filename = extractFilenameWithCharset(disposition); <del> } <add> String headerValue = part.getHeader(HttpHeaders.CONTENT_DISPOSITION); <add> ContentDisposition disposition = ContentDisposition.parse(headerValue); <add> String filename = disposition.getFilename(); <ide> if (filename != null) { <add> if (filename.startsWith("=?") && filename.endsWith("?=")) { <add> filename = MimeDelegate.decode(filename); <add> } <ide> files.add(part.getName(), new StandardMultipartFile(part, filename)); <ide> } <ide> else { <ide> protected void handleParseFailure(Throwable ex) { <ide> throw new MultipartException("Failed to parse multipart servlet request", ex); <ide> } <ide> <del> @Nullable <del> private String extractFilename(String contentDisposition, String key) { <del> int startIndex = contentDisposition.indexOf(key); <del> if (startIndex == -1) { <del> return null; <del> } <del> String filename = contentDisposition.substring(startIndex + key.length()); <del> if (filename.startsWith("\"")) { <del> int endIndex = filename.indexOf("\"", 1); <del> if (endIndex != -1) { <del> return filename.substring(1, endIndex); <del> } <del> } <del> else { <del> int endIndex = filename.indexOf(";"); <del> if (endIndex != -1) { <del> return filename.substring(0, endIndex); <del> } <del> } <del> return filename; <del> } <del> <del> @Nullable <del> private String extractFilename(String contentDisposition) { <del> return extractFilename(contentDisposition, FILENAME_KEY); <del> } <del> <del> @Nullable <del> private String extractFilenameWithCharset(String contentDisposition) { <del> String filename = extractFilename(contentDisposition, FILENAME_WITH_CHARSET_KEY); <del> if (filename == null) { <del> return null; <del> } <del> int index = filename.indexOf("'"); <del> if (index != -1) { <del> Charset charset = null; <del> try { <del> charset = Charset.forName(filename.substring(0, index)); <del> } <del> catch (IllegalArgumentException ex) { <del> // ignore <del> } <del> filename = filename.substring(index + 1); <del> // Skip language information.. <del> index = filename.indexOf("'"); <del> if (index != -1) { <del> filename = filename.substring(index + 1); <del> } <del> if (charset != null) { <del> filename = new String(filename.getBytes(StandardCharsets.US_ASCII), charset); <del> } <del> } <del> return filename; <del> } <del> <del> <ide> @Override <ide> protected void initializeMultipart() { <ide> parseRequest(getRequest()); <ide> public void transferTo(File dest) throws IOException, IllegalStateException { <ide> } <ide> } <ide> <add> <add> /** <add> * Inner class to avoid a hard dependency on the JavaMail API. <add> */ <add> private static class MimeDelegate { <add> <add> public static String decode(String value) { <add> try { <add> return MimeUtility.decodeText(value); <add> } <add> catch (UnsupportedEncodingException ex) { <add> throw new IllegalStateException(ex); <add> } <add> } <add> } <add> <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/multipart/support/StandardMultipartHttpServletRequestTests.java <add>/* <add> * Copyright 2002-2017 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add>package org.springframework.web.multipart.support; <add> <add>import org.junit.Test; <add> <add>import org.springframework.mock.web.test.MockHttpServletRequest; <add>import org.springframework.mock.web.test.MockPart; <add>import org.springframework.web.multipart.MultipartFile; <add> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertNotNull; <add> <add>/** <add> * Unit tests for {@link StandardMultipartHttpServletRequest}. <add> * @author Rossen Stoyanchev <add> */ <add>public class StandardMultipartHttpServletRequestTests { <add> <add> <add> @Test <add> public void filename() throws Exception { <add> <add> StandardMultipartHttpServletRequest request = getRequest( <add> "file", "form-data; name=\"file\"; filename=\"myFile.txt\""); <add> <add> MultipartFile multipartFile = request.getFile("file"); <add> assertNotNull(multipartFile); <add> assertEquals("myFile.txt", multipartFile.getOriginalFilename()); <add> } <add> <add> @Test // SPR-13319 <add> public void filenameRfc5987() throws Exception { <add> <add> StandardMultipartHttpServletRequest request = getRequest( <add> "file", "form-data; name=\"file\"; filename*=\"UTF-8''foo-%c3%a4-%e2%82%ac.html\""); <add> <add> MultipartFile multipartFile = request.getFile("file"); <add> assertNotNull(multipartFile); <add> assertEquals("foo-ä-€.html", multipartFile.getOriginalFilename()); <add> } <add> <add> @Test // SPR-15205 <add> public void filenameRfc2047() throws Exception { <add> <add> StandardMultipartHttpServletRequest request = getRequest( <add> "file", "form-data; name=\"file\"; filename=\"=?UTF-8?Q?Declara=C3=A7=C3=A3o.pdf?=\""); <add> <add> MultipartFile multipartFile = request.getFile("file"); <add> assertNotNull(multipartFile); <add> assertEquals("Declaração.pdf", multipartFile.getOriginalFilename()); <add> } <add> <add> <add> private StandardMultipartHttpServletRequest getRequest(String name, String dispositionValue) { <add> MockHttpServletRequest request = new MockHttpServletRequest(); <add> MockPart part = new MockPart(name, new byte[0]); <add> part.getHeaders().set("Content-Disposition", dispositionValue); <add> request.addPart(part); <add> return new StandardMultipartHttpServletRequest(request); <add> } <add> <add>} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/RequestPartIntegrationTests.java <ide> public ResponseEntity<Object> create(@RequestPart(name = "json-data") TestData t <ide> <ide> @RequestMapping(value = "/spr13319", method = POST, consumes = "multipart/form-data") <ide> public ResponseEntity<Void> create(@RequestPart("file") MultipartFile multipartFile) { <del> assertEquals("%C3%A9l%C3%A8ve.txt", multipartFile.getOriginalFilename()); <add> assertEquals("élève.txt", multipartFile.getOriginalFilename()); <ide> return ResponseEntity.ok().build(); <ide> } <ide> }
3
Ruby
Ruby
pour local bottles without sha256
4cfd333c5a9fd32f1d9870b3e4987c7dad76a88a
<ide><path>Library/Homebrew/formula_installer.rb <ide> def pour_bottle?(install_bottle_options = { warn: false }) <ide> return false if @pour_failed <ide> <ide> bottle = formula.bottle <del> return false unless bottle <add> return false if !bottle && !formula.local_bottle_path <ide> return true if force_bottle? <ide> return false if build_from_source? || build_bottle? || interactive? <ide> return false if ARGV.cc
1
Ruby
Ruby
fix small typo
c02391f8f97182e818d22a0f0ec4a5589d2fff15
<ide><path>actionmailer/test/base_test.rb <ide> def custom_block(include_html=false) <ide> test "explicit multipart with options" do <ide> email = BaseMailer.custom_block(true).deliver <ide> assert_equal(2, email.parts.size) <del> assert_equal("multipart/alternate", email.mime_type) <add> assert_equal("multipart/alternative", email.mime_type) <ide> assert_equal("text/plain", email.parts[0].mime_type) <ide> assert_equal("base64", email.parts[0].content_transfer_encoding) <ide> assert_equal("text/html", email.parts[1].mime_type)
1
Python
Python
fix init for padding
233945bfe0847e9e9c43156c7360e181e8490ecd
<ide><path>spacy/ml/_precomputable_affine.py <ide> def init(model, X=None, Y=None): <ide> <ide> ops = model.ops <ide> W = normal_init(ops, W.shape, mean=float(ops.xp.sqrt(1.0 / nF * nI))) <add> pad = normal_init(ops, pad.shape, mean=1.0) <ide> model.set_param("W", W) <ide> model.set_param("b", b) <ide> model.set_param("pad", pad)
1
PHP
PHP
accept any datetimeinterface as valid
f3462c06bae748986da5d6350e2df917f64ab994
<ide><path>src/Validation/Validation.php <ide> namespace Cake\Validation; <ide> <ide> use Cake\Utility\Text; <del>use DateTime; <add>use DateTimeInterface; <ide> use LogicException; <ide> use NumberFormatter; <ide> use RuntimeException; <ide> public static function custom($check, $regex = null) <ide> * - `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash <ide> * - `y` 2006 just the year without any separators <ide> * <del> * @param string|\DateTime $check a valid date string/object <add> * @param string|\DateTimeInterface $check a valid date string/object <ide> * @param string|array $format Use a string or an array of the keys above. <ide> * Arrays should be passed as ['dmy', 'mdy', etc] <ide> * @param string|null $regex If a custom regular expression is used this is the only validation that will occur. <ide> * @return bool Success <ide> */ <ide> public static function date($check, $format = 'ymd', $regex = null) <ide> { <del> if ($check instanceof DateTime) { <add> if ($check instanceof DateTimeInterface) { <ide> return true; <ide> } <ide> <ide> public static function date($check, $format = 'ymd', $regex = null) <ide> * <ide> * All values matching the "date" core validation rule, and the "time" one will be valid <ide> * <del> * @param string|\DateTime $check Value to check <add> * @param string|\DateTimeInterface $check Value to check <ide> * @param string|array $dateFormat Format of the date part. See Validation::date() for more information. <ide> * @param string|null $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur. <ide> * @return bool True if the value is valid, false otherwise <ide> public static function date($check, $format = 'ymd', $regex = null) <ide> */ <ide> public static function datetime($check, $dateFormat = 'ymd', $regex = null) <ide> { <del> if ($check instanceof DateTime) { <add> if ($check instanceof DateTimeInterface) { <ide> return true; <ide> } <ide> $valid = false; <ide> public static function datetime($check, $dateFormat = 'ymd', $regex = null) <ide> * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m) <ide> * Does not allow/validate seconds. <ide> * <del> * @param string|\DateTime $check a valid time string/object <add> * @param string|\DateTimeInterface $check a valid time string/object <ide> * @return bool Success <ide> */ <ide> public static function time($check) <ide> { <del> if ($check instanceof DateTime) { <add> if ($check instanceof DateTimeInterface) { <ide> return true; <ide> } <ide> if (is_array($check)) { <ide><path>tests/TestCase/Validation/ValidationTest.php <ide> public function testDateTimeObject() <ide> $this->assertTrue(Validation::date($dateTime)); <ide> $this->assertTrue(Validation::time($dateTime)); <ide> $this->assertTrue(Validation::dateTime($dateTime)); <add> <add> $dateTime = new \DateTimeImmutable(); <add> $this->assertTrue(Validation::date($dateTime)); <add> $this->assertTrue(Validation::time($dateTime)); <add> $this->assertTrue(Validation::dateTime($dateTime)); <ide> } <ide> <ide> /**
2
Javascript
Javascript
fix situation where build can hang indefinitely
841cd6c4d78abdf8bee8fa64feb2f401db45a5d2
<ide><path>packages/next/build/webpack/plugins/terser-webpack-plugin/src/TaskRunner.js <ide> export default class TaskRunner { <ide> const done = () => step(index, result) <ide> if (cachePath) { <ide> writeFileP(cachePath, JSON.stringify(result), 'utf8') <del> .then(done) <del> .catch(done) <add> // This is important to stay as `.then(fn1, fn2)` and not <add> // `.then(fn1).catch(fn2)` so that we don't double-invoke `step` <add> // when `done` emits an error. <add> .then(done, done) <add> .catch(err => { <add> // Abort task on internal error (`done` failed). This can <add> // happen when users have a bad `package-lock.json` with an <add> // invalid webpack version, etc: <add> callback(err) <add> }) <ide> } <ide> } catch (error) { <ide> step(index, { error }) <ide> } <ide> } <ide> <ide> if (this.cacheDir) { <del> readFileP(cachePath, 'utf8') <del> .then(data => step(index, JSON.parse(data))) <del> .catch(() => enqueue()) <add> // This is important to stay as `.then(fn1, fn2)` and not <add> // `.then(fn1).catch(fn2)` so that we don't double-invoke `step` when <add> // `step` emits an error. <add> readFileP(cachePath, 'utf8').then( <add> data => { <add> try { <add> step(index, JSON.parse(data)) <add> } catch (err) { <add> // Abort task on internal error (`done` failed). This can happen <add> // when users have a bad `package-lock.json` with an invalid <add> // webpack version, etc: <add> callback(err) <add> } <add> }, <add> () => enqueue() <add> ) <ide> } else { <ide> enqueue() <ide> } <ide><path>packages/next/build/webpack/plugins/terser-webpack-plugin/src/index.js <ide> import stringHash from 'next/dist/compiled/string-hash' <ide> import { SourceMapConsumer } from 'next/dist/compiled/source-map' <ide> import { SourceMapSource, RawSource } from 'webpack-sources' <del>import { RequestShortener } from 'webpack' <add>import RequestShortener from 'webpack/lib/RequestShortener' <ide> import TaskRunner from './TaskRunner' <ide> <ide> const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/ <ide> export class TerserPlugin { <ide> <ide> taskRunner.run(tasks, (tasksError, results) => { <ide> if (tasksError) { <del> compilation.errors.push(tasksError) <del> <add> try { <add> taskRunner.exit() <add> } finally { <add> callback(tasksError) <add> } <ide> return <ide> } <ide>
2
Javascript
Javascript
add missing test/mocks.js
3f0a37f380e262fa86689f06c0801ae54d8a0983
<ide><path>test/mocks.js <add>/** <add> * Mock implementation of {@link angular.service.$log} that gathers all logged messages in arrays <add> * (one array per logging level). These arrays are exposed as `logs` property of each of the <add> * level-specific log function, e.g. for level `error` the array is exposed as <add> * `$logMock.error.logs` <add> * <add> * Please note that this is not a factory function, but rather the actual mock instance. This is <add> * important because it allows `beforeEach` and `afterEach` test hooks to clean up or check the <add> * state of `logs` arrays in between tests. <add> * <add> * Exposing the instance in this way makes this mock a singleton, which means that the instance <add> * becomes global state for tests. To mitigate the issue, each time the `$log` mock is registered <add> * with the injector, a check is performed to ensure that there are no pending logs in `logs` <add> * arrays. This means that if a message is logged via $log during a test, the `logs` array must be <add> * emptied before the test is finished. `Array#shift` method can be used for this purpose as <add> * follows: <add> * <add> * <pre> <add> * it('should do some good', function() { <add> * var scope = angular.scope(), <add> * $log = scope.$service('$log'); <add> * <add> * //do something that triggers a message to be logged <add> * expect($log.error.logs.shift()).toEqual(['message', 'arg1', 'arg2']); <add> * }); <add> * </pre> <add> * <add> * See {@link angular.mock} for more info on angular mocks. <add> */ <add>var $logMock = { <add> log: function log(){ log.logs.push(arguments) }, <add> warn: function warn(){ warn.logs.push(arguments) }, <add> info: function info(){ info.logs.push(arguments) }, <add> error: function error(){ error.logs.push(arguments) } <add>}; <add>$logMock.log.logs = []; <add>$logMock.warn.logs = []; <add>$logMock.info.logs = []; <add>$logMock.error.logs = []; <add> <add>angular.service('$log', function() { <add> return $logMock; <add>}); <add> <add> <add>/** <add> * Factory that returns mock implementation of {@link angular.service.$exceptionHandler} that <add> * gathers all errors in an array. This array is exposed as `errors` property of the mock and can be <add> * accessed as `$exceptionHandler.errors`. <add> * <add> * Note that this factory is not registered with angular's injector by default (as opposed to <add> * `$logMock`). It is your responsibility to register this factory when you need it. Typically like <add> * this: <add> * <add> * <pre> <add> * var scope = angular.scope(null, {'$exceptionHandler': $exceptionHandlerMockFactory}); <add> * </pre> <add> * <add> */ <add>function $exceptionHandlerMockFactory() { <add> function mockHandler(e) { <add> mockHandler.errors.push(e); <add> } <add> mockHandler.errors = []; <add> <add> return mockHandler; <add>} <ide>\ No newline at end of file
1
Ruby
Ruby
define just the cattr_reader
1c8539da4738d51795422903b84f79705bc854cc
<ide><path>actionpack/lib/action_view/digestor.rb <ide> class Digestor <ide> ([@a-z"'][@a-z_\/\."']+) # the template name itself -- 2nd capture <ide> /x <ide> <del> cattr_accessor(:cache) { Hash.new } <add> cattr_reader(:cache) <add> @@cache = Hash.new <ide> <ide> def self.digest(name, format, finder, options = {}) <ide> cache["#{name}.#{format}"] ||= new(name, format, finder, options).digest
1
Ruby
Ruby
simplify rendering of environment variables
d8eab8c2114f8f89decb4293283ec747f82f9d08
<ide><path>Library/Homebrew/cask/lib/hbc/cli/doctor.rb <ide> def self.run <ide> ohai "Homebrew-Cask Staging Location:", render_staging_location(Hbc.caskroom) <ide> ohai "Homebrew-Cask Cached Downloads:", render_cached_downloads <ide> ohai "Homebrew-Cask Taps:" <del> puts render_taps(Hbc.default_tap) <del> puts render_taps(*alt_taps) <add> puts render_taps(Hbc.default_tap, *alt_taps) <ide> ohai "Contents of $LOAD_PATH:", render_load_path($LOAD_PATH) <ide> ohai "Environment Variables:" <del> render_env_var("RUBYLIB") <del> render_env_var("RUBYOPT") <del> render_env_var("RUBYPATH") <del> render_env_var("RBENV_VERSION") <del> render_env_var("CHRUBY_VERSION") <del> render_env_var("GEM_HOME") <del> render_env_var("GEM_PATH") <del> render_env_var("BUNDLE_PATH") <del> render_env_var("PATH") <del> render_env_var("SHELL") <del> locale_variables <add> <add> environment_variables = [ <add> "RUBYLIB", <add> "RUBYOPT", <add> "RUBYPATH", <add> "RBENV_VERSION", <add> "CHRUBY_VERSION", <add> "GEM_HOME", <add> "GEM_PATH", <add> "BUNDLE_PATH", <add> "PATH", <add> "SHELL", <add> ] <add> <add> (locale_variables + environment_variables).sort.each(&method(:render_env_var)) <ide> end <ide> <ide> def self.locale_variables <del> ENV.keys.grep(/^(?:LC_\S+|LANG|LANGUAGE)\Z/).sort.each(&method(:render_env_var)) <add> ENV.keys.grep(/^(?:LC_\S+|LANG|LANGUAGE)\Z/).sort <ide> end <ide> <ide> def self.none_string <ide> def self.render_taps(*taps) <ide> end <ide> <ide> def self.render_env_var(var) <del> if ENV.key?(var) <del> var = %Q(#{var}="#{ENV[var]}") <del> puts user_tilde(var) <del> end <add> return unless ENV.key?(var) <add> var = %Q(#{var}="#{ENV[var]}") <add> puts user_tilde(var) <ide> end <ide> <ide> def self.user_tilde(path)
1
PHP
PHP
switch increments to use unsignedbiginteger
a40653328d830b92b464540bc1468b6f183b75d4
<ide><path>src/Illuminate/Database/Schema/Blueprint.php <ide> public function foreign($columns, $name = null) <ide> } <ide> <ide> /** <del> * Create a new auto-incrementing integer (4-byte) column on the table. <add> * Create a new auto-incrementing integer column on the table. <ide> * <ide> * @param string $column <ide> * @return \Illuminate\Database\Schema\ColumnDefinition <ide> */ <ide> public function increments($column) <ide> { <del> return $this->unsignedInteger($column, true); <add> return $this->{Builder::$defaultIncrementsType}($column, true); <ide> } <ide> <ide> /** <ide> public function mediumIncrements($column) <ide> return $this->unsignedMediumInteger($column, true); <ide> } <ide> <add> /** <add> * Create a new auto-incrementing integer (4-byte) column on the table. <add> * <add> * @param string $column <add> * @return \Illuminate\Database\Schema\ColumnDefinition <add> */ <add> public function integerIncrements($column) <add> { <add> return $this->unsignedInteger($column, true); <add> } <add> <ide> /** <ide> * Create a new auto-incrementing big integer (8-byte) column on the table. <ide> * <ide><path>src/Illuminate/Database/Schema/Builder.php <ide> class Builder <ide> */ <ide> public static $defaultStringLength = 255; <ide> <add> /** <add> * The default increments type for migrations. <add> * <add> * @var string <add> */ <add> public static $defaultIncrementsType = 'unsignedBigInteger'; <add> <ide> /** <ide> * Create a new database Schema manager. <ide> * <ide> public static function defaultStringLength($length) <ide> static::$defaultStringLength = $length; <ide> } <ide> <add> /** <add> * Set the default increments type to a 4 byte integer. <add> * <add> * @return void <add> */ <add> public static function useIntegerIncrements() <add> { <add> static::$defaultIncrementsType = 'unsignedInteger'; <add> } <add> <ide> /** <ide> * Determine if the given table exists. <ide> *
2
Text
Text
fix inadvertent double bullets in bulleted lists
dd6b9a2cfadf2b5f98db800d414ac1cb67739a1c
<ide><path>docs/faq/OrganizingState.md <ide> Data with IDs, nesting, or relationships should generally be stored in a “norm <ide> **Documentation** <ide> <ide> - [Redux Fundamentals: Async Logic and Data Flow](../tutorials/fundamentals/part-6-async-logic.md) <del>- - [Redux Fundamentals: Standard Redux Patterns](../tutorials/fundamentals/part-7-standard-patterns.md) <add>- [Redux Fundamentals: Standard Redux Patterns](../tutorials/fundamentals/part-7-standard-patterns.md) <ide> - [Examples: Real World example](../introduction/Examples.md#real-world) <ide> - [Recipes: Structuring Reducers - Prerequisite Concepts](../recipes/structuring-reducers/PrerequisiteConcepts.md#normalizing-data) <ide> - [Recipes: Structuring Reducers - Normalizing State Shape](../recipes/structuring-reducers/NormalizingStateShape.md) <ide><path>docs/faq/Reducers.md <ide> Many users later want to try to share data between two reducers, but find that ` <ide> <ide> - If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data. <ide> - You may need to write some custom functions for handling some of these actions. This may require replacing `combineReducers` with your own top-level reducer function. You can also use a utility such as [reduce-reducers](https://github.com/acdlite/reduce-reducers) to run `combineReducers` to handle most actions, but also run a more specialized reducer for specific actions that cross state slices. <del>- - [Middleware with async logic](../tutorials/fundamentals/part-4-store.md#middleware) such as [redux-thunk](https://github.com/reduxjs/redux-thunk) have access to the entire state through `getState()`. An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice. <add>- [Middleware with async logic](../tutorials/fundamentals/part-4-store.md#middleware) such as [redux-thunk](https://github.com/reduxjs/redux-thunk) have access to the entire state through `getState()`. An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice. <ide> <ide> In general, remember that reducers are just functions—you can organize them and subdivide them any way you want, and you are encouraged to break them down into smaller, reusable functions (“reducer composition”). While you do so, you may pass a custom third argument from a parent reducer if a child reducer needs additional data to calculate its next state. You just need to make sure that together they follow the basic rules of reducers: `(state, action) => newState`, and update state immutably rather than mutating it directly. <ide> <ide><path>docs/tutorials/fundamentals/part-3-state-actions-reducers.md <ide> Let's take a quick look at what the initial project contains: <ide> - `/api` <ide> - `client.js`: a small AJAX request client that allows us to make GET and POST requests <ide> - `server.js`: provides a fake REST API for our data. Our app will fetch data from these fake endpoints later. <del>- - `/exampleAddons`: contains some additional Redux addons that we'll use later in the tutorial to show how things work <add> - `/exampleAddons`: contains some additional Redux addons that we'll use later in the tutorial to show how things work <ide> <ide> If you load the app now, you should see a welcome message, but the rest of the app is otherwise empty. <ide>
3
Ruby
Ruby
add a test for legacy options
f306e56d214587b5ef6f6b5505b34280da19a075
<ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_raises_when_non_formula_constant_exists <ide> Object.send(:remove_const, const) <ide> end <ide> end <add> <add> def test_legacy_options <add> f = formula do <add> url "foo-1.0" <add> <add> def options <add> [["--foo", "desc"], ["--bar", "desc"]] <add> end <add> <add> option "baz" <add> end <add> <add> assert f.option_defined?("foo") <add> assert f.option_defined?("bar") <add> assert f.option_defined?("baz") <add> end <ide> end
1
Javascript
Javascript
add missing parameter to $routechangeerror
3b5fd53e2db3dafedd0f0e65ab272379aff81139
<ide><path>src/ngRoute/route.js <ide> function $RouteProvider(){ <ide> * @description <ide> * Broadcasted if any of the resolve promises are rejected. <ide> * <add> * @param {Object} angularEvent Synthetic event object <ide> * @param {Route} current Current route information. <ide> * @param {Route} previous Previous route information. <ide> * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
1
Javascript
Javascript
add pipeline test for destroy of returned stream
9e3eddc75dde9df9356264b42bd30facb82583cd
<ide><path>test/parallel/test-stream-pipeline.js <ide> const { promisify } = require('util'); <ide> })); <ide> src.push(null); <ide> } <add> <add>{ <add> const src = new PassThrough(); <add> const dst = pipeline( <add> src, <add> async function * (source) { <add> for await (const chunk of source) { <add> yield chunk; <add> } <add> }, <add> common.mustCall((err) => { <add> assert.strictEqual(err.code, 'ERR_STREAM_PREMATURE_CLOSE'); <add> }) <add> ); <add> src.push('asd'); <add> dst.destroy(); <add>}
1
Javascript
Javascript
fix accent mark
9d560507e54612cf2fdd84cbaa117337568a384c
<ide><path>src/locale/es.js <ide> export default moment.defineLocale('es', { <ide> dow: 1, // Monday is the first day of the week. <ide> doy: 4, // The week that contains Jan 4th is the first week of the year. <ide> }, <del> invalidDate: 'Fecha invalida', <add> invalidDate: 'Fecha inválida', <ide> }); <ide><path>src/test/locale/es.js <ide> test('test short months proper', function (assert) { <ide> test('translated invalid date', function (assert) { <ide> assert.equal( <ide> moment('nonsense', 'DD-MMM-YYYY').format(), <del> 'Fecha invalida', <add> 'Fecha inválida', <ide> 'Invalid date should translate' <ide> ); <ide> });
2
Python
Python
add first code for process io / no display
86def8a52a216eaa5dceabc2cc54914b577e1a4f
<ide><path>glances/glances.py <ide> else: <ide> psutil_get_cpu_percent_tag = True <ide> <add>try: <add> # get_io_counter only available on Linux and FreeBSD <add> psutil.Process(os.getpid()).get_io_counters() <add>except Exception: <add> psutil_get_io_counter_tag = False <add>else: <add> psutil_get_io_counter_tag = True <add> <ide> try: <ide> # (phy|virt)mem_usage methods only available with PsUtil 0.3.0+ <ide> psutil.phymem_usage() <ide> def __itemexist__(self, item_type): <ide> return i <ide> return -1 <ide> <del> def add(self, item_state, item_type, item_value): <add> def add(self, item_state, item_type, item_value, proc_list = []): <ide> """ <ide> item_state = "OK|CAREFUL|WARNING|CRITICAL" <ide> item_type = "CPU|LOAD|MEM" <ide> item_value = value <ide> Item is defined by: <ide> ["begin", "end", "WARNING|CRITICAL", "CPU|LOAD|MEM", <del> MAX, AVG, MIN, SUM, COUNT] <add> MAX, AVG, MIN, SUM, COUNT, <add> [top3 process list]] <ide> If item is a 'new one': <ide> Add the new item at the beginning of the logs list <ide> Else: <ide> def add(self, item_state, item_type, item_value): <ide> item.append(item_value) # MIN <ide> item.append(item_value) # SUM <ide> item.append(1) # COUNT <add> item.append([]) # TOP3 PROCESS LIST <ide> self.logs_list.insert(0, item) <ide> if self.len() > self.logs_max: <ide> self.logs_list.pop() <ide> def add(self, item_state, item_type, item_value): <ide> self.logs_list[item_index][5] = ( <ide> self.logs_list[item_index][7] / <ide> self.logs_list[item_index][8]) <add> # TOP3 PROCESS LIST <add> # TODO <add> self.logs_list[item_index][9] = [] <ide> <ide> return self.len() <ide> <ide> def __update__(self): <ide> <ide> # MEM <ide> # !!! TODO <del> # Mem functions Pending deprecation warning in PsUtil 0.5.1 <del> # See the forum: http://bit.ly/LPMXMP <add> # To be replaced by: psutil.virtual_memory() et psutil.swap_memory() <add> # In the PsUtil version 0.6 or higher <ide> # !!! <ide> # <ide> try: <ide> def __update__(self): <ide> try: <ide> self.network_old <ide> except Exception: <del> if psutil_network_io_tag: <del> self.network_old = psutil.network_io_counters(True) <add> self.network_old = psutil.network_io_counters(True) <ide> else: <ide> try: <ide> self.network_new = psutil.network_io_counters(True) <ide> def __update__(self): <ide> procstat = {} <ide> procstat['proc_size'] = proc.get_memory_info().vms <ide> procstat['proc_resident'] = proc.get_memory_info().rss <add> <ide> if psutil_get_cpu_percent_tag: <ide> procstat['cpu_percent'] = \ <ide> proc.get_cpu_percent(interval=0) <add> <ide> procstat['mem_percent'] = proc.get_memory_percent() <add> <add> ### <add> # !!! DID NOT WORK... <add> # Uncomment the following line to test: <add> # tag_io = True (in DisplayProcess) <add> ### <add> if psutil_get_io_counter_tag: <add> self.proc_io_new = proc.get_io_counters() <add> try: <add> # Compute delta <add> procstat['read_bytes'] = self.proc_io_new.read_bytes - self.proc_io_old.read_bytes <add> procstat['write_bytes'] = self.proc_io_new.write_bytes - self.proc_io_old.write_bytes <add> except Exception: <add> pass <add> self.proc_io_old = self.proc_io_new <add> <ide> procstat['pid'] = proc.pid <ide> procstat['uid'] = proc.username <add> <ide> try: <ide> # Deprecated in PsUtil 0.5.0 <ide> procstat['nice'] = proc.nice <ide> except: <ide> # Specific for PsUtil 0.5.0 <ide> procstat['nice'] = proc.get_nice() <add> <ide> procstat['status'] = str(proc.status)[:1].upper() <ide> procstat['proc_time'] = proc.get_cpu_times() <ide> procstat['proc_name'] = proc.name <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> else: <ide> process_x = self.process_x <ide> # Display the process summary <del> if (screen_y > self.process_y + 3 and <add> if (screen_y > self.process_y + 4 and <ide> screen_x > process_x + 48): <ide> # Processes sumary <ide> self.term_window.addnstr(self.process_y, process_x, _("Processes"), <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> str(other), <ide> _("other")), 42) <ide> <del> # Display the process detail <del> tag_pid = False <del> tag_uid = False <del> tag_nice = False <del> tag_status = False <del> tag_proc_time = False <del> if screen_x > process_x + 55: <del> tag_pid = True <del> if screen_x > process_x + 64: <del> tag_uid = True <del> if screen_x > process_x + 70: <del> tag_nice = True <del> if screen_x > process_x + 74: <del> tag_status = True <del> if screen_x > process_x + 77: <del> tag_proc_time = True <del> <ide> # Processes detail <del> if (screen_y > self.process_y + 8 and <add> if (screen_y > self.process_y + 4 and <ide> screen_x > process_x + 49): <add> <add> # Display the process detail <add> tag_pid = False <add> tag_uid = False <add> tag_nice = False <add> tag_status = False <add> tag_proc_time = False <add> tag_io = False <add> if screen_x > process_x + 55: <add> tag_pid = True <add> if screen_x > process_x + 64: <add> tag_uid = True <add> if screen_x > process_x + 70: <add> tag_nice = True <add> if screen_x > process_x + 74: <add> tag_status = True <add> if screen_x > process_x + 77: <add> tag_proc_time = True <add> if screen_x > process_x + 97: <add> # !!! Did not work yet... <add> #~ tag_io = True <add> tag_io = False <add> <ide> # VMS <ide> self.term_window.addnstr( <ide> self.process_y + 2, process_x, <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> self.process_y + 2, process_x + process_name_x, <ide> _("TIME+"), 8) <ide> process_name_x += 10 <add> # IO <add> if tag_io: <add> self.term_window.addnstr( <add> self.process_y + 2, process_x + process_name_x, <add> _("IO Read"), 8) <add> process_name_x += 10 <add> self.term_window.addnstr( <add> self.process_y + 2, process_x + process_name_x, <add> _("IO Write"), 8) <add> process_name_x += 10 <ide> # PROCESS NAME <ide> self.term_window.addnstr( <ide> self.process_y + 2, process_x + process_name_x, <ide> def displayProcess(self, processcount, processlist, log_count=0): <ide> self.term_window.addnstr( <ide> self.process_y + 3 + processes, process_x + 52, <ide> dtime, 8) <add> # IO <add> if tag_io: <add> # Processes are only refresh every 2 refresh_time <add> elapsed_time = max(1, self.__refresh_time) * 2 <add> io_read = processlist[processes]['read_bytes'] <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 62, <add> self.__autoUnit(io_read / elapsed_time) + "B", <add> 8) <add> io_write = processlist[processes]['write_bytes'] <add> self.term_window.addnstr( <add> self.process_y + 3 + processes, process_x + 72, <add> self.__autoUnit(io_write / elapsed_time) + "B", <add> 8) <ide> # display process command line <ide> max_process_name = screen_x - process_x - process_name_x <ide> process_name = processlist[processes]['proc_name']
1
Java
Java
remove batchedexecutiontime from fabric metrics
bd7df8bdaacfe3d623e66d1624e057a6b728315a
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/FabricUIManager.java <ide> public class FabricUIManager implements UIManager, LifecycleEventListener { <ide> <ide> private long mRunStartTime = 0l; <ide> private long mBatchedExecutionTime = 0l; <del> private long mNonBatchedExecutionTime = 0l; <ide> private long mDispatchViewUpdatesTime = 0l; <ide> private long mCommitStartTime = 0l; <ide> private long mLayoutTime = 0l; <ide> private void dispatchMountItems() { <ide> <ide> @UiThread <ide> private void dispatchPreMountItems(long frameTimeNanos) { <del> long nonBatchedExecutionStartTime = SystemClock.uptimeMillis(); <ide> Systrace.beginSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE, "FabricUIManager::premountViews"); <ide> <ide> while (true) { <ide> private void dispatchPreMountItems(long frameTimeNanos) { <ide> <ide> preMountItemsToDispatch.execute(mMountingManager); <ide> } <del> mNonBatchedExecutionTime = SystemClock.uptimeMillis() - nonBatchedExecutionStartTime; <ide> Systrace.endSection(Systrace.TRACE_TAG_REACT_JAVA_BRIDGE); <ide> } <ide> <ide> public Map<String, Long> getPerformanceCounters() { <ide> performanceCounters.put("DispatchViewUpdatesTime", mDispatchViewUpdatesTime); <ide> performanceCounters.put("RunStartTime", mRunStartTime); <ide> performanceCounters.put("BatchedExecutionTime", mBatchedExecutionTime); <del> performanceCounters.put("NonBatchedExecutionTime", mNonBatchedExecutionTime); <ide> performanceCounters.put("FinishFabricTransactionTime", mFinishTransactionTime); <ide> performanceCounters.put("FinishFabricTransactionCPPTime", mFinishTransactionCPPTime); <ide> return performanceCounters;
1
Text
Text
update external links in security guide
27e6fba1f4a50c4b581c8f30a75b5f4066d562ce
<ide><path>guides/source/security.md <ide> Hence, the cookie serves as temporary authentication for the web application. An <ide> <ide> * Instead of stealing a cookie unknown to the attacker, they fix a user's session identifier (in the cookie) known to them. Read more about this so-called session fixation later. <ide> <del>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from 0.5%-10% of account balance, $0.5-$30 for credit card numbers ($20-$60 with full details), $0.1-$1.5 for identities (Name, SSN, and DOB), $20-$50 for retailer accounts, and $6-$10 for cloud service provider accounts, according to the [Symantec Internet Security Threat Report (2017)](https://www.symantec.com/content/dam/symantec/docs/reports/istr-22-2017-en.pdf). <add>The main objective of most attackers is to make money. The underground prices for stolen bank login accounts range from 0.5%-10% of account balance, $0.5-$30 for credit card numbers ($20-$60 with full details), $0.1-$1.5 for identities (Name, SSN, and DOB), $20-$50 for retailer accounts, and $6-$10 for cloud service provider accounts, according to the [Symantec Internet Security Threat Report (2017)](https://docs.broadcom.com/docs/istr-22-2017-en). <ide> <ide> ### Session Storage <ide> <ide> SELECT * FROM projects WHERE (name = '') UNION <ide> <ide> The result won't be a list of projects (because there is no project with an empty name), but a list of user names and their password. So hopefully you encrypted the passwords in the database! The only problem for the attacker is, that the number of columns has to be the same in both queries. That's why the second query includes a list of ones (1), which will be always the value 1, in order to match the number of columns in the first query. <ide> <del>Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails [to at least 2.1.1](http://www.rorsecurity.info/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter/). <add>Also, the second query renames some columns with the AS statement so that the web application displays the values from the user table. Be sure to update your Rails [to at least 2.1.1](https://rorsecurity.info/journal/2008/09/08/sql-injection-issue-in-limit-and-offset-parameter.html). <ide> <ide> #### Countermeasures <ide> <ide> Instead of passing a string to the conditions option, you can pass an array to s <ide> Model.where("login = ? AND password = ?", entered_user_name, entered_password).first <ide> ``` <ide> <del>As you can see, the first part of the array is an SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result: <add>As you can see, the first part of the array is a SQL fragment with question marks. The sanitized versions of the variables in the second part of the array replace the question marks. Or you can pass a hash for the same result: <ide> <ide> ```ruby <ide> Model.where(login: entered_user_name, password: entered_password).first <ide> The most common entry points are message posts, user comments, and guest books, <ide> <ide> XSS attacks work like this: An attacker injects some code, the web application saves it and displays it on a page, later presented to a victim. Most XSS examples simply display an alert box, but it is more powerful than that. XSS can steal the cookie, hijack the session, redirect the victim to a fake website, display advertisements for the benefit of the attacker, change elements on the web site to get confidential information or install malicious software through security holes in the web browser. <ide> <del>During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The [Symantec Global Internet Security threat report](http://eval.symantec.com/mktginfo/enterprise/white_papers/b-whitepaper_internet_security_threat_report_xiii_04-2008.en-us.pdf) also documented 239 browser plug-in vulnerabilities in the last six months of 2007. [Mpack](http://pandalabs.pandasecurity.com/mpack-uncovered/) is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit an SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high profile targets. <add>During the second half of 2007, there were 88 vulnerabilities reported in Mozilla browsers, 22 in Safari, 18 in IE, and 12 in Opera. The Symantec Global Internet Security threat report also documented 239 browser plug-in vulnerabilities in the last six months of 2007. [Mpack](https://www.pandasecurity.com/en/mediacenter/malware/mpack-uncovered/) is a very active and up-to-date attack framework which exploits these vulnerabilities. For criminal hackers, it is very attractive to exploit a SQL-Injection vulnerability in a web application framework and insert malicious code in every textual table column. In April 2008 more than 510,000 sites were hacked like this, among them the British government, United Nations, and many more high profile targets. <ide> <ide> #### HTML/JavaScript Injection <ide> <ide> The log files on www.attacker.com will read like this: <ide> GET http://www.attacker.com/_app_session=836c1c25278e5b321d6bea4f19cb57e2 <ide> ``` <ide> <del>You can mitigate these attacks (in the obvious way) by adding the **httpOnly** flag to cookies, so that `document.cookie` may not be read by JavaScript. HTTP only cookies can be used from IE v6.SP1, Firefox v2.0.0.5, Opera 9.5, Safari 4, and Chrome 1.0.154 onwards. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](https://www.owasp.org/index.php/HTTPOnly#Browsers_Supporting_HttpOnly), though. <add>You can mitigate these attacks (in the obvious way) by adding the **httpOnly** flag to cookies, so that `document.cookie` may not be read by JavaScript. HTTP only cookies can be used from IE v6.SP1, Firefox v2.0.0.5, Opera 9.5, Safari 4, and Chrome 1.0.154 onwards. But other, older browsers (such as WebTV and IE 5.5 on Mac) can actually cause the page to fail to load. Be warned that cookies [will still be visible using Ajax](https://owasp.org/www-community/HttpOnly#browsers-supporting-httponly), though. <ide> <ide> ##### Defacement <ide> <ide> This example pops up a message box. It will be recognized by the above `sanitize <ide> <ide> _In order to understand today's attacks on web applications, it's best to take a look at some real-world attack vectors._ <ide> <del>The following is an excerpt from the [Js.Yamanner@m](http://www.symantec.com/security_response/writeup.jsp?docid=2006-061211-4111-99&tabid=1) Yahoo! Mail [worm](http://groovin.net/stuff/yammer.txt). It appeared on June 11, 2006 and was the first webmail interface worm: <add>The following is an excerpt from the [Js.Yamanner@m Yahoo! Mail worm](https://community.broadcom.com/symantecenterprise/communities/community-home/librarydocuments/viewdocument?DocumentKey=12d8d106-1137-4d7c-8bb4-3ea1faec83fa). It appeared on June 11, 2006 and was the first webmail interface worm: <ide> <ide> ```html <ide> <img src='http://us.i1.yimg.com/us.yimg.com/i/us/nt/ma/ma_mail_1.gif' <ide> Another problem for the worm's author was the [CSRF security tokens](#cross-site <ide> <ide> In the end, he got a 4 KB worm, which he injected into his profile page. <ide> <del>The [moz-binding](https://www.securiteam.com/securitynews/5LP051FHPE.html) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example). <add>The [moz-binding](https://securiteam.com/securitynews/5LP051FHPE) CSS property proved to be another way to introduce JavaScript in CSS in Gecko-based browsers (Firefox, for example). <ide> <ide> #### Countermeasures <ide> <ide> This example, again, showed that a restricted list filter is never complete. How <ide> <ide> If you want to provide text formatting other than HTML (due to security), use a mark-up language which is converted to HTML on the server-side. [RedCloth](http://redcloth.org/) is such a language for Ruby, but without precautions, it is also vulnerable to XSS. <ide> <del>For example, RedCloth translates `_test_` to `<em>test<em>`, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the [all-new version 4](http://www.redcloth.org) that removed serious bugs. However, even that version has [some security bugs](http://www.rorsecurity.info/journal/2008/10/13/new-redcloth-security.html), so the countermeasures still apply. Here is an example for version 3.0.4: <add>For example, RedCloth translates `_test_` to `<em>test<em>`, which makes the text italic. However, up to the current version 3.0.4, it is still vulnerable to XSS. Get the [all-new version 4](http://www.redcloth.org) that removed serious bugs. However, even that version has [some security bugs](https://rorsecurity.info/journal/2008/10/13/new-redcloth-security.html), so the countermeasures still apply. Here is an example for version 3.0.4: <ide> <ide> ```ruby <ide> RedCloth.new('<script>alert(1)</script>').to_html <ide> Here is a list of common headers: <ide> * **X-Frame-Options:** _`SAMEORIGIN` in Rails by default_ - allow framing on same domain. Set it to 'DENY' to deny framing at all or remove this header completely if you want to allow framing on all websites. <ide> * **X-XSS-Protection:** _`1; mode=block` in Rails by default_ - use XSS Auditor and block page if XSS attack is detected. Set it to '0;' if you want to switch XSS Auditor off(useful if response contents scripts from request parameters) <ide> * **X-Content-Type-Options:** _`nosniff` in Rails by default_ - stops the browser from guessing the MIME type of a file. <del>* **X-Content-Security-Policy:** [A powerful mechanism for controlling which sites certain content types can be loaded from](http://w3c.github.io/webappsec/specs/content-security-policy/csp-specification.dev.html) <add>* **X-Content-Security-Policy:** [A powerful mechanism for controlling which sites certain content types can be loaded from](https://w3c.github.io/webappsec-csp/) <ide> * **Access-Control-Allow-Origin:** Used to control which sites are allowed to bypass same origin policies and send cross-origin requests. <ide> * **Strict-Transport-Security:** [Used to control if the browser is allowed to only access a site over a secure connection](https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security) <ide> <ide> The security landscape shifts and it is important to keep up to date, because mi <ide> * Subscribe to the Rails security [mailing list](https://groups.google.com/forum/#!forum/rubyonrails-security). <ide> * [Brakeman - Rails Security Scanner](https://brakemanscanner.org/) - To perform static security analysis for Rails applications. <ide> * [Mozilla's Web Security Guidelines](https://infosec.mozilla.org/guidelines/web_security.html) - Recommendations on topics covering Content Security Policy, HTTP headers, Cookies, TLS configuration, etc. <del>* A [good security blog](https://www.owasp.org) including the [Cross-Site scripting Cheat Sheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md). <add>* A [good security blog](https://owasp.org/) including the [Cross-Site scripting Cheat Sheet](https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.md).
1
Python
Python
remove unneeded assignment of variable
52c6516509ea40493b888aad08f49961635f5fc8
<ide><path>airflow/contrib/sensors/bash_sensor.py <ide> def poke(self, context): <ide> self.sp = sp <ide> <ide> self.log.info("Output:") <del> line = '' <ide> for line in iter(sp.stdout.readline, b''): <ide> line = line.decode(self.output_encoding).strip() <ide> self.log.info(line)
1
Javascript
Javascript
add block scoping to test-readline-interface
daf5596c279bca8a461b8f573e9bdfb93acb539d
<ide><path>test/parallel/test-readline-interface.js <ide> function isWarned(emitter) { <ide> } <ide> <ide> [ true, false ].forEach(function(terminal) { <del> let fi; <del> let rli; <del> let called; <del> <ide> // disable history <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal, <del> historySize: 0 }); <del> assert.strictEqual(rli.historySize, 0); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal, historySize: 0 } <add> ); <add> assert.strictEqual(rli.historySize, 0); <ide> <del> fi.emit('data', 'asdf\n'); <del> assert.deepStrictEqual(rli.history, terminal ? [] : undefined); <del> rli.close(); <add> fi.emit('data', 'asdf\n'); <add> assert.deepStrictEqual(rli.history, terminal ? [] : undefined); <add> rli.close(); <add> } <ide> <ide> // default history size 30 <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> assert.strictEqual(rli.historySize, 30); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> assert.strictEqual(rli.historySize, 30); <ide> <del> fi.emit('data', 'asdf\n'); <del> assert.deepStrictEqual(rli.history, terminal ? ['asdf'] : undefined); <del> rli.close(); <add> fi.emit('data', 'asdf\n'); <add> assert.deepStrictEqual(rli.history, terminal ? ['asdf'] : undefined); <add> rli.close(); <add> } <ide> <ide> // sending a full line <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> called = false; <del> rli.on('line', function(line) { <del> called = true; <del> assert.strictEqual(line, 'asdf'); <del> }); <del> fi.emit('data', 'asdf\n'); <del> assert.ok(called); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> let called = false; <add> rli.on('line', function(line) { <add> called = true; <add> assert.strictEqual(line, 'asdf'); <add> }); <add> fi.emit('data', 'asdf\n'); <add> assert.ok(called); <add> } <ide> <ide> // sending a blank line <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> called = false; <del> rli.on('line', function(line) { <del> called = true; <del> assert.strictEqual(line, ''); <del> }); <del> fi.emit('data', '\n'); <del> assert.ok(called); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> let called = false; <add> rli.on('line', function(line) { <add> called = true; <add> assert.strictEqual(line, ''); <add> }); <add> fi.emit('data', '\n'); <add> assert.ok(called); <add> } <ide> <ide> // sending a single character with no newline <del> fi = new FakeInput(); <del> rli = new readline.Interface(fi, {}); <del> called = false; <del> rli.on('line', function(line) { <del> called = true; <del> }); <del> fi.emit('data', 'a'); <del> assert.ok(!called); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface(fi, {}); <add> let called = false; <add> rli.on('line', function(line) { <add> called = true; <add> }); <add> fi.emit('data', 'a'); <add> assert.ok(!called); <add> rli.close(); <add> } <ide> <ide> // sending a single character with no newline and then a newline <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> called = false; <del> rli.on('line', function(line) { <del> called = true; <del> assert.strictEqual(line, 'a'); <del> }); <del> fi.emit('data', 'a'); <del> assert.ok(!called); <del> fi.emit('data', '\n'); <del> assert.ok(called); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> let called = false; <add> rli.on('line', function(line) { <add> called = true; <add> assert.strictEqual(line, 'a'); <add> }); <add> fi.emit('data', 'a'); <add> assert.ok(!called); <add> fi.emit('data', '\n'); <add> assert.ok(called); <add> rli.close(); <add> } <ide> <ide> // sending multiple newlines at once <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> let expectedLines = ['foo', 'bar', 'baz']; <del> let callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', `${expectedLines.join('\n')}\n`); <del> assert.strictEqual(callCount, expectedLines.length); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo', 'bar', 'baz']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', `${expectedLines.join('\n')}\n`); <add> assert.strictEqual(callCount, expectedLines.length); <add> rli.close(); <add> } <ide> <ide> // sending multiple newlines at once that does not end with a new line <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> expectedLines = ['foo', 'bar', 'baz', 'bat']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', expectedLines.join('\n')); <del> assert.strictEqual(callCount, expectedLines.length - 1); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo', 'bar', 'baz', 'bat']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', expectedLines.join('\n')); <add> assert.strictEqual(callCount, expectedLines.length - 1); <add> rli.close(); <add> } <ide> <ide> // sending multiple newlines at once that does not end with a new(empty) <ide> // line and a `end` event <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> expectedLines = ['foo', 'bar', 'baz', '']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> rli.on('close', function() { <del> callCount++; <del> }); <del> fi.emit('data', expectedLines.join('\n')); <del> fi.emit('end'); <del> assert.strictEqual(callCount, expectedLines.length); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo', 'bar', 'baz', '']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> rli.on('close', function() { <add> callCount++; <add> }); <add> fi.emit('data', expectedLines.join('\n')); <add> fi.emit('end'); <add> assert.strictEqual(callCount, expectedLines.length); <add> rli.close(); <add> } <ide> <ide> // sending multiple newlines at once that does not end with a new line <ide> // and a `end` event(last line is) <ide> <ide> // \r\n should emit one line event, not two <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> expectedLines = ['foo', 'bar', 'baz', 'bat']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', expectedLines.join('\r\n')); <del> assert.strictEqual(callCount, expectedLines.length - 1); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo', 'bar', 'baz', 'bat']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', expectedLines.join('\r\n')); <add> assert.strictEqual(callCount, expectedLines.length - 1); <add> rli.close(); <add> } <ide> <ide> // \r\n should emit one line event when split across multiple writes. <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> expectedLines = ['foo', 'bar', 'baz', 'bat']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> expectedLines.forEach(function(line) { <del> fi.emit('data', `${line}\r`); <del> fi.emit('data', '\n'); <del> }); <del> assert.strictEqual(callCount, expectedLines.length); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo', 'bar', 'baz', 'bat']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> expectedLines.forEach(function(line) { <add> fi.emit('data', `${line}\r`); <add> fi.emit('data', '\n'); <add> }); <add> assert.strictEqual(callCount, expectedLines.length); <add> rli.close(); <add> } <ide> <ide> // \r should behave like \n when alone <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: true }); <del> expectedLines = ['foo', 'bar', 'baz', 'bat']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', expectedLines.join('\r')); <del> assert.strictEqual(callCount, expectedLines.length - 1); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: true } <add> ); <add> const expectedLines = ['foo', 'bar', 'baz', 'bat']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', expectedLines.join('\r')); <add> assert.strictEqual(callCount, expectedLines.length - 1); <add> rli.close(); <add> } <ide> <ide> // \r at start of input should output blank line <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: true }); <del> expectedLines = ['', 'foo' ]; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', '\rfoo\r'); <del> assert.strictEqual(callCount, expectedLines.length); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: true } <add> ); <add> const expectedLines = ['', 'foo' ]; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', '\rfoo\r'); <add> assert.strictEqual(callCount, expectedLines.length); <add> rli.close(); <add> } <ide> <ide> // Emit two line events when the delay <ide> // between \r and \n exceeds crlfDelay <ide> function isWarned(emitter) { <ide> <ide> // \t when there is no completer function should behave like an ordinary <ide> // character <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: true }); <del> called = false; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, '\t'); <del> assert.strictEqual(called, false); <del> called = true; <del> }); <del> fi.emit('data', '\t'); <del> fi.emit('data', '\n'); <del> assert.ok(called); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: true } <add> ); <add> let called = false; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, '\t'); <add> assert.strictEqual(called, false); <add> called = true; <add> }); <add> fi.emit('data', '\t'); <add> fi.emit('data', '\n'); <add> assert.ok(called); <add> rli.close(); <add> } <ide> <ide> // \t does not become part of the input when there is a completer function <del> fi = new FakeInput(); <del> const completer = (line) => [[], line]; <del> rli = new readline.Interface({ <del> input: fi, <del> output: fi, <del> terminal: true, <del> completer: completer <del> }); <del> called = false; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, 'foo'); <del> assert.strictEqual(called, false); <del> called = true; <del> }); <del> for (const character of '\tfo\to\t') { <del> fi.emit('data', character); <add> { <add> const fi = new FakeInput(); <add> const completer = (line) => [[], line]; <add> const rli = new readline.Interface({ <add> input: fi, <add> output: fi, <add> terminal: true, <add> completer: completer <add> }); <add> let called = false; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, 'foo'); <add> assert.strictEqual(called, false); <add> called = true; <add> }); <add> for (const character of '\tfo\to\t') { <add> fi.emit('data', character); <add> } <add> fi.emit('data', '\n'); <add> assert.ok(called); <add> rli.close(); <ide> } <del> fi.emit('data', '\n'); <del> assert.ok(called); <del> rli.close(); <ide> <ide> // constructor throws if completer is not a function or undefined <del> fi = new FakeInput(); <del> assert.throws(function() { <del> readline.createInterface({ <del> input: fi, <del> completer: 'string is not valid' <del> }); <del> }, common.expectsError({ <del> type: TypeError, <del> code: 'ERR_INVALID_OPT_VALUE' <del> })); <add> { <add> const fi = new FakeInput(); <add> assert.throws(function() { <add> readline.createInterface({ <add> input: fi, <add> completer: 'string is not valid' <add> }); <add> }, common.expectsError({ <add> type: TypeError, <add> code: 'ERR_INVALID_OPT_VALUE' <add> })); <add> } <ide> <ide> // duplicate lines are removed from history when <ide> // `options.removeHistoryDuplicates` is `true` <del> fi = new FakeInput(); <del> rli = new readline.Interface({ <del> input: fi, <del> output: fi, <del> terminal: true, <del> removeHistoryDuplicates: true <del> }); <del> expectedLines = ['foo', 'bar', 'baz', 'bar', 'bat', 'bat']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', `${expectedLines.join('\n')}\n`); <del> assert.strictEqual(callCount, expectedLines.length); <del> fi.emit('keypress', '.', { name: 'up' }); // 'bat' <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'bar' <del> assert.notStrictEqual(rli.line, expectedLines[--callCount]); <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'baz' <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'foo' <del> assert.notStrictEqual(rli.line, expectedLines[--callCount]); <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> assert.strictEqual(callCount, 0); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface({ <add> input: fi, <add> output: fi, <add> terminal: true, <add> removeHistoryDuplicates: true <add> }); <add> const expectedLines = ['foo', 'bar', 'baz', 'bar', 'bat', 'bat']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', `${expectedLines.join('\n')}\n`); <add> assert.strictEqual(callCount, expectedLines.length); <add> fi.emit('keypress', '.', { name: 'up' }); // 'bat' <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'bar' <add> assert.notStrictEqual(rli.line, expectedLines[--callCount]); <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'baz' <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'foo' <add> assert.notStrictEqual(rli.line, expectedLines[--callCount]); <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> assert.strictEqual(callCount, 0); <add> rli.close(); <add> } <ide> <ide> // duplicate lines are not removed from history when <ide> // `options.removeHistoryDuplicates` is `false` <del> fi = new FakeInput(); <del> rli = new readline.Interface({ <del> input: fi, <del> output: fi, <del> terminal: true, <del> removeHistoryDuplicates: false <del> }); <del> expectedLines = ['foo', 'bar', 'baz', 'bar', 'bat', 'bat']; <del> callCount = 0; <del> rli.on('line', function(line) { <del> assert.strictEqual(line, expectedLines[callCount]); <del> callCount++; <del> }); <del> fi.emit('data', `${expectedLines.join('\n')}\n`); <del> assert.strictEqual(callCount, expectedLines.length); <del> fi.emit('keypress', '.', { name: 'up' }); // 'bat' <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'bar' <del> assert.notStrictEqual(rli.line, expectedLines[--callCount]); <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'baz' <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'bar' <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> fi.emit('keypress', '.', { name: 'up' }); // 'foo' <del> assert.strictEqual(rli.line, expectedLines[--callCount]); <del> assert.strictEqual(callCount, 0); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface({ <add> input: fi, <add> output: fi, <add> terminal: true, <add> removeHistoryDuplicates: false <add> }); <add> const expectedLines = ['foo', 'bar', 'baz', 'bar', 'bat', 'bat']; <add> let callCount = 0; <add> rli.on('line', function(line) { <add> assert.strictEqual(line, expectedLines[callCount]); <add> callCount++; <add> }); <add> fi.emit('data', `${expectedLines.join('\n')}\n`); <add> assert.strictEqual(callCount, expectedLines.length); <add> fi.emit('keypress', '.', { name: 'up' }); // 'bat' <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'bar' <add> assert.notStrictEqual(rli.line, expectedLines[--callCount]); <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'baz' <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'bar' <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> fi.emit('keypress', '.', { name: 'up' }); // 'foo' <add> assert.strictEqual(rli.line, expectedLines[--callCount]); <add> assert.strictEqual(callCount, 0); <add> rli.close(); <add> } <ide> <ide> // sending a multi-byte utf8 char over multiple writes <del> const buf = Buffer.from('☮', 'utf8'); <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> callCount = 0; <del> rli.on('line', function(line) { <del> callCount++; <del> assert.strictEqual(line, buf.toString('utf8')); <del> }); <del> [].forEach.call(buf, function(i) { <del> fi.emit('data', Buffer.from([i])); <del> }); <del> assert.strictEqual(callCount, 0); <del> fi.emit('data', '\n'); <del> assert.strictEqual(callCount, 1); <del> rli.close(); <add> { <add> const buf = Buffer.from('☮', 'utf8'); <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> let callCount = 0; <add> rli.on('line', function(line) { <add> callCount++; <add> assert.strictEqual(line, buf.toString('utf8')); <add> }); <add> [].forEach.call(buf, function(i) { <add> fi.emit('data', Buffer.from([i])); <add> }); <add> assert.strictEqual(callCount, 0); <add> fi.emit('data', '\n'); <add> assert.strictEqual(callCount, 1); <add> rli.close(); <add> } <ide> <ide> // Regression test for repl freeze, #1968: <ide> // check that nothing fails if 'keypress' event throws. <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: true }); <del> const keys = []; <del> fi.on('keypress', function(key) { <del> keys.push(key); <del> if (key === 'X') { <del> throw new Error('bad thing happened'); <del> } <del> }); <del> try { <del> fi.emit('data', 'fooX'); <del> } catch (e) { } <del> fi.emit('data', 'bar'); <del> assert.strictEqual(keys.join(''), 'fooXbar'); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: true } <add> ); <add> const keys = []; <add> fi.on('keypress', function(key) { <add> keys.push(key); <add> if (key === 'X') { <add> throw new Error('bad thing happened'); <add> } <add> }); <add> try { <add> fi.emit('data', 'fooX'); <add> } catch (e) { } <add> fi.emit('data', 'bar'); <add> assert.strictEqual(keys.join(''), 'fooXbar'); <add> rli.close(); <add> } <ide> <ide> // calling readline without `new` <del> fi = new FakeInput(); <del> rli = readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> called = false; <del> rli.on('line', function(line) { <del> called = true; <del> assert.strictEqual(line, 'asdf'); <del> }); <del> fi.emit('data', 'asdf\n'); <del> assert.ok(called); <del> rli.close(); <add> { <add> const fi = new FakeInput(); <add> const rli = readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> let called = false; <add> rli.on('line', function(line) { <add> called = true; <add> assert.strictEqual(line, 'asdf'); <add> }); <add> fi.emit('data', 'asdf\n'); <add> assert.ok(called); <add> rli.close(); <add> } <ide> <ide> if (terminal) { <ide> // question <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> expectedLines = ['foo']; <del> rli.question(expectedLines[0], function() { <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo']; <add> rli.question(expectedLines[0], function() { <add> rli.close(); <add> }); <add> const cursorPos = rli._getCursorPos(); <add> assert.strictEqual(cursorPos.rows, 0); <add> assert.strictEqual(cursorPos.cols, expectedLines[0].length); <ide> rli.close(); <del> }); <del> let cursorPos = rli._getCursorPos(); <del> assert.strictEqual(cursorPos.rows, 0); <del> assert.strictEqual(cursorPos.cols, expectedLines[0].length); <del> rli.close(); <add> } <ide> <ide> // sending a multi-line question <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: fi, terminal: terminal }); <del> expectedLines = ['foo', 'bar']; <del> rli.question(expectedLines.join('\n'), function() { <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: fi, terminal: terminal } <add> ); <add> const expectedLines = ['foo', 'bar']; <add> rli.question(expectedLines.join('\n'), function() { <add> rli.close(); <add> }); <add> const cursorPos = rli._getCursorPos(); <add> assert.strictEqual(cursorPos.rows, expectedLines.length - 1); <add> assert.strictEqual(cursorPos.cols, expectedLines.slice(-1)[0].length); <ide> rli.close(); <del> }); <del> cursorPos = rli._getCursorPos(); <del> assert.strictEqual(cursorPos.rows, expectedLines.length - 1); <del> assert.strictEqual(cursorPos.cols, expectedLines.slice(-1)[0].length); <del> rli.close(); <add> } <ide> } <ide> <ide> // isFullWidthCodePoint() should return false for non-numeric values <ide> function isWarned(emitter) { <ide> .getStringWidth('\u001b[31m\u001b[39m'), 0); <ide> assert.strictEqual(internalReadline.getStringWidth('> '), 2); <ide> <del> assert.deepStrictEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); <add> { <add> const fi = new FakeInput(); <add> assert.deepStrictEqual(fi.listeners(terminal ? 'keypress' : 'data'), []); <add> } <ide> <ide> // check EventEmitter memory leak <ide> for (let i = 0; i < 12; i++) { <ide> function isWarned(emitter) { <ide> } <ide> <ide> // can create a new readline Interface with a null output arugument <del> fi = new FakeInput(); <del> rli = new readline.Interface({ input: fi, output: null, terminal: terminal }); <add> { <add> const fi = new FakeInput(); <add> const rli = new readline.Interface( <add> { input: fi, output: null, terminal: terminal } <add> ); <ide> <del> called = false; <del> rli.on('line', function(line) { <del> called = true; <del> assert.strictEqual(line, 'asdf'); <del> }); <del> fi.emit('data', 'asdf\n'); <del> assert.ok(called); <add> let called = false; <add> rli.on('line', function(line) { <add> called = true; <add> assert.strictEqual(line, 'asdf'); <add> }); <add> fi.emit('data', 'asdf\n'); <add> assert.ok(called); <ide> <del> assert.doesNotThrow(function() { <del> rli.setPrompt('ddd> '); <del> }); <add> assert.doesNotThrow(function() { <add> rli.setPrompt('ddd> '); <add> }); <ide> <del> assert.doesNotThrow(function() { <del> rli.prompt(); <del> }); <add> assert.doesNotThrow(function() { <add> rli.prompt(); <add> }); <ide> <del> assert.doesNotThrow(function() { <del> rli.write('really shouldnt be seeing this'); <del> }); <add> assert.doesNotThrow(function() { <add> rli.write('really shouldnt be seeing this'); <add> }); <ide> <del> assert.doesNotThrow(function() { <del> rli.question('What do you think of node.js? ', function(answer) { <del> console.log('Thank you for your valuable feedback:', answer); <del> rli.close(); <add> assert.doesNotThrow(function() { <add> rli.question('What do you think of node.js? ', function(answer) { <add> console.log('Thank you for your valuable feedback:', answer); <add> rli.close(); <add> }); <ide> }); <del> }); <add> } <ide> <ide> { <ide> const expected = terminal ?
1