content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Mixed
Python
fix return type in prev-date context variables
62a5b2dfa41b2928c35be954d13b5ed6e2b5b339
<ide><path>UPDATING.md <ide> This is to align the name with the actual code where the Scheduler launches the <ide> `[scheduler] parsing_processes` to Parse DAG files, calculates next DagRun date for each DAG, <ide> serialize them and store them in the DB. <ide> <add>### Context variables `prev_execution_date_success` and `prev_execution_date_success` are now `pendulum.DateTime` <add> <ide> ## Airflow 2.0.0b1 <ide> <ide> ### Rename policy to task_policy <ide><path>airflow/models/taskinstance.py <ide> def get_previous_execution_date( <ide> """ <ide> self.log.debug("previous_execution_date was called") <ide> prev_ti = self.get_previous_ti(state=state, session=session) <del> return prev_ti and prev_ti.execution_date <add> return prev_ti and pendulum.instance(prev_ti.execution_date) <ide> <ide> @provide_session <ide> def get_previous_start_date( <ide> def get_previous_start_date( <ide> """ <ide> self.log.debug("previous_start_date was called") <ide> prev_ti = self.get_previous_ti(state=state, session=session) <del> return prev_ti and prev_ti.start_date <add> return prev_ti and pendulum.instance(prev_ti.start_date) <ide> <ide> @property <ide> def previous_start_date_success(self) -> Optional[pendulum.DateTime]: <ide><path>tests/operators/test_python.py <ide> def setUp(self): <ide> default_args={'owner': 'airflow', 'start_date': DEFAULT_DATE}, <ide> schedule_interval=INTERVAL, <ide> ) <add> self.dag.create_dagrun( <add> run_type=DagRunType.MANUAL, <add> start_date=timezone.utcnow(), <add> execution_date=DEFAULT_DATE, <add> state=State.RUNNING, <add> ) <ide> self.addCleanup(self.dag.clear) <ide> <add> def tearDown(self): <add> super().tearDown() <add> with create_session() as session: <add> session.query(DagRun).delete() <add> session.query(TI).delete() <add> <ide> def _run_as_operator(self, fn, python_version=sys.version_info[0], **kwargs): <add> <ide> task = PythonVirtualenvOperator( <ide> python_callable=fn, python_version=python_version, task_id='task', dag=self.dag, **kwargs <ide> )
3
PHP
PHP
update redis to return default values
7596faa60c110b1f8507ee8df1f9984d52795eb0
<ide><path>src/Cache/Engine/RedisEngine.php <ide> public function set($key, $value, $ttl = null) <ide> * <ide> * @param string $key Identifier for the data <ide> * @param mixed $default Default value to return if the key does not exist. <del> * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it <add> * @return mixed The cached data, or the default if the data doesn't exist, has <add> * expired, or if there was an error fetching it <ide> */ <ide> public function get($key, $default = null) <ide> { <del> $key = $this->_key($key); <del> <del> $value = $this->_Redis->get($key); <add> $value = $this->_Redis->get($this->_key($key)); <add> if ($value === false) { <add> return $default; <add> } <ide> $isString = is_string($value); <ide> if ($isString && preg_match('/^[-]?\d+$/', $value)) { <ide> return (int)$value; <ide> } <del> if ($value !== false && $isString) { <add> if ($isString) { <ide> return unserialize($value); <ide> } <ide> <ide><path>tests/TestCase/Cache/Engine/RedisEngineTest.php <ide> public function testMultiDatabaseOperations() <ide> $result = Cache::write('save_in_1', true, 'redisdb1'); <ide> $this->assertTrue($result); <ide> $exist = Cache::read('save_in_0', 'redisdb1'); <del> $this->assertFalse($exist); <add> $this->assertNull($exist); <ide> $exist = Cache::read('save_in_1', 'redisdb1'); <ide> $this->assertTrue($exist); <ide> <ide> Cache::delete('save_in_0', 'redisdb0'); <ide> $exist = Cache::read('save_in_0', 'redisdb0'); <del> $this->assertFalse($exist); <add> $this->assertNull($exist); <ide> <ide> Cache::delete('save_in_1', 'redisdb1'); <ide> $exist = Cache::read('save_in_1', 'redisdb1'); <del> $this->assertFalse($exist); <add> $this->assertNull($exist); <ide> <ide> Cache::drop('redisdb0'); <ide> Cache::drop('redisdb1'); <ide> public function testReadAndWriteCache() <ide> Cache::delete('test', 'redis'); <ide> } <ide> <add> /** <add> * Test get with default value <add> * <add> * @return void <add> */ <add> public function testGetDefaultValue() <add> { <add> $redis = Cache::pool('redis'); <add> $this->assertFalse($redis->get('nope', false)); <add> $this->assertNull($redis->get('nope', null)); <add> $this->assertTrue($redis->get('nope', true)); <add> $this->assertSame(0, $redis->get('nope', 0)); <add> <add> $redis->set('yep', 0); <add> $this->assertSame(0, $redis->get('yep', false)); <add> } <add> <ide> /** <ide> * testExpiry method <ide> * <ide> public function testExpiry() <ide> $this->_configCache(['duration' => 1]); <ide> <ide> $result = Cache::read('test', 'redis'); <del> $this->assertFalse($result); <add> $this->assertNull($result); <ide> <ide> $data = 'this is a test of the emergency broadcasting system'; <ide> $result = Cache::write('other_test', $data, 'redis'); <ide> $this->assertTrue($result); <ide> <ide> sleep(2); <ide> $result = Cache::read('other_test', 'redis'); <del> $this->assertFalse($result); <add> $this->assertNull($result); <ide> <ide> $this->_configCache(['duration' => '+1 second']); <ide> <ide> public function testExpiry() <ide> <ide> sleep(2); <ide> $result = Cache::read('other_test', 'redis'); <del> $this->assertFalse($result); <add> $this->assertNull($result); <ide> <ide> sleep(2); <ide> <ide> $result = Cache::read('other_test', 'redis'); <del> $this->assertFalse($result); <add> $this->assertNull($result); <ide> <ide> $this->_configCache(['duration' => '+29 days']); <ide> $data = 'this is a test of the emergency broadcasting system'; <ide> public function testIncrementDecrementExpiring() <ide> <ide> sleep(2); <ide> <del> $this->assertFalse(Cache::read('test_increment', 'redis')); <del> $this->assertFalse(Cache::read('test_decrement', 'redis')); <add> $this->assertNull(Cache::read('test_increment', 'redis')); <add> $this->assertNull(Cache::read('test_decrement', 'redis')); <ide> } <ide> <ide> /** <ide> public function testClear() <ide> Cache::write('some_value', 'cache1', 'redis'); <ide> $result = Cache::clear('redis'); <ide> $this->assertTrue($result); <del> $this->assertFalse(Cache::read('some_value', 'redis')); <add> $this->assertNull(Cache::read('some_value', 'redis')); <ide> <ide> Cache::write('some_value', 'cache2', 'redis2'); <ide> $result = Cache::clear('redis'); <ide> $this->assertTrue($result); <del> $this->assertFalse(Cache::read('some_value', 'redis')); <add> $this->assertNull(Cache::read('some_value', 'redis')); <ide> $this->assertEquals('cache2', Cache::read('some_value', 'redis2')); <ide> <ide> Cache::clear('redis2'); <ide> public function testGroupReadWrite() <ide> $this->assertEquals('value', Cache::read('test_groups', 'redis_groups')); <ide> <ide> Cache::increment('group_a', 1, 'redis_helper'); <del> $this->assertFalse(Cache::read('test_groups', 'redis_groups')); <add> $this->assertNull(Cache::read('test_groups', 'redis_groups')); <ide> $this->assertTrue(Cache::write('test_groups', 'value2', 'redis_groups')); <ide> $this->assertEquals('value2', Cache::read('test_groups', 'redis_groups')); <ide> <ide> Cache::increment('group_b', 1, 'redis_helper'); <del> $this->assertFalse(Cache::read('test_groups', 'redis_groups')); <add> $this->assertNull(Cache::read('test_groups', 'redis_groups')); <ide> $this->assertTrue(Cache::write('test_groups', 'value3', 'redis_groups')); <ide> $this->assertEquals('value3', Cache::read('test_groups', 'redis_groups')); <ide> } <ide> public function testGroupDelete() <ide> $this->assertEquals('value', Cache::read('test_groups', 'redis_groups')); <ide> $this->assertTrue(Cache::delete('test_groups', 'redis_groups')); <ide> <del> $this->assertFalse(Cache::read('test_groups', 'redis_groups')); <add> $this->assertNull(Cache::read('test_groups', 'redis_groups')); <ide> } <ide> <ide> /** <ide> public function testGroupClear() <ide> <ide> $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); <ide> $this->assertTrue(Cache::clearGroup('group_a', 'redis_groups')); <del> $this->assertFalse(Cache::read('test_groups', 'redis_groups')); <add> $this->assertNull(Cache::read('test_groups', 'redis_groups')); <ide> <ide> $this->assertTrue(Cache::write('test_groups', 'value2', 'redis_groups')); <ide> $this->assertTrue(Cache::clearGroup('group_b', 'redis_groups')); <del> $this->assertFalse(Cache::read('test_groups', 'redis_groups')); <add> $this->assertNull(Cache::read('test_groups', 'redis_groups')); <ide> } <ide> <ide> /**
2
PHP
PHP
add random() function to query builder
9197863f0a6304afca17f0d88071bee471cbe949
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function take($value) <ide> return $this->limit($value); <ide> } <ide> <add> /** <add> * Add statements to query to get one or many random records. <add> * <add> * @param int $value <add> * @return $this <add> */ <add> public function random($value = 1) <add> { <add> return $this->orderByRaw('RAND()')->limit($value); <add> } <add> <ide> /** <ide> * Set the limit and offset for a given page. <ide> *
1
Text
Text
add note about latest github release
5815e3e232ef31221f25a9b1997c1f161c5cffdc
<ide><path>doc/contributing/releases.md <ide> This script will use the promoted builds and changelog to generate the post. Run <ide> * Select the tag version you pushed earlier. <ide> * For release title, copy the title from the changelog. <ide> * For the description, copy the rest of the changelog entry. <add>* If you are not releasing the latest "Current", uncheck <add> "Set as the latest release". <ide> * Click on the "Publish release" button. <ide> <ide> ### 19. Cleanup
1
Javascript
Javascript
load the testswarm listener via https
d225639a8ea62863482bd20249077688f60235db
<ide><path>test/data/testinit.js <ide> this.loadTests = function() { <ide> <ide> // Load the TestSwarm listener if swarmURL is in the address. <ide> if ( QUnit.isSwarm ) { <del> require( [ "http://swarm.jquery.org/js/inject.js?" + ( new Date() ).getTime() ], <add> require( [ "https://swarm.jquery.org/js/inject.js?" + ( new Date() ).getTime() ], <ide> function() { <ide> QUnit.start(); <ide> } );
1
Java
Java
update resttemplate javadoc
09b19d7aa6344998fffac70cb9fdf9a3dd775558
<ide><path>spring-web/src/main/java/org/springframework/http/client/support/InterceptingHttpAccessor.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. <ide> public abstract class InterceptingHttpAccessor extends HttpAccessor { <ide> * Set the request interceptors that this accessor should use. <ide> * <p>The interceptors will get immediately sorted according to their <ide> * {@linkplain AnnotationAwareOrderComparator#sort(List) order}. <add> * <p><strong>Note:</strong> This method does not support concurrent changes, <add> * and in most cases should not be called after initialization on startup. <add> * See also related note on {@link org.springframework.web.client.RestTemplate} <add> * regarding concurrent configuration changes. <ide> * @see #getRequestFactory() <ide> * @see AnnotationAwareOrderComparator <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/client/RestTemplate.java <ide> /* <del> * Copyright 2002-2021 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. <ide> /** <ide> * Synchronous client to perform HTTP requests, exposing a simple, template <ide> * method API over underlying HTTP client libraries such as the JDK <del> * {@code HttpURLConnection}, Apache HttpComponents, and others. <add> * {@code HttpURLConnection}, Apache HttpComponents, and others. RestTemplate <add> * offers templates for common scenarios by HTTP method, in addition to the <add> * generalized {@code exchange} and {@code execute} methods that support of <add> * less frequent cases. <ide> * <del> * <p>The RestTemplate offers templates for common scenarios by HTTP method, in <del> * addition to the generalized {@code exchange} and {@code execute} methods that <del> * support of less frequent cases. <add> * <p>RestTemplate is typically used as a shared component. However, its <add> * configuration does not support concurrent modification, and as such its <add> * configuration is typically prepared on startup. If necessary, you can create <add> * multiple, differently configured RestTemplate instances on startup. Such <add> * instances may use the same the underlying {@link ClientHttpRequestFactory} <add> * if they need to share HTTP client resources. <ide> * <ide> * <p><strong>NOTE:</strong> As of 5.0 this class is in maintenance mode, with <ide> * only minor requests for changes and bugs to be accepted going forward. Please,
2
Python
Python
add tf/th kernel conversion util
ed0cd2c60db98e6f4a315c420e1fed9968fe34d7
<ide><path>keras/utils/np_utils.py <ide> def probas_to_classes(y_pred): <ide> <ide> def categorical_probas_to_classes(p): <ide> return np.argmax(p, axis=1) <add> <add> <add>def convert_kernel(kernel, dim_ordering='th'): <add> '''Converts a kernel matrix (numpy array) <add> from Theano format to TensorFlow format <add> (or reciprocally, since the transformation <add> is its own inverse). <add> ''' <add> new_kernel = np.copy(kernel) <add> if dim_ordering == 'th': <add> w = kernel.shape[2] <add> h = kernel.shape[3] <add> for i in range(w): <add> for j in range(h): <add> new_kernel[:, :, i, j] = kernel[:, :, w - i - 1, h - j - 1] <add> elif dim_ordering == 'tf': <add> w = kernel.shape[0] <add> h = kernel.shape[1] <add> for i in range(w): <add> for j in range(h): <add> new_kernel[i, j, :, :] = kernel[w - i - 1, h - j - 1, :, :] <add> else: <add> raise Exception('Invalid dim_ordering: ' + str(dim_ordering)) <add> return new_kernel <ide><path>tests/keras/backend/test_backends.py <ide> <ide> from keras.backend import theano_backend as KTH <ide> from keras.backend import tensorflow_backend as KTF <add>from keras.utils.np_utils import convert_kernel <ide> <ide> <ide> def check_single_tensor_operation(function_name, input_shape, **kwargs): <ide> def check_single_tensor_operation(function_name, input_shape, **kwargs): <ide> def check_two_tensor_operation(function_name, x_input_shape, <ide> y_input_shape, **kwargs): <ide> xval = np.random.random(x_input_shape) - 0.5 <add> <ide> xth = KTH.variable(xval) <ide> xtf = KTF.variable(xval) <ide> <ide> yval = np.random.random(y_input_shape) - 0.5 <add> <ide> yth = KTH.variable(yval) <ide> ytf = KTF.variable(yval) <ide> <ide> def test_nn_operations(self): <ide> check_single_tensor_operation('l2_normalize', (4, 3), axis=-1) <ide> check_single_tensor_operation('l2_normalize', (4, 3), axis=1) <ide> <del> # def test_conv2d(self): <del> # '''conv2d works "properly" with Theano and TF but outputs different <del> # values in each case. Cause unclear (input / kernel shape format?) <del> # ''' <del> # # TH kernel shape: (depth, input_depth, rows, cols) <del> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 2, 2), <del> # strides=(1, 1), border_mode='valid') <del> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 2, 2), <del> # strides=(1, 1), border_mode='same') <del> <del> # # TF kernel shape: (rows, cols, input_depth, depth) <del> # check_two_tensor_operation('conv2d', (5, 10, 12, 3), (2, 2, 3, 4), <del> # strides=(1, 1), border_mode='valid', dim_ordering='tf') <del> # check_two_tensor_operation('conv2d', (5, 10, 12, 3), (2, 2, 3, 4), <del> # strides=(1, 1), border_mode='same', dim_ordering='tf') <del> <del> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 3, 3), <del> # strides=(1, 1), border_mode='valid') <del> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 3, 3), <del> # strides=(1, 1), border_mode='same') <del> <del> # check_two_tensor_operation('conv2d', (5, 3, 10, 12), (4, 3, 3, 3), <del> # strides=(2, 2), border_mode='valid') <del> <del> # def test_pool2d(self): <del> # '''pool2d works "properly" with Theano and TF but outputs different <del> # values in each case. Cause unclear (input shape format?) <del> # ''' <del> # check_single_tensor_operation('pool2d', (5, 3, 10, 12), pool_size=(2, 2), <del> # strides=(1, 1), border_mode='valid') <del> <del> # check_single_tensor_operation('pool2d', (5, 3, 9, 11), pool_size=(2, 2), <del> # strides=(1, 1), border_mode='valid') <del> <del> # check_single_tensor_operation('pool2d', (5, 3, 9, 11), pool_size=(2, 3), <del> # strides=(1, 1), border_mode='valid') <add> def test_conv2d(self): <add> # TH kernel shape: (depth, input_depth, rows, cols) <add> # TF kernel shape: (rows, cols, input_depth, depth) <add> <add> for input_shape in [(2, 3, 4, 5), (2, 3, 5, 6)]: <add> for kernel_shape in [(4, 3, 2, 2), (4, 3, 3, 4)]: <add> xval = np.random.random(input_shape) <add> <add> xth = KTH.variable(xval) <add> xtf = KTF.variable(xval) <add> <add> kernel_val = np.random.random(kernel_shape) - 0.5 <add> <add> kernel_th = KTH.variable(convert_kernel(kernel_val)) <add> kernel_tf = KTF.variable(kernel_val) <add> <add> zth = KTH.eval(KTH.conv2d(xth, kernel_th)) <add> ztf = KTF.eval(KTF.conv2d(xtf, kernel_tf)) <add> <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-05) <add> <add> input_shape = (1, 6, 5, 3) <add> kernel_shape = (3, 3, 3, 2) <add> <add> xval = np.random.random(input_shape) <add> <add> xth = KTH.variable(xval) <add> xtf = KTF.variable(xval) <add> <add> kernel_val = np.random.random(kernel_shape) - 0.5 <add> <add> kernel_th = KTH.variable(convert_kernel(kernel_val, dim_ordering='tf')) <add> kernel_tf = KTF.variable(kernel_val) <add> <add> zth = KTH.eval(KTH.conv2d(xth, kernel_th, dim_ordering='tf')) <add> ztf = KTF.eval(KTF.conv2d(xtf, kernel_tf, dim_ordering='tf')) <add> <add> assert zth.shape == ztf.shape <add> assert_allclose(zth, ztf, atol=1e-05) <add> <add> def test_pool2d(self): <add> check_single_tensor_operation('pool2d', (5, 3, 10, 12), pool_size=(2, 2), <add> strides=(1, 1), border_mode='valid') <add> <add> check_single_tensor_operation('pool2d', (5, 3, 9, 11), pool_size=(2, 2), <add> strides=(1, 1), border_mode='valid') <add> <add> check_single_tensor_operation('pool2d', (5, 3, 9, 11), pool_size=(2, 3), <add> strides=(1, 1), border_mode='valid') <ide> <ide> def test_random_normal(self): <ide> mean = 0.
2
Text
Text
add gitter badge to readme.md
7869f83ddd5a3156a358284cbef6837b5e7a2a62
<ide><path>README.md <ide> <ide> [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fjquery%2Fjquery.svg?type=shield)](https://app.fossa.io/projects/git%2Bgithub.com%2Fjquery%2Fjquery?ref=badge_shield) <ide> <add>[![Gitter](https://badges.gitter.im/jquery/jquery.svg)](https://gitter.im/jquery/jquery?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) <add> <ide> Contribution Guides <ide> -------------------------------------- <ide>
1
Java
Java
kill bridge only after cleaning up nativemodules
5328d952a8dd0945005d9f7305aba913f438ffa7
<ide><path>ReactAndroid/src/main/java/com/facebook/react/cxxbridge/CatalystInstanceImpl.java <ide> public void destroy() { <ide> <ide> // TODO: tell all APIs to shut down <ide> mDestroyed = true; <del> mHybridData.resetNative(); <ide> mReactQueueConfiguration.getNativeModulesQueueThread().runOnQueue(new Runnable() { <ide> @Override <ide> public void run() { <ide> mJavaRegistry.notifyJSInstanceDestroy(); <add> mHybridData.resetNative(); <ide> } <ide> }); <ide> boolean wasIdle = (mPendingJSCalls.getAndSet(0) == 0); <ide><path>ReactAndroid/src/main/java/com/facebook/react/uimanager/events/EventDispatcher.java <ide> public void onHostDestroy() { <ide> } <ide> <ide> public void onCatalystInstanceDestroyed() { <del> stopFrameCallback(); <add> UiThreadUtil.runOnUiThread(new Runnable() { <add> @Override <add> public void run() { <add> stopFrameCallback(); <add> } <add> }); <ide> } <ide> <ide> private void stopFrameCallback() {
2
PHP
PHP
fix comment error
27bacf6cca5040ff6ceaa3764f005ba22c795a9d
<ide><path>src/Http/Cookie/Cookie.php <ide> public function isSecure() <ide> /** <ide> * Create a cookie with Secure updated <ide> * <del> * @param bool $httpOnly HTTP Only <add> * @param bool $secure Secure attribute value <ide> * @return static <ide> */ <ide> public function withSecure($secure)
1
PHP
PHP
add failing test for mass composer registration
e86ada0d62d92fe8cc6df6b7d08b92bdfaeec1e5
<ide><path>tests/View/ViewFactoryTest.php <ide> public function testComposersCanBeMassRegistered() <ide> 'baz@baz' => array('qux', 'foo'), <ide> )); <ide> <add> $this->assertCount(3, $composers); <ide> $reflections = array( <ide> new ReflectionFunction($composers[0]), <ide> new ReflectionFunction($composers[1]),
1
PHP
PHP
pass proper value to class
423487fa9ac58a37ef22f32abe54e546b482d013
<ide><path>src/Illuminate/Queue/Console/WorkCommand.php <ide> protected function runWorker($connection, $queue, $delay, $memory, $daemon = fal <ide> { <ide> $this->worker->setCache($this->laravel['cache']->driver()); <ide> <del> $this->worker->setDaemonExceptionHandler($this->laravel['exception']); <add> $this->worker->setDaemonExceptionHandler( <add> $this->laravel['Illuminate\Contracts\Debug\ExceptionHandler'] <add> ); <ide> <ide> return $this->worker->daemon( <ide> $connection, $queue, $delay, $memory,
1
Ruby
Ruby
fix additional quotes already handled by #inspect
2c4ef98f0d880142766ed181743af7f8f2d7f724
<ide><path>Library/Homebrew/rubocops/lines.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> elsif shell_parameter_stripped == "--shell=" <ide> :arg <ide> else <del> "\"#{shell_parameter_stripped}\"" <add> shell_parameter_stripped <ide> end <ide> <ide> replacement_args = %w[]
1
Ruby
Ruby
avoid improper, late usage of formula dsl
15280ba1073afc13f239b9606de8f9623e8bc0a3
<ide><path>Library/Homebrew/test/build_environment_spec.rb <ide> end <ide> <ide> describe BuildEnvironment::DSL do <del> subject(:build_environment_dsl) { double.extend(described_class) } <add> let(:build_environment_dsl) do <add> klass = described_class <add> Class.new do <add> extend(klass) <add> end <add> end <ide> <ide> context "with a single argument" do <del> before do <del> build_environment_dsl.instance_eval do <add> subject do <add> Class.new(build_environment_dsl) do <ide> env :std <ide> end <ide> end <ide><path>Library/Homebrew/test/cleaner_spec.rb <ide> describe Cleaner do <ide> include FileUtils <ide> <del> subject(:cleaner) { described_class.new(f) } <add> describe "#clean" do <add> subject(:cleaner) { described_class.new(f) } <ide> <del> let(:f) { formula("cleaner_test") { url "foo-1.0" } } <add> let(:f) { formula("cleaner_test") { url "foo-1.0" } } <ide> <del> before do <del> f.prefix.mkpath <del> end <add> before do <add> f.prefix.mkpath <add> end <ide> <del> describe "#clean" do <ide> it "cleans files" do <ide> f.bin.mkpath <ide> f.lib.mkpath <ide> end <ide> <ide> describe "::skip_clean" do <add> def stub_formula_skip_clean(skip_paths) <add> formula("cleaner_test") do <add> url "foo-1.0" <add> <add> skip_clean skip_paths <add> end <add> end <add> <ide> it "adds paths that should be skipped" do <del> f.class.skip_clean "bin" <add> f = stub_formula_skip_clean("bin") <ide> f.bin.mkpath <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(f.bin).to be_a_directory <ide> end <ide> <ide> it "also skips empty sub-directories under the added paths" do <del> f.class.skip_clean "bin" <add> f = stub_formula_skip_clean("bin") <ide> subdir = f.bin/"subdir" <ide> subdir.mkpath <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(f.bin).to be_a_directory <ide> expect(subdir).to be_a_directory <ide> end <ide> <ide> it "allows skipping broken symlinks" do <del> f.class.skip_clean "symlink" <add> f = stub_formula_skip_clean("symlink") <add> f.prefix.mkpath <ide> symlink = f.prefix/"symlink" <ide> ln_s "target", symlink <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(symlink).to be_a_symlink <ide> end <ide> <ide> it "allows skipping symlinks pointing to an empty directory" do <del> f.class.skip_clean "c" <add> f = stub_formula_skip_clean("c") <ide> dir = f.prefix/"b" <ide> symlink = f.prefix/"c" <ide> <ide> dir.mkpath <ide> ln_s dir.basename, symlink <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(dir).not_to exist <ide> expect(symlink).to be_a_symlink <ide> expect(symlink).not_to exist <ide> end <ide> <ide> it "allows skipping symlinks whose target was pruned before" do <del> f.class.skip_clean "a" <add> f = stub_formula_skip_clean("a") <ide> dir = f.prefix/"b" <ide> symlink = f.prefix/"a" <ide> <ide> dir.mkpath <ide> ln_s dir.basename, symlink <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(dir).not_to exist <ide> expect(symlink).to be_a_symlink <ide> expect(symlink).not_to exist <ide> end <ide> <ide> it "allows skipping '.la' files" do <add> f = stub_formula_skip_clean(:la) <add> <ide> file = f.lib/"foo.la" <ide> <del> f.class.skip_clean :la <ide> f.lib.mkpath <ide> touch file <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(file).to exist <ide> end <ide> <ide> it "allows skipping sub-directories" do <add> f = stub_formula_skip_clean("lib/subdir") <add> <ide> dir = f.lib/"subdir" <del> f.class.skip_clean "lib/subdir" <ide> <ide> dir.mkpath <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(dir).to be_a_directory <ide> end <ide> <ide> it "allows skipping paths relative to prefix" do <add> f = stub_formula_skip_clean("bin/a") <add> <ide> dir1 = f.bin/"a" <ide> dir2 = f.lib/"bin/a" <ide> <del> f.class.skip_clean "bin/a" <ide> dir1.mkpath <ide> dir2.mkpath <ide> <del> cleaner.clean <add> described_class.new(f).clean <ide> <ide> expect(dir1).to exist <ide> expect(dir2).not_to exist <ide><path>Library/Homebrew/test/formula_spec.rb <ide> specify "service complicated" do <ide> f = formula do <ide> url "https://brew.sh/test-1.0.tbz" <del> end <ide> <del> f.class.service do <del> run [opt_bin/"beanstalkd"] <del> run_type :immediate <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> working_dir var <del> keep_alive true <add> service do <add> run [opt_bin/"beanstalkd"] <add> run_type :immediate <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> working_dir var <add> keep_alive true <add> end <ide> end <ide> expect(f.service).not_to be_nil <ide> end <ide><path>Library/Homebrew/test/livecheck/livecheck_spec.rb <ide> <ide> describe "::livecheck_url_to_string" do <ide> let(:f_livecheck_url) do <add> homepage_url_s = homepage_url <add> stable_url_s = stable_url <add> head_url_s = head_url <add> <ide> formula("test_livecheck_url") do <ide> desc "Test Livecheck URL formula" <del> homepage "https://brew.sh" <del> url "https://brew.sh/test-0.0.1.tgz" <del> head "https://github.com/Homebrew/brew.git" <add> homepage homepage_url_s <add> url stable_url_s <add> head head_url_s <ide> end <ide> end <ide> <ide> end <ide> <ide> it "returns a URL string when given a livecheck_url string" do <del> f_livecheck_url.livecheck.url(livecheck_url) <ide> expect(livecheck.livecheck_url_to_string(livecheck_url, f_livecheck_url)).to eq(livecheck_url) <ide> end <ide> <ide> it "returns a URL symbol when given a valid livecheck_url symbol" do <del> f_livecheck_url.livecheck.url(:head) <del> expect(livecheck.livecheck_url_to_string(head_url, f_livecheck_url)).to eq(head_url) <del> <del> f_livecheck_url.livecheck.url(:homepage) <del> expect(livecheck.livecheck_url_to_string(homepage_url, f_livecheck_url)).to eq(homepage_url) <del> <del> c_livecheck_url.livecheck.url(:homepage) <del> expect(livecheck.livecheck_url_to_string(homepage_url, c_livecheck_url)).to eq(homepage_url) <del> <del> f_livecheck_url.livecheck.url(:stable) <del> expect(livecheck.livecheck_url_to_string(stable_url, f_livecheck_url)).to eq(stable_url) <del> <del> c_livecheck_url.livecheck.url(:url) <del> expect(livecheck.livecheck_url_to_string(cask_url, c_livecheck_url)).to eq(cask_url) <add> expect(livecheck.livecheck_url_to_string(:head, f_livecheck_url)).to eq(head_url) <add> expect(livecheck.livecheck_url_to_string(:homepage, f_livecheck_url)).to eq(homepage_url) <add> expect(livecheck.livecheck_url_to_string(:homepage, c_livecheck_url)).to eq(homepage_url) <add> expect(livecheck.livecheck_url_to_string(:stable, f_livecheck_url)).to eq(stable_url) <add> expect(livecheck.livecheck_url_to_string(:url, c_livecheck_url)).to eq(cask_url) <ide> end <ide> <ide> it "returns nil when not given a string or valid symbol" do <ide><path>Library/Homebrew/test/service_spec.rb <ide> require "service" <ide> <ide> describe Homebrew::Service do <del> let(:klass) do <del> Class.new(Formula) do <add> let(:name) { "formula_name" } <add> <add> def stub_formula(&block) <add> formula(name) do <ide> url "https://brew.sh/test-1.0.tbz" <add> <add> instance_eval(&block) if block <ide> end <ide> end <del> let(:name) { "formula_name" } <del> let(:path) { Formulary.core_path(name) } <del> let(:spec) { :stable } <del> let(:f) { klass.new(name, path, spec) } <ide> <ide> describe "#std_service_path_env" do <ide> it "returns valid std_service_path_env" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :immediate <del> environment_variables PATH: std_service_path_env <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> working_dir var <del> keep_alive true <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :immediate <add> environment_variables PATH: std_service_path_env <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> working_dir var <add> keep_alive true <add> end <ide> end <ide> <ide> path = f.service.std_service_path_env <ide> <ide> describe "#process_type" do <ide> it "throws for unexpected type" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> process_type :cow <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> process_type :cow <add> end <ide> end <ide> <ide> expect { <ide> <ide> describe "#keep_alive" do <ide> it "throws for unexpected keys" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> keep_alive test: "key" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> keep_alive test: "key" <add> end <ide> end <ide> <ide> expect { <ide> <ide> describe "#run_type" do <ide> it "throws for unexpected type" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :cow <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :cow <add> end <ide> end <ide> <ide> expect { <ide> <ide> describe "#sockets" do <ide> it "throws for missing type" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> sockets "127.0.0.1:80" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> sockets "127.0.0.1:80" <add> end <ide> end <ide> <ide> expect { <ide> end <ide> <ide> it "throws for missing host" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> sockets "tcp://:80" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> sockets "tcp://:80" <add> end <ide> end <ide> <ide> expect { <ide> end <ide> <ide> it "throws for missing port" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> sockets "tcp://127.0.0.1" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> sockets "tcp://127.0.0.1" <add> end <ide> end <ide> <ide> expect { <ide> <ide> describe "#manual_command" do <ide> it "returns valid manual_command" do <del> f.class.service do <del> run "#{HOMEBREW_PREFIX}/bin/beanstalkd" <del> run_type :immediate <del> environment_variables PATH: std_service_path_env, ETC_DIR: etc/"beanstalkd" <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> working_dir var <del> keep_alive true <add> f = stub_formula do <add> service do <add> run "#{HOMEBREW_PREFIX}/bin/beanstalkd" <add> run_type :immediate <add> environment_variables PATH: std_service_path_env, ETC_DIR: etc/"beanstalkd" <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> working_dir var <add> keep_alive true <add> end <ide> end <ide> <ide> path = f.service.manual_command <ide> expect(path).to eq("ETC_DIR=\"#{HOMEBREW_PREFIX}/etc/beanstalkd\" #{HOMEBREW_PREFIX}/bin/beanstalkd") <ide> end <ide> <ide> it "returns valid manual_command without variables" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :immediate <del> environment_variables PATH: std_service_path_env <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> working_dir var <del> keep_alive true <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :immediate <add> environment_variables PATH: std_service_path_env <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> working_dir var <add> keep_alive true <add> end <ide> end <ide> <ide> path = f.service.manual_command <ide> <ide> describe "#to_plist" do <ide> it "returns valid plist" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> run_type :immediate <del> environment_variables PATH: std_service_path_env, FOO: "BAR", ETC_DIR: etc/"beanstalkd" <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> input_path var/"in/beanstalkd" <del> root_dir var <del> working_dir var <del> keep_alive true <del> launch_only_once true <del> process_type :interactive <del> restart_delay 30 <del> interval 5 <del> macos_legacy_timers true <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :immediate <add> environment_variables PATH: std_service_path_env, FOO: "BAR", ETC_DIR: etc/"beanstalkd" <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> input_path var/"in/beanstalkd" <add> root_dir var <add> working_dir var <add> keep_alive true <add> launch_only_once true <add> process_type :interactive <add> restart_delay 30 <add> interval 5 <add> macos_legacy_timers true <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid plist with socket" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> sockets "tcp://127.0.0.1:80" <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> sockets "tcp://127.0.0.1:80" <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid partial plist" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :immediate <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :immediate <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid interval plist" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :interval <del> interval 5 <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :interval <add> interval 5 <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid cron plist" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :cron <del> cron "@daily" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :cron <add> cron "@daily" <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid keepalive-exit plist" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> keep_alive successful_exit: false <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> keep_alive successful_exit: false <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid keepalive-crashed plist" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> keep_alive crashed: true <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> keep_alive crashed: true <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> end <ide> <ide> it "returns valid keepalive-path plist" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> keep_alive path: opt_pkgshare/"test-path" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> keep_alive path: opt_pkgshare/"test-path" <add> end <ide> end <ide> <ide> plist = f.service.to_plist <ide> <ide> describe "#to_systemd_unit" do <ide> it "returns valid unit" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> run_type :immediate <del> environment_variables PATH: std_service_path_env, FOO: "BAR" <del> error_log_path var/"log/beanstalkd.error.log" <del> log_path var/"log/beanstalkd.log" <del> input_path var/"in/beanstalkd" <del> root_dir var <del> working_dir var <del> keep_alive true <del> process_type :interactive <del> restart_delay 30 <del> macos_legacy_timers true <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :immediate <add> environment_variables PATH: std_service_path_env, FOO: "BAR" <add> error_log_path var/"log/beanstalkd.error.log" <add> log_path var/"log/beanstalkd.log" <add> input_path var/"in/beanstalkd" <add> root_dir var <add> working_dir var <add> keep_alive true <add> process_type :interactive <add> restart_delay 30 <add> macos_legacy_timers true <add> end <ide> end <ide> <ide> unit = f.service.to_systemd_unit <ide> end <ide> <ide> it "returns valid partial oneshot unit" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :immediate <del> launch_only_once true <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :immediate <add> launch_only_once true <add> end <ide> end <ide> <ide> unit = f.service.to_systemd_unit <ide> <ide> describe "#to_systemd_timer" do <ide> it "returns valid timer" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> run_type :interval <del> interval 5 <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :interval <add> interval 5 <add> end <ide> end <ide> <ide> unit = f.service.to_systemd_timer <ide> end <ide> <ide> it "returns valid partial timer" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :immediate <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :immediate <add> end <ide> end <ide> <ide> unit = f.service.to_systemd_timer <ide> end <ide> <ide> it "throws on incomplete cron" do <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :cron <del> cron "1 2 3 4" <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :cron <add> cron "1 2 3 4" <add> end <ide> end <ide> <ide> expect { <ide> } <ide> <ide> styles.each do |cron, calendar| <del> f.class.service do <del> run opt_bin/"beanstalkd" <del> run_type :cron <del> cron cron.to_s <add> f = stub_formula do <add> service do <add> run opt_bin/"beanstalkd" <add> run_type :cron <add> cron cron.to_s <add> end <ide> end <ide> <ide> unit = f.service.to_systemd_timer <ide> <ide> describe "#timed?" do <ide> it "returns false for immediate" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> run_type :immediate <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :immediate <add> end <ide> end <ide> <ide> expect(f.service.timed?).to be(false) <ide> end <ide> <ide> it "returns true for interval" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> run_type :interval <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :interval <add> end <ide> end <ide> <ide> expect(f.service.timed?).to be(true) <ide> <ide> describe "#keep_alive?" do <ide> it "returns true when keep_alive set to hash" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> keep_alive crashed: true <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive crashed: true <add> end <ide> end <ide> <ide> expect(f.service.keep_alive?).to be(true) <ide> end <ide> <ide> it "returns true when keep_alive set to true" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> keep_alive true <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive true <add> end <ide> end <ide> <ide> expect(f.service.keep_alive?).to be(true) <ide> end <ide> <ide> it "returns false when keep_alive not set" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> end <ide> end <ide> <ide> expect(f.service.keep_alive?).to be(false) <ide> end <ide> <ide> it "returns false when keep_alive set to false" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> keep_alive false <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> keep_alive false <add> end <ide> end <ide> <ide> expect(f.service.keep_alive?).to be(false) <ide> <ide> describe "#command" do <ide> it "returns @run data" do <del> f.class.service do <del> run [opt_bin/"beanstalkd", "test"] <del> run_type :immediate <add> f = stub_formula do <add> service do <add> run [opt_bin/"beanstalkd", "test"] <add> run_type :immediate <add> end <ide> end <ide> <ide> command = f.service.command <ide><path>Library/Homebrew/test/support/fixtures/failball.rb <ide> class Failball < Formula <ide> def initialize(name = "failball", path = Pathname.new(__FILE__).expand_path, spec = :stable, <ide> alias_path: nil, force_bottle: false) <del> self.class.instance_eval do <del> stable.url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <del> stable.sha256 TESTBALL_SHA256 <del> end <ide> super <ide> end <ide> <add> DSL_PROC = proc do <add> url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <add> sha256 TESTBALL_SHA256 <add> end.freeze <add> private_constant :DSL_PROC <add> <add> DSL_PROC.call <add> <add> def self.inherited(other) <add> super <add> other.instance_eval(&DSL_PROC) <add> end <add> <ide> def install <ide> prefix.install "bin" <ide> prefix.install "libexec" <ide><path>Library/Homebrew/test/support/fixtures/testball.rb <ide> class Testball < Formula <ide> def initialize(name = "testball", path = Pathname.new(__FILE__).expand_path, spec = :stable, <ide> alias_path: nil, force_bottle: false) <del> self.class.instance_eval do <del> stable.url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <del> stable.sha256 TESTBALL_SHA256 <del> end <ide> super <ide> end <ide> <add> DSL_PROC = proc do <add> url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <add> sha256 TESTBALL_SHA256 <add> end.freeze <add> private_constant :DSL_PROC <add> <add> DSL_PROC.call <add> <add> def self.inherited(other) <add> super <add> other.instance_eval(&DSL_PROC) <add> end <add> <ide> def install <ide> prefix.install "bin" <ide> prefix.install "libexec" <ide><path>Library/Homebrew/test/support/fixtures/testball_bottle.rb <ide> class TestballBottle < Formula <ide> def initialize(name = "testball_bottle", path = Pathname.new(__FILE__).expand_path, spec = :stable, <ide> alias_path: nil, force_bottle: false) <del> self.class.instance_eval do <del> stable.url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <del> stable.sha256 TESTBALL_SHA256 <del> stable.bottle do <del> root_url "file://#{TEST_FIXTURE_DIR}/bottles" <del> sha256 cellar: :any_skip_relocation, Utils::Bottles.tag.to_sym => "8f9aecd233463da6a4ea55f5f88fc5841718c013f3e2a7941350d6130f1dc149" <del> end <del> cxxstdlib_check :skip <add> super <add> end <add> <add> DSL_PROC = proc do <add> url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <add> sha256 TESTBALL_SHA256 <add> <add> bottle do <add> root_url "file://#{TEST_FIXTURE_DIR}/bottles" <add> sha256 cellar: :any_skip_relocation, Utils::Bottles.tag.to_sym => "8f9aecd233463da6a4ea55f5f88fc5841718c013f3e2a7941350d6130f1dc149" <ide> end <add> <add> cxxstdlib_check :skip <add> end.freeze <add> private_constant :DSL_PROC <add> <add> DSL_PROC.call <add> <add> def self.inherited(other) <ide> super <add> other.instance_eval(&DSL_PROC) <ide> end <ide> <ide> def install <ide><path>Library/Homebrew/test/support/fixtures/testball_bottle_cellar.rb <ide> class TestballBottleCellar < Formula <ide> def initialize(name = "testball_bottle", path = Pathname.new(__FILE__).expand_path, spec = :stable, <ide> alias_path: nil, force_bottle: false) <del> self.class.instance_eval do <del> stable.url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <del> stable.sha256 TESTBALL_SHA256 <del> hexdigest = "8f9aecd233463da6a4ea55f5f88fc5841718c013f3e2a7941350d6130f1dc149" <del> stable.bottle do <del> root_url "file://#{TEST_FIXTURE_DIR}/bottles" <del> sha256 cellar: :any_skip_relocation, Utils::Bottles.tag.to_sym => hexdigest <del> end <del> cxxstdlib_check :skip <add> super <add> end <add> <add> DSL_PROC = proc do <add> url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" <add> sha256 TESTBALL_SHA256 <add> <add> bottle do <add> root_url "file://#{TEST_FIXTURE_DIR}/bottles" <add> sha256 cellar: :any_skip_relocation, Utils::Bottles.tag.to_sym => "8f9aecd233463da6a4ea55f5f88fc5841718c013f3e2a7941350d6130f1dc149" <ide> end <add> <add> cxxstdlib_check :skip <add> end.freeze <add> private_constant :DSL_PROC <add> <add> DSL_PROC.call <add> <add> def self.inherited(other) <ide> super <add> other.instance_eval(&DSL_PROC) <ide> end <ide> <ide> def install
9
Text
Text
fix typo in 1.bug_report.md
29694572ed499f18b63ac329173a9b893dd611a2
<ide><path>.github/ISSUE_TEMPLATE/1.Bug_report.md <ide> about: Create a bug report for the Next.js core / examples <ide> labels: 'template: bug' <ide> --- <ide> <del><!-- NOTE: This template is not optional. If you remove it or leave out sections there is a high likelyhood it will be moved to the GitHub Discussions "Help" section --> <add><!-- NOTE: This template is not optional. If you remove it or leave out sections there is a high likelihood it will be moved to the GitHub Discussions "Help" section --> <ide> <ide> # Bug report <ide>
1
Javascript
Javascript
remove errant return assignment
4b163fee1c494c35ac8b4ba49cd41e9c573b7a7b
<ide><path>packages/react-reconciler/src/ReactFiberBeginWork.js <ide> function updateSuspenseComponent( <ide> } else { <ide> // The current tree has not already timed out. That means the primary <ide> // children are not wrapped in a fragment fiber. <del> const currentPrimaryChild: Fiber = (current.child: any); <add> const currentPrimaryChild = current.child; <ide> if (nextDidTimeout) { <ide> // Timed out. Wrap the children in a fragment fiber to keep them <ide> // separate from the fallback children. <ide> function updateSuspenseComponent( <ide> null, <ide> ); <ide> primaryChildFragment.child = currentPrimaryChild; <del> currentPrimaryChild.return = primaryChildFragment; <ide> <ide> // Even though we're creating a new fiber, there are no new children, <ide> // because we're reusing an already mounted tree. So we don't need to <ide><path>packages/react-reconciler/src/__tests__/ReactSuspense-test.internal.js <ide> describe('ReactSuspense', () => { <ide> <ide> root.update(null); <ide> expect(root).toFlushWithoutYielding(); <add> jest.advanceTimersByTime(1000); <add> }); <add> <add> it('#14162', () => { <add> const {lazy} = React; <add> <add> function Hello() { <add> return <span>hello</span>; <add> } <add> <add> async function fetchComponent() { <add> return new Promise(r => { <add> // simulating a delayed import() call <add> setTimeout(r, 1000, {default: Hello}); <add> }); <add> } <add> <add> const LazyHello = lazy(fetchComponent); <add> <add> class App extends React.Component { <add> state = {render: false}; <add> <add> componentDidMount() { <add> setTimeout(() => this.setState({render: true})); <add> } <add> <add> render() { <add> return ( <add> <Suspense fallback={<span>loading...</span>}> <add> {this.state.render && <LazyHello />} <add> </Suspense> <add> ); <add> } <add> } <add> <add> const root = ReactTestRenderer.create(null); <ide> <add> root.update(<App name="world" />); <ide> jest.advanceTimersByTime(1000); <ide> }); <ide> });
2
Ruby
Ruby
remove accidental raise!
02fc45a057878c49b6397900e5dcf828fdb8c09d
<ide><path>activerecord/lib/active_record/fixtures.rb <ide> def self.identify(label) <ide> attr_reader :table_name, :name, :fixtures, :model_class <ide> <ide> def initialize(connection, table_name, class_name, fixture_path, file_filter = DEFAULT_FILTER_RE) <del> raise if file_filter != DEFAULT_FILTER_RE <ide> @connection = connection <ide> @table_name = table_name <ide> @fixture_path = fixture_path
1
Text
Text
enclose variables in back quote
ae0f9189fc07c77b3c19bde4ebed72eaa6e0d3b7
<ide><path>docs/docs/10.4-test-utils.md <ide> Pass a mocked component module to this method to augment it with useful methods <ide> boolean isElement(ReactElement element) <ide> ``` <ide> <del>Returns true if `element` is any ReactElement. <add>Returns `true` if `element` is any ReactElement. <ide> <ide> ### isElementOfType <ide> <ide> ```javascript <ide> boolean isElementOfType(ReactElement element, function componentClass) <ide> ``` <ide> <del>Returns true if `element` is a ReactElement whose type is of a React `componentClass`. <add>Returns `true` if `element` is a ReactElement whose type is of a React `componentClass`. <ide> <ide> ### isDOMComponent <ide> <ide> ```javascript <ide> boolean isDOMComponent(ReactComponent instance) <ide> ``` <ide> <del>Returns true if `instance` is a DOM component (such as a `<div>` or `<span>`). <add>Returns `true` if `instance` is a DOM component (such as a `<div>` or `<span>`). <ide> <ide> ### isCompositeComponent <ide> <ide> ```javascript <ide> boolean isCompositeComponent(ReactComponent instance)` <ide> ``` <ide> <del>Returns true if `instance` is a composite component (created with `React.createClass()`). <add>Returns `true` if `instance` is a composite component (created with `React.createClass()`). <ide> <ide> ### isCompositeComponentWithType <ide> <ide> ```javascript <ide> boolean isCompositeComponentWithType(ReactComponent instance, function componentClass) <ide> ``` <ide> <del>Returns true if `instance` is a composite component (created with `React.createClass()`) whose type is of a React `componentClass`. <add>Returns `true` if `instance` is a composite component (created with `React.createClass()`) whose type is of a React `componentClass`. <ide> <ide> ### findAllInRenderedTree <ide> <ide> ```javascript <ide> array findAllInRenderedTree(ReactComponent tree, function test) <ide> ``` <ide> <del>Traverse all components in `tree` and accumulate all components where `test(component)` is true. This is not that useful on its own, but it's used as a primitive for other test utils. <add>Traverse all components in `tree` and accumulate all components where `test(component)` is `true`. This is not that useful on its own, but it's used as a primitive for other test utils. <ide> <ide> ### scryRenderedDOMComponentsWithClass <ide> <ide> Similar to `React.render`. <ide> ReactComponent shallowRenderer.getRenderOutput() <ide> ``` <ide> <del>After render has been called, returns shallowly rendered output. You can then begin to assert facts about the output. For example, if your component's render method returns: <add>After `render` has been called, returns shallowly rendered output. You can then begin to assert facts about the output. For example, if your component's render method returns: <ide> <ide> ```javascript <ide> <div>
1
Javascript
Javascript
make 'getreference' monomorphic
97c6703aab3dbb2f336f893aada9c105b3ea0cc7
<ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js <ide> const HarmonyImportDependency = require("./HarmonyImportDependency"); <ide> const Template = require("../Template"); <ide> <add>const EMPTY_MAP = new Map(); <add> <add>class ExportMode { <add> constructor(type) { <add> this.type = type; <add> this.name = null; <add> this.map = EMPTY_MAP; <add> this.module = null; <add> this.userRequest = null; <add> } <add>} <add> <add>const EMPTY_STAR_MODE = new ExportMode("empty-star"); <add> <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> constructor( <ide> request, <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> const importedModule = this.module; <ide> <ide> if (!importedModule) { <del> return { <del> type: "missing", <del> userRequest: this.userRequest <del> }; <add> const mode = new ExportMode("missing"); <add> mode.userRequest = this.userRequest; <add> return mode; <ide> } <ide> <ide> if ( <ide> !ignoreUnused && <ide> (name ? !used : this.originModule.usedExports === false) <ide> ) { <del> return { <del> type: "unused", <del> name: name || "*" <del> }; <add> const mode = new ExportMode("unused"); <add> mode.name = name || "*"; <add> return mode; <ide> } <ide> <ide> const strictHarmonyModule = this.originModule.buildMeta.strictHarmonyModule; <ide> if (name && id === "default" && importedModule.buildMeta) { <ide> if (!importedModule.buildMeta.exportsType) { <del> if (strictHarmonyModule) { <del> return { <del> type: "reexport-non-harmony-default-strict", <del> module: importedModule, <del> name <del> }; <del> } else { <del> return { <del> type: "reexport-non-harmony-default", <del> module: importedModule, <del> name <del> }; <del> } <add> const mode = new ExportMode( <add> strictHarmonyModule <add> ? "reexport-non-harmony-default-strict" <add> : "reexport-non-harmony-default" <add> ); <add> mode.name = name; <add> mode.module = importedModule; <add> return mode; <ide> } else if (importedModule.buildMeta.exportsType === "named") { <del> return { <del> type: "reexport-named-default", <del> module: importedModule, <del> name <del> }; <add> const mode = new ExportMode("reexport-named-default"); <add> mode.name = name; <add> mode.module = importedModule; <add> return mode; <ide> } <ide> } <ide> <ide> const isNotAHarmonyModule = <ide> importedModule.buildMeta && !importedModule.buildMeta.exportsType; <ide> if (name) { <del> // export { name as name } <add> let mode; <ide> if (id) { <add> // export { name as name } <ide> if (isNotAHarmonyModule && strictHarmonyModule) { <del> return { <del> type: "rexport-non-harmony-undefined", <del> module: importedModule, <del> name <del> }; <add> mode = new ExportMode("rexport-non-harmony-undefined"); <add> mode.name = name; <ide> } else { <del> return { <del> type: "safe-reexport", <del> module: importedModule, <del> map: new Map([[name, id]]) <del> }; <add> mode = new ExportMode("safe-reexport"); <add> mode.map = new Map([[name, id]]); <ide> } <del> } <del> <del> // export { * as name } <del> if (isNotAHarmonyModule && strictHarmonyModule) { <del> return { <del> type: "reexport-fake-namespace-object", <del> module: importedModule, <del> name <del> }; <ide> } else { <del> return { <del> type: "reexport-namespace-object", <del> module: importedModule, <del> name <del> }; <add> // export { * as name } <add> if (isNotAHarmonyModule && strictHarmonyModule) { <add> mode = new ExportMode("reexport-fake-namespace-object"); <add> mode.name = name; <add> } else { <add> mode = new ExportMode("reexport-namespace-object"); <add> mode.name = name; <add> } <ide> } <add> mode.module = importedModule; <add> return mode; <ide> } <ide> <ide> const hasUsedExports = Array.isArray(this.originModule.usedExports); <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> ); <ide> <ide> if (map.size === 0) { <del> return { <del> type: "empty-star" <del> }; <add> return EMPTY_STAR_MODE; <ide> } <ide> <del> return { <del> type: "safe-reexport", <del> module: importedModule, <del> map <del> }; <add> const mode = new ExportMode("safe-reexport"); <add> mode.module = importedModule; <add> mode.map = map; <add> return mode; <ide> } <ide> <ide> const map = new Map( <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> ); <ide> <ide> if (map.size === 0) { <del> return { <del> type: "empty-star" <del> }; <add> return EMPTY_STAR_MODE; <ide> } <ide> <del> return { <del> type: "checked-reexport", <del> module: importedModule, <del> map <del> }; <add> const mode = new ExportMode("checked-reexport"); <add> mode.module = importedModule; <add> mode.map = map; <add> return mode; <ide> } <ide> <ide> if (hasProvidedExports) { <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> ); <ide> <ide> if (map.size === 0) { <del> return { <del> type: "empty-star" <del> }; <add> return EMPTY_STAR_MODE; <ide> } <ide> <del> return { <del> type: "safe-reexport", <del> module: importedModule, <del> map <del> }; <add> const mode = new ExportMode("safe-reexport"); <add> mode.module = importedModule; <add> mode.map = map; <add> return mode; <ide> } <ide> <del> return { <del> type: "dynamic-reexport", <del> module: importedModule <del> }; <add> const mode = new ExportMode("dynamic-reexport"); <add> mode.module = importedModule; <add> return mode; <ide> } <ide> <ide> getReference() { <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> }; <ide> <ide> default: <add> console.log(mode); <ide> throw new Error(`Unknown mode ${mode.type}`); <ide> } <ide> }
1
PHP
PHP
use better assertion
9d9e6ad4fff39ac7c3f0eb3538755206b252dc28
<ide><path>tests/TestCase/Utility/HashTest.php <ide> public function testMaxDimensions() <ide> { <ide> $data = []; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals(0, $result); <add> $this->assertSame(0, $result); <ide> <ide> $data = ['a', 'b']; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals(1, $result); <add> $this->assertSame(1, $result); <ide> <ide> $data = ['1' => '1.1', '2', '3' => ['3.1' => '3.1.1']]; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals($result, 2); <add> $this->assertSame(2, $result); <ide> <ide> $data = ['1' => ['1.1' => '1.1.1'], '2', '3' => ['3.1' => ['3.1.1' => '3.1.1.1']]]; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals($result, 3); <add> $this->assertSame(3, $result); <ide> <ide> $data = [ <ide> '1' => ['1.1' => '1.1.1'], <ide> ['2' => ['2.1' => ['2.1.1' => '2.1.1.1']]], <ide> '3' => ['3.1' => ['3.1.1' => '3.1.1.1']] <ide> ]; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals($result, 4); <add> $this->assertSame(4, $result); <ide> <ide> $data = [ <ide> '1' => [ <ide> public function testMaxDimensions() <ide> '2' => ['2.1' => '2.1.1'] <ide> ]; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals($result, 5); <add> $this->assertSame(5, $result); <ide> <ide> $data = [ <ide> '1' => false, <ide> '2' => ['2.1' => '2.1.1'] <ide> ]; <ide> $result = Hash::maxDimensions($data); <del> $this->assertEquals($result, 2); <add> $this->assertSame(2, $result); <ide> } <ide> <ide> /**
1
Python
Python
add timestamp history for each batch in training
ae655521533ee1c35ae4d8ac18a7e99e35e3012e
<ide><path>official/resnet/keras/keras_cifar_main.py <ide> def run(flags_obj): <ide> eval_output = model.evaluate(eval_input_dataset, <ide> steps=num_eval_steps, <ide> verbose=1) <del> stats = keras_common.build_stats(history, eval_output) <add> stats = keras_common.build_stats(history, eval_output, time_callback) <ide> return stats <ide> <ide> <ide> def main(_): <ide> with logger.benchmark_context(flags.FLAGS): <del> run(flags.FLAGS) <add> return run(flags.FLAGS) <ide> <ide> <ide> if __name__ == '__main__': <ide><path>official/resnet/keras/keras_common.py <ide> from tensorflow.python.keras.optimizer_v2 import (gradient_descent as <ide> gradient_descent_v2) <ide> <del> <ide> FLAGS = flags.FLAGS <ide> BASE_LEARNING_RATE = 0.1 # This matches Jing's version. <ide> TRAIN_TOP_1 = 'training_accuracy_top_1' <ide> <ide> <add>class BatchTimestamp(object): <add> """A structure to store batch time stamp.""" <add> <add> def __init__(self, batch_index, timestamp): <add> self.batch_index = batch_index <add> self.timestamp = timestamp <add> <add> <ide> class TimeHistory(tf.keras.callbacks.Callback): <ide> """Callback for Keras models.""" <ide> <del> def __init__(self, batch_size): <add> def __init__(self, batch_size, log_steps): <ide> """Callback for logging performance (# image/second). <ide> <ide> Args: <ide> def __init__(self, batch_size): <ide> """ <ide> self._batch_size = batch_size <ide> super(TimeHistory, self).__init__() <del> self.log_steps = 100 <add> self.log_steps = log_steps <add> <add> # has stats for all batches <add> self.batch_start_timestamps = [] <add> # only has stats for batch_index % log_steps == 0 (excluding 0) <add> self.batch_end_timestamps = [] <ide> <ide> def on_train_begin(self, logs=None): <ide> self.record_batch = True <ide> <add> def on_train_end(self, logs=None): <add> self.train_finish_time = time.time() <add> <ide> def on_batch_begin(self, batch, logs=None): <ide> if self.record_batch: <del> self.start_time = time.time() <add> timestamp = time.time() <add> self.start_time = timestamp <ide> self.record_batch = False <add> self.batch_start_timestamps.append(BatchTimestamp(batch, timestamp)) <ide> <ide> def on_batch_end(self, batch, logs=None): <ide> if batch % self.log_steps == 0: <del> elapsed_time = time.time() - self.start_time <add> timestamp = time.time() <add> elapsed_time = timestamp - self.start_time <ide> examples_per_second = (self._batch_size * self.log_steps) / elapsed_time <ide> self.record_batch = True <del> # TODO(anjalisridhar): add timestamp as well. <ide> if batch != 0: <add> self.batch_end_timestamps.append(BatchTimestamp(batch, timestamp)) <ide> tf.logging.info("BenchmarkMetric: {'num_batches':%d, 'time_taken': %f," <ide> "'images_per_second': %f}" % <ide> (batch, elapsed_time, examples_per_second)) <ide> def get_optimizer(): <ide> <ide> def get_callbacks(learning_rate_schedule_fn, num_images): <ide> """Returns common callbacks.""" <del> time_callback = TimeHistory(FLAGS.batch_size) <add> time_callback = TimeHistory(FLAGS.batch_size, FLAGS.log_steps) <ide> <ide> tensorboard_callback = tf.keras.callbacks.TensorBoard( <ide> log_dir=FLAGS.model_dir) <ide> def get_callbacks(learning_rate_schedule_fn, num_images): <ide> return time_callback, tensorboard_callback, lr_callback <ide> <ide> <del>def build_stats(history, eval_output): <add>def build_stats(history, eval_output, time_callback): <ide> """Normalizes and returns dictionary of stats. <ide> <ide> Args: <ide> def build_stats(history, eval_output): <ide> if eval_output: <ide> stats['accuracy_top_1'] = eval_output[1].item() <ide> stats['eval_loss'] = eval_output[0].item() <add> <ide> if history and history.history: <ide> train_hist = history.history <ide> # Gets final loss from training. <ide> def build_stats(history, eval_output): <ide> elif 'sparse_categorical_accuracy' in train_hist: <ide> stats[TRAIN_TOP_1] = train_hist['sparse_categorical_accuracy'][-1].item() <ide> <add> if time_callback: <add> stats['batch_start_timestamps'] = time_callback.batch_start_timestamps <add> stats['batch_end_timestamps'] = time_callback.batch_end_timestamps <add> stats['train_finish_time'] = time_callback.train_finish_time <add> <ide> return stats <ide> <ide> <ide> def define_keras_flags(): <ide> help='The number of steps to run for training. If it is larger than ' <ide> '# batches per epoch, then use # batches per epoch. When this flag is ' <ide> 'set, only one epoch is going to run for training.') <add> flags.DEFINE_integer( <add> name='log_steps', default=100, <add> help='For every log_steps, we log the timing information such as ' <add> 'examples per second. Besides, for every log_steps, we store the ' <add> 'timestamp of a batch end.') <ide> <ide> <ide> def get_synth_input_fn(height, width, num_channels, num_classes, <ide><path>official/resnet/keras/keras_common_test.py <ide> def test_build_stats(self): <ide> <ide> history = self._build_history(1.145, cat_accuracy=.99988) <ide> eval_output = self._build_eval_output(.56432111, 5.990) <del> stats = keras_common.build_stats(history, eval_output) <add> th = keras_common.TimeHistory(128, 100) <add> <add> th.batch_start_timestamps = [1, 2, 3] <add> th.batch_end_timestamps = [4, 5, 6] <add> th.train_finish_time = 12345 <add> stats = keras_common.build_stats(history, eval_output, th) <ide> <ide> self.assertEqual(1.145, stats['loss']) <ide> self.assertEqual(.99988, stats['training_accuracy_top_1']) <ide> <ide> self.assertEqual(.56432111, stats['accuracy_top_1']) <ide> self.assertEqual(5.990, stats['eval_loss']) <ide> <add> self.assertItemsEqual([1, 2, 3], stats['batch_start_timestamps']) <add> self.assertItemsEqual([4, 5, 6], stats['batch_end_timestamps']) <add> self.assertEqual(12345, stats['train_finish_time']) <add> <ide> def test_build_stats_sparse(self): <ide> <ide> history = self._build_history(1.145, cat_accuracy_sparse=.99988) <ide> eval_output = self._build_eval_output(.928, 1.9844) <del> stats = keras_common.build_stats(history, eval_output) <add> stats = keras_common.build_stats(history, eval_output, None) <ide> <ide> self.assertEqual(1.145, stats['loss']) <ide> self.assertEqual(.99988, stats['training_accuracy_top_1']) <ide> <ide> self.assertEqual(.928, stats['accuracy_top_1']) <ide> self.assertEqual(1.9844, stats['eval_loss']) <ide> <add> def test_time_history(self): <add> th = keras_common.TimeHistory(batch_size=128, log_steps=3) <add> <add> th.on_train_begin() <add> th.on_batch_begin(0) <add> th.on_batch_end(0) <add> th.on_batch_begin(1) <add> th.on_batch_end(1) <add> th.on_batch_begin(2) <add> th.on_batch_end(2) <add> th.on_batch_begin(3) <add> th.on_batch_end(3) <add> th.on_batch_begin(4) <add> th.on_batch_end(4) <add> th.on_batch_begin(5) <add> th.on_batch_end(5) <add> th.on_batch_begin(6) <add> th.on_batch_end(6) <add> th.on_train_end() <add> <add> self.assertEqual(3, len(th.batch_start_timestamps)) <add> self.assertEqual(2, len(th.batch_end_timestamps)) <add> <add> self.assertEqual(0, th.batch_start_timestamps[0].batch_index) <add> self.assertEqual(1, th.batch_start_timestamps[1].batch_index) <add> self.assertEqual(4, th.batch_start_timestamps[2].batch_index) <add> <add> self.assertEqual(3, th.batch_end_timestamps[0].batch_index) <add> self.assertEqual(6, th.batch_end_timestamps[1].batch_index) <add> <ide> def _build_history(self, loss, cat_accuracy=None, <ide> cat_accuracy_sparse=None): <ide> history_p = Mock() <ide><path>official/resnet/keras/keras_imagenet_main.py <ide> def run(flags_obj): <ide> time_callback, <ide> lr_callback, <ide> tensorboard_callback <del> ], <add> ], <ide> validation_steps=num_eval_steps, <ide> validation_data=validation_data, <ide> verbose=1) <add> <ide> eval_output = None <ide> if not flags_obj.skip_eval: <ide> eval_output = model.evaluate(eval_input_dataset, <ide> steps=num_eval_steps, <ide> verbose=1) <del> <del> stats = keras_common.build_stats(history, eval_output) <add> stats = keras_common.build_stats(history, eval_output, time_callback) <ide> return stats <ide> <ide> <ide> def main(_): <ide> with logger.benchmark_context(flags.FLAGS): <del> run(flags.FLAGS) <add> return run(flags.FLAGS) <ide> <ide> <ide> if __name__ == '__main__':
4
Python
Python
use nodeauthpassword in vcloud
59afbb4a15aefd09ebd9714fa1e3cb7dcb1ae1e8
<ide><path>libcloud/drivers/vcloud.py <ide> <ide> from libcloud.providers import Provider <ide> from libcloud.types import NodeState, InvalidCredsException <del>from libcloud.base import Node, Response, ConnectionUserAndKey, NodeDriver, NodeSize, NodeImage <add>from libcloud.base import Node, Response, ConnectionUserAndKey, NodeDriver, NodeSize, NodeImage, NodeAuthPassword <ide> <ide> import base64 <ide> import httplib <ide> def create_node(self, **kwargs): <ide> except IndexError: <ide> network = '' <ide> <add> password = None <add> if kwargs.has_key('auth'): <add> auth = kwargs['auth'] <add> if isinstance(auth, NodeAuthPassword): <add> password = auth.password <add> else: <add> raise ValueError('auth must be of NodeAuthPassword type') <add> <ide> instantiate_xml = InstantiateVAppXML( <ide> name=name, <ide> template=image.id, <ide> net_href=network, <ide> cpus=str(kwargs.get('cpus', 1)), <ide> memory=str(size.ram), <del> password=kwargs.get('password', None), <add> password=password, <ide> row=kwargs.get('row', None), <ide> group=kwargs.get('group', None) <ide> ) <ide> def create_node(self, **kwargs): <ide> <ide> return node <ide> <add> features = {"create_node": ["password"]} <add> <ide> class HostingComConnection(VCloudConnection): <ide> host = "vcloud.safesecureweb.com" <ide>
1
Python
Python
add test for vocab serialization
7b1ddcc04da5e4bc366cc6bba0d14924e1999782
<ide><path>spacy/tests/serialize/test_serialization.py <ide> <ide> from ..util import get_doc, assert_docs_equal <ide> from ...tokens import Doc <add>from ...vocab import Vocab <ide> <ide> import pytest <ide> <ide> def test_serialize_empty_doc(en_vocab): <ide> for token1, token2 in zip(doc, doc2): <ide> assert token1.text == token2.text <ide> <add> <add>@pytest.mark.xfail <add>@pytest.mark.parametrize('text', ['rat']) <add>def test_serialize_vocab(en_vocab, text): <add> text_hash = en_vocab.strings.add(text) <add> vocab_bytes = en_vocab.to_bytes() <add> new_vocab = Vocab().from_bytes(vocab_bytes) <add> assert new_vocab.strings(text_hash) == text <add> <ide> # <ide> #@pytest.mark.parametrize('text', [TEXT]) <ide> #def test_serialize_tokens(en_vocab, text):
1
PHP
PHP
update syslog to use namespaces
8c57b0e4fc0e2fe956d8aef7f2da7e39b811314b
<ide><path>lib/Cake/Log/Engine/SyslogLog.php <ide> * @since CakePHP(tm) v 2.4 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <add>namespace Cake\Log\Engine; <ide> <del>App::uses('BaseLog', 'Log/Engine'); <add>use Cake\Log\Engine\BaseLog; <ide> <ide> /** <ide> * Syslog stream for Logging. Writes logs to the system logger <del> * <del> * @package Cake.Log.Engine <ide> */ <ide> class SyslogLog extends BaseLog { <ide> <ide> /** <ide> * <ide> * By default messages are formatted as: <del> * type: message <add> * type: message <ide> * <ide> * To override the log format (e.g. to add your own info) define the format key when configuring <ide> * this logger <add><path>lib/Cake/Test/TestCase/Log/Engine/SyslogLogTest.php <del><path>lib/Cake/Test/Case/Log/Engine/SyslogLogTest.php <ide> * @since CakePHP(tm) v 2.4 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <del>App::uses('SyslogLog', 'Log/Engine'); <add>namespace Cake\Test\TestCase\Log\Engine; <add> <add>use Cake\TestSuite\TestCase; <ide> <ide> /** <ide> * SyslogLogTest class <del> * <del> * @package Cake.Test.Case.Log.Engine <ide> */ <del>class SyslogLogTest extends CakeTestCase { <add>class SyslogLogTest extends TestCase { <ide> <ide> /** <ide> * Tests that the connection to the logger is open with the right arguments <ide> * <ide> * @return void <ide> */ <ide> public function testOpenLog() { <del> $log = $this->getMock('SyslogLog', array('_open', '_write')); <add> $log = $this->getMock('Cake\Log\Engine\SyslogLog', array('_open', '_write')); <ide> $log->expects($this->once())->method('_open')->with('', LOG_ODELAY, LOG_USER); <ide> $log->write('debug', 'message'); <ide> <del> $log = $this->getMock('SyslogLog', array('_open', '_write')); <add> $log = $this->getMock('Cake\Log\Engine\SyslogLog', array('_open', '_write')); <ide> $log->config(array( <ide> 'prefix' => 'thing', <ide> 'flag' => LOG_NDELAY, <ide> public function testOpenLog() { <ide> * @return void <ide> */ <ide> public function testWriteOneLine($type, $expected) { <del> $log = $this->getMock('SyslogLog', array('_open', '_write')); <add> $log = $this->getMock('Cake\Log\Engine\SyslogLog', array('_open', '_write')); <ide> $log->expects($this->once())->method('_write')->with($expected, $type . ': Foo'); <ide> $log->write($type, 'Foo'); <ide> } <ide> public function testWriteOneLine($type, $expected) { <ide> * @return void <ide> */ <ide> public function testWriteMultiLine() { <del> $log = $this->getMock('SyslogLog', array('_open', '_write')); <add> $log = $this->getMock('Cake\Log\Engine\SyslogLog', array('_open', '_write')); <ide> $log->expects($this->at(1))->method('_write')->with(LOG_DEBUG, 'debug: Foo'); <ide> $log->expects($this->at(2))->method('_write')->with(LOG_DEBUG, 'debug: Bar'); <ide> $log->expects($this->exactly(2))->method('_write');
2
Python
Python
replace getters/setters with properties - round 3
3074e50bfc5ee1435adf5ebc6dace6693579dfa0
<ide><path>glances/core/glances_client_browser.py <ide> def serve_forever(self): <ide> "Server list dictionnary change inside the loop (wait next update)") <ide> <ide> # Update the screen (list or Glances client) <del> if self.screen.get_active() is None: <add> if self.screen.active_server is None: <ide> # Display the Glances browser <ide> self.screen.update(self.get_servers_list()) <ide> else: <ide> # Display the Glances client for the selected server <del> logger.debug("Selected server: %s" % self.get_servers_list()[self.screen.get_active()]) <add> logger.debug("Selected server: {0}".format(self.get_servers_list()[self.screen.active_server])) <ide> <ide> # Connection can take time <ide> # Display a popup <ide> self.screen.display_popup(_("Connect to %s:%s" % (v['name'], v['port'])), duration=1) <ide> <ide> # A password is needed to access to the server's stats <del> if self.get_servers_list()[self.screen.get_active()]['password'] is None: <add> if self.get_servers_list()[self.screen.active_server]['password'] is None: <ide> from hashlib import sha256 <ide> # Display a popup to enter password <ide> clear_password = self.screen.display_popup(_("Password needed for %s: " % v['name']), is_input=True) <ide> def serve_forever(self): <ide> self.set_in_selected('password', encoded_password) <ide> <ide> # Display the Glance client on the selected server <del> logger.info("Connect Glances client to the %s server" % <del> self.get_servers_list()[self.screen.get_active()]['key']) <add> logger.info("Connect Glances client to the {0} server".format( <add> self.get_servers_list()[self.screen.active_server]['key'])) <ide> <ide> # Init the client <ide> args_server = self.args <ide> <ide> # Overwrite connection setting <del> args_server.client = self.get_servers_list()[self.screen.get_active()]['ip'] <del> args_server.port = self.get_servers_list()[self.screen.get_active()]['port'] <del> args_server.username = self.get_servers_list()[self.screen.get_active()]['username'] <del> args_server.password = self.get_servers_list()[self.screen.get_active()]['password'] <del> client = GlancesClient(config=self.config, <del> args=args_server, <del> return_to_browser=True) <add> args_server.client = self.get_servers_list()[self.screen.active_server]['ip'] <add> args_server.port = self.get_servers_list()[self.screen.active_server]['port'] <add> args_server.username = self.get_servers_list()[self.screen.active_server]['username'] <add> args_server.password = self.get_servers_list()[self.screen.active_server]['password'] <add> client = GlancesClient(config=self.config, args=args_server, return_to_browser=True) <ide> <ide> # Test if client and server are in the same major version <ide> if not client.login(): <ide> def serve_forever(self): <ide> connection_type = client.serve_forever() <ide> <ide> try: <del> logger.debug("Disconnect Glances client from the %s server" % <del> self.get_servers_list()[self.screen.get_active()]['key']) <add> logger.debug("Disconnect Glances client from the {0} server".format( <add> self.get_servers_list()[self.screen.active_server]['key'])) <ide> except IndexError: <ide> # Server did not exist anymore <ide> pass <ide> def serve_forever(self): <ide> self.set_in_selected('status', 'ONLINE') <ide> <ide> # Return to the browser (no server selected) <del> self.screen.set_active(None) <add> self.screen.active_server = None <ide> <ide> def set_in_selected(self, key, value): <del> """Set the (key, value) for the selected server in the list""" <add> """Set the (key, value) for the selected server in the list.""" <ide> # Static list then dynamic one <del> if self.screen.get_active() >= len(self.static_server.get_servers_list()): <del> self.autodiscover_server.set_server(self.screen.get_active() - len(self.static_server.get_servers_list()), <del> key, <del> value) <add> if self.screen.active_server >= len(self.static_server.get_servers_list()): <add> self.autodiscover_server.set_server( <add> self.screen.active_server - len(self.static_server.get_servers_list()), <add> key, value) <ide> else: <del> self.static_server.set_server(self.screen.get_active(), <del> key, <del> value) <add> self.static_server.set_server(self.screen.active_server, key, value) <ide> <ide> def end(self): <ide> """End of the client browser session.""" <ide><path>glances/outputs/glances_curses.py <ide> def __init__(self, args=None): <ide> self.__refresh_time = args.time <ide> <ide> # Init the cursor position for the client browser <del> self.cursor_init() <add> self.cursor_position = 0 <ide> <ide> # Active Glances server number <del> self.set_active() <add> self._active_server = None <ide> <del> def set_active(self, index=None): <del> """Set the active server or None if no server selected""" <del> self.active_server = index <add> @property <add> def active_server(self): <add> """Return the active server or None if it's the browser list.""" <add> return self._active_server <ide> <del> def get_active(self): <del> """Return the active server (the one display in front) or None if it is the browser list""" <del> return self.active_server <del> <del> def cursor_init(self): <del> """Init the cursor position to the top of the list""" <del> return self.cursor_set(0) <add> @active_server.setter <add> def active_server(self, index): <add> """Set the active server or None if no server selected.""" <add> self._active_server = index <ide> <del> def cursor_set(self, pos): <del> """Set the cursor position and return it""" <del> self.cursor_position = pos <del> <del> def cursor_get(self): <del> """Return the cursor position""" <add> @property <add> def cursor(self): <add> """Get the cursor position.""" <ide> return self.cursor_position <ide> <add> @cursor.setter <add> def cursor(self, position): <add> """Set the cursor position.""" <add> self.cursor_position = position <add> <ide> def cursor_up(self, servers_list): <ide> """Set the cursor to position N-1 in the list""" <ide> if self.cursor_position > 0: <ide> def __catch_key(self, servers_list): <ide> sys.exit(0) <ide> elif self.pressedkey == 10: <ide> # 'ENTER' > Run Glances on the selected server <del> logger.debug("Server number %s selected" % (self.cursor_get() + 1)) <del> self.set_active(self.cursor_get()) <add> logger.debug("Server number {0} selected".format(self.cursor + 1)) <add> self.active_server = self.cursor <ide> elif self.pressedkey == 259: <ide> # 'UP' > Up in the server list <ide> logger <ide> def update(self, servers_list): <ide> # Wait 100ms... <ide> curses.napms(100) <ide> <del> return self.get_active() <add> return self.active_server <ide> <ide> def flush(self, servers_list): <ide> """Update the servers' list screen. <ide> def display(self, servers_list): <ide> <ide> # If a servers has been deleted from the list... <ide> # ... and if the cursor is in the latest position <del> if self.cursor_get() > len(servers_list) - 1: <add> if self.cursor > len(servers_list) - 1: <ide> # Set the cursor position to the latest item <del> self.cursor_set(len(servers_list) - 1) <add> self.cursor = len(servers_list) - 1 <ide> <ide> # Display table <ide> line = 0 <ide> def display(self, servers_list): <ide> xc = x <ide> <ide> # Is the line selected ? <del> if line == self.cursor_get(): <add> if line == self.cursor: <ide> # Display cursor <del> self.term_window.addnstr(y, xc, <del> ">", <del> screen_x - xc, <del> self.colors_list['BOLD']) <add> self.term_window.addnstr( <add> y, xc, ">", screen_x - xc, self.colors_list['BOLD']) <ide> <ide> # Display alias instead of name <ide> server_stat <ide> def display(self, servers_list): <ide> for c in column_def: <ide> if xc < screen_x and y < screen_y and c[1] is not None: <ide> # Display server stats <del> self.term_window.addnstr(y, xc, <del> "%s" % server_stat[c[0]], <del> c[2], <del> self.colors_list[v['status']]) <add> self.term_window.addnstr( <add> y, xc, format(server_stat[c[0]]), c[2], self.colors_list[v['status']]) <ide> xc += c[2] + self.space_between_column <ide> cpt += 1 <ide> # Next line, next server...
2
Javascript
Javascript
fix bug with the readywait dom ready addition
1ac3713e7fa187838b04290ada9e4fc56e01f145
<ide><path>src/core.js <ide> jQuery.extend({ <ide> } <ide> <ide> // Make sure that the DOM is not already loaded <del> if ( !jQuery.readyWait && !jQuery.isReady ) { <add> if ( !jQuery.readyWait || (wait !== true && !jQuery.isReady) ) { <ide> // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). <ide> if ( !document.body ) { <ide> return setTimeout( jQuery.ready, 13 );
1
Javascript
Javascript
fix spelling error and reword for clarity
72ad746b85e3dcfefd794d7dc376e7ade798ff49
<ide><path>src/ng/directive/input.js <ide> var VALID_CLASS = 'ng-valid', <ide> * @description <ide> * <ide> * `NgModelController` provides API for the `ng-model` directive. The controller contains <del> * services for data-binding, validation, CSS update, value formatting and parsing. It <del> * specifically does not contain any logic which deals with DOM rendering or listening to <del> * DOM events. The `NgModelController` is meant to be extended by other directives where, the <del> * directive provides DOM manipulation and the `NgModelController` provides the data-binding. <add> * services for data-binding, validation, CSS updates, and value formatting and parsing. It <add> * purposefully does not contain any logic which deals with DOM rendering or listening to <add> * DOM events. Such DOM related logic should be provided by other directives which make use of <add> * `NgModelController` for data-binding. <ide> * Note that you cannot use `NgModelController` in a directive with an isolated scope, <ide> * as, in that case, the `ng-model` value gets put into the isolated scope and does not get <del> * propogated to the parent scope. <add> * propagated to the parent scope. <ide> * <ide> * <ide> * This example shows how to use `NgModelController` with a custom control to achieve
1
Javascript
Javascript
remove straggling test
aa3cb1eeac5ebe2e85b3bebf0b9f458d9b38237e
<ide><path>packages/ember-views/tests/views/view/nearest_view_test.js <del>var set = Ember.set, get = Ember.get; <del> <del>module("Ember.View nearest view helpers"); <del> <del>test("collectionView should return the nearest collection view", function() { <del> var itemViewChild; <del> <del> var view = Ember.CollectionView.create({ <del> content: Ember.A([1, 2, 3]), <del> isARealCollection: true, <del> <del> itemViewClass: Ember.View.extend({ <del> render: function(buffer) { <del> this.appendChild(Ember.View.create()); <del> } <del> }) <del> }); <del> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> itemViewChild = view.get('childViews')[0].get('childViews')[0]; <del> equal(itemViewChild.get('collectionView.isARealCollection'), true, "finds collection view in the hierarchy"); <del>}); <del> <del>test("itemView should return the nearest child of a collection view", function() { <del> var itemViewChild; <del> <del> var view = Ember.CollectionView.create({ <del> content: Ember.A([1, 2, 3]), <del> <del> itemViewClass: Ember.View.extend({ <del> isAnItemView: true, <del> <del> render: function(buffer) { <del> this.appendChild(Ember.View.create()); <del> } <del> }) <del> }); <del> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> itemViewChild = view.get('childViews')[0].get('childViews')[0]; <del> equal(itemViewChild.get('itemView.isAnItemView'), true, "finds item view in the hierarchy"); <del>}); <del> <del>test("itemView should return the nearest child of a collection view", function() { <del> var itemViewChild; <del> <del> var view = Ember.CollectionView.create({ <del> content: Ember.A([1, 2, 3]), <del> <del> itemViewClass: Ember.View.extend({ <del> isAnItemView: true, <del> <del> render: function(buffer) { <del> this.appendChild(Ember.View.create()); <del> } <del> }) <del> }); <del> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> itemViewChild = view.get('childViews')[0].get('childViews')[0]; <del> equal(itemViewChild.get('contentView.isAnItemView'), true, "finds a view with a content property in the hierarchy"); <del>}); <del> <del>test("nearestWithProperty should search immediate parent", function(){ <del> var childView; <del> <del> var view = Ember.View.create({ <del> myProp: true, <del> <del> render: function(buffer) { <del> this.appendChild(Ember.View.create()); <del> } <del> }); <del> <del> Ember.run(function() { <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> childView = view.get('childViews')[0]; <del> equal(childView.nearestWithProperty('myProp'), view); <del> <del>}); <del>
1
Javascript
Javascript
remove unreachable code paths from plugins
692d8a41281e65b66195835ff69b887dfa65af5f
<ide><path>src/plugins/plugin.filler.js <ide> class simpleArc { <ide> pathSegment(ctx, bounds, opts) { <ide> const {x, y, radius} = this; <ide> bounds = bounds || {start: 0, end: TAU}; <del> if (opts.reverse) { <del> ctx.arc(x, y, radius, bounds.end, bounds.start, true); <del> } else { <del> ctx.arc(x, y, radius, bounds.start, bounds.end); <del> } <add> ctx.arc(x, y, radius, bounds.end, bounds.start, true); <ide> return !opts.bounds; <ide> } <ide> <del> interpolate(point, property) { <add> interpolate(point) { <ide> const {x, y, radius} = this; <ide> const angle = point.angle; <del> if (property === 'angle') { <del> return { <del> x: x + Math.cos(angle) * radius, <del> y: y + Math.sin(angle) * radius, <del> angle <del> }; <del> } <add> return { <add> x: x + Math.cos(angle) * radius, <add> y: y + Math.sin(angle) * radius, <add> angle <add> }; <ide> } <ide> } <ide> <ide><path>src/plugins/plugin.title.js <ide> function createTitle(chart, titleOpts) { <ide> chart.titleBlock = title; <ide> } <ide> <del>function removeTitle(chart) { <del> const title = chart.titleBlock; <del> if (title) { <del> layouts.removeBox(chart, title); <del> delete chart.titleBlock; <del> } <del>} <del> <del>function createOrUpdateTitle(chart, options) { <del> const title = chart.titleBlock; <del> if (title) { <del> layouts.configure(chart, title, options); <del> title.options = options; <del> } else { <del> createTitle(chart, options); <del> } <del>} <del> <ide> export default { <ide> id: 'title', <ide> <ide> export default { <ide> }, <ide> <ide> beforeUpdate(chart, _args, options) { <del> if (options === false) { <del> removeTitle(chart); <del> } else { <del> createOrUpdateTitle(chart, options); <del> } <add> const title = chart.titleBlock; <add> layouts.configure(chart, title, options); <add> title.options = options; <ide> }, <ide> <ide> defaults: {
2
Javascript
Javascript
fix tests for webworkermaintemplateplugin
60900aaee7c9bee6da5ca22ca3ba9d9d286d612b
<ide><path>test/WebWorkerMainTemplatePlugin.test.js <ide> const sinon = require("sinon"); <ide> const WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin"); <ide> const applyPluginWithOptions = require("./helpers/applyPluginWithOptions"); <ide> <del>describe("WebWorkerMainTemplatePlugin", function() { <add>const createMockChunk = (ids, chunks) => { <add> return { <add> ids: ids, <add> _chunks: new Set(chunks), <add> getChunks() { <add> return this._chunks; <add> } <add> }; <add>}; <add> <add>describe("WebWorkerMainTemplatePlugin", function () { <ide> let env; <ide> <ide> beforeEach(() => { <ide> env = {}; <ide> }); <ide> <del> it("has apply function", function() { <add> it("has apply function", function () { <ide> (new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function(); <ide> }); <ide> <del> describe("when applied", function() { <del> beforeEach(function() { <add> describe("when applied", function () { <add> beforeEach(function () { <ide> env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin); <ide> env.handlerContext = { <ide> requireFn: 'requireFn', <ide> describe("WebWorkerMainTemplatePlugin", function() { <ide> }; <ide> }); <ide> <del> it("binds five event handlers", function() { <add> it("binds five event handlers", function () { <ide> env.eventBindings.length.should.be.exactly(5); <ide> }); <ide> <del> describe("local-vars handler", function() { <add> describe("local-vars handler", function () { <ide> beforeEach(() => { <ide> env.eventBinding = env.eventBindings[0]; <ide> }); <ide> describe("WebWorkerMainTemplatePlugin", function() { <ide> <ide> describe("when no chunks are provided", () => { <ide> beforeEach(() => { <del> const chunk = { <del> ids: [], <del> chunks: [] <del> }; <add> const chunk = createMockChunk(); <ide> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); <ide> }); <ide> <ide> describe("WebWorkerMainTemplatePlugin", function() { <ide> <ide> describe("when chunks are provided", () => { <ide> beforeEach(() => { <del> const chunk = { <del> ids: [1, 2, 3], <del> chunks: [ <del> 'foo', <del> 'bar', <del> 'baz' <del> ] <del> }; <add> const chunk = createMockChunk([1, 2, 3], [ <add> 'foo', <add> 'bar', <add> 'baz' <add> ]); <ide> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123'); <ide> }); <ide> <ide> var installedChunks = { <ide> <ide> describe("when called", () => { <ide> beforeEach(() => { <del> const chunk = {}; <add> const chunk = createMockChunk(); <ide> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123'); <ide> }); <ide> <ide> resolve(); <ide> <ide> describe("when no chunks are provided", () => { <ide> beforeEach(() => { <del> const chunk = { <del> ids: [], <del> chunks: [] <del> }; <add> const chunk = createMockChunk(); <ide> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); <ide> }); <ide> <ide> resolve(); <ide> <ide> describe("when chunks are provided", () => { <ide> beforeEach(() => { <del> const chunk = { <del> ids: [1, 2, 3], <del> chunks: [ <del> 'foo', <del> 'bar', <del> 'baz' <del> ] <del> }; <add> const chunk = createMockChunk([1, 2, 3], [ <add> 'foo', <add> 'bar', <add> 'baz' <add> ]); <ide> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk); <ide> }); <ide> <ide> installedChunks[chunkIds.pop()] = 1; <ide> <ide> describe("when called", () => { <ide> beforeEach(() => { <del> const chunk = {}; <add> const chunk = createMockChunk(); <ide> env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123'); <ide> }); <ide>
1
Javascript
Javascript
fix undefined reference in fs.js
6bd11f147ab6277a672f8e36e707306752d93538
<ide><path>lib/fs.js <ide> var sys = require('./sys'), <ide> events = require('events'); <ide> <add>var fs = exports; <add> <ide> exports.Stats = process.Stats; <ide> <ide> process.Stats.prototype._checkModeProperty = function (property) {
1
Javascript
Javascript
fix names of options to match the exported types
0f22db981dc615d76be1c7dd74fc840fae41827c
<ide><path>lib/config/defaults.js <ide> const applyJavascriptParserOptionsDefaults = ( <ide> D(parserOptions, "wrappedContextRecursive", true); <ide> D(parserOptions, "wrappedContextCritical", false); <ide> D(parserOptions, "strictThisContextOnImports", false); <del> if (futureDefaults) D(parserOptions, "exportPresence", "error"); <add> if (futureDefaults) D(parserOptions, "exportsPresence", "error"); <ide> }; <ide> <ide> /** <ide><path>lib/dependencies/HarmonyExportDependencyParserPlugin.js <ide> const { HarmonyStarExportsList } = HarmonyExportImportedSpecifierDependency; <ide> module.exports = class HarmonyExportDependencyParserPlugin { <ide> constructor(options) { <ide> this.exportPresenceMode = <del> options.reexportExportPresence !== undefined <del> ? ExportPresenceModes.fromUserOption(options.reexportExportPresence) <del> : options.exportPresence !== undefined <del> ? ExportPresenceModes.fromUserOption(options.exportPresence) <add> options.reexportExportsPresence !== undefined <add> ? ExportPresenceModes.fromUserOption(options.reexportExportsPresence) <add> : options.exportsPresence !== undefined <add> ? ExportPresenceModes.fromUserOption(options.exportsPresence) <ide> : options.strictExportPresence <ide> ? ExportPresenceModes.ERROR <ide> : ExportPresenceModes.AUTO; <ide><path>lib/dependencies/HarmonyExportImportedSpecifierDependency.js <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> * @returns {WebpackError[]} warnings <ide> */ <ide> getWarnings(moduleGraph) { <del> const exportPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <del> if (exportPresence === ExportPresenceModes.WARN) { <add> const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <add> if (exportsPresence === ExportPresenceModes.WARN) { <ide> return this._getErrors(moduleGraph); <ide> } <ide> return null; <ide> class HarmonyExportImportedSpecifierDependency extends HarmonyImportDependency { <ide> * @returns {WebpackError[]} errors <ide> */ <ide> getErrors(moduleGraph) { <del> const exportPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <del> if (exportPresence === ExportPresenceModes.ERROR) { <add> const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <add> if (exportsPresence === ExportPresenceModes.ERROR) { <ide> return this._getErrors(moduleGraph); <ide> } <ide> return null; <ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js <ide> module.exports = class HarmonyImportDependencyParserPlugin { <ide> */ <ide> constructor(options) { <ide> this.exportPresenceMode = <del> options.importExportPresence !== undefined <del> ? ExportPresenceModes.fromUserOption(options.importExportPresence) <del> : options.exportPresence !== undefined <del> ? ExportPresenceModes.fromUserOption(options.exportPresence) <add> options.importExportsPresence !== undefined <add> ? ExportPresenceModes.fromUserOption(options.importExportsPresence) <add> : options.exportsPresence !== undefined <add> ? ExportPresenceModes.fromUserOption(options.exportsPresence) <ide> : options.strictExportPresence <ide> ? ExportPresenceModes.ERROR <ide> : ExportPresenceModes.AUTO; <ide><path>lib/dependencies/HarmonyImportSpecifierDependency.js <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> * @returns {WebpackError[]} warnings <ide> */ <ide> getWarnings(moduleGraph) { <del> const exportPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <del> if (exportPresence === ExportPresenceModes.WARN) { <add> const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <add> if (exportsPresence === ExportPresenceModes.WARN) { <ide> return this._getErrors(moduleGraph); <ide> } <ide> return null; <ide> class HarmonyImportSpecifierDependency extends HarmonyImportDependency { <ide> * @returns {WebpackError[]} errors <ide> */ <ide> getErrors(moduleGraph) { <del> const exportPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <del> if (exportPresence === ExportPresenceModes.ERROR) { <add> const exportsPresence = this._getEffectiveExportPresenceLevel(moduleGraph); <add> if (exportsPresence === ExportPresenceModes.ERROR) { <ide> return this._getErrors(moduleGraph); <ide> } <ide> return null; <ide><path>test/Defaults.unittest.js <ide> describe("Defaults", () => { <ide> + }, <ide> + Object { <ide> <del> + "exportPresence": "error", <add> + "exportsPresence": "error", <ide> <ide> - "__dirname": "mock", <ide> - "__filename": "mock", <ide><path>test/configCases/compiletime/exports-presence/webpack.config.js <ide> module.exports = { <ide> { <ide> test: /aaa/, <ide> parser: { <del> exportPresence: false <add> exportsPresence: false <ide> } <ide> }, <ide> { <ide> test: /bbb/, <ide> parser: { <del> exportPresence: "warn" <add> exportsPresence: "warn" <ide> } <ide> }, <ide> { <ide> test: /ccc/, <ide> parser: { <del> exportPresence: "error" <add> exportsPresence: "error" <ide> } <ide> }, <ide> { <ide> test: /ddd/, <ide> parser: { <del> exportPresence: "error", <del> importExportPresence: "warn", <del> reexportExportPresence: false <add> exportsPresence: "error", <add> importExportsPresence: "warn", <add> reexportExportsPresence: false <ide> } <ide> } <ide> ]
7
Javascript
Javascript
adopt box3 in buffergeometry
d782e3a17e3c0bff7151e5270aefd8ea1151bbfd
<ide><path>src/core/BufferGeometry.js <ide> THREE.BufferGeometry.prototype = { <ide> <ide> if ( ! this.boundingBox ) { <ide> <del> this.boundingBox = { <del> <del> min: new THREE.Vector3( Infinity, Infinity, Infinity ), <del> max: new THREE.Vector3( -Infinity, -Infinity, -Infinity ) <del> <del> }; <add> this.boundingBox = new THREE.Box3(); <ide> <ide> } <ide> <ide> THREE.BufferGeometry.prototype = { <ide> <ide> computeBoundingSphere: function () { <ide> <del> if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 }; <add> if ( ! this.boundingSphere ) { <add> this.boundingSphere = new THREE.Sphere(); <add> } <ide> <ide> var positions = this.attributes[ "position" ].array; <ide>
1
PHP
PHP
add missing parameter to optionparser
3fa46f58bf51f90833c2a9cc5222b4fe56de7be3
<ide><path>src/Console/Command/Task/TestTask.php <ide> public function getOptionParser() { <ide> ])->addOption('force', [ <ide> 'short' => 'f', <ide> 'help' => __d('cake_console', 'Force overwriting existing files without prompting.') <add> ])->addOption('fixtures', [ <add> 'help' => __d('cake_console', 'A comma separated list of fixture names you want to include.') <ide> ]); <ide> <ide> return $parser;
1
Ruby
Ruby
reset raw_post_data between test requests
7a8d9649cdefe5706003e1e377e22722962dff22
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def head(action, **args) <ide> def process(action, method: "GET", params: {}, session: nil, body: nil, flash: {}, format: nil, xhr: false, as: nil) <ide> check_required_ivars <ide> <del> if body <del> @request.set_header "RAW_POST_DATA", body <del> end <del> <ide> http_method = method.to_s.upcase <ide> <ide> @html_document = nil <ide> def process(action, method: "GET", params: {}, session: nil, body: nil, flash: { <ide> @response.request = @request <ide> @controller.recycle! <ide> <add> if body <add> @request.set_header "RAW_POST_DATA", body <add> end <add> <ide> @request.set_header "REQUEST_METHOD", http_method <ide> <ide> if as <ide> def scrub_env!(env) <ide> env.delete "action_dispatch.request.query_parameters" <ide> env.delete "action_dispatch.request.request_parameters" <ide> env["rack.input"] = StringIO.new <add> env.delete "RAW_POST_DATA" <ide> env <ide> end <ide> <ide><path>actionpack/test/controller/test_case_test.rb <ide> def test_filtered_parameters_reset_between_requests <ide> assert_equal "baz", @request.filtered_parameters[:foo] <ide> end <ide> <add> def test_raw_post_reset_between_post_requests <add> post :no_op, params: { foo: "bar" } <add> assert_equal "foo=bar", @request.raw_post <add> <add> post :no_op, params: { foo: "baz" } <add> assert_equal "foo=baz", @request.raw_post <add> end <add> <ide> def test_path_is_kept_after_the_request <ide> get :test_params, params: { id: "foo" } <ide> assert_equal "/test_case_test/test/test_params/foo", @request.path
2
Text
Text
add notes about creating a ui theme
201677eb1d81dedc0e7db9981bee114d724fca10
<ide><path>docs/creating-a-theme.md <ide> contains all of the variables provided by the [core themes][ui-variables]. <ide> Syntax themes don't need to provide any variables to other themes and only <ide> target elements within the editor. <ide> <add>To create a UI theme, do the following: <add> <add>1. Fork one of the following repos <add> 1. [atom-dark-ui] <add> 1. [atom-light-ui] <add>1. Open a terminal in the forked theme's directory <add>1. Open your new theme in a Dev Mode Atom window (either run `atom -d .` in the terminal or use `cmd-shift-o` from atom) <add>1. Change the name of the theme in the theme's `package.json` file <add>1. Run `apm link` to tell Atom about your new theme <add>1. Reload Atom (`cmd-r`) <add>1. Enable the theme via the themes panel in settings <add>1. Make changes! Since you opened the theme in a Dev Mode window, changes will <add> be instantly reflected in the editor without having to reload. <add> <ide> ## Development workflow <ide> <del>There are a few of tools to help make theme development much faster. <add>There are a few of tools to help make theme development fast. <ide> <ide> ### Live Reload <ide> <ide> changes affect all the components in the system. The [styleguide] is a page with <ide> every component Atom supports rendered. <ide> <ide> To open the styleguide, open the command palette (`cmd-p`) and search for <del>styleguide or use the shortcut `cmd-ctrl-shift-g`. <add>_styleguide_ or use the shortcut `cmd-ctrl-shift-g`. <ide> <ide> ![styleguide-img] <ide> <ide> styleguide or use the shortcut `cmd-ctrl-shift-g`. <ide> [ui-variables]: https://github.com/atom/atom-dark-ui/blob/master/stylesheets/ui-variables.less <ide> [livereload]: https://github.com/atom/dev-live-reload <ide> [styleguide]: https://github.com/atom/styleguide <add>[atom-dark-ui]: https://github.com/atom/atom-dark-ui <add>[atom-light-ui]: https://github.com/atom/atom-light-ui <ide> [styleguide-img]: https://f.cloud.github.com/assets/69169/1347390/2d431d98-36af-11e3-8f8e-3f4ce1e67adb.png <ide> [devtools-img]: https://f.cloud.github.com/assets/69169/1347391/2d51f91c-36af-11e3-806f-f7b334af43e9.png <ide> [themesettings-img]: https://f.cloud.github.com/assets/69169/1347569/3150bd0c-36b2-11e3-9d69-423503acfe3f.png
1
Ruby
Ruby
fix spelling mistakes
f55fe55d5aeb7f58c47d2b12f2e805c6df9690bd
<ide><path>activejob/test/cases/test_case_test.rb <ide> <ide> class ActiveJobTestCaseTest < ActiveJob::TestCase <ide> # this tests that this job class doesn't get its adapter set. <del> # that's the correct behaviour since we don't want to break <del> # the `class_attribute` inheritence <del> class TestClassAttributeInheritenceJob < ActiveJob::Base <add> # that's the correct behavior since we don't want to break <add> # the `class_attribute` inheritance <add> class TestClassAttributeInheritanceJob < ActiveJob::Base <ide> def self.queue_adapter=(*) <del> raise 'Attemping to break `class_attribute` inheritence, bad!' <add> raise 'Attemping to break `class_attribute` inheritance, bad!' <ide> end <ide> end <ide>
1
Go
Go
add credentialspec from configs support
04995fa7c71216969e17670cc3fb938de137af35
<ide><path>daemon/cluster/executor/container/container.go <ide> func (c *containerConfig) applyPrivileges(hc *enginecontainer.HostConfig) { <ide> hc.SecurityOpt = append(hc.SecurityOpt, "credentialspec=file://"+credentials.GetFile()) <ide> case *api.Privileges_CredentialSpec_Registry: <ide> hc.SecurityOpt = append(hc.SecurityOpt, "credentialspec=registry://"+credentials.GetRegistry()) <add> case *api.Privileges_CredentialSpec_Config: <add> hc.SecurityOpt = append(hc.SecurityOpt, "credentialspec=config://"+credentials.GetConfig()) <ide> } <ide> } <ide> <ide><path>daemon/oci_windows.go <ide> func (daemon *Daemon) createSpecWindowsFields(c *container.Container, s *specs.S <ide> if cs, err = readCredentialSpecRegistry(c.ID, csValue); err != nil { <ide> return err <ide> } <add> } else if match, csValue = getCredentialSpec("config://", splitsOpt[1]); match { <add> if csValue == "" { <add> return fmt.Errorf("no value supplied for config:// credential spec security option") <add> } <add> <add> // if the container does not have a DependencyStore, then we <add> // return an error <add> if c.DependencyStore == nil { <add> return fmt.Errorf("cannot use config:// credential spec security option if not swarmkit managed") <add> } <add> csConfig, err := c.DependencyStore.Configs().Get(csValue) <add> if err != nil { <add> return fmt.Errorf("error getting value from config store: %v", err) <add> } <add> // stuff the resulting secret data into a string to use as the <add> // CredentialSpec <add> cs = string(csConfig.Spec.Data) <ide> } else { <ide> return fmt.Errorf("invalid credential spec security option - value must be prefixed file:// or registry:// followed by a value") <ide> }
2
Ruby
Ruby
modernize size calculation in schema cache
f45084c746a79cee3ff6c08fc4e42be15cac2bba
<ide><path>activerecord/lib/active_record/connection_adapters/schema_cache.rb <ide> def clear! <ide> end <ide> <ide> def size <del> [@columns, @columns_hash, @primary_keys, @data_sources].map(&:size).inject :+ <add> [@columns, @columns_hash, @primary_keys, @data_sources].sum(&:size) <ide> end <ide> <ide> # Clear out internal caches for the data source +name+.
1
Python
Python
add example for training text classifier
2bc7d87c705b038d699309b25eec7ab3df4e9308
<ide><path>examples/training/train_textcat.py <add>from __future__ import unicode_literals <add>import plac <add>import random <add>import tqdm <add> <add>from thinc.neural.optimizers import Adam <add>from thinc.neural.ops import NumpyOps <add>import thinc.extra.datasets <add> <add>import spacy.lang.en <add>from spacy.gold import GoldParse, minibatch <add>from spacy.util import compounding <add>from spacy.pipeline import TextCategorizer <add> <add> <add>def train_textcat(tokenizer, textcat, <add> train_texts, train_cats, dev_texts, dev_cats, <add> n_iter=20): <add> ''' <add> Train the TextCategorizer without associated pipeline. <add> ''' <add> textcat.begin_training() <add> optimizer = Adam(NumpyOps(), 0.001) <add> train_docs = [tokenizer(text) for text in train_texts] <add> train_gold = [GoldParse(doc, cats=cats) for doc, cats in <add> zip(train_docs, train_cats)] <add> train_data = zip(train_docs, train_gold) <add> batch_sizes = compounding(4., 128., 1.001) <add> for i in range(n_iter): <add> losses = {} <add> for batch in minibatch(tqdm.tqdm(train_data, leave=False), <add> size=batch_sizes): <add> docs, golds = zip(*batch) <add> textcat.update((docs, None), golds, sgd=optimizer, drop=0.2, <add> losses=losses) <add> with textcat.model.use_params(optimizer.averages): <add> scores = evaluate(tokenizer, textcat, dev_texts, dev_cats) <add> yield losses['textcat'], scores <add> <add> <add>def evaluate(tokenizer, textcat, texts, cats): <add> docs = (tokenizer(text) for text in texts) <add> tp = 1e-8 # True positives <add> fp = 1e-8 # False positives <add> fn = 1e-8 # False negatives <add> tn = 1e-8 # True negatives <add> for i, doc in enumerate(textcat.pipe(docs)): <add> gold = cats[i] <add> for label, score in doc.cats.items(): <add> if score >= 0.5 and label in gold: <add> tp += 1. <add> elif score >= 0.5 and label not in gold: <add> fp += 1. <add> elif score < 0.5 and label not in gold: <add> tn += 1 <add> if score < 0.5 and label in gold: <add> fn += 1 <add> precis = tp / (tp + fp) <add> recall = tp / (tp + fn) <add> fscore = 2 * (precis * recall) / (precis + recall) <add> return {'textcat_p': precis, 'textcat_r': recall, 'textcat_f': fscore} <add> <add> <add>def load_data(): <add> # Partition off part of the train data --- avoid running experiments <add> # against test. <add> train_data, _ = thinc.extra.datasets.imdb() <add> <add> random.shuffle(train_data) <add> <add> texts, labels = zip(*train_data) <add> cats = [(['POSITIVE'] if y else []) for y in labels] <add> <add> split = int(len(train_data) * 0.8) <add> <add> train_texts = texts[:split] <add> train_cats = cats[:split] <add> dev_texts = texts[split:] <add> dev_cats = cats[split:] <add> return (train_texts, train_cats), (dev_texts, dev_cats) <add> <add> <add>def main(): <add> nlp = spacy.lang.en.English() <add> tokenizer = nlp.tokenizer <add> textcat = TextCategorizer(tokenizer.vocab, labels=['POSITIVE']) <add> <add> print("Load IMDB data") <add> (train_texts, train_cats), (dev_texts, dev_cats) = load_data() <add> <add> print("Itn.\tLoss\tP\tR\tF") <add> progress = '{i:d} {loss:.3f} {textcat_p:.3f} {textcat_r:.3f} {textcat_f:.3f}' <add> <add> for i, (loss, scores) in enumerate(train_textcat(tokenizer, textcat, <add> train_texts, train_cats, <add> dev_texts, dev_cats, n_iter=20)): <add> print(progress.format(i=i, loss=loss, **scores)) <add> <add> <add>if __name__ == '__main__': <add> plac.call(main)
1
Text
Text
accept contributer agreement
35272eade8b7088ce7159a67ae220891a05de886
<ide><path>.github/CONTRIBUTOR_AGREEMENT.md <ide> U.S. Federal law. Any choice of law rules will not apply. <ide> 7. Please place an “x” on one of the applicable statement below. Please do NOT <ide> mark both statements: <ide> <del> * [ ] I am signing on behalf of myself as an individual and no other person <add> * [x] I am signing on behalf of myself as an individual and no other person <ide> or entity, including my employer, has or will have rights with respect to my <ide> contributions. <ide> <del> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> * [x] I am signing on behalf of my employer or a legal entity and I have the <ide> actual authority to contractually bind that entity. <ide> <ide> ## Contributor Details
1
Javascript
Javascript
remove an internal argument to the remove method
349edbd6c53aa93d4fd207d3c0c4c24a7b0314dd
<ide><path>src/manipulation.js <ide> function domManip( collection, args, callback, ignored ) { <ide> return collection; <ide> } <ide> <add>function remove( elem, selector, keepData ) { <add> var node, <add> nodes = selector ? jQuery.filter( selector, elem ) : elem, <add> i = 0; <add> <add> for ( ; (node = nodes[i]) != null; i++ ) { <add> if ( !keepData && node.nodeType === 1 ) { <add> jQuery.cleanData( getAll( node ) ); <add> } <add> <add> if ( node.parentNode ) { <add> if ( keepData && jQuery.contains( node.ownerDocument, node ) ) { <add> setGlobalEval( getAll( node, "script" ) ); <add> } <add> node.parentNode.removeChild( node ); <add> } <add> } <add> <add> return elem; <add>} <add> <ide> jQuery.extend({ <ide> htmlPrefilter: function( html ) { <ide> return html.replace( rxhtmlTag, "<$1></$2>" ); <ide> jQuery.extend({ <ide> }); <ide> <ide> jQuery.fn.extend({ <add> detach: function( selector ) { <add> return remove( this, selector, true ); <add> }, <add> <add> remove: function( selector ) { <add> return remove( this, selector ); <add> }, <add> <ide> text: function( value ) { <ide> return access( this, function( value ) { <ide> return value === undefined ? <ide> jQuery.fn.extend({ <ide> }); <ide> }, <ide> <del> remove: function( selector, keepData /* Internal Use Only */ ) { <del> var elem, <del> elems = selector ? jQuery.filter( selector, this ) : this, <del> i = 0; <del> <del> for ( ; (elem = elems[i]) != null; i++ ) { <del> if ( !keepData && elem.nodeType === 1 ) { <del> jQuery.cleanData( getAll( elem ) ); <del> } <del> <del> if ( elem.parentNode ) { <del> if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { <del> setGlobalEval( getAll( elem, "script" ) ); <del> } <del> elem.parentNode.removeChild( elem ); <del> } <del> } <del> <del> return this; <del> }, <del> <ide> empty: function() { <ide> var elem, <ide> i = 0; <ide> jQuery.fn.extend({ <ide> <ide> // Force callback invocation <ide> }, ignored ); <del> }, <del> <del> detach: function( selector ) { <del> return this.remove( selector, true ); <ide> } <ide> }); <ide>
1
Ruby
Ruby
write bottle metadata files
dbccff4d8019aedb414ff007a2578a2a46910484
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> class Step <ide> attr_reader :command, :name, :status, :output, :time <ide> <del> def initialize test, command, puts_output_on_success = false <add> def initialize test, command, options={} <ide> @test = test <ide> @category = test.category <ide> @command = command <del> @puts_output_on_success = puts_output_on_success <add> @puts_output_on_success = options[:puts_output_on_success] <ide> @name = command.split[1].delete '-' <ide> @status = :running <ide> @repository = HOMEBREW_REPOSITORY <ide> def formula formula <ide> test "brew install --verbose #{dependencies}" unless dependencies.empty? <ide> test "brew install --verbose --build-bottle #{formula}" <ide> return unless steps.last.passed? <del> test "brew bottle #{formula}", true <add> bottle_step = test "brew bottle #{formula}", :puts_output_on_success => true <ide> bottle_revision = bottle_new_revision(formula_object) <ide> bottle_filename = bottle_filename(formula_object, bottle_revision) <add> if bottle_step.passed? and bottle_step.has_output? <add> bottle_base = bottle_filename.gsub(bottle_suffix(bottle_revision), '') <add> bottle_output = bottle_step.output.gsub /.*(bottle do.*end)/m, '\1' <add> File.open "#{bottle_base}.bottle.rb", 'w' do |file| <add> file.write bottle_output <add> end <add> end <ide> test "brew uninstall #{formula}" <ide> test "brew install #{bottle_filename}" <ide> test "brew test #{formula}" if formula_object.test_defined? <ide> def cleanup_after <ide> FileUtils.rm_rf @brewbot_root unless ARGV.include? "--keep-logs" <ide> end <ide> <del> def test cmd, puts_output_on_success = false <del> step = Step.new self, cmd, puts_output_on_success <add> def test cmd, options={} <add> step = Step.new self, cmd, options <ide> step.run <ide> steps << step <add> step <ide> end <ide> <ide> def check_results
1
Python
Python
improve assets and dvc handling
8cb7f9ccff5da3a5eaeb3c3ebe99214f6673d084
<ide><path>spacy/cli/project.py <del>from typing import List, Dict, Any, Optional, Sequence <add>from typing import List, Dict, Any, Optional, Sequence, Union <ide> import typer <ide> import srsly <ide> from pathlib import Path <ide> from ..util import get_hash, get_checksum, split_command <ide> <ide> <del>CONFIG_FILE = "project.yml" <add>PROJECT_FILE = "project.yml" <ide> DVC_CONFIG = "dvc.yaml" <ide> DVC_DIR = ".dvc" <ide> DIRS = [ <ide> os.environ.get("TORCH_HOME"), <ide> Path.home() / ".keras", <ide> ] <del>DVC_CONFIG_COMMENT = """# This file is auto-generated by spaCy based on your project.yml. Do not edit <del># it directly and edit the project.yml instead and re-run the project.""" <add>DVC_CONFIG_COMMENT = f"""# This file is auto-generated by spaCy based on your {PROJECT_FILE}. Do not edit <add># it directly and edit the {PROJECT_FILE} instead and re-run the project.""" <ide> CLI_HELP = f"""Command-line interface for spaCy projects and working with project <ide> templates. You'd typically start by cloning a project template to a local <ide> directory and fetching its assets like datasets etc. See the project's <del>{CONFIG_FILE} for the available commands. Under the hood, spaCy uses DVC (Data <add>{PROJECT_FILE} for the available commands. Under the hood, spaCy uses DVC (Data <ide> Version Control) to manage input and output files and to ensure steps are only <ide> re-run if their inputs change. <ide> """ <ide> def project_init_cli( <ide> # fmt: off <ide> path: Path = Arg(Path.cwd(), help="Path to cloned project. Defaults to current working directory.", exists=True, file_okay=False), <ide> git: bool = Opt(False, "--git", "-G", help="Initialize project as a Git repo"), <del> force: bool = Opt(False, "--force", "-F", help="Force initiziation"), <add> force: bool = Opt(False, "--force", "-F", "-f", help="Force initiziation"), <ide> # fmt: on <ide> ): <ide> """Initialize a project directory with DVC and optionally Git. This should <ide> def project_init_cli( <ide> be a Git repo, it should be initialized with Git first, before initializing <ide> DVC. This allows DVC to integrate with Git. <ide> """ <del> project_init(path, git=git, force=force, silent=True) <add> project_init(path, git=git, force=force) <ide> <ide> <ide> @project_cli.command("assets") <ide> def project_assets_cli( <ide> # fmt: on <ide> ): <ide> """Use DVC (Data Version Control) to fetch project assets. Assets are <del> defined in the "assets" section of the project config. If possible, DVC <add> defined in the "assets" section of the project.yml. If possible, DVC <ide> will try to track the files so you can pull changes from upstream. It will <ide> also try and store the checksum so the assets are versioned. If the file <ide> can't be tracked or checked, it will be downloaded without DVC. If a checksum <del> is provided in the project config, the file is only downloaded if no local <add> is provided in the project.yml, the file is only downloaded if no local <ide> file with the same checksum exists. <ide> """ <ide> project_assets(project_dir) <ide> def project_run_all_cli( <ide> # fmt: on <ide> ): <ide> """Run all commands defined in the project. This command will use DVC and <del> the defined outputs and dependencies in the project config to determine <add> the defined outputs and dependencies in the project.yml to determine <ide> which steps need to be re-run and where to start. This means you're only <ide> re-generating data if the inputs have changed. <ide> <ide> def project_run_all_cli( <ide> def project_run_cli( <ide> # fmt: off <ide> ctx: typer.Context, <del> subcommand: str = Arg(None, help="Name of command defined in project config"), <add> subcommand: str = Arg(None, help=f"Name of command defined in the {PROJECT_FILE}"), <ide> project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False), <ide> show_help: bool = Opt(False, "--help", help="Show help message and available subcommands") <ide> # fmt: on <ide> ): <del> """Run a named script defined in the project config. If the command is <add> """Run a named script defined in the project.yml. If the command is <ide> part of the default pipeline defined in the "run" section, DVC is used to <ide> determine whether the step should re-run if its inputs have changed, or <ide> whether everything is up to date. If the script is not part of the default <ide> def project_run_cli( <ide> @project_cli.command("exec", hidden=True) <ide> def project_exec_cli( <ide> # fmt: off <del> subcommand: str = Arg(..., help="Name of command defined in project config"), <add> subcommand: str = Arg(..., help=f"Name of command defined in the {PROJECT_FILE}"), <ide> project_dir: Path = Arg(Path.cwd(), help="Location of project directory. Defaults to current working directory.", exists=True, file_okay=False), <ide> # fmt: on <ide> ): <del> """Execute a command defined in the project config. This CLI command is <add> """Execute a command defined in the project.yml. This CLI command is <ide> only called internally in auto-generated DVC pipelines, as a shortcut for <del> multi-step commands in the project config. You typically shouldn't have to <add> multi-step commands in the project.yml. You typically shouldn't have to <ide> call it yourself. To run a command, call "run" or "run-all". <ide> """ <ide> project_exec(project_dir, subcommand) <ide> def project_update_dvc_cli( <ide> # fmt: on <ide> ): <ide> """Update the auto-generated DVC config file. Uses the steps defined in the <del> "run" section of the project config. This typically happens automatically <add> "run" section of the project.yml. This typically happens automatically <ide> when running a command, but can also be triggered manually if needed. <ide> """ <ide> config = load_project_config(project_dir) <ide> updated = update_dvc_config(project_dir, config, verbose=verbose, force=force) <ide> if updated: <del> msg.good(f"Updated DVC config from {CONFIG_FILE}") <add> msg.good(f"Updated DVC config from {PROJECT_FILE}") <ide> else: <del> msg.info(f"No changes found in {CONFIG_FILE}, no update needed") <add> msg.info(f"No changes found in {PROJECT_FILE}, no update needed") <ide> <ide> <ide> app.add_typer(project_cli, name="project") <ide> def project_clone( <ide> cmd = f"git clone {repo} {tmp_dir} --no-checkout --depth 1 --config core.sparseCheckout=true" <ide> try: <ide> run_command(cmd) <del> except SystemExit: <add> except DVCError: <ide> err = f"Could not clone the repo '{repo}' into the temp dir '{tmp_dir}'." <ide> msg.fail(err) <ide> with (tmp_dir / ".git" / "info" / "sparse-checkout").open("w") as f: <ide> f.write(name) <ide> try: <ide> run_command(["git", "-C", str(tmp_dir), "fetch"]) <ide> run_command(["git", "-C", str(tmp_dir), "checkout"]) <del> except SystemExit: <add> except DVCError: <ide> err = f"Could not clone '{name}' in the repo '{repo}'." <ide> msg.fail(err) <ide> shutil.move(str(tmp_dir / Path(name).name), str(project_dir)) <ide> def project_init( <ide> with working_dir(project_dir) as cwd: <ide> if git: <ide> run_command(["git", "init"]) <del> init_cmd = ["dvc", "init"] <del> if silent: <del> init_cmd.append("--quiet") <del> if not git: <del> init_cmd.append("--no-scm") <del> if force: <del> init_cmd.append("--force") <del> run_command(init_cmd) <add> flags = {"--force": force, "--quiet": silent, "--no-scm": not git} <add> try: <add> run_dvc_command(["init"], flags=flags) <add> except DVCError: <add> msg.fail( <add> "Failed to initialize project. This likely means that the " <add> "project is already initialized and has a .dvc directory. " <add> "To force-initialize, use the --force flag.", <add> exits=1, <add> ) <ide> # We don't want to have analytics on by default – our users should <ide> # opt-in explicitly. If they want it, they can always enable it. <ide> if not analytics: <del> run_command(["dvc", "config", "core.analytics", "false"]) <del> # Remove unused and confusing plot templates from .dvc directory <del> # TODO: maybe we shouldn't do this, but it's otherwise super confusing <del> # once you commit your changes via Git and it creates a bunch of files <del> # that have no purpose <add> run_dvc_command(["config", "core.analytics", "false"]) <add> # Remove unused and confusing plot templates from .dvc directory. <add> # Otherwise super confusing once you commit your changes via Git and it <add> # creates a bunch of files that have no purpose. <ide> plots_dir = cwd / DVC_DIR / "plots" <ide> if plots_dir.exists(): <ide> shutil.rmtree(str(plots_dir)) <ide> config = load_project_config(cwd) <ide> setup_check_dvc(cwd, config) <add> msg.good("Initialized project") <ide> <ide> <ide> def project_assets(project_dir: Path) -> None: <ide> def project_assets(project_dir: Path) -> None: <ide> setup_check_dvc(project_path, config) <ide> assets = config.get("assets", {}) <ide> if not assets: <del> msg.warn(f"No assets specified in {CONFIG_FILE}", exits=0) <add> msg.warn(f"No assets specified in {PROJECT_FILE}", exits=0) <ide> msg.info(f"Fetching {len(assets)} asset(s)") <ide> variables = config.get("variables", {}) <ide> fetched_assets = [] <ide> for asset in assets: <del> url = asset["url"].format(**variables) <ide> dest = asset["dest"].format(**variables) <del> fetched_path = fetch_asset(project_path, url, dest, asset.get("checksum")) <add> url = asset.get("url") <add> checksum = asset.get("checksum") <add> if not url: <add> # project.yml defines asset without URL that the user has to place <add> if not Path(dest).exists(): <add> err = f"No URL provided for asset. You need to add this file yourself: {dest}" <add> msg.warn(err) <add> else: <add> if checksum == get_checksum(dest): <add> msg.good(f"Asset exists with matching checksum: {dest}") <add> fetched_assets.append((project_path / dest).resolve()) <add> else: <add> msg.fail(f"Asset available but with incorrect checksum: {dest}") <add> continue <add> url = url.format(**variables) <add> fetched_path = fetch_asset(project_path, url, dest, checksum) <ide> if fetched_path: <ide> fetched_assets.append(str(fetched_path)) <ide> if fetched_assets: <ide> with working_dir(project_path): <del> run_command(["dvc", "add", *fetched_assets, "--external"]) <add> run_dvc_command(["add", *fetched_assets, "--external"]) <ide> <ide> <ide> def fetch_asset( <ide> def fetch_asset( <ide> # Try with tracking the source first, then just downloading with <ide> # DVC, then a regular non-DVC download. <ide> try: <del> dvc_cmd = ["dvc", "import-url", url, str(dest_path)] <del> print(subprocess.check_output(dvc_cmd, stderr=subprocess.DEVNULL)) <del> except subprocess.CalledProcessError: <del> dvc_cmd = ["dvc", "get-url", url, str(dest_path)] <del> print(subprocess.check_output(dvc_cmd, stderr=subprocess.DEVNULL)) <del> except subprocess.CalledProcessError: <add> run_dvc_command(["import-url", url, str(dest_path)]) <add> except DVCError: <add> run_dvc_command(["get-url", url, str(dest_path)]) <add> except DVCError: <ide> try: <ide> download_file(url, dest_path) <ide> except requests.exceptions.HTTPError as e: <ide> msg.fail(f"Download failed: {dest}", e) <ide> return None <ide> if checksum and checksum != get_checksum(dest_path): <del> msg.warn(f"Checksum doesn't match value defined in {CONFIG_FILE}: {dest}") <add> msg.fail(f"Checksum doesn't match value defined in {PROJECT_FILE}: {dest}") <ide> msg.good(f"Fetched asset {dest}") <ide> return dest_path <ide> <ide> def project_run_all(project_dir: Path, *dvc_args) -> None: <ide> """ <ide> config = load_project_config(project_dir) <ide> setup_check_dvc(project_dir, config) <del> dvc_cmd = ["dvc", "repro", *dvc_args] <ide> with working_dir(project_dir): <del> run_command(dvc_cmd) <add> try: <add> run_dvc_command(["repro", *dvc_args]) <add> except DVCError: <add> # We could raise a custom error here, but the output produced by <add> # DVC is already pretty substantial. <add> sys.exit(1) <ide> <ide> <ide> def print_run_help(project_dir: Path, subcommand: Optional[str] = None) -> None: <del> """Simulate a CLI help prompt using the info available in the project config. <add> """Simulate a CLI help prompt using the info available in the project.yml. <ide> <ide> project_dir (Path): The project directory. <ide> subcommand (Optional[str]): The subcommand or None. If a subcommand is <ide> def print_run_help(project_dir: Path, subcommand: Optional[str] = None) -> None: <ide> if help_text: <ide> msg.text(f"\n{help_text}\n") <ide> else: <del> print(f"\nAvailable commands in {CONFIG_FILE}") <add> print(f"\nAvailable commands in {PROJECT_FILE}") <ide> print(f"Usage: {COMMAND} project run [COMMAND] {project_dir}") <ide> msg.table([(cmd["name"], cmd.get("help", "")) for cmd in config_commands]) <del> msg.text("Run all commands defined in the 'run' block of the project config:") <add> msg.text(f"Run all commands defined in the 'run' block of the {PROJECT_FILE}:") <ide> print(f"{COMMAND} project run-all {project_dir}") <ide> <ide> <ide> def project_run(project_dir: Path, subcommand: str, *dvc_args) -> None: <del> """Run a named script defined in the project config. If the script is part <add> """Run a named script defined in the project.yml. If the script is part <ide> of the default pipeline (defined in the "run" section), DVC is used to <ide> execute the command, so it can determine whether to rerun it. It then <ide> calls into "exec" to execute it. <ide> def project_run(project_dir: Path, subcommand: str, *dvc_args) -> None: <ide> validate_subcommand(commands.keys(), subcommand) <ide> if subcommand in config.get("run", []): <ide> # This is one of the pipeline commands tracked in DVC <del> dvc_cmd = ["dvc", "repro", subcommand, *dvc_args] <ide> with working_dir(project_dir): <del> run_command(dvc_cmd) <add> try: <add> run_dvc_command(["repro", subcommand, *dvc_args]) <add> except DVCError: <add> # We could raise a custom error here, but the output produced by <add> # DVC is already pretty substantial. <add> sys.exit(1) <ide> else: <ide> cmd = commands[subcommand] <ide> # Deps in non-DVC commands aren't tracked, but if they're defined, <ide> def project_run(project_dir: Path, subcommand: str, *dvc_args) -> None: <ide> run_commands(cmd["script"], variables) <ide> <ide> <del>def project_exec(project_dir: Path, subcommand: str): <del> """Execute a command defined in the project config. <add>def project_exec(project_dir: Path, subcommand: str) -> None: <add> """Execute a command defined in the project.yml. <ide> <ide> project_dir (Path): Path to project directory. <ide> subcommand (str): Name of command to run. <ide> def project_exec(project_dir: Path, subcommand: str): <ide> <ide> <ide> def load_project_config(path: Path) -> Dict[str, Any]: <del> """Load the project config file from a directory and validate it. <add> """Load the project.yml file from a directory and validate it. <ide> <ide> path (Path): The path to the project directory. <del> RETURNS (Dict[str, Any]): The loaded project config. <add> RETURNS (Dict[str, Any]): The loaded project.yml. <ide> """ <del> config_path = path / CONFIG_FILE <add> config_path = path / PROJECT_FILE <ide> if not config_path.exists(): <del> msg.fail("Can't find project config", config_path, exits=1) <del> invalid_err = f"Invalid project config in {CONFIG_FILE}" <add> msg.fail(f"Can't find {PROJECT_FILE}", config_path, exits=1) <add> invalid_err = f"Invalid {PROJECT_FILE}. Double-check that the YAML is correct." <ide> try: <ide> config = srsly.read_yaml(config_path) <ide> except ValueError as e: <ide> def update_dvc_config( <ide> dict, so if any of the config values change, the DVC config is regenerated. <ide> <ide> path (Path): The path to the project directory. <del> config (Dict[str, Any]): The loaded project config. <add> config (Dict[str, Any]): The loaded project.yml. <ide> verbose (bool): Whether to print additional info (via DVC). <ide> silent (bool): Don't output anything (via DVC). <ide> force (bool): Force update, even if hashes match. <ide> def update_dvc_config( <ide> with dvc_config_path.open("r", encoding="utf8") as f: <ide> ref_hash = f.readline().strip().replace("# ", "") <ide> if ref_hash == config_hash and not force: <del> return False # Nothing has changed in project config, don't need to update <add> return False # Nothing has changed in project.yml, don't need to update <ide> dvc_config_path.unlink() <ide> variables = config.get("variables", {}) <del> commands = [] <add> dvc_commands = [] <ide> # We only want to include commands that are part of the main list of "run" <ide> # commands in project.yml and should be run in sequence <ide> config_commands = {cmd["name"]: cmd for cmd in config.get("commands", [])} <ide> def update_dvc_config( <ide> deps_cmd = [c for cl in [["-d", p] for p in deps] for c in cl] <ide> outputs_cmd = [c for cl in [["-o", p] for p in outputs] for c in cl] <ide> outputs_nc_cmd = [c for cl in [["-O", p] for p in outputs_no_cache] for c in cl] <del> dvc_cmd = ["dvc", "run", "-n", name, "-w", str(path), "--no-exec"] <del> if verbose: <del> dvc_cmd.append("--verbose") <del> if silent: <del> dvc_cmd.append("--quiet") <add> dvc_cmd = ["run", "-n", name, "-w", str(path), "--no-exec"] <ide> full_cmd = [*dvc_cmd, *deps_cmd, *outputs_cmd, *outputs_nc_cmd, *project_cmd] <del> commands.append(" ".join(full_cmd)) <add> dvc_commands.append(" ".join(full_cmd)) <ide> with working_dir(path): <del> run_commands(commands, variables, silent=True) <add> dvc_flags = {"--verbose": verbose, "--quiet": silent} <add> run_dvc_commands(dvc_commands, variables, flags=dvc_flags) <ide> with dvc_config_path.open("r+", encoding="utf8") as f: <ide> content = f.read() <ide> f.seek(0, 0) <ide> def setup_check_dvc(project_dir: Path, config: Dict[str, Any]) -> None: <ide> DVC project. <ide> <ide> project_dir (Path): The path to the project directory. <del> config (Dict[str, Any]): The loaded project config. <add> config (Dict[str, Any]): The loaded project.yml. <ide> """ <ide> if not project_dir.exists(): <ide> msg.fail(f"Can't find project directory: {project_dir}") <ide> def setup_check_dvc(project_dir: Path, config: Dict[str, Any]) -> None: <ide> with msg.loading("Updating DVC config..."): <ide> updated = update_dvc_config(project_dir, config, silent=True) <ide> if updated: <del> msg.good(f"Updated DVC config from changed {CONFIG_FILE}") <del> <del> <del>def run_commands( <del> commands: List[str] = tuple(), variables: Dict[str, str] = {}, silent: bool = False <del>) -> None: <del> """Run a sequence of commands in a subprocess, in order. <del> <del> commands (List[str]): The string commands. <del> variables (Dict[str, str]): Dictionary of variable names, mapped to their <del> values. Will be used to substitute format string variables in the <del> commands. <del> silent (bool): Don't print the commands. <del> """ <del> for command in commands: <del> # Substitute variables, e.g. "./{NAME}.json" <del> command = command.format(**variables) <del> command = split_command(command) <del> # Not sure if this is needed or a good idea. Motivation: users may often <del> # use commands in their config that reference "python" and we want to <del> # make sure that it's always executing the same Python that spaCy is <del> # executed with and the pip in the same env, not some other Python/pip. <del> # Also ensures cross-compatibility if user 1 writes "python3" (because <del> # that's how it's set up on their system), and user 2 without the <del> # shortcut tries to re-run the command. <del> if len(command) and command[0] in ("python", "python3"): <del> command[0] = sys.executable <del> elif len(command) and command[0] in ("pip", "pip3"): <del> command = [sys.executable, "-m", "pip", *command[1:]] <del> if not silent: <del> print(f"Running command: {' '.join(command)}") <del> run_command(command) <add> msg.good(f"Updated DVC config from changed {PROJECT_FILE}") <ide> <ide> <ide> def convert_asset_url(url: str) -> str: <ide> def convert_asset_url(url: str) -> str: <ide> RETURNS (str): The converted URL. <ide> """ <ide> # If the asset URL is a regular GitHub URL it's likely a mistake <del> if re.match("(http(s?)):\/\/github.com", url): <add> if re.match(r"(http(s?)):\/\/github.com", url): <ide> converted = url.replace("github.com", "raw.githubusercontent.com") <ide> converted = re.sub(r"/(tree|blob)/", "/", converted) <ide> msg.warn( <ide> def validate_subcommand(commands: Sequence[str], subcommand: str) -> None: <ide> """ <ide> if subcommand not in commands: <ide> msg.fail( <del> f"Can't find command '{subcommand}' in {CONFIG_FILE}. " <add> f"Can't find command '{subcommand}' in {PROJECT_FILE}. " <ide> f"Available commands: {', '.join(commands)}", <ide> exits=1, <ide> ) <ide> def download_file(url: str, dest: Path, chunk_size: int = 1024) -> None: <ide> for data in response.iter_content(chunk_size=chunk_size): <ide> size = f.write(data) <ide> bar.update(size) <add> <add> <add>def run_commands( <add> commands: List[str] = tuple(), variables: Dict[str, str] = {}, silent: bool = False <add>) -> None: <add> """Run a sequence of commands in a subprocess, in order. <add> <add> commands (List[str]): The string commands. <add> variables (Dict[str, str]): Dictionary of variable names, mapped to their <add> values. Will be used to substitute format string variables in the <add> commands. <add> silent (bool): Don't print the commands. <add> """ <add> for command in commands: <add> # Substitute variables, e.g. "./{NAME}.json" <add> command = command.format(**variables) <add> command = split_command(command) <add> # Not sure if this is needed or a good idea. Motivation: users may often <add> # use commands in their config that reference "python" and we want to <add> # make sure that it's always executing the same Python that spaCy is <add> # executed with and the pip in the same env, not some other Python/pip. <add> # Also ensures cross-compatibility if user 1 writes "python3" (because <add> # that's how it's set up on their system), and user 2 without the <add> # shortcut tries to re-run the command. <add> if len(command) and command[0] in ("python", "python3"): <add> command[0] = sys.executable <add> elif len(command) and command[0] in ("pip", "pip3"): <add> command = [sys.executable, "-m", "pip", *command[1:]] <add> if not silent: <add> print(f"Running command: {' '.join(command)}") <add> run_command(command) <add> <add> <add>def run_dvc_commands( <add> commands: List[str] = tuple(), <add> variables: Dict[str, str] = {}, <add> flags: Dict[str, bool] = {}, <add>) -> None: <add> """Run a sequence of DVC commands in a subprocess, in order. <add> <add> commands (List[str]): The string commands without the leading "dvc". <add> variables (Dict[str, str]): Dictionary of variable names, mapped to their <add> values. Will be used to substitute format string variables in the <add> commands. <add> flags (Dict[str, bool]): Conditional flags to be added to command. Makes it <add> easier to pass flags like --quiet that depend on a variable or <add> command-line setting while avoiding lots of nested conditionals. <add> """ <add> for command in commands: <add> # Substitute variables, e.g. "./{NAME}.json" <add> command = command.format(**variables) <add> command = split_command(command) <add> run_dvc_command(command, flags=flags) <add> <add> <add>def run_dvc_command( <add> command: Union[str, List[str]], flags: Dict[str, bool] = {}, silent: bool = False <add>) -> None: <add> """Run a DVC command in a subprocess. This wrapper gives us a bit more <add> control over how the output and errors are presented. Raises a DVC error if <add> the "dvc" command returns a non-zero exit code and uses the error message <add> logged by DVC. <add> <add> command (Union[str, List[str]]): The command, without the leading "dvc". <add> flags (Dict[str, bool]): Conditional flags to be added to command. Makes it <add> easier to pass flags like --quiet that depend on a variable or <add> command-line setting while avoiding lots of nested conditionals. <add> silent (bool): Don't print any output. <add> """ <add> if isinstance(command, str): <add> command = split_command(command) <add> dvc_command = ["dvc", *command] <add> # Add the flags if they are set to True <add> for flag, is_active in flags.items(): <add> if is_active: <add> dvc_command.append(flag) <add> proc = subprocess.Popen(dvc_command, stderr=subprocess.PIPE, stdout=subprocess.PIPE) <add> if not silent: <add> lines = proc.stdout.read().decode("utf8").split("\n\n") <add> for line in lines: <add> line = line.strip() <add> if is_relevant_dvc_output(line): <add> print(f"{line}\n") <add> _, err = proc.communicate() # Important: otherwise returncode will be None! <add> if proc.returncode != 0: <add> if isinstance(err, bytes): <add> err = err.decode("utf8") <add> raise DVCError(err) <add> <add> <add>def is_relevant_dvc_output(line: str) -> bool: <add> """Check whether the output by DVC is something we want to keep. <add> <add> line (str): A line written to stdout,. <add> RETURNS (bool): Whether to use/print the line. <add> """ <add> # Writing them like this for readability but maybe replace with regex? <add> conditions = [ <add> not line, <add> line.startswith("What's next?"), <add> line.startswith("Having any troubles?"), <add> ] <add> return not any(conditions) <add> <add> <add>class DVCError(RuntimeError): <add> """Custom error type for anything produced by the DVC CLI.""" <add> <add> pass <ide><path>spacy/schemas.py <ide> class Config: <ide> class ProjectConfigAsset(BaseModel): <ide> # fmt: off <ide> dest: StrictStr = Field(..., title="Destination of downloaded asset") <del> url: StrictStr = Field(..., title="URL of asset") <add> url: Optional[StrictStr] = Field(None, title="URL of asset") <ide> checksum: str = Field(None, title="MD5 hash of file", regex=r"([a-fA-F\d]{32})") <ide> # fmt: on <ide>
2
PHP
PHP
add `wherehas` assertable json method
cbdfde20578553816a69ccd8f4d1f9e42958ba72
<ide><path>src/Illuminate/Testing/Fluent/Concerns/Matching.php <ide> <ide> trait Matching <ide> { <add> /** <add> * Assets that all values exist and match their expected values. <add> * <add> * @param string $key <add> * @param array|string $expected <add> * <add> * @return $this <add> */ <add> public function whereHas(string $key, $expected) <add> { <add> $actual = Collection::make( <add> $this->prop($key) ?? $this->prop() <add> ); <add> <add> $missing = Collection::make($expected)->reject(function ($search) use ($key, $actual) { <add> if ($actual->containsStrict($key, $search)) { <add> return true; <add> } <add> <add> return $actual->containsStrict($search); <add> })->toArray(); <add> <add> $values = array_values($missing); <add> <add> PHPUnit::assertEmpty( <add> $missing, <add> sprintf( <add> 'Property [%s] does not contain [%s].', <add> $key, <add> implode(', ', $values) <add> ) <add> ); <add> <add> return $this; <add> } <add> <ide> /** <ide> * Asserts that the property matches the expected value. <ide> * <ide><path>tests/Testing/Fluent/AssertTest.php <ide> public function testAssertWhereFailsWhenDoesNotMatchValueUsingArrayable() <ide> ]); <ide> } <ide> <add> public function testAssertWhereHasFailsWithEmptyValue() <add> { <add> $assert = AssertableJson::fromArray([]); <add> <add> $this->expectException(AssertionFailedError::class); <add> $this->expectExceptionMessage('Property [foo] does not contain [1].'); <add> <add> $assert->whereHas('foo', ['1']); <add> } <add> <add> public function testAssertWhereHasFailsWithMissingValue() <add> { <add> $assert = AssertableJson::fromArray([ <add> 'foo' => ['bar', 'baz'], <add> ]); <add> <add> $this->expectException(AssertionFailedError::class); <add> $this->expectExceptionMessage('Property [foo] does not contain [invalid].'); <add> <add> $assert->whereHas('foo', ['bar', 'baz', 'invalid']); <add> } <add> <add> public function testAssertWhereHasFailsWithMissingNestedValue() <add> { <add> $assert = AssertableJson::fromArray([ <add> ['id' => 1], <add> ['id' => 2], <add> ['id' => 3], <add> ['id' => 4], <add> ]); <add> <add> $this->expectException(AssertionFailedError::class); <add> $this->expectExceptionMessage('Property [id] does not contain [5].'); <add> <add> $assert->whereHas('id', [1,2,3,4,5]); <add> } <add> <add> public function testAssertWhereHasFailsWhenDoesNotMatchType() <add> { <add> $assert = AssertableJson::fromArray([ <add> 'foo' => [1,2,3,4] <add> ]); <add> <add> $this->expectException(AssertionFailedError::class); <add> $this->expectExceptionMessage('Property [foo] does not contain [1].'); <add> <add> $assert->whereHas('foo', ['1']); <add> } <add> <add> public function testAssertWhereHasWithNestedValue() <add> { <add> $assert = AssertableJson::fromArray([ <add> ['id' => 1], <add> ['id' => 2], <add> ['id' => 3], <add> ['id' => 4], <add> ]); <add> <add> $assert->whereHas('id', 1); <add> $assert->whereHas('id', [1,2,3,4]); <add> $assert->whereHas('id', [4,3,2,1]); <add> } <add> <add> public function testAssertWhereHasWithMatchingType() <add> { <add> $assert = AssertableJson::fromArray([ <add> 'foo' => [1,2,3,4] <add> ]); <add> <add> $assert->whereHas('foo', 1); <add> $assert->whereHas('foo', [1]); <add> } <add> <add> public function testAssertWhereHasWithNullValue() <add> { <add> $assert = AssertableJson::fromArray([ <add> 'foo' => null, <add> ]); <add> <add> $assert->whereHas('foo', null); <add> $assert->whereHas('foo', [null]); <add> } <add> <add> public function testAssertWhereHasWithOutOfOrderMatchingType() <add> { <add> $assert = AssertableJson::fromArray([ <add> 'foo' => [4,1,7,3] <add> ]); <add> <add> $assert->whereHas('foo', [1,7,4,3]); <add> } <add> <add> public function testAssertWhereHasWithOutOfOrderNestedMatchingType() <add> { <add> $assert = AssertableJson::fromArray([ <add> ['bar' => 5], <add> ['baz' => 4], <add> ['zal' => 8], <add> ]); <add> <add> $assert->whereHas('baz', 4); <add> } <add> <ide> public function testAssertNestedWhereMatchesValue() <ide> { <ide> $assert = AssertableJson::fromArray([
2
Javascript
Javascript
fix traversal up when unmounting
c5b6601536c621ab8d68b97268b5c6af66b1d37d
<ide><path>src/renderers/shared/fiber/ReactFiberCommitWork.js <ide> module.exports = function<T, P, I, TI, C>( <ide> } <ide> node = node.return; <ide> } <add> node.sibling.return = node.return; <ide> node = node.sibling; <ide> while (node.tag !== HostComponent && node.tag !== HostText) { <ide> // If it is not host node and, we might have a host node inside it. <ide> module.exports = function<T, P, I, TI, C>( <ide> if (!node.child) { <ide> continue siblings; <ide> } else { <add> node.child.return = node; <ide> node = node.child; <ide> } <ide> } <ide> module.exports = function<T, P, I, TI, C>( <ide> commitUnmount(node); <ide> if (node.child) { <ide> // TODO: Coroutines need to visit the stateNode. <add> node.child.return = node; <ide> node = node.child; <ide> continue; <ide> } <ide> module.exports = function<T, P, I, TI, C>( <ide> } <ide> node = node.return; <ide> } <add> node.sibling.return = node.return; <ide> node = node.sibling; <ide> } <ide> } <ide> module.exports = function<T, P, I, TI, C>( <ide> commitUnmount(node); <ide> if (node.child) { <ide> // TODO: Coroutines need to visit the stateNode. <add> node.child.return = node; <ide> node = node.child; <ide> continue; <ide> } <ide> module.exports = function<T, P, I, TI, C>( <ide> } <ide> node = node.return; <ide> } <add> node.sibling.return = node.return; <ide> node = node.sibling; <ide> } <ide> }
1
Go
Go
replace errextractpointnotdirectory with errdefs
8cd244a318c8c1f16eeeb6a8fa48c0cb79cc16ab
<ide><path>daemon/archive.go <ide> import ( <ide> "github.com/pkg/errors" <ide> ) <ide> <del>// ErrExtractPointNotDirectory is used to convey that the operation to extract <del>// a tar archive to a directory in a container has failed because the specified <del>// path does not refer to a directory. <del>var ErrExtractPointNotDirectory = errors.New("extraction point is not a directory") <del> <ide> // ContainerCopy performs a deprecated operation of archiving the resource at <ide> // the specified path in the container identified by the given name. <ide> func (daemon *Daemon) ContainerCopy(name string, res string) (io.ReadCloser, error) { <ide> func (daemon *Daemon) ContainerArchivePath(name string, path string) (content io <ide> // ContainerExtractToDir extracts the given archive to the specified location <ide> // in the filesystem of the container identified by the given name. The given <ide> // path must be of a directory in the container. If it is not, the error will <del>// be ErrExtractPointNotDirectory. If noOverwriteDirNonDir is true then it will <add>// be an errdefs.InvalidParameter. If noOverwriteDirNonDir is true then it will <ide> // be an error if unpacking the given content would cause an existing directory <ide> // to be replaced with a non-directory and vice versa. <ide> func (daemon *Daemon) ContainerExtractToDir(name, path string, copyUIDGID, noOverwriteDirNonDir bool, content io.Reader) error { <ide> func (daemon *Daemon) containerArchivePath(container *container.Container, path <ide> <ide> // containerExtractToDir extracts the given tar archive to the specified location in the <ide> // filesystem of this container. The given path must be of a directory in the <del>// container. If it is not, the error will be ErrExtractPointNotDirectory. If <add>// container. If it is not, the error will be an errdefs.InvalidParameter. If <ide> // noOverwriteDirNonDir is true then it will be an error if unpacking the <ide> // given content would cause an existing directory to be replaced with a non- <ide> // directory and vice versa. <ide> func (daemon *Daemon) containerExtractToDir(container *container.Container, path <ide> } <ide> <ide> if !stat.IsDir() { <del> return ErrExtractPointNotDirectory <add> return errdefs.InvalidParameter(errors.New("extraction point is not a directory")) <ide> } <ide> <ide> // Need to check if the path is in a volume. If it is, it cannot be in a
1
Javascript
Javascript
add tests of querystring benchmark
ee587f39ae44150e9105c7e401712e52cb9254fb
<ide><path>test/parallel/test-benchmark-querystring.js <add>'use strict'; <add> <add>require('../common'); <add> <add>const runBenchmark = require('../common/benchmark'); <add> <add>runBenchmark('querystring', [ <add> 'n=1', <add> 'input="there is nothing to unescape here"', <add> 'type=noencode' <add>]);
1
Javascript
Javascript
add strict equalities in src/core/function.js
8f5894d81af75217ea6b8a0d286d92705b9d82ad
<ide><path>src/core/function.js <ide> var PDFFunction = (function PDFFunctionClosure() { <ide> //var mask = IR[8]; <ide> var range = IR[9]; <ide> <del> if (m != args.length) { <add> if (m !== args.length) { <ide> error('Incorrect number of arguments: ' + m + ' != ' + <ide> args.length); <ide> } <ide> var PDFFunction = (function PDFFunctionClosure() { <ide> var length = diff.length; <ide> <ide> return function constructInterpolatedFromIRResult(args) { <del> var x = n == 1 ? args[0] : Math.pow(args[0], n); <add> var x = (n === 1 ? args[0] : Math.pow(args[0], n)); <ide> <ide> var out = []; <ide> for (var j = 0; j < length; ++j) { <ide> var PDFFunction = (function PDFFunctionClosure() { <ide> } <ide> <ide> var inputSize = domain.length / 2; <del> if (inputSize != 1) { <add> if (inputSize !== 1) { <ide> error('Bad domain for stiched function'); <ide> } <ide> <ide> var PDFFunction = (function PDFFunctionClosure() { <ide> <ide> function isPDFFunction(v) { <ide> var fnDict; <del> if (typeof v != 'object') { <add> if (typeof v !== 'object') { <ide> return false; <ide> } else if (isDict(v)) { <ide> fnDict = v; <ide> var PostScriptEvaluator = (function PostScriptEvaluatorClosure() { <ide> var operator, a, b; <ide> while (counter < length) { <ide> operator = operators[counter++]; <del> if (typeof operator == 'number') { <add> if (typeof operator === 'number') { <ide> // Operator is really an operand and should be pushed to the stack. <ide> stack.push(operator); <ide> continue; <ide> var PostScriptEvaluator = (function PostScriptEvaluatorClosure() { <ide> case 'eq': <ide> b = stack.pop(); <ide> a = stack.pop(); <del> stack.push(a == b); <add> stack.push(a === b); <ide> break; <ide> case 'exch': <ide> stack.roll(2, 1); <ide> var PostScriptEvaluator = (function PostScriptEvaluatorClosure() { <ide> case 'ne': <ide> b = stack.pop(); <ide> a = stack.pop(); <del> stack.push(a != b); <add> stack.push(a !== b); <ide> break; <ide> case 'neg': <ide> a = stack.pop(); <ide> var PostScriptEvaluator = (function PostScriptEvaluatorClosure() { <ide> b = stack.pop(); <ide> a = stack.pop(); <ide> if (isBool(a) && isBool(b)) { <del> stack.push(a != b); <add> stack.push(a !== b); <ide> } else { <ide> stack.push(a ^ b); <ide> }
1
Text
Text
simplify text in pull-requests.md
794d8be94e65a13cdbe12ea296637fe9e57e2878
<ide><path>doc/guides/contributing/pull-requests.md <ide> $ git remote add upstream https://github.com/nodejs/node.git <ide> $ git fetch upstream <ide> ``` <ide> <del>It is recommended to configure `git` so that it knows who you are: <add>Configure `git` so that it knows who you are: <ide> <ide> ```text <ide> $ git config user.name "J. Random User" <ide> For contributing C++ code, you may want to look at the <ide> <ide> ### Step 4: Commit <ide> <del>It is a recommended best practice to keep your changes as logically grouped <add>It is a best practice to keep your changes as logically grouped <ide> as possible within individual commits. There is no limit to the number of <ide> commits any single Pull Request may have, and many contributors find it easier <ide> to review changes that are split across multiple commits.
1
Ruby
Ruby
build fix for observed_classes
f56d4de29c1d6f09f29797fb2fdfb9e010a9c2e2
<ide><path>activerecord/test/cases/lifecycle_test.rb <ide> def test_before_destroy <ide> def test_auto_observer <ide> topic_observer = TopicaAuditor.instance <ide> assert_nil TopicaAuditor.observed_class <del> assert_equal [Topic], TopicaAuditor.instance.observed_classes.to_a <add> assert_equal [Topic], TopicaAuditor.observed_classes.to_a <ide> <ide> topic = Topic.find(1) <ide> assert_equal topic.title, topic_observer.topic.title
1
Go
Go
return error instead of logging
ef490cae4520ff1c8aa765ec9107885417a2583b
<ide><path>api/server/httputils/httputils.go <ide> import ( <ide> <ide> "github.com/docker/docker/errdefs" <ide> "github.com/pkg/errors" <del> "github.com/sirupsen/logrus" <ide> ) <ide> <ide> // APIVersionKey is the client's requested API version. <ide> func CheckForJSON(r *http.Request) error { <ide> ct := r.Header.Get("Content-Type") <ide> <ide> // No Content-Type header is ok as long as there's no Body <del> if ct == "" { <del> if r.Body == nil || r.ContentLength == 0 { <del> return nil <del> } <add> if ct == "" && (r.Body == nil || r.ContentLength == 0) { <add> return nil <ide> } <ide> <ide> // Otherwise it better be json <del> if matchesContentType(ct, "application/json") { <del> return nil <del> } <del> return errdefs.InvalidParameter(errors.Errorf("Content-Type specified (%s) must be 'application/json'", ct)) <add> return matchesContentType(ct, "application/json") <ide> } <ide> <ide> // ParseForm ensures the request form is parsed even with invalid content types. <ide> func VersionFromContext(ctx context.Context) string { <ide> } <ide> <ide> // matchesContentType validates the content type against the expected one <del>func matchesContentType(contentType, expectedType string) bool { <add>func matchesContentType(contentType, expectedType string) error { <ide> mimetype, _, err := mime.ParseMediaType(contentType) <ide> if err != nil { <del> logrus.Errorf("Error parsing media type: %s error: %v", contentType, err) <add> return errdefs.InvalidParameter(errors.Wrapf(err, "malformed Content-Type header (%s)", contentType)) <add> } <add> if mimetype != expectedType { <add> return errdefs.InvalidParameter(errors.Errorf("unsupported Content-Type header (%s): must be '%s'", contentType, expectedType)) <ide> } <del> return err == nil && mimetype == expectedType <add> return nil <ide> } <ide><path>api/server/httputils/httputils_test.go <ide> import "testing" <ide> <ide> // matchesContentType <ide> func TestJsonContentType(t *testing.T) { <del> if !matchesContentType("application/json", "application/json") { <del> t.Fail() <add> err := matchesContentType("application/json", "application/json") <add> if err != nil { <add> t.Error(err) <ide> } <ide> <del> if !matchesContentType("application/json; charset=utf-8", "application/json") { <del> t.Fail() <add> err = matchesContentType("application/json; charset=utf-8", "application/json") <add> if err != nil { <add> t.Error(err) <ide> } <ide> <del> if matchesContentType("dockerapplication/json", "application/json") { <del> t.Fail() <add> expected := "unsupported Content-Type header (dockerapplication/json): must be 'application/json'" <add> err = matchesContentType("dockerapplication/json", "application/json") <add> if err == nil || err.Error() != expected { <add> t.Errorf(`expected "%s", got "%v"`, expected, err) <add> } <add> <add> expected = "malformed Content-Type header (foo;;;bar): mime: invalid media parameter" <add> err = matchesContentType("foo;;;bar", "application/json") <add> if err == nil || err.Error() != expected { <add> t.Errorf(`expected "%s", got "%v"`, expected, err) <ide> } <ide> }
2
Python
Python
fix bugs in unused code paths
3eb219fd97200282b6aed9fe760e843d4916bc06
<ide><path>numpy/compat/_inspect.py <ide> def ismethod(object): <ide> __name__ name with which this method was defined <ide> im_class class object in which this method belongs <ide> im_func function object containing implementation of method <del> im_self instance to which this method is bound, or None""" <add> im_self instance to which this method is bound, or None <add> <add> """ <ide> return isinstance(object, types.MethodType) <ide> <ide> def isfunction(object): <ide> def isfunction(object): <ide> func_defaults tuple of any default values for arguments <ide> func_doc (same as __doc__) <ide> func_globals global namespace in which this function was defined <del> func_name (same as __name__)""" <add> func_name (same as __name__) <add> <add> """ <ide> return isinstance(object, types.FunctionType) <ide> <ide> def iscode(object): <ide> def iscode(object): <ide> co_names tuple of names of local variables <ide> co_nlocals number of local variables <ide> co_stacksize virtual machine stack space required <del> co_varnames tuple of names of arguments and local variables""" <add> co_varnames tuple of names of arguments and local variables <add> <add> """ <ide> return isinstance(object, types.CodeType) <ide> <ide> # ------------------------------------------------ argument list extraction <ide> def getargs(co): <ide> <ide> Three things are returned: (args, varargs, varkw), where 'args' is <ide> a list of argument names (possibly containing nested lists), and <del> 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" <add> 'varargs' and 'varkw' are the names of the * and ** arguments or None. <add> <add> """ <ide> <ide> if not iscode(co): <ide> raise TypeError('arg is not a code object') <ide> <del> code = co.co_code <ide> nargs = co.co_argcount <ide> names = co.co_varnames <ide> args = list(names[:nargs]) <del> step = 0 <ide> <ide> # The following acrobatics are for anonymous (tuple) arguments. <add> # Which we do not need to support, so remove to avoid importing <add> # the dis module. <ide> for i in range(nargs): <ide> if args[i][:1] in ['', '.']: <del> stack, remain, count = [], [], [] <del> while step < len(code): <del> op = ord(code[step]) <del> step = step + 1 <del> if op >= dis.HAVE_ARGUMENT: <del> opname = dis.opname[op] <del> value = ord(code[step]) + ord(code[step+1])*256 <del> step = step + 2 <del> if opname in ['UNPACK_TUPLE', 'UNPACK_SEQUENCE']: <del> remain.append(value) <del> count.append(value) <del> elif opname == 'STORE_FAST': <del> stack.append(names[value]) <del> <del> # Special case for sublists of length 1: def foo((bar)) <del> # doesn't generate the UNPACK_TUPLE bytecode, so if <del> # `remain` is empty here, we have such a sublist. <del> if not remain: <del> stack[0] = [stack[0]] <del> break <del> else: <del> remain[-1] = remain[-1] - 1 <del> while remain[-1] == 0: <del> remain.pop() <del> size = count.pop() <del> stack[-size:] = [stack[-size:]] <del> if not remain: break <del> remain[-1] = remain[-1] - 1 <del> if not remain: break <del> args[i] = stack[0] <del> <add> raise TypeError("tuple function arguments are not supported") <ide> varargs = None <ide> if co.co_flags & CO_VARARGS: <ide> varargs = co.co_varnames[nargs] <ide> def getargspec(func): <ide> 'args' is a list of the argument names (it may contain nested lists). <ide> 'varargs' and 'varkw' are the names of the * and ** arguments or None. <ide> 'defaults' is an n-tuple of the default values of the last n arguments. <add> <ide> """ <ide> <ide> if ismethod(func): <ide> def getargvalues(frame): <ide> A tuple of four things is returned: (args, varargs, varkw, locals). <ide> 'args' is a list of the argument names (it may contain nested lists). <ide> 'varargs' and 'varkw' are the names of the * and ** arguments or None. <del> 'locals' is the locals dictionary of the given frame.""" <add> 'locals' is the locals dictionary of the given frame. <add> <add> """ <ide> args, varargs, varkw = getargs(frame.f_code) <ide> return args, varargs, varkw, frame.f_locals <ide> <ide> def joinseq(seq): <ide> return '(' + ', '.join(seq) + ')' <ide> <ide> def strseq(object, convert, join=joinseq): <del> """Recursively walk a sequence, stringifying each element.""" <add> """Recursively walk a sequence, stringifying each element. <add> <add> """ <ide> if type(object) in [list, tuple]: <ide> return join([strseq(_o, convert, join) for _o in object]) <ide> else: <ide> def formatargspec(args, varargs=None, varkw=None, defaults=None, <ide> The first four arguments are (args, varargs, varkw, defaults). The <ide> other four arguments are the corresponding optional formatting functions <ide> that are called to turn names and values into strings. The ninth <del> argument is an optional function to format the sequence of arguments.""" <add> argument is an optional function to format the sequence of arguments. <add> <add> """ <ide> specs = [] <ide> if defaults: <ide> firstdefault = len(args) - len(defaults) <ide> def formatargvalues(args, varargs, varkw, locals, <ide> The first four arguments are (args, varargs, varkw, locals). The <ide> next four arguments are the corresponding optional formatting functions <ide> that are called to turn names and values into strings. The ninth <del> argument is an optional function to format the sequence of arguments.""" <add> argument is an optional function to format the sequence of arguments. <add> <add> """ <ide> def convert(name, locals=locals, <ide> formatarg=formatarg, formatvalue=formatvalue): <ide> return formatarg(name) + formatvalue(locals[name]) <ide> def convert(name, locals=locals, <ide> specs.append(formatvarargs(varargs) + formatvalue(locals[varargs])) <ide> if varkw: <ide> specs.append(formatvarkw(varkw) + formatvalue(locals[varkw])) <del> return '(' + string.join(specs, ', ') + ')' <del> <del>if __name__ == '__main__': <del> import inspect <del> def foo(x, y, z=None): <del> return None <del> <del> print(inspect.getargs(foo.__code__)) <del> print(getargs(foo.__code__)) <del> <del> print(inspect.getargspec(foo)) <del> print(getargspec(foo)) <del> <del> print(inspect.formatargspec(*inspect.getargspec(foo))) <del> print(formatargspec(*getargspec(foo))) <add> return '(' + ', '.join(specs) + ')' <ide><path>numpy/compat/tests/test_compat.py <ide> from os.path import join <ide> <ide> from numpy.compat import isfileobj <del>from numpy.testing import TestCase, assert_ <add>from numpy.testing import assert_ <ide> from numpy.testing.utils import tempdir <ide> <ide>
2
PHP
PHP
add exists as alias to has
183bf16a2c939889f4461e237a851b55cf858f8e
<ide><path>src/Illuminate/Http/Concerns/InteractsWithInput.php <ide> public function bearerToken() <ide> } <ide> } <ide> <add> /** <add> * Determine if the request contains a given input item key. <add> * <add> * @param string|array $key <add> * @return bool <add> */ <add> public function exists($key) <add> { <add> return $this->has($key); <add> } <add> <ide> /** <ide> * Determine if the request contains a given input item key. <ide> *
1
Javascript
Javascript
fix flaky redirect tests
4d529253cf01c0e3c2953eb022eef907c2b7edec
<ide><path>cypress/integration/legacy/redirects/adding-development.js <add>// These tests require the client to be built and served with additional <add>// redirect configuration. The Cypress action in .github/workflows/cypress.yml <add>// contains the necessary commands to do this. <add> <ide> describe('Legacy redirects', () => { <ide> it('should redirect from front-end-libraries to front-end-development-libraries', () => { <ide> cy.visit('learn/front-end-libraries'); <ide> describe('Legacy redirects', () => { <ide> '/certification/certifieduser/front-end-development-libraries' <ide> ); <ide> }); <del> }); <ide> <del> it('should load this one challenge that throws an error if we do not test it separately', () => { <ide> cy.visit( <ide> 'learn/front-end-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers' <ide> ); <ide> describe('Legacy redirects', () => { <ide> '/learn/front-end-development-libraries/bootstrap/use-responsive-design-with-bootstrap-fluid-containers' <ide> ); <ide> }); <add> // Bit of hack: but we need to make sure the page is fully loaded before <add> // moving on. <add> cy.get('.react-monaco-editor-container').should('be.visible'); <ide> }); <ide> <ide> it('should redirect from /apis-and-microservices to /back-end-development-and-apis', () => {
1
Java
Java
update viewresolver registration classes
f54cee47b06c041c5c976ce23fc2079d70fad404
<ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java <ide> public void configureDefaultServletHandling(DefaultServletHandlerConfigurer conf <ide> } <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.tiles(); <ide> } <ide> <ide><path>spring-test/src/test/java/org/springframework/test/web/servlet/samples/spr/EncodedUriTests.java <ide> <ide> import org.springframework.web.context.WebApplicationContext; <ide> import org.springframework.web.servlet.config.annotation.EnableWebMvc; <del>import org.springframework.web.servlet.config.annotation.ViewResolutionRegistry; <add>import org.springframework.web.servlet.config.annotation.ViewResolverRegistry; <ide> import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <ide> import org.springframework.web.util.UriComponentsBuilder; <ide> public HandlerMappingConfigurer myHandlerMappingConfigurer() { <ide> } <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.jsp("", ""); <ide> } <ide> } <ide> public Object postProcessBeforeInitialization(Object bean, String beanName) thro <ide> <ide> // URL decode after request mapping, not before. <ide> requestMappingHandlerMapping.setUrlDecode(false); <del> <ide> } <del> <ide> return bean; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/BeanNameRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.view.BeanNameViewResolver; <del> <del>/** <del> * Encapsulates information required to create a <del> * {@link org.springframework.web.servlet.view.BeanNameViewResolver} bean. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class BeanNameRegistration extends ViewResolutionRegistration<BeanNameViewResolver> { <del> <del> public BeanNameRegistration(ViewResolutionRegistry registry) { <del> super(registry, new BeanNameViewResolver()); <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ContentNegotiatingRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.View; <del>import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; <del> <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.List; <del> <del>/** <del> * Encapsulates information required to create a {@link ContentNegotiatingViewResolver} bean. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class ContentNegotiatingRegistration extends ViewResolutionRegistration<ContentNegotiatingViewResolver> { <del> <del> private List<View> defaultViews; <del> <del> public ContentNegotiatingRegistration(ViewResolutionRegistry registry) { <del> super(registry, new ContentNegotiatingViewResolver()); <del> } <del> <del> /** <del> * Indicate whether a {@link javax.servlet.http.HttpServletResponse#SC_NOT_ACCEPTABLE 406 Not Acceptable} <del> * status code should be returned if no suitable view can be found. <del> * <del> * @see ContentNegotiatingViewResolver#setUseNotAcceptableStatusCode(boolean) <del> */ <del> public ContentNegotiatingRegistration useNotAcceptable(boolean useNotAcceptable) { <del> this.viewResolver.setUseNotAcceptableStatusCode(useNotAcceptable); <del> return this; <del> } <del> <del> /** <del> * <del> * Set the default views to use when a more specific view can not be obtained <del> * from the {@link org.springframework.web.servlet.ViewResolver} chain. <del> * <del> * @see ContentNegotiatingViewResolver#setDefaultViews(java.util.List) <del> */ <del> public ContentNegotiatingRegistration defaultViews(View... defaultViews) { <del> if(this.defaultViews == null) { <del> this.defaultViews = new ArrayList<View>(); <del> } <del> this.defaultViews.addAll(Arrays.asList(defaultViews)); <del> return this; <del> } <del> <del> @Override <del> protected ContentNegotiatingViewResolver getViewResolver() { <del> this.viewResolver.setDefaultViews(this.defaultViews); <del> return super.getViewResolver(); <del> } <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.java <ide> protected void addViewControllers(ViewControllerRegistry registry) { <ide> } <ide> <ide> @Override <del> protected void configureViewResolution(ViewResolutionRegistry registry) { <del> this.configurers.configureViewResolution(registry); <add> protected void configureViewResolvers(ViewResolverRegistry registry) { <add> this.configurers.configureViewResolvers(registry); <ide> } <ide> <ide> @Override <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/EnableWebMvc.java <ide> import org.springframework.context.annotation.Import; <ide> <ide> /** <del> * Add this annotation to an {@code @Configuration} class to have the Spring MVC <del> * configuration defined in {@link WebMvcConfigurationSupport} imported: <add> * Adding this annotation to an {@code @Configuration} class imports the Spring MVC <add> * configuration from {@link WebMvcConfigurationSupport}, e.g.: <ide> * <ide> * <pre class="code"> <ide> * &#064;Configuration <ide> * <ide> * } <ide> * </pre> <del> * <p>Customize the imported configuration by implementing the <del> * {@link WebMvcConfigurer} interface or more likely by extending the <del> * {@link WebMvcConfigurerAdapter} base class and overriding individual methods: <add> * <add> * <p>As of 4.1 this annotation may also import {@link WebMvcFreeMarkerConfiguration}, <add> * {@link WebMvcVelocityConfiguration}, or {@link WebMvcTilesConfiguration} if <add> * those libraries are found on the classpath. <add> * <add> * <p>To customize the imported configuration, implement the interface <add> * {@link WebMvcConfigurer} or more likely extend the empty method base class <add> * {@link WebMvcConfigurerAdapter} and override individual methods, e.g.: <ide> * <ide> * <pre class="code"> <ide> * &#064;Configuration <ide> * } <ide> * </pre> <ide> * <del> * <p>If the customization options of {@link WebMvcConfigurer} do not expose <del> * something you need to configure, consider removing the {@code @EnableWebMvc} <del> * annotation and extending directly from {@link WebMvcConfigurationSupport} <del> * overriding selected {@code @Bean} methods: <add> * <p>To customize the FreeMarker, Velocity, or Tiles configuration, additionally <add> * implement {@link FreeMarkerWebMvcConfigurer}, {@link VelocityWebMvcConfigurer}, <add> * and/or {@link TilesWebMvcConfigurer}. <add> * <add> * <p>If {@link WebMvcConfigurer} does not expose some advanced setting that <add> * needs to be configured, consider removing the {@code @EnableWebMvc} <add> * annotation and extending directly from {@link WebMvcConfigurationSupport}, e.g.: <ide> * <ide> * <pre class="code"> <ide> * &#064;Configuration <ide> * } <ide> * </pre> <ide> * <del> * @see WebMvcConfigurer <del> * @see WebMvcConfigurerAdapter <add> * <p>When the {@code @EnableWebMvc} annotation is removed, the FreeMarker, <add> * Velocity, and Tiles configuration is no longer automatically imported and need <add> * to be imported explicitly. <ide> * <ide> * @author Dave Syer <ide> * @author Rossen Stoyanchev <ide> * @author Sebastien Deleuze <ide> * @since 3.1 <add> * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurer <add> * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter <add> * @see org.springframework.web.servlet.config.annotation.FreeMarkerWebMvcConfigurer <add> * @see org.springframework.web.servlet.config.annotation.VelocityWebMvcConfigurer <add> * @see org.springframework.web.servlet.config.annotation.TilesWebMvcConfigurer <ide> */ <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Target(ElementType.TYPE) <ide> @Documented <del>@Import({DelegatingWebMvcConfiguration.class, ViewResolutionImportSelector.class}) <add>@Import({DelegatingWebMvcConfiguration.class, ViewConfigurationImportSelector.class}) <ide> public @interface EnableWebMvc { <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/FreeMarkerRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; <del> <del>/** <del> * Encapsulates information required to create a <del> * {@link org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver} and a <del> * {@link org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer} beans. <del> * Default configuration is "" prefix, ".ftl" suffix and "/WEB-INF/" templateLoaderPath. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class FreeMarkerRegistration extends ViewResolutionRegistration<FreeMarkerViewResolver> { <del> <del> <del> public FreeMarkerRegistration(ViewResolutionRegistry registry) { <del> super(registry, new FreeMarkerViewResolver()); <del> this.prefix(""); <del> this.suffix(".ftl"); <del> } <del> <del> /** <del> * Set the prefix that gets prepended to view names when building a URL. <del> * <del> * @see org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver#setPrefix(String) <del> */ <del> public FreeMarkerRegistration prefix(String prefix) { <del> this.viewResolver.setPrefix(prefix); <del> return this; <del> } <del> <del> /** <del> * Set the suffix that gets appended to view names when building a URL. <del> * <del> * @see org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver#setSuffix(String) <del> */ <del> public FreeMarkerRegistration suffix(String suffix) { <del> this.viewResolver.setSuffix(suffix); <del> return this; <del> } <del> <del> /** <del> * Enable or disable caching. <del> * <del> * @see org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver#setCache(boolean) <del> */ <del> public FreeMarkerRegistration cache(boolean cache) { <del> this.viewResolver.setCache(cache); <del> return this; <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/JspRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.view.InternalResourceViewResolver; <del> <del>/** <del> * Encapsulates information required to create an {@link InternalResourceViewResolver} bean. <del> * Default configuration is "/WEB-INF/" prefix and ".jsp" suffix. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class JspRegistration extends ViewResolutionRegistration<InternalResourceViewResolver> { <del> <del> public JspRegistration(ViewResolutionRegistry registry) { <del> this(registry, "/WEB-INF/", ".jsp"); <del> } <del> <del> public JspRegistration(ViewResolutionRegistry registry, String prefix, String suffix) { <del> super(registry, new InternalResourceViewResolver()); <del> this.viewResolver.setPrefix(prefix); <del> this.viewResolver.setSuffix(suffix); <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/TilesRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.view.tiles3.TilesViewResolver; <del> <del>/** <del> * Encapsulates information required to create a <del> * {@link org.springframework.web.servlet.view.tiles3.TilesViewResolver} and a <del> * {@link org.springframework.web.servlet.view.tiles3.TilesConfigurer} beans. <del> * <del> * Default definition is "/WEB-INF/tiles.xml" and no Tiles definition check refresh. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class TilesRegistration extends ViewResolutionRegistration<TilesViewResolver> { <del> <del> <del> public TilesRegistration(ViewResolutionRegistry registry) { <del> super(registry, new TilesViewResolver()); <del> } <del> <del> /** <del> * Set the prefix that gets prepended to view names when building a URL. <del> * <del> * @see TilesViewResolver#setPrefix(String) <del> */ <del> public TilesRegistration prefix(String prefix) { <del> this.viewResolver.setPrefix(prefix); <del> return this; <del> } <del> <del> /** <del> * Set the suffix that gets appended to view names when building a URL. <del> * <del> * @see TilesViewResolver#setSuffix(String) <del> */ <del> public TilesRegistration suffix(String suffix) { <del> this.viewResolver.setSuffix(suffix); <del> return this; <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/UrlBasedViewResolverRegistration.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.config.annotation; <add> <add>import org.springframework.web.servlet.view.UrlBasedViewResolver; <add> <add>import java.util.Map; <add> <add>/** <add> * Assist with configuring a {@link org.springframework.web.servlet.view.UrlBasedViewResolver}. <add> * <add> * @author Sebastien Deleuze <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class UrlBasedViewResolverRegistration { <add> <add> protected final UrlBasedViewResolver viewResolver; <add> <add> <add> public UrlBasedViewResolverRegistration(UrlBasedViewResolver viewResolver) { <add> this.viewResolver = viewResolver; <add> } <add> <add> <add> protected UrlBasedViewResolver getViewResolver() { <add> return this.viewResolver; <add> } <add> <add> /** <add> * Set the prefix that gets prepended to view names when building a URL. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setPrefix <add> */ <add> public UrlBasedViewResolverRegistration prefix(String prefix) { <add> this.viewResolver.setPrefix(prefix); <add> return this; <add> } <add> <add> /** <add> * Set the suffix that gets appended to view names when building a URL. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setSuffix <add> */ <add> public UrlBasedViewResolverRegistration suffix(String suffix) { <add> this.viewResolver.setSuffix(suffix); <add> return this; <add> } <add> <add> /** <add> * Set the view class that should be used to create views. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setViewClass <add> */ <add> public UrlBasedViewResolverRegistration viewClass(Class<?> viewClass) { <add> this.viewResolver.setViewClass(viewClass); <add> return this; <add> } <add> <add> /** <add> * Set the view names (or name patterns) that can be handled by this view <add> * resolver. View names can contain simple wildcards such that 'my*', '*Report' <add> * and '*Repo*' will all match the view name 'myReport'. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setViewNames <add> */ <add> public UrlBasedViewResolverRegistration viewNames(String... viewNames) { <add> this.viewResolver.setViewNames(viewNames); <add> return this; <add> } <add> <add> /** <add> * Set static attributes to be added to the model of every request for all <add> * views resolved by this view resolver. This allows for setting any kind of <add> * attribute values, for example bean references. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setAttributesMap <add> */ <add> public UrlBasedViewResolverRegistration attributes(Map<String, ?> attributes) { <add> this.viewResolver.setAttributesMap(attributes); <add> return this; <add> } <add> <add> /** <add> * Specify the maximum number of entries for the view cache. <add> * Default is 1024. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setCache(boolean) <add> */ <add> public UrlBasedViewResolverRegistration cacheLimit(int cacheLimit) { <add> this.viewResolver.setCacheLimit(cacheLimit); <add> return this; <add> } <add> <add> /** <add> * Enable or disable caching. <add> * <p>This is equivalent to setting the {@link #cacheLimit "cacheLimit"} <add> * property to the default limit (1024) or to 0, respectively. <add> * <p>Default is "true": caching is enabled. <add> * Disable this only for debugging and development. <add> * @see org.springframework.web.servlet.view.UrlBasedViewResolver#setCache(boolean) <add> */ <add> public UrlBasedViewResolverRegistration cache(boolean cache) { <add> this.viewResolver.setCache(cache); <add> return this; <add> } <add> <add>} <add> <add> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/VelocityRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.view.velocity.VelocityViewResolver; <del> <del>/** <del> * Encapsulates information required to create a <del> * {@link org.springframework.web.servlet.view.velocity.VelocityViewResolver} and a <del> * {@link org.springframework.web.servlet.view.velocity.VelocityConfigurer beans}. <del> * Default configuration is "" prefix, ".vm" suffix and "/WEB-INF/" resourceLoaderPath. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class VelocityRegistration extends ViewResolutionRegistration<VelocityViewResolver> { <del> <del> <del> public VelocityRegistration(ViewResolutionRegistry registry) { <del> super(registry, new VelocityViewResolver()); <del> this.prefix(""); <del> this.suffix(".vm"); <del> } <del> <del> /** <del> * Set the prefix that gets prepended to view names when building a URL. <del> * <del> * @see org.springframework.web.servlet.view.velocity.VelocityViewResolver#setPrefix(String) <del> */ <del> public VelocityRegistration prefix(String prefix) { <del> this.viewResolver.setPrefix(prefix); <del> return this; <del> } <del> <del> /** <del> * Set the suffix that gets appended to view names when building a URL. <del> * <del> * @see org.springframework.web.servlet.view.velocity.VelocityViewResolver#setSuffix(String) <del> */ <del> public VelocityRegistration suffix(String suffix) { <del> this.viewResolver.setSuffix(suffix); <del> return this; <del> } <del> <del> /** <del> * Enable or disable caching. <del> * <del> * @see org.springframework.web.servlet.view.velocity.VelocityViewResolver#setCache(boolean) <del> */ <del> public VelocityRegistration cache(boolean cache) { <del> this.viewResolver.setCache(cache); <del> return this; <del> } <del> <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolutionRegistration.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.web.servlet.ViewResolver; <del> <del>/** <del> * Encapsulates information required to create a view resolver. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class ViewResolutionRegistration<T extends ViewResolver> { <del> <del> protected final ViewResolutionRegistry registry; <del> <del> protected final T viewResolver; <del> <del> public ViewResolutionRegistration(ViewResolutionRegistry registry, T viewResolver) { <del> this.registry = registry; <del> this.viewResolver = viewResolver; <del> } <del> <del> public ViewResolutionRegistry and() { <del> return this.registry; <del> } <del> <del> protected T getViewResolver() { <del> return this.viewResolver; <del> } <del> <del>} <del> <del> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolutionRegistry.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.springframework.beans.factory.BeanFactoryUtils; <del>import org.springframework.beans.factory.BeanInitializationException; <del>import org.springframework.context.ApplicationContext; <del>import org.springframework.util.ObjectUtils; <del>import org.springframework.web.servlet.View; <del>import org.springframework.web.servlet.ViewResolver; <del>import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig; <del>import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; <del>import org.springframework.web.servlet.view.tiles3.TilesConfigurer; <del>import org.springframework.web.servlet.view.velocity.VelocityConfigurer; <del> <del>import java.util.ArrayList; <del>import java.util.List; <del> <del>/** <del> * Helps with configuring a list of view resolvers. <del> * <del> * @author Sebastien Deleuze <del> * @since 4.1 <del> */ <del>public class ViewResolutionRegistry { <del> <del> private final List<ViewResolutionRegistration<?>> registrations = new ArrayList<ViewResolutionRegistration<?>>(); <del> <del> private final ApplicationContext applicationContext; <del> <del> <del> public ViewResolutionRegistry(ApplicationContext context) { <del> this.applicationContext = context; <del> } <del> <del> <del> /** <del> * Register a custom {@link ViewResolver} bean. <del> */ <del> public ViewResolutionRegistration<ViewResolver> addViewResolver(ViewResolver viewResolver) { <del> ViewResolutionRegistration<ViewResolver> registration = new ViewResolutionRegistration<ViewResolver>(this, viewResolver); <del> registrations.add(registration); <del> return registration; <del> } <del> <del> /** <del> * Register an {@link org.springframework.web.servlet.view.InternalResourceViewResolver} <del> * bean with default "/WEB-INF/" prefix and ".jsp" suffix. <del> */ <del> public JspRegistration jsp() { <del> JspRegistration registration = new JspRegistration(this); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> /** <del> * Register an {@link org.springframework.web.servlet.view.InternalResourceViewResolver} <del> * bean with specified prefix and suffix. <del> */ <del> public JspRegistration jsp(String prefix, String suffix) { <del> JspRegistration registration = new JspRegistration(this, prefix, suffix); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> /** <del> * Register a {@link org.springframework.web.servlet.view.BeanNameViewResolver} bean. <del> */ <del> public BeanNameRegistration beanName() { <del> BeanNameRegistration registration = new BeanNameRegistration(this); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> /** <del> * Register a {@link org.springframework.web.servlet.view.tiles3.TilesViewResolver} and <del> * a {@link org.springframework.web.servlet.view.tiles3.TilesConfigurer} with <del> * default "/WEB-INF/tiles.xml" definition and no Tiles definition check refresh. <del> */ <del> public TilesRegistration tiles() { <del> if (!hasBeanOfType(TilesConfigurer.class)) { <del> throw new BeanInitializationException( <del> "It looks like you're trying to configure Tiles view resolution. " + <del> "If not using @EnableWebMvc you must import WebMvcTilesConfiguration, " + <del> "or declare your own TilesConfigurer bean."); <del> } <del> TilesRegistration registration = new TilesRegistration(this); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> /** <del> * Register a {@link org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver} <del> * and a {@link org.springframework.web.servlet.view.velocity.VelocityConfigurer} beans with <del> * default "" prefix, ".vm" suffix and "/WEB-INF/" resourceLoaderPath. <del> */ <del> public VelocityRegistration velocity() { <del> if (!hasBeanOfType(VelocityConfigurer.class)) { <del> throw new BeanInitializationException( <del> "It looks like you're trying to configure Velocity view resolution. " + <del> "If not using @EnableWebMvc you must import WebMvcVelocityConfiguration, " + <del> "or declare your own VelocityConfigurer bean."); <del> } <del> VelocityRegistration registration = new VelocityRegistration(this); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> /** <del> * Register a {@link org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver} <del> * and a {@link org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer} beans with <del> * "" prefix, ".ftl" suffix and "/WEB-INF/" templateLoaderPath. <del> */ <del> public FreeMarkerRegistration freemarker() { <del> if (!hasBeanOfType(FreeMarkerConfigurer.class)) { <del> throw new BeanInitializationException( <del> "It looks like you're trying to configure FreeMarker view resolution. " + <del> "If not using @EnableWebMvc you must import WebMvcFreeMarkerConfiguration, " + <del> "or declare your own FreeMarkerConfigurer bean."); <del> } <del> FreeMarkerRegistration registration = new FreeMarkerRegistration(this); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> protected boolean hasBeanOfType(Class<?> beanType) { <del> return !ObjectUtils.isEmpty(BeanFactoryUtils.beanNamesForTypeIncludingAncestors( <del> this.applicationContext, beanType, false, false)); <del> } <del> <del> /** <del> * Register a {@link org.springframework.web.servlet.view.ContentNegotiatingViewResolver} bean. <del> */ <del> public ContentNegotiatingRegistration contentNegotiating(View... defaultViews) { <del> ContentNegotiatingRegistration registration = new ContentNegotiatingRegistration(this); <del> registration.defaultViews(defaultViews); <del> addAndCheckViewResolution(registration); <del> return registration; <del> } <del> <del> protected List<ViewResolver> getViewResolvers() { <del> List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); <del> for(ViewResolutionRegistration<?> registration : this.registrations) { <del> viewResolvers.add(registration.getViewResolver()); <del> } <del> return viewResolvers; <del> } <del> <del> private void addAndCheckViewResolution(ViewResolutionRegistration<?> registration) { <del> for(ViewResolutionRegistration<?> existingRegistration : this.registrations) { <del> if(existingRegistration.getClass().equals(registration.getClass())) { <del> throw new IllegalStateException("An instance of " + registration.getClass().getSimpleName() <del> + " is already registered, and multiple view resolvers and configurers beans are not supported by this registry"); <del> } <del> } <del> registrations.add(registration); <del> } <del>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistry.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.config.annotation; <add> <add>import org.springframework.beans.factory.BeanFactoryUtils; <add>import org.springframework.beans.factory.BeanInitializationException; <add>import org.springframework.context.ApplicationContext; <add>import org.springframework.core.Ordered; <add>import org.springframework.util.CollectionUtils; <add>import org.springframework.util.ObjectUtils; <add>import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.servlet.View; <add>import org.springframework.web.servlet.ViewResolver; <add>import org.springframework.web.servlet.view.BeanNameViewResolver; <add>import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; <add>import org.springframework.web.servlet.view.InternalResourceViewResolver; <add>import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; <add>import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; <add>import org.springframework.web.servlet.view.tiles3.TilesConfigurer; <add>import org.springframework.web.servlet.view.tiles3.TilesViewResolver; <add>import org.springframework.web.servlet.view.velocity.VelocityConfigurer; <add>import org.springframework.web.servlet.view.velocity.VelocityViewResolver; <add> <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.List; <add> <add>/** <add> * Assist with the configuration of a chain of <add> * {@link org.springframework.web.servlet.ViewResolver ViewResolver} instances. <add> * This class is expected to be used via {@link WebMvcConfigurer#configureViewResolvers}. <add> * <add> * @author Sebastien Deleuze <add> * @author Rossen Stoyanchev <add> * @since 4.1 <add> */ <add>public class ViewResolverRegistry { <add> <add> private ContentNegotiatingViewResolver contentNegotiatingResolver; <add> <add> private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(4); <add> <add> private int order = Ordered.LOWEST_PRECEDENCE; <add> <add> private ContentNegotiationManager contentNegotiationManager; <add> <add> private ApplicationContext applicationContext; <add> <add> <add> protected void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) { <add> this.contentNegotiationManager = contentNegotiationManager; <add> } <add> <add> protected void setApplicationContext(ApplicationContext applicationContext) { <add> this.applicationContext = applicationContext; <add> } <add> <add> /** <add> * Whether any view resolvers have been registered. <add> */ <add> public boolean hasRegistrations() { <add> return (this.contentNegotiatingResolver != null || !this.viewResolvers.isEmpty()); <add> } <add> <add> <add> /** <add> * Enable use of a {@link ContentNegotiatingViewResolver} to front all other <add> * configured view resolvers and select among all selected Views based on <add> * media types requested by the client (e.g. in the Accept header). <add> * <add> * <p>If invoked multiple times the provided default views will be added to <add> * any other default views that may have been configured already. <add> * <add> * @see ContentNegotiatingViewResolver#setDefaultViews <add> */ <add> public void enableContentNegotiation(View... defaultViews) { <add> initContentNegotiatingViewResolver(defaultViews); <add> } <add> <add> /** <add> * Enable use of a {@link ContentNegotiatingViewResolver} to front all other <add> * configured view resolvers and select among all selected Views based on <add> * media types requested by the client (e.g. in the Accept header). <add> * <add> * <p>If invoked multiple times the provided default views will be added to <add> * any other default views that may have been configured already. <add> * <add> * @see ContentNegotiatingViewResolver#setDefaultViews <add> */ <add> public void enableContentNegotiation(boolean useNotAcceptableStatus, View... defaultViews) { <add> initContentNegotiatingViewResolver(defaultViews); <add> this.contentNegotiatingResolver.setUseNotAcceptableStatusCode(useNotAcceptableStatus); <add> } <add> <add> private void initContentNegotiatingViewResolver(View[] defaultViews) { <add> <add> // ContentNegotiatingResolver in the registry: elevate its precedence! <add> this.order = Ordered.HIGHEST_PRECEDENCE; <add> <add> if (this.contentNegotiatingResolver != null) { <add> if (!ObjectUtils.isEmpty(defaultViews)) { <add> if (!CollectionUtils.isEmpty(this.contentNegotiatingResolver.getDefaultViews())) { <add> List<View> views = new ArrayList<View>(this.contentNegotiatingResolver.getDefaultViews()); <add> views.addAll(Arrays.asList(defaultViews)); <add> this.contentNegotiatingResolver.setDefaultViews(views); <add> } <add> } <add> } <add> else { <add> this.contentNegotiatingResolver = new ContentNegotiatingViewResolver(); <add> this.contentNegotiatingResolver.setDefaultViews(Arrays.asList(defaultViews)); <add> this.contentNegotiatingResolver.setViewResolvers(this.viewResolvers); <add> this.contentNegotiatingResolver.setContentNegotiationManager(this.contentNegotiationManager); <add> } <add> } <add> <add> /** <add> * Enable view resolution by forwarding to JSP pages with a default view name <add> * prefix of "/WEB-INF/" and a default suffix of ".jsp". <add> * <add> * <p>This method may be invoked multiple and each call will register a <add> * separate ViewResolver instance. Note that since it's not easy to determine <add> * if a JSP exists without forwarding to it, using multiple JSP-based view <add> * resolvers only makes sense in combination with the "viewNames" property <add> * that indicates which view names are handled by which resolver. <add> */ <add> public UrlBasedViewResolverRegistration jsp() { <add> return jsp("/WEB-INF/", ".jsp"); <add> } <add> <add> /** <add> * Enable view resolution by forwarding to JSP pages with the specified <add> * prefix and suffix. <add> * <add> * <p>This method may be invoked multiple and each call will register a <add> * separate ViewResolver instance. Note that since it's not easy to determine <add> * if a JSP exists without forwarding to it, using multiple JSP-based view <add> * resolvers only makes sense in combination with the "viewNames" property <add> * that indicates which view names are handled by which resolver. <add> */ <add> public UrlBasedViewResolverRegistration jsp(String prefix, String suffix) { <add> InternalResourceViewResolver resolver = new InternalResourceViewResolver(); <add> resolver.setPrefix(prefix); <add> resolver.setSuffix(suffix); <add> this.viewResolvers.add(resolver); <add> return new UrlBasedViewResolverRegistration(resolver); <add> } <add> <add> /** <add> * Enable Tiles-based view resolution. <add> * <add> * <p>By default tiles definitions are expected to be in "/WEB-INF/tiles.xml". <add> * To change that and other Tiles-related options please also implement the <add> * interface {@link TilesWebMvcConfigurer}. <add> */ <add> public UrlBasedViewResolverRegistration tiles() { <add> if (this.applicationContext != null && !hasBeanOfType(TilesConfigurer.class)) { <add> throw new BeanInitializationException( <add> "It looks like you're trying to configure Tiles view resolution. " + <add> "If not using @EnableWebMvc you must import WebMvcTilesConfiguration, " + <add> "or declare your own TilesConfigurer bean."); <add> } <add> TilesRegistration registration = new TilesRegistration(); <add> this.viewResolvers.add(registration.getViewResolver()); <add> return registration; <add> } <add> <add> /** <add> * Enable FreeMarker-based view resolution with an empty default view name <add> * prefix and a default suffix of ".ftl". <add> * <add> * <p>By default the FreeMarker template loader path is set to "/WEB-INF/". <add> * To change that and other FreeMarker-related options please also implement <add> * the interface {@link FreeMarkerWebMvcConfigurer}. <add> */ <add> public UrlBasedViewResolverRegistration freeMarker() { <add> if (this.applicationContext != null && !hasBeanOfType(FreeMarkerConfigurer.class)) { <add> throw new BeanInitializationException( <add> "It looks like you're trying to configure FreeMarker view resolution. " + <add> "If not using @EnableWebMvc you must import WebMvcFreeMarkerConfiguration, " + <add> "or declare your own FreeMarkerConfigurer bean."); <add> } <add> FreeMarkerRegistration registration = new FreeMarkerRegistration(); <add> this.viewResolvers.add(registration.getViewResolver()); <add> return registration; <add> } <add> <add> /** <add> * Enable Velocity-based view resolution with an empty default view name <add> * prefix, a default suffix of ".vm". <add> * <add> * <p>By default the Velocity resource loader path is set to "/WEB-INF/". <add> * To change that and other Velocity-related options please also implement <add> * the interface {@link VelocityWebMvcConfigurer}. <add> */ <add> public UrlBasedViewResolverRegistration velocity() { <add> if (this.applicationContext != null && !hasBeanOfType(VelocityConfigurer.class)) { <add> throw new BeanInitializationException( <add> "It looks like you're trying to configure Velocity view resolution. " + <add> "If not using @EnableWebMvc you must import WebMvcVelocityConfiguration, " + <add> "or declare your own VelocityConfigurer bean."); <add> } <add> VelocityRegistration registration = new VelocityRegistration(); <add> this.viewResolvers.add(registration.getViewResolver()); <add> return registration; <add> } <add> <add> /** <add> * Enable the ability to map view names returned from controllers to <add> * {@link org.springframework.web.servlet.View} beans. <add> */ <add> public void beanName() { <add> BeanNameViewResolver resolver = new BeanNameViewResolver(); <add> this.viewResolvers.add(resolver); <add> } <add> <add> /** <add> * Register a {@link ViewResolver} bean instance. This may be useful to <add> * configure a custom (or 3rd party) resolver implementation. It may also be <add> * used as an alternative to other registration methods in this class when <add> * they don't expose some more advanced property that needs to be set. <add> */ <add> public void viewResolver(ViewResolver viewResolver) { <add> if (viewResolver instanceof ContentNegotiatingViewResolver) { <add> throw new BeanInitializationException( <add> "addViewResolver cannot be used to configure a ContentNegotiatingViewResolver. " + <add> "Please use the method enableContentNegotiation instead."); <add> } <add> this.viewResolvers.add(viewResolver); <add> } <add> <add> protected boolean hasBeanOfType(Class<?> beanType) { <add> return !ObjectUtils.isEmpty(BeanFactoryUtils.beanNamesForTypeIncludingAncestors( <add> this.applicationContext, beanType, false, false)); <add> } <add> <add> <add> protected int getOrder() { <add> return this.order; <add> } <add> <add> protected List<ViewResolver> getViewResolvers() { <add> if (this.contentNegotiatingResolver != null) { <add> return Collections.<ViewResolver>singletonList(this.contentNegotiatingResolver); <add> } <add> else { <add> return this.viewResolvers; <add> } <add> } <add> <add> <add> private static class TilesRegistration extends UrlBasedViewResolverRegistration { <add> <add> private TilesRegistration() { <add> super(new TilesViewResolver()); <add> } <add> } <add> <add> private static class VelocityRegistration extends UrlBasedViewResolverRegistration { <add> <add> private VelocityRegistration() { <add> super(new VelocityViewResolver()); <add> getViewResolver().setSuffix(".vm"); <add> } <add> } <add> <add> private static class FreeMarkerRegistration extends UrlBasedViewResolverRegistration { <add> <add> private FreeMarkerRegistration() { <add> super(new FreeMarkerViewResolver()); <add> getViewResolver().setSuffix(".ftl"); <add> } <add> } <add> <add>} <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupport.java <ide> import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver; <ide> import org.springframework.web.servlet.resource.ResourceUrlProvider; <ide> import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor; <del>import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; <add>import org.springframework.web.servlet.view.ViewResolverComposite; <ide> import org.springframework.web.util.UrlPathHelper; <ide> <ide> /** <ide> public class WebMvcConfigurationSupport implements ApplicationContextAware, Serv <ide> <ide> private PathMatchConfigurer pathMatchConfigurer; <ide> <del> private ViewResolutionRegistry viewResolutionRegistry; <ide> <ide> /** <ide> * Set the {@link javax.servlet.ServletContext}, e.g. for resource handling, <ide> public HandlerMapping viewControllerHandlerMapping() { <ide> protected void addViewControllers(ViewControllerRegistry registry) { <ide> } <ide> <del> /** <del> * Override this method to configure view resolution. <del> * @see ViewResolutionRegistry <del> */ <del> protected void configureViewResolution(ViewResolutionRegistry registry) { <del> } <del> <ide> /** <ide> * Return a {@link BeanNameUrlHandlerMapping} ordered at 2 to map URL <ide> * paths to controller bean names. <ide> protected final void addDefaultHandlerExceptionResolvers(List<HandlerExceptionRe <ide> } <ide> <ide> /** <del> * Register a {@link ViewResolverComposite} that contains an ordered list of <add> * Register a {@link org.springframework.web.servlet.view.ViewResolverComposite} that contains an ordered list of <ide> * view resolvers obtained either through <del> * {@link #configureViewResolution(ViewResolutionRegistry)}. <add> * {@link #configureViewResolvers(ViewResolverRegistry)}. <ide> */ <ide> @Bean <del> public ViewResolverComposite viewResolverComposite() { <del> ViewResolutionRegistry registry = getViewResolutionRegistry(); <del> ViewResolverComposite compositeViewResolver = new ViewResolverComposite(); <del> List<ViewResolver> viewResolvers = registry.getViewResolvers(); <del> ContentNegotiatingViewResolver contentNegotiatingViewResolver = null; <del> List<ViewResolver> filteredViewResolvers = new ArrayList<ViewResolver>(); <del> for(ViewResolver viewResolver : viewResolvers) { <del> if(viewResolver instanceof ContentNegotiatingViewResolver) { <del> contentNegotiatingViewResolver = (ContentNegotiatingViewResolver)viewResolver; <del> contentNegotiatingViewResolver.setContentNegotiationManager(this.mvcContentNegotiationManager()); <del> } else { <del> filteredViewResolvers.add(viewResolver); <del> } <del> } <del> if(contentNegotiatingViewResolver != null) { <del> contentNegotiatingViewResolver.setViewResolvers(filteredViewResolvers); <del> viewResolvers = new ArrayList<ViewResolver>(); <del> viewResolvers.add(contentNegotiatingViewResolver); <del> } <del> compositeViewResolver.setViewResolvers(viewResolvers); <del> compositeViewResolver.setApplicationContext(this.applicationContext); <del> compositeViewResolver.setServletContext(this.servletContext); <del> <del> return compositeViewResolver; <add> public ViewResolver mvcViewResolver() { <add> ViewResolverRegistry registry = new ViewResolverRegistry(); <add> registry.setContentNegotiationManager(mvcContentNegotiationManager()); <add> registry.setApplicationContext(this.applicationContext); <add> configureViewResolvers(registry); <add> <add> ViewResolverComposite composite = new ViewResolverComposite(); <add> composite.setOrder(registry.getOrder()); <add> composite.setViewResolvers(registry.getViewResolvers()); <add> composite.setApplicationContext(this.applicationContext); <add> composite.setServletContext(this.servletContext); <add> return composite; <ide> } <ide> <del> protected ViewResolutionRegistry getViewResolutionRegistry() { <del> if(this.viewResolutionRegistry == null) { <del> this.viewResolutionRegistry = new ViewResolutionRegistry(this.applicationContext); <del> configureViewResolution(this.viewResolutionRegistry); <del> } <del> return this.viewResolutionRegistry; <add> /** <add> * Override this method to configure view resolution. <add> * @see ViewResolverRegistry <add> */ <add> protected void configureViewResolvers(ViewResolverRegistry registry) { <ide> } <ide> <add> <ide> private final static class EmptyHandlerMapping extends AbstractHandlerMapping { <ide> <ide> @Override <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurer.java <ide> public interface WebMvcConfigurer { <ide> void addViewControllers(ViewControllerRegistry registry); <ide> <ide> /** <del> * Configure view resolution to translate view names to view implementations. <add> * Configure view resolvers to translate String-based view names returned from <add> * controllers into concrete {@link org.springframework.web.servlet.View} <add> * implementations to perform rendering with. <ide> */ <del> void configureViewResolution(ViewResolutionRegistry registry); <add> void configureViewResolvers(ViewResolverRegistry registry); <ide> <ide> /** <ide> * Add handlers to serve static resources such as images, js, and, css <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerAdapter.java <ide> public void addViewControllers(ViewControllerRegistry registry) { <ide> * <p>This implementation is empty. <ide> */ <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurerComposite.java <ide> public void addViewControllers(ViewControllerRegistry registry) { <ide> } <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> for (WebMvcConfigurer delegate : this.delegates) { <del> delegate.configureViewResolution(registry); <add> delegate.configureViewResolvers(registry); <ide> } <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcFreeMarkerConfiguration.java <ide> public void setWebMvcConfigurers(List<FreeMarkerWebMvcConfigurer> webMvcConfigur <ide> <ide> @Bean <ide> @Lazy <del> public FreeMarkerConfigurer freeMarkerConfigurer() { <add> public FreeMarkerConfigurer mvcFreeMarkerConfigurer() { <ide> FreeMarkerConfigurer configurer = new FreeMarkerConfigurer(); <ide> configurer.setTemplateLoaderPath("/WEB-INF/"); <ide> for (FreeMarkerWebMvcConfigurer webMvcConfigurer : this.webMvcConfigurers) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcTilesConfiguration.java <ide> public void setResourceLoader(ResourceLoader resourceLoader) { <ide> <ide> <ide> @Bean <del> public TilesConfigurer tilesConfigurer() { <add> public TilesConfigurer mvcTilesConfigurer() { <ide> TilesConfigurer configurer = new TilesConfigurer(); <ide> if (!this.webMvcConfigurers.isEmpty()) { <ide> for (TilesWebMvcConfigurer webMvcConfigurer : this.webMvcConfigurers) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/WebMvcVelocityConfiguration.java <ide> public void setWebMvcConfigurers(List<VelocityWebMvcConfigurer> webMvcConfigurer <ide> <ide> @Bean <ide> @Lazy <del> public VelocityConfigurer velocityConfigurer() { <add> public VelocityConfigurer mvcVelocityConfigurer() { <ide> VelocityConfigurer configurer = new VelocityConfigurer(); <ide> configurer.setResourceLoaderPath("/WEB-INF/"); <ide> for (VelocityWebMvcConfigurer webMvcConfigurer : this.webMvcConfigurers) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java <ide> public void setDefaultViews(List<View> defaultViews) { <ide> this.defaultViews = defaultViews; <ide> } <ide> <add> public List<View> getDefaultViews() { <add> return Collections.unmodifiableList(this.defaultViews); <add> } <add> <ide> /** <ide> * Sets the view resolvers to be wrapped by this view resolver. <ide> * <p>If this property is not set, view resolvers will be detected automatically. <ide> public void setViewResolvers(List<ViewResolver> viewResolvers) { <ide> this.viewResolvers = viewResolvers; <ide> } <ide> <add> public List<ViewResolver> getViewResolvers() { <add> return Collections.unmodifiableList(this.viewResolvers); <add> } <add> <ide> <ide> @Override <ide> protected void initServletContext(ServletContext servletContext) { <add><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/ViewResolverComposite.java <del><path>spring-webmvc/src/main/java/org/springframework/web/servlet/ViewResolverComposite.java <ide> * limitations under the License. <ide> */ <ide> <del>package org.springframework.web.servlet; <add>package org.springframework.web.servlet.view; <ide> <ide> import org.springframework.beans.BeansException; <add>import org.springframework.beans.factory.InitializingBean; <ide> import org.springframework.context.ApplicationContext; <ide> import org.springframework.context.ApplicationContextAware; <ide> import org.springframework.core.Ordered; <add>import org.springframework.util.CollectionUtils; <ide> import org.springframework.web.context.ServletContextAware; <add>import org.springframework.web.servlet.View; <add>import org.springframework.web.servlet.ViewResolver; <ide> <ide> import javax.servlet.ServletContext; <add>import java.util.ArrayList; <ide> import java.util.Collections; <ide> import java.util.List; <ide> import java.util.Locale; <ide> <ide> /** <del> * A {@link ViewResolverComposite} that delegates to a list of other {@link ViewResolver}s. <add> * A {@link org.springframework.web.servlet.ViewResolver} that delegates to others. <ide> * <ide> * @author Sebastien Deleuze <add> * @author Rossen Stoyanchev <ide> * @since 4.1 <ide> */ <del>public class ViewResolverComposite implements ApplicationContextAware, ServletContextAware, ViewResolver, Ordered { <add>public class ViewResolverComposite implements ViewResolver, Ordered, InitializingBean, <add> ApplicationContextAware, ServletContextAware { <ide> <del> private List<ViewResolver> viewResolvers; <add> private final List<ViewResolver> viewResolvers = new ArrayList<ViewResolver>(); <ide> <ide> private int order = Ordered.LOWEST_PRECEDENCE; <ide> <del> public void setOrder(int order) { <del> this.order = order; <del> } <del> <del> @Override <del> public int getOrder() { <del> return this.order; <del> } <ide> <ide> /** <ide> * Set the list of view viewResolvers to delegate to. <ide> */ <ide> public void setViewResolvers(List<ViewResolver> viewResolvers) { <del> this.viewResolvers = viewResolvers; <add> this.viewResolvers.clear(); <add> if (!CollectionUtils.isEmpty(viewResolvers)) { <add> this.viewResolvers.addAll(viewResolvers); <add> } <ide> } <ide> <ide> /** <ide> * Return the list of view viewResolvers to delegate to. <ide> */ <ide> public List<ViewResolver> getViewResolvers() { <del> return Collections.unmodifiableList(viewResolvers); <add> return Collections.unmodifiableList(this.viewResolvers); <add> } <add> <add> public void setOrder(int order) { <add> this.order = order; <ide> } <ide> <ide> @Override <del> public View resolveViewName(String viewName, Locale locale) throws Exception { <del> if (viewResolvers != null) { <del> for (ViewResolver viewResolver : viewResolvers) { <del> View v = viewResolver.resolveViewName(viewName, locale); <del> if (v != null) { <del> return v; <del> } <add> public int getOrder() { <add> return this.order; <add> } <add> <add> @Override <add> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <add> for (ViewResolver viewResolver : this.viewResolvers) { <add> if (viewResolver instanceof ApplicationContextAware) { <add> ((ApplicationContextAware)viewResolver).setApplicationContext(applicationContext); <ide> } <ide> } <add> } <ide> <del> return null; <add> @Override <add> public void setServletContext(ServletContext servletContext) { <add> for (ViewResolver viewResolver : this.viewResolvers) { <add> if (viewResolver instanceof ServletContextAware) { <add> ((ServletContextAware)viewResolver).setServletContext(servletContext); <add> } <add> } <ide> } <ide> <ide> @Override <del> public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { <del> if (viewResolvers != null) { <del> for (ViewResolver viewResolver : viewResolvers) { <del> if(viewResolver instanceof ApplicationContextAware) { <del> ((ApplicationContextAware)viewResolver).setApplicationContext(applicationContext); <del> } <add> public void afterPropertiesSet() throws Exception { <add> for (ViewResolver viewResolver : this.viewResolvers) { <add> if (viewResolver instanceof InitializingBean) { <add> ((InitializingBean) viewResolver).afterPropertiesSet(); <ide> } <ide> } <ide> } <ide> <ide> @Override <del> public void setServletContext(ServletContext servletContext) { <del> if (viewResolvers != null) { <del> for (ViewResolver viewResolver : viewResolvers) { <del> if(viewResolver instanceof ServletContextAware) { <del> ((ServletContextAware)viewResolver).setServletContext(servletContext); <del> } <add> public View resolveViewName(String viewName, Locale locale) throws Exception { <add> for (ViewResolver viewResolver : this.viewResolvers) { <add> View view = viewResolver.resolveViewName(viewName, locale); <add> if (view != null) { <add> return view; <ide> } <ide> } <add> return null; <ide> } <add> <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionIntegrationTests.java <ide> public SampleController sampleController() { <ide> @Configuration <ide> static class MinimalFreeMarkerWebConfig extends AbstractWebConfig { <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <del> registry.freemarker(); <add> public void configureViewResolvers(ViewResolverRegistry registry) { <add> registry.freeMarker(); <ide> } <ide> } <ide> <ide> @Configuration <ide> static class MinimalVelocityWebConfig extends AbstractWebConfig { <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.velocity(); <ide> } <ide> } <ide> <ide> @Configuration <ide> static class MinimalTilesWebConfig extends AbstractWebConfig { <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.tiles(); <ide> } <ide> } <ide> <ide> @Configuration <ide> static class FreeMarkerWebConfig extends AbstractWebConfig implements FreeMarkerWebMvcConfigurer { <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <del> registry.freemarker(); <add> public void configureViewResolvers(ViewResolverRegistry registry) { <add> registry.freeMarker(); <ide> } <ide> @Override <ide> public void configureFreeMarker(FreeMarkerConfigurer configurer) { <ide> public void configureFreeMarker(FreeMarkerConfigurer configurer) { <ide> @Configuration <ide> static class VelocityWebConfig extends AbstractWebConfig implements VelocityWebMvcConfigurer { <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.velocity(); <ide> } <ide> @Override <ide> public void configureVelocity(VelocityConfigurer configurer) { <ide> @Configuration <ide> static class TilesWebConfig extends AbstractWebConfig implements TilesWebMvcConfigurer { <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.tiles(); <ide> } <ide> @Override <ide> static class InvalidFreeMarkerWebConfig extends WebMvcConfigurationSupport { <ide> // No @EnableWebMvc and no FreeMarkerConfigurer bean <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <del> registry.freemarker(); <add> public void configureViewResolvers(ViewResolverRegistry registry) { <add> registry.freeMarker(); <ide> } <ide> } <ide> <ide> static class InvalidVelocityWebConfig extends WebMvcConfigurationSupport { <ide> // No @EnableWebMvc and no VelocityConfigurer bean <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.velocity(); <ide> } <ide> } <ide> static class InvalidTilesWebConfig extends WebMvcConfigurationSupport { <ide> // No @EnableWebMvc and no TilesConfigurer bean <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <ide> registry.tiles(); <ide> } <ide> } <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolutionRegistryTests.java <del>/* <del> * Copyright 2002-2014 the original author or authors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); <del> * you may not use this file except in compliance with the License. <del> * You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software <del> * distributed under the License is distributed on an "AS IS" BASIS, <del> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <del> * See the License for the specific language governing permissions and <del> * limitations under the License. <del> */ <del> <del>package org.springframework.web.servlet.config.annotation; <del> <del>import org.junit.Before; <del>import org.junit.Test; <del>import org.springframework.beans.DirectFieldAccessor; <del>import org.springframework.web.context.support.StaticWebApplicationContext; <del>import org.springframework.web.servlet.view.BeanNameViewResolver; <del>import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; <del>import org.springframework.web.servlet.view.InternalResourceViewResolver; <del>import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; <del>import org.springframework.web.servlet.view.json.MappingJackson2JsonView; <del>import org.springframework.web.servlet.view.tiles3.TilesViewResolver; <del>import org.springframework.web.servlet.view.velocity.VelocityViewResolver; <del> <del>import static org.junit.Assert.*; <del>import static org.junit.Assert.assertEquals; <del> <del>/** <del> * Test fixture with a {@link ViewResolutionRegistry}. <del> * <del> * @author Sebastien Deleuze <del> */ <del>public class ViewResolutionRegistryTests { <del> <del> private ViewResolutionRegistry registry; <del> <del> @Before <del> public void setUp() { <del> registry = new ViewResolutionRegistry(new StaticWebApplicationContext()); <del> } <del> <del> @Test <del> public void noViewResolution() { <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(0, registry.getViewResolvers().size()); <del> } <del> <del> @Test <del> public void customViewResolution() { <del> InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); <del> viewResolver.setPrefix("/"); <del> viewResolver.setSuffix(".jsp"); <del> registry.addViewResolver(viewResolver); <del> assertEquals(InternalResourceViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> InternalResourceViewResolver resolver = (InternalResourceViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("/", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".jsp", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> } <del> <del> @Test <del> public void beanNameViewResolution() { <del> registry.beanName(); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(BeanNameViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> } <del> <del> @Test <del> public void jspViewResolution() { <del> registry.jsp("/", ".jsp"); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(InternalResourceViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> InternalResourceViewResolver resolver = (InternalResourceViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("/", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".jsp", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> } <del> <del> @Test <del> public void defaultJspViewResolution() { <del> registry.jsp(); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(InternalResourceViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> InternalResourceViewResolver resolver = (InternalResourceViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("/WEB-INF/", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".jsp", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> } <del> <del> @Test <del> public void tilesViewResolution() { <del> this.registry.tiles(); <del> assertNotNull(this.registry.getViewResolvers()); <del> assertEquals(1, this.registry.getViewResolvers().size()); <del> assertEquals(TilesViewResolver.class, this.registry.getViewResolvers().get(0).getClass()); <del> } <del> <del> @Test <del> public void velocityViewResolution() { <del> registry.velocity().prefix("/").suffix(".vm").cache(true); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(VelocityViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> VelocityViewResolver resolver = (VelocityViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("/", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".vm", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> assertEquals(1024, resolverDirectFieldAccessor.getPropertyValue("cacheLimit")); <del> } <del> <del> @Test <del> public void defaultVelocityViewResolution() { <del> registry.velocity(); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(VelocityViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> VelocityViewResolver resolver = (VelocityViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".vm", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> } <del> <del> @Test <del> public void freeMarkerViewResolution() { <del> registry.freemarker().prefix("/").suffix(".fmt").cache(false); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(FreeMarkerViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> FreeMarkerViewResolver resolver = (FreeMarkerViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("/", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".fmt", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> assertEquals(0, resolverDirectFieldAccessor.getPropertyValue("cacheLimit")); <del> } <del> <del> @Test <del> public void defaultFreeMarkerViewResolution() { <del> registry.freemarker(); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(FreeMarkerViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> FreeMarkerViewResolver resolver = (FreeMarkerViewResolver)registry.getViewResolvers().get(0); <del> DirectFieldAccessor resolverDirectFieldAccessor = new DirectFieldAccessor(resolver); <del> assertEquals("", resolverDirectFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".ftl", resolverDirectFieldAccessor.getPropertyValue("suffix")); <del> } <del> <del> @Test <del> public void contentNegotiatingViewResolution() { <del> registry.contentNegotiating().useNotAcceptable(false).defaultViews(new MappingJackson2JsonView()); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(1, registry.getViewResolvers().size()); <del> assertEquals(ContentNegotiatingViewResolver.class, registry.getViewResolvers().get(0).getClass()); <del> } <del> <del> @Test <del> public void multipleViewResolutions() { <del> registry.jsp().and().beanName(); <del> assertNotNull(registry.getViewResolvers()); <del> assertEquals(2, registry.getViewResolvers().size()); <del> } <del> <del>} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/ViewResolverRegistryTests.java <add>/* <add> * Copyright 2002-2014 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.config.annotation; <add> <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.springframework.beans.DirectFieldAccessor; <add>import org.springframework.core.Ordered; <add>import org.springframework.web.accept.ContentNegotiationManager; <add>import org.springframework.web.context.support.StaticWebApplicationContext; <add>import org.springframework.web.servlet.ViewResolver; <add>import org.springframework.web.servlet.view.BeanNameViewResolver; <add>import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; <add>import org.springframework.web.servlet.view.InternalResourceViewResolver; <add>import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; <add>import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; <add>import org.springframework.web.servlet.view.json.MappingJackson2JsonView; <add>import org.springframework.web.servlet.view.tiles3.TilesConfigurer; <add>import org.springframework.web.servlet.view.tiles3.TilesViewResolver; <add>import org.springframework.web.servlet.view.velocity.VelocityConfigurer; <add>import org.springframework.web.servlet.view.velocity.VelocityViewResolver; <add>import org.springframework.web.servlet.view.xml.MarshallingView; <add> <add>import java.util.Arrays; <add> <add>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertEquals; <add> <add>/** <add> * Test fixture with a {@link ViewResolverRegistry}. <add> * <add> * @author Sebastien Deleuze <add> * @author Rossen Stoyanchev <add> */ <add>public class ViewResolverRegistryTests { <add> <add> private ViewResolverRegistry registry; <add> <add> <add> @Before <add> public void setUp() { <add> StaticWebApplicationContext context = new StaticWebApplicationContext(); <add> context.registerSingleton("freeMarkerConfigurer", FreeMarkerConfigurer.class); <add> context.registerSingleton("velocityConfigurer", VelocityConfigurer.class); <add> context.registerSingleton("tilesConfigurer", TilesConfigurer.class); <add> this.registry = new ViewResolverRegistry(); <add> this.registry.setApplicationContext(context); <add> this.registry.setContentNegotiationManager(new ContentNegotiationManager()); <add> } <add> <add> <add> @Test <add> public void order() { <add> assertEquals(Ordered.LOWEST_PRECEDENCE, this.registry.getOrder()); <add> this.registry.enableContentNegotiation(); <add> assertEquals(Ordered.HIGHEST_PRECEDENCE, this.registry.getOrder()); <add> } <add> <add> @Test <add> public void hasRegistrations() { <add> assertFalse(this.registry.hasRegistrations()); <add> this.registry.velocity(); <add> assertTrue(this.registry.hasRegistrations()); <add> } <add> <add> @Test <add> public void hasRegistrationsWhenContentNegotiationEnabled() { <add> assertFalse(this.registry.hasRegistrations()); <add> this.registry.enableContentNegotiation(); <add> assertTrue(this.registry.hasRegistrations()); <add> } <add> <add> @Test <add> public void noResolvers() { <add> assertNotNull(this.registry.getViewResolvers()); <add> assertEquals(0, this.registry.getViewResolvers().size()); <add> assertFalse(this.registry.hasRegistrations()); <add> } <add> <add> @Test <add> public void customViewResolver() { <add> InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); <add> viewResolver.setPrefix("/"); <add> viewResolver.setSuffix(".jsp"); <add> this.registry.viewResolver(viewResolver); <add> assertSame(viewResolver, this.registry.getViewResolvers().get(0)); <add> } <add> <add> @Test <add> public void beanName() { <add> this.registry.beanName(); <add> assertEquals(1, this.registry.getViewResolvers().size()); <add> assertEquals(BeanNameViewResolver.class, registry.getViewResolvers().get(0).getClass()); <add> } <add> <add> @Test <add> public void jspDefaultValues() { <add> this.registry.jsp(); <add> InternalResourceViewResolver resolver = checkAndGetResolver(InternalResourceViewResolver.class); <add> checkPropertyValues(resolver, "prefix", "/WEB-INF/", "suffix", ".jsp"); <add> } <add> <add> @Test <add> public void jsp() { <add> this.registry.jsp("/", ".jsp"); <add> InternalResourceViewResolver resolver = checkAndGetResolver(InternalResourceViewResolver.class); <add> checkPropertyValues(resolver, "prefix", "/", "suffix", ".jsp"); <add> } <add> <add> @Test <add> public void jspMultipleResolvers() { <add> this.registry.jsp().viewNames("view1", "view2"); <add> this.registry.jsp().viewNames("view3", "view4"); <add> assertNotNull(this.registry.getViewResolvers()); <add> assertEquals(2, this.registry.getViewResolvers().size()); <add> assertEquals(InternalResourceViewResolver.class, this.registry.getViewResolvers().get(0).getClass()); <add> assertEquals(InternalResourceViewResolver.class, this.registry.getViewResolvers().get(1).getClass()); <add> } <add> <add> @Test <add> public void tiles() { <add> this.registry.tiles(); <add> checkAndGetResolver(TilesViewResolver.class); <add> } <add> <add> @Test <add> public void velocity() { <add> this.registry.velocity().prefix("/").suffix(".vm").cache(true); <add> VelocityViewResolver resolver = checkAndGetResolver(VelocityViewResolver.class); <add> checkPropertyValues(resolver, "prefix", "/", "suffix", ".vm", "cacheLimit", 1024); <add> } <add> <add> @Test <add> public void velocityDefaultValues() { <add> this.registry.velocity(); <add> VelocityViewResolver resolver = checkAndGetResolver(VelocityViewResolver.class); <add> checkPropertyValues(resolver, "prefix", "", "suffix", ".vm"); <add> } <add> <add> @Test <add> public void freeMarker() { <add> this.registry.freeMarker().prefix("/").suffix(".fmt").cache(false); <add> FreeMarkerViewResolver resolver = checkAndGetResolver(FreeMarkerViewResolver.class); <add> checkPropertyValues(resolver, "prefix", "/", "suffix", ".fmt", "cacheLimit", 0); <add> } <add> <add> @Test <add> public void freeMarkerDefaultValues() { <add> this.registry.freeMarker(); <add> FreeMarkerViewResolver resolver = checkAndGetResolver(FreeMarkerViewResolver.class); <add> checkPropertyValues(resolver, "prefix", "", "suffix", ".ftl"); <add> } <add> <add> @Test <add> public void contentNegotiation() { <add> MappingJackson2JsonView view = new MappingJackson2JsonView(); <add> this.registry.enableContentNegotiation(view); <add> ContentNegotiatingViewResolver resolver = checkAndGetResolver(ContentNegotiatingViewResolver.class); <add> assertEquals(Arrays.asList(view), resolver.getDefaultViews()); <add> assertEquals(Ordered.HIGHEST_PRECEDENCE, this.registry.getOrder()); <add> } <add> <add> @Test <add> public void contentNegotiationAddsDefaultViewRegistrations() { <add> MappingJackson2JsonView view1 = new MappingJackson2JsonView(); <add> this.registry.enableContentNegotiation(view1); <add> <add> ContentNegotiatingViewResolver resolver1 = checkAndGetResolver(ContentNegotiatingViewResolver.class); <add> assertEquals(Arrays.asList(view1), resolver1.getDefaultViews()); <add> <add> MarshallingView view2 = new MarshallingView(); <add> this.registry.enableContentNegotiation(view2); <add> <add> ContentNegotiatingViewResolver resolver2 = checkAndGetResolver(ContentNegotiatingViewResolver.class); <add> assertEquals(Arrays.asList(view1, view2), resolver2.getDefaultViews()); <add> assertSame(resolver1, resolver2); <add> } <add> <add> <add> @SuppressWarnings("unchecked") <add> private <T extends ViewResolver> T checkAndGetResolver(Class<T> resolverType) { <add> assertNotNull(this.registry.getViewResolvers()); <add> assertEquals(1, this.registry.getViewResolvers().size()); <add> assertEquals(resolverType, this.registry.getViewResolvers().get(0).getClass()); <add> return (T) registry.getViewResolvers().get(0); <add> } <add> <add> private void checkPropertyValues(ViewResolver resolver, Object... nameValuePairs) { <add> DirectFieldAccessor accessor = new DirectFieldAccessor(resolver); <add> for (int i = 0; i < nameValuePairs.length ; i++, i++) { <add> Object expected = nameValuePairs[i + 1]; <add> Object actual = accessor.getPropertyValue((String) nameValuePairs[i]); <add> assertEquals(expected, actual); <add> } <add> } <add> <add>} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportExtensionTests.java <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; <ide> import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; <ide> import org.springframework.web.servlet.resource.ResourceUrlProviderExposingInterceptor; <add>import org.springframework.web.servlet.view.ViewResolverComposite; <ide> import org.springframework.web.util.UrlPathHelper; <ide> import org.springframework.web.servlet.view.ContentNegotiatingViewResolver; <ide> import org.springframework.web.servlet.view.InternalResourceViewResolver; <ide> import org.springframework.web.servlet.view.json.MappingJackson2JsonView; <ide> <ide> /** <del> * A test fixture with a sub-class of {@link WebMvcConfigurationSupport} that <add> * A test fixture with a sub-class of {@link WebMvcConfigurationSupport} that also <ide> * implements the various {@link WebMvcConfigurer} extension points. <ide> * <add> * The former doesn't implement the latter but the two must have compatible <add> * callback method signatures to support moving from simple to advanced <add> * configuration -- i.e. dropping @EnableWebMvc + WebMvcConfigurer and extending <add> * directly from WebMvcConfigurationSupport. <add> * <ide> * @author Rossen Stoyanchev <ide> * @author Sebastien Deleuze <ide> */ <ide> public class WebMvcConfigurationSupportExtensionTests { <ide> <del> private TestWebMvcConfigurationSupport webConfig; <add> private TestWebMvcConfigurationSupport config; <add> <add> private StaticWebApplicationContext context; <ide> <del> private StaticWebApplicationContext webAppContext; <ide> <ide> @Before <ide> public void setUp() { <del> this.webAppContext = new StaticWebApplicationContext(); <del> this.webAppContext.setServletContext(new MockServletContext(new FileSystemResourceLoader())); <del> this.webAppContext.registerSingleton("controller", TestController.class); <add> this.context = new StaticWebApplicationContext(); <add> this.context.setServletContext(new MockServletContext(new FileSystemResourceLoader())); <add> this.context.registerSingleton("controller", TestController.class); <ide> <del> this.webConfig = new TestWebMvcConfigurationSupport(); <del> this.webConfig.setApplicationContext(this.webAppContext); <del> this.webConfig.setServletContext(this.webAppContext.getServletContext()); <add> this.config = new TestWebMvcConfigurationSupport(); <add> this.config.setApplicationContext(this.context); <add> this.config.setServletContext(this.context.getServletContext()); <ide> } <ide> <ide> @Test <ide> public void handlerMappings() throws Exception { <del> RequestMappingHandlerMapping rmHandlerMapping = webConfig.requestMappingHandlerMapping(); <del> rmHandlerMapping.setApplicationContext(webAppContext); <add> RequestMappingHandlerMapping rmHandlerMapping = this.config.requestMappingHandlerMapping(); <add> rmHandlerMapping.setApplicationContext(this.context); <ide> rmHandlerMapping.afterPropertiesSet(); <ide> assertEquals(TestPathHelper.class, rmHandlerMapping.getUrlPathHelper().getClass()); <ide> assertEquals(TestPathMatcher.class, rmHandlerMapping.getPathMatcher().getClass()); <ide> public void handlerMappings() throws Exception { <ide> assertEquals(ConversionServiceExposingInterceptor.class, chain.getInterceptors()[1].getClass()); <ide> assertEquals(ResourceUrlProviderExposingInterceptor.class, chain.getInterceptors()[2].getClass()); <ide> <del> AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) webConfig.viewControllerHandlerMapping(); <del> handlerMapping.setApplicationContext(webAppContext); <add> AbstractHandlerMapping handlerMapping = (AbstractHandlerMapping) this.config.viewControllerHandlerMapping(); <add> handlerMapping.setApplicationContext(this.context); <ide> assertNotNull(handlerMapping); <ide> assertEquals(1, handlerMapping.getOrder()); <ide> assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass()); <ide> assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass()); <ide> HandlerExecutionChain handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/path")); <ide> assertNotNull(handler.getHandler()); <ide> <del> handlerMapping = (AbstractHandlerMapping) webConfig.resourceHandlerMapping(); <del> handlerMapping.setApplicationContext(webAppContext); <add> handlerMapping = (AbstractHandlerMapping) this.config.resourceHandlerMapping(); <add> handlerMapping.setApplicationContext(this.context); <ide> assertNotNull(handlerMapping); <del> assertEquals(Integer.MAX_VALUE-1, handlerMapping.getOrder()); <add> assertEquals(Integer.MAX_VALUE - 1, handlerMapping.getOrder()); <ide> assertEquals(TestPathHelper.class, handlerMapping.getUrlPathHelper().getClass()); <ide> assertEquals(TestPathMatcher.class, handlerMapping.getPathMatcher().getClass()); <ide> handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/resources/foo.gif")); <ide> assertNotNull(handler.getHandler()); <ide> <del> handlerMapping = (AbstractHandlerMapping) webConfig.defaultServletHandlerMapping(); <del> handlerMapping.setApplicationContext(webAppContext); <add> handlerMapping = (AbstractHandlerMapping) this.config.defaultServletHandlerMapping(); <add> handlerMapping.setApplicationContext(this.context); <ide> assertNotNull(handlerMapping); <ide> assertEquals(Integer.MAX_VALUE, handlerMapping.getOrder()); <ide> handler = handlerMapping.getHandler(new MockHttpServletRequest("GET", "/anyPath")); <ide> public void handlerMappings() throws Exception { <ide> @SuppressWarnings("unchecked") <ide> @Test <ide> public void requestMappingHandlerAdapter() throws Exception { <del> RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter(); <add> RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter(); <ide> <ide> // ConversionService <del> String actual = webConfig.mvcConversionService().convert(new TestBean(), String.class); <add> String actual = this.config.mvcConversionService().convert(new TestBean(), String.class); <ide> assertEquals("converted", actual); <ide> <ide> // Message converters <ide> public void requestMappingHandlerAdapter() throws Exception { <ide> <ide> @Test <ide> public void webBindingInitializer() throws Exception { <del> RequestMappingHandlerAdapter adapter = webConfig.requestMappingHandlerAdapter(); <add> RequestMappingHandlerAdapter adapter = this.config.requestMappingHandlerAdapter(); <ide> <ide> ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); <ide> assertNotNull(initializer); <ide> public void contentNegotiation() throws Exception { <ide> MockHttpServletRequest request = new MockHttpServletRequest("GET", "/foo.json"); <ide> NativeWebRequest webRequest = new ServletWebRequest(request); <ide> <del> ContentNegotiationManager manager = webConfig.requestMappingHandlerMapping().getContentNegotiationManager(); <add> ContentNegotiationManager manager = this.config.requestMappingHandlerMapping().getContentNegotiationManager(); <ide> assertEquals(Arrays.asList(MediaType.APPLICATION_JSON), manager.resolveMediaTypes(webRequest)); <ide> <ide> request.setRequestURI("/foo.xml"); <ide> public void contentNegotiation() throws Exception { <ide> <ide> @Test <ide> public void exceptionResolvers() throws Exception { <del> HandlerExceptionResolverComposite composite = (HandlerExceptionResolverComposite) webConfig.handlerExceptionResolver(); <del> assertEquals(1, composite.getExceptionResolvers().size()); <add> HandlerExceptionResolver exceptionResolver = this.config.handlerExceptionResolver(); <add> assertEquals(1, ((HandlerExceptionResolverComposite) exceptionResolver).getExceptionResolvers().size()); <ide> } <ide> <add> @SuppressWarnings("unchecked") <ide> @Test <ide> public void viewResolvers() throws Exception { <del> ViewResolverComposite viewResolver = webConfig.viewResolverComposite(); <del> assertEquals(Ordered.LOWEST_PRECEDENCE, viewResolver.getOrder()); <add> ViewResolverComposite viewResolver = (ViewResolverComposite) this.config.mvcViewResolver(); <add> assertEquals(Ordered.HIGHEST_PRECEDENCE, viewResolver.getOrder()); <ide> List<ViewResolver> viewResolvers = viewResolver.getViewResolvers(); <del> DirectFieldAccessor viewResolverFieldAccessor = new DirectFieldAccessor(viewResolvers.get(0)); <add> <add> DirectFieldAccessor accessor = new DirectFieldAccessor(viewResolvers.get(0)); <ide> assertEquals(1, viewResolvers.size()); <ide> assertEquals(ContentNegotiatingViewResolver.class, viewResolvers.get(0).getClass()); <del> assertFalse((Boolean)viewResolverFieldAccessor.getPropertyValue("useNotAcceptableStatusCode")); <del> List<View> defaultViews = (List<View>)viewResolverFieldAccessor.getPropertyValue("defaultViews"); <add> assertFalse((Boolean) accessor.getPropertyValue("useNotAcceptableStatusCode")); <add> assertNotNull(accessor.getPropertyValue("contentNegotiationManager")); <add> <add> List<View> defaultViews = (List<View>)accessor.getPropertyValue("defaultViews"); <ide> assertNotNull(defaultViews); <ide> assertEquals(1, defaultViews.size()); <ide> assertEquals(MappingJackson2JsonView.class, defaultViews.get(0).getClass()); <del> assertNotNull(viewResolverFieldAccessor.getPropertyValue("contentNegotiationManager")); <del> viewResolvers = (List<ViewResolver>)viewResolverFieldAccessor.getPropertyValue("viewResolvers"); <add> <add> viewResolvers = (List<ViewResolver>)accessor.getPropertyValue("viewResolvers"); <ide> assertNotNull(viewResolvers); <ide> assertEquals(1, viewResolvers.size()); <ide> assertEquals(InternalResourceViewResolver.class, viewResolvers.get(0).getClass()); <del> viewResolverFieldAccessor = new DirectFieldAccessor(viewResolvers.get(0)); <del> assertEquals("/", viewResolverFieldAccessor.getPropertyValue("prefix")); <del> assertEquals(".jsp", viewResolverFieldAccessor.getPropertyValue("suffix")); <add> accessor = new DirectFieldAccessor(viewResolvers.get(0)); <add> assertEquals("/", accessor.getPropertyValue("prefix")); <add> assertEquals(".jsp", accessor.getPropertyValue("suffix")); <ide> } <ide> <add> <ide> @Controller <ide> private static class TestController { <ide> <ide> public void addViewControllers(ViewControllerRegistry registry) { <ide> } <ide> <ide> @Override <del> public void configureViewResolution(ViewResolutionRegistry registry) { <add> public void configureViewResolvers(ViewResolverRegistry registry) { <add> registry.enableContentNegotiation(new MappingJackson2JsonView()); <ide> registry.jsp("/", ".jsp"); <del> registry.contentNegotiating().useNotAcceptable(false).defaultViews(new MappingJackson2JsonView()); <ide> } <ide> <ide> @Override <ide> public void addResourceHandlers(ResourceHandlerRegistry registry) { <ide> public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { <ide> configurer.enable("default"); <ide> } <del> <ide> } <ide> <ide> private class TestPathHelper extends UrlPathHelper {} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/config/annotation/WebMvcConfigurationSupportTests.java <ide> import org.springframework.web.servlet.HandlerExceptionResolver; <ide> import org.springframework.web.servlet.HandlerExecutionChain; <ide> import org.springframework.web.servlet.ViewResolver; <del>import org.springframework.web.servlet.ViewResolverComposite; <add>import org.springframework.web.servlet.view.ViewResolverComposite; <ide> import org.springframework.web.servlet.handler.AbstractHandlerMapping; <ide> import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping; <ide> import org.springframework.web.servlet.handler.ConversionServiceExposingInterceptor; <ide> public void handlerExceptionResolver() throws Exception { <ide> public void viewResolvers() throws Exception { <ide> ViewResolverComposite compositeResolver = this.wac.getBean(ViewResolverComposite.class); <ide> assertEquals(Ordered.LOWEST_PRECEDENCE, compositeResolver.getOrder()); <del> List<ViewResolver> viewResolvers = compositeResolver.getViewResolvers(); <del> assertEquals(0, viewResolvers.size()); <add> List<ViewResolver> resolvers = compositeResolver.getViewResolvers(); <add> assertEquals(0, resolvers.size()); <ide> } <ide> <ide> @Test
28
Javascript
Javascript
handle normal matrix for instancedmesh
853a1812a8cbc1cea83f54f2861d83e4a7ff112a
<ide><path>src/renderers/shaders/ShaderChunk/defaultnormal_vertex.glsl.js <ide> vec3 transformedNormal = objectNormal; <ide> <ide> #ifdef USE_INSTANCING <ide> <del> transformedNormal = mat3( instanceMatrix ) * transformedNormal; <add> // this is in lieu of a per-instance normal-matrix <add> // shear transforms in the instance matrix are not supported <add> <add> mat3 m = mat3( instanceMatrix ); <add> <add> transformedNormal /= vec3( dot( m[ 0 ], m[ 0 ] ), dot( m[ 1 ], m[ 1 ] ), dot( m[ 2 ], m[ 2 ] ) ); <add> <add> transformedNormal = m * transformedNormal; <ide> <ide> #endif <ide>
1
Javascript
Javascript
specify app-version and build-version
9583c5b2cc48066487e54929bbbba0ceea248a14
<ide><path>build/lib/package-application.js <ide> module.exports = function () { <ide> console.log(`Running electron-packager on ${CONFIG.intermediateAppPath}`) <ide> // https://github.com/electron-userland/electron-packager/blob/master/docs/api.md <ide> electronPackager({ <del> arch: process.arch, <del> asar: {unpack: buildAsarUnpackGlobExpression()}, <del> download: {cache: CONFIG.cachePath}, <del> dir: CONFIG.intermediateAppPath, <del> ignore: buildIgnoredPathsRegExp(), <del> out: CONFIG.buildOutputPath, <del> overwrite: true, <del> platform: process.platform, <del> version: CONFIG.appMetadata.electronVersion <add> 'app-version': CONFIG.appMetadata.version, <add> 'arch': process.arch, <add> 'asar': {unpack: buildAsarUnpackGlobExpression()}, <add> 'build-version': CONFIG.appMetadata.version, <add> 'download': {cache: CONFIG.cachePath}, <add> 'dir': CONFIG.intermediateAppPath, <add> 'ignore': buildIgnoredPathsRegExp(), <add> 'out': CONFIG.buildOutputPath, <add> 'overwrite': true, <add> 'platform': process.platform, <add> 'version': CONFIG.appMetadata.electronVersion <ide> }, (err, appPaths) => { <ide> if (err) { <ide> console.error(err)
1
Javascript
Javascript
remove duplicated code in fromobject
c0bfac6ba9fc48748db3f3558c1d6987013696d8
<ide><path>lib/buffer.js <ide> function fromString(string, encoding) { <ide> return b; <ide> } <ide> <add>function fromArrayLike(obj) { <add> const length = obj.length; <add> const b = allocate(length); <add> for (let i = 0; i < length; i++) <add> b[i] = obj[i] & 255; <add> return b; <add>} <ide> <ide> function fromObject(obj) { <ide> if (obj instanceof Buffer) { <ide> function fromObject(obj) { <ide> return b; <ide> } <ide> <del> if (Array.isArray(obj)) { <del> const length = obj.length; <del> const b = allocate(length); <del> for (let i = 0; i < length; i++) <del> b[i] = obj[i] & 255; <del> return b; <del> } <del> <ide> if (obj == null) { <ide> throw new TypeError('Must start with number, buffer, array or string'); <ide> } <ide> function fromObject(obj) { <ide> return binding.createFromArrayBuffer(obj); <ide> } <ide> <del> if (obj.buffer instanceof ArrayBuffer || obj.length) { <del> let length; <del> if (typeof obj.length !== 'number' || obj.length !== obj.length) <del> length = 0; <del> else <del> length = obj.length; <del> const b = allocate(length); <del> for (let i = 0; i < length; i++) { <del> b[i] = obj[i] & 255; <add> if (obj.buffer instanceof ArrayBuffer || 'length' in obj) { <add> if (typeof obj.length !== 'number' || obj.length !== obj.length) { <add> return allocate(0); <ide> } <del> return b; <add> return fromArrayLike(obj); <ide> } <ide> <ide> if (obj.type === 'Buffer' && Array.isArray(obj.data)) { <del> var array = obj.data; <del> const b = allocate(array.length); <del> for (let i = 0; i < array.length; i++) <del> b[i] = array[i] & 255; <del> return b; <add> return fromArrayLike(obj.data); <ide> } <ide> <ide> throw new TypeError('Must start with number, buffer, array or string'); <ide><path>test/parallel/test-buffer.js <ide> var c = new Buffer(512); <ide> console.log('c.length == %d', c.length); <ide> assert.strictEqual(512, c.length); <ide> <add>var d = new Buffer([]); <add>assert.strictEqual(0, d.length); <add> <add>var ui32 = new Uint32Array(4).fill(42); <add>var e = Buffer(ui32); <add>assert.deepEqual(ui32, e); <add> <ide> // First check Buffer#fill() works as expected. <ide> <ide> assert.throws(function() {
2
Javascript
Javascript
convert `metadata` to use private `class` fields
89785a23f3ad78fb27c6995bdd38c97f01947b2f
<ide><path>src/display/metadata.js <ide> import { objectFromMap } from "../shared/util.js"; <ide> <ide> class Metadata { <add> #metadataMap; <add> <add> #data; <add> <ide> constructor({ parsedData, rawData }) { <del> this._metadataMap = parsedData; <del> this._data = rawData; <add> this.#metadataMap = parsedData; <add> this.#data = rawData; <ide> } <ide> <ide> getRaw() { <del> return this._data; <add> return this.#data; <ide> } <ide> <ide> get(name) { <del> return this._metadataMap.get(name) ?? null; <add> return this.#metadataMap.get(name) ?? null; <ide> } <ide> <ide> getAll() { <del> return objectFromMap(this._metadataMap); <add> return objectFromMap(this.#metadataMap); <ide> } <ide> <ide> has(name) { <del> return this._metadataMap.has(name); <add> return this.#metadataMap.has(name); <ide> } <ide> } <ide>
1
Java
Java
use new features in junit jupiter 5.8.2
a0d54105e99111755489339e34b3cce3e525b8e9
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/ScriptUtilsUnitTests.java <ide> public void readAndSplitScriptContainingMultiLineNestedComments() throws Excepti <ide> } <ide> <ide> @ParameterizedTest <del> @CsvSource(delimiter = '#', value = { <del> // semicolon <del> "'select 1\n select '';''' # ; # false", <del> "'select 1\n select \";\"' # ; # false", <del> "'select 1; select 2' # ; # true", <del> // newline <del> "'select 1; select ''\n''' # '\n' # false", <del> "'select 1; select \"\n\"' # '\n' # false", <del> "'select 1\n select 2' # '\n' # true", <del> // double newline <del> "'select 1\n select 2' # '\n\n' # false", <del> "'select 1\n\n select 2' # '\n\n' # true", <del> // semicolon with MySQL style escapes '\\' <del> "'insert into users(first, last)\nvalues(''a\\\\'', ''b;'')' # ; # false", <del> "'insert into users(first, last)\nvalues(''Charles'', ''d\\''Artagnan''); select 1' # ; # true", <del> // semicolon inside comments <del> "'-- a;b;c\ninsert into colors(color_num) values(42);' # ; # true", <del> "'/* a;b;c */\ninsert into colors(color_num) values(42);' # ; # true", <del> "'-- a;b;c\ninsert into colors(color_num) values(42)' # ; # false", <del> "'/* a;b;c */\ninsert into colors(color_num) values(42)' # ; # false", <del> // single quotes inside comments <del> "'-- What\\''s your favorite color?\ninsert into colors(color_num) values(42);' # ; # true", <del> "'-- What''s your favorite color?\ninsert into colors(color_num) values(42);' # ; # true", <del> "'/* What\\''s your favorite color? */\ninsert into colors(color_num) values(42);' # ; # true", <del> "'/* What''s your favorite color? */\ninsert into colors(color_num) values(42);' # ; # true", <del> // double quotes inside comments <del> "'-- double \" quotes\ninsert into colors(color_num) values(42);' # ; # true", <del> "'-- double \\\" quotes\ninsert into colors(color_num) values(42);' # ; # true", <del> "'/* double \" quotes */\ninsert into colors(color_num) values(42);' # ; # true", <del> "'/* double \\\" quotes */\ninsert into colors(color_num) values(42);' # ; # true" <del> }) <add> @CsvSource(delimiter = '|', quoteCharacter = '~', textBlock = """ <add> # semicolon <add> ~select 1\n select ';'~ | ; | false <add> ~select 1\n select ";"~ | ; | false <add> ~select 1; select 2~ | ; | true <add> <add> # newline <add> ~select 1; select '\n'~ | ~\n~ | false <add> ~select 1; select "\n"~ | ~\n~ | false <add> ~select 1\n select 2~ | ~\n~ | true <add> <add> # double newline <add> ~select 1\n select 2~ | ~\n\n~ | false <add> ~select 1\n\n select 2~ | ~\n\n~ | true <add> <add> # semicolon with MySQL style escapes '\\' <add> ~insert into users(first, last)\n values('a\\\\', 'b;')~ | ; | false <add> ~insert into users(first, last)\n values('Charles', 'd\\'Artagnan'); select 1~ | ; | true <add> <add> # semicolon inside comments <add> ~-- a;b;c\n insert into colors(color_num) values(42);~ | ; | true <add> ~/* a;b;c */\n insert into colors(color_num) values(42);~ | ; | true <add> ~-- a;b;c\n insert into colors(color_num) values(42)~ | ; | false <add> ~/* a;b;c */\n insert into colors(color_num) values(42)~ | ; | false <add> <add> # single quotes inside comments <add> ~-- What\\'s your favorite color?\n insert into colors(color_num) values(42);~ | ; | true <add> ~-- What's your favorite color?\n insert into colors(color_num) values(42);~ | ; | true <add> ~/* What\\'s your favorite color? */\n insert into colors(color_num) values(42);~ | ; | true <add> ~/* What's your favorite color? */\n insert into colors(color_num) values(42);~ | ; | true <add> <add> # double quotes inside comments <add> ~-- double " quotes\n insert into colors(color_num) values(42);~ | ; | true <add> ~-- double \\" quotes\n insert into colors(color_num) values(42);~ | ; | true <add> ~/* double " quotes */\n insert into colors(color_num) values(42);~ | ; | true <add> ~/* double \\" quotes */\n insert into colors(color_num) values(42);~ | ; | true <add> """) <ide> @SuppressWarnings("deprecation") <ide> public void containsStatementSeparator(String script, String delimiter, boolean expected) { <ide> // Indirectly tests ScriptUtils.containsStatementSeparator(EncodedResource, String, String, String[], String, String).
1
Javascript
Javascript
accept function as headers value
a7150f1256f2a97a931b3c0d16eab70f45e81cae
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to <ide> * `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified. <ide> * - **data** – `{string|Object}` – Data to be sent as the request message data. <del> * - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server. <add> * - **headers** – `{Object}` – Map of strings or functions which return strings representing <add> * HTTP headers to send to the server. If the return value of a function is null, the header will <add> * not be sent. <ide> * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token. <ide> * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token. <ide> * - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` – <ide> function $HttpProvider() { <ide> <ide> defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]); <ide> <add> // execute if header value is function <add> execHeaders(defHeaders); <add> execHeaders(reqHeaders); <add> <ide> // using for-in instead of forEach to avoid unecessary iteration after header has been found <ide> defaultHeadersIteration: <ide> for (defHeaderName in defHeaders) { <ide> function $HttpProvider() { <ide> } <ide> <ide> return reqHeaders; <add> <add> function execHeaders(headers) { <add> var headerContent; <add> <add> forEach(headers, function(headerFn, header) { <add> if (isFunction(headerFn)) { <add> headerContent = headerFn(); <add> if (headerContent != null) { <add> headers[header] = headerContent; <add> } else { <add> delete headers[header]; <add> } <add> } <add> }); <add> } <ide> } <ide> } <ide> <ide><path>test/ng/httpSpec.js <ide> describe('$http', function() { <ide> <ide> $httpBackend.flush(); <ide> })); <add> <add> it('should send execute result if header value is function', inject(function() { <add> var headerConfig = {'Accept': function() { return 'Rewritten'; }}; <add> <add> function checkHeaders(headers) { <add> return headers['Accept'] == 'Rewritten'; <add> } <add> <add> $httpBackend.expect('GET', '/url', undefined, checkHeaders).respond(''); <add> $httpBackend.expect('POST', '/url', undefined, checkHeaders).respond(''); <add> $httpBackend.expect('PUT', '/url', undefined, checkHeaders).respond(''); <add> $httpBackend.expect('PATCH', '/url', undefined, checkHeaders).respond(''); <add> $httpBackend.expect('DELETE', '/url', undefined, checkHeaders).respond(''); <add> <add> $http({url: '/url', method: 'GET', headers: headerConfig}); <add> $http({url: '/url', method: 'POST', headers: headerConfig}); <add> $http({url: '/url', method: 'PUT', headers: headerConfig}); <add> $http({url: '/url', method: 'PATCH', headers: headerConfig}); <add> $http({url: '/url', method: 'DELETE', headers: headerConfig}); <add> <add> $httpBackend.flush(); <add> })); <ide> }); <ide> <ide>
2
Javascript
Javascript
add spero for cancer to react native showcase
9023e19dc3489690f37053b39c58985a2a3d8462
<ide><path>website/src/react-native/showcase.js <ide> var apps = [ <ide> link: 'https://itunes.apple.com/us/app/youmeyou/id949540333?mt=8', <ide> author: 'youmeyou, LLC', <ide> }, <add> { <add> name: 'Spero for Cancer', <add> icon: 'https://s3-us-west-1.amazonaws.com/cancerspot/site_images/Spero1024.png', <add> link: 'https://geo.itunes.apple.com/us/app/spero-for-cancer/id1033923573?mt=8', <add> author: 'Spero.io', <add> }, <ide> ]; <ide> <ide> var showcase = React.createClass({
1
PHP
PHP
fix schemacacheshell tests
7718c6376be2db7950a40bd6c8d3242487939f7b
<ide><path>tests/TestCase/Shell/SchemaCacheShellTest.php <ide> namespace Cake\Test\TestCase\Shell; <ide> <ide> use Cake\Cache\Cache; <add>use Cake\Console\ConsoleIo; <ide> use Cake\Console\Exception\StopException; <add>use Cake\Database\SchemaCache; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\Shell\SchemaCacheShell; <ide> use Cake\TestSuite\TestCase; <ide> class SchemaCacheShellTest extends TestCase <ide> */ <ide> public $fixtures = ['core.Articles', 'core.Tags']; <ide> <add> protected $connection; <add> <ide> /** <ide> * setup method <ide> * <ide> class SchemaCacheShellTest extends TestCase <ide> public function setUp(): void <ide> { <ide> parent::setUp(); <del> $this->io = $this->getMockBuilder('Cake\Console\ConsoleIo')->getMock(); <del> $this->shell = new SchemaCacheShell($this->io); <ide> <ide> $this->cache = $this->getMockBuilder('Cake\Cache\CacheEngine')->getMock(); <ide> $this->cache->expects($this->any()) <ide> ->method('init') <ide> ->will($this->returnValue(true)); <ide> Cache::setConfig('orm_cache', $this->cache); <ide> <del> $ds = ConnectionManager::get('test'); <del> $ds->cacheMetadata('orm_cache'); <add> $this->connection = clone ConnectionManager::get('test'); <add> $this->connection->cacheMetadata('orm_cache'); <ide> } <ide> <ide> /** <ide> public function tearDown(): void <ide> parent::tearDown(); <ide> Cache::drop('orm_cache'); <ide> <del> $ds = ConnectionManager::get('test'); <del> $ds->cacheMetadata(false); <add> unset($this->connection); <add> } <add> <add> protected function getShell() <add> { <add> $io = $this->getMockBuilder(ConsoleIo::class)->getMock(); <add> $shell = $this->getMockBuilder(SchemaCacheShell::class) <add> ->setConstructorArgs([$io]) <add> ->setMethods(['_getSchemaCache']) <add> ->getMock(); <add> <add> $schemaCache = new SchemaCache($this->connection); <add> $shell->expects($this->once()) <add> ->method('_getSchemaCache') <add> ->willReturn($schemaCache); <add> <add> return $shell; <ide> } <ide> <ide> /** <ide> public function tearDown(): void <ide> */ <ide> public function testClearEnablesMetadataCache() <ide> { <del> $ds = ConnectionManager::get('test'); <del> $ds->cacheMetadata(false); <add> $this->connection->cacheMetadata(false); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->clear(); <del> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->getSchemaCollection()); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->clear(); <add> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $this->connection->getSchemaCollection()); <ide> } <ide> <ide> /** <ide> public function testClearEnablesMetadataCache() <ide> */ <ide> public function testBuildEnablesMetadataCache() <ide> { <del> $ds = ConnectionManager::get('test'); <del> $ds->cacheMetadata(false); <add> $this->connection->cacheMetadata(false); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->build(); <del> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $ds->getSchemaCollection()); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->build(); <add> $this->assertInstanceOf('Cake\Database\Schema\CachedCollection', $this->connection->getSchemaCollection()); <ide> } <ide> <ide> /** <ide> public function testBuildNoArgs() <ide> ->with('test_articles') <ide> ->will($this->returnValue(true)); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->build(); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->build(); <ide> } <ide> <ide> /** <ide> public function testBuildNamedModel() <ide> ->method('delete') <ide> ->will($this->returnValue(false)); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->build('articles'); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->build('articles'); <ide> } <ide> <ide> /** <ide> public function testBuildOverwritesExistingData() <ide> ->method('delete') <ide> ->will($this->returnValue(false)); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->build('articles'); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->build('articles'); <ide> } <ide> <ide> /** <ide> public function testBuildOverwritesExistingData() <ide> public function testBuildInvalidConnection() <ide> { <ide> $this->expectException(StopException::class); <del> $this->shell->params['connection'] = 'derpy-derp'; <del> $this->shell->build('articles'); <add> <add> $shell = new SchemaCacheShell(new ConsoleIo()); <add> $shell->params['connection'] = 'derpy-derp'; <add> $shell->build('articles'); <ide> } <ide> <ide> /** <ide> public function testBuildInvalidConnection() <ide> public function testClearInvalidConnection() <ide> { <ide> $this->expectException(StopException::class); <del> $this->shell->params['connection'] = 'derpy-derp'; <del> $this->shell->clear('articles'); <add> <add> $shell = new SchemaCacheShell(new ConsoleIo()); <add> $shell->params['connection'] = 'derpy-derp'; <add> $shell->clear('articles'); <ide> } <ide> <ide> /** <ide> public function testClearNoArgs() <ide> ->method('delete') <ide> ->with('test_articles'); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->clear(); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->clear(); <ide> } <ide> <ide> /** <ide> public function testClearNamedModel() <ide> ->with('test_articles') <ide> ->will($this->returnValue(false)); <ide> <del> $this->shell->params['connection'] = 'test'; <del> $this->shell->clear('articles'); <add> $shell = $this->getShell(); <add> $shell->params['connection'] = 'test'; <add> $shell->clear('articles'); <ide> } <ide> }
1
Java
Java
fix scan(seed, f) to emit accumulated values asap
28d13528c8eac75e454f567af6af41c84beb8bae
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java <ide> package io.reactivex.internal.operators.flowable; <ide> <ide> import java.util.concurrent.Callable; <add>import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.BiFunction; <ide> import io.reactivex.internal.functions.ObjectHelper; <del>import io.reactivex.internal.subscribers.SinglePostCompleteSubscriber; <del>import io.reactivex.internal.subscriptions.EmptySubscription; <add>import io.reactivex.internal.fuseable.SimplePlainQueue; <add>import io.reactivex.internal.queue.SpscArrayQueue; <add>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class FlowableScanSeed<T, R> extends AbstractFlowableWithUpstream<T, R> { <ide> protected void subscribeActual(Subscriber<? super R> s) { <ide> return; <ide> } <ide> <del> source.subscribe(new ScanSeedSubscriber<T, R>(s, accumulator, r)); <add> source.subscribe(new ScanSeedSubscriber<T, R>(s, accumulator, r, bufferSize())); <ide> } <ide> <del> static final class ScanSeedSubscriber<T, R> extends SinglePostCompleteSubscriber<T, R> { <add> static final class ScanSeedSubscriber<T, R> <add> extends AtomicInteger <add> implements Subscriber<T>, Subscription { <ide> private static final long serialVersionUID = -1776795561228106469L; <ide> <add> final Subscriber<? super R> actual; <add> <ide> final BiFunction<R, ? super T, R> accumulator; <ide> <del> boolean done; <add> final SimplePlainQueue<R> queue; <add> <add> final AtomicLong requested; <add> <add> final int prefetch; <add> <add> final int limit; <add> <add> volatile boolean cancelled; <add> <add> volatile boolean done; <add> Throwable error; <add> <add> Subscription s; <add> <add> R value; <ide> <del> ScanSeedSubscriber(Subscriber<? super R> actual, BiFunction<R, ? super T, R> accumulator, R value) { <del> super(actual); <add> int consumed; <add> <add> ScanSeedSubscriber(Subscriber<? super R> actual, BiFunction<R, ? super T, R> accumulator, R value, int prefetch) { <add> this.actual = actual; <ide> this.accumulator = accumulator; <ide> this.value = value; <add> this.prefetch = prefetch; <add> this.limit = prefetch - (prefetch >> 2); <add> this.queue = new SpscArrayQueue<R>(prefetch); <add> this.queue.offer(value); <add> this.requested = new AtomicLong(); <add> } <add> <add> @Override <add> public void onSubscribe(Subscription s) { <add> if (SubscriptionHelper.validate(this.s, s)) { <add> this.s = s; <add> <add> actual.onSubscribe(this); <add> <add> s.request(prefetch - 1); <add> } <ide> } <ide> <ide> @Override <ide> public void onNext(T t) { <ide> } <ide> <ide> R v = value; <del> <del> R u; <del> <ide> try { <del> u = ObjectHelper.requireNonNull(accumulator.apply(v, t), "The accumulator returned a null value"); <del> } catch (Throwable e) { <del> Exceptions.throwIfFatal(e); <add> v = ObjectHelper.requireNonNull(accumulator.apply(v, t), "The accumulator returned a null value"); <add> } catch (Throwable ex) { <add> Exceptions.throwIfFatal(ex); <ide> s.cancel(); <del> onError(e); <add> onError(ex); <ide> return; <ide> } <ide> <del> value = u; <del> produced++; <del> actual.onNext(v); <add> value = v; <add> queue.offer(v); <add> drain(); <ide> } <ide> <ide> @Override <ide> public void onError(Throwable t) { <ide> RxJavaPlugins.onError(t); <ide> return; <ide> } <add> error = t; <ide> done = true; <del> value = null; <del> actual.onError(t); <add> drain(); <ide> } <ide> <ide> @Override <ide> public void onComplete() { <ide> return; <ide> } <ide> done = true; <del> complete(value); <add> drain(); <add> } <add> <add> @Override <add> public void cancel() { <add> cancelled = true; <add> s.cancel(); <add> if (getAndIncrement() == 0) { <add> queue.clear(); <add> } <add> } <add> <add> @Override <add> public void request(long n) { <add> if (SubscriptionHelper.validate(n)) { <add> BackpressureHelper.add(requested, n); <add> drain(); <add> } <add> } <add> <add> void drain() { <add> if (getAndIncrement() != 0) { <add> return; <add> } <add> <add> int missed = 1; <add> Subscriber<? super R> a = actual; <add> SimplePlainQueue<R> q = queue; <add> int lim = limit; <add> int c = consumed; <add> <add> for (;;) { <add> <add> long r = requested.get(); <add> long e = 0L; <add> <add> while (e != r) { <add> if (cancelled) { <add> q.clear(); <add> return; <add> } <add> boolean d = done; <add> <add> if (d) { <add> Throwable ex = error; <add> if (ex != null) { <add> q.clear(); <add> a.onError(ex); <add> return; <add> } <add> } <add> <add> R v = q.poll(); <add> boolean empty = v == null; <add> <add> if (d && empty) { <add> a.onComplete(); <add> return; <add> } <add> <add> if (empty) { <add> break; <add> } <add> <add> a.onNext(v); <add> <add> e++; <add> if (++c == lim) { <add> c = 0; <add> s.request(lim); <add> } <add> } <add> <add> if (e == r) { <add> if (done) { <add> Throwable ex = error; <add> if (ex != null) { <add> q.clear(); <add> a.onError(ex); <add> return; <add> } <add> if (q.isEmpty()) { <add> a.onComplete(); <add> return; <add> } <add> } <add> } <add> <add> if (e != 0L) { <add> BackpressureHelper.produced(requested, e); <add> } <add> <add> consumed = c; <add> missed = addAndGet(-missed); <add> if (missed == 0) { <add> break; <add> } <add> } <ide> } <ide> } <ide> } <ide><path>src/test/java/io/reactivex/flowable/FlowableScanTests.java <del>/** <del> * Copyright (c) 2016-present, RxJava Contributors. <del> * <del> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <del> * compliance with the License. You may obtain a copy of the License at <del> * <del> * http://www.apache.org/licenses/LICENSE-2.0 <del> * <del> * Unless required by applicable law or agreed to in writing, software distributed under the License is <del> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <del> * the License for the specific language governing permissions and limitations under the License. <del> */ <del> <del>package io.reactivex.flowable; <del> <del>import static org.junit.Assert.*; <del> <del>import java.util.*; <del>import java.util.concurrent.*; <del>import java.util.concurrent.atomic.AtomicInteger; <del> <del>import org.junit.Test; <del> <del>import io.reactivex.*; <del>import io.reactivex.exceptions.UndeliverableException; <del>import io.reactivex.flowable.FlowableEventStream.Event; <del>import io.reactivex.functions.*; <del>import io.reactivex.plugins.RxJavaPlugins; <del> <del>public class FlowableScanTests { <del> <del> @Test <del> public void testUnsubscribeScan() { <del> <del> FlowableEventStream.getEventStream("HTTP-ClusterB", 20) <del> .scan(new HashMap<String, String>(), new BiFunction<HashMap<String, String>, Event, HashMap<String, String>>() { <del> @Override <del> public HashMap<String, String> apply(HashMap<String, String> accum, Event perInstanceEvent) { <del> accum.put("instance", perInstanceEvent.instanceId); <del> return accum; <del> } <del> }) <del> .take(10) <del> .blockingForEach(new Consumer<HashMap<String, String>>() { <del> @Override <del> public void accept(HashMap<String, String> v) { <del> System.out.println(v); <del> } <del> }); <del> } <del> <del> @Test <del> public void testScanWithSeedDoesNotEmitErrorTwiceIfScanFunctionThrows() { <del> final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); <del> Consumer<Throwable> errorConsumer = new Consumer<Throwable>() { <del> @Override <del> public void accept(Throwable t) throws Exception { <del> list.add(t); <del> }}; <del> try { <del> RxJavaPlugins.setErrorHandler(errorConsumer); <del> final RuntimeException e = new RuntimeException(); <del> final RuntimeException e2 = new RuntimeException(); <del> Burst.items(1).error(e2) <del> .scan(0, throwingBiFunction(e)) <del> .test() <del> .assertNoValues() <del> .assertError(e); <del> <del> assertEquals("" + list, 1, list.size()); <del> assertTrue("" + list, list.get(0) instanceof UndeliverableException); <del> assertEquals(e2, list.get(0).getCause()); <del> } finally { <del> RxJavaPlugins.reset(); <del> } <del> } <del> <del> @Test <del> public void testScanWithSeedDoesNotEmitTerminalEventTwiceIfScanFunctionThrows() { <del> final RuntimeException e = new RuntimeException(); <del> Burst.item(1).create() <del> .scan(0, throwingBiFunction(e)) <del> .test() <del> .assertNoValues() <del> .assertError(e); <del> } <del> <del> @Test <del> public void testScanWithSeedDoesNotProcessOnNextAfterTerminalEventIfScanFunctionThrows() { <del> final RuntimeException e = new RuntimeException(); <del> final AtomicInteger count = new AtomicInteger(); <del> Burst.items(1, 2).create().scan(0, new BiFunction<Integer, Integer, Integer>() { <del> <del> @Override <del> public Integer apply(Integer n1, Integer n2) throws Exception { <del> count.incrementAndGet(); <del> throw e; <del> }}) <del> .test() <del> .assertNoValues() <del> .assertError(e); <del> assertEquals(1, count.get()); <del> } <del> <del> @Test <del> public void testScanWithSeedCompletesNormally() { <del> Flowable.just(1,2,3).scan(0, SUM) <del> .test() <del> .assertValues(0, 1, 3, 6) <del> .assertComplete(); <del> } <del> <del> @Test <del> public void testScanWithSeedWhenScanSeedProviderThrows() { <del> final RuntimeException e = new RuntimeException(); <del> Flowable.just(1,2,3).scanWith(throwingCallable(e), <del> SUM) <del> .test() <del> .assertError(e) <del> .assertNoValues(); <del> } <del> <del> @Test <del> public void testScanNoSeed() { <del> Flowable.just(1, 2, 3) <del> .scan(SUM) <del> .test() <del> .assertValues(1, 3, 6) <del> .assertComplete(); <del> } <del> <del> @Test <del> public void testScanNoSeedDoesNotEmitErrorTwiceIfScanFunctionThrows() { <del> final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); <del> Consumer<Throwable> errorConsumer = new Consumer<Throwable>() { <del> @Override <del> public void accept(Throwable t) throws Exception { <del> list.add(t); <del> }}; <del> try { <del> RxJavaPlugins.setErrorHandler(errorConsumer); <del> final RuntimeException e = new RuntimeException(); <del> final RuntimeException e2 = new RuntimeException(); <del> Burst.items(1, 2).error(e2) <del> .scan(throwingBiFunction(e)) <del> .test() <del> .assertValue(1) <del> .assertError(e); <del> <del> assertEquals("" + list, 1, list.size()); <del> assertTrue("" + list, list.get(0) instanceof UndeliverableException); <del> assertEquals(e2, list.get(0).getCause()); <del> } finally { <del> RxJavaPlugins.reset(); <del> } <del> } <del> <del> @Test <del> public void testScanNoSeedDoesNotEmitTerminalEventTwiceIfScanFunctionThrows() { <del> final RuntimeException e = new RuntimeException(); <del> Burst.items(1, 2).create() <del> .scan(throwingBiFunction(e)) <del> .test() <del> .assertValue(1) <del> .assertError(e); <del> } <del> <del> @Test <del> public void testScanNoSeedDoesNotProcessOnNextAfterTerminalEventIfScanFunctionThrows() { <del> final RuntimeException e = new RuntimeException(); <del> final AtomicInteger count = new AtomicInteger(); <del> Burst.items(1, 2, 3).create().scan(new BiFunction<Integer, Integer, Integer>() { <del> <del> @Override <del> public Integer apply(Integer n1, Integer n2) throws Exception { <del> count.incrementAndGet(); <del> throw e; <del> }}) <del> .test() <del> .assertValue(1) <del> .assertError(e); <del> assertEquals(1, count.get()); <del> } <del> <del> private static BiFunction<Integer,Integer, Integer> throwingBiFunction(final RuntimeException e) { <del> return new BiFunction<Integer, Integer, Integer>() { <del> @Override <del> public Integer apply(Integer n1, Integer n2) throws Exception { <del> throw e; <del> } <del> }; <del> } <del> <del> private static final BiFunction<Integer, Integer, Integer> SUM = new BiFunction<Integer, Integer, Integer>() { <del> <del> @Override <del> public Integer apply(Integer t1, Integer t2) throws Exception { <del> return t1 + t2; <del> } <del> }; <del> <del> private static Callable<Integer> throwingCallable(final RuntimeException e) { <del> return new Callable<Integer>() { <del> @Override <del> public Integer call() throws Exception { <del> throw e; <del> } <del> }; <del> } <del>} <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableScanTest.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.*; <ide> import static org.mockito.Mockito.*; <ide> <ide> import java.util.*; <del>import java.util.concurrent.Callable; <add>import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.junit.*; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.Flowable; <del>import io.reactivex.exceptions.TestException; <add>import io.reactivex.exceptions.*; <add>import io.reactivex.flowable.*; <add>import io.reactivex.flowable.FlowableEventStream.Event; <ide> import io.reactivex.functions.*; <add>import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.subscribers.*; <ide> <ide> public void onNext(Integer integer) { <ide> }); <ide> <ide> verify(producer.get(), never()).request(0); <del> verify(producer.get(), times(2)).request(1); <add> verify(producer.get(), times(1)).request(Flowable.bufferSize() - 1); <ide> } <ide> <ide> @Test <ide> public Object apply(Object a, Object b) throws Exception { <ide> .test() <ide> .assertFailure(TestException.class); <ide> } <add> <add> @Test <add> public void neverSource() { <add> Flowable.<Integer>never() <add> .scan(0, new BiFunction<Integer, Integer, Integer>() { <add> @Override <add> public Integer apply(Integer a, Integer b) throws Exception { <add> return a + b; <add> } <add> }) <add> .test() <add> .assertValue(0) <add> .assertNoErrors() <add> .assertNotComplete(); <add> } <add> <add> @Test <add> public void testUnsubscribeScan() { <add> <add> FlowableEventStream.getEventStream("HTTP-ClusterB", 20) <add> .scan(new HashMap<String, String>(), new BiFunction<HashMap<String, String>, Event, HashMap<String, String>>() { <add> @Override <add> public HashMap<String, String> apply(HashMap<String, String> accum, Event perInstanceEvent) { <add> accum.put("instance", perInstanceEvent.instanceId); <add> return accum; <add> } <add> }) <add> .take(10) <add> .blockingForEach(new Consumer<HashMap<String, String>>() { <add> @Override <add> public void accept(HashMap<String, String> v) { <add> System.out.println(v); <add> } <add> }); <add> } <add> <add> @Test <add> public void testScanWithSeedDoesNotEmitErrorTwiceIfScanFunctionThrows() { <add> final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); <add> Consumer<Throwable> errorConsumer = new Consumer<Throwable>() { <add> @Override <add> public void accept(Throwable t) throws Exception { <add> list.add(t); <add> }}; <add> try { <add> RxJavaPlugins.setErrorHandler(errorConsumer); <add> final RuntimeException e = new RuntimeException(); <add> final RuntimeException e2 = new RuntimeException(); <add> Burst.items(1).error(e2) <add> .scan(0, throwingBiFunction(e)) <add> .test() <add> .assertValues(0) <add> .assertError(e); <add> <add> assertEquals("" + list, 1, list.size()); <add> assertTrue("" + list, list.get(0) instanceof UndeliverableException); <add> assertEquals(e2, list.get(0).getCause()); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void testScanWithSeedDoesNotEmitTerminalEventTwiceIfScanFunctionThrows() { <add> final RuntimeException e = new RuntimeException(); <add> Burst.item(1).create() <add> .scan(0, throwingBiFunction(e)) <add> .test() <add> .assertValue(0) <add> .assertError(e); <add> } <add> <add> @Test <add> public void testScanWithSeedDoesNotProcessOnNextAfterTerminalEventIfScanFunctionThrows() { <add> final RuntimeException e = new RuntimeException(); <add> final AtomicInteger count = new AtomicInteger(); <add> Burst.items(1, 2).create().scan(0, new BiFunction<Integer, Integer, Integer>() { <add> <add> @Override <add> public Integer apply(Integer n1, Integer n2) throws Exception { <add> count.incrementAndGet(); <add> throw e; <add> }}) <add> .test() <add> .assertValues(0) <add> .assertError(e); <add> assertEquals(1, count.get()); <add> } <add> <add> @Test <add> public void testScanWithSeedCompletesNormally() { <add> Flowable.just(1,2,3).scan(0, SUM) <add> .test() <add> .assertValues(0, 1, 3, 6) <add> .assertComplete(); <add> } <add> <add> @Test <add> public void testScanWithSeedWhenScanSeedProviderThrows() { <add> final RuntimeException e = new RuntimeException(); <add> Flowable.just(1,2,3).scanWith(throwingCallable(e), <add> SUM) <add> .test() <add> .assertError(e) <add> .assertNoValues(); <add> } <add> <add> @Test <add> public void testScanNoSeed() { <add> Flowable.just(1, 2, 3) <add> .scan(SUM) <add> .test() <add> .assertValues(1, 3, 6) <add> .assertComplete(); <add> } <add> <add> @Test <add> public void testScanNoSeedDoesNotEmitErrorTwiceIfScanFunctionThrows() { <add> final List<Throwable> list = new CopyOnWriteArrayList<Throwable>(); <add> Consumer<Throwable> errorConsumer = new Consumer<Throwable>() { <add> @Override <add> public void accept(Throwable t) throws Exception { <add> list.add(t); <add> }}; <add> try { <add> RxJavaPlugins.setErrorHandler(errorConsumer); <add> final RuntimeException e = new RuntimeException(); <add> final RuntimeException e2 = new RuntimeException(); <add> Burst.items(1, 2).error(e2) <add> .scan(throwingBiFunction(e)) <add> .test() <add> .assertValue(1) <add> .assertError(e); <add> <add> assertEquals("" + list, 1, list.size()); <add> assertTrue("" + list, list.get(0) instanceof UndeliverableException); <add> assertEquals(e2, list.get(0).getCause()); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> @Test <add> public void testScanNoSeedDoesNotEmitTerminalEventTwiceIfScanFunctionThrows() { <add> final RuntimeException e = new RuntimeException(); <add> Burst.items(1, 2).create() <add> .scan(throwingBiFunction(e)) <add> .test() <add> .assertValue(1) <add> .assertError(e); <add> } <add> <add> @Test <add> public void testScanNoSeedDoesNotProcessOnNextAfterTerminalEventIfScanFunctionThrows() { <add> final RuntimeException e = new RuntimeException(); <add> final AtomicInteger count = new AtomicInteger(); <add> Burst.items(1, 2, 3).create().scan(new BiFunction<Integer, Integer, Integer>() { <add> <add> @Override <add> public Integer apply(Integer n1, Integer n2) throws Exception { <add> count.incrementAndGet(); <add> throw e; <add> }}) <add> .test() <add> .assertValue(1) <add> .assertError(e); <add> assertEquals(1, count.get()); <add> } <add> <add> private static BiFunction<Integer,Integer, Integer> throwingBiFunction(final RuntimeException e) { <add> return new BiFunction<Integer, Integer, Integer>() { <add> @Override <add> public Integer apply(Integer n1, Integer n2) throws Exception { <add> throw e; <add> } <add> }; <add> } <add> <add> private static final BiFunction<Integer, Integer, Integer> SUM = new BiFunction<Integer, Integer, Integer>() { <add> <add> @Override <add> public Integer apply(Integer t1, Integer t2) throws Exception { <add> return t1 + t2; <add> } <add> }; <add> <add> private static Callable<Integer> throwingCallable(final RuntimeException e) { <add> return new Callable<Integer>() { <add> @Override <add> public Integer call() throws Exception { <add> throw e; <add> } <add> }; <add> } <add> <add> @Test <add> public void scanEmptyBackpressured() { <add> Flowable.<Integer>empty() <add> .scan(0, SUM) <add> .test(1) <add> .assertResult(0); <add> } <add> <add> @Test <add> public void scanErrorBackpressured() { <add> Flowable.<Integer>error(new TestException()) <add> .scan(0, SUM) <add> .test(0) <add> .assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void scanTake() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>() { <add> @Override <add> public void onNext(Integer t) { <add> super.onNext(t); <add> onComplete(); <add> cancel(); <add> } <add> }; <add> <add> Flowable.range(1, 10) <add> .scan(0, SUM) <add> .subscribe(ts) <add> ; <add> <add> ts.assertResult(0); <add> } <add> <add> @Test <add> public void scanLong() { <add> int n = 2 * Flowable.bufferSize(); <add> <add> for (int b = 1; b <= n; b *= 2) { <add> List<Integer> list = Flowable.range(1, n) <add> .scan(0, new BiFunction<Integer, Integer, Integer>() { <add> @Override <add> public Integer apply(Integer a, Integer b) throws Exception { <add> return b; <add> } <add> }) <add> .rebatchRequests(b) <add> .toList() <add> .blockingGet(); <add> <add> for (int i = 0; i <= n; i++) { <add> assertEquals(i, list.get(i).intValue()); <add> } <add> } <add> } <ide> }
3
Python
Python
fix external elasticsearch logs link
e31e515b28a745b7428b42f1559ab456305fb3a0
<ide><path>airflow/providers/elasticsearch/log/es_task_handler.py <ide> from airflow.utils.helpers import parse_template_string <ide> from airflow.utils.log.file_task_handler import FileTaskHandler <ide> from airflow.utils.log.json_formatter import JSONFormatter <del>from airflow.utils.log.logging_mixin import LoggingMixin <add>from airflow.utils.log.logging_mixin import ExternalLoggingMixin, LoggingMixin <ide> <ide> # Elasticsearch hosted log type <ide> EsLogMsgType = List[Tuple[str, str]] <ide> <ide> <del>class ElasticsearchTaskHandler(FileTaskHandler, LoggingMixin): <add>class ElasticsearchTaskHandler(FileTaskHandler, ExternalLoggingMixin, LoggingMixin): <ide> """ <ide> ElasticsearchTaskHandler is a python log handler that <ide> reads logs from Elasticsearch. Note logs are not directly <ide> def get_external_log_url(self, task_instance: TaskInstance, try_number: int) -> <ide> url = 'https://' + self.frontend.format(log_id=quote(log_id)) <ide> return url <ide> <add> @property <add> def supports_external_link(self) -> bool: <add> """Whether we can support external links""" <add> return bool(self.frontend) <add> <ide> <ide> class _ESJsonLogFmt: <ide> """Helper class to read ES Logs and re-format it to match settings.LOG_FORMAT""" <ide><path>airflow/utils/log/log_reader.py <ide> def supports_read(self): <ide> return hasattr(self.log_handler, 'read') <ide> <ide> @property <del> def supports_external_link(self): <add> def supports_external_link(self) -> bool: <ide> """Check if the logging handler supports external links (e.g. to Elasticsearch, Stackdriver, etc).""" <del> return isinstance(self.log_handler, ExternalLoggingMixin) <add> if not isinstance(self.log_handler, ExternalLoggingMixin): <add> return False <add> <add> return self.log_handler.supports_external_link <ide> <ide> def render_log_filename(self, ti: TaskInstance, try_number: Optional[int] = None): <ide> """ <ide><path>airflow/utils/log/logging_mixin.py <ide> def log_name(self) -> str: <ide> def get_external_log_url(self, task_instance, try_number) -> str: <ide> """Return the URL for log visualization in the external service.""" <ide> <add> @property <add> @abc.abstractmethod <add> def supports_external_link(self) -> bool: <add> """Return whether handler is able to support external links.""" <add> <ide> <ide> # TODO: Formally inherit from io.IOBase <ide> class StreamLogWriter: <ide><path>tests/providers/elasticsearch/log/test_es_task_handler.py <ide> def test_get_external_log_url(self, es_frontend, expected_url): <ide> ) <ide> url = es_task_handler.get_external_log_url(self.ti, self.ti.try_number) <ide> assert expected_url == url <add> <add> @parameterized.expand( <add> [ <add> ('localhost:5601/{log_id}', True), <add> (None, False), <add> ] <add> ) <add> def test_supports_external_link(self, frontend, expected): <add> self.es_task_handler.frontend = frontend <add> assert self.es_task_handler.supports_external_link == expected <ide><path>tests/utils/log/test_log_reader.py <ide> from airflow.operators.dummy import DummyOperator <ide> from airflow.utils import timezone <ide> from airflow.utils.log.log_reader import TaskLogReader <add>from airflow.utils.log.logging_mixin import ExternalLoggingMixin <ide> from airflow.utils.session import create_session <ide> from tests.test_utils.config import conf_vars <ide> from tests.test_utils.db import clear_db_runs <ide> def test_read_log_stream_should_read_each_try_in_turn(self, mock_read): <ide> ], <ide> any_order=False, <ide> ) <add> <add> def test_supports_external_link(self): <add> task_log_reader = TaskLogReader() <add> <add> # Short circuit if log_handler doesn't include ExternalLoggingMixin <add> task_log_reader.log_handler = mock.MagicMock() <add> mock_prop = mock.PropertyMock() <add> mock_prop.return_value = False <add> type(task_log_reader.log_handler).supports_external_link = mock_prop <add> assert not task_log_reader.supports_external_link <add> mock_prop.assert_not_called() <add> <add> # Otherwise, defer to the log_handlers supports_external_link <add> task_log_reader.log_handler = mock.MagicMock(spec=ExternalLoggingMixin) <add> type(task_log_reader.log_handler).supports_external_link = mock_prop <add> assert not task_log_reader.supports_external_link <add> mock_prop.assert_called_once() <add> <add> mock_prop.return_value = True <add> assert task_log_reader.supports_external_link <ide><path>tests/www/views/test_views_log.py <ide> def test_redirect_to_external_log_with_local_log_handler(log_admin_client, task_ <ide> assert 'http://localhost/home' == response.headers['Location'] <ide> <ide> <del>class ExternalHandler(ExternalLoggingMixin): <add>class _ExternalHandler(ExternalLoggingMixin): <ide> EXTERNAL_URL = 'http://external-service.com' <ide> <del> def get_external_log_url(self, *args, **kwargs): <add> @property <add> def log_name(self) -> str: <add> return 'ExternalLog' <add> <add> def get_external_log_url(self, *args, **kwargs) -> str: <ide> return self.EXTERNAL_URL <ide> <add> @property <add> def supports_external_link(self) -> bool: <add> return True <add> <ide> <ide> @unittest.mock.patch( <ide> 'airflow.utils.log.log_reader.TaskLogReader.log_handler', <ide> new_callable=unittest.mock.PropertyMock, <del> return_value=ExternalHandler(), <add> return_value=_ExternalHandler(), <ide> ) <ide> def test_redirect_to_external_log_with_external_log_handler(_, log_admin_client): <ide> url_template = "redirect_to_external_log?dag_id={}&task_id={}&execution_date={}&try_number={}" <ide> def test_redirect_to_external_log_with_external_log_handler(_, log_admin_client) <ide> ) <ide> response = log_admin_client.get(url) <ide> assert 302 == response.status_code <del> assert ExternalHandler.EXTERNAL_URL == response.headers['Location'] <add> assert _ExternalHandler.EXTERNAL_URL == response.headers['Location'] <ide><path>tests/www/views/test_views_tasks.py <ide> def test_show_external_log_redirect_link_with_local_log_handler(capture_template <ide> <ide> <ide> class _ExternalHandler(ExternalLoggingMixin): <add> _supports_external_link = True <ide> LOG_NAME = 'ExternalLog' <ide> <ide> @property <del> def log_name(self): <add> def log_name(self) -> str: <ide> return self.LOG_NAME <ide> <add> def get_external_log_url(self, *args, **kwargs) -> str: <add> return 'http://external-service.com' <add> <add> @property <add> def supports_external_link(self) -> bool: <add> return self._supports_external_link <add> <ide> <ide> @pytest.mark.parametrize("endpoint", ["graph", "tree"]) <ide> @unittest.mock.patch( <ide> def test_show_external_log_redirect_link_with_external_log_handler( <ide> assert ctx['external_log_name'] == _ExternalHandler.LOG_NAME <ide> <ide> <add>@pytest.mark.parametrize("endpoint", ["graph", "tree"]) <add>@unittest.mock.patch( <add> 'airflow.utils.log.log_reader.TaskLogReader.log_handler', <add> new_callable=unittest.mock.PropertyMock, <add> return_value=_ExternalHandler(), <add>) <add>def test_external_log_redirect_link_with_external_log_handler_not_shown( <add> _external_handler, capture_templates, admin_client, endpoint <add>): <add> """Show external links if log handler is external.""" <add> _external_handler.return_value._supports_external_link = False <add> url = f'{endpoint}?dag_id=example_bash_operator' <add> with capture_templates() as templates: <add> admin_client.get(url, follow_redirects=True) <add> ctx = templates[0].local_context <add> assert not ctx['show_external_log_redirect'] <add> assert ctx['external_log_name'] is None <add> <add> <ide> def _get_appbuilder_pk_string(model_view_cls, instance) -> str: <ide> """Utility to get Flask-Appbuilder's string format "pk" for an object. <ide>
7
Ruby
Ruby
fix the next version of rails from 5.3 to 6.0
1d264f0bcd5081dcb4e5049a8124706f7623e63b
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def count(column_name = nil) <ide> unless column_name.nil? <ide> ActiveSupport::Deprecation.warn \ <ide> "When `count' is called with a block, it ignores other arguments. " \ <del> "This behavior is now deprecated and will result in an ArgumentError in Rails 5.3." <add> "This behavior is now deprecated and will result in an ArgumentError in Rails 6.0." <ide> end <ide> <ide> return super() <ide> def sum(column_name = nil) <ide> unless column_name.nil? <ide> ActiveSupport::Deprecation.warn \ <ide> "When `sum' is called with a block, it ignores other arguments. " \ <del> "This behavior is now deprecated and will result in an ArgumentError in Rails 5.3." <add> "This behavior is now deprecated and will result in an ArgumentError in Rails 6.0." <ide> end <ide> <ide> return super()
1
Javascript
Javascript
fix data loss with readable event
12274a5c1b0a85f6f8eaf3f6e5c78b1de7617dfc
<ide><path>lib/internal/child_process.js <ide> util.inherits(ChildProcess, EventEmitter); <ide> function flushStdio(subprocess) { <ide> if (subprocess.stdio == null) return; <ide> subprocess.stdio.forEach(function(stream, fd, stdio) { <del> if (!stream || !stream.readable) <add> if (!stream || !stream.readable || stream._readableState.readableListening) <ide> return; <ide> stream.resume(); <ide> }); <ide><path>test/parallel/test-child-process-flush-stdio.js <ide> const p = cp.spawn('echo'); <ide> p.on('close', common.mustCall(function(code, signal) { <ide> assert.strictEqual(code, 0); <ide> assert.strictEqual(signal, null); <add> spawnWithReadable(); <ide> })); <ide> <ide> p.stdout.read(); <ide> <del>setTimeout(function() { <del> p.kill(); <del>}, 100); <add>function spawnWithReadable() { <add> const buffer = []; <add> const p = cp.spawn('echo', ['123']); <add> p.on('close', common.mustCall(function(code, signal) { <add> assert.strictEqual(code, 0); <add> assert.strictEqual(signal, null); <add> assert.strictEqual(Buffer.concat(buffer).toString().trim(), '123'); <add> })); <add> p.stdout.on('readable', function() { <add> let buf; <add> while (buf = this.read()) <add> buffer.push(buf); <add> }); <add>}
2
Ruby
Ruby
remove unused variable
1308070e66b3b4dbf979eceb2f374d3a3a81bb5d
<ide><path>Library/Homebrew/cmd/pull.rb <ide> def pull <ide> begin <ide> changed_formulae << Formula[name] <ide> # Make sure we catch syntax errors. <del> rescue Exception => e <add> rescue Exception <ide> next <ide> end <ide> end
1
Go
Go
send archive options via pipe in chrootarchive
908db51804635ce002e97e4efb867f7352204f8e
<ide><path>pkg/chrootarchive/archive.go <ide> package chrootarchive <ide> <ide> import ( <add> "bytes" <ide> "encoding/json" <ide> "flag" <ide> "fmt" <ide> func untar() { <ide> <ide> var options *archive.TarOptions <ide> <del> if err := json.Unmarshal([]byte(os.Getenv("OPT")), &options); err != nil { <add> //read the options from the pipe "ExtraFiles" <add> if err := json.NewDecoder(os.NewFile(3, "options")).Decode(&options); err != nil { <ide> fatal(err) <ide> } <ide> <ide> func Untar(tarArchive io.Reader, dest string, options *archive.TarOptions) error <ide> } <ide> } <ide> <del> // We can't pass the exclude list directly via cmd line <del> // because we easily overrun the shell max argument list length <del> // when the full image list is passed (e.g. when this is used <del> // by `docker load`). Instead we will add the JSON marshalled <del> // and placed in the env, which has significantly larger <del> // max size <del> data, err := json.Marshal(options) <del> if err != nil { <del> return fmt.Errorf("Untar json encode: %v", err) <del> } <ide> decompressedArchive, err := archive.DecompressStream(tarArchive) <ide> if err != nil { <ide> return err <ide> } <ide> defer decompressedArchive.Close() <ide> <add> // We can't pass a potentially large exclude list directly via cmd line <add> // because we easily overrun the kernel's max argument/environment size <add> // when the full image list is passed (e.g. when this is used by <add> // `docker load`). We will marshall the options via a pipe to the <add> // child <add> r, w, err := os.Pipe() <add> if err != nil { <add> return fmt.Errorf("Untar pipe failure: %v", err) <add> } <ide> cmd := reexec.Command("docker-untar", dest) <ide> cmd.Stdin = decompressedArchive <del> cmd.Env = append(cmd.Env, fmt.Sprintf("OPT=%s", data)) <del> out, err := cmd.CombinedOutput() <del> if err != nil { <del> return fmt.Errorf("Untar %s %s", err, out) <add> cmd.ExtraFiles = append(cmd.ExtraFiles, r) <add> var output bytes.Buffer <add> cmd.Stdout = &output <add> cmd.Stderr = &output <add> <add> if err := cmd.Start(); err != nil { <add> return fmt.Errorf("Untar error on re-exec cmd: %v", err) <add> } <add> //write the options to the pipe for the untar exec to read <add> if err := json.NewEncoder(w).Encode(options); err != nil { <add> return fmt.Errorf("Untar json encode to pipe failed: %v", err) <add> } <add> w.Close() <add> <add> if err := cmd.Wait(); err != nil { <add> return fmt.Errorf("Untar re-exec error: %v: output: %s", err, output) <ide> } <ide> return nil <ide> } <ide><path>pkg/chrootarchive/archive_test.go <ide> import ( <ide> "os" <ide> "path" <ide> "path/filepath" <add> "strings" <ide> "testing" <ide> "time" <ide> <ide> func TestChrootTarUntar(t *testing.T) { <ide> } <ide> } <ide> <add>// gh#10426: Verify the fix for having a huge excludes list (like on `docker load` with large # of <add>// local images) <add>func TestChrootUntarWithHugeExcludesList(t *testing.T) { <add> tmpdir, err := ioutil.TempDir("", "docker-TestChrootUntarHugeExcludes") <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer os.RemoveAll(tmpdir) <add> src := filepath.Join(tmpdir, "src") <add> if err := os.MkdirAll(src, 0700); err != nil { <add> t.Fatal(err) <add> } <add> if err := ioutil.WriteFile(filepath.Join(src, "toto"), []byte("hello toto"), 0644); err != nil { <add> t.Fatal(err) <add> } <add> stream, err := archive.Tar(src, archive.Uncompressed) <add> if err != nil { <add> t.Fatal(err) <add> } <add> dest := filepath.Join(tmpdir, "dest") <add> if err := os.MkdirAll(dest, 0700); err != nil { <add> t.Fatal(err) <add> } <add> options := &archive.TarOptions{} <add> //65534 entries of 64-byte strings ~= 4MB of environment space which should overflow <add> //on most systems when passed via environment or command line arguments <add> excludes := make([]string, 65534, 65534) <add> for i := 0; i < 65534; i++ { <add> excludes[i] = strings.Repeat(string(i), 64) <add> } <add> options.ExcludePatterns = excludes <add> if err := Untar(stream, dest, options); err != nil { <add> t.Fatal(err) <add> } <add>} <add> <ide> func TestChrootUntarEmptyArchive(t *testing.T) { <ide> tmpdir, err := ioutil.TempDir("", "docker-TestChrootUntarEmptyArchive") <ide> if err != nil {
2
Ruby
Ruby
use more and cleanup new args apis
a7fe0ed8472a67362793059cf633d3030ffa11d9
<ide><path>Library/Homebrew/cmd/--cache.rb <ide> def __cache_args <ide> def __cache <ide> __cache_args.parse <ide> <del> if ARGV.named.empty? <add> if args.no_named? <ide> puts HOMEBREW_CACHE <ide> else <del> Homebrew.args.formulae.each do |f| <add> args.formulae.each do |f| <ide> if Fetch.fetch_bottle?(f) <ide> puts f.bottle.cached_download <ide> else <ide><path>Library/Homebrew/cmd/--cellar.rb <ide> def __cellar_args <ide> def __cellar <ide> __cellar_args.parse <ide> <del> if Homebrew.args.named.blank? <add> if args.no_named? <ide> puts HOMEBREW_CELLAR <ide> else <del> puts Homebrew.args.resolved_formulae.map(&:rack) <add> puts args.resolved_formulae.map(&:rack) <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cmd/--env.rb <ide> def __env <ide> __env_args.parse <ide> <ide> ENV.activate_extensions! <del> ENV.deps = Homebrew.args.formulae if superenv? <add> ENV.deps = args.formulae if superenv? <ide> ENV.setup_build_environment <del> ENV.universal_binary if ARGV.build_universal? <ide> <ide> shell = if args.plain? <ide> nil <ide><path>Library/Homebrew/cmd/--prefix.rb <ide> def __prefix_args <ide> def __prefix <ide> __prefix_args.parse <ide> <del> if Homebrew.args.named.blank? <add> if args.no_named? <ide> puts HOMEBREW_PREFIX <ide> else <del> puts Homebrew.args.resolved_formulae.map { |f| <add> puts args.resolved_formulae.map { |f| <ide> f.opt_prefix.exist? ? f.opt_prefix : f.installed_prefix <ide> } <ide> end <ide><path>Library/Homebrew/cmd/--repository.rb <ide> def __repository_args <ide> def __repository <ide> __repository_args.parse <ide> <del> if ARGV.named.empty? <add> if args.no_named? <ide> puts HOMEBREW_REPOSITORY <ide> else <del> puts ARGV.named.map { |tap| Tap.fetch(tap).path } <add> puts args.named.map { |tap| Tap.fetch(tap).path } <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cmd/analytics.rb <ide> def analytics_args <ide> def analytics <ide> analytics_args.parse <ide> <del> case args.remaining.first <add> case args.named.first <ide> when nil, "state" <ide> if Utils::Analytics.disabled? <ide> puts "Analytics are disabled." <ide> def analytics <ide> when "regenerate-uuid" <ide> Utils::Analytics.regenerate_uuid! <ide> else <del> raise UsageError, "Unknown subcommand." <add> raise UsageError, "unknown subcommand" <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cmd/cat.rb <ide> def cat_args <ide> <ide> Display the source of <formula>. <ide> EOS <del> max_named 1 <add> named :formula <ide> end <ide> end <ide> <ide> def cat <ide> cat_args.parse <del> # do not "fix" this to support multiple arguments, the output would be <del> # unparsable; if the user wants to cat multiple formula they can call <del> # `brew cat` multiple times. <del> formulae = Homebrew.args.formulae <del> raise FormulaUnspecifiedError if formulae.empty? <ide> <ide> cd HOMEBREW_REPOSITORY <ide> pager = if ENV["HOMEBREW_BAT"].nil? <ide> "cat" <ide> else <ide> "#{HOMEBREW_PREFIX}/bin/bat" <ide> end <del> safe_system pager, formulae.first.path, *Homebrew.args.passthrough <add> safe_system pager, args.formulae.first.path, *args.passthrough <ide> end <ide> end <ide><path>Library/Homebrew/cmd/cleanup.rb <ide> def cleanup_args <ide> def cleanup <ide> cleanup_args.parse <ide> <del> cleanup = Cleanup.new(*args.remaining, dry_run: args.dry_run?, scrub: args.s?, days: args.prune&.to_i) <add> cleanup = Cleanup.new(*args.named, dry_run: args.dry_run?, scrub: args.s?, days: args.prune&.to_i) <ide> if args.prune_prefix? <ide> cleanup.prune_prefix_symlinks_and_directories <ide> return <ide><path>Library/Homebrew/cmd/command.rb <ide> def command_args <ide> EOS <ide> switch :verbose <ide> switch :debug <add> min_named 1 <ide> end <ide> end <ide> <ide> def command <ide> command_args.parse <ide> <del> raise UsageError, "This command requires a command argument" if args.remaining.empty? <del> <del> args.remaining.each do |cmd| <add> args.named.each do |cmd| <ide> path = Commands.path(cmd) <ide> odie "Unknown command: #{cmd}" unless path <ide> puts path <ide><path>Library/Homebrew/cmd/deps.rb <ide> def deps <ide> Formulary.enable_factory_cache! <ide> <ide> recursive = !args.send("1?") <del> installed = args.installed? || ARGV.formulae.all?(&:opt_or_installed_prefix_keg) <add> installed = args.installed? || args.formulae.all?(&:opt_or_installed_prefix_keg) <ide> <ide> @use_runtime_dependencies = installed && recursive && <ide> !args.include_build? && <ide> def deps <ide> if args.installed? <ide> puts_deps_tree Formula.installed.sort, recursive <ide> else <del> raise FormulaUnspecifiedError if Homebrew.args.remaining.empty? <add> raise FormulaUnspecifiedError if args.no_named? <ide> <del> puts_deps_tree Homebrew.args.formulae, recursive <add> puts_deps_tree args.formulae, recursive <ide> end <ide> return <ide> elsif args.all? <ide> puts_deps Formula.sort, recursive <ide> return <del> elsif !Homebrew.args.remaining.empty? && args.for_each? <del> puts_deps Homebrew.args.formulae, recursive <add> elsif !args.no_named? && args.for_each? <add> puts_deps args.formulae, recursive <ide> return <ide> end <ide> <del> if Homebrew.args.remaining.empty? <add> if args.no_named? <ide> raise FormulaUnspecifiedError unless args.installed? <ide> <ide> puts_deps Formula.installed.sort, recursive <ide> return <ide> end <ide> <del> all_deps = deps_for_formulae(Homebrew.args.formulae, recursive, &(args.union? ? :| : :&)) <add> all_deps = deps_for_formulae(args.formulae, recursive, &(args.union? ? :| : :&)) <ide> all_deps = condense_requirements(all_deps) <ide> all_deps.select!(&:installed?) if args.installed? <ide> all_deps.map!(&method(:dep_display_name)) <ide><path>Library/Homebrew/cmd/desc.rb <ide> def desc <ide> search_type << :either if args.search <ide> search_type << :name if args.name <ide> search_type << :desc if args.description <del> odie "You must provide a search term." if search_type.present? && ARGV.named.empty? <add> odie "You must provide a search term." if search_type.present? && args.no_named? <ide> <ide> results = if search_type.empty? <del> raise FormulaUnspecifiedError if ARGV.named.empty? <add> raise FormulaUnspecifiedError if args.no_named? <ide> <ide> desc = {} <del> Homebrew.args.formulae.each { |f| desc[f.full_name] = f.desc } <add> args.formulae.each { |f| desc[f.full_name] = f.desc } <ide> Descriptions.new(desc) <ide> else <del> arg = ARGV.named.join(" ") <add> arg = args.named.join(" ") <ide> string_or_regex = query_regexp(arg) <ide> CacheStoreDatabase.use(:descriptions) do |db| <ide> cache_store = DescriptionCacheStore.new(db) <ide><path>Library/Homebrew/cmd/doctor.rb <ide> def doctor <ide> exit <ide> end <ide> <del> if ARGV.named.empty? <add> if args.no_named? <ide> slow_checks = %w[ <ide> check_for_broken_symlinks <ide> check_missing_deps <ide> ] <ide> methods = (checks.all.sort - slow_checks) + slow_checks <ide> else <del> methods = ARGV.named <add> methods = args.named <ide> end <ide> <ide> first_warning = true <ide><path>Library/Homebrew/cmd/fetch.rb <ide> def fetch_args <ide> switch :debug <ide> conflicts "--devel", "--HEAD" <ide> conflicts "--build-from-source", "--build-bottle", "--force-bottle" <add> min_named :formula <ide> end <ide> end <ide> <ide> def fetch <ide> fetch_args.parse <ide> <del> raise FormulaUnspecifiedError if ARGV.named.empty? <del> <ide> if args.deps? <ide> bucket = [] <del> Homebrew.args.formulae.each do |f| <add> args.formulae.each do |f| <ide> bucket << f <ide> bucket.concat f.recursive_dependencies.map(&:to_formula) <ide> end <ide> bucket.uniq! <ide> else <del> bucket = Homebrew.args.formulae <add> bucket = args.formulae <ide> end <ide> <ide> puts "Fetching: #{bucket * ", "}" if bucket.size > 1 <ide><path>Library/Homebrew/cmd/gist-logs.rb <ide> def create_issue(repo, title, body) <ide> def gist_logs <ide> gist_logs_args.parse <ide> <del> raise FormulaUnspecifiedError if Homebrew.args.resolved_formulae.length != 1 <add> raise FormulaUnspecifiedError if args.resolved_formulae.length != 1 <ide> <ide> Install.perform_preinstall_checks(all_fatal: true) <ide> Install.perform_build_from_source_checks(all_fatal: true) <del> gistify_logs(Homebrew.args.resolved_formulae.first) <add> gistify_logs(args.resolved_formulae.first) <ide> end <ide> end <ide><path>Library/Homebrew/cmd/home.rb <ide> def home_args <ide> def home <ide> home_args.parse <ide> <del> if args.remaining.empty? <add> if args.no_named? <ide> exec_browser HOMEBREW_WWW <ide> else <del> exec_browser(*Homebrew.args.formulae.map(&:homepage)) <add> exec_browser(*args.formulae.map(&:homepage)) <ide> end <ide> end <ide> end <ide><path>Library/Homebrew/cmd/info.rb <ide> def info <ide> end <ide> <ide> if args.category.present? <del> if Homebrew.args.named.present? && !VALID_FORMULA_CATEGORIES.include?(args.category) <add> if args.named.present? && !VALID_FORMULA_CATEGORIES.include?(args.category) <ide> raise UsageError, "--category must be one of #{VALID_FORMULA_CATEGORIES.join(", ")} when querying formulae" <ide> end <ide> <ide> def info <ide> end <ide> <ide> if args.json <del> raise UsageError, "Invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <del> if !(args.all? || args.installed?) && Homebrew.args.named.blank? <del> raise UsageError, "This command's option requires a formula argument" <add> raise UsageError, "invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <add> <add> if !(args.all? || args.installed?) && args.no_named? <add> raise FormulaUnspecifiedError if args.no_named? <ide> end <ide> <ide> print_json <ide> elsif args.github? <del> raise UsageError, "This command's option requires a formula argument" if Homebrew.args.named.blank? <add> raise FormulaUnspecifiedError if args.no_named? <ide> <del> exec_browser(*Homebrew.args.formulae.map { |f| github_info(f) }) <add> exec_browser(*args.formulae.map { |f| github_info(f) }) <ide> else <ide> print_info <ide> end <ide> end <ide> <ide> def print_info <del> if Homebrew.args.named.blank? <add> if args.no_named? <ide> if args.analytics? <ide> Utils::Analytics.output <ide> elsif HOMEBREW_CELLAR.exist? <ide> count = Formula.racks.length <ide> puts "#{count} #{"keg".pluralize(count)}, #{HOMEBREW_CELLAR.dup.abv}" <ide> end <ide> else <del> Homebrew.args.named.each_with_index do |f, i| <add> args.named.each_with_index do |f, i| <ide> puts unless i.zero? <ide> begin <ide> formula = if f.include?("/") || File.exist?(f) <ide> def print_json <ide> elsif args.installed? <ide> Formula.installed.sort <ide> else <del> Homebrew.args.formulae <add> args.formulae <ide> end <ide> json = ff.map(&:to_hash) <ide> puts JSON.generate(json) <ide><path>Library/Homebrew/cmd/install.rb <ide> def install_args <ide> conflicts "--devel", "--HEAD" <ide> conflicts "--build-from-source", "--build-bottle", "--force-bottle" <ide> formula_options <add> min_named :formula <ide> end <ide> end <ide> <ide> def install <ide> install_args.parse <ide> <del> Homebrew.args.named.each do |name| <add> args.named.each do |name| <ide> next if File.exist?(name) <ide> next if name !~ HOMEBREW_TAP_FORMULA_REGEX && name !~ HOMEBREW_CASK_TAP_CASK_REGEX <ide> <ide> tap = Tap.fetch(Regexp.last_match(1), Regexp.last_match(2)) <ide> tap.install unless tap.installed? <ide> end <ide> <del> raise FormulaUnspecifiedError if args.remaining.empty? <del> <ide> if args.ignore_dependencies? <ide> opoo <<~EOS <ide> #{Tty.bold}--ignore-dependencies is an unsupported Homebrew developer flag!#{Tty.reset} <ide> def install <ide> # developer tools are available, we need to stop them early on <ide> FormulaInstaller.prevent_build_flags unless DevelopmentTools.installed? <ide> <del> Homebrew.args.formulae.each do |f| <add> args.formulae.each do |f| <ide> # head-only without --HEAD is an error <del> if !Homebrew.args.HEAD? && f.stable.nil? && f.devel.nil? <add> if !args.HEAD? && f.stable.nil? && f.devel.nil? <ide> raise <<~EOS <ide> #{f.full_name} is a head-only formula <ide> Install with `brew install --HEAD #{f.full_name}` <ide><path>Library/Homebrew/cmd/link.rb <ide> def link_args <ide> description: "Allow keg-only formulae to be linked." <ide> switch :verbose <ide> switch :debug <add> min_named :keg <ide> end <ide> end <ide> <ide> def link <ide> link_args.parse <ide> <del> raise KegUnspecifiedError if ARGV.named.empty? <del> <ide> mode = OpenStruct.new <ide> <ide> mode.overwrite = true if args.overwrite? <ide> mode.dry_run = true if args.dry_run? <ide> <del> Homebrew.args.kegs.each do |keg| <add> args.kegs.each do |keg| <ide> keg_only = Formulary.keg_only?(keg.rack) <ide> <ide> if keg.linked? <ide><path>Library/Homebrew/cmd/list.rb <ide> def list <ide> # Unbrewed uses the PREFIX, which will exist <ide> # Things below use the CELLAR, which doesn't until the first formula is installed. <ide> unless HOMEBREW_CELLAR.exist? <del> raise NoSuchKegError, Hombrew.args.named.first if Homebrew.args.named.present? <add> raise NoSuchKegError, Hombrew.args.named.first if args.named.present? <ide> <ide> return <ide> end <ide> <ide> if args.pinned? || args.versions? <ide> filtered_list <del> elsif Homebrew.args.named.blank? <add> elsif args.no_named? <ide> if args.full_name? <ide> full_names = Formula.installed.map(&:full_name).sort(&tap_and_name_comparison) <ide> return if full_names.empty? <ide> <ide> puts Formatter.columns(full_names) <ide> else <ide> ENV["CLICOLOR"] = nil <del> safe_system "ls", *Homebrew.args.passthrough << HOMEBREW_CELLAR <add> safe_system "ls", *args.passthrough << HOMEBREW_CELLAR <ide> end <ide> elsif args.verbose? || !$stdout.tty? <del> system_command! "find", args: Homebrew.args.kegs.map(&:to_s) + %w[-not -type d -print], print_stdout: true <add> system_command! "find", args: args.kegs.map(&:to_s) + %w[-not -type d -print], print_stdout: true <ide> else <del> Homebrew.args.kegs.each { |keg| PrettyListing.new keg } <add> args.kegs.each { |keg| PrettyListing.new keg } <ide> end <ide> end <ide> <ide> def list_unbrewed <ide> end <ide> <ide> def filtered_list <del> names = if Homebrew.args.named.blank? <add> names = if args.no_named? <ide> Formula.racks <ide> else <del> racks = Homebrew.args.named.map { |n| Formulary.to_rack(n) } <add> racks = args.named.map { |n| Formulary.to_rack(n) } <ide> racks.select do |rack| <ide> Homebrew.failed = true unless rack.exist? <ide> rack.exist? <ide><path>Library/Homebrew/cmd/log.rb <ide> def log <ide> # user path, too. <ide> ENV["PATH"] = ENV["HOMEBREW_PATH"] <ide> <del> if ARGV.named.empty? <add> if args.no_named? <ide> git_log HOMEBREW_REPOSITORY <ide> else <del> path = Formulary.path(ARGV.named.first) <add> path = Formulary.path(args.named.first) <ide> tap = Tap.from_path(path) <ide> git_log path.dirname, path, tap <ide> end <ide> def git_log(cd_dir, path = nil, tap = nil) <ide> git -C "#{git_cd}" fetch --unshallow <ide> EOS <ide> end <del> args = Homebrew.args.options_only <del> args += ["--follow", "--", path] unless path.nil? <del> system "git", "log", *args <add> system_args = args.options_only <add> system_args += ["--follow", "--", path] if path.present? <add> system "git", "log", *system_args <ide> end <ide> end <ide><path>Library/Homebrew/cmd/migrate.rb <ide> def migrate_args <ide> "the same taps and migrate them anyway." <ide> switch :verbose <ide> switch :debug <add> min_named :formula <ide> end <ide> end <ide> <ide> def migrate <ide> migrate_args.parse <ide> <del> raise FormulaUnspecifiedError if Homebrew.args.named.blank? <del> <del> Homebrew.args.resolved_formulae.each do |f| <add> args.resolved_formulae.each do |f| <ide> if f.oldname <ide> unless (rack = HOMEBREW_CELLAR/f.oldname).exist? && !rack.subdirs.empty? <ide> raise NoSuchKegError, f.oldname <ide><path>Library/Homebrew/cmd/missing.rb <ide> def missing <ide> <ide> return unless HOMEBREW_CELLAR.exist? <ide> <del> ff = if Homebrew.args.named.blank? <add> ff = if args.no_named? <ide> Formula.installed.sort <ide> else <del> Homebrew.args.resolved_formulae.sort <add> args.resolved_formulae.sort <ide> end <ide> <ide> ff.each do |f| <ide><path>Library/Homebrew/cmd/options.rb <ide> def options <ide> puts_options Formula.to_a.sort <ide> elsif args.installed? <ide> puts_options Formula.installed.sort <add> elsif args.no_named? <add> raise FormulaUnspecifiedError <ide> else <del> raise FormulaUnspecifiedError if args.remaining.empty? <del> <del> puts_options Homebrew.args.formulae <add> puts_options args.formulae <ide> end <ide> end <ide> <ide><path>Library/Homebrew/cmd/outdated.rb <ide> def outdated_args <ide> def outdated <ide> outdated_args.parse <ide> <del> formulae = if Homebrew.args.resolved_formulae.blank? <add> formulae = if args.resolved_formulae.blank? <ide> Formula.installed <ide> else <del> Homebrew.args.resolved_formulae <add> args.resolved_formulae <ide> end <ide> if args.json <del> raise UsageError, "Invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <add> raise UsageError, "invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <ide> <ide> outdated = print_outdated_json(formulae) <ide> else <ide> outdated = print_outdated(formulae) <ide> end <del> Homebrew.failed = Homebrew.args.resolved_formulae.present? && !outdated.empty? <add> Homebrew.failed = args.resolved_formulae.present? && !outdated.empty? <ide> end <ide> <ide> def print_outdated(formulae) <ide><path>Library/Homebrew/cmd/pin.rb <ide> def pin_args <ide> issuing the `brew upgrade` <formula> command. See also `unpin`. <ide> EOS <ide> switch :debug <add> min_named :formula <ide> end <ide> end <ide> <ide> def pin <ide> pin_args.parse <ide> <del> raise FormulaUnspecifiedError if args.remaining.empty? <del> <del> Homebrew.args.resolved_formulae.each do |f| <add> args.resolved_formulae.each do |f| <ide> if f.pinned? <ide> opoo "#{f.name} already pinned" <ide> elsif !f.pinnable? <ide><path>Library/Homebrew/cmd/postinstall.rb <ide> def postinstall_args <ide> switch :force <ide> switch :verbose <ide> switch :debug <add> min_named :keg <ide> end <ide> end <ide> <ide> def postinstall <ide> postinstall_args.parse <ide> <del> raise KegUnspecifiedError if args.remaining.empty? <del> <del> Homebrew.args.resolved_formulae.each do |f| <add> args.resolved_formulae.each do |f| <ide> ohai "Postinstalling #{f}" <ide> fi = FormulaInstaller.new(f) <ide> fi.post_install <ide><path>Library/Homebrew/cmd/readall.rb <ide> def readall <ide> end <ide> <ide> options = { aliases: args.aliases? } <del> taps = if ARGV.named.empty? <add> taps = if args.no_named? <ide> Tap <ide> else <del> ARGV.named.map { |t| Tap.fetch(t) } <add> args.named.map { |t| Tap.fetch(t) } <ide> end <ide> taps.each do |tap| <ide> Homebrew.failed = true unless Readall.valid_tap?(tap, options) <ide><path>Library/Homebrew/cmd/reinstall.rb <ide> def reinstall_args <ide> description: "Print install times for each formula at the end of the run." <ide> conflicts "--build-from-source", "--force-bottle" <ide> formula_options <add> min_named :formula <ide> end <ide> end <ide> <ide> def reinstall <ide> reinstall_args.parse <ide> <del> raise FormulaUnspecifiedError if args.remaining.empty? <del> <ide> FormulaInstaller.prevent_build_flags unless DevelopmentTools.installed? <ide> <ide> Install.perform_preinstall_checks <ide> <del> Homebrew.args.resolved_formulae.each do |f| <add> args.resolved_formulae.each do |f| <ide> if f.pinned? <ide> onoe "#{f.full_name} is pinned. You must unpin it to reinstall." <ide> next <ide><path>Library/Homebrew/cmd/search.rb <ide> def search <ide> <ide> if package_manager = PACKAGE_MANAGERS.find { |name,| args[:"#{name}?"] } <ide> _, url = package_manager <del> exec_browser url.call(URI.encode_www_form_component(args.remaining.join(" "))) <add> exec_browser url.call(URI.encode_www_form_component(args.named.join(" "))) <ide> return <ide> end <ide> <del> if args.remaining.empty? <add> if args.no_named? <ide> if args.casks? <del> raise UsageError, "specifying both --formulae and --casks requires an argument!" if args.formulae? <add> raise UsageError, "specifying both --formulae and --casks requires <text>" if args.formulae? <ide> <ide> puts Formatter.columns(Cask::Cask.to_a.map(&:full_name).sort) <ide> else <ide> def search <ide> return <ide> end <ide> <del> query = args.remaining.join(" ") <add> query = args.named.join(" ") <ide> string_or_regex = query_regexp(query) <ide> <ide> if args.desc? <ide> def search <ide> end <ide> <ide> return unless $stdout.tty? <del> return if args.remaining.empty? <add> return if args.no_named? <ide> <ide> metacharacters = %w[\\ | ( ) [ ] { } ^ $ * + ?].freeze <ide> return unless metacharacters.any? do |char| <del> args.remaining.any? do |arg| <add> args.named.any? do |arg| <ide> arg.include?(char) && !arg.start_with?("/") <ide> end <ide> end <ide><path>Library/Homebrew/cmd/style.rb <ide> def style_args <ide> def style <ide> style_args.parse <ide> <del> target = if Homebrew.args.named.blank? <add> target = if args.no_named? <ide> nil <del> elsif Homebrew.args.named.any? { |file| File.exist? file } <del> Homebrew.args.named <del> elsif Homebrew.args.named.any? { |tap| tap.count("/") == 1 } <del> Homebrew.args.named.map { |tap| Tap.fetch(tap).path } <add> elsif args.named.any? { |file| File.exist? file } <add> args.named <add> elsif args.named.any? { |tap| tap.count("/") == 1 } <add> args.named.map { |tap| Tap.fetch(tap).path } <ide> else <del> Homebrew.args.formulae.map(&:path) <add> args.formulae.map(&:path) <ide> end <ide> <ide> only_cops = args.only_cops <ide><path>Library/Homebrew/cmd/switch.rb <ide> def switch_args <ide> EOS <ide> switch :verbose <ide> switch :debug <del> max_named 2 <add> named 2 <ide> end <ide> end <ide> <ide> def switch <ide> switch_args.parse <ide> <del> raise FormulaUnspecifiedError if args.remaining.empty? <del> <del> name = args.remaining.first <add> name = args.named.first <ide> rack = Formulary.to_rack(name) <ide> <ide> odie "#{name} not found in the Cellar." unless rack.directory? <ide> def switch <ide> .map { |d| Keg.new(d).version } <ide> .sort <ide> .join(", ") <del> version = args.remaining.second <del> raise UsageError, "Specify one of #{name}'s installed versions: #{versions}" unless version <add> version = args.named.second <ide> <ide> odie <<~EOS unless (rack/version).directory? <ide> #{name} does not have a version \"#{version}\" in the Cellar. <ide><path>Library/Homebrew/cmd/tap-info.rb <ide> def tap_info <ide> if args.installed? <ide> taps = Tap <ide> else <del> taps = Homebrew.args.named.sort.map do |name| <add> taps = args.named.sort.map do |name| <ide> Tap.fetch(name) <ide> end <ide> end <ide> <ide> if args.json <del> raise UsageError, "Invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <add> raise UsageError, "invalid JSON version: #{args.json}" unless ["v1", true].include? args.json <ide> <ide> print_tap_json(taps.sort_by(&:to_s)) <ide> else <ide><path>Library/Homebrew/cmd/tap.rb <ide> def tap <ide> Tap.each(&:link_completions_and_manpages) <ide> elsif args.list_pinned? <ide> puts Tap.select(&:pinned?).map(&:name) <del> elsif ARGV.named.empty? <add> elsif args.no_named? <ide> puts Tap.names <ide> else <del> tap = Tap.fetch(ARGV.named.first) <add> tap = Tap.fetch(args.named.first) <ide> begin <del> tap.install clone_target: ARGV.named.second, <add> tap.install clone_target: args.named.second, <ide> force_auto_update: force_auto_update?, <del> quiet: Homebrew.args.quiet? <add> quiet: args.quiet? <ide> rescue TapRemoteMismatchError => e <ide> odie e <ide> rescue TapAlreadyTappedError <ide><path>Library/Homebrew/cmd/uninstall.rb <ide> def uninstall_args <ide> description: "Don't fail uninstall, even if <formula> is a dependency of any installed "\ <ide> "formulae." <ide> switch :debug <add> min_named :formula <ide> end <ide> end <ide> <ide> def uninstall <ide> uninstall_args.parse <ide> <del> raise KegUnspecifiedError if args.remaining.empty? <del> <ide> kegs_by_rack = if args.force? <del> Hash[ARGV.named.map do |name| <add> Hash[args.named.map do |name| <ide> rack = Formulary.to_rack(name) <ide> next unless rack.directory? <ide> <ide> [rack, rack.subdirs.map { |d| Keg.new(d) }] <ide> end] <ide> else <del> Homebrew.args.kegs.group_by(&:rack) <add> args.kegs.group_by(&:rack) <ide> end <ide> <ide> handle_unsatisfied_dependents(kegs_by_rack) <ide> def initialize(requireds, dependents) <ide> protected <ide> <ide> def sample_command <del> "brew uninstall --ignore-dependencies #{ARGV.named.join(" ")}" <add> "brew uninstall --ignore-dependencies #{Homebrew.args.named.join(" ")}" <ide> end <ide> <ide> def are_required_by_deps <ide><path>Library/Homebrew/cmd/unlink.rb <ide> def unlink_args <ide> "deleting any files." <ide> switch :verbose <ide> switch :debug <add> min_named :keg <ide> end <ide> end <ide> <ide> def unlink <ide> unlink_args.parse <ide> <del> raise KegUnspecifiedError if args.remaining.empty? <del> <ide> mode = OpenStruct.new <ide> mode.dry_run = true if args.dry_run? <ide> <del> Homebrew.args.kegs.each do |keg| <add> args.kegs.each do |keg| <ide> if mode.dry_run <ide> puts "Would remove:" <ide> keg.unlink(mode) <ide><path>Library/Homebrew/cmd/unpack.rb <ide> def unpack_args <ide> def unpack <ide> unpack_args.parse <ide> <del> formulae = Homebrew.args.formulae <add> formulae = args.formulae <ide> raise FormulaUnspecifiedError if formulae.empty? <ide> <ide> if dir = args.destdir <ide><path>Library/Homebrew/cmd/unpin.rb <ide> def unpin_args <ide> def unpin <ide> unpin_args.parse <ide> <del> raise FormulaUnspecifiedError if args.remaining.empty? <add> raise FormulaUnspecifiedError if args.no_named? <ide> <del> Homebrew.args.resolved_formulae.each do |f| <add> args.resolved_formulae.each do |f| <ide> if f.pinned? <ide> f.unpin <ide> elsif !f.pinnable? <ide><path>Library/Homebrew/cmd/untap.rb <ide> def untap_args <ide> Remove a tapped formula repository. <ide> EOS <ide> switch :debug <add> min_named 1 <ide> end <ide> end <ide> <ide> def untap <ide> untap_args.parse <ide> <del> raise UsageError, "This command requires a tap argument from `brew tap`'s list" if args.remaining.empty? <del> <del> ARGV.named.each do |tapname| <add> args.named.each do |tapname| <ide> tap = Tap.fetch(tapname) <ide> odie "Untapping #{tap} is not allowed" if tap.core_tap? <ide> <ide><path>Library/Homebrew/cmd/update-report.rb <ide> module Homebrew <ide> <ide> def update_preinstall_header <ide> @update_preinstall_header ||= begin <del> ohai "Auto-updated Homebrew!" if ARGV.include?("--preinstall") <add> ohai "Auto-updated Homebrew!" if args.preinstall? <ide> true <ide> end <ide> end <ide> def update_report <ide> end <ide> <ide> if !updated <del> puts "Already up-to-date." if !ARGV.include?("--preinstall") && !ENV["HOMEBREW_UPDATE_FAILED"] <add> puts "Already up-to-date." if !args.preinstall? && !ENV["HOMEBREW_UPDATE_FAILED"] <ide> else <ide> if hub.empty? <ide> puts "No changes to formulae." <ide> def update_report <ide> .update_from_report!(hub) <ide> end <ide> end <del> puts if ARGV.include?("--preinstall") <add> puts if args.preinstall? <ide> end <ide> <ide> link_completions_manpages_and_docs <ide><path>Library/Homebrew/cmd/upgrade.rb <ide> def upgrade <ide> <ide> Install.perform_preinstall_checks <ide> <del> if Homebrew.args.named.blank? <add> if args.no_named? <ide> outdated = Formula.installed.select do |f| <ide> f.outdated?(fetch_head: args.fetch_HEAD?) <ide> end <ide> <ide> exit 0 if outdated.empty? <ide> else <del> outdated = Homebrew.args.resolved_formulae.select do |f| <add> outdated = args.resolved_formulae.select do |f| <ide> f.outdated?(fetch_head: args.fetch_HEAD?) <ide> end <ide> <del> (Homebrew.args.resolved_formulae - outdated).each do |f| <add> (args.resolved_formulae - outdated).each do |f| <ide> versions = f.installed_kegs.map(&:version) <ide> if versions.empty? <ide> ofail "#{f.full_specified_name} not installed" <ide> def upgrade_formula(f) <ide> tab = Tab.for_keg(keg) <ide> end <ide> <del> build_options = BuildOptions.new(Options.create(Homebrew.args.flags_only), f.options) <add> build_options = BuildOptions.new(Options.create(args.flags_only), f.options) <ide> options = build_options.used_options <ide> options |= f.build.used_options <ide> options &= f.options <ide> <ide> fi = FormulaInstaller.new(f) <ide> fi.options = options <ide> fi.build_bottle = args.build_bottle? <del> fi.installed_on_request = Homebrew.args.named.present? <add> fi.installed_on_request = args.named.present? <ide> fi.link_keg ||= keg_was_linked if keg_had_linked_opt <ide> if tab <ide> fi.build_bottle ||= tab.built_bottle? <ide><path>Library/Homebrew/cmd/uses.rb <ide> def uses_args <ide> description: "Show usage of <formula> by HEAD builds." <ide> switch :debug <ide> conflicts "--devel", "--HEAD" <add> min_named :formula <ide> end <ide> end <ide> <ide> def uses <ide> uses_args.parse <ide> <del> raise FormulaUnspecifiedError if args.remaining.empty? <del> <ide> Formulary.enable_factory_cache! <ide> <ide> used_formulae_missing = false <ide> used_formulae = begin <del> Homebrew.args.formulae <add> args.formulae <ide> rescue FormulaUnavailableError => e <ide> opoo e <ide> used_formulae_missing = true <ide> # If the formula doesn't exist: fake the needed formula object name. <del> Homebrew.args.named.map { |name| OpenStruct.new name: name, full_name: name } <add> args.named.map { |name| OpenStruct.new name: name, full_name: name } <ide> end <ide> <ide> use_runtime_dependents = args.installed? &&
41
Go
Go
remove unused field
a46ad5e7044313d98431788d6177691c4645d527
<ide><path>builder/dockerfile/imagecontext.go <ide> func (m *imageSources) Add(im *imageMount) { <ide> <ide> // imageMount is a reference to an image that can be used as a builder.Source <ide> type imageMount struct { <del> image builder.Image <del> source builder.Source <del> layer builder.ROLayer <add> image builder.Image <add> layer builder.ROLayer <ide> } <ide> <ide> func newImageMount(image builder.Image, layer builder.ROLayer) *imageMount {
1
Python
Python
raise meaningful error when loss cannot be found
44200a4b8ecbb72fc704bee8f10880206886bc90
<ide><path>keras/engine/compile_utils.py <ide> # ============================================================================== <ide> """Utilities for `Model.compile`.""" <ide> <del>import tensorflow.compat.v2 as tf <ide> <ide> import copy <ide> from keras import losses as losses_mod <ide> from keras import metrics as metrics_mod <ide> from keras.utils import generic_utils <ide> from keras.utils import losses_utils <ide> from keras.utils import tf_utils <add>import tensorflow.compat.v2 as tf <ide> <ide> <ide> class Container: <ide> def __call__(self, <ide> total_loss = tf.add_n(loss_values) <ide> return total_loss <ide> else: <del> # Ok for a model to have no compiled loss. <del> return tf.zeros(shape=()) <add> return None <ide> <ide> def reset_state(self): <ide> """Resets the state of loss metrics.""" <ide><path>keras/engine/training.py <ide> def run_eagerly(self): <ide> def run_eagerly(self, value): <ide> self._run_eagerly = value <ide> <add> def _validate_target_and_loss(self, y, loss): <add> """Raises error if target or loss is not found. <add> <add> This method verifies that the target and loss are properly populated <add> when applicable, or raises errors. <add> <add> Args: <add> y: the target for training. <add> loss: the total loss tensor including loss added via `compile` and <add> `add_loss`. <add> """ <add> <add> # `self.loss` references the loss added via `compile` call. If users have <add> # provided such, the target must be provided; otherwise it's a user error. <add> # Note that `self.loss` does not include losses added via `add_loss`, and it <add> # is a valid use when such loss from `add_loss` exists and target does not. <add> if self.loss and y is None: <add> raise ValueError( <add> 'Target data is missing. Your model was compiled with ' <add> f'loss={self.loss}, ' <add> 'and therefore expects target data to be provided in `fit()`.') <add> <add> # For training, there must be compiled loss or regularization loss to exist <add> # in order to apply the gradients. If one is not found, it means no loss <add> # was supplied via `compile` or `add_loss`. <add> elif loss is None: <add> raise ValueError( <add> 'No loss found. You may have forgotten to provide a `loss` argument ' <add> 'in the `compile()` method.') <add> <ide> def train_step(self, data): <ide> """The logic for one training step. <ide> <ide> def train_step(self, data): <ide> y_pred = self(x, training=True) <ide> loss = self.compiled_loss( <ide> y, y_pred, sample_weight, regularization_losses=self.losses) <del> if self.loss and y is None: <del> raise TypeError( <del> f'Target data is missing. Your model has `loss`: {self.loss}, ' <del> 'and therefore expects target data to be passed in `fit()`.') <add> self._validate_target_and_loss(y, loss) <ide> # Run backwards pass. <ide> self.optimizer.minimize(loss, self.trainable_variables, tape=tape) <ide> self.compiled_metrics.update_state(y, y_pred, sample_weight) <ide><path>keras/engine/training_test.py <ide> # ============================================================================== <ide> """Tests for training routines.""" <ide> <del>import tensorflow.compat.v2 as tf <ide> <ide> import collections <ide> import io <del>import tempfile <ide> import sys <del> <add>import tempfile <ide> from absl.testing import parameterized <del>import numpy as np <del>from tensorflow.python.framework import test_util as tf_test_util <ide> from keras import backend <ide> from keras import combinations <ide> from keras import keras_parameterized <ide> from keras.engine import training_utils_v1 <ide> from keras.utils import data_utils <ide> from keras.utils import np_utils <add>import numpy as np <add>import tensorflow.compat.v2 as tf <add>from tensorflow.python.framework import test_util as tf_test_util <ide> from tensorflow.python.platform import tf_logging as logging <ide> from tensorflow.python.training.rmsprop import RMSPropOptimizer <ide> <ide> def test_fit_on_empty(self): <ide> 'Unexpected result of `train_function`.*'): <ide> model.fit(x=np.array([]), y=np.array([])) <ide> <add> @keras_parameterized.run_all_keras_modes(always_skip_v1=True) <add> def test_fit_without_loss_at_compile(self): <add> model = sequential.Sequential([layers_module.Dense(1)]) <add> model.compile('sgd', run_eagerly=testing_utils.should_run_eagerly()) <add> x, y = np.ones((10, 1)), np.ones((10, 1)) <add> with self.assertRaisesRegex(ValueError, 'No loss found..*'): <add> model.fit(x, y, epochs=2) <add> <add> @keras_parameterized.run_all_keras_modes(always_skip_v1=True) <add> def test_fit_without_loss_at_compile_but_with_add_loss(self): <add> <add> class MyModel(sequential.Sequential): <add> <add> def call(self, x): <add> self.add_loss(tf.reduce_sum(x)) <add> return x <add> <add> model = MyModel([layers_module.Dense(1)]) <add> model.compile('sgd', run_eagerly=testing_utils.should_run_eagerly()) <add> x, y = np.ones((10, 1)), np.ones((10, 1)) <add> model.fit(x, y, epochs=2) <add> <ide> @keras_parameterized.run_all_keras_modes <ide> def test_run_eagerly_setting(self): <ide> model = sequential.Sequential([layers_module.Dense(1)]) <ide> def test_fit_on_no_output(self): <ide> model = training_module.Model(inputs, outputs) <ide> model.compile('rmsprop', 'mse') <ide> x = np.zeros((32, 3)) <del> with self.assertRaisesRegex(TypeError, 'Target data is missing..*'): <add> with self.assertRaisesRegex(ValueError, 'Target data is missing..*'): <ide> model.fit(x) <ide> <ide> @keras_parameterized.run_all_keras_modes(always_skip_v1=True) <ide> def test_fit_on_wrong_output_type(self): <ide> model.compile('rmsprop', 'mse') <ide> x = np.zeros((32, 3)) <ide> y = np.zeros((32, 2)) <del> with self.assertRaisesRegex(TypeError, 'Target data is missing..*'): <add> with self.assertRaisesRegex(ValueError, 'Target data is missing..*'): <ide> model.fit({'a': x, 'b': x, 'c': y}) <ide> <ide> @keras_parameterized.run_all_keras_modes
3
Javascript
Javascript
simplify if statement in webgltextures
bb01ca7eb6dfab9cca85f440a5dfda292b184c7a
<ide><path>src/renderers/webgl/WebGLTextures.js <ide> function WebGLTextures( _gl, extensions, state, properties, capabilities, paramT <ide> <ide> function textureNeedsPowerOfTwo( texture ) { <ide> <del> if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) return true; <del> if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) return true; <del> <del> return false; <del> <add> return (texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) || ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ); <add> <ide> } <ide> <ide> // Fallback filters for non-power-of-2 textures
1
Javascript
Javascript
add test for error in aftereach
fdc0bb232a259faf791b901f583e09bba3213ba5
<ide><path>test/scenario/RunnerSpec.js <ide> describe('Runner', function(){ <ide> it('should execute afterEach after every it', function() { <ide> Describe('describe name', function(){ <ide> AfterEach(logger('after;')); <del> It('should text', logger('body;')); <add> It('should text1', logger('body1;')); <ide> It('should text2', logger('body2;')); <ide> }); <del> expect(log).toEqual('body;after;body2;after;'); <add> expect(log).toEqual('body1;after;body2;after;'); <ide> }); <ide> <ide> it('should always execute afterEach after every it', function() { <ide> Describe('describe name', function(){ <ide> AfterEach(logger('after;')); <ide> It('should text', function() { <del> log = 'body;'; <add> logger('body1;')(); <ide> throw "MyError"; <ide> }); <ide> It('should text2', logger('body2;')); <ide> }); <del> expect(log).toEqual('body;after;body2;after;'); <add> expect(log).toEqual('body1;after;body2;after;'); <add> }); <add> <add> it('should report an error if afterEach fails', function() { <add> var next; <add> Describe('describe name', function(){ <add> AfterEach(function() { <add> $scenario.addStep('afterEachLog', logger('after;')); <add> $scenario.addStep('afterEachThrow', function() { <add> throw "AfterError"; <add> }); <add> }); <add> It('should text1', function() { <add> $scenario.addStep('step1', logger('step1;')); <add> }); <add> It('should text2', function() { <add> $scenario.addStep('step2', logger('step2;')); <add> }); <add> }); <add> $scenario.run(body); <add> expect(log).toEqual('step1;after;step2;after;'); <add> expect(scenario.$testrun.results).toEqual([ <add> { name : 'describe name: it should text1', <add> passed : false, <add> error : 'AfterError', <add> steps : [ 'step1', 'afterEachLog', 'afterEachThrow' ] }, <add> { name : 'describe name: it should text2', <add> passed : false, <add> error : 'AfterError', <add> steps : [ 'step2', 'afterEachLog', 'afterEachThrow' ] }]); <ide> }); <ide> }); <ide> });
1
Ruby
Ruby
handle legacy formulae pr from homebrew/homebrew
deed8e566c096da391a92060f19e5093ec3cd1f6
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> # --junit: Generate a JUnit XML test results file. <ide> # --no-bottle: Run brew install without --build-bottle <ide> # --keep-old: Run brew bottle --keep-old to build new bottles for a single platform. <add># --legacy Bulid formula from legacy Homebrew/homebrew repo. <add># (TODO remove it when it's not longer necessary) <ide> # --HEAD: Run brew install with --HEAD <ide> # --local: Ask Homebrew to write verbose logs under ./logs/ and set HOME to ./home/ <ide> # --tap=<tap>: Use the git repository of the given tap <ide> def diff_formulae(start_revision, end_revision, path, filter) <ide> # the right commit to BrewTestBot. <ide> unless travis_pr <ide> diff_start_sha1 = current_sha1 <del> test "brew", "pull", "--clean", @url <add> if ARGV.include?("--legacy") <add> test "brew", "pull", "--clean", "--legacy", @url <add> else <add> test "brew", "pull", "--clean", @url <add> end <ide> diff_end_sha1 = current_sha1 <ide> end <ide> @short_url = @url.gsub("https://github.com/", "") <ide> def test_ci_upload(tap) <ide> <ide> ARGV << "--verbose" <ide> ARGV << "--keep-old" if ENV["UPSTREAM_BOTTLE_KEEP_OLD"] <add> ARGV << "--legacy" if ENV["UPSTREAM_BOTTLE_LEGACY"] <ide> <ide> bottles = Dir["#{jenkins}/jobs/#{job}/configurations/axis-version/*/builds/#{id}/archive/*.bottle*.*"] <ide> return if bottles.empty? <ide> def test_ci_upload(tap) <ide> safe_system "brew", "update" <ide> <ide> if pr <del> pull_pr = "https://github.com/#{tap.user}/homebrew-#{tap.repo}/pull/#{pr}" <del> safe_system "brew", "pull", "--clean", pull_pr <add> if ARGV.include?("--legacy") <add> pull_pr = "https://github.com/Homebrew/homebrew/pull/#{pr}" <add> safe_system "brew", "pull", "--clean", "--legacy", pull_pr <add> else <add> pull_pr = "https://github.com/#{tap.user}/homebrew-#{tap.repo}/pull/#{pr}" <add> safe_system "brew", "pull", "--clean", pull_pr <add> end <ide> end <ide> <ide> bottle_args = ["--merge", "--write", *Dir["*.bottle.rb"]]
1
PHP
PHP
add strict typing for translation related classes
2a1afb47a103b77015174ae1c3f92b5ec6cc09e3
<ide><path>src/I18n/ChainMessagesLoader.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function __construct(array $loaders) <ide> * @return \Aura\Intl\Package <ide> * @throws \RuntimeException if any of the loaders in the chain is not a valid callable <ide> */ <del> public function __invoke() <add> public function __invoke(): Package <ide> { <ide> foreach ($this->_loaders as $k => $loader) { <ide> if (!is_callable($loader)) { <ide><path>src/I18n/I18n.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> <ide> use Aura\Intl\FormatterLocator; <ide> use Aura\Intl\PackageLocator; <add>use Aura\Intl\TranslatorInterface; <ide> use Cake\Cache\Cache; <ide> use Cake\I18n\Formatter\IcuFormatter; <ide> use Cake\I18n\Formatter\SprintfFormatter; <ide> class I18n <ide> * <ide> * @return \Cake\I18n\TranslatorRegistry The translators collection. <ide> */ <del> public static function translators() <add> public static function translators(): TranslatorRegistry <ide> { <ide> if (static::$_collection !== null) { <ide> return static::$_collection; <ide> public static function translators() <ide> * @param string|null $locale The locale for the translator. <ide> * @return void <ide> */ <del> public static function setTranslator($name, callable $loader, $locale = null) <add> public static function setTranslator(string $name, callable $loader, ?string $locale = null): void <ide> { <ide> $locale = $locale ?: static::getLocale(); <ide> <ide> public static function setTranslator($name, callable $loader, $locale = null) <ide> * @return \Aura\Intl\TranslatorInterface The configured translator. <ide> * @throws \Aura\Intl\Exception <ide> */ <del> public static function getTranslator($name = 'default', $locale = null) <add> public static function getTranslator(string $name = 'default', ?string $locale = null): TranslatorInterface <ide> { <ide> $translators = static::translators(); <ide> <ide> public static function getTranslator($name = 'default', $locale = null) <ide> * instance to be used for assembling a new translator. <ide> * @return void <ide> */ <del> public static function config($name, callable $loader) <add> public static function config(string $name, callable $loader): void <ide> { <ide> static::translators()->registerLoader($name, $loader); <ide> } <ide> public static function config($name, callable $loader) <ide> * @param string $locale The name of the locale to set as default. <ide> * @return void <ide> */ <del> public static function setLocale($locale) <add> public static function setLocale(string $locale): void <ide> { <ide> static::getDefaultLocale(); <ide> Locale::setDefault($locale); <ide> public static function setLocale($locale) <ide> * <ide> * @return string The name of the default locale. <ide> */ <del> public static function getLocale() <add> public static function getLocale(): string <ide> { <ide> static::getDefaultLocale(); <ide> $current = Locale::getDefault(); <ide> public static function getLocale() <ide> * <ide> * @return string <ide> */ <del> public static function getDefaultLocale() <add> public static function getDefaultLocale(): string <ide> { <ide> if (static::$_defaultLocale === null) { <ide> static::$_defaultLocale = Locale::getDefault() ?: static::DEFAULT_LOCALE; <ide> public static function getDefaultLocale() <ide> * <ide> * @return string The name of the formatter. <ide> */ <del> public static function getDefaultFormatter() <add> public static function getDefaultFormatter(): string <ide> { <ide> return static::translators()->defaultFormatter(); <ide> } <ide> public static function getDefaultFormatter() <ide> * @param string $name The name of the formatter to use. <ide> * @return void <ide> */ <del> public static function setDefaultFormatter($name) <add> public static function setDefaultFormatter(string $name): void <ide> { <ide> static::translators()->defaultFormatter($name); <ide> } <ide> public static function setDefaultFormatter($name) <ide> * @param bool $enable flag to enable or disable fallback <ide> * @return void <ide> */ <del> public static function useFallback($enable = true) <add> public static function useFallback(bool $enable = true): void <ide> { <ide> static::translators()->useFallback($enable); <ide> } <ide> public static function useFallback($enable = true) <ide> * <ide> * @return void <ide> */ <del> public static function clear() <add> public static function clear(): void <ide> { <ide> static::$_collection = null; <ide> } <ide><path>src/I18n/MessagesFileLoader.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class MessagesFileLoader <ide> * @param string $extension The file extension to use. This will also be mapped <ide> * to a messages parser class. <ide> */ <del> public function __construct($name, $locale, $extension = 'po') <add> public function __construct(string $name, string $locale, string $extension = 'po') <ide> { <ide> $this->_name = $name; <ide> $this->_locale = $locale; <ide> public function __invoke() <ide> * <ide> * @return array The list of folders where the translation file should be looked for <ide> */ <del> public function translationsFolders() <add> public function translationsFolders(): array <ide> { <ide> $locale = Locale::parseLocale($this->_locale) + ['region' => null]; <ide> <ide><path>src/I18n/PluralRules.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> class PluralRules <ide> * @link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html <ide> * @link https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals#List_of_Plural_Rules <ide> */ <del> public static function calculate($locale, $n) <add> public static function calculate(string $locale, $n): int <ide> { <ide> $locale = strtolower($locale); <ide> <ide><path>src/I18n/Translator.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> public function translate($key, array $tokensValues = []) <ide> * @param string $key The message key being handled. <ide> * @param string|array $message The message content. <ide> * @param array $vars The variables containing the `_context` key. <del> * @return string <add> * @return string|array <ide> */ <del> protected function resolveContext($key, $message, array $vars) <add> protected function resolveContext(string $key, $message, array $vars) <ide> { <ide> $context = $vars['_context'] ?? null; <ide> <ide><path>src/I18n/TranslatorFactory.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/I18n/TranslatorRegistry.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> use Aura\Intl\Exception; <ide> use Aura\Intl\FormatterLocator; <ide> use Aura\Intl\PackageLocator; <add>use Aura\Intl\TranslatorInterface; <ide> use Aura\Intl\TranslatorLocator; <ide> use Cake\Cache\CacheEngine; <ide> <ide> public function __construct( <ide> PackageLocator $packages, <ide> FormatterLocator $formatters, <ide> TranslatorFactory $factory, <del> $locale <add> string $locale <ide> ) { <ide> parent::__construct($packages, $formatters, $factory, $locale); <ide> <ide> public function __construct( <ide> * @param \Cake\Cache\CacheEngine $cacher The cacher instance. <ide> * @return void <ide> */ <del> public function setCacher(CacheEngine $cacher) <add> public function setCacher(CacheEngine $cacher): void <ide> { <ide> $this->_cacher = $cacher; <ide> } <ide> public function get($name, $locale = null) <ide> * locale. <ide> * @return \Aura\Intl\TranslatorInterface A translator object. <ide> */ <del> protected function _getTranslator($name, $locale) <add> protected function _getTranslator(string $name, ?string $locale): TranslatorInterface <ide> { <ide> try { <ide> return parent::get($name, $locale); <ide> protected function _getTranslator($name, $locale) <ide> * @param callable $loader A callable object that should return a Package <ide> * @return void <ide> */ <del> public function registerLoader($name, callable $loader) <add> public function registerLoader(string $name, callable $loader): void <ide> { <ide> $this->_loaders[$name] = $loader; <ide> } <ide> public function registerLoader($name, callable $loader) <ide> * @param string|null $name The name of the formatter to use. <ide> * @return string The name of the formatter. <ide> */ <del> public function defaultFormatter($name = null) <add> public function defaultFormatter(?string $name = null): string <ide> { <ide> if ($name === null) { <ide> return $this->_defaultFormatter; <ide> public function defaultFormatter($name = null) <ide> * @param bool $enable flag to enable or disable fallback <ide> * @return void <ide> */ <del> public function useFallback($enable = true) <add> public function useFallback(bool $enable = true): void <ide> { <ide> $this->_useFallback = $enable; <ide> } <ide> public function useFallback($enable = true) <ide> * <ide> * @param string $name The translation package name. <ide> * @param string $locale The locale to create the translator for. <del> * @return \Aura\Intl\Translator <add> * @return \Aura\Intl\TranslatorInterface|closure <ide> */ <del> protected function _fallbackLoader($name, $locale) <add> protected function _fallbackLoader(string $name, string $locale) <ide> { <ide> return $this->_loaders[$this->_fallbackLoader]($name, $locale); <ide> } <ide> protected function _fallbackLoader($name, $locale) <ide> * <ide> * @return callable <ide> */ <del> protected function _partialLoader() <add> protected function _partialLoader(): callable <ide> { <ide> return function ($name, $locale) { <ide> return $this->_fallbackLoader($name, $locale); <ide> protected function _partialLoader() <ide> * @param string $locale The locale that should be built the package for <ide> * @return \Aura\Intl\TranslatorInterface A translator object. <ide> */ <del> protected function _getFromLoader($name, $locale) <add> protected function _getFromLoader(string $name, string $locale): TranslatorInterface <ide> { <ide> $loader = $this->_loaders[$name]($name, $locale); <ide> $package = $loader; <ide> protected function _getFromLoader($name, $locale) <ide> * @param callable $loader invokable loader <ide> * @return callable loader <ide> */ <del> public function setLoaderFallback($name, callable $loader) <add> public function setLoaderFallback(string $name, callable $loader): callable <ide> { <ide> $fallbackDomain = 'default'; <ide> if (!$this->_useFallback || $name === $fallbackDomain) { <ide><path>src/I18n/functions.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide> * @return string|null The translated text, or null if invalid. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__ <ide> */ <del> function __($singular, ...$args) <add> function __(string $singular, ...$args): ?string <ide> { <ide> if (!$singular) { <ide> return null; <ide> function __($singular, ...$args) <ide> * @return string|null Plural form of translated string, or null if invalid. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__n <ide> */ <del> function __n($singular, $plural, $count, ...$args) <add> function __n(string $singular, string $plural, int $count, ...$args): ?string <ide> { <ide> if (!$singular) { <ide> return null; <ide> function __n($singular, $plural, $count, ...$args) <ide> * @return string|null Translated string. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__d <ide> */ <del> function __d($domain, $msg, ...$args) <add> function __d(string $domain, string $msg, ...$args): ?string <ide> { <ide> if (!$msg) { <ide> return null; <ide> function __d($domain, $msg, ...$args) <ide> * @return string|null Plural form of translated string. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dn <ide> */ <del> function __dn($domain, $singular, $plural, $count, ...$args) <add> function __dn(string $domain, string $singular, string $plural, int $count, ...$args): ?string <ide> { <ide> if (!$singular) { <ide> return null; <ide> function __dn($domain, $singular, $plural, $count, ...$args) <ide> * @return string|null Translated string. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__x <ide> */ <del> function __x($context, $singular, ...$args) <add> function __x(string $context, string $singular, ...$args): ?string <ide> { <ide> if (!$singular) { <ide> return null; <ide> function __x($context, $singular, ...$args) <ide> * @return string|null Plural form of translated string. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__xn <ide> */ <del> function __xn($context, $singular, $plural, $count, ...$args) <add> function __xn(string $context, string $singular, string $plural, int $count, ...$args): ?string <ide> { <ide> if (!$singular) { <ide> return null; <ide> function __xn($context, $singular, $plural, $count, ...$args) <ide> * @return string|null Translated string. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dx <ide> */ <del> function __dx($domain, $context, $msg, ...$args) <add> function __dx(string $domain, string $context, string $msg, ...$args): ?string <ide> { <ide> if (!$msg) { <ide> return null; <ide> function __dx($domain, $context, $msg, ...$args) <ide> * @return string|null Plural form of translated string. <ide> * @link https://book.cakephp.org/3.0/en/core-libraries/global-constants-and-functions.html#__dxn <ide> */ <del> function __dxn($domain, $context, $singular, $plural, $count, ...$args) <add> function __dxn(string $domain, string $context, string $singular, string $plural, int $count, ...$args): ?string <ide> { <ide> if (!$singular) { <ide> return null; <ide><path>tests/TestCase/I18n/I18nTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/I18n/MessagesFileLoaderTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/I18n/PluralRulesTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/I18n/TranslatorFactoryTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/I18n/TranslatorRegistryTest.php <ide> <?php <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
13
Javascript
Javascript
use common.pipe for emptytxt path
1f79e4f4b499040bf927b5465c3ac286aa859d43
<ide><path>test/simple/test-net-pipe-connect-errors.js <ide> var accessErrorFired = false; <ide> <ide> // Test if ENOTSOCK is fired when trying to connect to a file which is not <ide> // a socket. <del>var emptyTxt = path.join(common.fixturesDir, 'empty.txt'); <add>var emptyTxt = common.PIPE + '.txt'; <add>function cleanup() { <add> try { <add> fs.unlinkSync(emptyTxt); <add> } catch (e) { <add> if (e.code != 'ENOENT') <add> throw e; <add> } <add>} <add>process.on('exit', cleanup); <add>cleanup(); <add>fs.writeFileSync(emptyTxt, ''); <ide> var notSocketClient = net.createConnection(emptyTxt, function() { <ide> assert.ok(false); <ide> });
1
Text
Text
remove trailing whitespace
6fc98b04a930696246b8a40d5ca918c6506f1b40
<ide><path>docs/recipes/ReducingBoilerplate.md <ide> export const addTodo = makeActionCreator(ADD_TODO, 'todo') <ide> export const editTodo = makeActionCreator(EDIT_TODO, 'id', 'todo') <ide> export const removeTodo = makeActionCreator(REMOVE_TODO, 'id') <ide> ``` <del>There are also utility libraries to aid in generating action creators, such as [redux-action-utils](https://github.com/insin/redux-action-utils) and [redux-actions](https://github.com/acdlite/redux-actions). These can help with reducing your boilerplate code and adhering to standards such as [Flux Standard Action (FSA)](https://github.com/acdlite/flux-standard-action). <add>There are also utility libraries to aid in generating action creators, such as [redux-action-utils](https://github.com/insin/redux-action-utils) and [redux-actions](https://github.com/acdlite/redux-actions). These can help with reducing your boilerplate code and adhering to standards such as [Flux Standard Action (FSA)](https://github.com/acdlite/flux-standard-action). <ide> <ide> ## Async Action Creators <ide>
1
Python
Python
fix digital ocean tests
dc1290f0213652eb5466cadda5cae291586f4bf1
<ide><path>libcloud/test/common/test_digitalocean_v2.py <ide> def _v2_actions_12345670(self, method, url, body, headers): <ide> <ide> def _v2_actions_page_1(self, method, url, body, headers): <ide> body = self.fixtures.load('_v2_actions_page_1.json') <del> return (self.response[None], body, {}, <del> httplib.responses[self.response[None]]) <add> return (httplib.OK, body, {}, <add> httplib.responses[httplib.OK]) <ide> <ide> <ide> if __name__ == '__main__':
1
Mixed
Text
fix the typo of urls
fa378413f88054d0a336d675e7280930ddc86cb2
<ide><path>daemon/graphdriver/devmapper/README.md <ide> This uses the `dm` prefix and would be used something like `docker daemon --stor <ide> <ide> These options are currently documented both in [the man <ide> page](../../../man/docker.1.md) and in [the online <del>documentation](https://docs.docker.com/engine/userguide/storagedriver/device-mapper-driver/). <add>documentation](https://docs.docker.com/engine/reference/commandline/dockerd/#/storage-driver-options). <ide> If you add an options, update both the `man` page and the documentation. <ide><path>man/docker-build.1.md <ide> Cgroups are created if they do not already exist. <ide> Ulimit options <ide> <ide> For more information about `ulimit` see [Setting ulimits in a <del>container](https://docs.docker.com/reference/commandline/run/#setting-ulimits-in-a-container) <add>container](https://docs.docker.com/engine/reference/commandline/run/#set-ulimits-in-container---ulimit) <ide> <ide> # EXAMPLES <ide> <ide><path>pkg/authorization/authz.go <ide> const maxBodySize = 1048576 // 1MB <ide> // Authenticate Request: <ide> // Call authZ plugins with current REST request and AuthN response <ide> // Request contains full HTTP packet sent to the docker daemon <del>// https://docs.docker.com/reference/api/docker_remote_api/ <add>// https://docs.docker.com/engine/reference/api/docker_remote_api/ <ide> // <ide> // Authenticate Response: <ide> // Call authZ plugins with full info about current REST request, REST response and AuthN response
3
PHP
PHP
add more operators for various databases
6debd53e976daf189637462f6040f64b1cbb25eb
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> class Builder { <ide> protected $operators = array( <ide> '=', '<', '>', '<=', '>=', '<>', '!=', <ide> 'like', 'not like', 'between', 'ilike', <add> '&', '|', '^', '<<', '>>', <ide> ); <ide> <ide> /** <ide><path>src/Illuminate/Database/Query/Grammars/PostgresGrammar.php <ide> <ide> class PostgresGrammar extends Grammar { <ide> <add> /** <add> * All of the available clause operators. <add> * <add> * @var array <add> */ <add> protected $operators = array( <add> '=', '<', '>', '<=', '>=', '<>', '!=', <add> 'like', 'not like', 'between', 'ilike', <add> '&', '|', '#', '<<', '>>', <add> ); <add> <ide> /** <ide> * Compile an update statement into SQL. <ide> * <ide><path>src/Illuminate/Database/Query/Grammars/SQLiteGrammar.php <ide> <ide> class SQLiteGrammar extends Grammar { <ide> <add> /** <add> * All of the available clause operators. <add> * <add> * @var array <add> */ <add> protected $operators = array( <add> '=', '<', '>', '<=', '>=', '<>', '!=', <add> 'like', 'not like', 'between', 'ilike', <add> '&', '|', '<<', '>>', <add> ); <add> <ide> /** <ide> * Compile an insert statement into SQL. <ide> * <ide><path>src/Illuminate/Database/Query/Grammars/SqlServerGrammar.php <ide> <ide> class SqlServerGrammar extends Grammar { <ide> <add> /** <add> * All of the available clause operators. <add> * <add> * @var array <add> */ <add> protected $operators = array( <add> '=', '<', '>', '<=', '>=', '!<', '!>', '<>', '!=', <add> 'like', 'not like', 'between', 'ilike', <add> '&', '&=', '|', '|=', '^', '^=', <add> ); <add> <ide> /** <ide> * The keyword identifier wrapper format. <ide> * <ide> protected function compileRowConstraint($query) <ide> <ide> return "between {$start} and {$finish}"; <ide> } <del> <add> <ide> return ">= {$start}"; <ide> } <ide>
4
Java
Java
fix marble of maybe.flatmap events to maybesource
835ab00699d39c092ef6e90cf1868722b9180fe1
<ide><path>src/main/java/io/reactivex/Maybe.java <ide> public final <R> Maybe<R> flatMap(Function<? super T, ? extends MaybeSource<? ex <ide> * Maps the onSuccess, onError or onComplete signals of this Maybe into MaybeSource and emits that <ide> * MaybeSource's signals. <ide> * <p> <del> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeMap.nce.png" alt=""> <add> * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Maybe.flatMap.mmm.png" alt=""> <ide> * <dl> <ide> * <dt><b>Scheduler:</b></dt> <ide> * <dd>{@code flatMap} does not operate by default on a particular {@link Scheduler}.</dd>
1
Python
Python
prepare 1.2.1 pypi release
262e5751f474f51197ea13e3457bf348c7d6ff13
<ide><path>keras/__init__.py <ide> from . import optimizers <ide> from . import regularizers <ide> <del>__version__ = '1.2.0' <add>__version__ = '1.2.1' <ide><path>setup.py <ide> <ide> <ide> setup(name='Keras', <del> version='1.2.0', <add> version='1.2.1', <ide> description='Deep Learning for Python', <ide> author='Francois Chollet', <ide> author_email='francois.chollet@gmail.com', <ide> url='https://github.com/fchollet/keras', <del> download_url='https://github.com/fchollet/keras/tarball/1.2.0', <add> download_url='https://github.com/fchollet/keras/tarball/1.2.1', <ide> license='MIT', <ide> install_requires=['theano', 'pyyaml', 'six'], <ide> extras_require={
2
Text
Text
fix the spelling error in stream.md
e9518254d79645c3c060ea8d7f4898f8e12af9bb
<ide><path>doc/api/stream.md <ide> If the loop terminates with a `break` or a `throw`, the stream will be <ide> destroyed. In other terms, iterating over a stream will consume the stream <ide> fully. The stream will be read in chunks of size equal to the `highWaterMark` <ide> option. In the code example above, data will be in a single chunk if the file <del>has less then 64kb of data because no `highWaterMark` option is provided to <add>has less then 64KB of data because no `highWaterMark` option is provided to <ide> [`fs.createReadStream()`][]. <ide> <ide> ### Duplex and Transform Streams <ide> changes: <ide> * `options` {Object} <ide> * `highWaterMark` {number} Buffer level when <ide> [`stream.write()`][stream-write] starts returning `false`. **Default:** <del> `16384` (16kb), or `16` for `objectMode` streams. <add> `16384` (16KB), or `16` for `objectMode` streams. <ide> * `decodeStrings` {boolean} Whether to encode `string`s passed to <ide> [`stream.write()`][stream-write] to `Buffer`s (with the encoding <ide> specified in the [`stream.write()`][stream-write] call) before passing <ide> changes: <ide> * `options` {Object} <ide> * `highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store <ide> in the internal buffer before ceasing to read from the underlying resource. <del> **Default:** `16384` (16kb), or `16` for `objectMode` streams. <add> **Default:** `16384` (16KB), or `16` for `objectMode` streams. <ide> * `encoding` {string} If specified, then buffers will be decoded to <ide> strings using the specified encoding. **Default:** `null`. <ide> * `objectMode` {boolean} Whether this stream should behave
1
Ruby
Ruby
extract variable out of loop
1ed6ff1006fb5fd816b8b0267754b3113828e918
<ide><path>actionmailer/lib/action_mailer/mail_helper.rb <ide> def format_paragraph(text, len = 72, indent = 2) <ide> end <ide> end <ide> <add> indentation = " " * indent <ide> sentences.map { |sentence| <del> "#{" " * indent}#{sentence.join(' ')}" <add> "#{indentation}#{sentence.join(' ')}" <ide> }.join "\n" <ide> end <ide> end
1
Text
Text
add link to official string documentation
e5af318f13f3ca3c58e30a3ae9cf434f38396bc9
<ide><path>guide/english/java/strings/index.md <ide> The result will be: <ide> My <ide> ``` <ide> <add>**More Information:** <add>- [String Documentation](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html)
1
PHP
PHP
fix variable name
bf2d81458d18579443ffd2557298ef1e8aaf7fe3
<ide><path>src/Illuminate/Mail/Transport/LogTransport.php <ide> protected function getMimeEntityString(Swift_Mime_MimeEntity $entity) <ide> <ide> foreach ($entity->getChildren() as $children) <ide> { <del> $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($entity); <add> $string .= PHP_EOL.PHP_EOL.$this->getMimeEntityString($children); <ide> } <ide> <ide> return $string;
1
Ruby
Ruby
add strategy to livecheck dsl
72985277e84339912cc4f6771cfba12fd7e0b508
<ide><path>Library/Homebrew/livecheck.rb <ide> def initialize(formula) <ide> @regex = nil <ide> @skip = false <ide> @skip_msg = nil <add> @strategy = nil <ide> @url = nil <ide> end <ide> <ide> def skip? <ide> @skip <ide> end <ide> <add> # Sets the strategy instance variable to the provided symbol or returns the <add> # strategy instance variable when no argument is provided. The strategy <add> # symbols use snake case (e.g., `:page_match`) and correspond to the strategy <add> # file name. <add> # @param symbol [Symbol] symbol for the desired strategy <add> def strategy(symbol = nil) <add> case symbol <add> when nil <add> @strategy <add> when Symbol <add> @strategy = symbol <add> else <add> raise TypeError, "Livecheck#strategy expects a Symbol" <add> end <add> end <add> <ide> # Sets the url instance variable to the argument given, returns the url <ide> # instance variable when no argument is given. <ide> def url(val = nil) <ide> def to_hash <ide> "regex" => @regex, <ide> "skip" => @skip, <ide> "skip_msg" => @skip_msg, <add> "strategy" => @strategy, <ide> "url" => @url, <ide> } <ide> end <ide><path>Library/Homebrew/test/livecheck_spec.rb <ide> end <ide> end <ide> <add> describe "#strategy" do <add> it "returns nil if not set" do <add> expect(livecheckable.strategy).to be nil <add> end <add> <add> it "returns the Symbol if set" do <add> livecheckable.strategy(:page_match) <add> expect(livecheckable.strategy).to eq(:page_match) <add> end <add> <add> it "raises a TypeError if the argument isn't a Symbol" do <add> expect { <add> livecheckable.strategy("page_match") <add> }.to raise_error(TypeError, "Livecheck#strategy expects a Symbol") <add> end <add> end <add> <ide> describe "#url" do <ide> it "returns nil if unset" do <ide> expect(livecheckable.url).to be nil <ide> <ide> describe "#to_hash" do <ide> it "returns a Hash of all instance variables" do <del> expect(livecheckable.to_hash).to eq({ "regex"=>nil, "skip"=>false, "skip_msg"=>nil, "url"=>nil }) <add> expect(livecheckable.to_hash).to eq( <add> { <add> "regex" => nil, <add> "skip" => false, <add> "skip_msg" => nil, <add> "strategy" => nil, <add> "url" => nil, <add> }, <add> ) <ide> end <ide> end <ide> end
2
Go
Go
add a lockedmanageraction method to cluster…
250e05e42773a875d2fb8248b94fa72f2934a4b6
<ide><path>daemon/cluster/cluster.go <ide> func detectLockedError(err error) error { <ide> } <ide> return err <ide> } <add> <add>func (c *Cluster) lockedManagerAction(fn func(ctx context.Context, state nodeState) error) error { <add> c.mu.RLock() <add> defer c.mu.RUnlock() <add> <add> state := c.currentNodeState() <add> if !state.IsActiveManager() { <add> return c.errNoManager(state) <add> } <add> <add> ctx, cancel := c.getRequestContext() <add> defer cancel() <add> <add> return fn(ctx, state) <add>} <ide><path>daemon/cluster/networks.go <ide> func (c *Cluster) getNetworks(filters *swarmapi.ListNetworksRequest_Filters) ([] <ide> <ide> // GetNetwork returns a cluster network by an ID. <ide> func (c *Cluster) GetNetwork(input string) (apitypes.NetworkResource, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return apitypes.NetworkResource{}, c.errNoManager(state) <del> } <add> var network *swarmapi.Network <ide> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> network, err := getNetwork(ctx, state.controlClient, input) <del> if err != nil { <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> n, err := getNetwork(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <add> network = n <add> return nil <add> }); err != nil { <ide> return apitypes.NetworkResource{}, err <ide> } <ide> return convert.BasicNetworkFromGRPC(*network), nil <ide> func (c *Cluster) DetachNetwork(target string, containerID string) error { <ide> <ide> // CreateNetwork creates a new cluster managed network. <ide> func (c *Cluster) CreateNetwork(s apitypes.NetworkCreateRequest) (string, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return "", c.errNoManager(state) <del> } <del> <ide> if runconfig.IsPreDefinedNetwork(s.Name) { <ide> err := fmt.Errorf("%s is a pre-defined network and cannot be created", s.Name) <ide> return "", apierrors.NewRequestForbiddenError(err) <ide> } <ide> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> networkSpec := convert.BasicNetworkCreateToGRPC(s) <del> r, err := state.controlClient.CreateNetwork(ctx, &swarmapi.CreateNetworkRequest{Spec: &networkSpec}) <del> if err != nil { <add> var resp *swarmapi.CreateNetworkResponse <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> networkSpec := convert.BasicNetworkCreateToGRPC(s) <add> r, err := state.controlClient.CreateNetwork(ctx, &swarmapi.CreateNetworkRequest{Spec: &networkSpec}) <add> if err != nil { <add> return err <add> } <add> resp = r <add> return nil <add> }); err != nil { <ide> return "", err <ide> } <ide> <del> return r.Network.ID, nil <add> return resp.Network.ID, nil <ide> } <ide> <ide> // RemoveNetwork removes a cluster network. <ide> func (c *Cluster) RemoveNetwork(input string) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> network, err := getNetwork(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <ide> <del> network, err := getNetwork(ctx, state.controlClient, input) <del> if err != nil { <add> _, err = state.controlClient.RemoveNetwork(ctx, &swarmapi.RemoveNetworkRequest{NetworkID: network.ID}) <ide> return err <del> } <del> <del> _, err = state.controlClient.RemoveNetwork(ctx, &swarmapi.RemoveNetworkRequest{NetworkID: network.ID}) <del> return err <add> }) <ide> } <ide> <ide> func (c *Cluster) populateNetworkID(ctx context.Context, client swarmapi.ControlClient, s *types.ServiceSpec) error { <ide><path>daemon/cluster/nodes.go <ide> import ( <ide> types "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/daemon/cluster/convert" <ide> swarmapi "github.com/docker/swarmkit/api" <add> "golang.org/x/net/context" <ide> ) <ide> <ide> // GetNodes returns a list of all nodes known to a cluster. <ide> func (c *Cluster) GetNodes(options apitypes.NodeListOptions) ([]types.Node, erro <ide> <ide> // GetNode returns a node based on an ID. <ide> func (c *Cluster) GetNode(input string) (types.Node, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return types.Node{}, c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> node, err := getNode(ctx, state.controlClient, input) <del> if err != nil { <add> var node *swarmapi.Node <add> <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> n, err := getNode(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <add> node = n <add> return nil <add> }); err != nil { <ide> return types.Node{}, err <ide> } <add> <ide> return convert.NodeFromGRPC(*node), nil <ide> } <ide> <ide> // UpdateNode updates existing nodes properties. <ide> func (c *Cluster) UpdateNode(input string, version uint64, spec types.NodeSpec) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <del> <del> nodeSpec, err := convert.NodeSpecToGRPC(spec) <del> if err != nil { <del> return apierrors.NewBadRequestError(err) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> currentNode, err := getNode(ctx, state.controlClient, input) <del> if err != nil { <del> return err <del> } <del> <del> _, err = state.controlClient.UpdateNode( <del> ctx, <del> &swarmapi.UpdateNodeRequest{ <del> NodeID: currentNode.ID, <del> Spec: &nodeSpec, <del> NodeVersion: &swarmapi.Version{ <del> Index: version, <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> nodeSpec, err := convert.NodeSpecToGRPC(spec) <add> if err != nil { <add> return apierrors.NewBadRequestError(err) <add> } <add> <add> ctx, cancel := c.getRequestContext() <add> defer cancel() <add> <add> currentNode, err := getNode(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <add> <add> _, err = state.controlClient.UpdateNode( <add> ctx, <add> &swarmapi.UpdateNodeRequest{ <add> NodeID: currentNode.ID, <add> Spec: &nodeSpec, <add> NodeVersion: &swarmapi.Version{ <add> Index: version, <add> }, <ide> }, <del> }, <del> ) <del> return err <add> ) <add> return err <add> }) <ide> } <ide> <ide> // RemoveNode removes a node from a cluster <ide> func (c *Cluster) RemoveNode(input string, force bool) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> node, err := getNode(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <ide> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> node, err := getNode(ctx, state.controlClient, input) <del> if err != nil { <add> _, err = state.controlClient.RemoveNode(ctx, &swarmapi.RemoveNodeRequest{NodeID: node.ID, Force: force}) <ide> return err <del> } <del> <del> _, err = state.controlClient.RemoveNode(ctx, &swarmapi.RemoveNodeRequest{NodeID: node.ID, Force: force}) <del> return err <add> }) <ide> } <ide><path>daemon/cluster/secrets.go <ide> import ( <ide> types "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/daemon/cluster/convert" <ide> swarmapi "github.com/docker/swarmkit/api" <add> "golang.org/x/net/context" <ide> ) <ide> <ide> // GetSecret returns a secret from a managed swarm cluster <ide> func (c *Cluster) GetSecret(input string) (types.Secret, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return types.Secret{}, c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> secret, err := getSecret(ctx, state.controlClient, input) <del> if err != nil { <add> var secret *swarmapi.Secret <add> <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> s, err := getSecret(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <add> secret = s <add> return nil <add> }); err != nil { <ide> return types.Secret{}, err <ide> } <ide> return convert.SecretFromGRPC(secret), nil <ide> func (c *Cluster) GetSecrets(options apitypes.SecretListOptions) ([]types.Secret <ide> <ide> // CreateSecret creates a new secret in a managed swarm cluster. <ide> func (c *Cluster) CreateSecret(s types.SecretSpec) (string, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return "", c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> secretSpec := convert.SecretSpecToGRPC(s) <del> <del> r, err := state.controlClient.CreateSecret(ctx, <del> &swarmapi.CreateSecretRequest{Spec: &secretSpec}) <del> if err != nil { <add> var resp *swarmapi.CreateSecretResponse <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> secretSpec := convert.SecretSpecToGRPC(s) <add> <add> r, err := state.controlClient.CreateSecret(ctx, <add> &swarmapi.CreateSecretRequest{Spec: &secretSpec}) <add> if err != nil { <add> return err <add> } <add> resp = r <add> return nil <add> }); err != nil { <ide> return "", err <ide> } <del> <del> return r.Secret.ID, nil <add> return resp.Secret.ID, nil <ide> } <ide> <ide> // RemoveSecret removes a secret from a managed swarm cluster. <ide> func (c *Cluster) RemoveSecret(input string) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> secret, err := getSecret(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <ide> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <add> req := &swarmapi.RemoveSecretRequest{ <add> SecretID: secret.ID, <add> } <ide> <del> secret, err := getSecret(ctx, state.controlClient, input) <del> if err != nil { <add> _, err = state.controlClient.RemoveSecret(ctx, req) <ide> return err <del> } <del> <del> req := &swarmapi.RemoveSecretRequest{ <del> SecretID: secret.ID, <del> } <del> <del> _, err = state.controlClient.RemoveSecret(ctx, req) <del> return err <add> }) <ide> } <ide> <ide> // UpdateSecret updates a secret in a managed swarm cluster. <ide> // Note: this is not exposed to the CLI but is available from the API only <ide> func (c *Cluster) UpdateSecret(id string, version uint64, spec types.SecretSpec) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> secretSpec := convert.SecretSpecToGRPC(spec) <del> <del> _, err := state.controlClient.UpdateSecret(ctx, <del> &swarmapi.UpdateSecretRequest{ <del> SecretID: id, <del> SecretVersion: &swarmapi.Version{ <del> Index: version, <del> }, <del> Spec: &secretSpec, <del> }) <del> return err <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> secretSpec := convert.SecretSpecToGRPC(spec) <add> <add> _, err := state.controlClient.UpdateSecret(ctx, <add> &swarmapi.UpdateSecretRequest{ <add> SecretID: id, <add> SecretVersion: &swarmapi.Version{ <add> Index: version, <add> }, <add> Spec: &secretSpec, <add> }) <add> return err <add> }) <ide> } <ide><path>daemon/cluster/services.go <ide> func (c *Cluster) GetServices(options apitypes.ServiceListOptions) ([]types.Serv <ide> <ide> // GetService returns a service based on an ID or name. <ide> func (c *Cluster) GetService(input string) (types.Service, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return types.Service{}, c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> service, err := getService(ctx, state.controlClient, input) <del> if err != nil { <add> var service *swarmapi.Service <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> s, err := getService(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <add> service = s <add> return nil <add> }); err != nil { <ide> return types.Service{}, err <ide> } <ide> return convert.ServiceFromGRPC(*service), nil <ide> } <ide> <ide> // CreateService creates a new service in a managed swarm cluster. <ide> func (c *Cluster) CreateService(s types.ServiceSpec, encodedAuth string) (*apitypes.ServiceCreateResponse, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return nil, c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> err := c.populateNetworkID(ctx, state.controlClient, &s) <del> if err != nil { <del> return nil, err <del> } <add> var resp *apitypes.ServiceCreateResponse <add> err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> err := c.populateNetworkID(ctx, state.controlClient, &s) <add> if err != nil { <add> return err <add> } <ide> <del> serviceSpec, err := convert.ServiceSpecToGRPC(s) <del> if err != nil { <del> return nil, apierrors.NewBadRequestError(err) <del> } <add> serviceSpec, err := convert.ServiceSpecToGRPC(s) <add> if err != nil { <add> return apierrors.NewBadRequestError(err) <add> } <ide> <del> ctnr := serviceSpec.Task.GetContainer() <del> if ctnr == nil { <del> return nil, errors.New("service does not use container tasks") <del> } <add> ctnr := serviceSpec.Task.GetContainer() <add> if ctnr == nil { <add> return errors.New("service does not use container tasks") <add> } <ide> <del> if encodedAuth != "" { <del> ctnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth} <del> } <add> if encodedAuth != "" { <add> ctnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth} <add> } <ide> <del> // retrieve auth config from encoded auth <del> authConfig := &apitypes.AuthConfig{} <del> if encodedAuth != "" { <del> if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuth))).Decode(authConfig); err != nil { <del> logrus.Warnf("invalid authconfig: %v", err) <add> // retrieve auth config from encoded auth <add> authConfig := &apitypes.AuthConfig{} <add> if encodedAuth != "" { <add> if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuth))).Decode(authConfig); err != nil { <add> logrus.Warnf("invalid authconfig: %v", err) <add> } <ide> } <del> } <ide> <del> resp := &apitypes.ServiceCreateResponse{} <add> resp = &apitypes.ServiceCreateResponse{} <add> <add> // pin image by digest <add> if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" { <add> digestImage, err := c.imageWithDigestString(ctx, ctnr.Image, authConfig) <add> if err != nil { <add> logrus.Warnf("unable to pin image %s to digest: %s", ctnr.Image, err.Error()) <add> resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", ctnr.Image, err.Error())) <add> } else if ctnr.Image != digestImage { <add> logrus.Debugf("pinning image %s by digest: %s", ctnr.Image, digestImage) <add> ctnr.Image = digestImage <add> } else { <add> logrus.Debugf("creating service using supplied digest reference %s", ctnr.Image) <add> } <add> } <ide> <del> // pin image by digest <del> if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" { <del> digestImage, err := c.imageWithDigestString(ctx, ctnr.Image, authConfig) <add> r, err := state.controlClient.CreateService(ctx, &swarmapi.CreateServiceRequest{Spec: &serviceSpec}) <ide> if err != nil { <del> logrus.Warnf("unable to pin image %s to digest: %s", ctnr.Image, err.Error()) <del> resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", ctnr.Image, err.Error())) <del> } else if ctnr.Image != digestImage { <del> logrus.Debugf("pinning image %s by digest: %s", ctnr.Image, digestImage) <del> ctnr.Image = digestImage <del> } else { <del> logrus.Debugf("creating service using supplied digest reference %s", ctnr.Image) <add> return err <ide> } <del> } <del> <del> r, err := state.controlClient.CreateService(ctx, &swarmapi.CreateServiceRequest{Spec: &serviceSpec}) <del> if err != nil { <del> return nil, err <del> } <ide> <del> resp.ID = r.Service.ID <del> return resp, nil <add> resp.ID = r.Service.ID <add> return nil <add> }) <add> return resp, err <ide> } <ide> <ide> // UpdateService updates existing service to match new properties. <ide> func (c *Cluster) UpdateService(serviceIDOrName string, version uint64, spec types.ServiceSpec, encodedAuth string, registryAuthFrom string) (*apitypes.ServiceUpdateResponse, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return nil, c.errNoManager(state) <del> } <add> var resp *apitypes.ServiceUpdateResponse <ide> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <add> err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <ide> <del> err := c.populateNetworkID(ctx, state.controlClient, &spec) <del> if err != nil { <del> return nil, err <del> } <add> err := c.populateNetworkID(ctx, state.controlClient, &spec) <add> if err != nil { <add> return err <add> } <ide> <del> serviceSpec, err := convert.ServiceSpecToGRPC(spec) <del> if err != nil { <del> return nil, apierrors.NewBadRequestError(err) <del> } <add> serviceSpec, err := convert.ServiceSpecToGRPC(spec) <add> if err != nil { <add> return apierrors.NewBadRequestError(err) <add> } <ide> <del> currentService, err := getService(ctx, state.controlClient, serviceIDOrName) <del> if err != nil { <del> return nil, err <del> } <add> currentService, err := getService(ctx, state.controlClient, serviceIDOrName) <add> if err != nil { <add> return err <add> } <ide> <del> newCtnr := serviceSpec.Task.GetContainer() <del> if newCtnr == nil { <del> return nil, errors.New("service does not use container tasks") <del> } <add> newCtnr := serviceSpec.Task.GetContainer() <add> if newCtnr == nil { <add> return errors.New("service does not use container tasks") <add> } <ide> <del> if encodedAuth != "" { <del> newCtnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth} <del> } else { <del> // this is needed because if the encodedAuth isn't being updated then we <del> // shouldn't lose it, and continue to use the one that was already present <del> var ctnr *swarmapi.ContainerSpec <del> switch registryAuthFrom { <del> case apitypes.RegistryAuthFromSpec, "": <del> ctnr = currentService.Spec.Task.GetContainer() <del> case apitypes.RegistryAuthFromPreviousSpec: <del> if currentService.PreviousSpec == nil { <del> return nil, errors.New("service does not have a previous spec") <add> if encodedAuth != "" { <add> newCtnr.PullOptions = &swarmapi.ContainerSpec_PullOptions{RegistryAuth: encodedAuth} <add> } else { <add> // this is needed because if the encodedAuth isn't being updated then we <add> // shouldn't lose it, and continue to use the one that was already present <add> var ctnr *swarmapi.ContainerSpec <add> switch registryAuthFrom { <add> case apitypes.RegistryAuthFromSpec, "": <add> ctnr = currentService.Spec.Task.GetContainer() <add> case apitypes.RegistryAuthFromPreviousSpec: <add> if currentService.PreviousSpec == nil { <add> return errors.New("service does not have a previous spec") <add> } <add> ctnr = currentService.PreviousSpec.Task.GetContainer() <add> default: <add> return errors.New("unsupported registryAuthFrom value") <add> } <add> if ctnr == nil { <add> return errors.New("service does not use container tasks") <add> } <add> newCtnr.PullOptions = ctnr.PullOptions <add> // update encodedAuth so it can be used to pin image by digest <add> if ctnr.PullOptions != nil { <add> encodedAuth = ctnr.PullOptions.RegistryAuth <ide> } <del> ctnr = currentService.PreviousSpec.Task.GetContainer() <del> default: <del> return nil, errors.New("unsupported registryAuthFrom value") <del> } <del> if ctnr == nil { <del> return nil, errors.New("service does not use container tasks") <del> } <del> newCtnr.PullOptions = ctnr.PullOptions <del> // update encodedAuth so it can be used to pin image by digest <del> if ctnr.PullOptions != nil { <del> encodedAuth = ctnr.PullOptions.RegistryAuth <ide> } <del> } <ide> <del> // retrieve auth config from encoded auth <del> authConfig := &apitypes.AuthConfig{} <del> if encodedAuth != "" { <del> if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuth))).Decode(authConfig); err != nil { <del> logrus.Warnf("invalid authconfig: %v", err) <add> // retrieve auth config from encoded auth <add> authConfig := &apitypes.AuthConfig{} <add> if encodedAuth != "" { <add> if err := json.NewDecoder(base64.NewDecoder(base64.URLEncoding, strings.NewReader(encodedAuth))).Decode(authConfig); err != nil { <add> logrus.Warnf("invalid authconfig: %v", err) <add> } <ide> } <del> } <ide> <del> resp := &apitypes.ServiceUpdateResponse{} <del> <del> // pin image by digest <del> if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" { <del> digestImage, err := c.imageWithDigestString(ctx, newCtnr.Image, authConfig) <del> if err != nil { <del> logrus.Warnf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error()) <del> resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error())) <del> } else if newCtnr.Image != digestImage { <del> logrus.Debugf("pinning image %s by digest: %s", newCtnr.Image, digestImage) <del> newCtnr.Image = digestImage <del> } else { <del> logrus.Debugf("updating service using supplied digest reference %s", newCtnr.Image) <add> resp := &apitypes.ServiceUpdateResponse{} <add> <add> // pin image by digest <add> if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" { <add> digestImage, err := c.imageWithDigestString(ctx, newCtnr.Image, authConfig) <add> if err != nil { <add> logrus.Warnf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error()) <add> resp.Warnings = append(resp.Warnings, fmt.Sprintf("unable to pin image %s to digest: %s", newCtnr.Image, err.Error())) <add> } else if newCtnr.Image != digestImage { <add> logrus.Debugf("pinning image %s by digest: %s", newCtnr.Image, digestImage) <add> newCtnr.Image = digestImage <add> } else { <add> logrus.Debugf("updating service using supplied digest reference %s", newCtnr.Image) <add> } <ide> } <del> } <ide> <del> _, err = state.controlClient.UpdateService( <del> ctx, <del> &swarmapi.UpdateServiceRequest{ <del> ServiceID: currentService.ID, <del> Spec: &serviceSpec, <del> ServiceVersion: &swarmapi.Version{ <del> Index: version, <add> _, err = state.controlClient.UpdateService( <add> ctx, <add> &swarmapi.UpdateServiceRequest{ <add> ServiceID: currentService.ID, <add> Spec: &serviceSpec, <add> ServiceVersion: &swarmapi.Version{ <add> Index: version, <add> }, <ide> }, <del> }, <del> ) <del> <add> ) <add> return err <add> }) <ide> return resp, err <ide> } <ide> <ide> // RemoveService removes a service from a managed swarm cluster. <ide> func (c *Cluster) RemoveService(input string) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> service, err := getService(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <ide> <del> service, err := getService(ctx, state.controlClient, input) <del> if err != nil { <add> _, err = state.controlClient.RemoveService(ctx, &swarmapi.RemoveServiceRequest{ServiceID: service.ID}) <ide> return err <del> } <del> <del> _, err = state.controlClient.RemoveService(ctx, &swarmapi.RemoveServiceRequest{ServiceID: service.ID}) <del> return err <add> }) <ide> } <ide> <ide> // ServiceLogs collects service logs and writes them back to `config.OutStream` <ide><path>daemon/cluster/swarm.go <ide> func (c *Cluster) Join(req types.JoinRequest) error { <ide> <ide> // Inspect retrieves the configuration properties of a managed swarm cluster. <ide> func (c *Cluster) Inspect() (types.Swarm, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return types.Swarm{}, c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> swarm, err := getSwarm(ctx, state.controlClient) <del> if err != nil { <add> var swarm *swarmapi.Cluster <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> s, err := getSwarm(ctx, state.controlClient) <add> if err != nil { <add> return err <add> } <add> swarm = s <add> return nil <add> }); err != nil { <ide> return types.Swarm{}, err <ide> } <del> <ide> return convert.SwarmFromGRPC(*swarm), nil <ide> } <ide> <ide> // Update updates configuration of a managed swarm cluster. <ide> func (c *Cluster) Update(version uint64, spec types.Spec, flags types.UpdateFlags) error { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> swarm, err := getSwarm(ctx, state.controlClient) <del> if err != nil { <del> return err <del> } <add> return c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> swarm, err := getSwarm(ctx, state.controlClient) <add> if err != nil { <add> return err <add> } <ide> <del> // In update, client should provide the complete spec of the swarm, including <del> // Name and Labels. If a field is specified with 0 or nil, then the default value <del> // will be used to swarmkit. <del> clusterSpec, err := convert.SwarmSpecToGRPC(spec) <del> if err != nil { <del> return apierrors.NewBadRequestError(err) <del> } <add> // In update, client should provide the complete spec of the swarm, including <add> // Name and Labels. If a field is specified with 0 or nil, then the default value <add> // will be used to swarmkit. <add> clusterSpec, err := convert.SwarmSpecToGRPC(spec) <add> if err != nil { <add> return apierrors.NewBadRequestError(err) <add> } <ide> <del> _, err = state.controlClient.UpdateCluster( <del> ctx, <del> &swarmapi.UpdateClusterRequest{ <del> ClusterID: swarm.ID, <del> Spec: &clusterSpec, <del> ClusterVersion: &swarmapi.Version{ <del> Index: version, <del> }, <del> Rotation: swarmapi.KeyRotation{ <del> WorkerJoinToken: flags.RotateWorkerToken, <del> ManagerJoinToken: flags.RotateManagerToken, <del> ManagerUnlockKey: flags.RotateManagerUnlockKey, <add> _, err = state.controlClient.UpdateCluster( <add> ctx, <add> &swarmapi.UpdateClusterRequest{ <add> ClusterID: swarm.ID, <add> Spec: &clusterSpec, <add> ClusterVersion: &swarmapi.Version{ <add> Index: version, <add> }, <add> Rotation: swarmapi.KeyRotation{ <add> WorkerJoinToken: flags.RotateWorkerToken, <add> ManagerJoinToken: flags.RotateManagerToken, <add> ManagerUnlockKey: flags.RotateManagerUnlockKey, <add> }, <ide> }, <del> }, <del> ) <del> return err <add> ) <add> return err <add> }) <ide> } <ide> <ide> // GetUnlockKey returns the unlock key for the swarm. <ide> func (c *Cluster) GetUnlockKey() (string, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <add> var resp *swarmapi.GetUnlockKeyResponse <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> client := swarmapi.NewCAClient(state.grpcConn) <ide> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return "", c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> client := swarmapi.NewCAClient(state.grpcConn) <del> <del> r, err := client.GetUnlockKey(ctx, &swarmapi.GetUnlockKeyRequest{}) <del> if err != nil { <add> r, err := client.GetUnlockKey(ctx, &swarmapi.GetUnlockKeyRequest{}) <add> if err != nil { <add> return err <add> } <add> resp = r <add> return nil <add> }); err != nil { <ide> return "", err <ide> } <del> <del> if len(r.UnlockKey) == 0 { <add> if len(resp.UnlockKey) == 0 { <ide> // no key <ide> return "", nil <ide> } <del> <del> return encryption.HumanReadableKey(r.UnlockKey), nil <add> return encryption.HumanReadableKey(resp.UnlockKey), nil <ide> } <ide> <ide> // UnlockSwarm provides a key to decrypt data that is encrypted at rest. <ide><path>daemon/cluster/tasks.go <ide> import ( <ide> types "github.com/docker/docker/api/types/swarm" <ide> "github.com/docker/docker/daemon/cluster/convert" <ide> swarmapi "github.com/docker/swarmkit/api" <add> "golang.org/x/net/context" <ide> ) <ide> <ide> // GetTasks returns a list of tasks matching the filter options. <ide> func (c *Cluster) GetTasks(options apitypes.TaskListOptions) ([]types.Task, erro <ide> <ide> // GetTask returns a task by an ID. <ide> func (c *Cluster) GetTask(input string) (types.Task, error) { <del> c.mu.RLock() <del> defer c.mu.RUnlock() <del> <del> state := c.currentNodeState() <del> if !state.IsActiveManager() { <del> return types.Task{}, c.errNoManager(state) <del> } <del> <del> ctx, cancel := c.getRequestContext() <del> defer cancel() <del> <del> task, err := getTask(ctx, state.controlClient, input) <del> if err != nil { <add> var task *swarmapi.Task <add> if err := c.lockedManagerAction(func(ctx context.Context, state nodeState) error { <add> t, err := getTask(ctx, state.controlClient, input) <add> if err != nil { <add> return err <add> } <add> task = t <add> return nil <add> }); err != nil { <ide> return types.Task{}, err <ide> } <ide> return convert.TaskFromGRPC(*task), nil
7
Ruby
Ruby
move utilities out of `react_native_pods` - part 2
4f732ba9ee2a1e162729c97d5c12ea771b3a424a
<ide><path>scripts/cocoapods/__tests__/test_utils/InstallerMock.rb <ide> def target_with_name(name) <ide> <ide> class PodsProjectMock <ide> attr_reader :targets <add> attr_reader :native_targets <ide> attr_reader :path <ide> attr_reader :build_configurations <ide> @pod_group <add> attr_reader :save_invocation_count <ide> <del> def initialize(targets = [], pod_group = {}, path = "test/path-pod.xcodeproj", build_configurations = []) <add> def initialize(targets = [], pod_group = {}, path = "test/path-pod.xcodeproj", build_configurations = [], native_targets: []) <ide> @targets = targets <ide> @pod_group = pod_group <ide> @path = path <ide> @build_configurations = build_configurations <add> @save_invocation_count = 0 <add> @native_targets = native_targets <ide> end <ide> <ide> def pod_group(name) <ide> return @pod_group[name] <ide> end <ide> <ide> def save() <add> @save_invocation_count += 1 <ide> end <ide> end <ide> <ide> def initialize(user_project = UserProjectMock.new) <ide> class UserProjectMock <ide> attr_reader :path <ide> attr_reader :build_configurations <add> attr_reader :native_targets <ide> <del> def initialize(path = "/test/path.xcproj", build_configurations = []) <add> attr_reader :save_invocation_count <add> <add> <add> def initialize(path = "/test/path.xcproj", build_configurations = [], native_targets: []) <ide> @path = path <ide> @build_configurations = build_configurations <add> @native_targets = native_targets <add> @save_invocation_count = 0 <ide> end <ide> <ide> def save() <add> @save_invocation_count += 1 <ide> end <ide> end <ide> <ide><path>scripts/cocoapods/__tests__/utils-test.rb <ide> def test_hasPod_whenInstallerHasPod_returnTrue <ide> # ============================ # <ide> def test_excludeArchitectures_whenHermesEngineIsNotIncluded_excludeNothing <ide> # Arrange <del> user_project_mock = UserProjectMock.new("a/path", [ <del> BuildConfigurationMock.new("Debug"), <del> BuildConfigurationMock.new("Release"), <del> ]) <add> user_project_mock = prepare_empty_user_project_mock() <add> pods_projects_mock = PodsProjectMock.new() <ide> installer = InstallerMock.new(PodsProjectMock.new(), [ <ide> AggregatedProjectMock.new(user_project_mock) <ide> ]) <ide> def test_excludeArchitectures_whenHermesEngineIsNotIncluded_excludeNothing <ide> user_project_mock.build_configurations.each do |config| <ide> assert_equal(config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"], "") <ide> end <del> <add> assert_equal(user_project_mock.save_invocation_count, 1) <add> assert_equal(pods_projects_mock.save_invocation_count, 0) <ide> end <ide> <ide> def test_excludeArchitectures_whenHermesEngineIsIncluded_excludeI386 <ide> # Arrange <del> user_project_mock = UserProjectMock.new("a/path", [ <del> BuildConfigurationMock.new("Debug"), <del> BuildConfigurationMock.new("Release"), <del> ]) <del> installer = InstallerMock.new(PodsProjectMock.new([], {"hermes-engine" => {}}), [ <add> user_project_mock = prepare_empty_user_project_mock() <add> pods_projects_mock = PodsProjectMock.new([], {"hermes-engine" => {}}) <add> installer = InstallerMock.new(pods_projects_mock, [ <ide> AggregatedProjectMock.new(user_project_mock) <ide> ]) <ide> <ide> def test_excludeArchitectures_whenHermesEngineIsIncluded_excludeI386 <ide> user_project_mock.build_configurations.each do |config| <ide> assert_equal(config.build_settings["EXCLUDED_ARCHS[sdk=iphonesimulator*]"], "i386") <ide> end <add> <add> assert_equal(user_project_mock.save_invocation_count, 1) <add> assert_equal(pods_projects_mock.save_invocation_count, 1) <add> end <add> <add> # ================= # <add> # Test - Fix Config # <add> # ================= # <add> <add> def test_fixLibrarySearchPath_whenThereIsNoSearchPaths_doNothing <add> # Arrange <add> buildConfig = BuildConfigurationMock.new("Debug") <add> <add> # Act <add> ReactNativePodsUtils.fix_library_search_path(buildConfig) <add> <add> # Assert <add> assert_nil(buildConfig.build_settings["LIBRARY_SEARCH_PATHS"]) <add> end <add> <add> def test_fixLibrarySearchPath_whenThereAreSearchPathsAndSwiftUnescaped_removesSwift5_5 <add> # Arrange <add> buildConfig = BuildConfigurationMock.new("Debug", {"LIBRARY_SEARCH_PATHS" => [ <add> "$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)", <add> "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"", <add> "$(SDKROOT)/usr/lib/swift" <add> ]}) <add> <add> # Act <add> ReactNativePodsUtils.fix_library_search_path(buildConfig) <add> <add> # Assert <add> assert_equal(buildConfig.build_settings["LIBRARY_SEARCH_PATHS"], ["$(SDKROOT)/usr/lib/swift"]) <add> end <add> <add> def test_fixLibrarySearchPath_whenThereAreSearchPathsAndSwiftEscaped_removesSwift5_5 <add> # Arrange <add> buildConfig = BuildConfigurationMock.new("Debug", {"LIBRARY_SEARCH_PATHS" => [ <add> "$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)", <add> "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"", <add> "another/path", <add> "\"$(SDKROOT)/usr/lib/swift\"" <add> ]}) <add> <add> # Act <add> ReactNativePodsUtils.fix_library_search_path(buildConfig) <add> <add> # Assert <add> assert_equal(buildConfig.build_settings["LIBRARY_SEARCH_PATHS"], ["another/path", "\"$(SDKROOT)/usr/lib/swift\""]) <ide> end <ide> <add> def test_fixLibrarySearchPath_whenThereAreSearchPathsAndNoSwift_removesSwift5_5AndAddsSwiftAsFirst <add> # Arrange <add> buildConfig = BuildConfigurationMock.new("Debug", {"LIBRARY_SEARCH_PATHS" => [ <add> "another/path" <add> ]}) <add> <add> # Act <add> ReactNativePodsUtils.fix_library_search_path(buildConfig) <add> <add> # Assert <add> assert_equal(buildConfig.build_settings["LIBRARY_SEARCH_PATHS"], ["$(SDKROOT)/usr/lib/swift", "another/path"]) <add> end <add> <add> # ============================== # <add> # Test - Fix Library Search Path # <add> # ============================== # <add> <add> def test_fixLibrarySearchPaths_correctlySetsTheSearchPathsForAllProjects <add> firstTarget = prepare_target("FirstTarget") <add> secondTarget = prepare_target("SecondTarget") <add> thirdTarget = prepare_target("ThirdTarget") <add> user_project_mock = UserProjectMock.new("a/path", [ <add> prepare_config("Debug"), <add> prepare_config("Release"), <add> ], <add> :native_targets => [ <add> firstTarget, <add> secondTarget <add> ] <add> ) <add> pods_projects_mock = PodsProjectMock.new([], {"hermes-engine" => {}}, :native_targets => [ <add> thirdTarget <add> ]) <add> installer = InstallerMock.new(pods_projects_mock, [ <add> AggregatedProjectMock.new(user_project_mock) <add> ]) <add> <add> # Act <add> ReactNativePodsUtils.fix_library_search_paths(installer) <add> <add> # Assert <add> user_project_mock.build_configurations.each do |config| <add> assert_equal(config.build_settings["LIBRARY_SEARCH_PATHS"], [ <add> "$(SDKROOT)/usr/lib/swift", "another/path" <add> ]) <add> end <add> <add> user_project_mock.native_targets.each do |target| <add> target.build_configurations.each do |config| <add> assert_equal(config.build_settings["LIBRARY_SEARCH_PATHS"], [ <add> "$(SDKROOT)/usr/lib/swift", "another/path" <add> ]) <add> end <add> end <add> <add> pods_projects_mock.native_targets.each do |target| <add> target.build_configurations.each do |config| <add> assert_equal(config.build_settings["LIBRARY_SEARCH_PATHS"], [ <add> "$(SDKROOT)/usr/lib/swift", "another/path" <add> ]) <add> end <add> end <add> <add> assert_equal(user_project_mock.save_invocation_count, 1) <add> assert_equal(pods_projects_mock.save_invocation_count, 1) <add> end <add> <add> # ==================================== # <add> # Test - Set Node_Modules User Setting # <add> # ==================================== # <add> <add> def test_setNodeModulesUserSettings_addTheUserSetting <add> # Arrange <add> react_native_path = "react_native/node_modules" <add> user_project_mock = prepare_empty_user_project_mock() <add> pods_projects_mock = PodsProjectMock.new([], {"hermes-engine" => {}}) <add> installer = InstallerMock.new(pods_projects_mock, [ <add> AggregatedProjectMock.new(user_project_mock) <add> ]) <add> <add> # Act <add> ReactNativePodsUtils.set_node_modules_user_settings(installer, react_native_path) <add> <add> # Assert <add> user_project_mock.build_configurations.each do |config| <add> assert_equal(config.build_settings["REACT_NATIVE_PATH"], "${PODS_ROOT}/../#{react_native_path}") <add> end <add> <add> assert_equal(user_project_mock.save_invocation_count, 1) <add> assert_equal(pods_projects_mock.save_invocation_count, 1) <add> assert_equal(Pod::UI.collected_messages, ["Setting REACT_NATIVE build settings"]) <add> end <add>end <add> <add>def prepare_empty_user_project_mock <add> return UserProjectMock.new("a/path", [ <add> BuildConfigurationMock.new("Debug"), <add> BuildConfigurationMock.new("Release"), <add> ]) <add>end <add> <add>def prepare_config(config_name) <add> return BuildConfigurationMock.new(config_name, {"LIBRARY_SEARCH_PATHS" => [ <add> "$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)", <add> "\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"", <add> "another/path", <add> ]}) <add>end <add> <add>def prepare_target(name) <add> return TargetMock.new(name, [ <add> prepare_config("Debug"), <add> prepare_config("Release") <add> ]) <ide> end <ide><path>scripts/cocoapods/utils.rb <ide> def self.exclude_i386_architecture_while_using_hermes(installer) <ide> project.save() <ide> end <ide> end <add> <add> def self.set_node_modules_user_settings(installer, react_native_path) <add> Pod::UI.puts("Setting REACT_NATIVE build settings") <add> projects = installer.aggregate_targets <add> .map{ |t| t.user_project } <add> .uniq{ |p| p.path } <add> .push(installer.pods_project) <add> <add> projects.each do |project| <add> project.build_configurations.each do |config| <add> config.build_settings["REACT_NATIVE_PATH"] = File.join("${PODS_ROOT}", "..", react_native_path) <add> end <add> <add> project.save() <add> end <add> end <add> <add> def self.fix_library_search_paths(installer) <add> projects = installer.aggregate_targets <add> .map{ |t| t.user_project } <add> .uniq{ |p| p.path } <add> .push(installer.pods_project) <add> <add> projects.each do |project| <add> project.build_configurations.each do |config| <add> ReactNativePodsUtils.fix_library_search_path(config) <add> end <add> project.native_targets.each do |target| <add> target.build_configurations.each do |config| <add> ReactNativePodsUtils.fix_library_search_path(config) <add> end <add> end <add> project.save() <add> end <add> end <add> <add> private <add> <add> def self.fix_library_search_path(config) <add> lib_search_paths = config.build_settings["LIBRARY_SEARCH_PATHS"] <add> <add> if lib_search_paths == nil <add> # No search paths defined, return immediately <add> return <add> end <add> <add> # $(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME) causes problem with Xcode 12.5 + arm64 (Apple M1) <add> # since the libraries there are only built for x86_64 and i386. <add> lib_search_paths.delete("$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)") <add> lib_search_paths.delete("\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"") <add> <add> if !(lib_search_paths.include?("$(SDKROOT)/usr/lib/swift") || lib_search_paths.include?("\"$(SDKROOT)/usr/lib/swift\"")) <add> # however, $(SDKROOT)/usr/lib/swift is required, at least if user is not running CocoaPods 1.11 <add> lib_search_paths.insert(0, "$(SDKROOT)/usr/lib/swift") <add> end <add> end <add> <add> <ide> end <ide><path>scripts/react_native_pods.rb <ide> def use_flipper!(versions = {}, configurations: ['Debug']) <ide> use_flipper_pods(versions, :configurations => configurations) <ide> end <ide> <del>def fix_library_search_paths(installer) <del> def fix_config(config) <del> lib_search_paths = config.build_settings["LIBRARY_SEARCH_PATHS"] <del> if lib_search_paths <del> if lib_search_paths.include?("$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)") || lib_search_paths.include?("\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"") <del> # $(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME) causes problem with Xcode 12.5 + arm64 (Apple M1) <del> # since the libraries there are only built for x86_64 and i386. <del> lib_search_paths.delete("$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)") <del> lib_search_paths.delete("\"$(TOOLCHAIN_DIR)/usr/lib/swift-5.0/$(PLATFORM_NAME)\"") <del> if !(lib_search_paths.include?("$(SDKROOT)/usr/lib/swift") || lib_search_paths.include?("\"$(SDKROOT)/usr/lib/swift\"")) <del> # however, $(SDKROOT)/usr/lib/swift is required, at least if user is not running CocoaPods 1.11 <del> lib_search_paths.insert(0, "$(SDKROOT)/usr/lib/swift") <del> end <del> end <del> end <del> end <del> <del> projects = installer.aggregate_targets <del> .map{ |t| t.user_project } <del> .uniq{ |p| p.path } <del> .push(installer.pods_project) <del> <del> projects.each do |project| <del> project.build_configurations.each do |config| <del> fix_config(config) <del> end <del> project.native_targets.each do |target| <del> target.build_configurations.each do |config| <del> fix_config(config) <del> end <del> end <del> project.save() <del> end <del>end <del> <del>def set_node_modules_user_settings(installer, react_native_path) <del> puts "Setting REACT_NATIVE build settings" <del> projects = installer.aggregate_targets <del> .map{ |t| t.user_project } <del> .uniq{ |p| p.path } <del> .push(installer.pods_project) <del> <del> projects.each do |project| <del> project.build_configurations.each do |config| <del> config.build_settings["REACT_NATIVE_PATH"] = File.join("${PODS_ROOT}", "..", react_native_path) <del> end <del> <del> project.save() <del> end <del>end <del> <ide> def react_native_post_install(installer, react_native_path = "../node_modules/react-native") <ide> if ReactNativePodsUtils.has_pod(installer, 'Flipper') <ide> flipper_post_install(installer) <ide> end <ide> <ide> ReactNativePodsUtils.exclude_i386_architecture_while_using_hermes(installer) <del> fix_library_search_paths(installer) <add> ReactNativePodsUtils.fix_library_search_paths(installer) <ide> <ide> cpp_flags = DEFAULT_OTHER_CPLUSPLUSFLAGS <ide> if ENV['RCT_NEW_ARCH_ENABLED'] == '1' <ide> cpp_flags = NEW_ARCH_OTHER_CPLUSPLUSFLAGS <ide> end <ide> modify_flags_for_new_architecture(installer, cpp_flags) <ide> <del> set_node_modules_user_settings(installer, react_native_path) <add> ReactNativePodsUtils.set_node_modules_user_settings(installer, react_native_path) <ide> <ide> puts "Pod install took #{Time.now.to_i - $START_TIME} [s] to run" <ide> end
4
PHP
PHP
add another method for more fluency
75fa3461ee998bc1f8475de97917b94a25d5d35c
<ide><path>src/Illuminate/Filesystem/FilesystemManager.php <ide> public function __construct($app) <ide> $this->app = $app; <ide> } <ide> <add> /** <add> * Get a filesystem instance. <add> * <add> * @param string $name <add> * @return \Illuminate\Contracts\Filesystem\Filesystem <add> */ <add> public function drive($name = null) <add> { <add> return $this->disk($name); <add> } <add> <ide> /** <ide> * Get a filesystem instance. <ide> *
1
Javascript
Javascript
remove unneeded test statement
ff5766fc2e4c2964ff4278a08ce7146b59aa141a
<ide><path>test/parallel/test-event-emitter-subclass.js <ide> function MyEE(cb) { <ide> <ide> const myee = new MyEE(common.mustCall()); <ide> <del>myee.hasOwnProperty('usingDomains'); <del> <ide> Object.setPrototypeOf(ErrorEE.prototype, EventEmitter.prototype); <ide> Object.setPrototypeOf(ErrorEE, EventEmitter); <ide> function ErrorEE() {
1
PHP
PHP
fix geturlrange docblock.
d298373a22f95ab5d13cfdf0cb3b3baa0d90e8f5
<ide><path>src/Illuminate/Contracts/Pagination/LengthAwarePaginator.php <ide> interface LengthAwarePaginator extends Paginator <ide> * <ide> * @param int $start <ide> * @param int $end <del> * @return string <add> * @return array <ide> */ <ide> public function getUrlRange($start, $end); <ide> <ide><path>src/Illuminate/Pagination/AbstractPaginator.php <ide> public function previousPageUrl() <ide> * <ide> * @param int $start <ide> * @param int $end <del> * @return string <add> * @return array <ide> */ <ide> public function getUrlRange($start, $end) <ide> {
2
Mixed
Python
remove dependency on pytest for running tests
35401fe50fa3e460b2a4422630b017f106c79e03
<ide><path>README.md <ide> pip install [--editable] . <ide> <ide> A series of tests are included for the library and the example scripts. Library tests can be found in the [tests folder](https://github.com/huggingface/transformers/tree/master/transformers/tests) and examples tests in the [examples folder](https://github.com/huggingface/transformers/tree/master/examples). <ide> <del>These tests can be run using `pytest` (install pytest if needed with `pip install pytest`). <add>These tests can be run using `unittest` or `pytest` (install pytest if needed with `pip install pytest`). <ide> <ide> Depending on which framework is installed (TensorFlow 2.0 and/or PyTorch), the irrelevant tests will be skipped. Ensure that both frameworks are installed if you want to execute all tests. <ide> <ide> You can run the tests from the root of the cloned repository with the commands: <ide> <add>```bash <add>python -m unittest discover -s transformers/tests -p "*test.py" -t . <add>python -m unittest discover -s examples -p "*test.py" -t examples <add>``` <add> <add>or <add> <ide> ```bash <ide> python -m pytest -sv ./transformers/tests/ <ide> python -m pytest -sv ./examples/ <ide> ``` <ide> <add>By default, slow tests are skipped. Set the `RUN_SLOW` environment variable to `yes` to run them. <add> <ide> ### Do you want to run a Transformer model on a mobile device? <ide> <ide> You should check out our [`swift-coreml-transformers`](https://github.com/huggingface/swift-coreml-transformers) repo. <ide><path>docs/source/installation.md <ide> pip install [--editable] . <ide> <ide> An extensive test suite is included to test the library behavior and several examples. Library tests can be found in the [tests folder](https://github.com/huggingface/transformers/tree/master/transformers/tests) and examples tests in the [examples folder](https://github.com/huggingface/transformers/tree/master/examples). <ide> <del>Tests can be run using `pytest` (install pytest if needed with `pip install pytest`). <add>Tests can be run using `unittest` or `pytest` (install pytest if needed with `pip install pytest`). <ide> <ide> Run all the tests from the root of the cloned repository with the commands: <ide> <add>```bash <add>python -m unittest discover -s transformers/tests -p "*test.py" -t . <add>python -m unittest discover -s examples -p "*test.py" -t examples <add>``` <add> <add>or <add> <ide> ``` bash <ide> python -m pytest -sv ./transformers/tests/ <ide> python -m pytest -sv ./examples/ <ide> ``` <ide> <add>By default, slow tests are skipped. Set the `RUN_SLOW` environment variable to `yes` to run them. <add> <ide> ## OpenAI GPT original tokenization workflow <ide> <ide> If you want to reproduce the original tokenization process of the `OpenAI GPT` paper, you will need to install `ftfy` (use version 4.4.3 if you are using Python 2) and `SpaCy`: <ide><path>setup.py <ide> 'transformers-cli' <ide> ], <ide> # python_requires='>=3.5.0', <del> tests_require=['pytest'], <ide> classifiers=[ <ide> 'Intended Audience :: Science/Research', <ide> 'License :: OSI Approved :: Apache Software License', <ide><path>templates/adding_a_new_model/tests/modeling_tf_xxx_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import sys <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import XxxConfig, is_tf_available <ide> <ide> TFXxxForTokenClassification, <ide> TFXxxForQuestionAnswering, <ide> TF_XXX_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFXxxModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFXxxModel, TFXxxForMaskedLM, TFXxxForQuestionAnswering, <ide> def test_for_token_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_xxx_for_token_classification(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in ['xxx-base-uncased']: <ide><path>templates/adding_a_new_model/tests/modeling_xxx_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> if is_torch_available(): <ide> from transformers import (XxxConfig, XxxModel, XxxForMaskedLM, <ide> XxxForNextSentencePrediction, XxxForPreTraining, <ide> XxxForQuestionAnswering, XxxForSequenceClassification, <ide> XxxForTokenClassification, XxxForMultipleChoice) <ide> from transformers.modeling_xxx import XXX_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> <add>@require_torch <ide> class XxxModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (XxxModel, XxxForMaskedLM, XxxForQuestionAnswering, <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_xxx_model(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = XxxModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> sequence_output, pooled_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) <ide> sequence_output, pooled_output = model(input_ids, token_type_ids=token_type_ids) <ide> def create_and_check_xxx_model(self, config, input_ids, token_type_ids, input_ma <ide> <ide> def create_and_check_xxx_for_masked_lm(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = XxxForMaskedLM(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, masked_lm_labels=token_labels) <ide> result = { <ide> def create_and_check_xxx_for_masked_lm(self, config, input_ids, token_type_ids, <ide> <ide> def create_and_check_xxx_for_question_answering(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = XxxForQuestionAnswering(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, start_logits, end_logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, <ide> start_positions=sequence_labels, end_positions=sequence_labels) <ide> def create_and_check_xxx_for_question_answering(self, config, input_ids, token_t <ide> def create_and_check_xxx_for_sequence_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = XxxForSequenceClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) <ide> result = { <ide> def create_and_check_xxx_for_sequence_classification(self, config, input_ids, to <ide> def create_and_check_xxx_for_token_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = XxxForTokenClassification(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) <ide> result = { <ide> def test_for_token_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_xxx_for_token_classification(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(XXX_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/modeling_openai.py <ide> def load_tf_weights_in_openai_gpt(model, config, openai_checkpoint_folder_path): <ide> <ide> logger.info("Loading weights from {}".format(openai_checkpoint_folder_path)) <ide> <del> names = json.load(open(openai_checkpoint_folder_path + '/parameters_names.json', "r", encoding='utf-8')) <del> shapes = json.load(open(openai_checkpoint_folder_path + '/params_shapes.json', "r", encoding='utf-8')) <add> with open(openai_checkpoint_folder_path + '/parameters_names.json', "r", encoding='utf-8') as names_handle: <add> names = json.load(names_handle) <add> with open(openai_checkpoint_folder_path + '/params_shapes.json', "r", encoding='utf-8') as shapes_handle: <add> shapes = json.load(shapes_handle) <ide> offsets = np.cumsum([np.prod(shape) for shape in shapes]) <ide> init_params = [np.load(openai_checkpoint_folder_path + '/params_{}.npy'.format(n)) for n in range(10)] <ide> init_params = np.split(np.concatenate(init_params, 0), offsets)[:-1] <ide><path>transformers/tests/conftest.py <del># content of conftest.py <del> <del>import pytest <del> <del> <del>def pytest_addoption(parser): <del> parser.addoption( <del> "--runslow", action="store_true", default=False, help="run slow tests" <del> ) <del> parser.addoption( <del> "--use_cuda", action="store_true", default=False, help="run tests on gpu" <del> ) <del> <del> <del>def pytest_configure(config): <del> config.addinivalue_line("markers", "slow: mark test as slow to run") <del> <del> <del>def pytest_collection_modifyitems(config, items): <del> if config.getoption("--runslow"): <del> # --runslow given in cli: do not skip slow tests <del> return <del> skip_slow = pytest.mark.skip(reason="need --runslow option to run") <del> for item in items: <del> if "slow" in item.keywords: <del> item.add_marker(skip_slow) <del> <del>@pytest.fixture <del>def use_cuda(request): <del> """ Run test on gpu """ <del> return request.config.getoption("--use_cuda") <ide><path>transformers/tests/modeling_albert_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> if is_torch_available(): <ide> from transformers import (AlbertConfig, AlbertModel, AlbertForMaskedLM, <ide> AlbertForSequenceClassification, AlbertForQuestionAnswering, <ide> ) <ide> from transformers.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> <add>@require_torch <ide> class AlbertModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (AlbertModel, AlbertForMaskedLM) if is_torch_available() else () <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_albert_model(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = AlbertModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> sequence_output, pooled_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) <ide> sequence_output, pooled_output = model(input_ids, token_type_ids=token_type_ids) <ide> def create_and_check_albert_model(self, config, input_ids, token_type_ids, input <ide> <ide> def create_and_check_albert_for_masked_lm(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = AlbertForMaskedLM(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, masked_lm_labels=token_labels) <ide> result = { <ide> def create_and_check_albert_for_masked_lm(self, config, input_ids, token_type_id <ide> <ide> def create_and_check_albert_for_question_answering(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = AlbertForQuestionAnswering(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, start_logits, end_logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, <ide> start_positions=sequence_labels, end_positions=sequence_labels) <ide> def create_and_check_albert_for_question_answering(self, config, input_ids, toke <ide> def create_and_check_albert_for_sequence_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = AlbertForSequenceClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) <ide> result = { <ide> def test_for_sequence_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_albert_for_sequence_classification(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_auto_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import logging <ide> <ide> from transformers import is_torch_available <ide> <add>from .utils import require_torch, slow <add> <ide> if is_torch_available(): <ide> from transformers import (AutoConfig, BertConfig, <ide> AutoModel, BertModel, <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> <add>@require_torch <ide> class AutoModelTest(unittest.TestCase): <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_model_from_pretrained(self): <ide> for value in loading_info.values(): <ide> self.assertEqual(len(value), 0) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_lmhead_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_lmhead_model_from_pretrained(self): <ide> self.assertIsNotNone(model) <ide> self.assertIsInstance(model, BertForMaskedLM) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_classification_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_sequence_classification_model_from_pretrained(self): <ide> self.assertIsNotNone(model) <ide> self.assertIsInstance(model, BertForSequenceClassification) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_question_answering_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_bert_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor, floats_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> if is_torch_available(): <ide> from transformers import (BertConfig, BertModel, BertForMaskedLM, <ide> BertForNextSentencePrediction, BertForPreTraining, <ide> BertForQuestionAnswering, BertForSequenceClassification, <ide> BertForTokenClassification, BertForMultipleChoice) <ide> from transformers.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> <del>@pytest.mark.usefixtures("use_cuda") <add>@require_torch <ide> class BertModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (BertModel, BertForMaskedLM, BertForNextSentencePrediction, <ide> def __init__(self, <ide> num_labels=3, <ide> num_choices=4, <ide> scope=None, <del> device='cpu', <ide> ): <ide> self.parent = parent <ide> self.batch_size = batch_size <ide> def __init__(self, <ide> self.num_labels = num_labels <ide> self.num_choices = num_choices <ide> self.scope = scope <del> self.device = device <ide> <ide> def prepare_config_and_inputs(self): <del> input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).to(self.device) <add> input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size) <ide> <ide> input_mask = None <ide> if self.use_input_mask: <del> input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2).to(self.device) <add> input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2) <ide> <ide> token_type_ids = None <ide> if self.use_token_type_ids: <del> token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size).to(self.device) <add> token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size) <ide> <ide> sequence_labels = None <ide> token_labels = None <ide> choice_labels = None <ide> if self.use_labels: <del> sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size).to(self.device) <del> token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels).to(self.device) <del> choice_labels = ids_tensor([self.batch_size], self.num_choices).to(self.device) <add> sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size) <add> token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels) <add> choice_labels = ids_tensor([self.batch_size], self.num_choices) <ide> <ide> config = BertConfig( <ide> vocab_size_or_config_json_file=self.vocab_size, <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_bert_model(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertModel(config=config) <del> model.to(input_ids.device) <add> model.to(torch_device) <ide> model.eval() <ide> sequence_output, pooled_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) <ide> sequence_output, pooled_output = model(input_ids, token_type_ids=token_type_ids) <ide> def create_and_check_bert_model(self, config, input_ids, token_type_ids, input_m <ide> <ide> def create_and_check_bert_model_as_decoder(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask): <ide> model = BertModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> sequence_output, pooled_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask) <ide> sequence_output, pooled_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, encoder_hidden_states=encoder_hidden_states) <ide> def create_and_check_bert_model_as_decoder(self, config, input_ids, token_type_i <ide> <ide> def create_and_check_bert_for_masked_lm(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForMaskedLM(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, masked_lm_labels=token_labels) <ide> result = { <ide> def create_and_check_bert_for_masked_lm(self, config, input_ids, token_type_ids, <ide> <ide> def create_and_check_bert_model_for_masked_lm_as_decoder(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels, encoder_hidden_states, encoder_attention_mask): <ide> model = BertForMaskedLM(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, masked_lm_labels=token_labels, encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=encoder_attention_mask) <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, masked_lm_labels=token_labels, encoder_hidden_states=encoder_hidden_states) <ide> def create_and_check_bert_model_for_masked_lm_as_decoder(self, config, input_ids <ide> <ide> def create_and_check_bert_for_next_sequence_prediction(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForNextSentencePrediction(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, seq_relationship_score = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, next_sentence_label=sequence_labels) <ide> result = { <ide> def create_and_check_bert_for_next_sequence_prediction(self, config, input_ids, <ide> <ide> def create_and_check_bert_for_pretraining(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForPreTraining(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores, seq_relationship_score = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, <ide> masked_lm_labels=token_labels, next_sentence_label=sequence_labels) <ide> def create_and_check_bert_for_pretraining(self, config, input_ids, token_type_id <ide> <ide> def create_and_check_bert_for_question_answering(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = BertForQuestionAnswering(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, start_logits, end_logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, <ide> start_positions=sequence_labels, end_positions=sequence_labels) <ide> def create_and_check_bert_for_question_answering(self, config, input_ids, token_ <ide> def create_and_check_bert_for_sequence_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = BertForSequenceClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels) <ide> result = { <ide> def create_and_check_bert_for_sequence_classification(self, config, input_ids, t <ide> def create_and_check_bert_for_token_classification(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = BertForTokenClassification(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels) <ide> result = { <ide> def create_and_check_bert_for_token_classification(self, config, input_ids, toke <ide> def create_and_check_bert_for_multiple_choice(self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_choices = self.num_choices <ide> model = BertForMultipleChoice(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <ide> multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous() <ide> def setUp(self): <ide> def test_config(self): <ide> self.config_tester.run_common_tests() <ide> <del> def test_bert_model(self, use_cuda=False): <del> # ^^ This could be a real fixture <del> if use_cuda: <del> self.model_tester.device = "cuda" <add> def test_bert_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_bert_model(*config_and_inputs) <ide> <ide> def test_for_token_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_bert_for_token_classification(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_common_test.py <ide> <ide> import unittest <ide> import logging <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <add>from .utils import require_torch, slow, torch_device <add> <ide> if is_torch_available(): <ide> import torch <ide> import numpy as np <ide> <ide> from transformers import (AdaptiveEmbedding, PretrainedConfig, PreTrainedModel, <ide> BertModel, BertConfig, BERT_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> GPT2LMHeadModel, GPT2Config, GPT2_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> if sys.version_info[0] == 2: <ide> import cPickle as pickle <ide> def _config_zero_init(config): <ide> <ide> class CommonTestCases: <ide> <add> @require_torch <ide> class CommonModelTester(unittest.TestCase): <ide> <ide> model_tester = None <ide> def test_save_load(self): <ide> <ide> for model_class in self.all_model_classes: <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> with torch.no_grad(): <ide> outputs = model(**inputs_dict) <ide> <ide> with TemporaryDirectory() as tmpdirname: <ide> model.save_pretrained(tmpdirname) <ide> model = model_class.from_pretrained(tmpdirname) <add> model.to(torch_device) <ide> with torch.no_grad(): <ide> after_outputs = model(**inputs_dict) <ide> <ide> # Make sure we don't have nans <del> out_1 = after_outputs[0].numpy() <del> out_2 = outputs[0].numpy() <add> out_1 = after_outputs[0].cpu().numpy() <add> out_2 = outputs[0].cpu().numpy() <ide> out_1 = out_1[~np.isnan(out_1)] <ide> out_2 = out_2[~np.isnan(out_2)] <ide> max_diff = np.amax(np.abs(out_1 - out_2)) <ide> def test_determinism(self): <ide> <ide> for model_class in self.all_model_classes: <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> first, second = model(inputs_dict["input_ids"])[0], model(inputs_dict["input_ids"])[0] <ide> self.assertEqual(first.ne(second).sum().item(), 0) <ide> def test_attention_outputs(self): <ide> config.output_attentions = True <ide> config.output_hidden_states = False <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(**inputs_dict) <ide> attentions = outputs[-1] <ide> def test_attention_outputs(self): <ide> config.output_attentions = True <ide> config.output_hidden_states = True <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(**inputs_dict) <ide> self.assertEqual(out_len+1, len(outputs)) <ide> def _create_and_check_torchscript(self, config, inputs_dict): <ide> configs_no_init.torchscript = True <ide> for model_class in self.all_model_classes: <ide> model = model_class(config=configs_no_init) <add> model.to(torch_device) <ide> model.eval() <ide> inputs = inputs_dict['input_ids'] # Let's keep only input_ids <ide> <ide> def _create_and_check_torchscript(self, config, inputs_dict): <ide> except ValueError: <ide> self.fail("Couldn't load module.") <ide> <add> model.to(torch_device) <ide> model.eval() <add> <add> loaded_model.to(torch_device) <ide> loaded_model.eval() <ide> <ide> model_params = model.parameters() <ide> def test_headmasking(self): <ide> configs_no_init = _config_zero_init(config) # To be sure we have no Nan <ide> for model_class in self.all_model_classes: <ide> model = model_class(config=configs_no_init) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> # Prepare head_mask <ide> # Set require_grad after having prepared the tensor to avoid error (leaf variable has been moved into the graph interior) <del> head_mask = torch.ones(self.model_tester.num_hidden_layers, self.model_tester.num_attention_heads) <add> head_mask = torch.ones(self.model_tester.num_hidden_layers, self.model_tester.num_attention_heads, device=torch_device) <ide> head_mask[0, 0] = 0 <ide> head_mask[-1, :-1] = 0 <ide> head_mask.requires_grad_(requires_grad=True) <ide> def test_head_pruning(self): <ide> config.output_attentions = True <ide> config.output_hidden_states = False <ide> model = model_class(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> heads_to_prune = {0: list(range(1, self.model_tester.num_attention_heads)), <ide> -1: [0]} <ide> def test_head_pruning_save_load_from_pretrained(self): <ide> config.output_attentions = True <ide> config.output_hidden_states = False <ide> model = model_class(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> heads_to_prune = {0: list(range(1, self.model_tester.num_attention_heads)), <ide> -1: [0]} <ide> def test_head_pruning_save_load_from_pretrained(self): <ide> os.makedirs(directory) <ide> model.save_pretrained(directory) <ide> model = model_class.from_pretrained(directory) <add> model.to(torch_device) <ide> <ide> outputs = model(**inputs_dict) <ide> attentions = outputs[-1] <ide> def test_head_pruning_save_load_from_config_init(self): <ide> config.pruned_heads = heads_to_prune <ide> <ide> model = model_class(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> outputs = model(**inputs_dict) <ide> def test_head_pruning_integration(self): <ide> config.pruned_heads = heads_to_prune <ide> <ide> model = model_class(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> outputs = model(**inputs_dict) <ide> def test_head_pruning_integration(self): <ide> os.makedirs(directory) <ide> model.save_pretrained(directory) <ide> model = model_class.from_pretrained(directory) <add> model.to(torch_device) <ide> shutil.rmtree(directory) <ide> <ide> outputs = model(**inputs_dict) <ide> def test_hidden_states_output(self): <ide> config.output_hidden_states = True <ide> config.output_attentions = False <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(**inputs_dict) <ide> hidden_states = outputs[-1] <ide> def test_inputs_embeds(self): <ide> <ide> for model_class in self.all_model_classes: <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> wte = model.get_input_embeddings() <ide> def prepare_config_and_inputs(self): <ide> def create_and_check_base_model(self, config, input_ids, token_type_ids, position_ids, <ide> mc_labels, lm_labels, mc_token_ids): <ide> model = self.base_model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> outputs = model(input_ids, position_ids, token_type_ids) <ide> def create_and_check_base_model(self, config, input_ids, token_type_ids, positio <ide> def create_and_check_lm_head(self, config, input_ids, token_type_ids, position_ids, <ide> mc_labels, lm_labels, mc_token_ids): <ide> model = self.lm_head_model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(input_ids, position_ids, token_type_ids, lm_labels) <ide> loss, lm_logits = outputs[:2] <ide> def create_and_check_presents(self, config, input_ids, token_type_ids, position_ <ide> mc_labels, lm_labels, mc_token_ids): <ide> for model_class in self.all_model_classes: <ide> model = model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(input_ids) <ide> presents = outputs[-1] <ide> def create_and_check_presents(self, config, input_ids, token_type_ids, position_ <ide> def create_and_check_double_heads(self, config, input_ids, token_type_ids, position_ids, <ide> mc_labels, lm_labels, mc_token_ids): <ide> model = self.double_head_model_class(config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(input_ids, mc_token_ids, lm_labels=lm_labels, mc_labels=mc_labels, <ide> token_type_ids=token_type_ids, position_ids=position_ids) <ide> def run_common_tests(self, test_presents=False): <ide> config_and_inputs = self.prepare_config_and_inputs() <ide> self.create_and_check_presents(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def run_slow_tests(self): <ide> self.create_and_check_model_from_pretrained() <ide> <ide> def ids_tensor(shape, vocab_size, rng=None, name=None): <ide> for _ in range(total_dims): <ide> values.append(rng.randint(0, vocab_size - 1)) <ide> <del> return torch.tensor(data=values, dtype=torch.long).view(shape).contiguous() <add> return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous() <ide> <ide> <ide> def floats_tensor(shape, scale=1.0, rng=None, name=None): <ide> def floats_tensor(shape, scale=1.0, rng=None, name=None): <ide> for _ in range(total_dims): <ide> values.append(rng.random() * scale) <ide> <del> return torch.tensor(data=values, dtype=torch.float).view(shape).contiguous() <add> return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous() <ide> <ide> <add>@require_torch <ide> class ModelUtilsTest(unittest.TestCase): <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_ctrl_test.py <ide> from __future__ import print_function <ide> <ide> import unittest <del>import pytest <ide> import shutil <ide> import pdb <ide> <ide> if is_torch_available(): <ide> from transformers import (CTRLConfig, CTRLModel, CTRL_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> CTRLLMHeadModel) <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> <add>@require_torch <ide> class CTRLModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (CTRLModel, CTRLLMHeadModel) if is_torch_available() else () <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_ctrl_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): <ide> model = CTRLModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask) <ide> def create_and_check_ctrl_model(self, config, input_ids, input_mask, head_mask, <ide> <ide> def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): <ide> model = CTRLLMHeadModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss, lm_logits, _ = model(input_ids, token_type_ids=token_type_ids, labels=input_ids) <ide> def test_ctrl_lm_head_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_lm_head_model(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(CTRL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_distilbert_test.py <ide> from __future__ import print_function <ide> <ide> import unittest <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> if is_torch_available(): <ide> from transformers import (DistilBertConfig, DistilBertModel, DistilBertForMaskedLM, <ide> DistilBertForTokenClassification, <ide> DistilBertForQuestionAnswering, DistilBertForSequenceClassification) <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> <add>@require_torch <ide> class DistilBertModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (DistilBertModel, DistilBertForMaskedLM, DistilBertForQuestionAnswering, <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_distilbert_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = DistilBertModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> (sequence_output,) = model(input_ids, input_mask) <ide> (sequence_output,) = model(input_ids) <ide> def create_and_check_distilbert_model(self, config, input_ids, input_mask, seque <ide> <ide> def create_and_check_distilbert_for_masked_lm(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = DistilBertForMaskedLM(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, masked_lm_labels=token_labels) <ide> result = { <ide> def create_and_check_distilbert_for_masked_lm(self, config, input_ids, input_mas <ide> <ide> def create_and_check_distilbert_for_question_answering(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> model = DistilBertForQuestionAnswering(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, start_logits, end_logits = model(input_ids, attention_mask=input_mask, start_positions=sequence_labels, end_positions=sequence_labels) <ide> result = { <ide> def create_and_check_distilbert_for_question_answering(self, config, input_ids, <ide> def create_and_check_distilbert_for_sequence_classification(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = DistilBertForSequenceClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, labels=sequence_labels) <ide> result = { <ide> def create_and_check_distilbert_for_sequence_classification(self, config, input_ <ide> def create_and_check_distilbert_for_token_classification(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = DistilBertForTokenClassification(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss, logits = model(input_ids, attention_mask=input_mask, labels=token_labels) <ide> def test_for_token_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_distilbert_for_token_classification(*config_and_inputs) <ide> <del> # @pytest.mark.slow <add> # @slow <ide> # def test_model_from_pretrained(self): <ide> # cache_dir = "/tmp/transformers_test/" <ide> # for model_name in list(DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_encoder_decoder_test.py <ide> <ide> import logging <ide> import unittest <del>import pytest <ide> <ide> from transformers import is_torch_available <add>from .utils import require_torch, slow <ide> <ide> if is_torch_available(): <ide> from transformers import BertModel, BertForMaskedLM, Model2Model <ide> from transformers.modeling_bert import BERT_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> <add>@require_torch <ide> class EncoderDecoderModelTest(unittest.TestCase): <del> @pytest.mark.slow <add> @slow <ide> def test_model2model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_gpt2_test.py <ide> from __future__ import print_function <ide> <ide> import unittest <del>import pytest <ide> import shutil <ide> <ide> from transformers import is_torch_available <ide> <ide> if is_torch_available(): <ide> from transformers import (GPT2Config, GPT2Model, GPT2_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> GPT2LMHeadModel, GPT2DoubleHeadsModel) <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> <add>@require_torch <ide> class GPT2ModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (GPT2Model, GPT2LMHeadModel, GPT2DoubleHeadsModel) if is_torch_available() else () <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_gpt2_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): <ide> model = GPT2Model(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask) <ide> def create_and_check_gpt2_model(self, config, input_ids, input_mask, head_mask, <ide> <ide> def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args): <ide> model = GPT2LMHeadModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss, lm_logits, _ = model(input_ids, token_type_ids=token_type_ids, labels=input_ids) <ide> def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mas <ide> <ide> def create_and_check_double_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, *args): <ide> model = GPT2DoubleHeadsModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> <ide> def test_gpt2_double_lm_head_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_double_lm_head_model(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(GPT2_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_openai_test.py <ide> from __future__ import print_function <ide> <ide> import unittest <del>import pytest <ide> import shutil <ide> <ide> from transformers import is_torch_available <ide> <ide> if is_torch_available(): <ide> from transformers import (OpenAIGPTConfig, OpenAIGPTModel, OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP, <ide> OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel) <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> <add>@require_torch <ide> class OpenAIGPTModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel) if is_torch_available() else () <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_openai_gpt_model(self, config, input_ids, head_mask, token_type_ids, *args): <ide> model = OpenAIGPTModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask) <ide> def create_and_check_openai_gpt_model(self, config, input_ids, head_mask, token_ <ide> <ide> def create_and_check_lm_head_model(self, config, input_ids, head_mask, token_type_ids, *args): <ide> model = OpenAIGPTLMHeadModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss, lm_logits = model(input_ids, token_type_ids=token_type_ids, labels=input_ids) <ide> def create_and_check_lm_head_model(self, config, input_ids, head_mask, token_typ <ide> <ide> def create_and_check_double_lm_head_model(self, config, input_ids, head_mask, token_type_ids, *args): <ide> model = OpenAIGPTDoubleHeadsModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss, lm_logits, mc_logits = model(input_ids, token_type_ids=token_type_ids, lm_labels=input_ids) <ide> def test_openai_gpt_double_lm_head_model(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_double_lm_head_model(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_roberta_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> from transformers import (RobertaConfig, RobertaModel, RobertaForMaskedLM, <ide> RobertaForSequenceClassification, RobertaForTokenClassification) <ide> from transformers.modeling_roberta import ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> <add>@require_torch <ide> class RobertaModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (RobertaForMaskedLM, RobertaModel) if is_torch_available() else () <ide> def check_loss_output(self, result): <ide> def create_and_check_roberta_model(self, config, input_ids, token_type_ids, input_mask, sequence_labels, <ide> token_labels, choice_labels): <ide> model = RobertaModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> sequence_output, pooled_output = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids) <ide> sequence_output, pooled_output = model(input_ids, token_type_ids=token_type_ids) <ide> def create_and_check_roberta_model(self, config, input_ids, token_type_ids, inpu <ide> def create_and_check_roberta_for_masked_lm(self, config, input_ids, token_type_ids, input_mask, sequence_labels, <ide> token_labels, choice_labels): <ide> model = RobertaForMaskedLM(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, prediction_scores = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, masked_lm_labels=token_labels) <ide> result = { <ide> def create_and_check_roberta_for_token_classification(self, config, input_ids, t <ide> sequence_labels, token_labels, choice_labels): <ide> config.num_labels = self.num_labels <ide> model = RobertaForTokenClassification(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> loss, logits = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, <ide> labels=token_labels) <ide> def test_for_masked_lm(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_roberta_for_masked_lm(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_model_from_pretrained(self): <ide> <ide> class RobertaModelIntegrationTest(unittest.TestCase): <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_inference_masked_lm(self): <ide> model = RobertaForMaskedLM.from_pretrained('roberta-base') <del> <add> <ide> input_ids = torch.tensor([[ 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) <ide> output = model(input_ids)[0] <ide> expected_shape = torch.Size((1, 11, 50265)) <ide> def test_inference_masked_lm(self): <ide> torch.allclose(output[:, :3, :3], expected_slice, atol=1e-3) <ide> ) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_inference_no_head(self): <ide> model = RobertaModel.from_pretrained('roberta-base') <del> <add> <ide> input_ids = torch.tensor([[ 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) <ide> output = model(input_ids)[0] <ide> # compare the actual values for a slice. <ide> def test_inference_no_head(self): <ide> torch.allclose(output[:, :3, :3], expected_slice, atol=1e-3) <ide> ) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_inference_classification_head(self): <ide> model = RobertaForSequenceClassification.from_pretrained('roberta-large-mnli') <del> <add> <ide> input_ids = torch.tensor([[ 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) <ide> output = model(input_ids)[0] <ide> expected_shape = torch.Size((1, 3)) <ide><path>transformers/tests/modeling_tf_albert_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import sys <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import AlbertConfig, is_tf_available <ide> <ide> from transformers.modeling_tf_albert import (TFAlbertModel, TFAlbertForMaskedLM, <ide> TFAlbertForSequenceClassification, <ide> TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFAlbertModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = ( <ide> def test_for_sequence_classification(self): <ide> self.model_tester.create_and_check_albert_for_sequence_classification( <ide> *config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> # for model_name in list(TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_auto_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import logging <ide> <ide> from transformers import is_tf_available <ide> <add>from .utils import require_tf, slow <add> <ide> if is_tf_available(): <ide> from transformers import (AutoConfig, BertConfig, <ide> TFAutoModel, TFBertModel, <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFAutoModelTest(unittest.TestCase): <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> import h5py <ide> self.assertTrue(h5py.version.hdf5_version.startswith("1.10")) <ide> def test_model_from_pretrained(self): <ide> self.assertIsNotNone(model) <ide> self.assertIsInstance(model, TFBertModel) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_lmhead_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_lmhead_model_from_pretrained(self): <ide> self.assertIsNotNone(model) <ide> self.assertIsInstance(model, TFBertForMaskedLM) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_classification_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_sequence_classification_model_from_pretrained(self): <ide> self.assertIsNotNone(model) <ide> self.assertIsInstance(model, TFBertForSequenceClassification) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_question_answering_model_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_bert_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import sys <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import BertConfig, is_tf_available <ide> <ide> TFBertForTokenClassification, <ide> TFBertForQuestionAnswering, <ide> TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFBertModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFBertModel, TFBertForMaskedLM, TFBertForNextSentencePrediction, <ide> def test_for_token_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_bert_for_token_classification(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> # for model_name in list(TF_BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_common_test.py <ide> import uuid <ide> import tempfile <ide> <del>import pytest <ide> import sys <ide> <ide> from transformers import is_tf_available, is_torch_available <ide> <add>from .utils import require_tf, slow <add> <ide> if is_tf_available(): <ide> import tensorflow as tf <ide> import numpy as np <ide> from transformers import TFPreTrainedModel <ide> # from transformers.modeling_bert import BertModel, BertConfig, BERT_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> if sys.version_info[0] == 2: <ide> import cPickle as pickle <ide> def _config_zero_init(config): <ide> <ide> class TFCommonTestCases: <ide> <add> @require_tf <ide> class TFCommonModelTester(unittest.TestCase): <ide> <ide> model_tester = None <ide> def test_compile_tf_model(self): <ide> for model_class in self.all_model_classes: <ide> # Prepare our model <ide> model = model_class(config) <del> <add> <ide> # Let's load it from the disk to be sure we can use pretrained weights <ide> with TemporaryDirectory() as tmpdirname: <ide> outputs = model(inputs_dict) # build the model <ide><path>transformers/tests/modeling_tf_ctrl_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import sys <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import CTRLConfig, is_tf_available <ide> <ide> if is_tf_available(): <ide> import tensorflow as tf <ide> from transformers.modeling_tf_ctrl import (TFCTRLModel, TFCTRLLMHeadModel, <ide> TF_CTRL_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFCTRLModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFCTRLModel, TFCTRLLMHeadModel) if is_tf_available() else () <ide> def test_ctrl_lm_head(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_ctrl_lm_head(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_CTRL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_distilbert_test.py <ide> from __future__ import print_function <ide> <ide> import unittest <del>import pytest <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import DistilBertConfig, is_tf_available <ide> <ide> TFDistilBertForMaskedLM, <ide> TFDistilBertForQuestionAnswering, <ide> TFDistilBertForSequenceClassification) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFDistilBertModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFDistilBertModel, TFDistilBertForMaskedLM, TFDistilBertForQuestionAnswering, <ide> def test_for_sequence_classification(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_distilbert_for_sequence_classification(*config_and_inputs) <ide> <del> # @pytest.mark.slow <add> # @slow <ide> # def test_model_from_pretrained(self): <ide> # cache_dir = "/tmp/transformers_test/" <ide> # for model_name in list(DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_gpt2_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import sys <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import GPT2Config, is_tf_available <ide> <ide> from transformers.modeling_tf_gpt2 import (TFGPT2Model, TFGPT2LMHeadModel, <ide> TFGPT2DoubleHeadsModel, <ide> TF_GPT2_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFGPT2ModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFGPT2Model, TFGPT2LMHeadModel, <ide> def test_gpt2_double_head(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_gpt2_double_head(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_GPT2_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_openai_gpt_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import sys <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import OpenAIGPTConfig, is_tf_available <ide> <ide> from transformers.modeling_tf_openai import (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, <ide> TFOpenAIGPTDoubleHeadsModel, <ide> TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFOpenAIGPTModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, <ide> def test_openai_gpt_double_head(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_openai_gpt_double_head(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_roberta_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import RobertaConfig, is_tf_available <ide> <ide> TFRobertaForSequenceClassification, <ide> TFRobertaForTokenClassification, <ide> TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFRobertaModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFRobertaModel,TFRobertaForMaskedLM, <ide> def test_for_masked_lm(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_roberta_for_masked_lm(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_ROBERTA_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> def test_model_from_pretrained(self): <ide> <ide> class TFRobertaModelIntegrationTest(unittest.TestCase): <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_inference_masked_lm(self): <ide> model = TFRobertaForMaskedLM.from_pretrained('roberta-base') <del> <add> <ide> input_ids = tf.constant([[ 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) <ide> output = model(input_ids)[0] <ide> expected_shape = [1, 11, 50265] <ide> def test_inference_masked_lm(self): <ide> numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-3) <ide> ) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_inference_no_head(self): <ide> model = TFRobertaModel.from_pretrained('roberta-base') <del> <add> <ide> input_ids = tf.constant([[ 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) <ide> output = model(input_ids)[0] <ide> # compare the actual values for a slice. <ide> def test_inference_no_head(self): <ide> numpy.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-3) <ide> ) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_inference_classification_head(self): <ide> model = TFRobertaForSequenceClassification.from_pretrained('roberta-large-mnli') <del> <add> <ide> input_ids = tf.constant([[ 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]]) <ide> output = model(input_ids)[0] <ide> expected_shape = [1, 3] <ide><path>transformers/tests/modeling_tf_transfo_xl_test.py <ide> import unittest <ide> import random <ide> import shutil <del>import pytest <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> from transformers import TransfoXLConfig, is_tf_available <ide> <ide> from transformers.modeling_tf_transfo_xl import (TFTransfoXLModel, <ide> TFTransfoXLLMHeadModel, <ide> TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> <add>@require_tf <ide> class TFTransfoXLModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFTransfoXLModel, TFTransfoXLLMHeadModel) if is_tf_available() else () <ide> def test_transfo_xl_lm_head(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_transfo_xl_lm_head(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_xlm_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_tf_available <ide> <ide> TFXLMForSequenceClassification, <ide> TFXLMForQuestionAnsweringSimple, <ide> TF_XLM_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <ide> <add>@require_tf <ide> class TFXLMModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes = (TFXLMModel, TFXLMWithLMHeadModel, <ide> def test_xlm_sequence_classif(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_xlm_sequence_classif(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_XLM_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_tf_xlnet_test.py <ide> import json <ide> import random <ide> import shutil <del>import pytest <ide> <ide> from transformers import XLNetConfig, is_tf_available <ide> <ide> TFXLNetForTokenClassification, <ide> TFXLNetForQuestionAnsweringSimple, <ide> TF_XLNET_PRETRAINED_MODEL_ARCHIVE_MAP) <del>else: <del> pytestmark = pytest.mark.skip("Require TensorFlow") <ide> <ide> from .modeling_tf_common_test import (TFCommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_tf, slow <ide> <add> <add>@require_tf <ide> class TFXLNetModelTest(TFCommonTestCases.TFCommonModelTester): <ide> <ide> all_model_classes=(TFXLNetModel, TFXLNetLMHeadModel, <ide> def test_xlnet_base_model(self): <ide> def test_xlnet_lm_head(self): <ide> self.model_tester.set_seed() <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <del> self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs) <add> self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs) <ide> <ide> def test_xlnet_sequence_classif(self): <ide> self.model_tester.set_seed() <ide> def test_xlnet_qa(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_xlnet_qa(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TF_XLNET_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_transfo_xl_test.py <ide> import unittest <ide> import random <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> if is_torch_available(): <ide> import torch <ide> from transformers import (TransfoXLConfig, TransfoXLModel, TransfoXLLMHeadModel) <ide> from transformers.modeling_transfo_xl import TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <add> <add>@require_torch <ide> class TransfoXLModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (TransfoXLModel, TransfoXLLMHeadModel) if is_torch_available() else () <ide> def set_seed(self): <ide> <ide> def create_transfo_xl_model(self, config, input_ids_1, input_ids_2, lm_labels): <ide> model = TransfoXLModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> hidden_states_1, mems_1 = model(input_ids_1) <ide> def check_transfo_xl_model_output(self, result): <ide> <ide> def create_transfo_xl_lm_head(self, config, input_ids_1, input_ids_2, lm_labels): <ide> model = TransfoXLLMHeadModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> lm_logits_1, mems_1 = model(input_ids_1) <ide> def test_transfo_xl_lm_head(self): <ide> output_result = self.model_tester.create_transfo_xl_lm_head(*config_and_inputs) <ide> self.model_tester.check_transfo_xl_lm_head_output(output_result) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_xlm_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> if is_torch_available(): <ide> from transformers import (XLMConfig, XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, <ide> XLMForSequenceClassification, XLMForQuestionAnsweringSimple) <ide> from transformers.modeling_xlm import XLM_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <ide> <add>@require_torch <ide> class XLMModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes = (XLMModel, XLMWithLMHeadModel, XLMForQuestionAnswering, <ide> def check_loss_output(self, result): <ide> <ide> def create_and_check_xlm_model(self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, input_mask): <ide> model = XLMModel(config=config) <add> model.to(torch_device) <ide> model.eval() <ide> outputs = model(input_ids, lengths=input_lengths, langs=token_type_ids) <ide> outputs = model(input_ids, langs=token_type_ids) <ide> def create_and_check_xlm_model(self, config, input_ids, token_type_ids, input_le <ide> <ide> def create_and_check_xlm_lm_head(self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, input_mask): <ide> model = XLMWithLMHeadModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss, logits = model(input_ids, token_type_ids=token_type_ids, labels=token_labels) <ide> def create_and_check_xlm_lm_head(self, config, input_ids, token_type_ids, input_ <ide> <ide> def create_and_check_xlm_simple_qa(self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, input_mask): <ide> model = XLMForQuestionAnsweringSimple(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> outputs = model(input_ids) <ide> def create_and_check_xlm_simple_qa(self, config, input_ids, token_type_ids, inpu <ide> <ide> def create_and_check_xlm_qa(self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, input_mask): <ide> model = XLMForQuestionAnswering(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> outputs = model(input_ids) <ide> def create_and_check_xlm_qa(self, config, input_ids, token_type_ids, input_lengt <ide> <ide> def create_and_check_xlm_sequence_classif(self, config, input_ids, token_type_ids, input_lengths, sequence_labels, token_labels, is_impossible_labels, input_mask): <ide> model = XLMForSequenceClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> (logits,) = model(input_ids) <ide> def test_xlm_sequence_classif(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_xlm_sequence_classif(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(XLM_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/modeling_xlnet_test.py <ide> import json <ide> import random <ide> import shutil <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> from transformers import (XLNetConfig, XLNetModel, XLNetLMHeadModel, XLNetForSequenceClassification, <ide> XLNetForTokenClassification, XLNetForQuestionAnswering) <ide> from transformers.modeling_xlnet import XLNET_PRETRAINED_MODEL_ARCHIVE_MAP <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .modeling_common_test import (CommonTestCases, ids_tensor) <ide> from .configuration_common_test import ConfigTester <add>from .utils import require_torch, slow, torch_device <ide> <add> <add>@require_torch <ide> class XLNetModelTest(CommonTestCases.CommonModelTester): <ide> <ide> all_model_classes=(XLNetModel, XLNetLMHeadModel, XLNetForTokenClassification, <ide> def prepare_config_and_inputs(self): <ide> input_mask = ids_tensor([self.batch_size, self.seq_length], 2).float() <ide> <ide> input_ids_q = ids_tensor([self.batch_size, self.seq_length + 1], self.vocab_size) <del> perm_mask = torch.zeros(self.batch_size, self.seq_length + 1, self.seq_length + 1, dtype=torch.float) <add> perm_mask = torch.zeros(self.batch_size, self.seq_length + 1, self.seq_length + 1, dtype=torch.float, device=torch_device) <ide> perm_mask[:, :, -1] = 1.0 # Previous tokens don't see last token <del> target_mapping = torch.zeros(self.batch_size, 1, self.seq_length + 1, dtype=torch.float) <add> target_mapping = torch.zeros(self.batch_size, 1, self.seq_length + 1, dtype=torch.float, device=torch_device) <ide> target_mapping[:, 0, -1] = 1.0 # predict last token <ide> <ide> sequence_labels = None <ide> def set_seed(self): <ide> def create_and_check_xlnet_base_model(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <ide> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> _, _ = model(input_ids_1, input_mask=input_mask) <ide> def create_and_check_xlnet_base_model(self, config, input_ids_1, input_ids_2, in <ide> <ide> config.mem_len = 0 <ide> model = XLNetModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> no_mems_outputs = model(input_ids_1) <ide> self.parent.assertEqual(len(no_mems_outputs), 1) <ide> def create_and_check_xlnet_base_model(self, config, input_ids_1, input_ids_2, in <ide> def create_and_check_xlnet_base_model_with_att_output(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <ide> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> _, _, attentions = model(input_ids_1, target_mapping=target_mapping) <ide> def create_and_check_xlnet_base_model_with_att_output(self, config, input_ids_1, <ide> def create_and_check_xlnet_lm_head(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <ide> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetLMHeadModel(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> loss_1, all_logits_1, mems_1 = model(input_ids_1, token_type_ids=segment_ids, labels=lm_labels) <ide> def create_and_check_xlnet_lm_head(self, config, input_ids_1, input_ids_2, input <ide> def create_and_check_xlnet_qa(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <ide> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetForQuestionAnswering(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> outputs = model(input_ids_1) <ide> def create_and_check_xlnet_qa(self, config, input_ids_1, input_ids_2, input_ids_ <ide> def create_and_check_xlnet_token_classif(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <ide> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetForTokenClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> logits, mems_1 = model(input_ids_1) <ide> def prepare_config_and_inputs_for_common(self): <ide> def create_and_check_xlnet_sequence_classif(self, config, input_ids_1, input_ids_2, input_ids_q, perm_mask, input_mask, <ide> target_mapping, segment_ids, lm_labels, sequence_labels, is_impossible_labels, token_labels): <ide> model = XLNetForSequenceClassification(config) <add> model.to(torch_device) <ide> model.eval() <ide> <ide> logits, mems_1 = model(input_ids_1) <ide> def test_xlnet_base_model_with_att_output(self): <ide> def test_xlnet_lm_head(self): <ide> self.model_tester.set_seed() <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <del> self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs) <add> self.model_tester.create_and_check_xlnet_lm_head(*config_and_inputs) <ide> <ide> def test_xlnet_sequence_classif(self): <ide> self.model_tester.set_seed() <ide> def test_xlnet_qa(self): <ide> config_and_inputs = self.model_tester.prepare_config_and_inputs() <ide> self.model_tester.create_and_check_xlnet_qa(*config_and_inputs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_model_from_pretrained(self): <ide> cache_dir = "/tmp/transformers_test/" <ide> for model_name in list(XLNET_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/optimization_test.py <ide> <ide> import unittest <ide> import os <del>import pytest <ide> <ide> from transformers import is_torch_available <ide> <ide> get_cosine_schedule_with_warmup, <ide> get_cosine_with_hard_restarts_schedule_with_warmup, <ide> get_linear_schedule_with_warmup) <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") <ide> <ide> from .tokenization_tests_commons import TemporaryDirectory <add>from .utils import require_torch <ide> <ide> <ide> def unwrap_schedule(scheduler, num_steps=10): <ide> def unwrap_and_save_reload_schedule(scheduler, num_steps=10): <ide> scheduler.load_state_dict(state_dict) <ide> return lrs <ide> <add>@require_torch <ide> class OptimizationTest(unittest.TestCase): <ide> <ide> def assertListAlmostEqual(self, list1, list2, tol): <ide> def test_adam_w(self): <ide> self.assertListAlmostEqual(w.tolist(), [0.4, 0.2, -0.5], tol=1e-2) <ide> <ide> <add>@require_torch <ide> class ScheduleInitTest(unittest.TestCase): <ide> m = torch.nn.Linear(50, 50) if is_torch_available() else None <ide> optimizer = AdamW(m.parameters(), lr=10.) if is_torch_available() else None <ide><path>transformers/tests/tokenization_auto_test.py <ide> <ide> import unittest <ide> import shutil <del>import pytest <ide> import logging <ide> <ide> from transformers import AutoTokenizer, BertTokenizer, AutoTokenizer, GPT2Tokenizer <ide> from transformers import BERT_PRETRAINED_CONFIG_ARCHIVE_MAP, GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP <ide> <add>from .utils import slow <add> <ide> <ide> class AutoTokenizerTest(unittest.TestCase): <del> @pytest.mark.slow <add> @slow <ide> def test_tokenizer_from_pretrained(self): <ide> logging.basicConfig(level=logging.INFO) <ide> for model_name in list(BERT_PRETRAINED_CONFIG_ARCHIVE_MAP.keys())[:1]: <ide><path>transformers/tests/tokenization_bert_test.py <ide> <ide> import os <ide> import unittest <del>import pytest <ide> from io import open <ide> <ide> from transformers.tokenization_bert import (BasicTokenizer, <ide> _is_whitespace, VOCAB_FILES_NAMES) <ide> <ide> from .tokenization_tests_commons import CommonTestCases <add>from .utils import slow <ide> <ide> class BertTokenizationTest(CommonTestCases.CommonTokenizerTester): <ide> <ide> def test_is_punctuation(self): <ide> self.assertFalse(_is_punctuation(u"A")) <ide> self.assertFalse(_is_punctuation(u" ")) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_builders(self): <ide> tokenizer = self.tokenizer_class.from_pretrained("bert-base-uncased") <ide> <ide><path>transformers/tests/tokenization_distilbert_test.py <ide> <ide> import os <ide> import unittest <del>import pytest <ide> from io import open <ide> <ide> from transformers.tokenization_distilbert import (DistilBertTokenizer) <ide> <ide> from .tokenization_tests_commons import CommonTestCases <ide> from .tokenization_bert_test import BertTokenizationTest <add>from .utils import slow <ide> <ide> class DistilBertTokenizationTest(BertTokenizationTest): <ide> <ide> class DistilBertTokenizationTest(BertTokenizationTest): <ide> def get_tokenizer(self, **kwargs): <ide> return DistilBertTokenizer.from_pretrained(self.tmpdirname, **kwargs) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_builders(self): <ide> tokenizer = DistilBertTokenizer.from_pretrained("distilbert-base-uncased") <ide> <ide><path>transformers/tests/tokenization_roberta_test.py <ide> import os <ide> import json <ide> import unittest <del>import pytest <ide> from io import open <ide> <ide> from transformers.tokenization_roberta import RobertaTokenizer, VOCAB_FILES_NAMES <ide> from .tokenization_tests_commons import CommonTestCases <add>from .utils import slow <ide> <ide> <ide> class RobertaTokenizationTest(CommonTestCases.CommonTokenizerTester): <ide> def roberta_dict_integration_testing(self): <ide> [0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2] <ide> ) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_builders(self): <ide> tokenizer = RobertaTokenizer.from_pretrained("roberta-base") <ide> <ide><path>transformers/tests/tokenization_tests_commons.py <ide> def test_pickle_tokenizer(self): <ide> with TemporaryDirectory() as tmpdirname: <ide> <ide> filename = os.path.join(tmpdirname, u"tokenizer.bin") <del> pickle.dump(tokenizer, open(filename, "wb")) <add> with open(filename, "wb") as handle: <add> pickle.dump(tokenizer, handle) <ide> <del> tokenizer_new = pickle.load(open(filename, "rb")) <add> with open(filename, "rb") as handle: <add> tokenizer_new = pickle.load(handle) <ide> <ide> subwords_loaded = tokenizer_new.tokenize(text) <ide> <ide><path>transformers/tests/tokenization_transfo_xl_test.py <ide> <ide> import os <ide> import unittest <del>import pytest <ide> from io import open <ide> <ide> from transformers import is_torch_available <ide> <ide> if is_torch_available(): <ide> import torch <ide> from transformers.tokenization_transfo_xl import TransfoXLTokenizer, VOCAB_FILES_NAMES <del>else: <del> pytestmark = pytest.mark.skip("Require Torch") # TODO: untangle Transfo-XL tokenizer from torch.load and torch.save <ide> <ide> from .tokenization_tests_commons import CommonTestCases <add>from .utils import require_torch <ide> <add> <add>@require_torch <ide> class TransfoXLTokenizationTest(CommonTestCases.CommonTokenizerTester): <ide> <ide> tokenizer_class = TransfoXLTokenizer if is_torch_available() else None <ide><path>transformers/tests/tokenization_utils_test.py <ide> <ide> import unittest <ide> import six <del>import pytest <ide> <ide> from transformers import PreTrainedTokenizer <ide> from transformers.tokenization_gpt2 import GPT2Tokenizer <ide> <add>from .utils import slow <add> <ide> class TokenizerUtilsTest(unittest.TestCase): <del> @pytest.mark.slow <add> <ide> def check_tokenizer_from_pretrained(self, tokenizer_class): <ide> s3_models = list(tokenizer_class.max_model_input_sizes.keys()) <ide> for model_name in s3_models[:1]: <ide> def check_tokenizer_from_pretrained(self, tokenizer_class): <ide> special_tok_id = tokenizer.convert_tokens_to_ids(special_tok) <ide> self.assertIsInstance(special_tok_id, int) <ide> <add> @slow <ide> def test_pretrained_tokenizers(self): <ide> self.check_tokenizer_from_pretrained(GPT2Tokenizer) <ide> <ide><path>transformers/tests/tokenization_xlm_test.py <ide> import os <ide> import unittest <ide> import json <del>import pytest <ide> <ide> from transformers.tokenization_xlm import XLMTokenizer, VOCAB_FILES_NAMES <ide> <ide> from .tokenization_tests_commons import CommonTestCases <add>from .utils import slow <ide> <ide> class XLMTokenizationTest(CommonTestCases.CommonTokenizerTester): <ide> <ide> def test_full_tokenizer(self): <ide> self.assertListEqual( <ide> tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_builders(self): <ide> tokenizer = XLMTokenizer.from_pretrained("xlm-mlm-en-2048") <ide> <ide><path>transformers/tests/tokenization_xlnet_test.py <ide> <ide> import os <ide> import unittest <del>import pytest <ide> <ide> from transformers.tokenization_xlnet import (XLNetTokenizer, SPIECE_UNDERLINE) <ide> <ide> from .tokenization_tests_commons import CommonTestCases <add>from .utils import slow <ide> <ide> SAMPLE_VOCAB = os.path.join(os.path.dirname(os.path.abspath(__file__)), <ide> 'fixtures/test_sentencepiece.model') <ide> def test_tokenizer_no_lower(self): <ide> u'9', u'2', u'0', u'0', u'0', u',', SPIECE_UNDERLINE + u'and', SPIECE_UNDERLINE + u'this', <ide> SPIECE_UNDERLINE + u'is', SPIECE_UNDERLINE + u'f', u'al', u'se', u'.']) <ide> <del> @pytest.mark.slow <add> @slow <ide> def test_sequence_builders(self): <ide> tokenizer = XLNetTokenizer.from_pretrained("xlnet-base-cased") <ide> <ide><path>transformers/tests/utils.py <add>import os <add>import unittest <add> <add>from distutils.util import strtobool <add> <add>from transformers.file_utils import _tf_available, _torch_available <add> <add> <add>try: <add> run_slow = os.environ["RUN_SLOW"] <add>except KeyError: <add> # RUN_SLOW isn't set, default to skipping slow tests. <add> _run_slow_tests = False <add>else: <add> # RUN_SLOW is set, convert it to True or False. <add> try: <add> _run_slow_tests = strtobool(run_slow) <add> except ValueError: <add> # More values are supported, but let's keep the message simple. <add> raise ValueError("If set, RUN_SLOW must be yes or no.") <add> <add> <add>def slow(test_case): <add> """ <add> Decorator marking a test as slow. <add> <add> Slow tests are skipped by default. Set the RUN_SLOW environment variable <add> to a truthy value to run them. <add> <add> """ <add> if not _run_slow_tests: <add> test_case = unittest.skip("test is slow")(test_case) <add> return test_case <add> <add> <add>def require_torch(test_case): <add> """ <add> Decorator marking a test that requires PyTorch. <add> <add> These tests are skipped when PyTorch isn't installed. <add> <add> """ <add> if not _torch_available: <add> test_case = unittest.skip("test requires PyTorch")(test_case) <add> return test_case <add> <add> <add>def require_tf(test_case): <add> """ <add> Decorator marking a test that requires TensorFlow. <add> <add> These tests are skipped when TensorFlow isn't installed. <add> <add> """ <add> if not _tf_available: <add> test_case = unittest.skip("test requires TensorFlow")(test_case) <add> return test_case <add> <add> <add>if _torch_available: <add> # Set the USE_CUDA environment variable to select a GPU. <add> torch_device = "cuda" if os.environ.get("USE_CUDA") else "cpu" <add>else: <add> torch_device = None <ide><path>transformers/tokenization_albert.py <ide> def _tokenize(self, text, return_unicode=True, sample=False): <ide> pieces = self.sp_model.SampleEncodeAsPieces(text, 64, 0.1) <ide> new_pieces = [] <ide> for piece in pieces: <del> if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit(): <add> if len(piece) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): <ide> cur_pieces = self.sp_model.EncodeAsPieces( <ide> piece[:-1].replace(SPIECE_UNDERLINE, '')) <ide> if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: <ide> def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None): <ide> """ <ide> Creates a mask from the two sequences passed to be used in a sequence-pair classification task. <ide> An ALBERT sequence pair mask has the following format: <del> 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 <del> | first sequence | second sequence <del> <add> 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 <add> | first sequence | second sequence <add> <ide> if token_ids_1 is None, only returns the first portion of the mask (0's). <ide> """ <ide> sep = [self.sep_token_id] <ide><path>transformers/tokenization_ctrl.py <ide> def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs): <ide> self.max_len_single_sentence = self.max_len # no default special tokens - you can update this value if you add special tokens <ide> self.max_len_sentences_pair = self.max_len # no default special tokens - you can update this value if you add special tokens <ide> <del> self.encoder = json.load(open(vocab_file, encoding="utf-8")) <add> with open(vocab_file, encoding="utf-8") as vocab_handle: <add> self.encoder = json.load(vocab_handle) <ide> self.decoder = {v:k for k,v in self.encoder.items()} <del> merges = open(merges_file, encoding='utf-8').read().split('\n')[1:-1] <add> with open(merges_file, encoding='utf-8') as merges_handle: <add> merges = merges_handle.read().split('\n')[1:-1] <ide> merges = [tuple(merge.split()) for merge in merges] <ide> self.bpe_ranks = dict(zip(merges, range(len(merges)))) <ide> self.cache = {} <ide><path>transformers/tokenization_gpt2.py <ide> def bytes_to_unicode(): <ide> """ <ide> Returns list of utf-8 byte and a mapping to unicode strings. <ide> We specifically avoids mapping to whitespace/control characters the bpe code barfs on. <del> <add> <ide> The reversible bpe codes work on unicode strings. <ide> This means you need a large # of unicode characters in your vocab if you want to avoid UNKs. <ide> When you're at something like a 10B token dataset you end up needing around 5K for decent coverage. <ide> def __init__(self, vocab_file, merges_file, errors='replace', unk_token="<|endof <ide> self.max_len_single_sentence = self.max_len # no default special tokens - you can update this value if you add special tokens <ide> self.max_len_sentences_pair = self.max_len # no default special tokens - you can update this value if you add special tokens <ide> <del> self.encoder = json.load(open(vocab_file, encoding="utf-8")) <add> with open(vocab_file, encoding="utf-8") as vocab_handle: <add> self.encoder = json.load(vocab_handle) <ide> self.decoder = {v: k for k, v in self.encoder.items()} <ide> self.errors = errors # how to handle errors in decoding <ide> self.byte_encoder = bytes_to_unicode() <ide> self.byte_decoder = {v: k for k, v in self.byte_encoder.items()} <del> bpe_data = open(merges_file, encoding='utf-8').read().split('\n')[1:-1] <del> bpe_merges = [tuple(merge.split()) for merge in bpe_data] <add> with open(merges_file, encoding='utf-8') as merges_handle: <add> bpe_merges = merges_handle.read().split('\n')[1:-1] <add> bpe_merges = [tuple(merge.split()) for merge in bpe_merges] <ide> self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges)))) <ide> self.cache = {} <ide> <ide> def save_vocabulary(self, save_directory): <ide> writer.write(' '.join(bpe_tokens) + u'\n') <ide> index += 1 <ide> <del> return vocab_file, merge_file <ide>\ No newline at end of file <add> return vocab_file, merge_file <ide><path>transformers/tokenization_openai.py <ide> def __init__(self, vocab_file, merges_file, unk_token="<unk>", **kwargs): <ide> self.nlp = BasicTokenizer(do_lower_case=True) <ide> self.fix_text = None <ide> <del> self.encoder = json.load(open(vocab_file, encoding="utf-8")) <add> with open(vocab_file, encoding="utf-8") as vocab_handle: <add> self.encoder = json.load(vocab_handle) <ide> self.decoder = {v:k for k,v in self.encoder.items()} <del> merges = open(merges_file, encoding='utf-8').read().split('\n')[1:-1] <add> with open(merges_file, encoding='utf-8') as merges_handle: <add> merges = merges_handle.read().split('\n')[1:-1] <ide> merges = [tuple(merge.split()) for merge in merges] <ide> self.bpe_ranks = dict(zip(merges, range(len(merges)))) <ide> self.cache = {} <ide><path>transformers/tokenization_utils.py <ide> def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs) <ide> "We assumed '{}' was a path or url to a directory containing vocabulary files " <ide> "named {} but couldn't find such vocabulary files at this path or url.".format( <ide> pretrained_model_name_or_path, ', '.join(s3_models), <del> pretrained_model_name_or_path, <add> pretrained_model_name_or_path, <ide> list(cls.vocab_files_names.values()))) <ide> <ide> # Get files from url, cache, or disk depending on the case <ide> def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs) <ide> # Did we saved some inputs and kwargs to reload ? <ide> tokenizer_config_file = resolved_vocab_files.pop('tokenizer_config_file', None) <ide> if tokenizer_config_file is not None: <del> init_kwargs = json.load(open(tokenizer_config_file, encoding="utf-8")) <add> with open(tokenizer_config_file, encoding="utf-8") as tokenizer_config_handle: <add> init_kwargs = json.load(tokenizer_config_handle) <ide> saved_init_inputs = init_kwargs.pop('init_inputs', ()) <ide> if not init_inputs: <ide> init_inputs = saved_init_inputs <ide> def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs) <ide> if args_name not in init_kwargs: <ide> init_kwargs[args_name] = file_path <ide> if special_tokens_map_file is not None: <del> special_tokens_map = json.load(open(special_tokens_map_file, encoding="utf-8")) <add> with open(special_tokens_map_file, encoding="utf-8") as special_tokens_map_handle: <add> special_tokens_map = json.load(special_tokens_map_handle) <ide> for key, value in special_tokens_map.items(): <ide> if key not in init_kwargs: <ide> init_kwargs[key] = value <ide> def _from_pretrained(cls, pretrained_model_name_or_path, *init_inputs, **kwargs) <ide> <ide> # Add supplementary tokens. <ide> if added_tokens_file is not None: <del> added_tok_encoder = json.load(open(added_tokens_file, encoding="utf-8")) <add> with open(added_tokens_file, encoding="utf-8") as added_tokens_handle: <add> added_tok_encoder = json.load(added_tokens_handle) <ide> added_tok_decoder = {v:k for k, v in added_tok_encoder.items()} <ide> tokenizer.added_tokens_encoder.update(added_tok_encoder) <ide> tokenizer.added_tokens_decoder.update(added_tok_decoder) <ide> def prepare_for_model(self, ids, pair_ids=None, max_length=None, add_special_tok <ide> logger.warning("Token indices sequence length is longer than the specified maximum sequence length " <ide> "for this model ({} > {}). Running this sequence through the model will result in " <ide> "indexing errors".format(len(ids), self.max_len)) <del> <add> <ide> return encoded_inputs <ide> <ide> def truncate_sequences(self, ids, pair_ids=None, num_tokens_to_remove=0, truncation_strategy='longest_first', stride=0): <ide><path>transformers/tokenization_xlm.py <ide> class XLMTokenizer(PreTrainedTokenizer): <ide> <ide> - argument ``special_tokens`` and function ``set_special_tokens``, can be used to add additional symbols \ <ide> (ex: "__classify__") to a vocabulary <del> <add> <ide> - `lang2id` attribute maps the languages supported by the model with their ids if provided (automatically set for pretrained vocabularies) <ide> <ide> - `id2lang` attributes does reverse mapping if provided (automatically set for pretrained vocabularies) <ide> def __init__(self, vocab_file, merges_file, unk_token="<unk>", bos_token="<s>", <ide> self.ja_word_tokenizer = None <ide> self.zh_word_tokenizer = None <ide> <del> self.encoder = json.load(open(vocab_file, encoding="utf-8")) <add> with open(vocab_file, encoding="utf-8") as vocab_handle: <add> self.encoder = json.load(vocab_handle) <ide> self.decoder = {v:k for k,v in self.encoder.items()} <del> merges = open(merges_file, encoding='utf-8').read().split('\n')[:-1] <add> with open(merges_file, encoding='utf-8') as merges_handle: <add> merges = merges_handle.read().split('\n')[:-1] <ide> merges = [tuple(merge.split()[:2]) for merge in merges] <ide> self.bpe_ranks = dict(zip(merges, range(len(merges)))) <ide> self.cache = {} <ide><path>transformers/tokenization_xlnet.py <ide> def _tokenize(self, text, return_unicode=True, sample=False): <ide> pieces = self.sp_model.SampleEncodeAsPieces(text, 64, 0.1) <ide> new_pieces = [] <ide> for piece in pieces: <del> if len(piece) > 1 and piece[-1] == ',' and piece[-2].isdigit(): <add> if len(piece) > 1 and piece[-1] == str(',') and piece[-2].isdigit(): <ide> cur_pieces = self.sp_model.EncodeAsPieces( <ide> piece[:-1].replace(SPIECE_UNDERLINE, '')) <ide> if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE: <ide> def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None): <ide> An XLNet sequence pair mask has the following format: <ide> 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 2 <ide> | first sequence | second sequence | CLS segment ID <del> <add> <ide> if token_ids_1 is None, only returns the first portion of the mask (0's). <ide> """ <ide> sep = [self.sep_token_id]
50
PHP
PHP
fix some formatting issues
16c0e3e6c176055bef248eb88b385c881fb13ed6
<ide><path>src/Illuminate/Console/Command.php <ide> use Symfony\Component\Console\Input\InputInterface; <ide> use Symfony\Component\Console\Output\OutputInterface; <ide> use Symfony\Component\Console\Question\ChoiceQuestion; <del>use Symfony\Component\Console\Command\Command as SymfonyCommand; <ide> use Symfony\Component\Console\Formatter\OutputFormatterStyle; <add>use Symfony\Component\Console\Command\Command as SymfonyCommand; <ide> use Illuminate\Contracts\Foundation\Application as LaravelApplication; <ide> <ide> class Command extends SymfonyCommand <ide> public function error($string) <ide> public function warn($string) <ide> { <ide> $style = new OutputFormatterStyle('yellow'); <add> <ide> $this->output->getFormatter()->setStyle('warning', $style); <add> <ide> $this->output->writeln("<warning>$string</warning>"); <ide> } <ide>
1
Python
Python
add type annotations to setup.py
402274641168f412f44c545c34f3e7edf5cf1476
<ide><path>setup.py <ide> class CleanCommand(Command): <ide> description = "Tidy up the project root" <ide> user_options: List[str] = [] <ide> <del> def initialize_options(self): <add> def initialize_options(self) -> None: <ide> """Set default values for options.""" <ide> <del> def finalize_options(self): <add> def finalize_options(self) -> None: <ide> """Set final values for options.""" <ide> <ide> @staticmethod <del> def rm_all_files(files: List[str]): <add> def rm_all_files(files: List[str]) -> None: <ide> """Remove all files from the list""" <ide> for file in files: <ide> try: <ide> os.remove(file) <ide> except Exception as e: # noqa pylint: disable=broad-except <ide> logger.warning("Error when removing %s: %s", file, e) <ide> <del> def run(self): <add> def run(self) -> None: <ide> """Remove temporary files and directories.""" <ide> os.chdir(my_dir) <ide> self.rm_all_files(glob.glob('./build/*')) <ide> class CompileAssets(Command): <ide> description = "Compile and build the frontend assets" <ide> user_options: List[str] = [] <ide> <del> def initialize_options(self): <add> def initialize_options(self) -> None: <ide> """Set default values for options.""" <ide> <del> def finalize_options(self): <add> def finalize_options(self) -> None: <ide> """Set final values for options.""" <ide> <del> def run(self): # noqa <add> def run(self) -> None: # noqa <ide> """Run a command to compile and build assets.""" <ide> subprocess.check_call('./airflow/www/compile_assets.sh') <ide> <ide> class ListExtras(Command): <ide> description = "List available extras" <ide> user_options: List[str] = [] <ide> <del> def initialize_options(self): <add> def initialize_options(self) -> None: <ide> """Set default values for options.""" <ide> <del> def finalize_options(self): <add> def finalize_options(self) -> None: <ide> """Set final values for options.""" <ide> <del> def run(self): # noqa <add> def run(self) -> None: # noqa <ide> """List extras.""" <ide> print("\n".join(wrap(", ".join(EXTRAS_REQUIREMENTS.keys()), 100))) <ide> <ide> def git_version(version_: str) -> str: <ide> return 'no_git_version' <ide> <ide> <del>def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version"])): <add>def write_version(filename: str = os.path.join(*[my_dir, "airflow", "git_version"])) -> None: <ide> """ <ide> Write the Semver version + git hash to file, e.g. ".dev0+2f635dc265e78db6708f59f68e8009abb92c1e65". <ide> <ide> def add_all_deprecated_provider_packages() -> None: <ide> ) <ide> <ide> <del>def is_package_excluded(package: str, exclusion_list: List[str]): <add>def is_package_excluded(package: str, exclusion_list: List[str]) -> bool: <ide> """ <ide> Checks if package should be excluded. <ide> <ide> def sort_extras_requirements() -> Dict[str, List[str]]: <ide> ] <ide> <ide> <del>def get_provider_package_from_package_id(package_id: str): <add>def get_provider_package_from_package_id(package_id: str) -> str: <ide> """ <ide> Builds the name of provider package out of the package id provided/ <ide> <ide> def get_provider_package_from_package_id(package_id: str): <ide> return f"apache-airflow-providers-{package_suffix}" <ide> <ide> <del>def get_excluded_providers(): <add>def get_excluded_providers() -> List[str]: <ide> """ <ide> Returns packages excluded for the current python version. <ide> <ide> def get_excluded_providers(): <ide> return ['apache.hive'] if PY39 else [] <ide> <ide> <del>def get_all_provider_packages(): <add>def get_all_provider_packages() -> str: <ide> """Returns all provider packages configured in setup.py""" <ide> excluded_providers = get_excluded_providers() <ide> return " ".join( <ide> class AirflowDistribution(Distribution): <ide> <ide> """ <ide> <del> def parse_config_files(self, *args, **kwargs): # pylint: disable=signature-differs <add> def parse_config_files(self, *args, **kwargs) -> None: # pylint: disable=signature-differs <ide> """ <ide> Ensure that when we have been asked to install providers from sources <ide> that we don't *also* try to install those providers from PyPI. <ide> def add_all_provider_packages() -> None: <ide> class Develop(develop_orig): <ide> """Forces removal of providers in editable mode.""" <ide> <del> def run(self): <add> def run(self) -> None: <ide> self.announce('Installing in editable mode. Uninstalling provider packages!', level=log.INFO) <ide> # We need to run "python3 -m pip" because it might be that older PIP binary is in the path <ide> # And it results with an error when running pip directly (cannot import pip module) <ide> def run(self): <ide> class Install(install_orig): <ide> """Forces installation of providers from sources in editable mode.""" <ide> <del> def run(self): <add> def run(self) -> None: <ide> self.announce('Standard installation. Providers are installed from packages', level=log.INFO) <ide> super().run() <ide>
1
Java
Java
improve exceptions for multi-operand expressions
bff36fb1456ff498354960a725f63f9116ee5b74
<ide><path>spring-expression/src/main/java/org/springframework/expression/spel/SpelMessage.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public enum SpelMessage { <ide> OPERAND_NOT_INCREMENTABLE(Kind.ERROR,1066,"the expression component ''{0}'' does not support increment"), // <ide> OPERAND_NOT_DECREMENTABLE(Kind.ERROR,1067,"the expression component ''{0}'' does not support decrement"), // <ide> NOT_ASSIGNABLE(Kind.ERROR,1068,"the expression component ''{0}'' is not assignable"), // <del> ; <add> MISSING_CHARACTER(Kind.ERROR,1069,"missing expected character ''{0}''"), <add> LEFT_OPERAND_PROBLEM(Kind.ERROR,1070, "Problem parsing left operand"); <ide> <ide> private Kind kind; <ide> private int code; <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/InternalSpelExpressionParser.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 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> * Hand written SpEL parser. Instances are reusable but are not thread safe. <ide> * <ide> * @author Andy Clement <add> * @author Phillip Webb <ide> * @since 3.0 <ide> */ <ide> class InternalSpelExpressionParser extends TemplateAwareExpressionParser { <ide> private SpelNodeImpl eatExpression() { <ide> Token t = peekToken(); <ide> if (t.kind==TokenKind.ASSIGN) { // a=b <ide> if (expr==null) { <del> expr = new NullLiteral(toPos(t.startpos-1,t.endpos-1)); <del> } <add> expr = new NullLiteral(toPos(t.startpos-1,t.endpos-1)); <add> } <ide> nextToken(); <ide> SpelNodeImpl assignedValue = eatLogicalOrExpression(); <ide> return new Assign(toPos(t),expr,assignedValue); <ide> private SpelNodeImpl eatLogicalOrExpression() { <ide> while (peekIdentifierToken("or") || peekToken(TokenKind.SYMBOLIC_OR)) { <ide> Token t = nextToken(); //consume OR <ide> SpelNodeImpl rhExpr = eatLogicalAndExpression(); <del> checkRightOperand(t,rhExpr); <add> checkOperands(t,expr,rhExpr); <ide> expr = new OpOr(toPos(t),expr,rhExpr); <ide> } <ide> return expr; <ide> private SpelNodeImpl eatLogicalAndExpression() { <ide> while (peekIdentifierToken("and") || peekToken(TokenKind.SYMBOLIC_AND)) { <ide> Token t = nextToken();// consume 'AND' <ide> SpelNodeImpl rhExpr = eatRelationalExpression(); <del> checkRightOperand(t,rhExpr); <add> checkOperands(t,expr,rhExpr); <ide> expr = new OpAnd(toPos(t),expr,rhExpr); <ide> } <ide> return expr; <ide> private SpelNodeImpl eatRelationalExpression() { <ide> if (relationalOperatorToken != null) { <ide> Token t = nextToken(); //consume relational operator token <ide> SpelNodeImpl rhExpr = eatSumExpression(); <del> checkRightOperand(t,rhExpr); <add> checkOperands(t,expr,rhExpr); <ide> TokenKind tk = relationalOperatorToken.kind; <ide> if (relationalOperatorToken.isNumericRelationalOperator()) { <ide> int pos = toPos(t); <ide> private SpelNodeImpl eatProductExpression() { <ide> while (peekToken(TokenKind.STAR,TokenKind.DIV,TokenKind.MOD)) { <ide> Token t = nextToken(); // consume STAR/DIV/MOD <ide> SpelNodeImpl rhExpr = eatPowerIncDecExpression(); <del> checkRightOperand(t,rhExpr); <add> checkOperands(t,expr,rhExpr); <ide> if (t.kind==TokenKind.STAR) { <ide> expr = new OpMultiply(toPos(t),expr,rhExpr); <ide> } else if (t.kind==TokenKind.DIV) { <ide> public String toString(Token t) { <ide> } <ide> } <ide> <add> private void checkOperands(Token token, SpelNodeImpl left, SpelNodeImpl right) { <add> checkLeftOperand(token, left); <add> checkRightOperand(token, right); <add> } <add> <add> private void checkLeftOperand(Token token, SpelNodeImpl operandExpression) { <add> if (operandExpression==null) { <add> raiseInternalException(token.startpos,SpelMessage.LEFT_OPERAND_PROBLEM); <add> } <add> } <add> <ide> private void checkRightOperand(Token token, SpelNodeImpl operandExpression) { <ide> if (operandExpression==null) { <ide> raiseInternalException(token.startpos,SpelMessage.RIGHT_OPERAND_PROBLEM); <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/standard/Tokenizer.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2013 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> * Lex some input data into a stream of tokens that can then be parsed. <ide> * <ide> * @author Andy Clement <add> * @author Phillip Webb <ide> * @since 3.0 <ide> */ <ide> class Tokenizer { <ide> public void process() { <ide> } <ide> break; <ide> case '&': <del> if (isTwoCharToken(TokenKind.SYMBOLIC_AND)) { <del> pushPairToken(TokenKind.SYMBOLIC_AND); <add> if (!isTwoCharToken(TokenKind.SYMBOLIC_AND)) { <add> throw new InternalParseException(new SpelParseException( <add> expressionString, pos, <add> SpelMessage.MISSING_CHARACTER, "&")); <ide> } <add> pushPairToken(TokenKind.SYMBOLIC_AND); <ide> break; <ide> case '|': <del> if (isTwoCharToken(TokenKind.SYMBOLIC_OR)) { <del> pushPairToken(TokenKind.SYMBOLIC_OR); <add> if (!isTwoCharToken(TokenKind.SYMBOLIC_OR)) { <add> throw new InternalParseException(new SpelParseException( <add> expressionString, pos, <add> SpelMessage.MISSING_CHARACTER, "|")); <ide> } <add> pushPairToken(TokenKind.SYMBOLIC_OR); <ide> break; <ide> case '?': <ide> if (isTwoCharToken(TokenKind.SELECT)) { <ide><path>spring-expression/src/test/java/org/springframework/expression/spel/SpelReproTests.java <ide> <ide> package org.springframework.expression.spel; <ide> <add>import static org.junit.Assert.assertEquals; <add>import static org.junit.Assert.assertFalse; <add>import static org.junit.Assert.assertTrue; <add>import static org.junit.Assert.fail; <add> <ide> import java.lang.reflect.Field; <ide> import java.lang.reflect.Method; <ide> import java.util.ArrayList; <ide> import java.util.Properties; <ide> <ide> import org.junit.Ignore; <add>import org.junit.Rule; <ide> import org.junit.Test; <del> <add>import org.junit.rules.ExpectedException; <ide> import org.springframework.core.convert.TypeDescriptor; <ide> import org.springframework.expression.AccessException; <ide> import org.springframework.expression.BeanResolver; <ide> import org.springframework.expression.spel.support.StandardTypeLocator; <ide> import org.springframework.expression.spel.testresources.le.div.mod.reserved.Reserver; <ide> <del>import static org.junit.Assert.*; <del> <ide> /** <ide> * Reproduction tests cornering various SpEL JIRA issues. <ide> * <ide> */ <ide> public class SpelReproTests extends ExpressionTestCase { <ide> <add> @Rule <add> public ExpectedException thrown = ExpectedException.none(); <add> <ide> @Test <ide> public void testNPE_SPR5661() { <ide> evaluate("joinThreeStrings('a',null,'c')", "anullc", String.class); <ide> public void SPR_10091_primitiveTestValue() { <ide> Object value = parser.parseExpression("primitiveProperty").getValue(evaluationContext); <ide> } <ide> <add> @Test <add> public void SPR_10146_malformedExpressions() throws Exception { <add> doTestSpr10146("/foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146("*foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146("%foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146("<foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146(">foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146("&&foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146("||foo", "EL1070E:(pos 0): Problem parsing left operand"); <add> doTestSpr10146("&foo", "EL1069E:(pos 0): missing expected character '&'"); <add> doTestSpr10146("|foo", "EL1069E:(pos 0): missing expected character '|'"); <add> } <add> <add> private void doTestSpr10146(String expression, String expectedMessage) { <add> thrown.expect(SpelParseException.class); <add> thrown.expectMessage(expectedMessage); <add> new SpelExpressionParser().parseExpression(expression); <add> } <ide> <ide> public static class BooleanHolder { <ide>
4
Text
Text
update react lesson link (remove 404)
7f6a653c289d61cc0286e887cbb836ae2a51d226
<ide><path>curriculum/challenges/english/03-front-end-libraries/react/introducing-inline-styles.english.md <ide> forumTopicId: 301395 <ide> <ide> ## Description <ide> <section id='description'> <del>There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of <a target="_blank" href="learn/front-end-libraries/react/define-an-html-class-in-jsx"> the way you apply classes to JSX elements</a>. <add>There are other complex concepts that add powerful capabilities to your React code. But you may be wondering about the more simple problem of how to style those JSX elements you create in React. You likely know that it won't be exactly the same as working with HTML because of <a target="_blank" href="/learn/front-end-libraries/react/define-an-html-class-in-jsx"> the way you apply classes to JSX elements</a>. <ide> If you import styles from a stylesheet, it isn't much different at all. You apply a class to your JSX element using the <code>className</code> attribute, and apply styles to the class in your stylesheet. Another option is to apply inline styles, which are very common in ReactJS development. <ide> You apply inline styles to JSX elements similar to how you do it in HTML, but with a few JSX differences. Here's an example of an inline style in HTML: <ide> <code>&lt;div style="color: yellow; font-size: 16px"&gt;Mellow Yellow&lt;/div&gt;</code>
1
Go
Go
create the bridge device with ioctl
7a94cdf8edd917899a38a58917cd4439652047a1
<ide><path>network.go <ide> import ( <ide> "net" <ide> "strconv" <ide> "sync" <add> "syscall" <add> "unsafe" <ide> ) <ide> <ide> const ( <ide> DefaultNetworkBridge = "docker0" <ide> DisableNetworkBridge = "none" <ide> portRangeStart = 49153 <ide> portRangeEnd = 65535 <add> siocBRADDBR = 0x89a0 <ide> ) <ide> <ide> // Calculates the first and last IP addresses in an IPNet <ide> func CreateBridgeIface(config *DaemonConfig) error { <ide> } <ide> utils.Debugf("Creating bridge %s with network %s", config.BridgeIface, ifaceAddr) <ide> <del> if err := netlink.NetworkLinkAdd(config.BridgeIface, "bridge"); err != nil { <del> return fmt.Errorf("Error creating bridge: %s", err) <add> if err := createBridgeIface(config.BridgeIface); err != nil { <add> return err <ide> } <ide> iface, err := net.InterfaceByName(config.BridgeIface) <ide> if err != nil { <ide> func CreateBridgeIface(config *DaemonConfig) error { <ide> return nil <ide> } <ide> <add>// Create the actual bridge device. This is more backward-compatible than <add>// netlink.NetworkLinkAdd and works on RHEL 6. <add>func createBridgeIface(name string) error { <add> s, err := syscall.Socket(syscall.AF_INET6, syscall.SOCK_STREAM, syscall.IPPROTO_IP) <add> if err != nil { <add> return fmt.Errorf("Error creating bridge creation socket: %s", err) <add> } <add> defer syscall.Close(s) <add> <add> nameBytePtr, err := syscall.BytePtrFromString(name) <add> if err != nil { <add> return fmt.Errorf("Error converting bridge name %s to byte array: %s", name, err) <add> } <add> <add> if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, uintptr(s), siocBRADDBR, uintptr(unsafe.Pointer(nameBytePtr))); err != 0 { <add> return fmt.Errorf("Error creating bridge: %s", err) <add> } <add> return nil <add>} <add> <ide> // Return the IPv4 address of a network interface <ide> func getIfaceAddr(name string) (net.Addr, error) { <ide> iface, err := net.InterfaceByName(name)
1