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
Go
Go
add missing defer to delete temp dir
51e721ab072441ba6ae14b84613cf2b3acd6316b
<ide><path>cliconfig/config_test.go <ide> func TestJsonSaveWithNoFile(t *testing.T) { <ide> t.Fatalf("Expected error. File should not have been able to save with no file name.") <ide> } <ide> <del> tmpHome, _ := ioutil.TempDir("", "config-test") <add> tmpHome, err := ioutil.TempDir("", "config-test") <add> if err != nil { <add> t.Fatalf("Failed to create a temp dir: %q", err) <add> } <add> defer os.RemoveAll(tmpHome) <add> <ide> fn := filepath.Join(tmpHome, ConfigFileName) <ide> f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) <ide> err = config.SaveToWriter(f) <ide> func TestLegacyJsonSaveWithNoFile(t *testing.T) { <ide> t.Fatalf("Expected error. File should not have been able to save with no file name.") <ide> } <ide> <del> tmpHome, _ := ioutil.TempDir("", "config-test") <add> tmpHome, err := ioutil.TempDir("", "config-test") <add> if err != nil { <add> t.Fatalf("Failed to create a temp dir: %q", err) <add> } <add> defer os.RemoveAll(tmpHome) <add> <ide> fn := filepath.Join(tmpHome, ConfigFileName) <ide> f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) <ide> err = config.SaveToWriter(f) <ide><path>integration-cli/docker_cli_build_test.go <ide> func (s *DockerSuite) TestBuildRenamedDockerfile(c *check.C) { <ide> c.Fatalf("test4 should have used dFile, output:%s", out) <ide> } <ide> <del> dirWithNoDockerfile, _ := ioutil.TempDir(os.TempDir(), "test5") <add> dirWithNoDockerfile, err := ioutil.TempDir(os.TempDir(), "test5") <add> c.Assert(err, check.IsNil) <ide> nonDockerfileFile := filepath.Join(dirWithNoDockerfile, "notDockerfile") <ide> if _, err = os.Create(nonDockerfileFile); err != nil { <ide> c.Fatal(err) <ide><path>integration-cli/docker_cli_config_test.go <ide> func (s *DockerSuite) TestConfigHttpHeader(c *check.C) { <ide> <ide> homeKey := homedir.Key() <ide> homeVal := homedir.Get() <del> tmpDir, _ := ioutil.TempDir("", "fake-home") <add> tmpDir, err := ioutil.TempDir("", "fake-home") <add> c.Assert(err, check.IsNil) <ide> defer os.RemoveAll(tmpDir) <ide> <ide> dotDocker := filepath.Join(tmpDir, ".docker") <ide> func (s *DockerSuite) TestConfigHttpHeader(c *check.C) { <ide> "HttpHeaders": { "MyHeader": "MyValue" } <ide> }` <ide> <del> err := ioutil.WriteFile(tmpCfg, []byte(data), 0600) <add> err = ioutil.WriteFile(tmpCfg, []byte(data), 0600) <ide> if err != nil { <ide> c.Fatalf("Err creating file(%s): %v", tmpCfg, err) <ide> } <ide> func (s *DockerSuite) TestConfigHttpHeader(c *check.C) { <ide> } <ide> <ide> func (s *DockerSuite) TestConfigDir(c *check.C) { <del> cDir, _ := ioutil.TempDir("", "fake-home") <add> cDir, err := ioutil.TempDir("", "fake-home") <add> c.Assert(err, check.IsNil) <add> defer os.RemoveAll(cDir) <ide> <ide> // First make sure pointing to empty dir doesn't generate an error <ide> out, rc := dockerCmd(c, "--config", cDir, "ps") <ide> func (s *DockerSuite) TestConfigDir(c *check.C) { <ide> // Test with env var too <ide> cmd := exec.Command(dockerBinary, "ps") <ide> cmd.Env = append(os.Environ(), "DOCKER_CONFIG="+cDir) <del> out, rc, err := runCommandWithOutput(cmd) <add> out, rc, err = runCommandWithOutput(cmd) <ide> <ide> if rc != 0 || err != nil { <ide> c.Fatalf("ps2 didn't work:\nrc:%d\nout%s\nerr:%v", rc, out, err)
3
PHP
PHP
use null coalescing operator to refactor
7a7cacc3fd02d7d4c596c1a0f8af3c5b7a2990b4
<ide><path>src/Illuminate/Http/Concerns/InteractsWithInput.php <ide> public function allFiles() <ide> { <ide> $files = $this->files->all(); <ide> <del> return $this->convertedFiles <del> ? $this->convertedFiles <del> : $this->convertedFiles = $this->convertUploadedFiles($files); <add> return $this->convertedFiles = $this->convertedFiles ?? $this->convertUploadedFiles($files); <ide> } <ide> <ide> /**
1
Ruby
Ruby
add code and message to test response as per
518540a06734b56d3b56277bf79bb7df95f6980b
<ide><path>actionpack/lib/action_controller/test_process.rb <ide> def response_code <ide> headers['Status'][0,3].to_i rescue 0 <ide> end <ide> <add> def code <add> headers['Status'].to_s.split(' ')[0] <add> end <add> <add> def message <add> headers['Status'].to_s.split(' ',2)[1] <add> end <add> <ide> # was the response successful? <ide> def success? <ide> response_code == 200
1
Python
Python
fix regression in a hidden callback use case
7df963b400f3dcf85e679e6f00af8c3c12971347
<ide><path>numpy/f2py/cb_rules.py <ide> jmp_buf jmpbuf; <ide> } #name#_t; <ide> <del>static void show_#name#(#name#_t *ptr) { <del> if (ptr != NULL) { <del> CFUNCSMESSPY(\"show_#name#: capi=\", ptr->capi); <del> CFUNCSMESSPY(\"show_#name#: args_capi=\", ptr->args_capi); <del> } else { <del> CFUNCSMESS(\"show_#name#: ptr=NULL\\n"); <del> } <del>} <del> <ide> #if defined(F2PY_THREAD_LOCAL_DECL) && !defined(F2PY_USE_PYTHON_TLS) <ide> <ide> static F2PY_THREAD_LOCAL_DECL #name#_t *_active_#name# = NULL; <ide> <ide> static #name#_t *swap_active_#name#(#name#_t *ptr) { <del> CFUNCSMESS2(\"swap_active_#name#: active=%p, ptr=%p\\n", _active_#name#, ptr); <ide> #name#_t *prev = _active_#name#; <ide> _active_#name# = ptr; <ide> return prev; <ide> <ide> /*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/ <ide> #static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) { <add> #name#_t cb_local = { NULL, NULL, 0 }; <ide> #name#_t *cb = NULL; <ide> PyTupleObject *capi_arglist = NULL; <ide> PyObject *capi_return = NULL; <ide> f2py_cb_start_clock(); <ide> #endif <ide> cb = get_active_#name#(); <del> show_#name#(cb); <ide> if (cb == NULL) { <ide> capi_longjmp_ok = 0; <del> PyErr_SetString(#modulename#_error,\"cb: No active callback #name#!\\n\"); <del> goto capi_fail; <add> cb = &cb_local; <ide> } <ide> capi_arglist = cb->args_capi; <ide> CFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\"); <ide> CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi); <ide> if (cb->capi==NULL) { <ide> capi_longjmp_ok = 0; <ide> cb->capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\"); <add> CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi); <ide> } <ide> if (cb->capi==NULL) { <ide> PyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\"); <ide> } <ide> #endtitle# <ide> """, <del> 'need': ['setjmp.h', 'CFUNCSMESS', 'CFUNCSMESSPY', 'F2PY_THREAD_LOCAL_DECL'], <add> 'need': ['setjmp.h', 'CFUNCSMESS', 'F2PY_THREAD_LOCAL_DECL'], <ide> 'maxnofargs': '#maxnofargs#', <ide> 'nofoptargs': '#nofoptargs#', <ide> 'docstr': """\ <ide><path>numpy/f2py/cfuncs.py <ide> cppmacros['CFUNCSMESS'] = """\ <ide> #ifdef DEBUGCFUNCS <ide> #define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess); <del>#define CFUNCSMESS1(mess, arg) fprintf(stderr,\"debug-capi:\"mess, arg); <del>#define CFUNCSMESS2(mess, arg1, arg2) fprintf(stderr,\"debug-capi:\"mess, arg1, arg2); <ide> #define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\ <ide> PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ <ide> fprintf(stderr,\"\\n\"); <ide> #else <ide> #define CFUNCSMESS(mess) <del>#define CFUNCSMESS1(mess, arg) <del>#define CFUNCSMESS2(mess, arg1, arg2) <ide> #define CFUNCSMESSPY(mess,obj) <ide> #endif <ide> """ <ide><path>numpy/f2py/rules.py <ide> {l_not(isintent_callback): """ fprintf(stderr,\"#vardebugshowvalue# (call-back in C).\\n\",#cbname#);"""}]}, <ide> """\ <ide> CFUNCSMESS(\"Saving callback variables for `#varname#`.\\n\"); <del> show_#cbname#(#varname#_cb_ptr); <del> #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr); <del> show_#cbname#(#varname#_cb_ptr); <del> """, <add> #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr);""", <ide> ], <ide> 'cleanupfrompyobj': <ide> """\ <ide> CFUNCSMESS(\"Restoring callback variables for `#varname#`.\\n\"); <del> show_#cbname#(#varname#_cb_ptr); <ide> #varname#_cb_ptr = swap_active_#cbname#(#varname#_cb_ptr); <del> show_#cbname#(#varname#_cb_ptr); <ide> Py_DECREF(#varname#_cb.args_capi); <ide> }""", <ide> 'need': ['SWAP', 'create_cb_arglist'], <ide><path>numpy/f2py/tests/test_callback.py <ide> class TestF77Callback(util.F2PyTest): <ide> <ide> a = callback(cu, lencu) <ide> end <add> <add> subroutine hidden_callback(a, r) <add> external global_f <add>cf2py intent(callback, hide) global_f <add> integer a, r, global_f <add>cf2py intent(out) r <add> r = global_f(a) <add> end <add> <add> subroutine hidden_callback2(a, r) <add> external global_f <add> integer a, r, global_f <add>cf2py intent(out) r <add> r = global_f(a) <add> end <ide> """ <ide> <ide> @pytest.mark.parametrize('name', 't,t2'.split(',')) <ide> def runner(name): <ide> if errors: <ide> raise AssertionError(errors) <ide> <add> def test_hidden_callback(self): <add> try: <add> self.module.hidden_callback(2) <add> except Exception as msg: <add> assert_(str(msg).startswith('Callback global_f not defined')) <add> <add> try: <add> self.module.hidden_callback2(2) <add> except Exception as msg: <add> assert_(str(msg).startswith('cb: Callback global_f not defined')) <add> <add> self.module.global_f = lambda x: x + 1 <add> r = self.module.hidden_callback(2) <add> assert_(r == 3) <add> <add> self.module.global_f = lambda x: x + 2 <add> r = self.module.hidden_callback(2) <add> assert_(r == 4) <add> <add> del self.module.global_f <add> try: <add> self.module.hidden_callback(2) <add> except Exception as msg: <add> assert_(str(msg).startswith('Callback global_f not defined')) <add> <add> self.module.global_f = lambda x=0: x + 3 <add> r = self.module.hidden_callback(2) <add> assert_(r == 5) <add> <add> # reproducer of gh18341 <add> r = self.module.hidden_callback2(2) <add> assert_(r == 3) <add> <ide> <ide> class TestF77CallbackPythonTLS(TestF77Callback): <ide> """ <ide><path>numpy/f2py/tests/util.py <ide> def build_module(source_files, options=[], skip=[], only=[], module_name=None): <ide> Compile and import a f2py module, built from the given files. <ide> <ide> """ <del> options = options + ['--debug-capi'] <add> <ide> code = ("import sys; sys.path = %s; import numpy.f2py as f2py2e; " <ide> "f2py2e.main()" % repr(sys.path)) <ide>
5
Text
Text
add missing spaces [ci skip]
233946654272562dc73e471ac34cf4df31934a57
<ide><path>guides/source/active_record_migrations.md <ide> ActiveRecord::Schema.define(version: 20080906171750) do <ide> <ide> create_table "products", force: true do |t| <ide> t.string "name" <del> t.text "description" <add> t.text "description" <ide> t.datetime "created_at" <ide> t.datetime "updated_at" <del> t.string "part_number" <add> t.string "part_number" <ide> end <ide> end <ide> ```
1
Go
Go
use hostip to decide on portmapper version
5d3b0102f71fa7691f62377826c48487eabf94d6
<ide><path>libnetwork/drivers/bridge/port_mapping.go <ide> func (n *bridgeNetwork) allocatePort(bnd *types.PortBinding, ulPxyEnabled bool) <ide> <ide> portmapper := n.portMapper <ide> <del> if bnd.IP.To4() == nil { <add> if bnd.HostIP.To4() == nil { <ide> portmapper = n.portMapperV6 <ide> } <ide>
1
PHP
PHP
add tests for resource()
966388080dbd2341ed3e5f68fafe51dbcc1ab51d
<ide><path>src/Routing/ScopedRouteCollection.php <ide> public function get($name) { <ide> * @return array Array of mapped resources <ide> */ <ide> public function resource($name, $options = [], $callback = null) { <add> if (is_callable($options) && $callback === null) { <add> $callback = $options; <add> $options = []; <add> } <ide> $options += array( <ide> 'connectOptions' => [], <ide> 'id' => static::ID . '|' . static::UUID <ide> public function resource($name, $options = [], $callback = null) { <ide> unset($options['connectOptions']); <ide> <ide> $urlName = Inflector::underscore($name); <del> $ext = null; <ide> <add> $ext = null; <ide> if (!empty($options['_ext'])) { <ide> $ext = $options['_ext']; <ide> } <ide> public function resource($name, $options = [], $callback = null) { <ide> <ide> if (is_callable($callback)) { <ide> $idName = Inflector::singularize($urlName) . '_id'; <del> $path = '/' . $urlName . '/:' . $idName; <add> $path = $this->_path . '/' . $urlName . '/:' . $idName; <ide> Router::scope($path, $this->params(), $callback); <ide> } <ide> } <ide><path>tests/TestCase/Routing/ScopedRouteCollectionTest.php <ide> public function testConnectBasic() { <ide> */ <ide> public function testConnectExtensions() { <ide> $routes = new ScopedRouteCollection('/l', [], ['json']); <add> $this->assertEquals(['json'], $routes->extensions()); <add> <ide> $routes->connect('/:controller'); <ide> $route = $routes->routes()[0]; <ide> <ide> public function testMatch() { <ide> $this->assertFalse($result, 'No matches'); <ide> } <ide> <add>/** <add> * Test matching plugin routes. <add> * <add> * @return void <add> */ <add> public function testMatchPlugin() { <add> $context = [ <add> '_base' => '/', <add> '_scheme' => 'http', <add> '_host' => 'example.org', <add> ]; <add> $routes = new ScopedRouteCollection('/contacts', ['plugin' => 'Contacts']); <add> $routes->connect('/', ['controller' => 'Contacts']); <add> <add> $result = $routes->match( <add> ['plugin' => 'Contacts', 'controller' => 'Contacts', 'action' => 'index'], <add> $context <add> ); <add> $this->assertFalse($result); <add> <add> $result = $routes->match(['controller' => 'Contacts', 'action' => 'index'], $context); <add> $this->assertFalse($result); <add> } <add> <add>/** <add> * Test connecting resources. <add> * <add> * @return void <add> */ <add> public function testResource() { <add> $routes = new ScopedRouteCollection('/api', ['prefix' => 'api']); <add> $routes->resource('Articles', ['_ext' => 'json']); <add> <add> $all = $routes->routes(); <add> $this->assertCount(6, $all); <add> <add> $this->assertEquals('/api/articles', $all[0]->template); <add> $this->assertEquals('json', $all[0]->defaults['_ext']); <add> $this->assertEquals('Articles', $all[0]->defaults['controller']); <add> } <add> <add>/** <add> * Test nesting resources <add> * <add> * @return void <add> */ <add> public function testResourceNested() { <add> $routes = new ScopedRouteCollection('/api', ['prefix' => 'api']); <add> $routes->resource('Articles', function($routes) { <add> $this->assertEquals('/api/articles/', $routes->path()); <add> $this->assertEquals(['prefix' => 'api'], $routes->params()); <add> <add> $routes->resource('Comments'); <add> $route = $routes->routes()[0]; <add> $this->assertEquals('/api/articles/:article_id/comments', $route->template); <add> }); <add> } <add> <ide> }
2
Ruby
Ruby
add process_type to service dsl
698f4a8f6999d3faee87ae6321274b58d7ae13e8
<ide><path>Library/Homebrew/service.rb <ide> class Service <ide> RUN_TYPE_INTERVAL = "interval" <ide> RUN_TYPE_CRON = "cron" <ide> <add> PROCESS_TYPE_BACKGROUND = "background" <add> PROCESS_TYPE_STANDARD = "standard" <add> PROCESS_TYPE_INTERACTIVE = "interactive" <add> PROCESS_TYPE_ADAPTIVE = "adaptive" <add> <ide> # sig { params(formula: Formula).void } <ide> def initialize(formula, &block) <ide> @formula = formula <ide> def restart_delay(value = nil) <ide> end <ide> end <ide> <add> sig { params(type: T.nilable(String)).returns(T.nilable(String)) } <add> def process_type(type = nil) <add> case T.unsafe(type) <add> when nil <add> @process_type <add> when PROCESS_TYPE_BACKGROUND, PROCESS_TYPE_STANDARD, PROCESS_TYPE_INTERACTIVE, PROCESS_TYPE_ADAPTIVE <add> @process_type = type.to_s <add> when String <add> raise TypeError, "Service#process_type allows: "\ <add> "'#{PROCESS_TYPE_BACKGROUND}'/'#{PROCESS_TYPE_STANDARD}'/"\ <add> "'#{PROCESS_TYPE_INTERACTIVE}'/'#{PROCESS_TYPE_ADAPTIVE}'" <add> else <add> raise TypeError, "Service#process_type expects a String" <add> end <add> end <add> <ide> sig { params(type: T.nilable(T.any(String, Symbol))).returns(T.nilable(String)) } <ide> def run_type(type = nil) <ide> case T.unsafe(type) <ide> def to_plist <ide> base[:KeepAlive] = @keep_alive if @keep_alive == true <ide> base[:LegacyTimers] = @macos_legacy_timers if @macos_legacy_timers == true <ide> base[:TimeOut] = @restart_delay if @restart_delay.present? <add> base[:ProcessType] = @process_type.capitalize if @process_type.present? <ide> base[:WorkingDirectory] = @working_dir if @working_dir.present? <ide> base[:RootDirectory] = @root_dir if @root_dir.present? <ide> base[:StandardInPath] = @input_path if @input_path.present? <ide><path>Library/Homebrew/test/service_spec.rb <ide> root_dir var <ide> working_dir var <ide> keep_alive true <add> process_type "interactive" <ide> restart_delay 30 <ide> macos_legacy_timers true <ide> end <ide> \t<string>homebrew.mxcl.formula_name</string> <ide> \t<key>LegacyTimers</key> <ide> \t<true/> <add> \t<key>ProcessType</key> <add> \t<string>Interactive</string> <ide> \t<key>ProgramArguments</key> <ide> \t<array> <ide> \t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string> <ide> root_dir var <ide> working_dir var <ide> keep_alive true <add> process_type "interactive" <ide> restart_delay 30 <ide> macos_legacy_timers true <ide> end
2
Ruby
Ruby
add error message that cask was installed manually
5f62f417fd1b86bb664afa364d2af2972bb489d6
<ide><path>Library/Homebrew/cask/cmd/upgrade.rb <ide> def self.upgrade_casks( <ide> cask.artifacts.any?(Artifact::Installer::ManualInstaller) <ide> end <ide> <add> if manual_installer_casks.present? <add> ofail "Not upgrading #{manual_installer_casks.count} casks because they was install manually" <add> puts manual_installer_casks.map(&:to_s) <add> end <add> <ide> outdated_casks -= manual_installer_casks <ide> <ide> return false if outdated_casks.empty?
1
Ruby
Ruby
tweak the format
f22aeb14f613d4e9257e0e7e451d5004e59e4d06
<ide><path>Library/Homebrew/cmd/tap-readme.rb <ide> module Homebrew <ide> def tap_readme <ide> name = ARGV.first <del> <ide> raise "A name is required" if name.nil? <ide> <add> titleized_name = name.dup <add> titleized_name[0] = titleized_name[0].upcase <add> <ide> template = <<-EOS.undent <del> Homebrew-#{name} <del> =========#{'=' * name.size} <add> # Homebrew #{titleized_name} <ide> <del> How do I install these formulae? <del> -------------------------------- <del> Just `brew tap homebrew/#{name}` and then `brew install <formula>`. <add> ## How do I install these formulae? <add> `brew install homebrew/#{name}/<formula>` <ide> <del> If the formula conflicts with one from Homebrew/homebrew or another tap, you can `brew install homebrew/#{name}/<formula>`. <add> Or `brew tap homebrew/#{name}` and then `brew install <formula>`. <ide> <del> You can also install via URL: <add> Or install via URL (which will not receive updates): <ide> <ide> ``` <ide> brew install https://raw.githubusercontent.com/Homebrew/homebrew-#{name}/master/<formula>.rb <ide> ``` <ide> <del> Docs <del> ---- <del> `brew help`, `man brew`, or the Homebrew [docs][]. <del> <del> [docs]:https://github.com/Homebrew/homebrew/blob/master/share/doc/homebrew/README.md#readme <add> ## Documentation <add> `brew help`, `man brew` or check [Homebrew's documentation](https://github.com/Homebrew/homebrew/tree/master/share/doc/homebrew#readme). <ide> EOS <ide> <ide> puts template if ARGV.verbose?
1
Java
Java
implement hashcode() for synthesized annotations
def7663ec465ee293d70efd14dbded1fa3332ee5
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/SynthesizedAnnotationInvocationHandler.java <ide> import java.lang.reflect.AnnotatedElement; <ide> import java.lang.reflect.InvocationHandler; <ide> import java.lang.reflect.Method; <add>import java.util.Arrays; <ide> import java.util.Iterator; <ide> import java.util.Map; <ide> <ide> public Object invoke(Object proxy, Method method, Object[] args) throws Throwabl <ide> if (isEqualsMethod(method)) { <ide> return equals(proxy, args[0]); <ide> } <add> if (isHashCodeMethod(method)) { <add> return hashCode(proxy); <add> } <ide> if (isToStringMethod(method)) { <ide> return toString(proxy); <ide> } <ide> else if (value instanceof Annotation[]) { <ide> return value; <ide> } <ide> <add> /** <add> * See {@link Annotation#equals(Object)} for a definition of the required algorithm. <add> * <add> * @param proxy the synthesized annotation <add> * @param other the other object to compare against <add> */ <ide> private boolean equals(Object proxy, Object other) { <ide> if (this == other) { <ide> return true; <ide> private boolean equals(Object proxy, Object other) { <ide> return true; <ide> } <ide> <add> /** <add> * See {@link Annotation#hashCode()} for a definition of the required algorithm. <add> * <add> * @param proxy the synthesized annotation <add> */ <add> private int hashCode(Object proxy) { <add> int result = 0; <add> <add> for (Method attributeMethod : getAttributeMethods(this.annotationType)) { <add> Object value = invokeMethod(attributeMethod, proxy); <add> int hashCode; <add> if (value.getClass().isArray()) { <add> hashCode = hashCodeForArray(value); <add> } <add> else { <add> hashCode = value.hashCode(); <add> } <add> result += (127 * attributeMethod.getName().hashCode()) ^ hashCode; <add> } <add> <add> return result; <add> } <add> <add> /** <add> * WARNING: we can NOT use any of the {@code nullSafeHashCode()} methods <add> * in Spring's {@link ObjectUtils} because those hash code generation <add> * algorithms do not comply with the requirements specified in <add> * {@link Annotation#hashCode()}. <add> * <add> * @param array the array to compute the hash code for <add> */ <add> private int hashCodeForArray(Object array) { <add> if (array instanceof boolean[]) { <add> return Arrays.hashCode((boolean[]) array); <add> } <add> if (array instanceof byte[]) { <add> return Arrays.hashCode((byte[]) array); <add> } <add> if (array instanceof char[]) { <add> return Arrays.hashCode((char[]) array); <add> } <add> if (array instanceof double[]) { <add> return Arrays.hashCode((double[]) array); <add> } <add> if (array instanceof float[]) { <add> return Arrays.hashCode((float[]) array); <add> } <add> if (array instanceof int[]) { <add> return Arrays.hashCode((int[]) array); <add> } <add> if (array instanceof long[]) { <add> return Arrays.hashCode((long[]) array); <add> } <add> if (array instanceof short[]) { <add> return Arrays.hashCode((short[]) array); <add> } <add> <add> // else <add> return Arrays.hashCode((Object[]) array); <add> } <add> <add> /** <add> * See {@link Annotation#toString()} for guidelines on the recommended format. <add> * <add> * @param proxy the synthesized annotation <add> */ <ide> private String toString(Object proxy) { <ide> StringBuilder sb = new StringBuilder("@").append(annotationType.getName()).append("("); <ide> <ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java <ide> public void equalsForSynthesizedAnnotations() throws Exception { <ide> assertThat(webMappingWithAliases, is(not(synthesizedWebMapping1))); <ide> } <ide> <add> @Test <add> public void hashCodeForSynthesizedAnnotations() throws Exception { <add> Method methodWithPath = WebController.class.getMethod("handleMappedWithPathAttribute"); <add> WebMapping webMappingWithAliases = methodWithPath.getAnnotation(WebMapping.class); <add> assertNotNull(webMappingWithAliases); <add> <add> Method methodWithPathAndValue = WebController.class.getMethod("handleMappedWithSamePathAndValueAttributes"); <add> WebMapping webMappingWithPathAndValue = methodWithPathAndValue.getAnnotation(WebMapping.class); <add> assertNotNull(webMappingWithPathAndValue); <add> <add> WebMapping synthesizedWebMapping1 = synthesizeAnnotation(webMappingWithAliases); <add> assertNotNull(synthesizedWebMapping1); <add> WebMapping synthesizedWebMapping2 = synthesizeAnnotation(webMappingWithAliases); <add> assertNotNull(synthesizedWebMapping2); <add> <add> // Equality amongst standard annotations <add> assertThat(webMappingWithAliases.hashCode(), is(webMappingWithAliases.hashCode())); <add> assertThat(webMappingWithPathAndValue.hashCode(), is(webMappingWithPathAndValue.hashCode())); <add> <add> // Inequality amongst standard annotations <add> assertThat(webMappingWithAliases.hashCode(), is(not(webMappingWithPathAndValue.hashCode()))); <add> assertThat(webMappingWithPathAndValue.hashCode(), is(not(webMappingWithAliases.hashCode()))); <add> <add> // Equality amongst synthesized annotations <add> assertThat(synthesizedWebMapping1.hashCode(), is(synthesizedWebMapping1.hashCode())); <add> assertThat(synthesizedWebMapping2.hashCode(), is(synthesizedWebMapping2.hashCode())); <add> assertThat(synthesizedWebMapping1.hashCode(), is(synthesizedWebMapping2.hashCode())); <add> assertThat(synthesizedWebMapping2.hashCode(), is(synthesizedWebMapping1.hashCode())); <add> <add> // Equality between standard and synthesized annotations <add> assertThat(synthesizedWebMapping1.hashCode(), is(webMappingWithPathAndValue.hashCode())); <add> assertThat(webMappingWithPathAndValue.hashCode(), is(synthesizedWebMapping1.hashCode())); <add> <add> // Inequality between standard and synthesized annotations <add> assertThat(synthesizedWebMapping1.hashCode(), is(not(webMappingWithAliases.hashCode()))); <add> assertThat(webMappingWithAliases.hashCode(), is(not(synthesizedWebMapping1.hashCode()))); <add> } <add> <ide> /** <ide> * Fully reflection-based test that verifies support for <ide> * {@linkplain AnnotationUtils#synthesizeAnnotation synthesizing annotations}
2
Ruby
Ruby
make fixture loading to bulk statements
d8d6bd5e63a9a4a6c06a4dde3c7137ee2be105fd
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb <ide> def reset_sequence!(table, column, sequence = nil) <ide> # We keep this method to provide fallback <ide> # for databases like sqlite that do not support bulk inserts. <ide> def insert_fixture(fixture, table_name) <del> fixture = fixture.stringify_keys <del> <del> columns = schema_cache.columns_hash(table_name) <del> binds = fixture.map do |name, value| <del> if column = columns[name] <del> type = lookup_cast_type_from_column(column) <del> Relation::QueryAttribute.new(name, value, type) <del> else <del> raise Fixture::FixtureError, %(table "#{table_name}" has no column named #{name.inspect}.) <del> end <del> end <del> <del> table = Arel::Table.new(table_name) <del> <del> values = binds.map do |bind| <del> value = with_yaml_fallback(bind.value_for_database) <del> [table[bind.name], value] <del> end <del> <del> manager = Arel::InsertManager.new <del> manager.into(table) <del> manager.insert(values) <del> execute manager.to_sql, "Fixture Insert" <add> execute(build_fixture_sql(Array.wrap(fixture), table_name), "Fixture Insert") <ide> end <ide> <ide> def insert_fixtures_set(fixture_set, tables_to_delete = []) <del> fixture_inserts = fixture_set.map do |table_name, fixtures| <del> next if fixtures.empty? <del> <del> build_fixture_sql(fixtures, table_name) <del> end.compact <del> <del> table_deletes = tables_to_delete.map { |table| +"DELETE FROM #{quote_table_name table}" } <add> fixture_inserts = build_fixture_statements(fixture_set) <add> table_deletes = tables_to_delete.map { |table| "DELETE FROM #{quote_table_name(table)}" } <ide> total_sql = Array(combine_multi_statements(table_deletes + fixture_inserts)) <ide> <ide> with_multi_statements do <ide> def execute_batch(sql, name = nil) <ide> execute(sql, name) <ide> end <ide> <add> DEFAULT_INSERT_VALUE = Arel.sql("DEFAULT").freeze <add> private_constant :DEFAULT_INSERT_VALUE <add> <ide> def default_insert_value(column) <del> Arel.sql("DEFAULT") <add> DEFAULT_INSERT_VALUE <ide> end <ide> <ide> def build_fixture_sql(fixtures, table_name) <ide> columns = schema_cache.columns_hash(table_name) <ide> <del> values = fixtures.map do |fixture| <add> values_list = fixtures.map do |fixture| <ide> fixture = fixture.stringify_keys <ide> <ide> unknown_columns = fixture.keys - columns.keys <ide> def build_fixture_sql(fixtures, table_name) <ide> table = Arel::Table.new(table_name) <ide> manager = Arel::InsertManager.new <ide> manager.into(table) <del> columns.each_key { |column| manager.columns << table[column] } <del> manager.values = manager.create_values_list(values) <ide> <add> if values_list.size == 1 <add> values = values_list.shift <add> new_values = [] <add> columns.each_key.with_index { |column, i| <add> unless values[i].equal?(DEFAULT_INSERT_VALUE) <add> new_values << values[i] <add> manager.columns << table[column] <add> end <add> } <add> values_list << new_values <add> else <add> columns.each_key { |column| manager.columns << table[column] } <add> end <add> <add> manager.values = manager.create_values_list(values_list) <ide> manager.to_sql <ide> end <ide> <add> def build_fixture_statements(fixture_set) <add> fixture_set.map do |table_name, fixtures| <add> next if fixtures.empty? <add> build_fixture_sql(fixtures, table_name) <add> end.compact <add> end <add> <ide> def build_truncate_statements(*table_names) <ide> truncate_tables = table_names.map do |table_name| <ide> "TRUNCATE TABLE #{quote_table_name(table_name)}" <ide><path>activerecord/lib/active_record/connection_adapters/mysql/database_statements.rb <ide> def execute_batch(sql, name = nil) <ide> end <ide> <ide> def default_insert_value(column) <del> Arel.sql("DEFAULT") unless column.auto_increment? <add> super unless column.auto_increment? <ide> end <ide> <ide> def last_inserted_id(result) <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3/database_statements.rb <ide> def execute_batch(sql, name = nil) <ide> end <ide> end <ide> <add> def build_fixture_statements(fixture_set) <add> fixture_set.flat_map do |table_name, fixtures| <add> next if fixtures.empty? <add> fixtures.map { |fixture| build_fixture_sql([fixture], table_name) } <add> end.compact <add> end <add> <ide> def build_truncate_statements(*table_names) <ide> truncate_tables = table_names.map do |table_name| <ide> "DELETE FROM #{quote_table_name(table_name)}" <ide><path>activerecord/lib/active_record/connection_adapters/sqlite3_adapter.rb <ide> def foreign_keys(table_name) <ide> end <ide> end <ide> <del> def insert_fixtures_set(fixture_set, tables_to_delete = []) <del> disable_referential_integrity do <del> transaction(requires_new: true) do <del> tables_to_delete.each { |table| delete "DELETE FROM #{quote_table_name(table)}", "Fixture Delete" } <del> <del> fixture_set.each do |table_name, rows| <del> rows.each { |row| insert_fixture(row, table_name) } <del> end <del> end <del> end <del> end <del> <ide> def build_insert_sql(insert) # :nodoc: <ide> sql = +"INSERT #{insert.into} #{insert.values_list}" <ide> <ide><path>activerecord/test/cases/fixtures_test.rb <ide> def test_insert_fixtures_set_raises_an_error_when_max_allowed_packet_is_smaller_ <ide> conn = ActiveRecord::Base.connection <ide> mysql_margin = 2 <ide> packet_size = 1024 <del> bytes_needed_to_have_a_1024_bytes_fixture = 860 <add> bytes_needed_to_have_a_1024_bytes_fixture = 906 <ide> fixtures = { <ide> "traffic_lights" => [ <ide> { "location" => "US", "state" => ["NY"], "long_state" => ["a" * bytes_needed_to_have_a_1024_bytes_fixture] }, <ide> def test_yaml_file_with_invalid_column <ide> ActiveRecord::FixtureSet.create_fixtures(FIXTURES_ROOT + "/naked/yml", "parrots") <ide> end <ide> <del> if current_adapter?(:SQLite3Adapter) <del> assert_equal(%(table "parrots" has no column named "arrr".), e.message) <del> else <del> assert_equal(%(table "parrots" has no columns named "arrr", "foobar".), e.message) <del> end <add> assert_equal(%(table "parrots" has no columns named "arrr", "foobar".), e.message) <ide> end <ide> <ide> def test_yaml_file_with_symbol_columns
5
Javascript
Javascript
fix broken layout because of code section
f1db7d735b475a7954023cc63f2b3f0ef685ea7e
<ide><path>src/ng/directive/ngModelOptions.js <ide> defaultModelOptions = new ModelOptions({ <ide> * - `debounce`: integer value which contains the debounce model update value in milliseconds. A <ide> * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a <ide> * custom value for each event. For example: <del> * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"` <add> * ``` <add> * ng-model-options="{ <add> * updateOn: 'default blur', <add> * debounce: { 'default': 500, 'blur': 0 } <add> * }" <add> * ``` <ide> * - `allowInvalid`: boolean value which indicates that the model can be set with values that did <ide> * not validate correctly instead of the default behavior of setting the model to undefined. <ide> * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
1
Python
Python
add the compress method/function
90f8ba7e2f4383537af035b614ba922f6195ce9c
<ide><path>numpy/ma/core.py <ide> 'default_fill_value', 'diagonal', 'divide', 'dump', 'dumps', <ide> 'empty', 'empty_like', 'equal', 'exp', <ide> 'fabs', 'fmod', 'filled', 'floor', 'floor_divide','fix_invalid', <del> 'getmask', 'getmaskarray', 'greater', 'greater_equal', 'hypot', <add> 'getdata','getmask', 'getmaskarray', 'greater', 'greater_equal', <add> 'hypot', <ide> 'ids', 'inner', 'innerproduct', <ide> 'isMA', 'isMaskedArray', 'is_mask', 'is_masked', 'isarray', <ide> 'left_shift', 'less', 'less_equal', 'load', 'loads', 'log', 'log10', <ide> def nmask (x): <ide> m = make_mask(mask_or(m, getmask(indices)), copy=0, shrink=True) <ide> return masked_array(d, mask=m) <ide> <del>def compress(a, condition): <add>def compress(a, condition, axis=None, out=None): <ide> """Return a where condition is True. <add> If condition is a MaskedArray, missing values are considered as False. <add> <add> Returns <add> ------- <add> A MaskedArray object. <add> <add> Notes <add> ----- <add> Please note the difference with compressed() ! <add> The output of compress has a mask, the output of compressed does not. <ide> <ide> """ <del> return a[condition] <add> # Get the basic components <add> (_data, _mask) = (getdata(a), getmask(a)) <add> # Get the type of output <add> if isinstance(a, MaskedArray): <add> _view = type(a) <add> else: <add> _view = MaskedArray <add> # Make sure the condition has no missing values <add> condition = filled(condition, False) <add> # <add> _new = ndarray.compress(_data, condition, axis=axis, out=out).view(_view) <add> _new._update_from(a) <add> if _mask is not nomask: <add> _new._mask = _mask.compress(condition, axis=axis) <add> return _new <ide> <ide> def round_(a, decimals=0, out=None): <ide> """Return a copy of a, rounded to 'decimals' places. <ide><path>numpy/ma/tests/test_core.py <ide> def test_putmask(self): <ide> assert_equal(mxx, [1,2,30,4,5,60]) <ide> <ide> def test_compress(self): <del> a = array([1,2,3],mask=[True,False,False]) <del> b = compress(a,a<3) <del> assert_equal(b,[1,2]) <del> assert_equal(b.mask,[True,False]) <add> "test compress" <add> a = masked_array([10, 20, 30, 40], fill_value=9999) <add> condition = (a > 15) & (a < 35) <add> assert_equal(a.compress(condition),[20,30]) <add> # <add> a[1] = masked <add> b = a.compress(condition) <add> assert_equal(b._data,[20,30]) <add> assert_equal(b._mask,[1,0]) <add> assert_equal(b.fill_value,9999) <add> # <add> a = masked_array([[10,20,30],[40,50,60]], mask=[[0,0,1],[1,0,0]]) <add> b = a.compress(a.ravel() >= 22) <add> assert_equal(b._data, [50, 60]) <add> assert_equal(b._mask, [0,0]) <add> # <add> x = numpy.array([3,1,2]) <add> b = a.compress(x >= 2, axis=1) <add> assert_equal(b._data, [[10,30],[40,60]]) <add> assert_equal(b._mask, [[0,1],[1,0]]) <add> <ide> <ide> <ide> #..............................................................................
2
Javascript
Javascript
use assert.strictequal() cluster test
4a63fa3bf964f7f32ccd8d55131b6b29ff3f4c40
<ide><path>test/parallel/test-cluster-shared-handle-bind-privileged-port.js <ide> if (cluster.isMaster) { <ide> // Master opens and binds the socket and shares it with the worker. <ide> cluster.schedulingPolicy = cluster.SCHED_NONE; <ide> cluster.fork().on('exit', common.mustCall(function(exitCode) { <del> assert.equal(exitCode, 0); <add> assert.strictEqual(exitCode, 0); <ide> })); <ide> } else { <ide> var s = net.createServer(common.fail); <ide> s.listen(42, common.fail.bind(null, 'listen should have failed')); <ide> s.on('error', common.mustCall(function(err) { <del> assert.equal(err.code, 'EACCES'); <add> assert.strictEqual(err.code, 'EACCES'); <ide> process.disconnect(); <ide> })); <ide> }
1
Python
Python
fix typo in retry docstring
6b6117faa2c733e400f68debd87d06dc73a3d47b
<ide><path>celery/app/task.py <ide> def retry(self, args=None, kwargs=None, exc=None, throw=True, <ide> If no exception was raised it will raise the ``exc`` <ide> argument provided. <ide> countdown (float): Time in seconds to delay the retry for. <del> eta (~datetime.dateime): Explicit time and date to run the <add> eta (~datetime.datetime): Explicit time and date to run the <ide> retry at. <ide> max_retries (int): If set, overrides the default retry limit for <ide> this execution. Changes to this parameter don't propagate to
1
Python
Python
add util function to enable gpu
ffda38356a1d51c1bced19c1c1bfdced3756c891
<ide><path>spacy/util.py <ide> import io <ide> import dill <ide> from collections import OrderedDict <add>from thinc.neural._classes.model import Model <ide> <ide> import msgpack <ide> import msgpack_numpy <ide> def minify_html(html): <ide> RETURNS (unicode): "Minified" HTML. <ide> """ <ide> return html.strip().replace(' ', '').replace('\n', '') <add> <add> <add>def use_gpu(gpu_id): <add> import cupy.cuda.device <add> from thinc.neural.ops import CupyOps <add> device = cupy.cuda.device.Device(gpu_id) <add> device.use() <add> Model.ops = CupyOps() <add> Model.Ops = CupyOps <add> return device <add>
1
Ruby
Ruby
remove dead code
b73a6f195af2a29c618f453f55db98329010f385
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def diff_formulae(start_revision, end_revision, path, filter) <ide> end.compact <ide> end <ide> <del> def brew_update <del> return unless current_branch == "master" <del> success = quiet_system "brew", "update" <del> success ||= quiet_system "brew", "update" <del> end <del> <ide> @category = __method__ <ide> @start_branch = current_branch <ide>
1
PHP
PHP
use utf8mb4 as default character set
9d01389ce3039f483dcc9ed405e02ba49042bfa3
<ide><path>config/database.php <ide> 'database' => env('DB_DATABASE', 'forge'), <ide> 'username' => env('DB_USERNAME', 'forge'), <ide> 'password' => env('DB_PASSWORD', ''), <del> 'charset' => 'utf8', <del> 'collation' => 'utf8_unicode_ci', <add> 'charset' => 'utf8mb4', <add> 'collation' => 'utf8mb4_unicode_ci', <ide> 'prefix' => '', <ide> 'strict' => true, <ide> 'engine' => null,
1
Ruby
Ruby
remove mocha usage
b17330cf391327f63fece617acdb57b35e341092
<ide><path>railties/test/commands/console_test.rb <ide> def test_no_options_does_not_set_debugger_flag <ide> end <ide> <ide> def test_start_with_debugger <del> rails_console = Rails::Console.new(app, parse_arguments(["--debugger"])) <del> rails_console.expects(:require_debugger).returns(nil) <add> stubbed_console = Class.new(Rails::Console) do <add> def require_debugger <add> end <add> end <ide> <add> rails_console = stubbed_console.new(app, parse_arguments(["--debugger"])) <ide> silence_stream(STDOUT) { rails_console.start } <ide> end <ide> end
1
Python
Python
fix print_run_help with new arg order
39953c7c60e97cdd9af5b90e4a26634528548a19
<ide><path>spacy/cli/project.py <ide> def print_run_help(project_dir: Path, subcommand: Optional[str] = None) -> None: <ide> commands = {cmd["name"]: cmd for cmd in config_commands} <ide> if subcommand: <ide> validate_subcommand(commands.keys(), subcommand) <del> print(f"Usage: {COMMAND} project run {project_dir} {subcommand}") <add> print(f"Usage: {COMMAND} project run {subcommand} {project_dir}") <ide> help_text = commands[subcommand].get("help") <ide> if help_text: <ide> msg.text(f"\n{help_text}\n") <ide> else: <ide> print(f"\nAvailable commands in {CONFIG_FILE}") <del> print(f"Usage: {COMMAND} project run {project_dir} [COMMAND]") <add> print(f"Usage: {COMMAND} project run [COMMAND] {project_dir}") <ide> msg.table([(cmd["name"], cmd.get("help", "")) for cmd in config_commands]) <ide> msg.text("Run all commands defined in the 'run' block of the project config:") <ide> print(f"{COMMAND} project run-all {project_dir}")
1
Javascript
Javascript
fix typing issue
101954490a945175118b159e0f43583301de8335
<ide><path>test/configCases/rebuild/finishModules/webpack.config.js <ide> var testPlugin = compiler => { <ide> NormalModule.getCompilationHooks(compilation).loader.tap( <ide> "TestPlugin", <ide> loaderContext => { <del> loaderContext.shouldReplace = shouldReplace; <add> /** @type {any} */ (loaderContext).shouldReplace = shouldReplace; <ide> } <ide> ); <ide> compilation.hooks.finishModules.tapAsync(
1
Ruby
Ruby
use full paths to strip, mktemp, cat and ls
d8c3b3a80a94bbc121539cd8d52eb252fb26c577
<ide><path>Library/Homebrew/brew.h.rb <ide> def macports_or_fink_installed? <ide> end <ide> <ide> def versions_of(keg_name) <del> `ls #{HOMEBREW_CELLAR}/#{keg_name}`.collect { |version| version.strip }.reverse <add> `/bin/ls #{HOMEBREW_CELLAR}/#{keg_name}`.collect { |version| version.strip }.reverse <ide> end <ide> <ide> <ide> def strip path, args='' <ide> else <ide> # strip unlinks the file and recreates it, thus breaking hard links! <ide> # is this expected behaviour? patch does it too… still, this fixes it <del> tmp=`mktemp -t #{path.basename}`.strip <del> `strip #{args} -o #{tmp} #{path}` <del> `cat #{tmp} > #{path}` <add> tmp = `/usr/bin/mktemp -t #{path.basename}`.chomp <add> `/usr/bin/strip #{args} -o #{tmp} #{path}` <add> `/bin/cat #{tmp} > #{path}` <ide> File.unlink tmp <ide> end <ide> end
1
Ruby
Ruby
fix output for absolute symlinks
fe204fdf4b5e7c10f88cf19e099b5bbedd67c600
<ide><path>Library/Homebrew/cmd/bottle.rb <ide> def print_filename(string, filename) <ide> Utils.popen_read("strings", "-t", "x", "-", file.to_s) do |io| <ide> until io.eof? <ide> str = io.readline.chomp <del> <ide> next if ignores.any? { |i| i =~ str } <del> <ide> next unless str.include? string <del> <ide> offset, match = str.split(" ", 2) <del> <ide> next if linked_libraries.include? match # Don't bother reporting a string if it was found by otool <del> result ||= true <add> <add> result = true <ide> <ide> if ARGV.verbose? <ide> print_filename string, file <ide> def print_filename(string, filename) <ide> end <ide> end <ide> <del> put_symlink_header = false <add> absolute_symlinks_start_with_string = [] <add> absolute_symlinks_rest = [] <ide> keg.find do |pn| <ide> if pn.symlink? && (link = pn.readlink).absolute? <del> if !put_symlink_header && link.to_s.start_with?(string) <del> opoo "Absolute symlink starting with #{string}:" <del> puts " #{pn} -> #{pn.resolved_path}" <del> put_symlink_header = true <add> if link.to_s.start_with?(string) <add> absolute_symlinks_start_with_string << pn <add> else <add> absolute_symlinks_rest << pn <ide> end <ide> <ide> result = true <ide> end <ide> end <ide> <add> if ARGV.verbose? <add> if absolute_symlinks_start_with_string.any? <add> opoo "Absolute symlink starting with #{string}:" <add> absolute_symlinks_start_with_string.each do |pn| <add> puts " #{pn} -> #{pn.resolved_path}" <add> end <add> end <add> <add> if absolute_symlinks_rest.any? <add> opoo "Absolute symlink:" <add> absolute_symlinks_rest.each do |pn| <add> puts " #{pn} -> #{pn.resolved_path}" <add> end <add> end <add> end <add> <ide> result <ide> end <ide>
1
Text
Text
update chinese translation of css flexbox
e873b388da138501858fa0d7d6e2eca631b5a4a7
<ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/add-flex-superpowers-to-the-tweet-embed.chinese.md <ide> id: 587d78ab367417b2b2512af1 <ide> title: Add Flex Superpowers to the Tweet Embed <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 添加Flex Superpowers到Tweet Embed <add>videoUrl: 'https://scrimba.com/p/pVaDAv/c9W7MhM' <add>forumTopicId: 301100 <add>localeTitle: 在推文中添加弹性盒子布局 <ide> --- <ide> <ide> ## Description <del><section id="description">右侧是推文嵌入,将用作实际示例。使用不同的布局,一些元素看起来会更好。最后的挑战展示了<code>display: flex</code> 。在这里,您将把它添加到嵌入的推文中的几个组件,以开始调整它们的位置。 </section> <add><section id='description'> <add> 我们以右边的嵌入推文为例。一些元素换一个布局方式或许更好看。上一个挑战演示了<code>display: flex</code>,现在你需要把它添加到推文内嵌的多个组件中,调整它们的位置。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>display: flex</code>添加到以下所有项目中 - 请注意,选择器已经设置在CSS: <code>header</code> ,标题的<code>.profile-name</code> ,标题的<code>.follow-btn</code> ,标题的<code>h3</code>和<code>h4</code> , <code>footer</code>和页脚的<code>.stats</code> 。 </section> <add><section id='instructions'> <add>为下列项目添加 CSS 属性<code>display: flex</code>。注意,CSS 选择器已写好: <add><code>header</code>、header 的<code>.profile-name</code>、header 的<code>.follow-btn</code>、header 的<code>h3</code>和<code>h4</code>、<code>footer</code>以及 footer 的<code>.stats</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: 您的<code>header</code>应该具有设置为flex的<code>display</code>属性。 <del> testString: 'assert($("header").css("display") == "flex", "Your <code>header</code> should have a <code>display</code> property set to flex.");' <del> - text: 您的<code>footer</code>应该具有设置为flex的<code>display</code>属性。 <del> testString: 'assert($("footer").css("display") == "flex", "Your <code>footer</code> should have a <code>display</code> property set to flex.");' <del> - text: 你的<code>h3</code>应该有一个<code>display</code>属性设置为flex。 <del> testString: 'assert($("h3").css("display") == "flex", "Your <code>h3</code> should have a <code>display</code> property set to flex.");' <del> - text: 你的<code>h4</code>应该有一个<code>display</code>属性设置为flex。 <del> testString: 'assert($("h4").css("display") == "flex", "Your <code>h4</code> should have a <code>display</code> property set to flex.");' <del> - text: 您的<code>.profile-name</code>应该将<code>display</code>属性设置为flex。 <del> testString: 'assert($(".profile-name").css("display") == "flex", "Your <code>.profile-name</code> should have a <code>display</code> property set to flex.");' <del> - text: 你的<code>.follow-btn</code>应该有一个<code>display</code>属性设置为flex。 <del> testString: 'assert($(".follow-btn").css("display") == "flex", "Your <code>.follow-btn</code> should have a <code>display</code> property set to flex.");' <del> - text: 您的<code>.stats</code>应该将<code>display</code>属性设置为flex。 <del> testString: 'assert($(".stats").css("display") == "flex", "Your <code>.stats</code> should have a <code>display</code> property set to flex.");' <add> - text: '<code>header</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('header').css('display') == 'flex', '<code>header</code>的<code>display</code>属性应为 flex。'); <add> - text: '<code>footer</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('footer').css('display') == 'flex', '<code>footer</code>的<code>display</code>属性应为 flex。'); <add> - text: '<code>h3</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('h3').css('display') == 'flex', '<code>h3</code>的<code>display</code>属性应为 flex。'); <add> - text: '<code>h4</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('h4').css('display') == 'flex', '<code>h4</code>的<code>display</code>属性应为 flex。'); <add> - text: '<code>.profile-name</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('.profile-name').css('display') == 'flex', '<code>.profile-name</code>的<code>display</code>属性应为 flex。'); <add> - text: '<code>.follow-btn</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('.follow-btn').css('display') == 'flex', '<code>.follow-btn</code>的<code>display</code>属性应为 flex。'); <add> - text: '<code>.stats</code>的<code>display</code>属性应为 flex。' <add> testString: assert($('.stats').css('display') == 'flex', '<code>.stats</code>的<code>display</code>属性应为 flex。'); <ide> <ide> ``` <ide> <ide> tests: <ide> font-family: Arial, sans-serif; <ide> } <ide> header { <del> <add> <ide> } <ide> header .profile-thumbnail { <ide> width: 50px; <ide> height: 50px; <ide> border-radius: 4px; <ide> } <ide> header .profile-name { <del> <add> <ide> margin-left: 10px; <ide> } <ide> header .follow-btn { <del> <add> <ide> margin: 0 0 0 auto; <ide> } <ide> header .follow-btn button { <ide> tests: <ide> padding: 5px; <ide> } <ide> header h3, header h4 { <del> <add> <ide> margin: 0; <ide> } <ide> #inner p { <ide> tests: <ide> opacity: 0.1; <ide> } <ide> footer { <del> <add> <ide> } <ide> footer .stats { <del> <add> <ide> font-size: 15px; <ide> } <ide> footer .stats strong { <ide> tests: <ide> <button class="like-btn">Like</button> <ide> </div> <ide> </footer> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/align-elements-using-the-align-items-property.chinese.md <ide> id: 587d78ad367417b2b2512af8 <ide> title: Align Elements Using the align-items Property <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用align-items属性对齐元素 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/c8aggtk' <add>forumTopicId: 301101 <add>localeTitle: 使用 align-items 属性对齐元素 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>align-items</code>属性类似于<code>justify-content</code> 。回想一下, <code>justify-content</code>属性沿主轴对齐flex项目。对于行,主轴是水平线,对于列,它是垂直线。 Flex容器还具有与<strong>主轴</strong>相反的横轴。对于行,横轴是垂直的,对于列,横轴是水平的。 CSS提供<code>align-items</code>属性以沿着交叉轴对齐flex项。对于一行,它告诉CSS如何在容器内向上或向下推动整行中的项目。对于列,如何在容器内向左或向右推送所有项目。 <code>align-items</code>可用的不同值包括: <ul><li> <code>flex-start</code> :将项目对齐到Flex容器的开头。对于行,这会将项目对齐到容器的顶部。对于列,这会将项目对齐到容器的左侧。 </li><li> <code>flex-end</code> :将项目对齐到Flex容器的末尾。对于行,这会将项目对齐到容器的底部。对于列,这会将项目对齐到容器的右侧。 </li><li> <code>center</code> :将项目对齐到中心。对于行,这会垂直对齐项目(项目上方和下方的空格相等)。对于列,它会水平对齐它们(项目左侧和右侧的空格相等)。 </li><li> <code>stretch</code> :拉伸项目以填充弹性容器。例如,行项目被拉伸以从上到下填充Flex容器。 </li><li> <code>baseline</code> :将项目与其基线对齐。基线是一个文本概念,将其视为字母所在的行。 </li></ul></section> <add><section id='description'> <add><code>align-items</code>属性与<code>justify-content</code>类似。回忆一下,<code>justify-content</code>属性使 flex 子元素沿主轴排列。行的主轴是水平线,列的主轴是垂直线。 <add>Flex 容器中,与主轴垂直的叫做 <strong>cross axis(交叉轴)</strong>。行的交叉轴是垂直的,列的交叉轴是水平的。 <add>使用 CSS 中的<code>align-items</code>属性定义 flex 子元素沿交叉轴的对齐方式,对行来说,将行中的项目在容器中往上或往下移动;对列来说,将列中的项目在容器中往左或往右移动。 <add><code>align-items</code>的可选值包括: <add><ul><li><code>flex-start</code>:从 flex 容器的起始位置开始对齐项目。对行来说,把项目移至容器顶部;对列来说,是把项目移至容器左边。</li><li><code>flex-end</code>:从 flex 容器的终止位置开始对齐项目。对行来说,把项目移至容器底部;对列来说,把项目移至容器右边。</li><li><code>center</code>:把项目居中放置。对行来说,垂直居中(项目距离顶部和底部的距离相等);对列来说,水平居中(项目距离左边和右边的距离相等)。</li><li><code>stretch</code>:拉伸项目,填满 flex 容器。例如,排成行的项目从容器顶部拉伸到底部。如未设置<code>align-items</code>的值,那么默认值是<code>stretch</code>。</li><li><code>baseline</code>:沿基线对齐。基线是文本相关的概念,可以认为它是字母排列的下端基准线。</li></ul> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">一个示例有助于显示此属性的运行情况。将CSS属性<code>align-items</code>添加到<code>#box-container</code>元素,并为其指定center值。 <strong>奖金</strong> <br>在代码编辑器中尝试使用<code>align-items</code>属性的其他选项来查看它们之间的差异。但请注意,中心值是唯一能够通过此挑战的值。 </section> <add><section id='instructions'> <add>这个例子可以帮助你理解这个属性,在<code>#box-container</code>添加 CSS 属性<code>align-items</code>并将值设为 center。 <add><strong>提示:</strong><br>在编辑器里试试<code>align-items</code>的其他可用值,看看它们之间的区别。但要通过挑战,你必须把值设为 center。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-container</code>元素的<code>align-items</code>属性应设置为center的值。' <del> testString: 'assert($("#box-container").css("align-items") == "center", "The <code>#box-container</code> element should have an <code>align-items</code> property set to a value of center.");' <add> - text: '<code>#box-container</code>元素应有<code>align-items</code>属性,其值应为 center。' <add> testString: assert($('#box-container').css('align-items') == 'center', '<code>#box-container</code>元素应有<code>align-items</code>属性,其值应为 center。'); <ide> <ide> ``` <ide> <ide> tests: <ide> background: gray; <ide> display: flex; <ide> height: 500px; <del> <add> <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <ide> tests: <ide> <div id="box-1"><p>Hello</p></div> <ide> <div id="box-2"><p>Goodbye</p></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/align-elements-using-the-justify-content-property.chinese.md <ide> id: 587d78ac367417b2b2512af6 <ide> title: Align Elements Using the justify-content Property <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用justify-content属性对齐元素 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/c43gnHm' <add>forumTopicId: 301102 <add>localeTitle: 使用 justify-content 属性对齐元素 <ide> --- <ide> <ide> ## Description <del><section id="description">有时,flex容器中的flex项不会填充容器中的所有空间。通常希望告诉CSS如何以特定方式对齐和展开弹性项目。幸运的是, <code>justify-content</code>属性有几个选项可以做到这一点。但首先,在审查这些选项之前,需要了解一些重要的术语。 <a href="https://www.w3.org/TR/css-flexbox-1/images/flex-direction-terms.svg" target="_blank">这是一个有用的图像,显​​示了一行来说明下面的概念。</a>回想一下,将flex容器设置为一行可以从左到右并排放置Flex项目。设置为列的弹性容器将弹性项目从上到下放置在垂直堆栈中。对于每个,柔性项目的排列方向称为<strong>主轴</strong> 。对于一行,这是一条切割每个项目的水平线。对于列,主轴是穿过项目的垂直线。如何沿着作为主轴的直线对弹性项目进行间隔有几种选择。其中最常用的是<code>justify-content: center;</code> ,将所有弹性项目对齐到Flex容器内的中心。其他选择包括: <ul><li> <code>flex-start</code> :将项目对齐到Flex容器的开头。对于一行,这会将项目推送到容器的左侧。对于列,这会将项目推送到容器的顶部。 </li><li> <code>flex-end</code> :将项目对齐到Flex容器的末尾。对于一行,这会将项目推送到容器的右侧。对于列,这会将项目推送到容器的底部。 </li><li> <code>space-between</code> :将项目与主轴的中心对齐,在项目之间放置额外的空间。第一个和最后一个项目被推送到Flex容器的最边缘。例如,在第一项中,第一项是在容器的左侧,最后一项是在容器的右侧,然后它们之间的其他项是均匀间隔的。 </li><li> <code>space-around</code> :类似于<code>space-between</code>但是第一个和最后一个项目没有锁定到容器的边缘,空间分布在所有项目周围</li></ul></section> <add><section id='description'> <add>flex 子元素有时不能充满整个 flex 容器,所以我们经常需要告诉 CSS 以什么方式排列 flex 子元素,以及调整它们的间距。幸运的是,我们可以通过<code>justify-content</code>属性的不同的值来实现。在介绍<code>justify-content</code>的可选值之前,我们要先理解一些重要术语。 <add><a href="https://www.w3.org/TR/css-flexbox-1/images/flex-direction-terms.svg" target="_blank">这张图片的元素横着排列,很好地描述了下面的概念。</a> <add>回忆一下,把 flex 容器设为一个行,它的子元素会从左到右逐个排列,把 flex 容器设为一个列,它的子元素会从上到下逐个排列。子元素排列的方向被称为 <strong>main axis(主轴)</strong>。对于行,主轴水平贯穿每一个项目;对于列,主轴垂直贯穿每一个项目。 <add>关于 flex 子元素在主轴的排列方式,可以选择以下值:其中一个很常用的是<code>justify-content: center;</code>,使 flex 子元素在 flex 容器中居中排列。其他可选值还有: <add> <add><ul><li><code>flex-start</code>:从 flex 容器的起始位置开始排列项目。对行来说是把项目移至左边,对于列是把项目移至顶部。如未设置<code>justify-content</code>的值,那么默认值是<code>flex-start</code>。</li><li><code>flex-end</code>:从 flex 容器的终止位置开始排列项目。对行来说是把项目移至右边,对于列是把项目移至底部。</li><li><code>space-between</code>:项目间保留一定间距地沿主轴居中排列。第一个和最后一个项目被放置在容器边沿。例如,在行中第一个项目会紧贴着容器左边,最后一个项目会紧贴着容器右边,然后其他项目均匀排布。</li><li><code>space-around</code>:与<code>space-between</code>相似,但头尾两个项目不会紧贴容器边缘,所有项目之间的空间均匀排布。</li></ul> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">一个示例有助于显示此属性的运行情况。将CSS属性<code>justify-content</code>添加到<code>#box-container</code>元素,并为其赋值为center。 <strong>奖金</strong> <br>在代码编辑器中尝试使用<code>justify-content</code>属性的其他选项来查看它们之间的差异。但请注意,中心值是唯一能够通过此挑战的值。 </section> <add><section id='instructions'> <add>这个例子可以帮助你理解这个属性,在<code>#box-container</code>元素添加 CSS 属性<code>justify-content</code>,其值为 center。 <add><strong>提示:</strong><br>在编辑器里试试<code>justify-content</code>的其他可用值,看看它们之间的区别。但要通过挑战,你必须把值设为 center. <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-container</code>元素应该将<code>justify-content</code>属性设置为center的值。' <del> testString: 'assert($("#box-container").css("justify-content") == "center", "The <code>#box-container</code> element should have a <code>justify-content</code> property set to a value of center.");' <add> - text: '<code>#box-container</code>应有<code>justify-content</code>属性,其值应为 center。' <add> testString: assert($('#box-container').css('justify-content') == 'center', '<code>#box-container</code>应有<code>justify-content</code>属性,其值应为 center。'); <ide> <ide> ``` <ide> <ide> tests: <ide> background: gray; <ide> display: flex; <ide> height: 500px; <del> <add> <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <ide> tests: <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-a-column-in-the-tweet-embed.chinese.md <ide> id: 587d78ac367417b2b2512af5 <ide> title: Apply the flex-direction Property to Create a Column in the Tweet Embed <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 应用flex-direction属性在Tweet Embed中创建一个列 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cnzdVC9' <add>forumTopicId: 301103 <add>localeTitle: 使用 flex-direction 在嵌入推文中创建一列 <ide> --- <ide> <ide> ## Description <del><section id="description"> tweet嵌入<code>header</code>和<code>footer</code>先前使用了<code>flex-direction</code>属性和行值。同样, <code>.profile-name</code>元素中的项目可以很好地堆叠为列。 </section> <add><section id='description'> <add>在上一个挑战中,把嵌入推文的<code>header</code>和<code>footer</code>的<code>flex-direction</code>属性值设为 row(行)。相似地,把<code>.profile-name</code>选择器对应的元素竖着排列会好看一点。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex-direction</code>添加到标头的<code>.profile-name</code>元素,并将值设置为column。 </section> <add><section id='instructions'> <add>在 header 的<code>.profile-name</code>元素添加 CSS 属性<code>flex-direction</code>,将其值设为 column。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>.profile-name</code>元素应将<code>flex-direction</code>属性设置为column。 <del> testString: 'assert($(".profile-name").css("flex-direction") == "column", "The <code>.profile-name</code> element should have a <code>flex-direction</code> property set to column.");' <add> - text: '<code>.profile-name</code>应有<code>flex-direction</code>属性,其值应为 column。' <add> testString: assert($('.profile-name').css('flex-direction') == 'column', '<code>.profile-name</code>应有<code>flex-direction</code>属性,其值应为 column。'); <ide> <ide> ``` <ide> <ide> tests: <ide> } <ide> header .profile-name { <ide> display: flex; <del> <add> <ide> margin-left: 10px; <ide> } <ide> header .follow-btn { <ide> tests: <ide> <button class="like-btn">Like</button> <ide> </div> <ide> </footer> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/apply-the-flex-direction-property-to-create-rows-in-the-tweet-embed.chinese.md <ide> id: 587d78ab367417b2b2512af3 <ide> title: Apply the flex-direction Property to Create Rows in the Tweet Embed <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 应用flex-direction属性在Tweet Embed中创建行 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cJb8yuq' <add>forumTopicId: 301104 <add>localeTitle: 使用 flex-direction 在嵌入推文中创建多行 <ide> --- <ide> <ide> ## Description <del><section id="description"> tweet嵌入示例中的<code>header</code>和<code>footer</code>具有可以使用<code>flex-direction</code>属性排列为行的子项。这告诉CSS水平对齐孩子。 </section> <add><section id='description'> <add>嵌入推文示例中的<code>header</code>和<code>footer</code>有自己的子元素,使用<code>flex-direction</code>属性可以把这些子元素排成行。这个属性告诉 CSS 需要将这些子元素水平排列。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex-direction</code>添加到<code>header</code>和<code>footer</code> ,并将值设置为row。 </section> <add><section id='instructions'> <add>为<code>header</code>和<code>footer</code>添加 CSS 属性<code>flex-direction</code>并把值设为 row。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>header</code>应该将<code>flex-direction</code>属性设置为row。 <del> testString: 'assert(code.match(/header\s*?{[^}]*?flex-direction:\s*?row;/g), "The <code>header</code> should have a <code>flex-direction</code> property set to row.");' <del> - text: <code>footer</code>应将<code>flex-direction</code>属性设置为row。 <del> testString: 'assert(code.match(/footer\s*?{[^}]*?flex-direction:\s*?row;/g), "The <code>footer</code> should have a <code>flex-direction</code> property set to row.");' <add> - text: '<code>header</code>应有<code>flex-direction</code>属性,其值应为 row。' <add> testString: 'assert(code.match(/header\s*?{\s*?.*?\s*?.*?\s*?flex-direction:\s*?row;/g), ''<code>header</code>应有<code>flex-direction</code>属性,其值应为 row。'');' <add> - text: '<code>footer</code>应有<code>flex-direction</code>属性,其值应为 row。' <add> testString: 'assert(code.match(/footer\s*?{\s*?.*?\s*?.*?\s*?flex-direction:\s*?row;/g), ''<code>footer</code>应有<code>flex-direction</code>属性,其值应为 row。'');' <ide> <ide> ``` <ide> <ide> tests: <ide> } <ide> header { <ide> display: flex; <del> <add> <ide> } <ide> header .profile-thumbnail { <ide> width: 50px; <ide> tests: <ide> } <ide> footer { <ide> display: flex; <del> <add> <ide> } <ide> footer .stats { <ide> display: flex; <ide> tests: <ide> <button class="like-btn">Like</button> <ide> </div> <ide> </footer> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-display-flex-to-position-two-boxes.chinese.md <ide> id: 587d78ab367417b2b2512af0 <ide> title: 'Use display: flex to Position Two Boxes' <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用display:flex定位两个Box <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cgz3QS7' <add>forumTopicId: 301105 <add>localeTitle: '使用 display: flex 定位两个盒子' <ide> --- <ide> <ide> ## Description <del><section id="description">本节使用交替挑战样式来展示如何使用CSS以灵活的方式定位元素。首先,挑战将解释理论,然后使用简单推文组件的实际挑战将应用flexbox概念。放置CSS属性<code>display: flex;</code>在元素上允许您使用其他flex属性来构建响应式页面。 </section> <add><section id='description'> <add>这节会使用一种不同的挑战方式来学习一下如何使用 CSS 更灵活地布局元素。首先通过一个挑战来理解原理,然后通过操作一个简单的推文组件来应用“弹性盒子”(flexbox)。 <add>只要在一个元素的 CSS 中添加<code>display: flex;</code>,就可以使用其它 flex 属性来构建响应式页面了。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>display</code>添加到<code>#box-container</code>并将其值设置为flex。 </section> <add><section id='instructions'> <add>为<code>#box-container</code>添加<code>display</code>属性,设置其值为 flex。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-container</code>应将<code>display</code>属性设置为flex值。' <del> testString: 'assert($("#box-container").css("display") == "flex", "<code>#box-container</code> should have the <code>display</code> property set to a value of flex.");' <add> - text: '<code>#box-container</code>应有<code>display</code>属性,其值应为 flex。' <add> testString: assert($('#box-container').css('display') == 'flex', '<code>#box-container</code>应有<code>display</code>属性,其值应为 flex。'); <ide> <ide> ``` <ide> <ide> tests: <ide> <style> <ide> #box-container { <ide> height: 500px; <del> <add> <ide> } <del> <add> <ide> #box-1 { <ide> background-color: dodgerblue; <ide> width: 50%; <ide> height: 50%; <del> <ide> } <ide> <ide> #box-2 { <ide> background-color: orangered; <ide> width: 50%; <ide> height: 50%; <del> <ide> } <ide> </style> <ide> <div id="box-container"> <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-align-items-property-in-the-tweet-embed.chinese.md <ide> id: 587d78ad367417b2b2512af9 <ide> title: Use the align-items Property in the Tweet Embed <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用Tweet Embed中的align-items属性 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cd3PNfq' <add>forumTopicId: 301106 <add>localeTitle: 在推文中使用 align-items 属性 <ide> --- <ide> <ide> ## Description <del><section id="description">最后一个挑战引入了<code>align-items</code>属性并举了一个例子。此属性可应用于一些tweet嵌入元素,以对齐其中的flex项。 </section> <add><section id='description'> <add>上一个挑战介绍了<code>align-items</code>属性并给出了例子。可以对嵌入推文的一些元素使用这个属性,以调整其中 flex 子元素的位置。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>align-items</code>添加到标题的<code>.follow-btn</code>元素中。将值设置为居中。 </section> <add><section id='instructions'> <add>在 header 的<code>.follow-btn</code>添加 CSS 属性<code>align-items</code>,把值设为 center。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>.follow-btn</code>元素应将<code>align-items</code>属性设置为center的值。 <del> testString: 'assert($(".follow-btn").css("align-items") == "center", "The <code>.follow-btn</code> element should have the <code>align-items</code> property set to a value of center.");' <add> - text: '<code>.follow-btn</code>应有<code>align-items</code>属性,其值应为 center.' <add> testString: assert($('.follow-btn').css('align-items') == 'center', '<code>.follow-btn</code>应有<code>align-items</code>属性,其值应为 center.'); <ide> <ide> ``` <ide> <ide> tests: <ide> } <ide> header .follow-btn { <ide> display: flex; <del> <add> <ide> margin: 0 0 0 auto; <ide> } <ide> header .follow-btn button { <ide> tests: <ide> padding: 5px; <ide> } <ide> header h3, header h4 { <del> display: flex; <del> <add> display: flex; <ide> margin: 0; <ide> } <ide> #inner p { <ide> tests: <ide> <button class="like-btn">Like</button> <ide> </div> <ide> </footer> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-align-self-property.chinese.md <ide> id: 587d78af367417b2b2512b00 <ide> title: Use the align-self Property <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用align-self属性 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cMbvzfv' <add>forumTopicId: 301107 <add>localeTitle: 使用 align-self 属性 <ide> --- <ide> <ide> ## Description <del><section id="description"> flex项的最终属性是<code>align-self</code> 。此属性允许您单独调整每个项目的对齐方式,而不是一次性设置它们。这很有用,因为使用CSS属性<code>float</code> , <code>clear</code>和<code>vertical-align</code>其他常用调整技术对flex项不起作用。 <code>align-self</code>接受与<code>align-items</code>相同的值,并将覆盖<code>align-items</code>属性设置的任何值。 </section> <add><section id='description'> <add>flex 子项目的最后一个属性是<code>align-self</code>。这个属性允许你调整每个项目自己的对齐方式,而不是一次性设置全部项目。因为<code>float</code>、<code>clear</code>和<code>vertical-align</code>等调整对齐方式的属性都不能应用于 flex 子元素,所以这个属性显得十分有用。 <add><code>align-self</code>可设置的值与<code>align-items</code>的一样,并且它会覆盖<code>align-items</code>的值。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>align-self</code>添加到<code>#box-1</code>和<code>#box-2</code> 。给<code>#box-1</code>一个中心值,给<code>#box-2</code>一个flex-end值。 </section> <add><section id='instructions'> <add>在<code>#box-1</code>和<code>#box-2</code>添加 CSS 属性<code>align-self</code>。<code>#box-1</code>设为 center,<code>#box-2</code>设为 flex-end。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-1</code>元素应将<code>align-self</code>属性设置为center的值。' <del> testString: 'assert($("#box-1").css("align-self") == "center", "The <code>#box-1</code> element should have the <code>align-self</code> property set to a value of center.");' <del> - text: '<code>#box-2</code>元素应该将<code>align-self</code>属性设置为flex-end的值。' <del> testString: 'assert($("#box-2").css("align-self") == "flex-end", "The <code>#box-2</code> element should have the <code>align-self</code> property set to a value of flex-end.");' <add> - text: '<code>#box-1</code>元素应有<code>align-self</code>属性,其值应为 center。' <add> testString: assert($('#box-1').css('align-self') == 'center', '<code>#box-1</code>元素应有<code>align-self</code>属性,其值应为 center。'); <add> - text: '<code>#box-2</code>元素应有<code>align-self</code>属性,其值应为 flex-end。' <add> testString: assert($('#box-2').css('align-self') == 'flex-end', '<code>#box-2</code>元素应有<code>align-self</code>属性,其值应为 flex-end。'); <ide> <ide> ``` <ide> <ide> tests: <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <del> <add> <ide> height: 200px; <ide> width: 200px; <ide> } <ide> <ide> #box-2 { <ide> background-color: orangered; <del> <add> <ide> height: 200px; <ide> width: 200px; <ide> } <ide> tests: <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-basis-property-to-set-the-initial-size-of-an-item.chinese.md <ide> id: 587d78ae367417b2b2512afd <ide> title: Use the flex-basis Property to Set the Initial Size of an Item <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex-basis属性设置项的初始大小 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/c3d9nCa' <add>forumTopicId: 301108 <add>localeTitle: 使用 flex-basis 属性设置项目的初始大小 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>flex-basis</code>属性指定CSS在使用<code>flex-shrink</code>或<code>flex-grow</code>进行调整之前的项的初始大小。 <code>flex-basis</code>属性使用的单位与其他大小属性( <code>px</code> , <code>em</code> , <code>%</code>等)相同。该值根据内容<code>auto</code>项目大小。 </section> <add><section id='description'> <add><code>flex-basis</code>属性定义了在使用 CSS 的<code>flex-shrink</code>或<code>flex-grow</code>属性对项目进行调整前,项目的初始大小。 <add><code>flex-basis</code>属性的单位与其他表示尺寸的属性的单位一致(<code>px</code>、<code>em</code>、<code>%</code>等)。如果值为<code>auto</code>,则项目的尺寸随内容调整。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">使用<code>flex-basis</code>设置框的初始大小。将CSS属性<code>flex-basis</code>添加到<code>#box-1</code>和<code>#box-2</code> 。给<code>#box-1</code>一个值为<code>10em</code> , <code>#box-2</code>给一个值为<code>20em</code> 。 </section> <add><section id='instructions'> <add>使用<code>flex-basis</code>为盒子设置初始值。给<code>#box-1</code>和<code>#box-2</code>添加 CSS 属性<code>flex-basis</code>。设置<code>#box-1</code>的尺寸初始值为<code>10em</code>,<code>#box-2</code>的尺寸初始值为<code>20em</code>。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-1</code>元素应该具有<code>flex-basis</code>属性。' <del> testString: 'assert($("#box-1").css("flex-basis") != "auto", "The <code>#box-1</code> element should have a <code>flex-basis</code> property.");' <del> - text: '<code>#box-1</code>元素的<code>flex-basis</code>值应为<code>10em</code> 。' <del> testString: 'assert(code.match(/#box-1\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?10em;/g), "The <code>#box-1</code> element should have a <code>flex-basis</code> value of <code>10em</code>.");' <del> - text: '<code>#box-2</code>元素应该具有<code>flex-basis</code>属性。' <del> testString: 'assert($("#box-2").css("flex-basis") != "auto", "The <code>#box-2</code> element should have the <code>flex-basis</code> property.");' <del> - text: '<code>#box-2</code>元素的<code>flex-basis</code>值应为<code>20em</code> 。' <del> testString: 'assert(code.match(/#box-2\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?20em;/g), "The <code>#box-2</code> element should have a <code>flex-basis</code> value of <code>20em</code>.");' <add> - text: '<code>#box-1</code>元素应有<code>flex-basis</code>属性。' <add> testString: assert($('#box-1').css('flex-basis') != 'auto', '<code>#box-1</code>元素应有<code>flex-basis</code>属性。'); <add> - text: '<code>#box-1</code>的<code>flex-basis</code>应为<code>10em</code>。' <add> testString: 'assert(code.match(/#box-1\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?10em;/g), ''<code>#box-1</code>的<code>flex-basis</code>应为<code>10em</code>。'');' <add> - text: '<code>#box-2</code>元素应有<code>flex-basis</code>属性。' <add> testString: assert($('#box-2').css('flex-basis') != 'auto', '<code>#box-2</code>元素应有<code>flex-basis</code>属性。'); <add> - text: '<code>#box-2</code>的<code>flex-basis</code>应为<code>20em</code>。' <add> testString: 'assert(code.match(/#box-2\s*?{\s*?.*?\s*?.*?\s*?flex-basis:\s*?20em;/g), ''<code>#box-2</code>的<code>flex-basis</code>应为<code>20em</code>。'');' <ide> <ide> ``` <ide> <ide> tests: <ide> display: flex; <ide> height: 500px; <ide> } <del> <add> <ide> #box-1 { <ide> background-color: dodgerblue; <ide> height: 200px; <del> <add> <ide> } <del> <add> <ide> #box-2 { <ide> background-color: orangered; <ide> height: 200px; <del> <add> <ide> } <ide> </style> <del> <add> <ide> <div id="box-container"> <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-column.chinese.md <ide> id: 587d78ac367417b2b2512af4 <ide> title: Use the flex-direction Property to Make a Column <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex-direction属性创建列 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cZmWeA4' <add>forumTopicId: 301109 <add>localeTitle: 使用 flex-direction 属性创建一列 <ide> --- <ide> <ide> ## Description <del><section id="description">最后两个挑战使用了<code>flex-direction</code>属性设置为row。此属性还可以通过垂直堆叠Flex容器的子项来创建列。 </section> <add><section id='description'> <add>之前两个挑战使用<code>flex-direction</code>属性创建行(row)。这个属性还能创建一个列,让子元素垂直排列在 flex 容器中。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex-direction</code>添加到<code>#box-container</code>元素,并为其赋值column。 </section> <add><section id='instructions'> <add>给<code>#box-container</code>元素添加 CSS 属性<code>flex-direction</code>,赋值为 column。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-container</code>元素应该将<code>flex-direction</code>属性设置为column。' <del> testString: 'assert($("#box-container").css("flex-direction") == "column", "The <code>#box-container</code> element should have a <code>flex-direction</code> property set to column.");' <add> - text: '<code>#box-container</code>应有<code>flex-direction</code>属性,其值应为 column。' <add> testString: assert($('#box-container').css('flex-direction') == 'column', '<code>#box-container</code>应有<code>flex-direction</code>属性,其值应为 column。'); <ide> <ide> ``` <ide> <ide> tests: <ide> #box-container { <ide> display: flex; <ide> height: 500px; <del> <add> <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <ide> tests: <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-direction-property-to-make-a-row.chinese.md <ide> id: 587d78ab367417b2b2512af2 <ide> title: Use the flex-direction Property to Make a Row <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex-direction属性创建一行 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cBEkbfJ' <add>forumTopicId: 301110 <add>localeTitle: 使用 flex-direction 属性创建一行 <ide> --- <ide> <ide> ## Description <del><section id="description">添加<code>display: flex</code> to a element将其转换为flex容器。这使得可以将该元素的任何子节点对齐成行或列。您可以通过将<code>flex-direction</code>属性添加到父项并将其设置为行或列来完成此操作。创建行将水平对齐子项,创建列将垂直对齐子项。 <code>flex-direction</code>其他选项是row-reverse和column-reverse。 <strong>注意</strong> <br> <code>flex-direction</code>属性的默认值为row。 </section> <add><section id='description'> <add>给元素添加<code>display: flex</code>属性使其变成 flex 容器。只要给父元素添加<code>flex-direction</code>属性,并把属性值设置为 row 或 column,即可横排或竖排它的子元素。设为 row 可以让子元素水平排列,设为 column 可以让子元素垂直排列。 <add><code>flex-direction</code>的其他可选值还有 row-reverse 和 column-reverse。 <add><strong>注意</strong><br><code>flex-direction</code>的默认值为 row。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex-direction</code>添加到<code>#box-container</code>元素,并为其赋值row-reverse。 </section> <add><section id='instructions'> <add>为<code>#box-container</code>添加 CSS 属性<code>flex-direction</code>,其值设为 row-reverse。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-container</code>元素的<code>flex-direction</code>属性应设置为row-reverse。' <del> testString: 'assert($("#box-container").css("flex-direction") == "row-reverse", "The <code>#box-container</code> element should have a <code>flex-direction</code> property set to row-reverse.");' <add> - text: '<code>#box-container</code>应有<code>flex-direction</code>属性,其值应为 row-reverse。' <add> testString: assert($('#box-container').css('flex-direction') == 'row-reverse', '<code>#box-container</code>应有<code>flex-direction</code>属性,其值应为 row-reverse。'); <ide> <ide> ``` <ide> <ide> tests: <ide> #box-container { <ide> display: flex; <ide> height: 500px; <del> <add> <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <ide> tests: <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-grow-property-to-expand-items.chinese.md <ide> id: 587d78ae367417b2b2512afc <ide> title: Use the flex-grow Property to Expand Items <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex-grow属性扩展项目 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/c2p78cg' <add>forumTopicId: 1301111 <add>localeTitle: 使用 flex-grow 属性扩展项目 <ide> --- <ide> <ide> ## Description <del><section id="description">与<code>flex-shrink</code>相反的是<code>flex-grow</code>属性。回想一下,当容器缩小时, <code>flex-shrink</code>控制项目的大小。当父容器展开时, <code>flex-grow</code>属性控制项的大小。使用上一个挑战中的类似示例,如果一个项目的<code>flex-grow</code>值为1而另一个项目的<code>flex-grow</code>值为3,则值为3的项目将增长为另一个项目的三倍。 </section> <add><section id='description'> <add>与<code>flex-shrink</code>相对的是<code>flex-grow</code>。你应该还记得,<code>flex-shrink</code>会在容器太小时对元素作出调整。相应地,<code>flex-grow</code>会在容器太大时对元素作出调整。 <add>例子与上一个挑战相似,如果一个项目的<code>flex-grow</code>属性值为 1,另一个项目的<code>flex-grow</code>属性值为 3,那么后者会较前者扩大三倍。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex-grow</code>添加到<code>#box-1</code>和<code>#box-2</code> 。将<code>#box-1</code>的值设为1,将<code>#box-2</code>的值设为2。 </section> <add><section id='instructions'> <add>为<code>#box-1</code>和<code>#box-2</code>添加 CSS 属性<code>flex-grow</code>,<code>#box-1</code>的值设为 1,<code>#box-2</code>的值设为 2。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-1</code>元素应将<code>flex-grow</code>属性设置为值1。' <del> testString: 'assert($("#box-1").css("flex-grow") == "1", "The <code>#box-1</code> element should have the <code>flex-grow</code> property set to a value of 1.");' <del> - text: '<code>#box-2</code>元素应将<code>flex-grow</code>属性设置为值2。' <del> testString: 'assert($("#box-2").css("flex-grow") == "2", "The <code>#box-2</code> element should have the <code>flex-grow</code> property set to a value of 2.");' <add> - text: '<code>#box-1</code>元素应有<code>flex-grow</code>属性,其值应为 1。' <add> testString: assert($('#box-1').css('flex-grow') == '1', '<code>#box-1</code>元素应有<code>flex-grow</code>属性,其值应为 1。'); <add> - text: '<code>#box-2</code>元素应有<code>flex-grow</code>属性,其值应为 2。' <add> testString: assert($('#box-2').css('flex-grow') == '2', '<code>#box-2</code>元素应有<code>flex-grow</code>属性,其值应为 2。'); <ide> <ide> ``` <ide> <ide> tests: <ide> display: flex; <ide> height: 500px; <ide> } <del> <add> <ide> #box-1 { <ide> background-color: dodgerblue; <ide> height: 200px; <del> <add> <ide> } <del> <add> <ide> #box-2 { <ide> background-color: orangered; <ide> height: 200px; <del> <add> <ide> } <ide> </style> <ide> <ide> <div id="box-container"> <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-shorthand-property.chinese.md <ide> id: 587d78ae367417b2b2512afe <ide> title: Use the flex Shorthand Property <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex速记属性 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cbpW2tE' <add>forumTopicId: 301112 <add>localeTitle: 使用 flex 短方法属性 <ide> --- <ide> <ide> ## Description <del><section id="description">有一个快捷方式可以同时设置多个flex属性。通过使用<code>flex</code>属性,可以将<code>flex-grow</code> , <code>flex-shrink</code>和<code>flex-basis</code>属性设置在一起。例如, <code>flex: 1 0 10px;</code>将项目设置为<code>flex-grow: 1;</code> , <code>flex-shrink: 0;</code> ,和<code>flex-basis: 10px;</code> 。默认属性设置为<code>flex: 0 1 auto;</code> 。 </section> <add><section id='description'> <add>上面几个 flex 属性有一个简写方式。<code>flex-grow</code>、<code>flex-shrink</code>和<code>flex-basis</code>属性可以在<code>flex</code>中一同设置。 <add>例如,<code>flex: 1 0 10px;</code>会把项目属性设为<code>flex-grow: 1;</code>、<code>flex-shrink: 0;</code>以及<code>flex-basis: 10px;</code>。 <add>属性的默认设置是<code>flex: 0 1 auto;</code>。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex</code>添加到<code>#box-1</code>和<code>#box-2</code> 。给<code>#box-1</code>赋值,使<code>flex-grow</code>为2, <code>flex-shrink</code>为2, <code>flex-basis</code>为150px。给<code>#box-2</code>赋值,使<code>flex-grow</code>为1, <code>flex-shrink</code>为1,其<code>flex-basis</code>为150px。这些值将导致<code>#box-1</code>增长以在容器大于300px时以<code>#box-2</code>两倍速率填充额外空间,并在容器小于300px时以<code>#box-2</code>的速率缩小两倍。 300px是两个框的<code>flex-basis</code>值的组合大小。 </section> <add><section id='instructions'> <add>在<code>#box-1</code>和<code>#box-2</code>添加<code>flex</code>属性。为<code>#box-1</code>设置<code>flex-grow</code>属性值为 2,<code>flex-shrink</code>属性值为 2,<code>flex-basis</code>属性值为 150px。为<code>#box-2</code>设置<code>flex-grow</code>属性值为 1,<code>flex-shrink</code>属性值为 1,<code>flex-basis</code>属性值为 150px。 <add>通过上面的设置,在容器大于 300px 时,<code>#box-1</code>扩大的空间是<code>#box-2</code>扩大空间的两倍;在容器小于 300px 时,<code>#box-1</code>缩小的空间<code>#box-2</code>缩小空间的两倍。300px 是两个盒子的<code>flex-basis</code>的值之和。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-1</code>元素的<code>flex</code>属性应设置为2 2 150px。' <del> testString: 'assert($("#box-1").css("flex-grow") == "2" && $("#box-1").css("flex-shrink") == "2" && $("#box-1").css("flex-basis") == "150px", "The <code>#box-1</code> element should have the <code>flex</code> property set to a value of 2 2 150px.");' <del> - text: '<code>#box-2</code>元素的<code>flex</code>属性应设置为1 1 150px。' <del> testString: 'assert($("#box-2").css("flex-grow") == "1" && $("#box-2").css("flex-shrink") == "1" && $("#box-2").css("flex-basis") == "150px", "The <code>#box-2</code> element should have the <code>flex</code> property set to a value of 1 1 150px.");' <del> - text: '您的代码应该使用<code>#box-1</code>和<code>#box-2</code>的<code>flex</code>属性。' <del> testString: 'assert(code.match(/flex:\s*?\d\s+?\d\s+?150px;/g).length == 2, "Your code should use the <code>flex</code> property for <code>#box-1</code> and <code>#box-2</code>.");' <add> - text: '<code>#box-1</code>元素应有<code>flex</code>属性,其值应为 2 2 150px。' <add> testString: assert($('#box-1').css('flex-grow') == '2' && $('#box-1').css('flex-shrink') == '2' && $('#box-1').css('flex-basis') == '150px', '<code>#box-1</code>元素应有<code>flex</code>属性,其值应为 2 2 150px。'); <add> - text: '<code>#box-2</code>元素应有<code>flex</code>属性,其值应为 1 1 150px。' <add> testString: assert($('#box-2').css('flex-grow') == '1' && $('#box-2').css('flex-shrink') == '1' && $('#box-2').css('flex-basis') == '150px', '<code>#box-2</code>元素应有<code>flex</code>属性,其值应为 1 1 150px。'); <add> - text: '应对<code>#box-1</code>和<code>#box-2</code>使用<code>flex</code>属性。' <add> testString: 'assert(code.match(/flex:\s*?\d\s+?\d\s+?150px;/g).length == 2, ''应对<code>#box-1</code>和<code>#box-2</code>使用<code>flex</code>属性。'');' <ide> <ide> ``` <ide> <ide> tests: <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <del> <add> <ide> height: 200px; <ide> } <ide> <ide> #box-2 { <ide> background-color: orangered; <del> <add> <ide> height: 200px; <ide> } <ide> </style> <ide> tests: <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-shrink-property-to-shrink-items.chinese.md <ide> id: 587d78ad367417b2b2512afb <ide> title: Use the flex-shrink Property to Shrink Items <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex-shrink属性收缩项目 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cd3PBfr' <add>forumTopicId: 301113 <add>localeTitle: 使用 flex-shrink 属性收缩项目 <ide> --- <ide> <ide> ## Description <del><section id="description">到目前为止,挑战中的所有属性都适用于Flex容器(flex项的父级)。但是,flex项有几个有用的属性。第一个是<code>flex-shrink</code>属性。当它被使用时,如果柔性容器太小,它允许物品收缩。当父容器的宽度小于其中所有flex项的组合宽度时,项会收缩。 <code>flex-shrink</code>属性将数字作为值。数字越大,与容器中的其他项目相比,它将收缩得越多。例如,如果一个项目的<code>flex-shrink</code>值为1而另一个项目的<code>flex-shrink</code>值为3,则值为3的项目将缩小为另一个项目的三倍。 </section> <add><section id='description'> <add>目前为止,挑战里的提到的属性都应用于 flex 容器(flex 子元素的父元素)。除此之外,flex 子元素也有很多实用属性。 <add>首先介绍的是<code>flex-shrink</code>属性。使用之后,如果 flex 容器太小,该项目会自动缩小。当容器的宽度小于里面所有项目的宽度,项目就会自动压缩。 <add>项目的<code>flex-shrink</code>属性接受 number 类型的值。数值越大,该项目与其他项目相比会被压缩得更厉害。例如,如果一个项目的<code>flex-shrink</code>属性值为 1 ,另一个项目的<code>flex-shrink</code>属性值为 3,那么后者相比前者会受到 3 倍压缩。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>flex-shrink</code>添加到<code>#box-1</code>和<code>#box-2</code> 。将<code>#box-1</code>的值设为1,将<code>#box-2</code>的值设为2。 </section> <add><section id='instructions'> <add>为<code>#box-1</code>和<code>#box-2</code>添加 CSS 属性<code>flex-shrink</code>,<code>#box-1</code>的值设为 1,<code>#box-2</code>的值设为 2。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-1</code>元素应将<code>flex-shrink</code>属性设置为值1。' <del> testString: 'assert($("#box-1").css("flex-shrink") == "1", "The <code>#box-1</code> element should have the <code>flex-shrink</code> property set to a value of 1.");' <del> - text: '<code>#box-2</code>元素的<code>flex-shrink</code>属性应设置为值2。' <del> testString: 'assert($("#box-2").css("flex-shrink") == "2", "The <code>#box-2</code> element should have the <code>flex-shrink</code> property set to a value of 2.");' <add> - text: '<code>#box-1</code>元素应有<code>flex-shrink</code>属性,其值应为 1.' <add> testString: assert($('#box-1').css('flex-shrink') == '1', '<code>#box-1</code>元素应有<code>flex-shrink</code>属性,其值应为 1.'); <add> - text: '<code>#box-2</code>元素应有<code>flex-shrink</code>属性,其值应为 2.' <add> testString: assert($('#box-2').css('flex-shrink') == '2', '<code>#box-2</code>元素应有<code>flex-shrink</code>属性,其值应为 2.'); <ide> <ide> ``` <ide> <ide> tests: <ide> background-color: dodgerblue; <ide> width: 100%; <ide> height: 200px; <del> <add> <ide> } <ide> <ide> #box-2 { <ide> background-color: orangered; <ide> width: 100%; <ide> height: 200px; <del> <add> <ide> } <ide> </style> <ide> <ide> <div id="box-container"> <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-flex-wrap-property-to-wrap-a-row-or-column.chinese.md <ide> id: 587d78ad367417b2b2512afa <ide> title: Use the flex-wrap Property to Wrap a Row or Column <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用flex-wrap属性包装行或列 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cQv9ZtG' <add>forumTopicId: 301114 <add>localeTitle: 使用 flex-wrap 属性包裹一行或一列 <ide> --- <ide> <ide> ## Description <del><section id="description"> CSS flexbox具有将flex项分割为多行(或列)的功能。默认情况下,Flex容器将所有Flex项目放在一起。例如,一行将全部在一行上。但是,使用<code>flex-wrap</code>属性,它会告诉CSS包装项目。这意味着额外的项目将移动到新的行或列中。包装发生的断点取决于物品的大小和容器的大小。 CSS还有包装方向的选项: <ul><li> <code>nowrap</code> :这是默认设置,不包装项目。 </li><li> <code>wrap</code> :如果项目在一行中,则从左到右包装,如果它们在列中,则从上到下包装。 </li><li> <code>wrap-reverse</code> :如果项目在一行中,则从下到上包装项目;如果它们在列中,则从右到左包装。 </li></ul></section> <add><section id='description'> <add>CSS flexbox 有一个把 flex 子元素拆分为多行(或多列)的特性。默认情况下,flex 容器会调整项目大小,把它们都塞到一起。如果是行的话,所有项目都会在一条直线上。 <add>不过,使用<code>flex-wrap</code>属性可以使项目换行。这意味着多出来的项目会被移到新的行或列。换行发生的断点由项目和容器的大小决定。 <add>换行方向的可选值有这些: <add><ul><li><code>nowrap</code>:默认值,不换行。</li><li><code>wrap</code>:行从上到下排,列从左到又排。</li><li><code>wrap-reverse</code>:行从下到上排,列从左到右排。</li></ul> <add></section> <ide> <ide> ## Instructions <del><section id="instructions">当前布局对于一行有太多的框。将CSS属性<code>flex-wrap</code>添加到<code>#box-container</code>元素,并为其赋值wrap。 </section> <add><section id='instructions'> <add>现在的布局一行里面元素太多了,在<code>#box-container</code>元素添加 CSS 属性<code>flex-wrap</code>,把值设为 wrap。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-container</code>元素应该将<code>flex-wrap</code>属性设置为wrap值。' <del> testString: 'assert($("#box-container").css("flex-wrap") == "wrap", "The <code>#box-container</code> element should have the <code>flex-wrap</code> property set to a value of wrap.");' <add> - text: '<code>#box-container</code>元素应有<code>flex-wrap</code>属性,其值应为 wrap。' <add> testString: assert($('#box-container').css('flex-wrap') == 'wrap', '<code>#box-container</code>元素应有<code>flex-wrap</code>属性,其值为 wrap。'); <ide> <ide> ``` <ide> <ide> tests: <ide> background: gray; <ide> display: flex; <ide> height: 100%; <del> <add> <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <ide> tests: <ide> <div id="box-5"></div> <ide> <div id="box-6"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-justify-content-property-in-the-tweet-embed.chinese.md <ide> id: 587d78ac367417b2b2512af7 <ide> title: Use the justify-content Property in the Tweet Embed <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 在Tweet Embed中使用justify-content属性 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/c43GgTa' <add>forumTopicId: 301115 <add>localeTitle: 在推文中使用 justify-content 属性 <ide> --- <ide> <ide> ## Description <del><section id="description">最后一项挑战展示了一个<code>justify-content</code>属性的例子。对于tweet嵌入,可以应用此属性来对齐<code>.profile-name</code>元素中的项目。 </section> <add><section id='description'> <add>上一项挑战展示了<code>justify-content</code>属性的作用。如果我们想对齐推文内的子元素,可以把<code>justify-content</code>应用在<code>.profile-name</code>上。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>justify-content</code>添加到标头的<code>.profile-name</code>元素,并将值设置为上一个挑战中的任何选项。 </section> <add><section id='instructions'> <add>在 header 的<code>.profile-name</code>元素添加 CSS 属性<code>justify-content</code>,把它的值设为上面挑战提到的任意可用值。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: <code>.profile-name</code>元素应将<code>justify-content</code>属性设置为以下任何值:center,flex-start,flex-end,space-between,space-around或space-evenly。 <del> testString: 'assert(code.match(/header\s.profile-name\s*{\s*?.*?\s*?.*?\s*?\s*?.*?\s*?justify-content\s*:\s*(center|flex-start|flex-end|space-between|space-around|space-evenly)\s*;/g), "The <code>.profile-name</code> element should have the <code>justify-content</code> property set to any of these values: center, flex-start, flex-end, space-between, space-around, or space-evenly.");' <add> - text: '<code>.profile-name</code>元素的<code>justify-content</code>属性可选以下值:center、flex-start、flex-end、space-between、space-around。' <add> testString: 'assert(code.match(/header\s.profile-name\s*{\s*?.*?\s*?.*?\s*?\s*?.*?\s*?justify-content\s*:\s*(center|flex-start|flex-end|space-between|space-around)\s*;/g), ''<code>.profile-name</code>元素的<code>justify-content</code>属性可选以下值:center、flex-start、flex-end、space-between、space-around。'');' <ide> <ide> ``` <ide> <ide> tests: <ide> header .profile-name { <ide> display: flex; <ide> flex-direction: column; <del> <add> <ide> margin-left: 10px; <ide> } <ide> header .follow-btn { <ide> tests: <ide> <button class="like-btn">Like</button> <ide> </div> <ide> </footer> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file <ide><path>curriculum/challenges/chinese/01-responsive-web-design/css-flexbox/use-the-order-property-to-rearrange-items.chinese.md <ide> id: 587d78ae367417b2b2512aff <ide> title: Use the order Property to Rearrange Items <ide> challengeType: 0 <del>videoUrl: '' <del>localeTitle: 使用order属性重新排列项目 <add>videoUrl: 'https://scrimba.com/p/pVaDAv/cMbvNAG' <add>forumTopicId: 301116 <add>localeTitle: 使用 order 属性重新排列项目 <ide> --- <ide> <ide> ## Description <del><section id="description"> <code>order</code>属性用于告诉CSS Flex项目在Flex容器中的显示顺序。默认情况下,项目将以与源HTML相同的顺序显示。该属性将数字作为值,可以使用负数。 </section> <add><section id='description'> <add><code>order</code>属性告诉 CSS flex 容器里项目的顺序。默认情况下,项目排列顺序与源 HTML 文件中顺序相同。这个属性接受数字作为参数,可以使用负数。 <add></section> <ide> <ide> ## Instructions <del><section id="instructions">将CSS属性<code>order</code>添加到<code>#box-1</code>和<code>#box-2</code> 。给<code>#box-1</code>一个值2,给<code>#box-2</code>一个值1。 </section> <add><section id='instructions'> <add>给<code>#box-1</code>和<code>#box-2</code>添加 CSS 属性<code>order</code>,<code>#box-1</code>的<code>order</code>属性值设为 2,<code>#box-2</code>的<code>order</code>属性值设为 1。 <add></section> <ide> <ide> ## Tests <ide> <section id='tests'> <ide> <ide> ```yml <ide> tests: <del> - text: '<code>#box-1</code>元素的<code>order</code>属性应设置为值2。' <del> testString: 'assert($("#box-1").css("order") == "2", "The <code>#box-1</code> element should have the <code>order</code> property set to a value of 2.");' <del> - text: '<code>#box-2</code>元素应该将<code>order</code>属性设置为值1。' <del> testString: 'assert($("#box-2").css("order") == "1", "The <code>#box-2</code> element should have the <code>order</code> property set to a value of 1.");' <add> - text: '<code>#box-1</code>元素应有<code>order</code>属性,其值应为 2。' <add> testString: assert($('#box-1').css('order') == '2', '<code>#box-1</code>元素应有<code>order</code>属性,其值应为 2。'); <add> - text: '<code>#box-2</code>元素应有<code>order</code>属性,其值应为 1。' <add> testString: assert($('#box-2').css('order') == '1', '<code>#box-2</code>元素应有<code>order</code>属性,其值应为 1。'); <ide> <ide> ``` <ide> <ide> tests: <ide> } <ide> #box-1 { <ide> background-color: dodgerblue; <del> <add> <ide> height: 200px; <ide> width: 200px; <ide> } <ide> <ide> #box-2 { <ide> background-color: orangered; <del> <add> <ide> height: 200px; <ide> width: 200px; <ide> } <ide> tests: <ide> <div id="box-1"></div> <ide> <div id="box-2"></div> <ide> </div> <del> <ide> ``` <ide> <ide> </div> <ide> tests: <ide> ## Solution <ide> <section id='solution'> <ide> <del>```js <add>```html <ide> // solution required <ide> ``` <add> <ide> </section> <add> <ide>\ No newline at end of file
17
Javascript
Javascript
add missings async assert timeout
d58163a5fa8faa477e5c43fc73a40cb48d8866a0
<ide><path>test/unit/editor/old_to_convert/Serialization.tests.js <ide> QUnit.module( "Serialization" ); <ide> <ide> QUnit.test( "Test Serialization", function( assert ) { <ide> <add> assert.timeout( 1000 ); <add> <ide> // setup <ide> var editor = new Editor(); <ide> var done = assert.async(); <ide><path>test/unit/src/core/BufferGeometry.tests.js <ide> export default QUnit.module( 'Core', () => { <ide> <ide> QUnit.test( "fromGeometry/fromDirectGeometry", ( assert ) => { <ide> <add> assert.timeout( 1000 ); <add> <ide> var a = new BufferGeometry(); <ide> // BoxGeometry is a bit too simple but works fine in a pinch <ide> // var b = new BoxGeometry( 1, 1, 1 ); <ide><path>test/unit/src/core/DirectGeometry.tests.js <ide> export default QUnit.module( 'Core', () => { <ide> <ide> QUnit.test( "fromGeometry", ( assert ) => { <ide> <add> assert.timeout( 1000 ); <add> <ide> var a = new DirectGeometry(); <ide> <ide> var asyncDone = assert.async(); // tell QUnit when we're done with async stuff <ide> export default QUnit.module( 'Core', () => { <ide> <ide> asyncDone(); <ide> <del> } ); <add> }, onProgress, onError ); <add> <add> function onProgress() {} <add> <add> function onError( error ) { <add> <add> console.error( error ); <add> asyncDone(); <add> <add> } <ide> <ide> } ); <ide>
3
Javascript
Javascript
use class for write buffer entries
312289b791a5924eec5748fbd19ad6867ff37320
<ide><path>lib/_stream_writable.js <ide> var Stream = require('stream'); <ide> <ide> util.inherits(Writable, Stream); <ide> <add>function WriteReq(chunk, encoding, cb) { <add> this.chunk = chunk; <add> this.encoding = encoding; <add> this.callback = cb; <add>} <add> <ide> function WritableState(options, stream) { <ide> options = options || {}; <ide> <ide> function writeOrBuffer(stream, state, chunk, encoding, cb) { <ide> state.needDrain = !ret; <ide> <ide> if (state.writing) <del> state.buffer.push([chunk, encoding, cb]); <add> state.buffer.push(new WriteReq(chunk, encoding, cb)); <ide> else <ide> doWrite(stream, state, len, chunk, encoding, cb); <ide> <ide> function clearBuffer(stream, state) { <ide> <ide> for (var c = 0; c < state.buffer.length; c++) { <ide> var entry = state.buffer[c]; <del> var chunk = entry[0]; <del> var encoding = entry[1]; <del> var cb = entry[2]; <add> var chunk = entry.chunk; <add> var encoding = entry.encoding; <add> var cb = entry.callback; <ide> var len = state.objectMode ? 1 : chunk.length; <ide> <ide> doWrite(stream, state, len, chunk, encoding, cb); <ide><path>test/simple/test-stream2-transform.js <ide> test('writable side consumption', function(t) { <ide> t.equal(transformed, 10); <ide> t.equal(tx._transformState.writechunk.length, 5); <ide> t.same(tx._writableState.buffer.map(function(c) { <del> return c[0].length; <add> return c.chunk.length; <ide> }), [6, 7, 8, 9, 10]); <ide> <ide> t.end();
2
Javascript
Javascript
show stderr on v8 coverage test failures
eb0bf8d3077f7fd4d09f187b8bb8290ec8f8171b
<ide><path>test/parallel/test-v8-coverage.js <ide> function nextdir() { <ide> const output = spawnSync(process.execPath, [ <ide> require.resolve('../fixtures/v8-coverage/basic') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <add> if (output.status !== 0) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 0); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('basic.js', coverageDirectory); <ide> function nextdir() { <ide> const output = spawnSync(process.execPath, [ <ide> require.resolve('../fixtures/v8-coverage/exit-1') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <add> if (output.status !== 1) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 1); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('exit-1.js', coverageDirectory); <ide> function nextdir() { <ide> require.resolve('../fixtures/v8-coverage/sigint') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <ide> if (!common.isWindows) { <add> if (output.signal !== 'SIGINT') { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.signal, 'SIGINT'); <ide> } <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> function nextdir() { <ide> const output = spawnSync(process.execPath, [ <ide> require.resolve('../fixtures/v8-coverage/spawn-subprocess') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <add> if (output.status !== 0) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 0); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('subprocess.js', <ide> function nextdir() { <ide> const output = spawnSync(process.execPath, [ <ide> require.resolve('../fixtures/v8-coverage/worker') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <add> if (output.status !== 0) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 0); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('subprocess.js', <ide> function nextdir() { <ide> const output = spawnSync(process.execPath, [ <ide> require.resolve('../fixtures/v8-coverage/spawn-subprocess-no-cov') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <add> if (output.status !== 0) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 0); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('subprocess.js', <ide> function nextdir() { <ide> const output = spawnSync(process.execPath, [ <ide> require.resolve('../fixtures/v8-coverage/async-hooks') <ide> ], { env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } }); <add> if (output.status !== 0) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 0); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('async-hooks.js', <ide> function nextdir() { <ide> cwd: tmpdir.path, <ide> env: { ...process.env, NODE_V8_COVERAGE: coverageDirectory } <ide> }); <add> if (output.status !== 0) { <add> console.log(output.stderr.toString()); <add> } <ide> assert.strictEqual(output.status, 0); <ide> assert.strictEqual(output.stderr.toString(), ''); <ide> const fixtureCoverage = getFixtureCoverage('basic.js',
1
Go
Go
fix testeventsimageimport racy, fixes
eeb8ceb9edb61f4b8889360e4c4a2c4250c2d9f6
<ide><path>integration-cli/docker_cli_events_test.go <ide> func (s *DockerSuite) TestEventsImagePull(c *check.C) { <ide> func (s *DockerSuite) TestEventsImageImport(c *check.C) { <ide> since := daemonTime(c).Unix() <ide> <add> id := make(chan string) <add> eventImport := make(chan struct{}) <add> eventsCmd := exec.Command(dockerBinary, "events", "--since", strconv.FormatInt(since, 10)) <add> stdout, err := eventsCmd.StdoutPipe() <add> if err != nil { <add> c.Fatal(err) <add> } <add> err = eventsCmd.Start() <add> if err != nil { <add> c.Fatal(err) <add> } <add> defer eventsCmd.Process.Kill() <add> <add> go func() { <add> containerID := <-id <add> <add> matchImport := regexp.MustCompile(containerID + `: import$`) <add> scanner := bufio.NewScanner(stdout) <add> for scanner.Scan() { <add> if matchImport.MatchString(scanner.Text()) { <add> close(eventImport) <add> } <add> } <add> }() <add> <ide> runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "true") <ide> out, _, err := runCommandWithOutput(runCmd) <ide> if err != nil { <ide> func (s *DockerSuite) TestEventsImageImport(c *check.C) { <ide> if err != nil { <ide> c.Errorf("import failed with errors: %v, output: %q", err, out) <ide> } <add> newContainerID := strings.TrimSpace(out) <add> id <- newContainerID <ide> <del> eventsCmd := exec.Command(dockerBinary, "events", <del> fmt.Sprintf("--since=%d", since), <del> fmt.Sprintf("--until=%d", daemonTime(c).Unix())) <del> out, _, _ = runCommandWithOutput(eventsCmd) <del> <del> events := strings.Split(strings.TrimSpace(out), "\n") <del> event := strings.TrimSpace(events[len(events)-1]) <del> <del> if !strings.HasSuffix(event, ": import") { <del> c.Fatalf("Missing import event - got:%q", event) <add> select { <add> case <-time.After(5 * time.Second): <add> c.Fatal("failed to observe image import in timely fashion") <add> case <-eventImport: <add> // ignore, done <ide> } <del> <ide> } <ide> <ide> func (s *DockerSuite) TestEventsFilters(c *check.C) {
1
PHP
PHP
fix typo in variable
7a0b86ff9297639e14d772b79e5d555cdbeb28c1
<ide><path>src/Illuminate/Html/HtmlBuilder.php <ide> public function link($url, $title = null, $attributes = array(), $secure = null) <ide> { <ide> $url = $this->url->to($url, array(), $secure); <ide> <del> if (is_null($title) or $title === false) $title = $uri; <add> if (is_null($title) or $title === false) $title = $url; <ide> <ide> return '<a href="'.$url.'"'.$this->attributes($attributes).'>'.$this->entities($title).'</a>'; <ide> }
1
Javascript
Javascript
use common/fixtures in tls-connect-no-host
c0bba73ac2263b7997484537bbe9f0d30fdeaf85
<ide><path>test/parallel/test-tls-connect-no-host.js <ide> 'use strict'; <ide> const common = require('../common'); <add>const fixtures = require('../common/fixtures'); <ide> <ide> if (!common.hasCrypto) <ide> common.skip('missing crypto'); <ide> <ide> const tls = require('tls'); <ide> <ide> const assert = require('assert'); <del>const fs = require('fs'); <del>const path = require('path'); <ide> <del>const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); <del>const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); <add>const cert = fixtures.readSync('test_cert.pem'); <add>const key = fixtures.readSync('test_key.pem'); <ide> <ide> // https://github.com/nodejs/node/issues/1489 <ide> // tls.connect(options) with no options.host should accept a cert with
1
Javascript
Javascript
fix an issue with validation error formatting
18c313097a96212ad866ba6e7e7323e4736afca9
<ide><path>lib/WebpackOptionsValidationError.js <ide> class WebpackOptionsValidationError extends Error { <ide> constructor(validationErrors) { <ide> super(); <ide> <del> if(Error.hasOwnProperty("captureStackTrace")) { <del> Error.captureStackTrace(this, this.constructor); <del> } <ide> this.name = "WebpackOptionsValidationError"; <ide> <ide> this.message = "Invalid configuration object. " + <ide> "Webpack has been initialised using a configuration object that does not match the API schema.\n" + <ide> validationErrors.map(err => " - " + indent(WebpackOptionsValidationError.formatValidationError(err), " ", false)).join("\n"); <ide> this.validationErrors = validationErrors; <add> <add> if(Error.hasOwnProperty("captureStackTrace")) { <add> Error.captureStackTrace(this, this.constructor); <add> } <ide> } <ide> <ide> static formatSchema(schema, prevSchemas) {
1
Ruby
Ruby
do it in style
3cec029685cdbfa820eb6b4a98daf81ed80e1d27
<ide><path>activerecord/lib/active_record/connection_adapters/sqlite_adapter.rb <ide> def tables(name = nil) #:nodoc: <ide> end <ide> <ide> def columns(table_name, name = nil) #:nodoc: <del> table_structure(table_name).map { |field| <add> table_structure(table_name).map do |field| <ide> SQLiteColumn.new(field['name'], field['dflt_value'], field['type'], field['notnull'] == "0") <del> } <add> end <ide> end <ide> <ide> def indexes(table_name, name = nil) #:nodoc:
1
Text
Text
fix typo in the readme
7e6b6fbec9ce46d29e5bc37a24185188ed876511
<ide><path>README.md <ide> This is another example of pipeline used for that can extract question answers f <ide> <ide> On top of the answer, the pretrained model used here returned its confidence score, along with the start position and its end position in the tokenized sentence. You can learn more about the tasks supported by the `pipeline` API in [this tutorial](https://huggingface.co/transformers/task_summary.html). <ide> <del>To download and use any of the pretrained models on your given task, you just need to use those three lines of codes (PyTorch verison): <add>To download and use any of the pretrained models on your given task, you just need to use those three lines of codes (PyTorch version): <ide> ```python <ide> >>> from transformers import AutoTokenizer, AutoModel <ide>
1
Java
Java
move exceptions to public area, + exceptionhelper
d4e8f29730350efc763521f94f7ea23cf417b0e4
<ide><path>src/main/java/io/reactivex/Completable.java <ide> <ide> import io.reactivex.annotations.SchedulerSupport; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.*; <ide> import io.reactivex.internal.operators.completable.*; <ide> import io.reactivex.internal.subscribers.completable.*; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.schedulers.Schedulers; <ide> <ide><path>src/main/java/io/reactivex/Flowable.java <ide> <ide> import io.reactivex.annotations.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.flowables.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.schedulers.ImmediateThinScheduler; <ide> import io.reactivex.internal.subscribers.flowable.*; <ide> import io.reactivex.internal.subscriptions.EmptySubscription; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.ArrayListSupplier; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.schedulers.*; <ide> import io.reactivex.subscribers.*; <ide><path>src/main/java/io/reactivex/Observable.java <ide> <ide> import io.reactivex.annotations.*; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.operators.observable.*; <ide> import io.reactivex.internal.subscribers.observable.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.ArrayListSupplier; <ide> import io.reactivex.observables.*; <ide> import io.reactivex.observers.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide><path>src/main/java/io/reactivex/Scheduler.java <ide> import java.util.concurrent.TimeUnit; <ide> <ide> import io.reactivex.disposables.*; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public abstract class Scheduler { <ide><path>src/main/java/io/reactivex/Single.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.operators.single.*; <ide> import io.reactivex.internal.subscribers.single.*; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.schedulers.Schedulers; <ide> <ide><path>src/main/java/io/reactivex/annotations/SchedulerSupport.java <ide> <ide> package io.reactivex.annotations; <ide> <del>import io.reactivex.schedulers.Schedulers; <ide> import java.lang.annotation.*; <ide> <add>import io.reactivex.schedulers.Schedulers; <add> <ide> /** <ide> * Indicates what kind of scheduler the class or method uses. <ide> * <p> <ide><path>src/main/java/io/reactivex/disposables/CompositeDisposable.java <ide> <ide> import java.util.*; <ide> <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.internal.disposables.DisposableContainer; <ide> import io.reactivex.internal.functions.Objects; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.OpenHashSet; <ide> <ide> /** <ide> * A disposable container that can hold onto multiple other disposables. <ide><path>src/main/java/io/reactivex/disposables/RefCountDisposable.java <ide> <ide> package io.reactivex.disposables; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.concurrent.atomic.*; <ide> <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.functions.Objects; <ide> <ide> public final class RefCountDisposable implements Disposable { <ide><path>src/main/java/io/reactivex/disposables/ReferenceDisposable.java <ide> <ide> package io.reactivex.disposables; <ide> <del>import io.reactivex.internal.functions.Objects; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <add>import io.reactivex.internal.functions.Objects; <add> <ide> abstract class ReferenceDisposable<T> extends AtomicReference<T> implements Disposable { <ide> /** */ <ide> private static final long serialVersionUID = 6537757548749041217L; <ide><path>src/main/java/io/reactivex/disposables/SerialDisposable.java <ide> <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <del>import io.reactivex.internal.disposables.*; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> <ide> public final class SerialDisposable implements Disposable { <ide> final AtomicReference<Disposable> resource; <add><path>src/main/java/io/reactivex/exceptions/Exceptions.java <del><path>src/main/java/io/reactivex/internal/util/Exceptions.java <ide> * the License for the specific language governing permissions and limitations under the License. <ide> */ <ide> <del>package io.reactivex.internal.util; <add>package io.reactivex.exceptions; <ide> <del>import java.util.concurrent.atomic.AtomicReference; <del> <del>import io.reactivex.exceptions.*; <del> <del>public enum Exceptions { <del> ; <add>/** <add> * Utility class to help propagate checked exceptions and rethrow exceptions <add> * designated as fatal. <add> */ <add>public final class Exceptions { <add> <add> /** Utility class. */ <add> private Exceptions() { <add> throw new IllegalStateException("No instances!"); <add> } <ide> /** <ide> * Convenience method to throw a {@code RuntimeException} and {@code Error} directly <ide> * or wrap any other exception type into a {@code RuntimeException}. <ide> else if (t instanceof StackOverflowError) { <ide> throw (LinkageError) t; <ide> } <ide> } <del> <del> /** <del> * A singleton instance of a Throwable indicating a terminal state for exceptions, <del> * don't leak this! <del> */ <del> public static final Throwable TERMINATED = new Throwable("No further exceptions"); <del> <del> public static <T> boolean addThrowable(AtomicReference<Throwable> field, Throwable exception) { <del> for (;;) { <del> Throwable current = field.get(); <del> <del> if (current == TERMINATED) { <del> return false; <del> } <del> <del> Throwable update; <del> if (current == null) { <del> update = exception; <del> } else { <del> update = new CompositeException(current, exception); <del> } <del> <del> if (field.compareAndSet(current, update)) { <del> return true; <del> } <del> } <del> } <del> <del> public static <T> Throwable terminate(AtomicReference<Throwable> field) { <del> Throwable current = field.get(); <del> if (current != TERMINATED) { <del> current = field.getAndSet(TERMINATED); <del> } <del> return current; <del> } <ide> } <ide><path>src/main/java/io/reactivex/flowables/BlockingFlowable.java <ide> import io.reactivex.Flowable; <ide> import io.reactivex.Optional; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.operators.flowable.*; <ide> import io.reactivex.internal.subscribers.flowable.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.subscribers.DefaultObserver; <ide> <ide><path>src/main/java/io/reactivex/flowables/ConnectableFlowable.java <ide> <ide> package io.reactivex.flowables; <ide> <del>import org.reactivestreams.*; <add>import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <ide><path>src/main/java/io/reactivex/internal/disposables/ListCompositeDisposable.java <ide> <ide> import java.util.*; <ide> <del>import io.reactivex.disposables.*; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.internal.functions.Objects; <del>import io.reactivex.internal.util.*; <ide> <ide> /** <ide> * A disposable container that can hold onto multiple other disposables. <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableAwait.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.functions.Objects; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public enum CompletableAwait { <ide> ; <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableLift.java <ide> package io.reactivex.internal.operators.completable; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class CompletableLift extends Completable { <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableMerge.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class CompletableMerge extends Completable { <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletablePeek.java <ide> package io.reactivex.internal.operators.completable; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.disposables.Disposable; <del>import io.reactivex.disposables.Disposables; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class CompletablePeek extends Completable { <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableUnsubscribeOn.java <ide> package io.reactivex.internal.operators.completable; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.disposables.Disposable; <del>import io.reactivex.disposables.Disposables; <add>import io.reactivex.disposables.*; <ide> <ide> public final class CompletableUnsubscribeOn extends Completable { <ide> <ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableUsing.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.internal.functions.Objects; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class CompletableUsing<R> extends Completable { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterator.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public final class BlockingFlowableIterator<T> <ide> extends AtomicReference<Subscription> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableLatest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.Optional; <del>import io.reactivex.internal.subscribers.flowable.DisposableSubscriber; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <add>import io.reactivex.subscribers.DisposableSubscriber; <ide> <ide> /** <ide> * Wait for and iterate over the latest values of the source observable. If the source works faster than the <ide><path>src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableMostRecent.java <ide> <ide> import org.reactivestreams.Publisher; <ide> <del>import io.reactivex.internal.util.*; <add>import io.reactivex.exceptions.Exceptions; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.subscribers.DefaultObserver; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableNext.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.Optional; <del>import io.reactivex.internal.subscribers.flowable.DisposableSubscriber; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <add>import io.reactivex.subscribers.DisposableSubscriber; <ide> <ide> /** <ide> * Returns an Iterable that blocks until the Observable emits another item, then returns that item. <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBuffer.java <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.BooleanSupplier; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.internal.util.QueueDrainHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableBufferBoundary<T, U extends Collection<? super T>, Open, Close> <ide> extends Flowable<U> { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundarySupplier.java <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <ide> import io.reactivex.internal.util.QueueDrainHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableBufferBoundarySupplier<T, U extends Collection<? super T>, B> <ide> extends Flowable<U> { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferExactBoundary.java <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <ide> import io.reactivex.internal.util.QueueDrainHelper; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableBufferExactBoundary<T, U extends Collection<? super T>, B> <ide> extends Flowable<U> { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferTimed.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.*; <ide> import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> import io.reactivex.*; <ide> import io.reactivex.Scheduler.Worker; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <ide> import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableCollect.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.BiConsumer; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public final class FlowableCollect<T, U> extends Flowable<U> { <ide> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import java.util.*; <add>import java.util.Iterator; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <ide> void innerComplete(int index) { <ide> <ide> void innerError(int index, Throwable e) { <ide> <del> if (Exceptions.addThrowable(error, e)) { <add> if (ExceptionHelper.addThrowable(error, e)) { <ide> if (!delayErrors) { <ide> cancelAll(); <ide> done = true; <ide> void drainAsync() { <ide> Exceptions.throwIfFatal(ex); <ide> <ide> cancelAll(); <del> Exceptions.addThrowable(error, ex); <del> ex = Exceptions.terminate(error); <add> ExceptionHelper.addThrowable(error, ex); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> return; <ide> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, SpscLinkedArr <ide> if (d) { <ide> if (delayErrors) { <ide> if (empty) { <del> Throwable e = Exceptions.terminate(error); <add> Throwable e = ExceptionHelper.terminate(error); <ide> <del> if (e != null && e != Exceptions.TERMINATED) { <add> if (e != null && e != ExceptionHelper.TERMINATED) { <ide> a.onError(e); <ide> } else { <ide> a.onComplete(); <ide> } <ide> return true; <ide> } <ide> } else { <del> Throwable e = Exceptions.terminate(error); <add> Throwable e = ExceptionHelper.terminate(error); <ide> <del> if (e != null && e != Exceptions.TERMINATED) { <add> if (e != null && e != ExceptionHelper.TERMINATED) { <ide> cancelAll(); <ide> q.clear(); <ide> a.onError(e); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMap.java <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.queue.SpscArrayQueue; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.internal.util.ExceptionHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class FlowableConcatMap<T, R> extends FlowableSource<T, R> { <ide> void subscribeActual() { <ide> <ide> @Override <ide> public void onError(Throwable t) { <del> if (Exceptions.addThrowable(error, t)) { <add> if (ExceptionHelper.addThrowable(error, t)) { <ide> inner.cancel(); <ide> <ide> if (getAndIncrement() == 0) { <del> t = Exceptions.terminate(error); <del> if (t != Exceptions.TERMINATED) { <add> t = ExceptionHelper.terminate(error); <add> if (t != ExceptionHelper.TERMINATED) { <ide> actual.onError(t); <ide> } <ide> } <ide> public void innerNext(R value) { <ide> if (compareAndSet(1, 0)) { <ide> return; <ide> } <del> Throwable e = Exceptions.terminate(error); <del> if (e != Exceptions.TERMINATED) { <add> Throwable e = ExceptionHelper.terminate(error); <add> if (e != ExceptionHelper.TERMINATED) { <ide> actual.onError(e); <ide> } <ide> } <ide> } <ide> <ide> @Override <ide> public void innerError(Throwable e) { <del> if (Exceptions.addThrowable(error, e)) { <add> if (ExceptionHelper.addThrowable(error, e)) { <ide> s.cancel(); <ide> <ide> if (getAndIncrement() == 0) { <del> e = Exceptions.terminate(error); <del> if (e != Exceptions.TERMINATED) { <add> e = ExceptionHelper.terminate(error); <add> if (e != ExceptionHelper.TERMINATED) { <ide> actual.onError(e); <ide> } <ide> } <ide> void drain() { <ide> if (get() == 0 && compareAndSet(0, 1)) { <ide> actual.onNext(vr); <ide> if (!compareAndSet(1, 0)) { <del> Throwable e = Exceptions.terminate(error); <del> if (e != Exceptions.TERMINATED) { <add> Throwable e = ExceptionHelper.terminate(error); <add> if (e != ExceptionHelper.TERMINATED) { <ide> actual.onError(e); <ide> } <ide> return; <ide> void subscribeActual() { <ide> <ide> @Override <ide> public void onError(Throwable t) { <del> if (Exceptions.addThrowable(error, t)) { <add> if (ExceptionHelper.addThrowable(error, t)) { <ide> done = true; <ide> drain(); <ide> } else { <ide> public void innerNext(R value) { <ide> <ide> @Override <ide> public void innerError(Throwable e) { <del> if (Exceptions.addThrowable(error, e)) { <add> if (ExceptionHelper.addThrowable(error, e)) { <ide> if (!veryEnd) { <ide> s.cancel(); <ide> done = true; <ide> void drain() { <ide> if (d && !veryEnd) { <ide> Throwable ex = error.get(); <ide> if (ex != null) { <del> ex = Exceptions.terminate(error); <del> if (ex != Exceptions.TERMINATED) { <add> ex = ExceptionHelper.terminate(error); <add> if (ex != ExceptionHelper.TERMINATED) { <ide> actual.onError(ex); <ide> } <ide> return; <ide> void drain() { <ide> boolean empty = v == null; <ide> <ide> if (d && empty) { <del> Throwable ex = Exceptions.terminate(error); <del> if (ex != null && ex != Exceptions.TERMINATED) { <add> Throwable ex = ExceptionHelper.terminate(error); <add> if (ex != null && ex != ExceptionHelper.TERMINATED) { <ide> actual.onError(ex); <ide> } else { <ide> actual.onComplete(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEager.java <ide> <ide> import org.reactivestreams.*; <ide> <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> public void onNext(T t) { <ide> <ide> @Override <ide> public void onError(Throwable t) { <del> if (Exceptions.addThrowable(error, t)) { <add> if (ExceptionHelper.addThrowable(error, t)) { <ide> done = true; <ide> drain(); <ide> } else { <ide> public void innerNext(InnerQueuedSubscriber<R> inner, R value) { <ide> <ide> @Override <ide> public void innerError(InnerQueuedSubscriber<R> inner, Throwable e) { <del> if (Exceptions.addThrowable(this.error, e)) { <add> if (ExceptionHelper.addThrowable(this.error, e)) { <ide> inner.setDone(); <ide> if (errorMode != ErrorMode.END) { <ide> s.cancel(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDebounce.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.functions.Function; <del>import io.reactivex.internal.subscribers.flowable.DisposableSubscriber; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.internal.util.BackpressureHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableDebounce<T, U> extends Flowable<T> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableDoOnEach.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.fuseable.ConditionalSubscriber; <ide> import io.reactivex.internal.subscribers.flowable.*; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class FlowableDoOnEach<T> extends Flowable<T> { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFlatMap.java <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.queue.*; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> <ide> public final class FlowableFlatMap<T, U> extends Flowable<U> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFlattenIterable.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import java.util.*; <add>import java.util.Iterator; <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.*; <ide> public void onNext(T t) { <ide> <ide> @Override <ide> public void onError(Throwable t) { <del> if (Exceptions.addThrowable(error, t)) { <add> if (ExceptionHelper.addThrowable(error, t)) { <ide> done = true; <ide> drain(); <ide> } else { <ide> void drain() { <ide> } catch (Throwable ex) { <ide> Exceptions.throwIfFatal(ex); <ide> s.cancel(); <del> Exceptions.addThrowable(error, ex); <del> ex = Exceptions.terminate(error); <add> ExceptionHelper.addThrowable(error, ex); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> current = null; <ide> q.clear(); <ide> boolean checkTerminated(boolean d, boolean empty, Subscriber<?> a, SimpleQueue<? <ide> if (d) { <ide> Throwable ex = error.get(); <ide> if (ex != null) { <del> ex = Exceptions.terminate(error); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> current = null; <ide> q.clear(); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFromAsync.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFromCallable.java <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.subscriptions.DeferredScalarSubscription; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public final class FlowableFromCallable<T> extends Flowable<T> implements Callable<T> { <ide> final Callable<? extends T> callable; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableFromIterable.java <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.ConditionalSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> <ide> public final class FlowableFromIterable<T> extends Flowable<T> { <ide> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupBy.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import java.util.*; <add>import java.util.Map; <ide> import java.util.concurrent.ConcurrentHashMap; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.flowables.GroupedFlowable; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class FlowableGroupBy<T, K, V> extends Flowable<GroupedFlowable<K, V>> { <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.*; <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> void cancelAll() { <ide> } <ide> <ide> void errorAll(Subscriber<?> a) { <del> Throwable ex = Exceptions.terminate(error); <add> Throwable ex = ExceptionHelper.terminate(error); <ide> <ide> for (UnicastProcessor<TRight> up : lefts.values()) { <ide> up.onError(ex); <ide> void errorAll(Subscriber<?> a) { <ide> <ide> void fail(Throwable exc, Subscriber<?> a, SimpleQueue<?> q) { <ide> Exceptions.throwIfFatal(exc); <del> Exceptions.addThrowable(error, exc); <add> ExceptionHelper.addThrowable(error, exc); <ide> q.clear(); <ide> cancelAll(); <ide> errorAll(a); <ide> else if (mode == RIGHT_CLOSE) { <ide> <ide> @Override <ide> public void innerError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> active.decrementAndGet(); <ide> drain(); <ide> } else { <ide> public void innerClose(boolean isLeft, LeftRightEndSubscriber index) { <ide> <ide> @Override <ide> public void innerCloseError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> drain(); <ide> } else { <ide> RxJavaPlugins.onError(ex); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableJoin.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.disposables.CompositeDisposable; <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> void cancelAll() { <ide> } <ide> <ide> void errorAll(Subscriber<?> a) { <del> Throwable ex = Exceptions.terminate(error); <add> Throwable ex = ExceptionHelper.terminate(error); <ide> <ide> lefts.clear(); <ide> rights.clear(); <ide> void errorAll(Subscriber<?> a) { <ide> <ide> void fail(Throwable exc, Subscriber<?> a, SimpleQueue<?> q) { <ide> Exceptions.throwIfFatal(exc); <del> Exceptions.addThrowable(error, exc); <add> ExceptionHelper.addThrowable(error, exc); <ide> q.clear(); <ide> cancelAll(); <ide> errorAll(a); <ide> void drain() { <ide> <ide> e++; <ide> } else { <del> Exceptions.addThrowable(error, new MissingBackpressureException("Could not emit value due to lack of requests")); <add> ExceptionHelper.addThrowable(error, new MissingBackpressureException("Could not emit value due to lack of requests")); <ide> q.clear(); <ide> cancelAll(); <ide> errorAll(a); <ide> else if (mode == RIGHT_VALUE) { <ide> <ide> e++; <ide> } else { <del> Exceptions.addThrowable(error, new MissingBackpressureException("Could not emit value due to lack of requests")); <add> ExceptionHelper.addThrowable(error, new MissingBackpressureException("Could not emit value due to lack of requests")); <ide> q.clear(); <ide> cancelAll(); <ide> errorAll(a); <ide> else if (mode == RIGHT_CLOSE) { <ide> <ide> @Override <ide> public void innerError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> active.decrementAndGet(); <ide> drain(); <ide> } else { <ide> public void innerClose(boolean isLeft, LeftRightEndSubscriber index) { <ide> <ide> @Override <ide> public void innerCloseError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> drain(); <ide> } else { <ide> RxJavaPlugins.onError(ex); <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableMapNotification.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <del>import io.reactivex.functions.*; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.internal.util.BackpressureHelper; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableObserveOn.java <ide> <ide> import io.reactivex.Scheduler; <ide> import io.reactivex.Scheduler.Worker; <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.queue.SpscArrayQueue; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> <ide> public final class FlowableObserveOn<T> extends FlowableSource<T, T> { <ide> final Scheduler scheduler; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableOnBackpressureBuffer.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <del>import io.reactivex.exceptions.MissingBackpressureException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.*; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.BackpressureHelper; <ide> <ide> public final class FlowableOnBackpressureBuffer<T> extends Flowable<T> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowablePublish.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.flowables.ConnectableFlowable; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.queue.SpscArrayQueue; <ide> import io.reactivex.internal.subscribers.flowable.SubscriberResourceWrapper; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableRedo.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.subscribers.flowable.ToNotificationSubscriber; <ide> import io.reactivex.internal.subscriptions.SubscriptionArbiter; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.processors.BehaviorProcessor; <ide> <ide> // FIXME split and update to the Rsc version <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.disposables.*; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.flowables.ConnectableFlowable; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.subscribers.flowable.SubscriberResourceWrapper; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableScanSeed.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <del>import io.reactivex.functions.*; <add>import io.reactivex.functions.BiFunction; <ide> import io.reactivex.internal.queue.SpscArrayQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableThrottleFirstTimed.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.Scheduler.Worker; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.internal.util.BackpressureHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.DisposableHelper; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.FullArbiterSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableTimeout<T, U, V> extends Flowable<T> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTimed.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.Scheduler.Worker; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.subscribers.flowable.FullArbiterSubscriber; <ide> import io.reactivex.internal.subscriptions.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableToList.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import java.util.*; <add>import java.util.Collection; <ide> import java.util.concurrent.Callable; <ide> <ide> import org.reactivestreams.*; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindow.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import java.util.*; <add>import java.util.ArrayDeque; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.UnicastProcessor; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableWindowBoundary<T, B> extends Flowable<Flowable<T>> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySelector.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.UnicastProcessor; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableWindowBoundarySelector<T, B, V> extends Flowable<Flowable<T>> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundarySupplier.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <del>import io.reactivex.internal.subscribers.flowable.*; <add>import io.reactivex.internal.subscribers.flowable.QueueDrainSubscriber; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.UnicastProcessor; <del>import io.reactivex.subscribers.SerializedSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public final class FlowableWindowBoundarySupplier<T, B> extends Flowable<Flowable<T>> { <ide> final Publisher<T> source; <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableZip.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import java.util.*; <add>import java.util.Arrays; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.queue.SpscArrayQueue; <ide> public void cancel() { <ide> } <ide> <ide> void error(Throwable e, int index) { <del> if (Exceptions.addThrowable(error, e)) { <add> if (ExceptionHelper.addThrowable(error, e)) { <ide> drain(); <ide> } else { <ide> RxJavaPlugins.onError(e); <ide> void drain() { <ide> if (error.get() != null) { <ide> cancelAll(); <ide> <del> Throwable ex = Exceptions.terminate(error); <add> Throwable ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> <ide> void drain() { <ide> <ide> cancelAll(); <ide> <del> Exceptions.addThrowable(error, ex); <del> ex = Exceptions.terminate(error); <add> ExceptionHelper.addThrowable(error, ex); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> <ide> void drain() { <ide> <ide> cancelAll(); <ide> <del> Exceptions.addThrowable(error, ex); <del> ex = Exceptions.terminate(error); <add> ExceptionHelper.addThrowable(error, ex); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> <ide> void drain() { <ide> <ide> Throwable ex = new NullPointerException("The zipper returned a null value"); <ide> <del> Exceptions.addThrowable(error, ex); <del> ex = Exceptions.terminate(error); <add> ExceptionHelper.addThrowable(error, ex); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> <ide> void drain() { <ide> if (error.get() != null) { <ide> cancelAll(); <ide> <del> Throwable ex = Exceptions.terminate(error); <add> Throwable ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> <ide> void drain() { <ide> <ide> cancelAll(); <ide> <del> Exceptions.addThrowable(error, ex); <del> ex = Exceptions.terminate(error); <add> ExceptionHelper.addThrowable(error, ex); <add> ex = ExceptionHelper.terminate(error); <ide> <ide> a.onError(ex); <ide> <ide><path>src/main/java/io/reactivex/internal/operators/flowable/ScalarXMap.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.Flowable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.subscriptions.*; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> /** <ide> * Utility classes to work with scalar-sourced XMap operators (where X == { flat, concat, switch }). <ide><path>src/main/java/io/reactivex/internal/operators/observable/BlockingObservableLatest.java <ide> import io.reactivex.*; <ide> import io.reactivex.Observable; <ide> import io.reactivex.Optional; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.subscribers.observable.DisposableObserver; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> /** <ide> * Wait for and iterate over the latest values of the source observable. If the source works faster than the <ide><path>src/main/java/io/reactivex/internal/operators/observable/BlockingObservableMostRecent.java <ide> import java.util.*; <ide> <ide> import io.reactivex.ObservableConsumable; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.exceptions.Exceptions; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observers.DefaultObserver; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/operators/observable/BlockingObservableNext.java <ide> import io.reactivex.Observable; <ide> import io.reactivex.Optional; <ide> import io.reactivex.Try; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.subscribers.observable.DisposableObserver; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> /** <ide> * Returns an Iterable that blocks until the Observable emits another item, then returns that item. <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableCombineLatest.java <ide> <ide> package io.reactivex.internal.operators.observable; <ide> <del>import java.util.*; <add>import java.util.Arrays; <ide> import java.util.concurrent.atomic.*; <ide> <del>import io.reactivex.Observable; <del>import io.reactivex.ObservableConsumable; <del>import io.reactivex.Observer; <add>import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.CompositeException; <ide> import io.reactivex.functions.Function; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableConcatMap.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.observers.SerializedObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableDistinct.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.disposables.*; <ide> import io.reactivex.internal.functions.*; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public final class ObservableDistinct<T, K> extends ObservableSource<T, T> { <ide> final Function<? super T, K> keySelector; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableFlatMap.java <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.queue.*; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public final class ObservableFlatMap<T, U> extends ObservableSource<T, U> { <ide> final Function<? super T, ? extends ObservableConsumable<? extends U>> mapper; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableGroupJoin.java <ide> import io.reactivex.ObservableConsumable; <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.internal.util.ExceptionHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.subjects.UnicastSubject; <ide> <ide> void cancelAll() { <ide> } <ide> <ide> void errorAll(Observer<?> a) { <del> Throwable ex = Exceptions.terminate(error); <add> Throwable ex = ExceptionHelper.terminate(error); <ide> <ide> for (UnicastSubject<TRight> up : lefts.values()) { <ide> up.onError(ex); <ide> void errorAll(Observer<?> a) { <ide> <ide> void fail(Throwable exc, Observer<?> a, SpscLinkedArrayQueue<?> q) { <ide> Exceptions.throwIfFatal(exc); <del> Exceptions.addThrowable(error, exc); <add> ExceptionHelper.addThrowable(error, exc); <ide> q.clear(); <ide> cancelAll(); <ide> errorAll(a); <ide> else if (mode == RIGHT_CLOSE) { <ide> <ide> @Override <ide> public void innerError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> active.decrementAndGet(); <ide> drain(); <ide> } else { <ide> public void innerClose(boolean isLeft, LeftRightEndSubscriber index) { <ide> <ide> @Override <ide> public void innerCloseError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> drain(); <ide> } else { <ide> RxJavaPlugins.onError(ex); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableJoin.java <ide> import io.reactivex.ObservableConsumable; <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.operators.observable.ObservableGroupJoin.*; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.internal.util.ExceptionHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public class ObservableJoin<TLeft, TRight, TLeftEnd, TRightEnd, R> extends ObservableSource<TLeft, R> { <ide> void cancelAll() { <ide> } <ide> <ide> void errorAll(Observer<?> a) { <del> Throwable ex = Exceptions.terminate(error); <add> Throwable ex = ExceptionHelper.terminate(error); <ide> <ide> lefts.clear(); <ide> rights.clear(); <ide> void errorAll(Observer<?> a) { <ide> <ide> void fail(Throwable exc, Observer<?> a, SpscLinkedArrayQueue<?> q) { <ide> Exceptions.throwIfFatal(exc); <del> Exceptions.addThrowable(error, exc); <add> ExceptionHelper.addThrowable(error, exc); <ide> q.clear(); <ide> cancelAll(); <ide> errorAll(a); <ide> else if (mode == RIGHT_CLOSE) { <ide> <ide> @Override <ide> public void innerError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> active.decrementAndGet(); <ide> drain(); <ide> } else { <ide> public void innerClose(boolean isLeft, LeftRightEndSubscriber index) { <ide> <ide> @Override <ide> public void innerCloseError(Throwable ex) { <del> if (Exceptions.addThrowable(error, ex)) { <add> if (ExceptionHelper.addThrowable(error, ex)) { <ide> drain(); <ide> } else { <ide> RxJavaPlugins.onError(ex); <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservablePublish.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.disposables.*; <ide> import io.reactivex.internal.queue.SpscLinkedArrayQueue; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observables.ConnectableObservable; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableRedo.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.subscribers.observable.ToNotificationObserver; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.subjects.BehaviorSubject; <ide> <ide> public final class ObservableRedo<T> extends Observable<T> { <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableReplay.java <ide> import io.reactivex.*; <ide> import io.reactivex.Observable; <ide> import io.reactivex.Observer; <del>import io.reactivex.disposables.*; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.disposables.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observables.ConnectableObservable; <ide> import io.reactivex.schedulers.Timed; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableTimer.java <ide> <ide> package io.reactivex.internal.operators.observable; <ide> <del>import io.reactivex.internal.disposables.EmptyDisposable; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <del>import io.reactivex.internal.disposables.DisposableHelper; <add>import io.reactivex.internal.disposables.*; <ide> <ide> public final class ObservableTimer extends Observable<Long> { <ide> final Scheduler scheduler; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundary.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <ide> import io.reactivex.internal.subscribers.observable.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observers.SerializedObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.subjects.UnicastSubject; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableWindowBoundarySelector.java <ide> import io.reactivex.ObservableConsumable; <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <ide> import io.reactivex.internal.subscribers.observable.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observers.SerializedObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.subjects.UnicastSubject; <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableWindowTimed.java <ide> import io.reactivex.Observer; <ide> import io.reactivex.Scheduler.Worker; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.MpscLinkedQueue; <ide> import io.reactivex.internal.subscribers.observable.QueueDrainObserver; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observers.SerializedObserver; <ide> import io.reactivex.subjects.UnicastSubject; <ide> <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleAwait.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <ide> <ide> public enum SingleAwait { <ide> ; <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleContains.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.BiPredicate; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public final class SingleContains<T> extends Single<Boolean> { <ide> <ide><path>src/main/java/io/reactivex/internal/schedulers/IoScheduler.java <ide> <ide> import io.reactivex.Scheduler; <ide> import io.reactivex.disposables.*; <del>import io.reactivex.internal.disposables.*; <add>import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/schedulers/ScheduledRunnable.java <ide> import java.util.concurrent.Future; <ide> import java.util.concurrent.atomic.AtomicReferenceArray; <ide> <del>import io.reactivex.disposables.*; <add>import io.reactivex.disposables.Disposable; <ide> import io.reactivex.internal.disposables.DisposableContainer; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide><path>src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import io.reactivex.Scheduler; <del>import io.reactivex.disposables.Disposable; <del>import io.reactivex.disposables.Disposables; <add>import io.reactivex.disposables.*; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide><path>src/main/java/io/reactivex/internal/subscribers/completable/CallbackCompletableSubscriber.java <ide> <ide> import io.reactivex.CompletableSubscriber; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.disposables.DisposableHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class CallbackCompletableSubscriber <ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BasicFuseableConditionalSubscriber.java <ide> <ide> import org.reactivestreams.Subscription; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.*; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BasicFuseableSubscriber.java <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.fuseable.QueueSubscription; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BlockingSingleSubscriber.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.disposables.Disposable; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <ide> <ide> public abstract class BlockingSingleSubscriber<T> extends CountDownLatch <ide> implements Subscriber<T>, Disposable { <ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/BlockingSubscriber.java <ide> <ide> package io.reactivex.internal.subscribers.flowable; <ide> <del>import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import java.util.Queue; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.internal.util.NotificationLite; <ide> <ide> public final class BlockingSubscriber<T> extends AtomicReference<Subscription> implements Subscriber<T>, Subscription { <ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/LambdaSubscriber.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class LambdaSubscriber<T> extends AtomicReference<Subscription> implements Subscriber<T>, Subscription, Disposable { <ide><path>src/main/java/io/reactivex/internal/subscribers/flowable/ToNotificationSubscriber.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class ToNotificationSubscriber<T> implements Subscriber<T> { <ide><path>src/main/java/io/reactivex/internal/subscribers/observable/BlockingSingleObserver.java <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.Disposable; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.exceptions.Exceptions; <ide> <ide> public abstract class BlockingSingleObserver<T> extends CountDownLatch <ide> implements Observer<T>, Disposable { <ide><path>src/main/java/io/reactivex/internal/subscribers/observable/DisposableObserver.java <ide> <ide> package io.reactivex.internal.subscribers.observable; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> <ide> /** <ide> * An abstract subscription that allows asynchronous cancellation. <ide><path>src/main/java/io/reactivex/internal/subscribers/observable/LambdaObserver.java <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.disposables.DisposableHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class LambdaObserver<T> extends AtomicReference<Disposable> implements Observer<T>, Disposable { <ide><path>src/main/java/io/reactivex/internal/subscribers/observable/ToNotificationObserver.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.disposables.DisposableHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class ToNotificationObserver<T> implements Observer<T> { <ide><path>src/main/java/io/reactivex/internal/subscribers/single/BiConsumerSingleSubscriber.java <ide> <ide> import io.reactivex.SingleSubscriber; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.BiConsumer; <ide> import io.reactivex.internal.disposables.DisposableHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class BiConsumerSingleSubscriber<T> <ide><path>src/main/java/io/reactivex/internal/subscribers/single/ConsumerSingleSubscriber.java <ide> <ide> import io.reactivex.SingleSubscriber; <ide> import io.reactivex.disposables.Disposable; <del>import io.reactivex.exceptions.CompositeException; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.disposables.DisposableHelper; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public final class ConsumerSingleSubscriber<T> <ide><path>src/main/java/io/reactivex/internal/subscriptions/AsyncSubscription.java <ide> <ide> package io.reactivex.internal.subscriptions; <ide> <del>import io.reactivex.internal.disposables.DisposableHelper; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.reactivestreams.Subscription; <ide> <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.util.BackpressureHelper; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/util/ExceptionHelper.java <add>/** <add> * Copyright 2016 Netflix, Inc. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.util; <add> <add>import java.util.concurrent.atomic.AtomicReference; <add> <add>import io.reactivex.exceptions.CompositeException; <add> <add>/** <add> * Terminal atomics for Throwable containers. <add> */ <add>public enum ExceptionHelper { <add> ; <add> /** <add> * A singleton instance of a Throwable indicating a terminal state for exceptions, <add> * don't leak this! <add> */ <add> public static final Throwable TERMINATED = new Throwable("No further exceptions"); <add> <add> public static <T> boolean addThrowable(AtomicReference<Throwable> field, Throwable exception) { <add> for (;;) { <add> Throwable current = field.get(); <add> <add> if (current == TERMINATED) { <add> return false; <add> } <add> <add> Throwable update; <add> if (current == null) { <add> update = exception; <add> } else { <add> update = new CompositeException(current, exception); <add> } <add> <add> if (field.compareAndSet(current, update)) { <add> return true; <add> } <add> } <add> } <add> <add> public static <T> Throwable terminate(AtomicReference<Throwable> field) { <add> Throwable current = field.get(); <add> if (current != TERMINATED) { <add> current = field.getAndSet(TERMINATED); <add> } <add> return current; <add> } <add>} <ide><path>src/main/java/io/reactivex/internal/util/QueueDrainHelper.java <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.BooleanSupplier; <ide> import io.reactivex.internal.fuseable.SimpleQueue; <ide> import io.reactivex.internal.queue.*; <ide><path>src/main/java/io/reactivex/observables/BlockingObservable.java <ide> import io.reactivex.Observer; <ide> import io.reactivex.Optional; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.operators.observable.*; <ide> import io.reactivex.internal.subscribers.flowable.BlockingSubscriber; <ide> import io.reactivex.internal.subscribers.observable.*; <del>import io.reactivex.internal.util.*; <add>import io.reactivex.internal.util.NotificationLite; <ide> import io.reactivex.observers.DefaultObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide><path>src/main/java/io/reactivex/observers/Observers.java <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.functions.*; <del>import io.reactivex.internal.subscribers.observable.*; <add>import io.reactivex.internal.subscribers.observable.DisposableObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> /** <ide><path>src/main/java/io/reactivex/observers/SerializedObserver.java <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.disposables.DisposableHelper; <ide> import io.reactivex.internal.util.*; <ide><path>src/main/java/io/reactivex/plugins/RxJavaPlugins.java <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> /** <ide> * Utility class to inject handlers to certain standard RxJava operations. <ide><path>src/main/java/io/reactivex/processors/BehaviorProcessor.java <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide><path>src/main/java/io/reactivex/processors/FlowProcessor.java <ide> <ide> package io.reactivex.processors; <ide> <del>import org.reactivestreams.*; <add>import org.reactivestreams.Processor; <ide> <ide> import io.reactivex.Flowable; <ide> <ide><path>src/main/java/io/reactivex/processors/SerializedProcessor.java <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.util.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide><path>src/main/java/io/reactivex/schedulers/TestScheduler.java <ide> <ide> package io.reactivex.schedulers; <ide> <del>import java.util.*; <del>import java.util.concurrent.PriorityBlockingQueue; <del>import java.util.concurrent.TimeUnit; <add>import java.util.Queue; <add>import java.util.concurrent.*; <ide> <ide> import io.reactivex.Scheduler; <del>import io.reactivex.disposables.Disposable; <del>import io.reactivex.disposables.Disposables; <add>import io.reactivex.disposables.*; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.internal.functions.Objects; <ide> <ide><path>src/main/java/io/reactivex/subjects/BehaviorSubject.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.functions.Objects; <ide> import io.reactivex.internal.util.*; <ide><path>src/main/java/io/reactivex/subjects/SerializedSubject.java <ide> <ide> import io.reactivex.Observer; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.util.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <add><path>src/main/java/io/reactivex/subscribers/DisposableSubscriber.java <del><path>src/main/java/io/reactivex/internal/subscribers/flowable/DisposableSubscriber.java <ide> * the License for the specific language governing permissions and limitations under the License. <ide> */ <ide> <del>package io.reactivex.internal.subscribers.flowable; <add>package io.reactivex.subscribers; <ide> <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <ide><path>src/main/java/io/reactivex/subscribers/SerializedSubscriber.java <ide> <ide> import org.reactivestreams.*; <ide> <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Predicate; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.internal.util.*; <ide><path>src/main/java/io/reactivex/subscribers/Subscribers.java <ide> <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.internal.functions.*; <del>import io.reactivex.internal.subscribers.flowable.*; <ide> import io.reactivex.internal.subscriptions.SubscriptionHelper; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide><path>src/test/java/io/reactivex/completable/CompletableTest.java <ide> package io.reactivex.completable; <ide> <ide> import static org.junit.Assert.*; <add>import static org.mockito.Matchers.*; <ide> import static org.mockito.Mockito.*; <ide> <ide> import java.util.*; <ide><path>src/test/java/io/reactivex/exceptions/ExceptionsTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.util.Exceptions; <add>import io.reactivex.internal.util.ExceptionHelper; <ide> import io.reactivex.observables.GroupedObservable; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.subjects.PublishSubject; <ide> public class ExceptionsTest { <ide> @Ignore("Exceptions is not an enum") <ide> @Test <ide> public void constructorShouldBePrivate() { <del> TestHelper.checkUtilityClass(Exceptions.class); <add> TestHelper.checkUtilityClass(ExceptionHelper.class); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/flowable/FlowableConversionTest.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.Flowable.Operator; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.operators.flowable.*; <del>import io.reactivex.internal.util.Exceptions; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.*; <ide> <ide><path>src/test/java/io/reactivex/flowable/FlowableSubscriberTest.java <ide> import io.reactivex.Flowable.Operator; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.subscribers.*; <del>import io.reactivex.subscribers.DefaultObserver; <ide> <ide> public class FlowableSubscriberTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/BlockingFlowableToIteratorTest.java <ide> import org.junit.*; <ide> import org.reactivestreams.*; <ide> <del>import io.reactivex.*; <add>import io.reactivex.Flowable; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableCacheTest.java <ide> import io.reactivex.Flowable; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Consumer; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapEagerTest.java <ide> <ide> package io.reactivex.internal.operators.flowable; <ide> <del>import org.reactivestreams.Publisher; <ide> import static org.junit.Assert.*; <ide> <ide> import java.lang.reflect.Method; <ide> import java.util.*; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.junit.*; <add>import org.reactivestreams.Publisher; <ide> <del>import io.reactivex.*; <add>import io.reactivex.Flowable; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatTest.java <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Functions; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.*; <ide> import io.reactivex.schedulers.*; <ide> import io.reactivex.subscribers.*; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Function; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.TestScheduler; <ide> import io.reactivex.subscribers.TestSubscriber; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDoOnSubscribeTest.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.functions.Consumer; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> <ide> public class FlowableDoOnSubscribeTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFromIterableTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableFromIterableTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java <ide> import io.reactivex.flowables.GroupedFlowable; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.fuseable.QueueSubscription; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableGroupByTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.LongConsumer; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableMergeDelayErrorTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeMaxConcurrentTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.internal.schedulers.IoScheduler; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableObserveOnTest.java <ide> import io.reactivex.Optional; <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.*; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableObserveOnTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorResumeNextViaFunctionTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.Flowable.Operator; <ide> import io.reactivex.functions.Function; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.*; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnErrorReturnTest.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.functions.Function; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.*; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableOnExceptionResumeNextViaObservableTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.functions.Function; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowablePublishTest.java <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.flowables.ConnectableFlowable; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.*; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRangeTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.functions.Consumer; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableRangeTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Function; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.flowables.GroupedFlowable; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableRetryTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.TestScheduler; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSerializeTest.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.subscribers.DefaultObserver; <ide> <ide> public class FlowableSerializeTest { <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSingleTest.java <ide> import static org.mockito.Mockito.*; <ide> <ide> import java.util.*; <del>import java.util.concurrent.atomic.*; <add>import java.util.concurrent.atomic.AtomicLong; <ide> <del>import org.junit.*; <add>import org.junit.Test; <ide> import org.mockito.InOrder; <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.functions.*; <del>import io.reactivex.subscribers.*; <add>import io.reactivex.subscribers.DefaultObserver; <ide> <ide> public class FlowableSingleTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSwitchTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.TestScheduler; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableSwitchTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastOneTest.java <ide> <ide> import io.reactivex.Flowable; <ide> import io.reactivex.functions.Consumer; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableTakeLastOneTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeLastTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableTakeLastTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeWhileTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Predicate; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.*; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutTests.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.TestScheduler; <ide> import io.reactivex.subscribers.TestSubscriber; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeoutWithSelectorTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <del>import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.functions.Function; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithSizeTest.java <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableWindowWithSizeTest { <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableWindowWithTimeTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.functions.*; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.schedulers.TestScheduler; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> <ide> public class FlowableWindowWithTimeTest { <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableZipTest.java <ide> import io.reactivex.Optional; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions; <del>import io.reactivex.internal.subscriptions.*; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class FlowableZipTest { <ide> BiFunction<String, String, String> concat2Strings; <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTimeoutWithSelectorTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.TestException; <del>import io.reactivex.functions.*; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.schedulers.Schedulers; <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.disposables.*; <add>import io.reactivex.disposables.Disposable; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.schedulers.Schedulers; <ide> <ide><path>src/test/java/io/reactivex/processors/ReplayProcessorBoundedConcurrencyTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class ReplayProcessorBoundedConcurrencyTest { <ide> <ide><path>src/test/java/io/reactivex/processors/ReplayProcessorConcurrencyTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.functions.Consumer; <ide> import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.subscribers.DefaultObserver; <del>import io.reactivex.subscribers.TestSubscriber; <add>import io.reactivex.subscribers.*; <ide> <ide> public class ReplayProcessorConcurrencyTest { <ide> <ide><path>src/test/java/io/reactivex/schedulers/TestSchedulerTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.Exceptions; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <del>import io.reactivex.internal.util.Exceptions; <ide> <ide> public class TestSchedulerTest { <ide> <ide><path>src/test/java/io/reactivex/single/SingleNullTests.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.Single.*; <add>import io.reactivex.Single.SingleOperator; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions;
151
Python
Python
update version number
d0ed8aeb2126a4b14b8413bd8c6d54952451e890
<ide><path>libcloud/__init__.py <ide> <ide> __all__ = ["__version__", "enable_debug"] <ide> <del>__version__ = "0.4.3-dev" <add>__version__ = "0.5.0-dev" <ide> <ide> def enable_debug(fo): <ide> """
1
Text
Text
improve description and tests descriptions
c4cf53a7428bcbd6c029af0688008ae23f66a67d
<ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/closest-pair-problem.md <ide> dashedName: closest-pair-problem <ide> <ide> # --description-- <ide> <del>Provide a function to find the closest two points among a set of given points in two dimensions, i.e. to solve the [Closest pair of points problem](<https://en.wikipedia.org/wiki/Closest pair of points problem> "wp: Closest pair of points problem") in the *planar* case. <add>Provide a function to find the closest two points among a set of given points in two dimensions. <ide> <del>The straightforward solution is a O(n<sup>2</sup>) algorithm (which we can call *brute-force algorithm*); the pseudo-code (using indexes) could be simply: <add>The straightforward solution is a $O(n^2)$ algorithm (which we can call *brute-force algorithm*); the pseudo-code (using indexes) could be simply: <ide> <ide> <pre><strong>bruteForceClosestPair</strong> of P(1), P(2), ... P(N) <ide> <strong>if</strong> N &#x3C; 2 <strong>then</strong> <ide> The straightforward solution is a O(n<sup>2</sup>) algorithm (which we can call <ide> <strong>endif</strong> <ide> </pre> <ide> <del>A better algorithm is based on the recursive divide and conquer approach, as explained also at [Wikipedia's Closest pair of points problem](<https://en.wikipedia.org/wiki/Closest pair of points problem#Planar_case> "wp: Closest pair of points problem#Planar_case"), which is `O(nlog(n))` a pseudo-code could be: <add>A better algorithm is based on the recursive divide and conquer approach, which is $O(n\log n)$ a pseudo-code could be: <ide> <ide> <pre><strong>closestPair</strong> of (xP, yP) <ide> where xP is P(1) .. P(N) sorted by x coordinate, and <ide> A better algorithm is based on the recursive divide and conquer approach, as exp <ide> <strong>endif</strong> <ide> </pre> <ide> <del>For the input, expect the argument to be an array of objects (points) with `x` and `y` members set to numbers. For the output, return an object containing the key:value pairs for `distance` and `pair` (the pair of two closest points). <add>For the input, expect the argument to be an array of `Point` objects with `x` and `y` members set to numbers. Return an object containing the key:value pairs for `distance` and `pair` (the pair of two closest points). <ide> <del>**References and further readings:** <add>For example `getClosestPair` with input array `points`: <add> <add>```js <add>const points = [ <add> new Point(1, 2), <add> new Point(3, 3), <add> new Point(2, 2) <add>]; <add>``` <add> <add>Would return: <add> <add>```js <add>{ <add> distance: 1, <add> pair: [ <add> { <add> x: 1, <add> y: 2 <add> }, <add> { <add> x: 2, <add> y: 2 <add> } <add> ] <add>} <add>``` <add> <add>**Note:** Sort the `pair` array by their `x` values in incrementing order. <ide> <del><ul> <del> <li><a href='https://en.wikipedia.org/wiki/Closest pair of points problem' title='wp: Closest pair of points problem' target='_blank'>Closest pair of points problem</a></li> <del> <li><a href='https://www.cs.mcgill.ca/~cs251/ClosestPair/ClosestPairDQ.html' target='_blank'>Closest Pair (McGill)</a></li> <del> <li><a href='https://www.cs.ucsb.edu/~suri/cs235/ClosestPair.pdf' target='_blank'>Closest Pair (UCSB)</a></li> <del> <li><a href='https://classes.cec.wustl.edu/~cse241/handouts/closestpair.pdf' target='_blank'>Closest pair (WUStL)</a></li> <del> </ul> <ide> <ide> # --hints-- <ide> <ide> For the input, expect the argument to be an array of objects (points) with `x` a <ide> assert(typeof getClosestPair === 'function'); <ide> ``` <ide> <del>Distance should be the following. <add>`getClosestPair(points1).distance` should be `0.0894096443343775`. <ide> <ide> ```js <ide> assert.equal(getClosestPair(points1).distance, answer1.distance); <ide> ``` <ide> <del>Points should be the following. <add>`getClosestPair(points1).pair` should be `[ { x: 7.46489, y: 4.6268 }, { x: 7.46911, y: 4.71611 } ]`. <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <del>Distance should be the following. <add>`getClosestPair(points2).distance` should be `65.06919393998976`. <ide> <ide> ```js <ide> assert.equal(getClosestPair(points2).distance, answer2.distance); <ide> ``` <ide> <del>Points should be the following. <add>`getClosestPair(points2).pair` should be `[ { x: 37134, y: 1963 }, { x: 37181, y: 2008 } ]`. <ide> <ide> ```js <ide> assert.deepEqual( <ide> assert.deepEqual( <ide> ); <ide> ``` <ide> <add>`getClosestPair(points3).distance` should be `6754.625082119658`. <add> <add>```js <add>assert.equal(getClosestPair(points3).distance, answer3.distance); <add>``` <add> <add>`getClosestPair(points3).pair` should be `[ { x: 46817, y: 64975 }, { x: 48953, y: 58567 } ]`. <add> <add>```js <add>assert.deepEqual( <add> JSON.parse(JSON.stringify(getClosestPair(points3))).pair, <add> answer3.pair <add>); <add>``` <add> <ide> # --seed-- <ide> <ide> ## --after-user-code-- <ide> const points1 = [ <ide> new Point(1.45428, 0.087596) <ide> ]; <ide> <del>const points2 = [ <del> new Point(37100, 13118), <del> new Point(37134, 1963), <del> new Point(37181, 2008), <del> new Point(37276, 21611), <del> new Point(37307, 9320) <del>]; <del> <ide> const answer1 = { <ide> distance: 0.0894096443343775, <ide> pair: [ <ide> const answer1 = { <ide> ] <ide> }; <ide> <add>const points2 = [ <add> new Point(37100, 13118), <add> new Point(37134, 1963), <add> new Point(37181, 2008), <add> new Point(37276, 21611), <add> new Point(37307, 9320) <add>]; <add> <ide> const answer2 = { <ide> distance: 65.06919393998976, <ide> pair: [ <ide> const answer2 = { <ide> ] <ide> }; <ide> <del>const benchmarkPoints = [ <del> new Point(16909, 54699), <add>const points3 = [ <add> new Point(16910, 54699), <ide> new Point(14773, 61107), <ide> new Point(95547, 45344), <ide> new Point(95951, 17573), <ide> const benchmarkPoints = [ <ide> new Point(70721, 66707), <ide> new Point(31863, 9837), <ide> new Point(49358, 30795), <del> new Point(13041, 39745), <add> new Point(13041, 39744), <ide> new Point(59635, 26523), <ide> new Point(25859, 1292), <ide> new Point(1551, 53890), <ide> const benchmarkPoints = [ <ide> new Point(51090, 52158), <ide> new Point(48953, 58567) <ide> ]; <add> <add>const answer3 = { <add> distance: 6754.625082119658, <add> pair: [ <add> { <add> x: 46817, <add> y: 64975 <add> }, <add> { <add> x: 48953, <add> y: 58567 <add> } <add> ] <add>} <ide> ``` <ide> <ide> ## --seed-contents-- <ide> const closestPair = function _closestPair(Px, Py) { <ide> <ide> return { <ide> distance: minDelta, <del> pair: closestPair <add> pair: closestPair.sort((pointA, pointB) => pointA.x - pointB.x) <ide> }; <ide> }; <ide>
1
Ruby
Ruby
avoid extra delegation to `lazyattributehash`
0adcec49541aac069600202ed5f83c8ef6f2197e
<ide><path>activemodel/lib/active_model/attribute_set.rb <ide> def initialize(attributes) <ide> end <ide> <ide> def [](name) <del> attributes[name] || Attribute.null(name) <add> @attributes[name] || default_attribute(name) <ide> end <ide> <ide> def []=(name, value) <del> attributes[name] = value <add> @attributes[name] = value <ide> end <ide> <ide> def values_before_type_cast <ide> attributes.transform_values(&:value_before_type_cast) <ide> end <ide> <ide> def to_hash <del> initialized_attributes.transform_values(&:value) <add> keys.index_with { |name| self[name].value } <ide> end <del> alias_method :to_h, :to_hash <add> alias :to_h :to_hash <ide> <ide> def key?(name) <ide> attributes.key?(name) && self[name].initialized? <ide> def fetch_value(name, &block) <ide> end <ide> <ide> def write_from_database(name, value) <del> attributes[name] = self[name].with_value_from_database(value) <add> @attributes[name] = self[name].with_value_from_database(value) <ide> end <ide> <ide> def write_from_user(name, value) <ide> raise FrozenError, "can't modify frozen attributes" if frozen? <del> attributes[name] = self[name].with_value_from_user(value) <add> @attributes[name] = self[name].with_value_from_user(value) <ide> value <ide> end <ide> <ide> def write_cast_value(name, value) <del> attributes[name] = self[name].with_cast_value(value) <add> @attributes[name] = self[name].with_cast_value(value) <ide> value <ide> end <ide> <ide> def freeze <del> @attributes.freeze <add> attributes.freeze <ide> super <ide> end <ide> <ide> def deep_dup <del> self.class.allocate.tap do |copy| <del> copy.instance_variable_set(:@attributes, attributes.deep_dup) <del> end <add> AttributeSet.new(attributes.deep_dup) <ide> end <ide> <ide> def initialize_dup(_) <del> @attributes = attributes.dup <add> @attributes = @attributes.dup <ide> super <ide> end <ide> <ide> def initialize_clone(_) <del> @attributes = attributes.clone <add> @attributes = @attributes.clone <ide> super <ide> end <ide> <ide> def reset(key) <ide> end <ide> <ide> def accessed <del> attributes.select { |_, attr| attr.has_been_read? }.keys <add> attributes.each_key.select { |name| self[name].has_been_read? } <ide> end <ide> <ide> def map(&block) <ide> def ==(other) <ide> attr_reader :attributes <ide> <ide> private <del> def initialized_attributes <del> attributes.select { |_, attr| attr.initialized? } <add> def default_attribute(name) <add> Attribute.null(name) <ide> end <ide> end <ide> end <ide><path>activemodel/lib/active_model/attribute_set/builder.rb <ide> def initialize(types, default_attributes = {}) <ide> end <ide> <ide> def build_from_database(values = {}, additional_types = {}) <del> attributes = LazyAttributeHash.new(types, values, additional_types, default_attributes) <del> LazyAttributeSet.new(attributes) <add> LazyAttributeSet.new(values, types, additional_types, default_attributes) <ide> end <ide> end <ide> end <ide> <ide> class LazyAttributeSet < AttributeSet # :nodoc: <del> def fetch_value(name, &block) <del> attributes.fetch_value(name, &block) <del> end <del> end <del> <del> class LazyAttributeHash # :nodoc: <del> delegate :transform_values, :each_key, :each_value, :fetch, :except, to: :materialize <del> <del> def initialize(types, values, additional_types, default_attributes, delegate_hash = {}) <del> @types = types <add> def initialize(values, types, additional_types, default_attributes, attributes = {}) <add> super(attributes) <ide> @values = values <add> @types = types <ide> @additional_types = additional_types <ide> @default_attributes = default_attributes <del> @delegate_hash = delegate_hash <ide> @casted_values = {} <ide> @materialized = false <ide> end <ide> <del> def key?(key) <del> delegate_hash.key?(key) || values.key?(key) || types.key?(key) <add> def key?(name) <add> (values.key?(name) || types.key?(name) || @attributes.key?(name)) && self[name].initialized? <ide> end <ide> <del> def [](key) <del> delegate_hash[key] || assign_default_value(key) <del> end <del> <del> def []=(key, value) <del> delegate_hash[key] = value <add> def keys <add> keys = values.keys | types.keys | @attributes.keys <add> keys.keep_if { |name| self[name].initialized? } <ide> end <ide> <ide> def fetch_value(name, &block) <del> if attr = delegate_hash[name] <add> if attr = @attributes[name] <ide> return attr.value(&block) <ide> end <ide> <ide> def fetch_value(name, &block) <ide> type = additional_types.fetch(name, types[name]) <ide> @casted_values[name] = type.deserialize(value) <ide> else <del> attr = assign_default_value(name, value_present, value) || Attribute.null(name) <add> attr = default_attribute(name, value_present, value) <ide> attr.value(&block) <ide> end <ide> end <ide> end <ide> <add> protected <add> def attributes <add> unless @materialized <add> values.each_key { |key| self[key] } <add> types.each_key { |key| self[key] } <add> @materialized = true <add> end <add> @attributes <add> end <add> <add> private <add> attr_reader :values, :types, :additional_types, :default_attributes <add> <add> def default_attribute( <add> name, <add> value_present = true, <add> value = values.fetch(name) { value_present = false } <add> ) <add> type = additional_types.fetch(name, types[name]) <add> <add> if value_present <add> @attributes[name] = Attribute.from_database(name, value, type, @casted_values[name]) <add> elsif types.key?(name) <add> if attr = default_attributes[name] <add> @attributes[name] = attr.dup <add> else <add> @attributes[name] = Attribute.uninitialized(name, type) <add> end <add> else <add> Attribute.null(name) <add> end <add> end <add> end <add> <add> class LazyAttributeHash # :nodoc: <add> delegate :transform_values, :each_value, :fetch, :except, to: :materialize <add> <add> def initialize(types, values, additional_types, default_attributes, delegate_hash = {}) <add> @types = types <add> @values = values <add> @additional_types = additional_types <add> @materialized = false <add> @delegate_hash = delegate_hash <add> @default_attributes = default_attributes <add> end <add> <add> def key?(key) <add> delegate_hash.key?(key) || values.key?(key) || types.key?(key) <add> end <add> <add> def [](key) <add> delegate_hash[key] || assign_default_value(key) <add> end <add> <add> def []=(key, value) <add> delegate_hash[key] = value <add> end <add> <ide> def deep_dup <ide> dup.tap do |copy| <ide> copy.instance_variable_set(:@delegate_hash, delegate_hash.transform_values(&:dup)) <ide> def initialize_dup(_) <ide> super <ide> end <ide> <del> def select <add> def each_key(&block) <ide> keys = types.keys | values.keys | delegate_hash.keys <del> keys.each_with_object({}) do |key, hash| <del> attribute = self[key] <del> if yield(key, attribute) <del> hash[key] = attribute <del> end <del> end <add> keys.each(&block) <ide> end <ide> <ide> def ==(other) <ide> def materialize <ide> private <ide> attr_reader :types, :values, :additional_types, :delegate_hash, :default_attributes <ide> <del> def assign_default_value( <del> name, <del> value_present = true, <del> value = values.fetch(name) { value_present = false } <del> ) <add> def assign_default_value(name) <ide> type = additional_types.fetch(name, types[name]) <add> value_present = true <add> value = values.fetch(name) { value_present = false } <ide> <ide> if value_present <del> delegate_hash[name] = Attribute.from_database(name, value, type, @casted_values[name]) <add> delegate_hash[name] = Attribute.from_database(name, value, type) <ide> elsif types.key?(name) <ide> attr = default_attributes[name] <ide> if attr <ide><path>activemodel/test/cases/attribute_set_test.rb <ide> def assert_valid_value(*) <ide> <ide> test "marshalling dump/load legacy materialized attribute hash" do <ide> builder = AttributeSet::Builder.new(foo: Type::String.new) <add> <add> def builder.build_from_database(values = {}, additional_types = {}) <add> attributes = LazyAttributeHash.new(types, values, additional_types, default_attributes) <add> AttributeSet.new(attributes) <add> end <add> <ide> attributes = builder.build_from_database(foo: "1") <ide> <ide> attributes.instance_variable_get(:@attributes).instance_eval do
3
Python
Python
fix syntax error in the docstrings
d1a5ca16abaf1b64b6205b8facfb2e0d191ec2d3
<ide><path>libcloud/compute/types.py <ide> class Provider(object): <ide> @cvar OPSOURCE: Opsource Cloud <ide> @cvar NINEFOLD: Ninefold <ide> @cvar TERREMARK: Terremark <del> @cvar: EC2_US_WEST_OREGON: Amazon AWS US West 2 (Oregon) <add> @cvar EC2_US_WEST_OREGON: Amazon AWS US West 2 (Oregon) <ide> @cvar CLOUDSTACK: CloudStack <ide> @cvar CLOUDSIGMA_US: CloudSigma US Las Vegas <ide> @cvar RACKSPACE_NOVA_BETA: Rackspace Nova Private Beta (ORD) <ide><path>libcloud/storage/types.py <ide> class Provider(object): <ide> @cvar S3_AP_NORTHEAST_HOST: Amazon S3 Asia South East (Tokyo) <ide> @cvar NINEFOLD: Ninefold <ide> @cvar GOOGLE_STORAGE Google Storage <del> @cvar: S3_US_WEST_OREGON: Amazon S3 US West 2 (Oregon) <add> @cvar S3_US_WEST_OREGON: Amazon S3 US West 2 (Oregon) <ide> @cvar NIMBUS: Nimbus.io driver <ide> """ <ide> DUMMY = 0
2
Text
Text
fix typos in materials article
eb6e93e132a47998171c5e2caf9b03ea001fcf15
<ide><path>threejs/lessons/threejs-materials.md <ide> This article is part of a series of articles about three.js. The <ide> first article is [three.js fundamentals](threejs-fundamentals.html). If <ide> you haven't read that yet and you're new to three.js you might want to <ide> consider starting there. <del> <del>Three.js provides several types of materials. <add> <add>Three.js provides several types of materials. <ide> They define how objects will appear in the scene. <ide> Which materials you use really depends on what you're trying to <ide> accomplish. <ide> note that properties of type `THREE.Color` have multiple ways to be set. <ide> <ide> ```js <ide> material.color.set(0x00FFFF); // same as CSS's #RRGGBB style <del>material.color.set(cssString); // any CSS color, eg 'purple', '#F32', <add>material.color.set(cssString); // any CSS color, eg 'purple', '#F32', <ide> // 'rgb(255, 127, 64)', <ide> // 'hsl(180, 50%, 25%)' <ide> material.color.set(someColor) // some other THREE.Color <ide> material.color.setHSL(h, s, l) // where h, s, and l are 0 to 1 <del>material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1 <add>material.color.setRGB(r, g, b) // where r, g, and b are 0 to 1 <ide> ``` <ide> <ide> And at creation time you can pass either a hex number or a CSS string <ide> const m5 = new THREE.MeshBasicMaterial({color: 'hsl(0,100%,50%)'); // red <ide> <ide> So let's go over three.js's set of materials. <ide> <del>The `MeshBasicMaterial` is not affected by lights. <add>The `MeshBasicMaterial` is not affected by lights. <ide> The `MeshLambertMaterial` computes lighting only at the vertices vs the `MeshPhongMaterial` which computes lighting at every pixel. The `MeshPhongMaterial` <ide> also supports specular highlights. <ide> <ide> The `shininess` setting of the `MeshPhongMaterial` determines the *shininess* of <ide> </div> <ide> </div> <ide> <del>Note that setting the `emissive` property to a color on either a <add>Note that setting the `emissive` property to a color on either a <ide> `MeshLambertMaterial` or a `MeshPhongMaterial` and setting the `color` to black <ide> (and `shininess` to 0 for phong) ends up looking just like the `MeshBasicMaterial`. <ide> <ide> don't need the extra features then use the simplest material. If you don't <ide> need the lighting and the specular highlight then use the `MeshBasicMaterial`. <ide> <ide> The `MeshToonMaterial` is similar to the `MeshPhongMaterial` <del>with one big difference. Rather than shading smoothly it uses a gradient map <add>with one big difference. Rather than shading smoothly it uses a gradient map <ide> (an X by 1 texture) to decide how to shade. The default uses a gradient map <ide> that is 70% brightness for the first 70% and 100% after but you can supply your <ide> own gradient map. This ends up giving a 2 tone look that looks like a cartoon. <ide> The first one is `MeshStandardMaterial`. The biggest difference between <ide> settings `roughness` and `metalness`. <ide> <ide> At a basic level [`roughness`](MeshStandardMaterial.roughness) is the opposite <del>of `shininess`. Something that has a high roughness, like a baseball doesn't <del>have hard reflections where as something that's not rough, like a billiard ball <add>of `shininess`. Something that has a high roughness, like a baseball doesn't <add>have hard reflections whereas something that's not rough, like a billiard ball, <ide> is very shiny. Roughness goes from 0 to 1. <ide> <ide> The other setting, [`metalness`](MeshStandardMaterial.metalness), says <ide> across and `metalness` from 0 to 1 down. <ide> <div data-diagram="MeshStandardMaterial" style="min-height: 400px"></div> <ide> <ide> The `MeshPhysicalMaterial` is same as the `MeshStandardMaterial` but it <del>adds a `clearCoat` parameter that goes from 0 to 1 for how much to <add>adds a `clearCoat` parameter that goes from 0 to 1 for how much to <ide> apply a clearcoat gloss layer and a `clearCoatRoughness` parameter <ide> that specifies how rough the gloss layer is. <ide> <ide> Here's the same grid of `roughness` by `metalness` as above but with <ide> <div data-diagram="MeshPhysicalMaterial" style="min-height: 400px"></div> <ide> <ide> The various standard materials progress from fastest to slowest <del>`MeshBasicMaterial` ➡ `MeshLambertMaterial` ➡ `MeshPhongMaterial` ➡ <add>`MeshBasicMaterial` ➡ `MeshLambertMaterial` ➡ `MeshPhongMaterial` ➡ <ide> `MeshStandardMaterial` ➡ `MeshPhysicalMaterial`. The slower materials <ide> can make more realistic looking scenes but you might need to design <ide> your code to use the faster materials on low powered or mobile machines. <ide> <ide> There are 3 materials that have special uses. `ShadowMaterial` <ide> is used to get the data created from shadows. We haven't <ide> covered shadows yet. When we do we'll use this material <del>to take a peak at what's happening behind the scenes. <add>to take a peek at what's happening behind the scenes. <ide> <ide> The `MeshDepthMaterial` renders the depth of each pixel where <ide> pixels at negative [`near`](PerspectiveCamera.near) of the camera are 0 and negative [`far`](PerspectiveCamera.far) are 1. Certain special effects can use this data which we'll <ide> get into at another time. <ide> </div> <ide> <ide> The `MeshNormalMaterial` will show you the *normals* of geometry. <del>*Normals* are the direction a particular triangle or pixel faces. <del>`MeshNormalMaterial` draws the view space normals. (the normals relative to the camera). <add>*Normals* are the direction a particular triangle or pixel faces. <add>`MeshNormalMaterial` draws the view space normals (the normals relative to the camera). <ide> <span class="color:red;">x is red</span>, <ide> <span class="color:green;">y is green</span>, and <ide> <span class="color:blue;">z is blue</span> so things facing <ide> to the right will be red, up will be green, and toward the screen will be blue. <ide> </div> <ide> </div> <ide> <del>`ShaderMaterial` is for making custom materials using three.js shader <add>`ShaderMaterial` is for making custom materials using the three.js shader <ide> system. `RawShaderMaterial` is for making entirely custom shaders with <ide> no help from three.js. Both of these topics are large and will be <ide> covered later. <ide> Most materials share a bunch of settings all defined by `Material`. <ide> for all of them but let's go over two of the most commonly used <ide> properties. <ide> <del>[`flatShading`](Material.flatShading): <add>[`flatShading`](Material.flatShading): <ide> whether or not the object looks faceted or smooth. default = `false`. <ide> <ide> <div class="spread"> <ide> Here are 6 planes drawn with `THREE.FrontSide` and `THREE.DoubleSide`. <ide> There's really a lot to consider with materials and we actually still <ide> have a bunch more to go. In particular we've mostly ignored textures <ide> which open up a whole slew of options. Before we cover textures though <del>we need to take a break and cover <add>we need to take a break and cover <ide> [setting up your development environment](threejs-setup.html) <ide> <ide> <div class="threejs_bottombar"> <ide> <h3>material.needsUpdate</h3> <ide> <p> <ide> This topic rarely affects most three.js apps but just as an FYI... <del>Three.js applies material settings when a material is used where "used" <add>Three.js applies material settings when a material is used where "used" <ide> means "something is rendered that uses the material". Some material settings are <ide> only applied once as changing them requires lots of work by three.js. <ide> In those cases you need to set <code>material.needsUpdate = true</code> to tell <ide> using the material are: <ide> </p> <ide> <ul> <ide> <li><code>flatShading</code></li> <del> <li>adding or removing a texture. <add> <li>adding or removing a texture <ide> <p> <del> Changing a texture is ok, but if want switch from using no texture <del> to using a texture or from using a texture to using no texture <add> Changing a texture is ok, but if want to switch from using no texture <add> to using a texture or from using a texture to using no texture <ide> then you need to set <code>needsUpdate = true</code>. <ide> </p> <ide> <p>In the case of going from texture to no-texture it is often
1
Go
Go
fix data race in controller sandboxes
092437ad0e882ac26f48dff75ebb1e3ef183037a
<ide><path>libnetwork/libnetwork_test.go <ide> func createGlobalInstance(t *testing.T) { <ide> "AllowNonDefaultBridge": true, <ide> }, <ide> } <del> net, err := createTestNetwork(bridgeNetType, "network", netOption) <add> <add> net1, err := controller.NetworkByName("testhost") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> net2, err := createTestNetwork("bridge", "network2", netOption) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> _, err = net1.CreateEndpoint("pep1") <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> _, err = net2.CreateEndpoint("pep2") <ide> if err != nil { <del> t.Fatal("new network") <add> t.Fatal(err) <ide> } <ide> <del> _, err = net.CreateEndpoint("ep1") <add> _, err = net2.CreateEndpoint("pep3") <ide> if err != nil { <del> t.Fatal("createendpoint") <add> t.Fatal(err) <ide> } <ide> } <ide> <ide> func debugf(format string, a ...interface{}) (int, error) { <ide> <ide> func parallelJoin(t *testing.T, ep libnetwork.Endpoint, thrNumber int) { <ide> debugf("J%d.", thrNumber) <del> err := ep.Join("racing_container") <add> var err error <add> if thrNumber == first { <add> err = ep.Join(fmt.Sprintf("%drace", thrNumber), libnetwork.JoinOptionUseDefaultSandbox()) <add> } else { <add> err = ep.Join(fmt.Sprintf("%drace", thrNumber)) <add> } <add> <ide> runtime.LockOSThread() <ide> if err != nil { <ide> if _, ok := err.(libnetwork.ErrNoContainer); !ok { <ide> if _, ok := err.(libnetwork.ErrInvalidJoin); !ok { <del> t.Fatal(err) <add> t.Fatalf("thread %d: %v", thrNumber, err) <ide> } <ide> } <ide> debugf("JE%d(%v).", thrNumber, err) <ide> func parallelJoin(t *testing.T, ep libnetwork.Endpoint, thrNumber int) { <ide> <ide> func parallelLeave(t *testing.T, ep libnetwork.Endpoint, thrNumber int) { <ide> debugf("L%d.", thrNumber) <del> err := ep.Leave("racing_container") <add> var err error <add> if thrNumber == first { <add> err = ep.Leave(fmt.Sprintf("%drace", thrNumber)) <add> } else { <add> err = controller.LeaveAll(fmt.Sprintf("%drace", thrNumber)) <add> } <add> <ide> runtime.LockOSThread() <ide> if err != nil { <ide> if _, ok := err.(libnetwork.ErrNoContainer); !ok { <ide> if _, ok := err.(libnetwork.ErrInvalidJoin); !ok { <del> t.Fatal(err) <add> t.Fatalf("thread %d: %v", thrNumber, err) <ide> } <ide> } <ide> debugf("LE%d(%v).", thrNumber, err) <ide> func runParallelTests(t *testing.T, thrNumber int) { <ide> } <ide> defer netns.Set(origns) <ide> <del> net, err := controller.NetworkByName("network") <add> net1, err := controller.NetworkByName("testhost") <add> if err != nil { <add> t.Fatal(err) <add> } <add> if net1 == nil { <add> t.Fatal("Could not find network1") <add> } <add> <add> net2, err := controller.NetworkByName("network2") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <del> if net == nil { <del> t.Fatal("Could not find network") <add> if net2 == nil { <add> t.Fatal("Could not find network2") <add> } <add> <add> epName := fmt.Sprintf("pep%d", thrNumber) <add> <add> //var err error <add> var ep libnetwork.Endpoint <add> <add> if thrNumber == first { <add> ep, err = net1.EndpointByName(epName) <add> } else { <add> ep, err = net2.EndpointByName(epName) <ide> } <ide> <del> ep, err := net.EndpointByName("ep1") <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide> func runParallelTests(t *testing.T, thrNumber int) { <ide> <ide> debugf("\n") <ide> <add> err = ep.Delete() <add> if err != nil { <add> t.Fatal(err) <add> } <add> <ide> if thrNumber == first { <ide> for thrdone := range done { <ide> select { <ide> func runParallelTests(t *testing.T, thrNumber int) { <ide> } <ide> <ide> testns.Close() <del> err = ep.Delete() <del> if err != nil { <del> t.Fatal(err) <del> } <ide> <del> if err := net.Delete(); err != nil { <add> if err := net2.Delete(); err != nil { <ide> t.Fatal(err) <ide> } <ide> } <ide><path>libnetwork/sandboxdata.go <ide> func (s *sandboxData) rmEndpoint(ep *endpoint) { <ide> } <ide> } <ide> <del> // We don't check if s.endpoints is empty here because <del> // it should never be empty during a rmEndpoint call and <del> // if it is we will rightfully panic here <ide> s.Lock() <add> if len(s.endpoints) == 0 { <add> // s.endpoints should never be empty and this is unexpected error condition <add> // We log an error message to note this down for debugging purposes. <add> logrus.Errorf("No endpoints in sandbox while trying to remove endpoint %s", ep.Name()) <add> s.Unlock() <add> return <add> } <add> <ide> highEpBefore := s.endpoints[0] <ide> var ( <ide> i int <ide> func (c *controller) LeaveAll(id string) error { <ide> } <ide> <ide> sData.sandbox().Destroy() <add> <add> c.Lock() <ide> delete(c.sandboxes, sandbox.GenerateKey(id)) <add> c.Unlock() <ide> <ide> return nil <ide> }
2
Text
Text
fix typos in the stream doc
58a241d53790aee5dd6327543fc9849bd21fb9a7
<ide><path>doc/api/stream.md <ide> There are four fundamental stream types within Node.js: <ide> * [Readable][] - streams from which data can be read (for example <ide> [`fs.createReadStream()`][]). <ide> * [Writable][] - streams to which data can be written (for example <del> [`fs.createWriteStream`][]). <add> [`fs.createWriteStream()`][]). <ide> * [Duplex][] - streams that are both Readable and Writable (for example <ide> [`net.Socket`][]). <ide> * [Transform][] - Duplex streams that can modify or transform the data as it <ide> queue until it is consumed. <ide> Once the total size of the internal read buffer reaches the threshold specified <ide> by `highWaterMark`, the stream will temporarily stop reading data from the <ide> underlying resource until the data currently buffered can be consumed (that is, <del>the stream will stop calling the internal `readable.\_read()` method that is <add>the stream will stop calling the internal `readable._read()` method that is <ide> used to fill the read buffer). <ide> <ide> Data is buffered in Writable streams when the <ide> The buffered data will be flushed when either the [`stream.uncork()`][] or <ide> The primary intent of `writable.cork()` is to avoid a situation where writing <ide> many small chunks of data to a stream do not cause an backup in the internal <ide> buffer that would have an adverse impact on performance. In such situations, <del>implementations that implement the `writable.\_writev()` method can perform <add>implementations that implement the `writable._writev()` method can perform <ide> buffered writes in a more optimized manner. <ide> <ide> ##### writable.end([chunk][, encoding][, callback]) <ide> following example: <ide> <ide> ```js <ide> getReadableStreamSomehow() <del> .resume(); <add> .resume() <ide> .on('end', () => { <ide> console.log('Reached the end, but did not read anything.'); <ide> }); <ide> const myWritable = new Writable({ <ide> The `stream.Writable` class is extended to implement a [Writable][] stream. <ide> <ide> Custom Writable streams *must* call the `new stream.Writable([options])` <del>constructor and implement the `writable.\_write()` method. The <del>`writable.\_writev()` method *may* also be implemented. <add>constructor and implement the `writable._write()` method. The <add>`writable._writev()` method *may* also be implemented. <ide> <ide> #### Constructor: new stream.Writable([options]) <ide> <ide> All Writable stream implementations must provide a <ide> resource. <ide> <ide> *Note*: [Transform][] streams provide their own implementation of the <del>[`writable._write()`]. <add>[`writable._write()`][stream-_write]. <ide> <ide> *Note*: **This function MUST NOT be called by application code directly.** It <ide> should be implemented by child classes, and called only by the internal Writable <ide> successfully or failed with an error. The first argument passed to the <ide> write succeeded. <ide> <ide> It is important to note that all calls to `writable.write()` that occur between <del>the time `writable.\_write()` is called and the `callback` is called will cause <add>the time `writable._write()` is called and the `callback` is called will cause <ide> the written data to be buffered. Once the `callback` is invoked, the stream will <ide> emit a `'drain'` event. If a stream implementation is capable of processing <del>multiple chunks of data at once, the `writable.\_writev()` method should be <add>multiple chunks of data at once, the `writable._writev()` method should be <ide> implemented. <ide> <ide> If the `decodeStrings` property is set in the constructor options, then <ide> data encodings. If the `decodeStrings` property is explicitly set to `false`, <ide> the `encoding` argument can be safely ignored, and `chunk` will always be a <ide> `Buffer`. <ide> <del>The `writable.\_write()` method is prefixed with an underscore because it is <add>The `writable._write()` method is prefixed with an underscore because it is <ide> internal to the class that defines it, and should never be called directly by <ide> user programs. <ide> <ide> user programs. <ide> should be implemented by child classes, and called only by the internal Writable <ide> class methods only. <ide> <del>The `writable.\_writev()` method may be implemented in addition to <del>`writable.\_write()` in stream implementations that are capable of processing <add>The `writable._writev()` method may be implemented in addition to <add>`writable._write()` in stream implementations that are capable of processing <ide> multiple chunks of data at once. If implemented, the method will be called with <ide> all chunks of data currently buffered in the write queue. <ide> <del>The `writable.\_writev()` method is prefixed with an underscore because it is <add>The `writable._writev()` method is prefixed with an underscore because it is <ide> internal to the class that defines it, and should never be called directly by <ide> user programs. <ide> <ide> #### Errors While Writing <ide> <ide> It is recommended that errors occurring during the processing of the <del>`writable.\_write()` and `writable.\_writev()` methods are reported by invoking <add>`writable._write()` and `writable._writev()` methods are reported by invoking <ide> the callback and passing the error as the first argument. This will cause an <ide> `'error'` event to be emitted by the Writable. Throwing an Error from within <del>`writable.\_write()` can result in expected and inconsistent behavior depending <add>`writable._write()` can result in expected and inconsistent behavior depending <ide> on how the stream is being used. Using the callback ensures consistent and <ide> predictable handling of errors. <ide> <ide> class MyWritable extends Writable { <ide> The `stream.Readable` class is extended to implement a [Readable][] stream. <ide> <ide> Custom Readable streams *must* call the `new stream.Readable([options])` <del>constructor and implement the `readable.\_read()` method. <add>constructor and implement the `readable._read()` method. <ide> <ide> #### new stream.Readable([options]) <ide> <ide> should be implemented by child classes, and called only by the internal Readable <ide> class methods only. <ide> <ide> All Readable stream implementations must provide an implementation of the <del>`readable.\_read()` method to fetch data from the underlying resource. <add>`readable._read()` method to fetch data from the underlying resource. <ide> <ide> When `readable._read()` is called, if data is available from the resource, the <ide> implementation should begin pushing that data into the read queue using the <ide> much data to fetch. Other implementations may ignore this argument and simply <ide> provide data whenever it becomes available. There is no need to "wait" until <ide> `size` bytes are available before calling [`stream.push(chunk)`][stream-push]. <ide> <del>The `readable.\_read()` method is prefixed with an underscore because it is <add>The `readable._read()` method is prefixed with an underscore because it is <ide> internal to the class that defines it, and should never be called directly by <ide> user programs. <ide> <ide> class SourceWrapper extends Readable { <ide> } <ide> ``` <ide> *Note*: The `readable.push()` method is intended be called only by Readable <del>Implemeters, and only from within the `readable.\_read()` method. <add>Implemeters, and only from within the `readable._read()` method. <ide> <ide> #### Errors While Reading <ide> <ide> It is recommended that errors occurring during the processing of the <del>`readable.\_read()` method are emitted using the `'error'` event rather than <del>being thrown. Throwing an Error from within `readable.\_read()` can result in <add>`readable._read()` method are emitted using the `'error'` event rather than <add>being thrown. Throwing an Error from within `readable._read()` can result in <ide> expected and inconsistent behavior depending on whether the stream is operating <ide> in flowing or paused mode. Using the `'error'` event ensures consistent and <ide> predictable handling of errors. <ide> to extending the `stream.Readable` *and* `stream.Writable` classes). <ide> and parasitically from `stream.Writable`. <ide> <ide> Custom Duplex streams *must* call the `new stream.Duplex([options])` <del>constructor and implement *both* the `readable.\_read()` and <del>`writable.\_write()` methods. <add>constructor and implement *both* the `readable._read()` and <add>`writable._write()` methods. <ide> <ide> #### new stream.Duplex(options) <ide> <ide> that is either much smaller or much larger than its input. <ide> The `stream.Transform` class is extended to implement a [Transform][] stream. <ide> <ide> The `stream.Transform` class prototypically inherits from `stream.Duplex` and <del>implements its own versions of the `writable.\_write()` and `readable.\_read()` <add>implements its own versions of the `writable._write()` and `readable._read()` <ide> methods. Custom Transform implementations *must* implement the <del>[`transform.\_transform()`][stream-_transform] method and *may* also implement <del>the [`transform.\_flush()`][stream-._flush] method. <add>[`transform._transform()`][stream-_transform] method and *may* also implement <add>the [`transform._flush()`][stream-_flush] method. <ide> <ide> *Note*: Care must be taken when using Transform streams in that data written <ide> to the stream can cause the Writable side of the stream to become paused if <ide> store an amount of internal state used to optimally compress the output. When <ide> the stream ends, however, that additional data needs to be flushed so that the <ide> compressed data will be complete. <ide> <del>Custom [Transform][] implementations *may* implement the `transform.\_flush()` <add>Custom [Transform][] implementations *may* implement the `transform._flush()` <ide> method. This will be called when there is no more written data to be consumed, <ide> but before the [`'end'`][] event is emitted signaling the end of the <ide> [Readable][] stream. <ide> <del>Within the `transform.\_flush()` implementation, the `readable.push()` method <add>Within the `transform._flush()` implementation, the `readable.push()` method <ide> may be called zero or more times, as appropriate. The `callback` function must <ide> be called when the flush operation is complete. <ide> <del>The `transform.\_flush()` method is prefixed with an underscore because it is <add>The `transform._flush()` method is prefixed with an underscore because it is <ide> internal to the class that defines it, and should never be called directly by <ide> user programs. <ide> <ide> should be implemented by child classes, and called only by the internal Readable <ide> class methods only. <ide> <ide> All Transform stream implementations must provide a `_transform()` <del>method to accept input and produce output. The `transform.\_transform()` <add>method to accept input and produce output. The `transform._transform()` <ide> implementation handles the bytes being written, computes an output, then passes <ide> that output off to the readable portion using the `readable.push()` method. <ide> <ide> transform.prototype._transform = function (data, encoding, callback) { <ide> }; <ide> ``` <ide> <del>The `transform.\_transform()` method is prefixed with an underscore because it <add>The `transform._transform()` method is prefixed with an underscore because it <ide> is internal to the class that defines it, and should never be called directly by <ide> user programs. <ide> <ide> net.createServer((socket) => { <ide> <ide> In addition to new Readable streams switching into flowing mode, <ide> pre-v0.10 style streams can be wrapped in a Readable class using the <del>[`readable.wrap()`][] method. <add>[`readable.wrap()`][`stream.wrap()`] method. <ide> <ide> <ide> ### `readable.read(0)`
1
Javascript
Javascript
remove unused error code in module_job
8fa640e2db60e74d24b15de95f51fd9b55f5e793
<ide><path>lib/internal/modules/esm/module_job.js <ide> class ModuleJob { <ide> // `moduleProvider` is a function <ide> constructor(loader, url, moduleProvider, isMain) { <ide> this.loader = loader; <del> this.error = null; <del> this.hadError = false; <ide> this.isMain = isMain; <ide> <ide> // This is a Promise<{ module, reflect }>, whose fields will be copied <ide> class ModuleJob { <ide> const dependencyJobs = await moduleJob.linked; <ide> return Promise.all(dependencyJobs.map(addJobsToDependencyGraph)); <ide> }; <del> try { <del> await addJobsToDependencyGraph(this); <del> } catch (e) { <del> if (!this.hadError) { <del> this.error = e; <del> this.hadError = true; <del> } <del> throw e; <del> } <add> await addJobsToDependencyGraph(this); <ide> try { <ide> if (this.isMain && process._breakFirstLine) { <ide> delete process._breakFirstLine; <ide> class ModuleJob { <ide> <ide> async run() { <ide> const module = await this.instantiate(); <del> try { <del> module.evaluate(-1, false); <del> } catch (e) { <del> this.hadError = true; <del> this.error = e; <del> throw e; <del> } <add> module.evaluate(-1, false); <ide> return module; <ide> } <ide> } <ide><path>test/es-module/test-esm-error-cache.js <add>'use strict'; <add> <add>// Flags: --experimental-modules <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add> <add>common.crashOnUnhandledRejection(); <add> <add>const file = '../../fixtures/syntax/bad_syntax.js'; <add> <add>let error; <add>(async () => { <add> try { <add> await import(file); <add> } catch (e) { <add> assert.strictEqual(e.name, 'SyntaxError'); <add> error = e; <add> } <add> <add> assert(error); <add> <add> try { <add> await import(file); <add> } catch (e) { <add> assert.strictEqual(error, e); <add> } <add>})();
2
Python
Python
remove outdated options and fix formatting
8d3bfb3c046ae7fbaa45714d22e029e13766ecfb
<ide><path>spacy/tests/conftest.py <ide> def pytest_addoption(parser): <ide> parser.addoption("--slow", action="store_true", help="include slow tests") <ide> <ide> <del>def pytest_runtest_setup(item): <del> for opt in ["slow"]: <del> if opt in item.keywords and not item.config.getoption("--%s" % opt): <del> pytest.skip("need --%s option to run" % opt) <del> <del> <ide> @pytest.fixture(scope="module") <ide> def tokenizer(): <ide> return get_lang_class("xx").Defaults.create_tokenizer() <ide> def ru_tokenizer(): <ide> pymorphy = pytest.importorskip("pymorphy2") <ide> return get_lang_class("ru").Defaults.create_tokenizer() <ide> <add> <ide> def pytest_runtest_setup(item): <ide> def getopt(opt): <ide> # When using 'pytest --pyargs spacy' to test an installed copy of <ide> def getopt(opt): <ide> # options weren't given. <ide> return item.config.getoption("--%s" % opt, False) <ide> <del> for opt in ['models', 'vectors', 'slow']: <add> for opt in ["slow"]: <ide> if opt in item.keywords and not getopt(opt): <ide> pytest.skip("need --%s option to run" % opt) <del> <del> # Check if test is marked with models and has arguments set, i.e. specific <del> # language. If so, skip test if flag not set. <del> if item.get_marker('models'): <del> for arg in item.get_marker('models').args: <del> if not getopt(arg) and not getopt("all"): <del> pytest.skip("need --%s or --all option to run" % arg)
1
Javascript
Javascript
use more primordials in shared validators
053874939a6015b91264a3a7c80b0d728ffff262
<ide><path>lib/internal/validators.js <ide> <ide> const { <ide> ArrayIsArray, <add> ArrayPrototypeIncludes, <add> ArrayPrototypeJoin, <add> ArrayPrototypeMap, <ide> NumberIsInteger, <ide> NumberMAX_SAFE_INTEGER, <ide> NumberMIN_SAFE_INTEGER, <ide> NumberParseInt, <add> RegExpPrototypeTest, <ide> String, <add> StringPrototypeToUpperCase, <add> StringPrototypeTrim, <ide> } = primordials; <ide> <ide> const { <ide> function parseFileMode(value, name, def) { <ide> } <ide> <ide> if (typeof value === 'string') { <del> if (!octalReg.test(value)) { <add> if (!RegExpPrototypeTest(octalReg, value)) { <ide> throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc); <ide> } <ide> return NumberParseInt(value, 8); <ide> function validateNumber(value, name) { <ide> } <ide> <ide> const validateOneOf = hideStackFrames((value, name, oneOf) => { <del> if (!oneOf.includes(value)) { <del> const allowed = oneOf <del> .map((v) => (typeof v === 'string' ? `'${v}'` : String(v))) <del> .join(', '); <add> if (!ArrayPrototypeIncludes(oneOf, value)) { <add> const allowed = ArrayPrototypeJoin( <add> ArrayPrototypeMap(oneOf, (v) => <add> (typeof v === 'string' ? `'${v}'` : String(v))), <add> ', '); <ide> const reason = 'must be one of: ' + allowed; <ide> throw new ERR_INVALID_ARG_VALUE(name, value, reason); <ide> } <ide> function validateSignalName(signal, name = 'signal') { <ide> throw new ERR_INVALID_ARG_TYPE(name, 'string', signal); <ide> <ide> if (signals[signal] === undefined) { <del> if (signals[signal.toUpperCase()] !== undefined) { <add> if (signals[StringPrototypeToUpperCase(signal)] !== undefined) { <ide> throw new ERR_UNKNOWN_SIGNAL(signal + <ide> ' (signals must use all capital letters)'); <ide> } <ide> function validateEncoding(data, encoding) { <ide> // is an integer and that it falls within the legal range of port numbers. <ide> function validatePort(port, name = 'Port', { allowZero = true } = {}) { <ide> if ((typeof port !== 'number' && typeof port !== 'string') || <del> (typeof port === 'string' && port.trim().length === 0) || <add> (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || <ide> +port !== (+port >>> 0) || <ide> port > 0xFFFF || <ide> (port === 0 && !allowZero)) {
1
Javascript
Javascript
use typeof check for getattribute method
075da3091cda170bd8cd5ce47bad1c5b14760232
<ide><path>src/attributes/attr.js <ide> jQuery.extend({ <ide> } <ide> <ide> // Fallback to prop when attributes are not supported <del> if ( !elem.getAttribute ) { <add> if ( typeof elem.getAttribute === "undefined" ) { <ide> return jQuery.prop( elem, name, value ); <ide> } <ide>
1
Text
Text
update api docs for database subtree
722aa69413226963eba69733d6d1d093c006165b
<ide><path>src/Database/README.md <ide> <ide> This library abstracts and provides help with most aspects of dealing with relational <ide> databases such as keeping connections to the server, building queries, <del>filtering possible SQL injections, inspecting and altering schemas and with debugging and <add>preventing SQL injections, inspecting and altering schemas, and with debugging and <ide> profiling queries sent to the database. <ide> <ide> It adopts the API from the native PDO extension in PHP for familiarity, but solves many of the <del>inconsistencies PDO has, while also provides several features that extends PDO capabilities. <add>inconsistencies PDO has, while also providing several features that extend PDO's capabilities. <ide> <del>A distinguishing factor this library has, when compared to similar database connection packages, <add>A distinguishing factor of this library when compared to similar database connection packages, <ide> is that it takes the concept of "data types" to its core. It lets you work with complex PHP objects <ide> or structures that can be passed as query conditions or to be inserted in the database. <ide> <ide> This library is able to work with the following databases: <ide> * SQLite <ide> * Microsoft SQL Server (2008 and above) <ide> <del>The first thing you need to do for using this library is creating a connection object, <del>and before performing any operations with the connection, you need to specify a driver <add>The first thing you need to do when using this library is create a connection object. <add>Before performing any operations with the connection, you need to specify a driver <ide> to use: <ide> <ide> ```php <ide> $connection = new Connection([ <ide> <ide> Drivers are classes responsible for actually executing the commands to the database and <ide> correctly building the SQL according to the database specific dialect. Drivers can also <del>be specified by passing a class name, in that case, include all the connection details <add>be specified by passing a class name. In that case, include all the connection details <ide> directly in the options array: <ide> <ide> ```php <ide> use Cake\Database\Connection; <ide> <ide> $connection = new Connection([ <del> 'driver' => 'Cake\Driver\Sqlite' <add> 'driver' => 'Cake\Database\Driver\Sqlite' <ide> 'database' => '/path/to/file.db' <ide> ]); <ide> ``` <ide> <ide> ### Connection options <ide> <del>This is a list of possible options that can be passed for creating a connection: <add>This is a list of possible options that can be passed when creating a connection: <ide> <ide> * `persistent`: Creates a persistent connection <ide> * `host`: The server host <ide> are: <ide> * timestamp <ide> * uuid <ide> <del>More types can be added dynamically, but it will be explained shortly after. <add>More types can be added dynamically in a bit. <ide> <ide> Statements can be reused by binding new values to the parameters in the query: <ide> <ide> More complex updates, deletes and insert queries can be generated using the `Que <ide> <ide> ## Query Builder <ide> <del>One of the goals of this library is allowing the generation of both simple and complex queries with <add>One of the goals of this library is to allow the generation of both simple and complex queries with <ide> ease. The query builder can be accessed by getting a new instance of a query: <ide> <ide> ```php <ide> $query = $connection->newQuery(); <ide> ``` <ide> <del>### Select <add>### Selecting Fields <ide> <ide> Adding fields to the `SELECT` clause: <ide> <ide> $query->where(['id' => 1]); <ide> <ide> // WHERE id > 2 <ide> $query->where(['id >' => 1]); <del> <del>// WHERE id = 2 <del>$query->where(['id >' => 1]); <ide> ``` <ide> <ide> As you can see you can use any operator by placing it with a space after the field name. <ide> A number of commonly used functions can be created with the func() method: <ide> * `concat()` Concatenate two values together. The arguments are treated as bound parameters unless marked as literal. <ide> * `coalesce()` Coalesce values. The arguments are treated as bound parameters unless marked as literal. <ide> * `dateDiff()` Get the difference between two dates/times. The arguments are treated as bound parameters unless marked as literal. <del>* `now()` Take either ‘time’ or ‘date’ as an argument allowing you to get either the current time, or current date. <add>* `now()` Take either 'time' or 'date' as an argument allowing you to get either the current time, or current date. <ide> <ide> When providing arguments for SQL functions, there are two kinds of parameters you can use, literal arguments and bound parameters. Literal <ide> parameters allow you to reference columns or other SQL literals. Bound parameters can be used to safely add user data to SQL functions.
1
PHP
PHP
code formatting issues
e064596297bd045650e8981c4114a94ceacafe97
<ide><path>src/Illuminate/Cache/RateLimiter.php <ide> public function __construct(Cache $cache) <ide> */ <ide> public function tooManyAttempts($key, $maxAttempts, $decayMinutes = 1) <ide> { <del> $attempts = $this->cache->get( <del> $key, 0 <del> ); <del> <ide> $lockedOut = $this->cache->has($key.':lockout'); <ide> <del> if ($attempts > $maxAttempts || $lockedOut) { <add> if ($this->attempts($key) > $maxAttempts || $lockedOut) { <ide> if (! $lockedOut) { <ide> $this->cache->add($key.':lockout', time() + ($decayMinutes * 60), $decayMinutes); <ide> } <ide> public function tooManyAttempts($key, $maxAttempts, $decayMinutes = 1) <ide> return false; <ide> } <ide> <del> /** <del> * Get the number of attempts using key. <del> * <del> * @param string $key <del> * @return mixed <del> */ <del> public function attempts($key) <del> { <del> return $this->cache->get($key, 0); <del> } <del> <ide> /** <ide> * Increment the counter for a given key for a given decay time. <ide> * <ide> public function hit($key, $decayMinutes = 1) <ide> return (int) $this->cache->increment($key); <ide> } <ide> <add> /** <add> * Get the number of attempts for the given key. <add> * <add> * @param string $key <add> * @return mixed <add> */ <add> public function attempts($key) <add> { <add> return $this->cache->get($key, 0); <add> } <add> <ide> /** <ide> * Clear the hits and lockout for the given key. <ide> * <ide><path>src/Illuminate/Foundation/Auth/ThrottlesLogins.php <ide> protected function hasTooManyLoginAttempts(Request $request) <ide> } <ide> <ide> /** <del> * Determine how many retries left. <add> * Increment the login attempts for the user. <ide> * <del> * @param \Illuminate\Http\Request $request <add> * @param \Illuminate\Http\Request $request <ide> * @return int <ide> */ <del> protected function retriesLeft(Request $request) <add> protected function incrementLoginAttempts(Request $request) <ide> { <del> $key = $request->input($this->loginUsername()).$request->ip(); <del> <del> $attempts = app(RateLimiter::class)->attempts($key); <del> <del> return $this->maxLoginAttempts() - $attempts + 1; <add> app(RateLimiter::class)->hit( <add> $request->input($this->loginUsername()).$request->ip() <add> ); <ide> } <ide> <ide> /** <del> * Increment the login attempts for the user. <add> * Determine how many retries are left for the user. <ide> * <ide> * @param \Illuminate\Http\Request $request <ide> * @return int <ide> */ <del> protected function incrementLoginAttempts(Request $request) <add> protected function retriesLeft(Request $request) <ide> { <del> app(RateLimiter::class)->hit( <add> $attempts = app(RateLimiter::class)->attempts( <ide> $request->input($this->loginUsername()).$request->ip() <ide> ); <add> <add> return $this->maxLoginAttempts() - $attempts + 1; <ide> } <ide> <ide> /**
2
Ruby
Ruby
remove unneeded logging
38aae1b122325816592cc9cc4c31e35bad38cd1f
<ide><path>actionpack/lib/action_controller/routing.rb <ide> def traverse_to_controller(segments, start_at = 0) <ide> controller_name = "#{mod_name}Controller" <ide> <ide> suppress(NameError) do <del> ActionController::Base.logger.info("Looking for #{controller_name}") <ide> controller = eval("mod::#{controller_name}", nil, __FILE__, __LINE__) <del> ActionController::Base.logger.info("Found") <del> # Detect the case when const_get returns an object from a parent namespace. <ide> <del> ActionController::Base.logger.info("#{controller.name} == #{mod.name}::#{controller_name}") <add> # Detect the case when const_get returns an object from a parent namespace. <ide> if mod == Object || controller.name == "#{mod.name}::#{controller_name}" <ide> return controller, (index - start_at) <ide> end
1
Javascript
Javascript
pass index to accessor functions
184c0ffea90401ecb4fb7b12f4caf437659bdbe3
<ide><path>src/geom/quadtree.js <ide> d3.geom.quadtree = function(points, x1, y1, x2, y2) { <ide> <ide> if (compat) points = data; <ide> else for (points = [], i = 0; i < n; ++i) { <del> points.push({x: +fx.call(this, d = data[i]), y: +fy.call(this, d)}); <add> points.push({x: +fx.call(this, d = data[i], i), y: +fy.call(this, d, i)}); <ide> } <ide> <ide> if (x1 != null) { <ide> d3.geom.quadtree = function(points, x1, y1, x2, y2) { <ide> // Create the root node. <ide> var root = d3_geom_quadtreeNode(); <ide> <del> root.add = function(d) { <del> insert(root, d, fx(d), fy(d), x1_, y1_, x2_, y2_); <add> root.add = function(d, i) { <add> insert(root, d, fx.call(this, d, i), fy.call(this, d, i), x1_, y1_, x2_, y2_); <ide> }; <ide> <ide> root.visit = function(f) {
1
Python
Python
fix kube client on mac with keepalive enabled
11face6206174fb29d602b368992297b2eb83981
<ide><path>airflow/kubernetes/kube_client.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> """Client for kubernetes communication""" <add>import logging <ide> from typing import Optional <ide> <ide> from airflow.configuration import conf <ide> <add>log = logging.getLogger(__name__) <add> <ide> try: <ide> from kubernetes import client, config <ide> from kubernetes.client import Configuration <ide> def _enable_tcp_keepalive() -> None: <ide> tcp_keep_intvl = conf.getint('kubernetes', 'tcp_keep_intvl') <ide> tcp_keep_cnt = conf.getint('kubernetes', 'tcp_keep_cnt') <ide> <del> socket_options = [ <del> (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1), <del> (socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, tcp_keep_idle), <del> (socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, tcp_keep_intvl), <del> (socket.IPPROTO_TCP, socket.TCP_KEEPCNT, tcp_keep_cnt), <del> ] <add> socket_options = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] <add> <add> if hasattr(socket, "TCP_KEEPIDLE"): <add> socket_options.append((socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, tcp_keep_idle)) <add> else: <add> log.warning("Unable to set TCP_KEEPIDLE on this platform") <add> <add> if hasattr(socket, "TCP_KEEPINTVL"): <add> socket_options.append((socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, tcp_keep_intvl)) <add> else: <add> log.warning("Unable to set TCP_KEEPINTVL on this platform") <add> <add> if hasattr(socket, "TCP_KEEPCNT"): <add> socket_options.append((socket.IPPROTO_TCP, socket.TCP_KEEPCNT, tcp_keep_cnt)) <add> else: <add> log.warning("Unable to set TCP_KEEPCNT on this platform") <add> <ide> HTTPSConnection.default_socket_options = HTTPSConnection.default_socket_options + socket_options <ide> HTTPConnection.default_socket_options = HTTPConnection.default_socket_options + socket_options <ide>
1
Python
Python
fix gpu usage
ce876c551e5dbdcfcccab9c75418376b906d0da3
<ide><path>spacy/_ml.py <ide> def backward(dY_ids, sgd=None): <ide> <ide> def _add_padding(self, Yf): <ide> Yf_padded = self.ops.xp.vstack((self.pad, Yf)) <del> return Yf_padded[1:] <add> return Yf_padded <ide> <ide> def _backprop_padding(self, dY, ids): <del> for i in range(ids.shape[0]): <del> for j in range(ids.shape[1]): <del> if ids[i, j] < 0: <del> self.d_pad[0, j] += dY[i, j] <add> # (1, nF, nO, nP) += (nN, nF, nO, nP) where IDs (nN, nF) < 0 <add> d_feats = dY[ids] <add> ids = ids.reshape((ids.shape[0], ids.shape[1], 1, 1)) <add> d_feats *= ids < 0 <add> self.d_pad += d_feats.sum(axis=0, keepdims=True) <ide> return dY, ids <ide> <ide> @staticmethod <ide> def init_weights(model): <ide> ''' <ide> if (model.W**2).sum() != 0.: <ide> return <del> model.ops.normal_init(model.W, model.nF * model.nI, inplace=True) <del> <del> ids = numpy.zeros((5000, model.nF), dtype='i') <del> ids += numpy.asarray(numpy.random.uniform(0, 1000, ids.shape), dtype='i') <del> tokvecs = numpy.zeros((5000, model.nI), dtype='f') <del> tokvecs += numpy.random.normal(loc=0., scale=1., <add> ops = model.ops <add> xp = ops.xp <add> ops.normal_init(model.W, model.nF * model.nI, inplace=True) <add> <add> ids = ops.allocate((5000, model.nF), dtype='f') <add> ids += xp.random.uniform(0, 1000, ids.shape) <add> ids = ops.asarray(ids, dtype='i') <add> tokvecs = ops.allocate((5000, model.nI), dtype='f') <add> tokvecs += xp.random.normal(loc=0., scale=1., <ide> size=tokvecs.size).reshape(tokvecs.shape) <ide> <ide> def predict(ids, tokvecs): <ide> def predict(ids, tokvecs): <ide> t_i = 0 <ide> for t_i in range(t_max): <ide> acts1 = predict(ids, tokvecs) <del> var = numpy.var(acts1) <del> mean = numpy.mean(acts1) <add> var = model.ops.xp.var(acts1) <add> mean = model.ops.xp.mean(acts1) <ide> if abs(var - 1.0) >= tol_var: <del> model.W /= numpy.sqrt(var) <add> model.W /= model.ops.xp.sqrt(var) <ide> elif abs(mean) >= tol_mean: <ide> model.b -= mean <ide> else:
1
Javascript
Javascript
add more context to dom nesting warning
64b1f05e7518e46c13ca9dbe8d2792054dd9a515
<ide><path>src/browser/__tests__/validateDOMNesting-test.js <ide> <ide> 'use strict'; <ide> <del>var isTagValidInContext; <add>var validateDOMNesting; <ide> <ide> // https://html.spec.whatwg.org/multipage/syntax.html#special <ide> var specialTags = [ <ide> var formattingTags = [ <ide> ]; <ide> <ide> function isTagStackValid(stack) { <add> var ancestorInfo = null; <ide> for (var i = 0; i < stack.length; i++) { <del> if (!isTagValidInContext(stack[i], stack.slice(0, i))) { <add> if (!validateDOMNesting.isTagValidInContext(stack[i], ancestorInfo)) { <ide> return false; <ide> } <add> ancestorInfo = <add> validateDOMNesting.updatedAncestorInfo(ancestorInfo, stack[i], null); <ide> } <ide> return true; <ide> } <ide> describe('ReactContextValidator', function() { <ide> beforeEach(function() { <ide> require('mock-modules').dumpCache(); <ide> <del> isTagValidInContext = require('validateDOMNesting').isTagValidInContext; <add> validateDOMNesting = require('validateDOMNesting'); <ide> }); <ide> <ide> it('allows any tag with no context', function() { <ide> // With renderToString (for example), we don't know where we're mounting the <ide> // tag so we must err on the side of leniency. <ide> specialTags.concat(formattingTags, ['mysterytag']).forEach(function(tag) { <del> expect(isTagValidInContext(tag, [])).toBe(true); <add> expect(validateDOMNesting.isTagValidInContext(tag, null)).toBe(true); <ide> }); <ide> }); <ide> <ide> describe('ReactContextValidator', function() { <ide> // Invalid, but not changed by browser parsing so we allow them <ide> expect(isTagStackValid(['div', 'ul', 'ul', 'li'])).toBe(true); <ide> expect(isTagStackValid(['div', 'label', 'div'])).toBe(true); <add> expect(isTagStackValid(['div', 'ul', 'li', 'section', 'li'])).toBe(true); <add> expect(isTagStackValid(['div', 'ul', 'li', 'dd', 'li'])).toBe(true); <ide> }); <ide> <ide> it('prevents problematic nestings', function() { <ide> expect(isTagStackValid(['a', 'a'])).toBe(false); <ide> expect(isTagStackValid(['form', 'form'])).toBe(false); <ide> expect(isTagStackValid(['p', 'p'])).toBe(false); <ide> expect(isTagStackValid(['table', 'tr'])).toBe(false); <add> expect(isTagStackValid(['div', 'ul', 'li', 'div', 'li'])).toBe(false); <ide> }); <ide> }); <ide><path>src/browser/ui/ReactDOMComponent.js <ide> function validateDangerousTag(tag) { <ide> } <ide> } <ide> <del>function processChildContext(context, tagName) { <add>function processChildContext(context, inst) { <ide> if (__DEV__) { <ide> // Pass down our tag name to child components for validation purposes <ide> context = assign({}, context); <del> var stack = context[validateDOMNesting.tagStackContextKey] || []; <del> context[validateDOMNesting.tagStackContextKey] = stack.concat([tagName]); <add> var info = context[validateDOMNesting.ancestorInfoContextKey]; <add> context[validateDOMNesting.ancestorInfoContextKey] = <add> validateDOMNesting.updatedAncestorInfo(info, inst._tag, inst); <ide> } <ide> return context; <ide> } <ide> ReactDOMComponent.Mixin = { <ide> <ide> assertValidProps(this, this._currentElement.props); <ide> if (__DEV__) { <del> if (context[validateDOMNesting.tagStackContextKey]) { <add> if (context[validateDOMNesting.ancestorInfoContextKey]) { <ide> validateDOMNesting( <del> context[validateDOMNesting.tagStackContextKey], <ide> this._tag, <del> this._currentElement <add> this, <add> context[validateDOMNesting.ancestorInfoContextKey] <ide> ); <ide> } <ide> } <ide> ReactDOMComponent.Mixin = { <ide> var mountImages = this.mountChildren( <ide> childrenToUse, <ide> transaction, <del> processChildContext(context, this._tag) <add> processChildContext(context, this) <ide> ); <ide> ret = mountImages.join(''); <ide> } <ide> ReactDOMComponent.Mixin = { <ide> this._updateDOMChildren( <ide> prevElement.props, <ide> transaction, <del> processChildContext(context, this._tag) <add> processChildContext(context, this) <ide> ); <ide> }, <ide> <ide><path>src/browser/ui/ReactDOMTextComponent.js <ide> assign(ReactDOMTextComponent.prototype, { <ide> */ <ide> mountComponent: function(rootID, transaction, context) { <ide> if (__DEV__) { <del> if (context[validateDOMNesting.tagStackContextKey]) { <add> if (context[validateDOMNesting.ancestorInfoContextKey]) { <ide> validateDOMNesting( <del> context[validateDOMNesting.tagStackContextKey], <ide> 'span', <del> null <add> null, <add> context[validateDOMNesting.ancestorInfoContextKey] <ide> ); <ide> } <ide> } <ide><path>src/browser/ui/ReactMount.js <ide> function mountComponentIntoNode( <ide> if (context === emptyObject) { <ide> context = {}; <ide> } <del> context[validateDOMNesting.tagStackContextKey] = <del> [container.nodeName.toLowerCase()]; <add> var tag = container.nodeName.toLowerCase(); <add> context[validateDOMNesting.ancestorInfoContextKey] = <add> validateDOMNesting.updatedAncestorInfo(null, tag, null); <ide> } <ide> var markup = ReactReconciler.mountComponent( <ide> componentInstance, rootID, transaction, context <ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js <ide> describe('ReactDOMComponent', function() { <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.calls[0].args[0]).toBe( <ide> 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' + <del> '<div> in this context (div > div).' <add> '<div>. See div > tr.' <ide> ); <ide> }); <ide> <ide> describe('ReactDOMComponent', function() { <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.calls[0].args[0]).toBe( <ide> 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' + <del> '<p> in this context (p).' <add> '<p>. See p > tr.' <ide> ); <ide> }); <ide> <ide> it('warns nicely for table rows', () => { <ide> spyOn(console, 'error'); <add> var Row = React.createClass({ <add> render: function() { <add> return <tr />; <add> } <add> }); <ide> var Foo = React.createClass({ <ide> render: function() { <del> return <table><tr /></table>; <add> return <table><Row /></table>; <ide> } <ide> }); <ide> ReactTestUtils.renderIntoDocument(<Foo />); <ide> <ide> expect(console.error.calls.length).toBe(1); <ide> expect(console.error.calls[0].args[0]).toBe( <ide> 'Warning: validateDOMNesting(...): <tr> cannot appear as a child of ' + <del> '<table> in this context (div > table). Add a <tbody> to your code ' + <del> 'to match the DOM tree generated by the browser. Check the render ' + <del> 'method of `Foo`.' <add> '<table>. See Foo > table > Row > tr. Add a <tbody> to your code to ' + <add> 'match the DOM tree generated by the browser.' <add> ); <add> }); <add> <add> it('gives useful context in warnings', () => { <add> spyOn(console, 'error'); <add> var Row = React.createClass({ <add> render: () => <tr /> <add> }); <add> var FancyRow = React.createClass({ <add> render: () => <Row /> <add> }); <add> var Table = React.createClass({ <add> render: function() { return <table>{this.props.children}</table>; } <add> }); <add> var FancyTable = React.createClass({ <add> render: function() { return <Table>{this.props.children}</Table>; } <add> }); <add> <add> var Viz1 = React.createClass({ <add> render: () => <table><FancyRow /></table> <add> }); <add> var App1 = React.createClass({ <add> render: () => <Viz1 /> <add> }); <add> ReactTestUtils.renderIntoDocument(<App1 />); <add> expect(console.error.calls.length).toBe(1); <add> expect(console.error.calls[0].args[0]).toContain( <add> 'See Viz1 > table > FancyRow > Row > tr.' <add> ); <add> <add> var Viz2 = React.createClass({ <add> render: () => <FancyTable><FancyRow /></FancyTable> <add> }); <add> var App2 = React.createClass({ <add> render: () => <Viz2 /> <add> }); <add> ReactTestUtils.renderIntoDocument(<App2 />); <add> expect(console.error.calls.length).toBe(2); <add> expect(console.error.calls[1].args[0]).toContain( <add> 'See Viz2 > FancyTable > Table > table > FancyRow > Row > tr.' <add> ); <add> <add> ReactTestUtils.renderIntoDocument(<FancyTable><FancyRow /></FancyTable>); <add> expect(console.error.calls.length).toBe(3); <add> expect(console.error.calls[2].args[0]).toContain( <add> 'See FancyTable > Table > table > FancyRow > Row > tr.' <add> ); <add> <add> ReactTestUtils.renderIntoDocument(<table><FancyRow /></table>); <add> expect(console.error.calls.length).toBe(4); <add> expect(console.error.calls[3].args[0]).toContain( <add> 'See table > FancyRow > Row > tr.' <add> ); <add> <add> ReactTestUtils.renderIntoDocument(<FancyTable><tr /></FancyTable>); <add> expect(console.error.calls.length).toBe(5); <add> expect(console.error.calls[4].args[0]).toContain( <add> 'See FancyTable > Table > table > tr.' <add> ); <add> <add> var Link = React.createClass({ <add> render: function() { return <a>{this.props.children}</a>; } <add> }); <add> ReactTestUtils.renderIntoDocument(<Link><div><Link /></div></Link>); <add> expect(console.error.calls.length).toBe(6); <add> expect(console.error.calls[5].args[0]).toContain( <add> 'See Link > a > ... > Link > a.' <ide> ); <ide> }); <ide> }); <ide><path>src/browser/validateDOMNesting.js <ide> <ide> 'use strict'; <ide> <add>var assign = require('Object.assign'); <ide> var emptyFunction = require('emptyFunction'); <ide> var warning = require('warning'); <ide> <ide> if (__DEV__) { <ide> 'xmp' <ide> ]; <ide> <del> /** <del> * Return whether `stack` contains `tag` and the last occurrence of `tag` is <del> * deeper than any element in the `scope` array. <del> * <del> * https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-the-specific-scope <del> * <del> * Examples: <del> * stackHasTagInSpecificScope(['p', 'quote'], 'p', ['button']) is true <del> * stackHasTagInSpecificScope(['p', 'button'], 'p', ['button']) is false <del> * <del> * @param {Array<string>} stack <del> * @param {string} tag <del> * @param {Array<string>} scope <del> */ <del> var stackHasTagInSpecificScope = function(stack, tag, scope) { <del> for (var i = stack.length - 1; i >= 0; i--) { <del> if (stack[i] === tag) { <del> return true; <del> } <del> if (scope.indexOf(stack[i]) !== -1) { <del> return false; <del> } <del> } <del> return false; <del> }; <del> <ide> // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope <ide> var inScopeTags = [ <ide> 'applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', <ide> 'template', <ide> <ide> // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point <del> // TODO: Distinguish by namespace here <add> // TODO: Distinguish by namespace here -- for <title>, including it here <add> // errs on the side of fewer warnings <ide> 'foreignObject', 'desc', 'title' <ide> ]; <del> var stackHasTagInScope = function(stack, tag) { <del> return stackHasTagInSpecificScope(stack, tag, inScopeTags); <del> }; <ide> <ide> // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope <ide> var buttonScopeTags = inScopeTags.concat(['button']); <del> var stackHasTagInButtonScope = function(stack, tag) { <del> return stackHasTagInSpecificScope(stack, tag, buttonScopeTags); <del> }; <del> <del> // See rules for 'li', 'dd', 'dt' start tags in <del> // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody <del> var listItemTagAllowed = function(tags, stack) { <del> // tags is ['li'] or ['dd, 'dt'] <del> for (var i = stack.length - 1; i >= 0; i--) { <del> if (tags.indexOf(stack[i]) !== -1) { <del> return false; <del> } else if ( <del> specialTags.indexOf(stack[i]) !== -1 && <del> stack[i] !== 'address' && stack[i] !== 'div' && stack[i] !== 'p' <del> ) { <del> return true; <del> } <del> } <del> return true; <del> }; <ide> <ide> // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags <ide> var impliedEndTags = <ide> ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; <ide> <add> var emptyAncestorInfo = { <add> parentTag: null, <add> <add> formTag: null, <add> aTagInScope: null, <add> buttonTagInScope: null, <add> nobrTagInScope: null, <add> pTagInButtonScope: null, <add> <add> listItemTagAutoclosing: null, <add> dlItemTagAutoclosing: null <add> }; <add> <add> var updatedAncestorInfo = function(oldInfo, tag, instance) { <add> var ancestorInfo = assign({}, oldInfo || emptyAncestorInfo); <add> var info = {tag: tag, instance: instance}; <add> <add> if (inScopeTags.indexOf(tag) !== -1) { <add> ancestorInfo.aTagInScope = null; <add> ancestorInfo.buttonTagInScope = null; <add> ancestorInfo.nobrTagInScope = null; <add> } <add> if (buttonScopeTags.indexOf(tag) !== -1) { <add> ancestorInfo.pTagInButtonScope = null; <add> } <add> <add> // See rules for 'li', 'dd', 'dt' start tags in <add> // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody <add> if ( <add> specialTags.indexOf(tag) !== -1 && <add> tag !== 'address' && tag !== 'div' && tag !== 'p' <add> ) { <add> ancestorInfo.listItemTagAutoclosing = null; <add> ancestorInfo.dlItemTagAutoclosing = null; <add> } <add> <add> ancestorInfo.parentTag = info; <add> <add> if (tag === 'form') { <add> ancestorInfo.formTag = info; <add> } <add> if (tag === 'a') { <add> ancestorInfo.aTagInScope = info; <add> } <add> if (tag === 'button') { <add> ancestorInfo.buttonTagInScope = info; <add> } <add> if (tag === 'nobr') { <add> ancestorInfo.nobrTagInScope = info; <add> } <add> if (tag === 'p') { <add> ancestorInfo.pTagInButtonScope = info; <add> } <add> if (tag === 'li') { <add> ancestorInfo.listItemTagAutoclosing = info; <add> } <add> if (tag === 'dd' || tag === 'dt') { <add> ancestorInfo.dlItemTagAutoclosing = info; <add> } <add> <add> return ancestorInfo; <add> }; <add> <ide> /** <del> * Returns whether we allow putting `tag` in the document if the current stack <del> * of open tags is `openTagStack`. <del> * <del> * Examples: <del> * isTagValidInContext('tr', [..., 'table', 'tbody']) is true <del> * isTagValidInContext('tr', [..., 'table']) is false <del> * <del> * @param {string} tag Lowercase HTML tag name or node name like '#text' <del> * @param {Array<string>} openTagStack <add> * Returns whether <ide> */ <del> var isTagValidInContext = function(tag, openTagStack) { <del> var currentTag = openTagStack[openTagStack.length - 1]; <del> <add> var isTagValidWithParent = function(tag, parentTag) { <ide> // First, let's check if we're in an unusual parsing mode... <del> switch (currentTag) { <add> switch (parentTag) { <ide> // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect <ide> case 'select': <ide> return tag === 'option' || tag === 'optgroup' || tag === '#text'; <ide> if (__DEV__) { <ide> // Probably in the "in body" parsing mode, so we outlaw only tag combos <ide> // where the parsing rules cause implicit opens or closes to be added. <ide> // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody <add> switch (tag) { <add> case 'h1': <add> case 'h2': <add> case 'h3': <add> case 'h4': <add> case 'h5': <add> case 'h6': <add> return ( <add> parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && <add> parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6' <add> ); <add> <add> case 'rp': <add> case 'rt': <add> return impliedEndTags.indexOf(parentTag) === -1; <add> <add> case 'caption': <add> case 'col': <add> case 'colgroup': <add> case 'frame': <add> case 'head': <add> case 'tbody': <add> case 'td': <add> case 'tfoot': <add> case 'th': <add> case 'thead': <add> case 'tr': <add> // These tags are only valid with a few parents that have special child <add> // parsing rules -- if we're down here, then none of those matched and <add> // so we allow it only if we don't know what the parent is, as all other <add> // cases are invalid. <add> return parentTag == null; <add> } <add> <add> return true; <add> }; <add> <add> /** <add> * Returns whether <add> */ <add> var findInvalidAncestorForTag = function(tag, ancestorInfo) { <ide> switch (tag) { <ide> case 'address': <ide> case 'article': <ide> if (__DEV__) { <ide> case 'hr': <ide> <ide> case 'xmp': <del> return !stackHasTagInButtonScope(openTagStack, 'p'); <ide> <ide> case 'h1': <ide> case 'h2': <ide> case 'h3': <ide> case 'h4': <ide> case 'h5': <ide> case 'h6': <del> return ( <del> !stackHasTagInButtonScope(openTagStack, 'p') && <del> currentTag !== 'h1' && currentTag !== 'h2' && currentTag !== 'h3' && <del> currentTag !== 'h4' && currentTag !== 'h5' && currentTag !== 'h6' <del> ); <add> return ancestorInfo.pTagInButtonScope; <ide> <ide> case 'form': <del> return ( <del> openTagStack.indexOf('form') === -1 && <del> !stackHasTagInButtonScope(openTagStack, 'p') <del> ); <add> return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; <ide> <ide> case 'li': <del> return listItemTagAllowed(['li'], openTagStack); <add> return ancestorInfo.listItemTagAutoclosing; <ide> <ide> case 'dd': <ide> case 'dt': <del> return listItemTagAllowed(['dd', 'dt'], openTagStack); <add> return ancestorInfo.dlItemTagAutoclosing; <ide> <ide> case 'button': <del> return !stackHasTagInScope(openTagStack, 'button'); <add> return ancestorInfo.buttonTagInScope; <ide> <ide> case 'a': <ide> // Spec says something about storing a list of markers, but it sounds <ide> // equivalent to this check. <del> return !stackHasTagInScope(openTagStack, 'a'); <add> return ancestorInfo.aTagInScope; <ide> <ide> case 'nobr': <del> return !stackHasTagInScope(openTagStack, 'nobr'); <add> return ancestorInfo.nobrTagInScope; <add> } <ide> <del> case 'rp': <del> case 'rt': <del> return impliedEndTags.indexOf(currentTag) === -1; <add> return null; <add> }; <ide> <del> case 'caption': <del> case 'col': <del> case 'colgroup': <del> case 'frame': <del> case 'head': <del> case 'tbody': <del> case 'td': <del> case 'tfoot': <del> case 'th': <del> case 'thead': <del> case 'tr': <del> return currentTag === undefined; <add> /** <add> * Given a ReactCompositeComponent instance, return a list of its recursive <add> * owners, starting at the root and ending with the instance itself. <add> */ <add> var findOwnerStack = function(instance) { <add> if (!instance) { <add> return []; <ide> } <ide> <del> return true; <add> var stack = []; <add> /*eslint-disable space-after-keywords */ <add> do { <add> /*eslint-enable space-after-keywords */ <add> stack.push(instance); <add> } while ((instance = instance._currentElement._owner)); <add> stack.reverse(); <add> return stack; <ide> }; <ide> <del> validateDOMNesting = function(parentStack, childTag, element) { <del> if (!isTagValidInContext(childTag, parentStack)) { <del> var info = ''; <del> var parentTag = parentStack[parentStack.length - 1]; <del> if (parentTag === 'table' && childTag === 'tr') { <del> info += <del> ' Add a <tbody> to your code to match the DOM tree generated by ' + <del> 'the browser.'; <del> } <del> if (element && element._owner) { <del> var name = element._owner.getName(); <del> if (name) { <del> info += ` Check the render method of \`${name}\`.`; <add> validateDOMNesting = function(childTag, childInstance, ancestorInfo) { <add> ancestorInfo = ancestorInfo || emptyAncestorInfo; <add> var parentInfo = ancestorInfo.parentTag; <add> var parentTag = parentInfo && parentInfo.tag; <add> <add> var invalidParent = <add> isTagValidWithParent(childTag, parentTag) ? null : parentInfo; <add> var invalidAncestor = <add> invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); <add> var problematic = invalidParent || invalidAncestor; <add> <add> if (problematic) { <add> var ancestorTag = problematic.tag; <add> var ancestorInstance = problematic.instance; <add> <add> var childOwner = childInstance && childInstance._currentElement._owner; <add> var ancestorOwner = <add> ancestorInstance && ancestorInstance._currentElement._owner; <add> <add> var childOwners = findOwnerStack(childOwner); <add> var ancestorOwners = findOwnerStack(ancestorOwner); <add> <add> var minStackLen = Math.min(childOwners.length, ancestorOwners.length); <add> var i; <add> <add> var deepestCommon = -1; <add> for (i = 0; i < minStackLen; i++) { <add> if (childOwners[i] === ancestorOwners[i]) { <add> deepestCommon = i; <add> } else { <add> break; <ide> } <ide> } <ide> <del> warning( <del> false, <del> 'validateDOMNesting(...): <%s> cannot appear as a child of <%s> ' + <del> 'in this context (%s).%s', <del> childTag, <del> parentTag, <del> parentStack.join(' > '), <del> info <add> var UNKNOWN = '(unknown)'; <add> var childOwnerNames = childOwners.slice(deepestCommon + 1).map( <add> (inst) => inst.getName() || UNKNOWN <add> ); <add> var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map( <add> (inst) => inst.getName() || UNKNOWN <ide> ); <add> var ownerInfo = [].concat( <add> // If the parent and child instances have a common owner ancestor, start <add> // with that -- otherwise we just start with the parent's owners. <add> deepestCommon !== -1 ? <add> childOwners[deepestCommon].getName() || UNKNOWN : <add> [], <add> ancestorOwnerNames, <add> ancestorTag, <add> // If we're warning about an invalid (non-parent) ancestry, add '...' <add> invalidAncestor ? ['...'] : [], <add> childOwnerNames, <add> childTag <add> ).join(' > '); <add> <add> if (invalidParent) { <add> var info = ''; <add> if (ancestorTag === 'table' && childTag === 'tr') { <add> info += <add> ' Add a <tbody> to your code to match the DOM tree generated by ' + <add> 'the browser.'; <add> } <add> warning( <add> false, <add> 'validateDOMNesting(...): <%s> cannot appear as a child of <%s>. ' + <add> 'See %s.%s', <add> childTag, <add> ancestorTag, <add> ownerInfo, <add> info <add> ); <add> } else { <add> warning( <add> false, <add> 'validateDOMNesting(...): <%s> cannot appear as a descendant of ' + <add> '<%s>. See %s.', <add> childTag, <add> ancestorTag, <add> ownerInfo <add> ); <add> } <ide> } <ide> }; <ide> <del> validateDOMNesting.tagStackContextKey = <del> '__validateDOMNesting_tagStack$' + Math.random().toString(36).slice(2); <add> validateDOMNesting.ancestorInfoContextKey = <add> '__validateDOMNesting_ancestorInfo$' + Math.random().toString(36).slice(2); <add> <add> validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; <ide> <ide> // For testing <del> validateDOMNesting.isTagValidInContext = isTagValidInContext; <add> validateDOMNesting.isTagValidInContext = function(tag, ancestorInfo) { <add> ancestorInfo = ancestorInfo || emptyAncestorInfo; <add> var parentInfo = ancestorInfo.parentTag; <add> var parentTag = parentInfo && parentInfo.tag; <add> return ( <add> isTagValidWithParent(tag, parentTag) && <add> !findInvalidAncestorForTag(tag, ancestorInfo) <add> ); <add> }; <ide> } <ide> <ide> module.exports = validateDOMNesting;
6
Javascript
Javascript
remove dead code from internal/http.js
acaa58e60260225ac935b385d6cc799b446e8799
<ide><path>lib/internal/http.js <ide> const { <ide> const { setUnrefTimeout } = require('internal/timers'); <ide> const { PerformanceEntry, notify } = internalBinding('performance'); <ide> <del>let nowCache; <ide> let utcCache; <ide> <del>function nowDate() { <del> if (!nowCache) cache(); <del> return nowCache; <del>} <del> <ide> function utcDate() { <ide> if (!utcCache) cache(); <ide> return utcCache; <ide> } <ide> <ide> function cache() { <ide> const d = new Date(); <del> nowCache = d.valueOf(); <ide> utcCache = d.toUTCString(); <ide> setUnrefTimeout(resetCache, 1000 - d.getMilliseconds()); <ide> } <ide> <ide> function resetCache() { <del> nowCache = undefined; <ide> utcCache = undefined; <ide> } <ide> <ide> function emitStatistics(statistics) { <ide> module.exports = { <ide> kOutHeaders: Symbol('kOutHeaders'), <ide> kNeedDrain: Symbol('kNeedDrain'), <del> nowDate, <ide> utcDate, <ide> emitStatistics <ide> };
1
Ruby
Ruby
fix dirty tracking for `touch`
d1107f4d1e2573948d4941ac44511a0af6241f80
<ide><path>activerecord/lib/active_record/attribute_methods/dirty.rb <ide> def write_attribute_without_type_cast(attr_name, value) <ide> result <ide> end <ide> <add> def _touch_row(attribute_names, time) <add> @_touch_attr_names = Set.new(attribute_names) <add> <add> affected_rows = super <add> <add> changes = {} <add> @attributes.keys.each do |attr_name| <add> next if @_touch_attr_names.include?(attr_name) <add> <add> if attribute_changed?(attr_name) <add> changes[attr_name] = _read_attribute(attr_name) <add> _write_attribute(attr_name, attribute_was(attr_name)) <add> clear_attribute_change(attr_name) <add> end <add> end <add> <add> changes_applied <add> changes.each { |attr_name, value| _write_attribute(attr_name, value) } <add> <add> affected_rows <add> ensure <add> @_touch_attr_names = nil <add> end <add> <ide> def _update_record(attribute_names = attribute_names_for_partial_writes) <ide> affected_rows = super <ide> changes_applied <ide><path>activerecord/lib/active_record/locking/optimistic.rb <ide> def _create_record(attribute_names = self.attribute_names) <ide> end <ide> <ide> def _touch_row(attribute_names, time) <add> @_touch_attr_names << self.class.locking_column if locking_enabled? <ide> super <del> ensure <del> clear_attribute_change(self.class.locking_column) if locking_enabled? <ide> end <ide> <ide> def _update_row(attribute_names, attempted_action = "update") <ide><path>activerecord/lib/active_record/persistence.rb <ide> def touch(*names, time: nil) <ide> end <ide> <ide> attribute_names = timestamp_attributes_for_update_in_model <del> attribute_names |= names.map(&:to_s) <add> attribute_names |= names.map!(&:to_s).map! { |name| <add> self.class.attribute_alias?(name) ? self.class.attribute_alias(name) : name <add> } <ide> <ide> unless attribute_names.empty? <ide> affected_rows = _touch_row(attribute_names, time) <ide> def _touch_row(attribute_names, time) <ide> time ||= current_time_from_proper_timezone <ide> <ide> attribute_names.each do |attr_name| <del> write_attribute(attr_name, time) <del> clear_attribute_change(attr_name) <add> _write_attribute(attr_name, time) <ide> end <ide> <ide> _update_row(attribute_names, "touch") <ide><path>activerecord/test/cases/locking_test.rb <ide> def test_touch_existing_lock <ide> <ide> p1.touch <ide> assert_equal 1, p1.lock_version <del> assert_not p1.changed?, "Changes should have been cleared" <add> assert_not_predicate p1, :changed?, "Changes should have been cleared" <add> assert_predicate p1, :saved_changes? <add> assert_equal ["lock_version", "updated_at"], p1.saved_changes.keys.sort <ide> end <ide> <ide> def test_touch_stale_object <ide> def test_touch_stale_object <ide> assert_raises(ActiveRecord::StaleObjectError) do <ide> stale_person.touch <ide> end <add> <add> assert_not_predicate stale_person, :saved_changes? <ide> end <ide> <ide> def test_update_with_dirty_primary_key <ide> def test_touch_existing_lock_without_default_should_work_with_null_in_the_databa <ide> t1.touch <ide> <ide> assert_equal 1, t1.lock_version <add> assert_not_predicate t1, :changed? <add> assert_predicate t1, :saved_changes? <add> assert_equal ["lock_version", "updated_at"], t1.saved_changes.keys.sort <ide> end <ide> <ide> def test_touch_stale_object_with_lock_without_default <ide> def test_touch_stale_object_with_lock_without_default <ide> assert_raises(ActiveRecord::StaleObjectError) do <ide> stale_object.touch <ide> end <add> <add> assert_not_predicate stale_object, :saved_changes? <ide> end <ide> <ide> def test_lock_without_default_should_work_with_null_in_the_database <ide><path>activerecord/test/cases/timestamp_test.rb <ide> def test_touching_a_record_updates_its_timestamp <ide> <ide> assert_not_equal @previously_updated_at, @developer.updated_at <ide> assert_equal previous_salary + 10000, @developer.salary <del> assert @developer.salary_changed?, "developer salary should have changed" <del> assert @developer.changed?, "developer should be marked as changed" <add> assert_predicate @developer, :salary_changed?, "developer salary should have changed" <add> assert_predicate @developer, :changed?, "developer should be marked as changed" <add> assert_equal ["salary"], @developer.changed <add> assert_predicate @developer, :saved_changes? <add> assert_equal ["updated_at", "updated_on"], @developer.saved_changes.keys.sort <add> <ide> @developer.reload <ide> assert_equal previous_salary, @developer.salary <ide> end <ide> <ide> def test_touching_a_record_with_default_scope_that_excludes_it_updates_its_timestamp <ide> developer = @developer.becomes(DeveloperCalledJamis) <del> <ide> developer.touch <add> <ide> assert_not_equal @previously_updated_at, developer.updated_at <add> assert_not_predicate developer, :changed? <add> assert_predicate developer, :saved_changes? <add> assert_equal ["updated_at", "updated_on"], developer.saved_changes.keys.sort <add> <ide> developer.reload <ide> assert_not_equal @previously_updated_at, developer.updated_at <ide> end
5
Python
Python
resolve merge conflict
53ff5d90959c0148e6ff5abb2ef614479806411c
<ide><path>official/resnet/keras/keras_cifar_main.py <ide> from official.resnet import cifar10_main as cifar_main <ide> from official.resnet import resnet_run_loop <ide> from official.resnet.keras import keras_common <del>from official.resnet.keras import keras_resnet_model <add>from official.resnet.keras import resnet56 <ide> from official.utils.flags import core as flags_core <ide> from official.utils.logs import logger <ide> from official.utils.misc import distribution_utils <ide> def run(flags_obj): <ide> optimizer = keras_common.get_optimizer() <ide> strategy = keras_common.get_dist_strategy() <ide> <del> model = keras_resnet_model.ResNet56(input_shape=(32, 32, 3), <del> classes=cifar_main._NUM_CLASSES) <add> model = resnet56.ResNet56(input_shape=(32, 32, 3), <add> classes=cifar_main._NUM_CLASSES) <ide> <ide> model.compile(loss='categorical_crossentropy', <ide> optimizer=optimizer, <ide> metrics=['categorical_accuracy'], <del> distribute=strategy) <ide> <ide> time_callback, tensorboard_callback, lr_callback = keras_common.get_fit_callbacks( <ide> learning_rate_schedule) <ide><path>official/resnet/keras/keras_resnet_model.py <del># Copyright 2017 The TensorFlow Authors. All Rights Reserved. <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>"""ResNet50 model for Keras adapted from tf.keras.applications.ResNet50. <del> <del># Reference: <del>- [Deep Residual Learning for Image Recognition]( <del> https://arxiv.org/abs/1512.03385) <del>Adapted from code contributed by BigMoyan. <del>""" <del>from __future__ import absolute_import <del>from __future__ import division <del>from __future__ import print_function <del> <del>import os <del>import warnings <del> <del>import tensorflow as tf <del> <del>WEIGHTS_PATH = ('https://github.com/fchollet/deep-learning-models/' <del> 'releases/download/v0.2/' <del> 'resnet50_weights_tf_dim_ordering_tf_kernels.h5') <del>WEIGHTS_PATH_NO_TOP = ('https://github.com/fchollet/deep-learning-models/' <del> 'releases/download/v0.2/' <del> 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5') <del> <del>BATCH_NORM_DECAY = 0.9 <del>BATCH_NORM_EPSILON = 1e-5 <del>L2_WEIGHT_DECAY = 1e-4 <del> <del> <del>def _obtain_input_shape(input_shape, <del> default_size, <del> min_size, <del> data_format, <del> require_flatten, <del> weights=None): <del> """Internal utility to compute/validate a model's input shape. <del> <del> Arguments: <del> input_shape: Either None (will return the default network input shape), <del> or a user-provided shape to be validated. <del> default_size: Default input width/height for the model. <del> min_size: Minimum input width/height accepted by the model. <del> data_format: Image data format to use. <del> require_flatten: Whether the model is expected to <del> be linked to a classifier via a Flatten layer. <del> weights: One of `None` (random initialization) <del> or 'imagenet' (pre-training on ImageNet). <del> If weights='imagenet' input channels must be equal to 3. <del> <del> Returns: <del> An integer shape tuple (may include None entries). <del> <del> Raises: <del> ValueError: In case of invalid argument values. <del> """ <del> if weights != 'imagenet' and input_shape and len(input_shape) == 3: <del> if data_format == 'channels_first': <del> if input_shape[0] not in {1, 3}: <del> warnings.warn( <del> 'This model usually expects 1 or 3 input channels. ' <del> 'However, it was passed an input_shape with ' + <del> str(input_shape[0]) + ' input channels.') <del> default_shape = (input_shape[0], default_size, default_size) <del> else: <del> if input_shape[-1] not in {1, 3}: <del> warnings.warn( <del> 'This model usually expects 1 or 3 input channels. ' <del> 'However, it was passed an input_shape with ' + <del> str(input_shape[-1]) + ' input channels.') <del> default_shape = (default_size, default_size, input_shape[-1]) <del> else: <del> if data_format == 'channels_first': <del> default_shape = (3, default_size, default_size) <del> else: <del> default_shape = (default_size, default_size, 3) <del> if weights == 'imagenet' and require_flatten: <del> if input_shape is not None: <del> if input_shape != default_shape: <del> raise ValueError('When setting`include_top=True` ' <del> 'and loading `imagenet` weights, ' <del> '`input_shape` should be ' + <del> str(default_shape) + '.') <del> return default_shape <del> if input_shape: <del> if data_format == 'channels_first': <del> if input_shape is not None: <del> if len(input_shape) != 3: <del> raise ValueError( <del> '`input_shape` must be a tuple of three integers.') <del> if input_shape[0] != 3 and weights == 'imagenet': <del> raise ValueError('The input must have 3 channels; got ' <del> '`input_shape=' + str(input_shape) + '`') <del> if ((input_shape[1] is not None and input_shape[1] < min_size) or <del> (input_shape[2] is not None and input_shape[2] < min_size)): <del> raise ValueError('Input size must be at least ' + <del> str(min_size) + 'x' + str(min_size) + <del> '; got `input_shape=' + <del> str(input_shape) + '`') <del> else: <del> if input_shape is not None: <del> if len(input_shape) != 3: <del> raise ValueError( <del> '`input_shape` must be a tuple of three integers.') <del> if input_shape[-1] != 3 and weights == 'imagenet': <del> raise ValueError('The input must have 3 channels; got ' <del> '`input_shape=' + str(input_shape) + '`') <del> if ((input_shape[0] is not None and input_shape[0] < min_size) or <del> (input_shape[1] is not None and input_shape[1] < min_size)): <del> raise ValueError('Input size must be at least ' + <del> str(min_size) + 'x' + str(min_size) + <del> '; got `input_shape=' + <del> str(input_shape) + '`') <del> else: <del> if require_flatten: <del> input_shape = default_shape <del> else: <del> if data_format == 'channels_first': <del> input_shape = (3, None, None) <del> else: <del> input_shape = (None, None, 3) <del> if require_flatten: <del> if None in input_shape: <del> raise ValueError('If `include_top` is True, ' <del> 'you should specify a static `input_shape`. ' <del> 'Got `input_shape=' + str(input_shape) + '`') <del> return input_shape <del> <del> <del>def identity_block(input_tensor, kernel_size, filters, stage, block, training): <del> """The identity block is the block that has no conv layer at shortcut. <del> <del> Arguments: <del> input_tensor: input tensor <del> kernel_size: default 3, the kernel size of <del> middle conv layer at main path <del> filters: list of integers, the filters of 3 conv layer at main path <del> stage: integer, current stage label, used for generating layer names <del> block: 'a','b'..., current block label, used for generating layer names <del> <del> Returns: <del> Output tensor for the block. <del> """ <del> filters1, filters2, filters3 = filters <del> if tf.keras.backend.image_data_format() == 'channels_last': <del> bn_axis = 3 <del> else: <del> bn_axis = 1 <del> conv_name_base = 'res' + str(stage) + block + '_branch' <del> bn_name_base = 'bn' + str(stage) + block + '_branch' <del> <del> x = tf.keras.layers.Conv2D(filters1, (1, 1), <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2a')(input_tensor) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2a', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> <del> x = tf.keras.layers.Conv2D(filters2, kernel_size, <del> padding='same', <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2b')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2b', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> <del> x = tf.keras.layers.Conv2D(filters3, (1, 1), <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2c')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2c', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> <del> x = tf.keras.layers.add([x, input_tensor]) <del> x = tf.keras.layers.Activation('relu')(x) <del> return x <del> <del> <del>def conv_block(input_tensor, <del> kernel_size, <del> filters, <del> stage, <del> block, <del> strides=(2, 2), <del> training=True): <del> """A block that has a conv layer at shortcut. <del> <del> Arguments: <del> input_tensor: input tensor <del> kernel_size: default 3, the kernel size of <del> middle conv layer at main path <del> filters: list of integers, the filters of 3 conv layer at main path <del> stage: integer, current stage label, used for generating layer names <del> block: 'a','b'..., current block label, used for generating layer names <del> strides: Strides for the first conv layer in the block. <del> training: Boolean to indicate if we are in the training loop. <del> <del> Returns: <del> Output tensor for the block. <del> <del> Note that from stage 3, <del> the first conv layer at main path is with strides=(2, 2) <del> And the shortcut should have strides=(2, 2) as well <del> """ <del> filters1, filters2, filters3 = filters <del> if tf.keras.backend.image_data_format() == 'channels_last': <del> bn_axis = 3 <del> else: <del> bn_axis = 1 <del> conv_name_base = 'res' + str(stage) + block + '_branch' <del> bn_name_base = 'bn' + str(stage) + block + '_branch' <del> <del> x = tf.keras.layers.Conv2D(filters1, (1, 1), <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2a')(input_tensor) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2a', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> <del> x = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2b', strides=strides)(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2b', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> <del> x = tf.keras.layers.Conv2D(filters3, (1, 1), <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2c')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2c', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> <del> shortcut = tf.keras.layers.Conv2D(filters3, (1, 1), strides=strides, <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '1')(input_tensor) <del> shortcut = tf.keras.layers.BatchNormalization( <del> axis=bn_axis, name=bn_name_base + '1', <del> momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON)( <del> shortcut, training=training) <del> <del> x = tf.keras.layers.add([x, shortcut]) <del> x = tf.keras.layers.Activation('relu')(x) <del> return x <del> <del> <del>def ResNet50(include_top=True, <del> weights=None, <del> input_tensor=None, <del> input_shape=None, <del> pooling=None, <del> classes=1000, <del> training=True): <del> """Instantiates the ResNet50 architecture. <del> <del> Optionally loads weights pre-trained on ImageNet. <del> Note that the data format convention used by the model is <del> the one specified in your Keras config at `~/.keras/keras.json`. <del> <del> Arguments: <del> include_top: whether to include the fully-connected <del> layer at the top of the network. <del> weights: one of `None` (random initialization), <del> 'imagenet' (pre-training on ImageNet), <del> or the path to the weights file to be loaded. <del> input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) <del> to use as image input for the model. <del> input_shape: optional shape tuple, only to be specified <del> if `include_top` is False (otherwise the input shape <del> has to be `(224, 224, 3)` (with `channels_last` data format) <del> or `(3, 224, 224)` (with `channels_first` data format). <del> It should have exactly 3 inputs channels, <del> and width and height should be no smaller than 197. <del> E.g. `(200, 200, 3)` would be one valid value. <del> pooling: Optional pooling mode for feature extraction <del> when `include_top` is `False`. <del> - `None` means that the output of the model will be <del> the 4D tensor output of the <del> last convolutional layer. <del> - `avg` means that global average pooling <del> will be applied to the output of the <del> last convolutional layer, and thus <del> the output of the model will be a 2D tensor. <del> - `max` means that global max pooling will <del> be applied. <del> classes: optional number of classes to classify images <del> into, only to be specified if `include_top` is True, and <del> if no `weights` argument is specified. <del> training: optional boolean indicating if this model will be <del> used for training or evaluation. This boolean is then <del> passed to the BatchNorm layer. <del> <del> Returns: <del> A Keras model instance. <del> <del> Raises: <del> ValueError: in case of invalid argument for `weights`, <del> or invalid input shape. <del> """ <del> if not (weights in {'imagenet', None} or os.path.exists(weights)): <del> raise ValueError('The `weights` argument should be either ' <del> '`None` (random initialization), `imagenet` ' <del> '(pre-training on ImageNet), ' <del> 'or the path to the weights file to be loaded.') <del> <del> if weights == 'imagenet' and include_top and classes != 1000: <del> raise ValueError('If using `weights` as `"imagenet"` with `include_top`' <del> ' as true, `classes` should be 1000') <del> <del> # Determine proper input shape <del> input_shape = _obtain_input_shape( <del> input_shape, <del> default_size=224, <del> min_size=197, <del> data_format=tf.keras.backend.image_data_format(), <del> require_flatten=include_top, <del> weights=weights) <del> <del> if input_tensor is None: <del> img_input = tf.keras.layers.Input(shape=input_shape) <del> else: <del> if not tf.keras.backend.is_keras_tensor(input_tensor): <del> img_input = tf.keras.layers.Input(tensor=input_tensor, shape=input_shape) <del> else: <del> img_input = input_tensor <del> if tf.keras.backend.image_data_format() == 'channels_last': <del> bn_axis = 3 <del> else: <del> bn_axis = 1 <del> <del> x = tf.keras.layers.ZeroPadding2D(padding=(3, 3), name='conv1_pad')(img_input) <del> x = tf.keras.layers.Conv2D(64, (7, 7), <del> strides=(2, 2), <del> padding='valid', <del> name='conv1')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, name='bn_conv1', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> x = tf.keras.layers.MaxPooling2D((3, 3), strides=(2, 2))(x) <del> <del> x = conv_block(x, 3, [64, 64, 256], stage=2, block='a', strides=(1, 1), <del> training=training) <del> x = identity_block(x, 3, [64, 64, 256], stage=2, block='b', <del> training=training) <del> x = identity_block(x, 3, [64, 64, 256], stage=2, block='c', <del> training=training) <del> <del> x = conv_block(x, 3, [128, 128, 512], stage=3, block='a', <del> training=training) <del> x = identity_block(x, 3, [128, 128, 512], stage=3, block='b', <del> training=training) <del> x = identity_block(x, 3, [128, 128, 512], stage=3, block='c', <del> training=training) <del> x = identity_block(x, 3, [128, 128, 512], stage=3, block='d', <del> training=training) <del> <del> x = conv_block(x, 3, [256, 256, 1024], stage=4, block='a', <del> training=training) <del> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='b', <del> training=training) <del> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='c', <del> training=training) <del> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='d', <del> training=training) <del> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='e', <del> training=training) <del> x = identity_block(x, 3, [256, 256, 1024], stage=4, block='f', <del> training=training) <del> <del> x = conv_block(x, 3, [512, 512, 2048], stage=5, block='a', <del> training=training) <del> x = identity_block(x, 3, [512, 512, 2048], stage=5, block='b', <del> training=training) <del> x = identity_block(x, 3, [512, 512, 2048], stage=5, block='c', <del> training=training) <del> <del> if include_top: <del> x = tf.keras.layers.AveragePooling2D((7, 7), name='avg_pool')(x) <del> x = tf.keras.layers.Flatten()(x) <del> x = tf.keras.layers.Dense(classes, activation='softmax', name='fc1000')(x) <del> else: <del> if pooling == 'avg': <del> x = tf.keras.layers.GlobalAveragePooling2D()(x) <del> elif pooling == 'max': <del> x = tf.keras.layers.GlobalMaxPooling2D()(x) <del> else: <del> warnings.warn('The output shape of `ResNet50(include_top=False)` ' <del> 'has been changed since Keras 2.2.0.') <del> <del> # Ensure that the model takes into account <del> # any potential predecessors of `input_tensor`. <del> if input_tensor is not None: <del> inputs = tf.keras.engine.get_source_inputs(input_tensor) <del> else: <del> inputs = img_input <del> # Create model. <del> model = tf.keras.models.Model(inputs, x, name='resnet50') <del> <del> # Load weights. <del> if weights == 'imagenet': <del> if include_top: <del> weights_path = tf.keras.utils.get_file( <del> 'resnet50_weights_tf_dim_ordering_tf_kernels.h5', <del> WEIGHTS_PATH, <del> cache_subdir='models', <del> md5_hash='a7b3fe01876f51b976af0dea6bc144eb') <del> else: <del> weights_path = tf.keras.utils.get_file( <del> 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', <del> WEIGHTS_PATH_NO_TOP, <del> cache_subdir='models', <del> md5_hash='a268eb855778b3df3c7506639542a6af') <del> model.load_weights(weights_path) <del> elif weights is not None: <del> model.load_weights(weights) <del> <del> return model <del> <del> <del>def identity_building_block(input_tensor, kernel_size, filters, stage, block, training): <del> """The identity block is the block that has no conv layer at shortcut. <del> <del> Arguments: <del> input_tensor: input tensor <del> kernel_size: default 3, the kernel size of <del> middle conv layer at main path <del> filters: list of integers, the filters of 3 conv layer at main path <del> stage: integer, current stage label, used for generating layer names <del> block: 'a','b'..., current block label, used for generating layer names <del> <del> Returns: <del> Output tensor for the block. <del> """ <del> filters1, filters2 = filters <del> if tf.keras.backend.image_data_format() == 'channels_last': <del> bn_axis = 3 <del> else: <del> bn_axis = 1 <del> conv_name_base = 'res' + str(stage) + block + '_branch' <del> bn_name_base = 'bn' + str(stage) + block + '_branch' <del> <del> x = tf.keras.layers.Conv2D(filters1, kernel_size, <del> padding='same', <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2a')(input_tensor) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2a', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> <del> x = tf.keras.layers.Conv2D(filters2, kernel_size, <del> padding='same', <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2b')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2b', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> <del> x = tf.keras.layers.add([x, input_tensor]) <del> x = tf.keras.layers.Activation('relu')(x) <del> return x <del> <del> <del>def conv_building_block(input_tensor, <del> kernel_size, <del> filters, <del> stage, <del> block, <del> strides=(2, 2), <del> training=True): <del> """A block that has a conv layer at shortcut. <del> <del> Arguments: <del> input_tensor: input tensor <del> kernel_size: default 3, the kernel size of <del> middle conv layer at main path <del> filters: list of integers, the filters of 3 conv layer at main path <del> stage: integer, current stage label, used for generating layer names <del> block: 'a','b'..., current block label, used for generating layer names <del> strides: Strides for the first conv layer in the block. <del> training: Boolean to indicate if we are in the training loop. <del> <del> Returns: <del> Output tensor for the block. <del> <del> Note that from stage 3, <del> the first conv layer at main path is with strides=(2, 2) <del> And the shortcut should have strides=(2, 2) as well <del> """ <del> filters1, filters2 = filters <del> if tf.keras.backend.image_data_format() == 'channels_last': <del> bn_axis = 3 <del> else: <del> bn_axis = 1 <del> conv_name_base = 'res' + str(stage) + block + '_branch' <del> bn_name_base = 'bn' + str(stage) + block + '_branch' <del> <del> x = tf.keras.layers.Conv2D(filters1, kernel_size, <del> padding='same', <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2a', strides=strides)(input_tensor) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2a', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> <del> x = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '2b')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <del> name=bn_name_base + '2b', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> <del> shortcut = tf.keras.layers.Conv2D(filters2, (1, 1), strides=strides, <del> kernel_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> bias_regularizer= <del> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <del> name=conv_name_base + '1')(input_tensor) <del> shortcut = tf.keras.layers.BatchNormalization( <del> axis=bn_axis, name=bn_name_base + '1', <del> momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON)( <del> shortcut, training=training) <del> <del> x = tf.keras.layers.add([x, shortcut]) <del> x = tf.keras.layers.Activation('relu')(x) <del> return x <del> <del> <del>def ResNet56(include_top=True, <del> weights=None, <del> input_tensor=None, <del> input_shape=None, <del> pooling=None, <del> classes=1000, <del> training=True): <del> """Instantiates the ResNet50 architecture. <del> <del> Optionally loads weights pre-trained on ImageNet. <del> Note that the data format convention used by the model is <del> the one specified in your Keras config at `~/.keras/keras.json`. <del> <del> Arguments: <del> include_top: whether to include the fully-connected <del> layer at the top of the network. <del> weights: one of `None` (random initialization), <del> 'imagenet' (pre-training on ImageNet), <del> or the path to the weights file to be loaded. <del> input_tensor: optional Keras tensor (i.e. output of `layers.Input()`) <del> to use as image input for the model. <del> input_shape: optional shape tuple, only to be specified <del> if `include_top` is False (otherwise the input shape <del> has to be `(224, 224, 3)` (with `channels_last` data format) <del> or `(3, 224, 224)` (with `channels_first` data format). <del> It should have exactly 3 inputs channels, <del> and width and height should be no smaller than 197. <del> E.g. `(200, 200, 3)` would be one valid value. <del> pooling: Optional pooling mode for feature extraction <del> when `include_top` is `False`. <del> - `None` means that the output of the model will be <del> the 4D tensor output of the <del> last convolutional layer. <del> - `avg` means that global average pooling <del> will be applied to the output of the <del> last convolutional layer, and thus <del> the output of the model will be a 2D tensor. <del> - `max` means that global max pooling will <del> be applied. <del> classes: optional number of classes to classify images <del> into, only to be specified if `include_top` is True, and <del> if no `weights` argument is specified. <del> training: optional boolean indicating if this model will be <del> used for training or evaluation. This boolean is then <del> passed to the BatchNorm layer. <del> <del> Returns: <del> A Keras model instance. <del> <del> Raises: <del> ValueError: in case of invalid argument for `weights`, <del> or invalid input shape. <del> """ <del> if not (weights in {'imagenet', None} or os.path.exists(weights)): <del> raise ValueError('The `weights` argument should be either ' <del> '`None` (random initialization), `imagenet` ' <del> '(pre-training on ImageNet), ' <del> 'or the path to the weights file to be loaded.') <del> <del> if weights == 'imagenet' and include_top and classes != 1000: <del> raise ValueError('If using `weights` as `"imagenet"` with `include_top`' <del> ' as true, `classes` should be 1000') <del> <del> # Determine proper input shape <del> input_shape = _obtain_input_shape( <del> input_shape, <del> default_size=32, <del> min_size=32, <del> data_format=tf.keras.backend.image_data_format(), <del> require_flatten=include_top, <del> weights=weights) <del> <del> if input_tensor is None: <del> img_input = tf.keras.layers.Input(shape=input_shape) <del> else: <del> if not tf.keras.backend.is_keras_tensor(input_tensor): <del> img_input = tf.keras.layers.Input(tensor=input_tensor, shape=input_shape) <del> else: <del> img_input = input_tensor <del> if tf.keras.backend.image_data_format() == 'channels_last': <del> bn_axis = 3 <del> else: <del> bn_axis = 1 <del> <del> x = tf.keras.layers.ZeroPadding2D(padding=(1, 1), name='conv1_pad')(img_input) <del> x = tf.keras.layers.Conv2D(16, (3, 3), <del> strides=(1, 1), <del> padding='valid', <del> name='conv1')(x) <del> x = tf.keras.layers.BatchNormalization(axis=bn_axis, name='bn_conv1', <del> momentum=BATCH_NORM_DECAY, <del> epsilon=BATCH_NORM_EPSILON)( <del> x, training=training) <del> x = tf.keras.layers.Activation('relu')(x) <del> # x = tf.keras.layers.MaxPooling2D((3, 3), strides=(2, 2))(x) <del> <del> x = conv_building_block(x, 3, [16, 16], stage=2, block='a', strides=(1, 1), <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='b', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='c', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='d', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='e', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='f', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='g', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='h', <del> training=training) <del> x = identity_building_block(x, 3, [16, 16], stage=2, block='i', <del> training=training) <del> <del> x = conv_building_block(x, 3, [32, 32], stage=3, block='a', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='b', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='c', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='d', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='e', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='f', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='g', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='h', <del> training=training) <del> x = identity_building_block(x, 3, [32, 32], stage=3, block='i', <del> training=training) <del> <del> x = conv_building_block(x, 3, [64, 64], stage=4, block='a', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='b', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='c', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='d', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='e', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='f', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='g', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='h', <del> training=training) <del> x = identity_building_block(x, 3, [64, 64], stage=4, block='i', <del> training=training) <del> <del> if include_top: <del> x = tf.keras.layers.AveragePooling2D((8, 8), name='avg_pool')(x) <del> x = tf.keras.layers.Flatten()(x) <del> x = tf.keras.layers.Dense(classes, activation='softmax', name='fc10')(x) <del> else: <del> if pooling == 'avg': <del> x = tf.keras.layers.GlobalAveragePooling2D()(x) <del> elif pooling == 'max': <del> x = tf.keras.layers.GlobalMaxPooling2D()(x) <del> else: <del> warnings.warn('The output shape of `ResNet50(include_top=False)` ' <del> 'has been changed since Keras 2.2.0.') <del> <del> # Ensure that the model takes into account <del> # any potential predecessors of `input_tensor`. <del> if input_tensor is not None: <del> inputs = tf.keras.engine.get_source_inputs(input_tensor) <del> else: <del> inputs = img_input <del> # Create model. <del> model = tf.keras.models.Model(inputs, x, name='resnet56') <del> <del> # Load weights. <del> if weights == 'imagenet': <del> if include_top: <del> weights_path = tf.keras.utils.get_file( <del> 'resnet50_weights_tf_dim_ordering_tf_kernels.h5', <del> WEIGHTS_PATH, <del> cache_subdir='models', <del> md5_hash='a7b3fe01876f51b976af0dea6bc144eb') <del> else: <del> weights_path = tf.keras.utils.get_file( <del> 'resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5', <del> WEIGHTS_PATH_NO_TOP, <del> cache_subdir='models', <del> md5_hash='a268eb855778b3df3c7506639542a6af') <del> model.load_weights(weights_path) <del> elif weights is not None: <del> model.load_weights(weights) <del> <del> return model <ide><path>official/resnet/keras/resnet56.py <add># Copyright 2017 The TensorFlow Authors. All Rights Reserved. <add># <add># Licensed under the Apache License, Version 2.0 (the "License"); <add># you may not use this file except in compliance with the License. <add># You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, software <add># distributed under the License is distributed on an "AS IS" BASIS, <add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add># See the License for the specific language governing permissions and <add># limitations under the License. <add># ============================================================================== <add>"""ResNet50 model for Keras adapted from tf.keras.applications.ResNet50. <add> <add># Reference: <add>- [Deep Residual Learning for Image Recognition]( <add> https://arxiv.org/abs/1512.03385) <add>Adapted from code contributed by BigMoyan. <add>""" <add>from __future__ import absolute_import <add>from __future__ import division <add>from __future__ import print_function <add> <add>import os <add>import warnings <add> <add>import tensorflow as tf <add> <add> <add>BATCH_NORM_DECAY = 0.9 <add>BATCH_NORM_EPSILON = 1e-5 <add>L2_WEIGHT_DECAY = 1e-4 <add> <add> <add>def _obtain_input_shape(input_shape, <add> default_size, <add> data_format): <add> """Internal utility to compute/validate a model's input shape. <add> <add> Arguments: <add> input_shape: Either None (will return the default network input shape), <add> or a user-provided shape to be validated. <add> default_size: Default input width/height for the model. <add> data_format: Image data format to use. <add> <add> Returns: <add> An integer shape tuple (may include None entries). <add> <add> Raises: <add> ValueError: In case of invalid argument values. <add> """ <add> if input_shape and len(input_shape) == 3: <add> if data_format == 'channels_first': <add> if input_shape[0] not in {1, 3}: <add> warnings.warn( <add> 'This model usually expects 1 or 3 input channels. ' <add> 'However, it was passed an input_shape with ' + <add> str(input_shape[0]) + ' input channels.') <add> default_shape = (input_shape[0], default_size, default_size) <add> else: <add> if input_shape[-1] not in {1, 3}: <add> warnings.warn( <add> 'This model usually expects 1 or 3 input channels. ' <add> 'However, it was passed an input_shape with ' + <add> str(input_shape[-1]) + ' input channels.') <add> default_shape = (default_size, default_size, input_shape[-1]) <add> <add> return input_shape <add> <add> <add>def identity_building_block(input_tensor, kernel_size, filters, stage, block, training): <add> """The identity block is the block that has no conv layer at shortcut. <add> <add> Arguments: <add> input_tensor: input tensor <add> kernel_size: default 3, the kernel size of <add> middle conv layer at main path <add> filters: list of integers, the filters of 3 conv layer at main path <add> stage: integer, current stage label, used for generating layer names <add> block: 'a','b'..., current block label, used for generating layer names <add> <add> Returns: <add> Output tensor for the block. <add> """ <add> filters1, filters2 = filters <add> if tf.keras.backend.image_data_format() == 'channels_last': <add> bn_axis = 3 <add> else: <add> bn_axis = 1 <add> conv_name_base = 'res' + str(stage) + block + '_branch' <add> bn_name_base = 'bn' + str(stage) + block + '_branch' <add> <add> x = tf.keras.layers.Conv2D(filters1, kernel_size, <add> padding='same', <add> kernel_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> bias_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> name=conv_name_base + '2a')(input_tensor) <add> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <add> name=bn_name_base + '2a', <add> momentum=BATCH_NORM_DECAY, <add> epsilon=BATCH_NORM_EPSILON)( <add> x, training=True) <add> x = tf.keras.layers.Activation('relu')(x) <add> <add> x = tf.keras.layers.Conv2D(filters2, kernel_size, <add> padding='same', <add> kernel_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> bias_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> name=conv_name_base + '2b')(x) <add> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <add> name=bn_name_base + '2b', <add> momentum=BATCH_NORM_DECAY, <add> epsilon=BATCH_NORM_EPSILON)( <add> x, training=True) <add> <add> x = tf.keras.layers.add([x, input_tensor]) <add> x = tf.keras.layers.Activation('relu')(x) <add> return x <add> <add> <add>def conv_building_block(input_tensor, <add> kernel_size, <add> filters, <add> stage, <add> block, <add> strides=(2, 2), <add> training=True): <add> """A block that has a conv layer at shortcut. <add> <add> Arguments: <add> input_tensor: input tensor <add> kernel_size: default 3, the kernel size of <add> middle conv layer at main path <add> filters: list of integers, the filters of 3 conv layer at main path <add> stage: integer, current stage label, used for generating layer names <add> block: 'a','b'..., current block label, used for generating layer names <add> strides: Strides for the first conv layer in the block. <add> training: Boolean to indicate if we are in the training loop. <add> <add> Returns: <add> Output tensor for the block. <add> <add> Note that from stage 3, <add> the first conv layer at main path is with strides=(2, 2) <add> And the shortcut should have strides=(2, 2) as well <add> """ <add> filters1, filters2 = filters <add> if tf.keras.backend.image_data_format() == 'channels_last': <add> bn_axis = 3 <add> else: <add> bn_axis = 1 <add> conv_name_base = 'res' + str(stage) + block + '_branch' <add> bn_name_base = 'bn' + str(stage) + block + '_branch' <add> <add> x = tf.keras.layers.Conv2D(filters1, kernel_size, <add> padding='same', <add> kernel_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> bias_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> name=conv_name_base + '2a', strides=strides)(input_tensor) <add> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <add> name=bn_name_base + '2a', <add> momentum=BATCH_NORM_DECAY, <add> epsilon=BATCH_NORM_EPSILON)( <add> x, training=True) <add> x = tf.keras.layers.Activation('relu')(x) <add> <add> x = tf.keras.layers.Conv2D(filters2, kernel_size, padding='same', <add> kernel_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> bias_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> name=conv_name_base + '2b')(x) <add> x = tf.keras.layers.BatchNormalization(axis=bn_axis, <add> name=bn_name_base + '2b', <add> momentum=BATCH_NORM_DECAY, <add> epsilon=BATCH_NORM_EPSILON)( <add> x, training=True) <add> <add> shortcut = tf.keras.layers.Conv2D(filters2, (1, 1), strides=strides, <add> kernel_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> bias_regularizer= <add> tf.keras.regularizers.l2(L2_WEIGHT_DECAY), <add> name=conv_name_base + '1')(input_tensor) <add> shortcut = tf.keras.layers.BatchNormalization( <add> axis=bn_axis, name=bn_name_base + '1', <add> momentum=BATCH_NORM_DECAY, epsilon=BATCH_NORM_EPSILON)( <add> shortcut, training=True) <add> <add> x = tf.keras.layers.add([x, shortcut]) <add> x = tf.keras.layers.Activation('relu')(x) <add> return x <add> <add> <add>def ResNet56(input_shape=None, classes=1000): <add> """Instantiates the ResNet56 architecture. <add> <add> Arguments: <add> input_shape: optional shape tuple <add> classes: optional number of classes to classify images into <add> <add> Returns: <add> A Keras model instance. <add> """ <add> # Determine proper input shape <add> input_shape = _obtain_input_shape( <add> input_shape, <add> default_size=32, <add> data_format=tf.keras.backend.image_data_format()) <add> <add> img_input = tf.keras.layers.Input(shape=input_shape) <add> if tf.keras.backend.image_data_format() == 'channels_last': <add> bn_axis = 3 <add> else: <add> bn_axis = 1 <add> <add> x = tf.keras.layers.ZeroPadding2D(padding=(1, 1), name='conv1_pad')(img_input) <add> x = tf.keras.layers.Conv2D(16, (3, 3), <add> strides=(1, 1), <add> padding='valid', <add> name='conv1')(x) <add> x = tf.keras.layers.BatchNormalization(axis=bn_axis, name='bn_conv1', <add> momentum=BATCH_NORM_DECAY, <add> epsilon=BATCH_NORM_EPSILON)( <add> x, training=True) <add> x = tf.keras.layers.Activation('relu')(x) <add> # x = tf.keras.layers.MaxPooling2D((3, 3), strides=(2, 2))(x) <add> <add> x = conv_building_block(x, 3, [16, 16], stage=2, block='a', strides=(1, 1), <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='b', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='c', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='d', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='e', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='f', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='g', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='h', <add> training=True) <add> x = identity_building_block(x, 3, [16, 16], stage=2, block='i', <add> training=True) <add> <add> x = conv_building_block(x, 3, [32, 32], stage=3, block='a', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='b', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='c', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='d', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='e', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='f', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='g', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='h', <add> training=True) <add> x = identity_building_block(x, 3, [32, 32], stage=3, block='i', <add> training=True) <add> <add> x = conv_building_block(x, 3, [64, 64], stage=4, block='a', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='b', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='c', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='d', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='e', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='f', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='g', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='h', <add> training=True) <add> x = identity_building_block(x, 3, [64, 64], stage=4, block='i', <add> training=True) <add> <add> x = tf.keras.layers.AveragePooling2D((8, 8), name='avg_pool')(x) <add> x = tf.keras.layers.Flatten()(x) <add> x = tf.keras.layers.Dense(classes, activation='softmax', name='fc10')(x) <add> <add> inputs = img_input <add> # Create model. <add> model = tf.keras.models.Model(inputs, x, name='resnet56') <add> <add> return model
3
Javascript
Javascript
move addclass to the compile phase
903e7352c9943e4d3757dd1cff58178d4c5375d6
<ide><path>src/ng/directive/ngBind.js <ide> var ngBindTemplateDirective = ['$interpolate', function($interpolate) { <ide> </example> <ide> */ <ide> var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) { <del> return function(scope, element, attr) { <del> element.addClass('ng-binding').data('$binding', attr.ngBindHtml); <add> return { <add> compile: function (tElement, tAttrs) { <add> tElement.addClass('ng-binding'); <ide> <del> var parsed = $parse(attr.ngBindHtml); <del> var changeDetector = $parse(attr.ngBindHtml, function getStringValue(value) { <add> return function (scope, element, attr) { <add> element.data('$binding', attr.ngBindHtml); <add> var parsed = $parse(attr.ngBindHtml); <add> var changeDetector = $parse(attr.ngBindHtml, function getStringValue(value) { <ide> return (value || '').toString(); <ide> }); <ide> <del> scope.$watch(changeDetector, function ngBindHtmlWatchAction() { <del> // we re-evaluate the expr because we want a TrustedValueHolderType <del> // for $sce, not a string <del> element.html($sce.getTrustedHtml(parsed(scope)) || ''); <del> }); <del> }; <add> scope.$watch(changeDetector, function ngBindHtmlWatchAction() { <add> // we re-evaluate the expr because we want a TrustedValueHolderType <add> // for $sce, not a string <add> element.html($sce.getTrustedHtml(parsed(scope)) || ''); <add> }); <add> }; <add> } <add> } <ide> }]; <ide><path>test/ng/directive/ngBindSpec.js <ide> describe('ngBind*', function() { <ide> <ide> <ide> describe('ngBindHtml', function() { <add> <add> it('should add ng-binding class to the element in compile phase', inject(function($compile) { <add> var element = jqLite('<div ng-bind-html="myHtml"></div>'); <add> $compile(element); <add> expect(element.hasClass('ng-binding')).toBe(true); <add> })); <add> <add> <ide> describe('SCE disabled', function() { <ide> beforeEach(function() { <ide> module(function($sceProvider) { $sceProvider.enabled(false); });
2
Mixed
PHP
remove duplicate function dropcolumns
ff036c1bba9fc0391a0ba33a99d35e9a2793fef7
<ide><path>readme.md <ide> - Migrated entire session back-end to Symfony HttpFoundation Session. The `native` driver should now be used in place of the `cookie` driver. All other drivers are available and work the same. New sessions will not be backwards compatible after updating. <ide> - Renamed `Session::getToken` to `Session::token`. <ide> - Added a few more helper methods to the `Collection` class. <add>- Removed `dropColumns` function. <ide> <ide> ## Beta 4 <ide> <ide><path>src/Illuminate/Database/Schema/Blueprint.php <ide> public function dropColumn($columns) <ide> return $this->addCommand('dropColumn', compact('columns')); <ide> } <ide> <del> /** <del> * Indicate that the given columns should be dropped. <del> * <del> * @param dynamic <del> * @return \Illuminate\Support\Fluent <del> */ <del> public function dropColumns() <del> { <del> return $this->dropColumn(func_get_args()); <del> } <del> <ide> /** <ide> * Indicate that the given columns should be renamed. <ide> * <ide> public function dropForeign($index) <ide> */ <ide> public function dropTimestamps() <ide> { <del> $this->dropColumns('created_at', 'updated_at'); <add> $this->dropColumn('created_at', 'updated_at'); <ide> } <ide> <ide> /** <ide><path>tests/Database/DatabaseMySqlSchemaGrammarTest.php <ide> public function testDropColumn() <ide> } <ide> <ide> <del> public function testDropColumns() <del> { <del> $blueprint = new Blueprint('users'); <del> $blueprint->dropColumns('foo', 'bar'); <del> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); <del> <del> $this->assertEquals(1, count($statements)); <del> $this->assertEquals('alter table `users` drop `foo`, drop `bar`', $statements[0]); <del> } <del> <del> <ide> public function testDropPrimary() <ide> { <ide> $blueprint = new Blueprint('users'); <ide><path>tests/Database/DatabasePostgresSchemaGrammarTest.php <ide> public function testDropColumn() <ide> } <ide> <ide> <del> public function testDropColumns() <del> { <del> $blueprint = new Blueprint('users'); <del> $blueprint->dropColumns('foo', 'bar'); <del> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); <del> <del> $this->assertEquals(1, count($statements)); <del> $this->assertEquals('alter table "users" drop column "foo", drop column "bar"', $statements[0]); <del> } <del> <del> <ide> public function testDropPrimary() <ide> { <ide> $blueprint = new Blueprint('users'); <ide><path>tests/Database/DatabaseSqlServerSchemaGrammarTest.php <ide> public function testDropColumn() <ide> } <ide> <ide> <del> public function testDropColumns() <del> { <del> $blueprint = new Blueprint('users'); <del> $blueprint->dropColumns('foo', 'bar'); <del> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); <del> <del> $this->assertEquals(1, count($statements)); <del> $this->assertEquals('alter table "users" drop column "foo", "bar"', $statements[0]); <del> } <del> <del> <ide> public function testDropPrimary() <ide> { <ide> $blueprint = new Blueprint('users');
5
Javascript
Javascript
move settimeout and friends into timers module
79944006e252170933e35862bdff2f7fba6bd762
<ide><path>lib/timers.js <ide> function debug () { <ide> // IDLE TIMEOUTS <ide> // <ide> // Because often many sockets will have the same idle timeout we will not <del>// use one timeout watcher per socket. It is too much overhead. Instead <add>// use one timeout watcher per item. It is too much overhead. Instead <ide> // we'll use a single watcher for all sockets with the same timeout value <ide> // and a linked list. This technique is described in the libev manual: <ide> // http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#Be_smart_about_timeouts <ide> function debug () { <ide> // value = list <ide> var lists = {}; <ide> <del>// show the most idle socket <add>// show the most idle item <ide> function peek (list) { <ide> if (list._idlePrev == list) return null; <ide> return list._idlePrev; <ide> } <ide> <ide> <del>// remove the most idle socket from the list <add>// remove the most idle item from the list <ide> function shift (list) { <ide> var first = list._idlePrev; <ide> remove(first); <ide> return first; <ide> } <ide> <ide> <del>// remove a socket from its list <del>function remove (socket) { <del> socket._idleNext._idlePrev = socket._idlePrev; <del> socket._idlePrev._idleNext = socket._idleNext; <add>// remove a item from its list <add>function remove (item) { <add> item._idleNext._idlePrev = item._idlePrev; <add> item._idlePrev._idleNext = item._idleNext; <ide> } <ide> <ide> <del>// remove a socket from its list and place at the end. <del>function append (list, socket) { <del> remove(socket); <del> socket._idleNext = list._idleNext; <del> socket._idleNext._idlePrev = socket; <del> socket._idlePrev = list; <del> list._idleNext = socket; <add>// remove a item from its list and place at the end. <add>function append (list, item) { <add> remove(item); <add> item._idleNext = list._idleNext; <add> item._idleNext._idlePrev = item; <add> item._idlePrev = list; <add> list._idleNext = item; <ide> } <ide> <ide> <ide> // the main function - creates lists on demand and the watchers associated <ide> // with them. <del>function insert (socket, msecs) { <del> socket._idleStart = new Date(); <del> socket._idleTimeout = msecs; <add>function insert (item, msecs) { <add> item._idleStart = new Date(); <add> item._idleTimeout = msecs; <ide> <ide> if (!msecs) return; <ide> <ide> function insert (socket, msecs) { <ide> list.again(msecs); <ide> } <ide> <del> append(list, socket); <add> append(list, item); <ide> assert(list._idleNext != list); // list is not empty <ide> } <ide> <ide> <del>var unenroll = exports.unenroll = function (socket) { <del> if (socket._idleNext) { <del> socket._idleNext._idlePrev = socket._idlePrev; <del> socket._idlePrev._idleNext = socket._idleNext; <add>var unenroll = exports.unenroll = function (item) { <add> if (item._idleNext) { <add> item._idleNext._idlePrev = item._idlePrev; <add> item._idlePrev._idleNext = item._idleNext; <ide> <del> var list = lists[socket._idleTimeout]; <add> var list = lists[item._idleTimeout]; <ide> // if empty then stop the watcher <ide> //debug('unenroll'); <ide> if (list && list._idlePrev == list) { <ide> var unenroll = exports.unenroll = function (socket) { <ide> <ide> <ide> // Does not start the time, just sets up the members needed. <del>exports.enroll = function (socket, msecs) { <del> // if this socket was already in a list somewhere <add>exports.enroll = function (item, msecs) { <add> // if this item was already in a list somewhere <ide> // then we should unenroll it from that <del> if (socket._idleNext) unenroll(socket); <add> if (item._idleNext) unenroll(item); <ide> <del> socket._idleTimeout = msecs; <del> socket._idleNext = socket; <del> socket._idlePrev = socket; <add> item._idleTimeout = msecs; <add> item._idleNext = item; <add> item._idlePrev = item; <ide> }; <ide> <del>// call this whenever the socket is active (not idle) <add>// call this whenever the item is active (not idle) <ide> // it will reset its timeout. <del>exports.active = function (socket) { <del> var msecs = socket._idleTimeout; <add>exports.active = function (item) { <add> var msecs = item._idleTimeout; <ide> if (msecs) { <ide> var list = lists[msecs]; <del> if (socket._idleNext == socket) { <del> insert(socket, msecs); <add> if (item._idleNext == item) { <add> insert(item, msecs); <ide> } else { <ide> // inline append <del> socket._idleStart = new Date(); <del> socket._idleNext._idlePrev = socket._idlePrev; <del> socket._idlePrev._idleNext = socket._idleNext; <del> socket._idleNext = list._idleNext; <del> socket._idleNext._idlePrev = socket; <del> socket._idlePrev = list; <del> list._idleNext = socket; <add> item._idleStart = new Date(); <add> item._idleNext._idlePrev = item._idlePrev; <add> item._idlePrev._idleNext = item._idleNext; <add> item._idleNext = list._idleNext; <add> item._idleNext._idlePrev = item; <add> item._idlePrev = list; <add> list._idleNext = item; <ide> } <ide> } <ide> }; <add> <add> <add> <add> <add> <add>// Timers <add>function addTimerListener (callback) { <add> var timer = this; <add> // Special case the no param case to avoid the extra object creation. <add> if (arguments.length > 2) { <add> var args = Array.prototype.slice.call(arguments, 2); <add> timer.callback = function () { callback.apply(timer, args); }; <add> } else { <add> timer.callback = callback; <add> } <add>} <add> <add> <add>exports.setTimeout = function (callback, after) { <add> var timer = new Timer(); <add> addTimerListener.apply(timer, arguments); <add> timer.start(after, 0); <add> return timer; <add>}; <add> <add>exports.setInterval = function (callback, repeat) { <add> var timer = new Timer(); <add> addTimerListener.apply(timer, arguments); <add> timer.start(repeat, repeat ? repeat : 1); <add> return timer; <add>}; <add> <add>exports.clearTimeout = function (timer) { <add> if (timer instanceof Timer) { <add> timer.callback = null; <add> timer.stop(); <add> } <add>}; <add> <add>exports.clearInterval = exports.clearTimeout; <ide><path>src/node.js <ide> var constants; // lazy loaded. <ide> }; <ide> })(); <ide> <del>// Timers <del>function addTimerListener (callback) { <del> var timer = this; <del> // Special case the no param case to avoid the extra object creation. <del> if (arguments.length > 2) { <del> var args = Array.prototype.slice.call(arguments, 2); <del> timer.callback = function () { callback.apply(timer, args); }; <del> } else { <del> timer.callback = callback; <del> } <del>} <ide> <del>var Timer; // lazy load <del> <del>global.setTimeout = function (callback, after) { <del> if (!Timer) Timer = process.binding("timer").Timer; <del> var timer = new Timer(); <del> addTimerListener.apply(timer, arguments); <del> timer.start(after, 0); <del> return timer; <add>global.setTimeout = function () { <add> var t = module.requireNative('timers'); <add> return t.setTimeout.apply(this, arguments); <ide> }; <ide> <del>global.setInterval = function (callback, repeat) { <del> if (!Timer) Timer = process.binding("timer").Timer; <del> var timer = new Timer(); <del> addTimerListener.apply(timer, arguments); <del> timer.start(repeat, repeat ? repeat : 1); <del> return timer; <add>global.setInterval = function () { <add> var t = module.requireNative('timers'); <add> return t.setInterval.apply(this, arguments); <ide> }; <ide> <del>global.clearTimeout = function (timer) { <del> if (!Timer) Timer = process.binding("timer").Timer; <del> if (timer instanceof Timer) { <del> timer.callback = null; <del> timer.stop(); <del> } <add>global.clearTimeout = function () { <add> var t = module.requireNative('timers'); <add> return t.clearTimeout.apply(this, arguments); <ide> }; <ide> <del>global.clearInterval = global.clearTimeout; <add>global.clearInterval = function () { <add> var t = module.requireNative('timers'); <add> return t.clearInterval.apply(this, arguments); <add>}; <ide> <ide> <ide> var stdout;
2
Java
Java
fix unit tests
6a1c8f0c5bfd2b8556099d3d70341513b4af4b15
<ide><path>rxjava-contrib/rxjava-android/src/test/java/rx/android/observables/AndroidObservableTest.java <ide> import org.robolectric.Robolectric; <ide> import org.robolectric.RobolectricTestRunner; <ide> import org.robolectric.annotation.Config; <add> <ide> import rx.Observable; <ide> import rx.Observer; <add>import rx.observers.TestObserver; <ide> import rx.operators.OperationObserveFromAndroidComponent; <del> <ide> import android.app.Activity; <ide> import android.app.Fragment; <ide> import android.os.Build; <ide> import android.support.v4.app.FragmentActivity; <del> <ide> import rx.android.observables.AndroidObservable; <ide> <ide> <ide> public void setup() { <ide> <ide> @Test <ide> public void itSupportsFragmentsFromTheSupportV4Library() { <del> AndroidObservable.fromFragment(supportFragment, Observable.just("success")).subscribe(observer); <add> AndroidObservable.fromFragment(supportFragment, Observable.just("success")).subscribe(new TestObserver<String>(observer)); <ide> verify(observer).onNext("success"); <ide> verify(observer).onCompleted(); <ide> } <ide> <ide> @Test <ide> public void itSupportsNativeFragments() { <del> AndroidObservable.fromFragment(fragment, Observable.just("success")).subscribe(observer); <add> AndroidObservable.fromFragment(fragment, Observable.just("success")).subscribe(new TestObserver<String>(observer)); <ide> verify(observer).onNext("success"); <ide> verify(observer).onCompleted(); <ide> } <ide><path>rxjava-contrib/rxjava-android/src/test/java/rx/android/operators/OperationObserveFromAndroidComponentTest.java <ide> import rx.Observer; <ide> import rx.Subscription; <ide> import rx.android.schedulers.AndroidSchedulers; <add>import rx.observers.TestObserver; <ide> import rx.operators.OperationObserveFromAndroidComponent; <ide> import rx.schedulers.Schedulers; <ide> import rx.subjects.PublishSubject; <ide> public void call(Integer i) { <ide> @Test <ide> public void itForwardsOnNextOnCompletedSequenceToTargetObserver() { <ide> Observable<Integer> source = Observable.from(1, 2, 3); <del> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source, mockFragment).subscribe(mockObserver); <add> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source, mockFragment).subscribe(new TestObserver<Integer>(mockObserver)); <ide> verify(mockObserver, times(3)).onNext(anyInt()); <ide> verify(mockObserver).onCompleted(); <ide> verify(mockObserver, never()).onError(any(Exception.class)); <ide> public void itForwardsOnNextOnCompletedSequenceToTargetObserver() { <ide> public void itForwardsOnErrorToTargetObserver() { <ide> final Exception exception = new Exception(); <ide> Observable<Integer> source = Observable.error(exception); <del> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source, mockFragment).subscribe(mockObserver); <add> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source, mockFragment).subscribe(new TestObserver<Integer>(mockObserver)); <ide> verify(mockObserver).onError(exception); <ide> verify(mockObserver, never()).onNext(anyInt()); <ide> verify(mockObserver, never()).onCompleted(); <ide> private void releaseComponentRef(Observable.OnSubscribeFunc<Integer> operator) t <ide> @Test <ide> public void itDoesNotForwardOnNextOnCompletedSequenceIfFragmentIsDetached() { <ide> PublishSubject<Integer> source = PublishSubject.create(); <del> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source.toObservable(), mockFragment).subscribe(mockObserver); <add> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source.toObservable(), mockFragment).subscribe(new TestObserver<Integer>(mockObserver)); <ide> <ide> source.onNext(1); <ide> <ide> public void itDoesNotForwardOnNextOnCompletedSequenceIfFragmentIsDetached() { <ide> @Test <ide> public void itDoesNotForwardOnErrorIfFragmentIsDetached() { <ide> PublishSubject<Integer> source = PublishSubject.create(); <del> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source.toObservable(), mockFragment).subscribe(mockObserver); <add> OperationObserveFromAndroidComponent.observeFromAndroidComponent(source.toObservable(), mockFragment).subscribe(new TestObserver<Integer>(mockObserver)); <ide> <ide> source.onNext(1); <ide> <ide> public Subscription onSubscribe(Observer<? super Integer> o) { <ide> }); <ide> <ide> Subscription sub = OperationObserveFromAndroidComponent.observeFromAndroidComponent( <del> testObservable, mockActivity).subscribe(mockObserver); <add> testObservable, mockActivity).subscribe(new TestObserver<Integer>(mockObserver)); <ide> sub.unsubscribe(); <ide> <ide> assertTrue(s.isUnsubscribed()); <ide><path>rxjava-contrib/rxjava-android/src/test/java/rx/android/schedulers/HandlerThreadSchedulerTest.java <ide> */ <ide> package rx.android.schedulers; <ide> <del>import android.os.Handler; <add>import static org.mockito.Matchers.*; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.concurrent.TimeUnit; <ide> <ide> import org.junit.Test; <ide> import org.junit.runner.RunWith; <ide> import org.mockito.ArgumentCaptor; <del>import static org.hamcrest.CoreMatchers.equalTo; <del>import static org.junit.Assert.assertNotNull; <del>import static org.junit.Assert.assertThat; <ide> import org.robolectric.RobolectricTestRunner; <ide> import org.robolectric.annotation.Config; <ide> <ide> import rx.Scheduler; <ide> import rx.Subscription; <del>import rx.operators.SafeObservableSubscription; <ide> import rx.util.functions.Func2; <del> <del>import java.util.concurrent.TimeUnit; <del> <del>import static org.mockito.Matchers.eq; <del>import static org.mockito.Mockito.mock; <del>import static org.mockito.Mockito.verify; <add>import android.os.Handler; <ide> <ide> @RunWith(RobolectricTestRunner.class) <ide> @Config(manifest=Config.NONE) <ide><path>rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/AsyncTest.java <ide> <ide> import rx.Observable; <ide> import rx.Observer; <add>import rx.observers.TestObserver; <ide> import rx.schedulers.Schedulers; <ide> import rx.schedulers.TestScheduler; <ide> import rx.util.functions.Action0; <ide> public void call() { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call() <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call() { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call() <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128, 256) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, Int <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128, 256) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public void call(Object... args) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128, 256, 512) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(null); <ide> public void call(Object... args) { <ide> <ide> Async.toAsync(action, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128, 256, 512) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onError(any(Throwable.class)); <ide> verify(observer, never()).onNext(null); <ide> public Integer call() { <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call() <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(0); <ide> public Integer call(Integer t1) { <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(1); <ide> public Integer call(Integer t1, Integer t2) { <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(3); <ide> public Integer call(Integer t1, Integer t2, Integer t3) { <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(7); <ide> public Integer call(Integer t1, Integer t2, Integer t3, Integer t4) { <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(15); <ide> public Integer call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5) <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(31); <ide> public Integer call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(63); <ide> public Integer call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(127); <ide> public Integer call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(255); <ide> public Integer call(Integer t1, Integer t2, Integer t3, Integer t4, Integer t5, <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128, 256) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(511); <ide> public Integer call(Object... args) { <ide> }; <ide> Async.toAsync(func, Schedulers.immediate()) <ide> .call(1, 2, 4, 8, 16, 32, 64, 128, 256, 512) <del> .subscribe(observer); <add> .subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onError(any(Throwable.class)); <ide> verify(observer, times(1)).onNext(1023); <ide> public String call() { <ide> <ide> @SuppressWarnings("unchecked") <ide> Observer<String> observer = mock(Observer.class); <del> observable.subscribe(observer); <add> observable.subscribe(new TestObserver<String>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> inOrder.verifyNoMoreInteractions(); <ide> public String call() { <ide> <ide> @SuppressWarnings("unchecked") <ide> Observer<String> observer = mock(Observer.class); <del> observable.subscribe(observer); <add> observable.subscribe(new TestObserver<String>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> inOrder.verify(observer, times(1)).onNext("one"); <ide> public String answer(InvocationOnMock invocation) throws Throwable { <ide> @SuppressWarnings("unchecked") <ide> Observer<String> observer3 = mock(Observer.class); <ide> <del> observable.subscribe(observer1); <del> observable.subscribe(observer2); <del> observable.subscribe(observer3); <add> observable.subscribe(new TestObserver<String>(observer1)); <add> observable.subscribe(new TestObserver<String>(observer2)); <add> observable.subscribe(new TestObserver<String>(observer3)); <ide> <ide> InOrder inOrder; <ide> inOrder = inOrder(observer1); <ide><path>rxjava-contrib/rxjava-async-util/src/test/java/rx/util/async/operators/OperationFromFunctionalsTest.java <ide> import java.util.concurrent.Callable; <ide> import java.util.concurrent.TimeUnit; <ide> import java.util.concurrent.atomic.AtomicInteger; <add> <ide> import junit.framework.Assert; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> import org.mockito.InOrder; <add> <ide> import static org.mockito.Mockito.*; <ide> import rx.Observable; <ide> import rx.Observer; <add>import rx.observers.TestObserver; <ide> import rx.schedulers.TestScheduler; <ide> import rx.util.async.Async; <ide> import rx.util.functions.Action0; <ide> private void testRunShouldThrow(Observable<Integer> source, Class<? extends Thro <ide> for (int i = 0; i < 3; i++) { <ide> <ide> Observer<Object> observer = mock(Observer.class); <del> source.subscribe(observer); <add> source.subscribe(new TestObserver<Object>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> <ide> public void call() { <ide> value.set(0); <ide> <ide> Observer<Object> observer = mock(Observer.class); <del> source.subscribe(observer); <add> source.subscribe(new TestObserver<Object>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> <ide> public Integer call() { <ide> for (int i = 0; i < 3; i++) { <ide> <ide> Observer<Object> observer = mock(Observer.class); <del> source.subscribe(observer); <add> source.subscribe(new TestObserver<Object>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> <ide> public void run() { <ide> value.set(0); <ide> <ide> Observer<Object> observer = mock(Observer.class); <del> source.subscribe(observer); <add> source.subscribe(new TestObserver<Object>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> <ide> public Integer call() throws Exception { <ide> for (int i = 0; i < 3; i++) { <ide> <ide> Observer<Object> observer = mock(Observer.class); <del> source.subscribe(observer); <add> source.subscribe(new TestObserver<Object>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> <ide><path>rxjava-contrib/rxjava-string/src/test/java/rx/observables/StringObservableTest.java <ide> import java.nio.charset.MalformedInputException; <ide> <ide> import org.junit.Test; <del>import static org.mockito.Mockito.*; <ide> <add>import static org.mockito.Mockito.*; <ide> import rx.Observable; <ide> import rx.Observer; <add>import rx.observers.TestObserver; <ide> import rx.util.AssertObservable; <ide> <ide> public class StringObservableTest { <ide> public void testJoinMixed() { <ide> <ide> Observer<Object> observer = mock(Observer.class); <ide> <del> result.subscribe(observer); <add> result.subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onNext("a, 1, c"); <ide> verify(observer, times(1)).onCompleted(); <ide> public void testJoinWithEmptyString() { <ide> <ide> Observer<Object> observer = mock(Observer.class); <ide> <del> result.subscribe(observer); <add> result.subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onNext(", b, c"); <ide> verify(observer, times(1)).onCompleted(); <ide> public void testJoinWithNull() { <ide> <ide> Observer<Object> observer = mock(Observer.class); <ide> <del> result.subscribe(observer); <add> result.subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onNext("a, null, c"); <ide> verify(observer, times(1)).onCompleted(); <ide> public void testJoinSingle() { <ide> <ide> Observer<Object> observer = mock(Observer.class); <ide> <del> result.subscribe(observer); <add> result.subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onNext("a"); <ide> verify(observer, times(1)).onCompleted(); <ide> public void testJoinEmpty() { <ide> <ide> Observer<Object> observer = mock(Observer.class); <ide> <del> result.subscribe(observer); <add> result.subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, times(1)).onNext(""); <ide> verify(observer, times(1)).onCompleted(); <ide> public void testJoinThrows() { <ide> <ide> Observer<Object> observer = mock(Observer.class); <ide> <del> result.subscribe(observer); <add> result.subscribe(new TestObserver<Object>(observer)); <ide> <ide> verify(observer, never()).onNext("a"); <ide> verify(observer, never()).onCompleted();
6
Java
Java
improve onsubscriberefcount comments
96c37422964828e983052a96bab2c4d607df7686
<ide><path>src/main/java/rx/internal/operators/OnSubscribeRefCount.java <ide> public void call(final Subscriber<? super T> subscriber) { <ide> source.connect(onSubscribe(subscriber, writeLocked)); <ide> } finally { <ide> // need to cover the case where the source is subscribed to <del> // outside of this class thus preventing the above Action1 <del> // being called <add> // outside of this class thus preventing the Action1 passed <add> // to source.connect above being called <ide> if (writeLocked.get()) { <del> // Action1 was not called <add> // Action1 passed to source.connect was not called <ide> lock.unlock(); <ide> } <ide> } <ide> public void onCompleted() { <ide> subscriber.onCompleted(); <ide> } <ide> void cleanup() { <add> // on error or completion we need to unsubscribe the base subscription <add> // and set the subscriptionCount to 0 <ide> lock.lock(); <ide> try { <ide> if (baseSubscription == currentBase) {
1
PHP
PHP
add tests for eloquent builder
01d5a77488e54bf425cfc6407b0c474d0d4190fc
<ide><path>tests/Database/DatabaseEloquentBuilderTest.php <ide> public function testGetMethodDoesntHydrateEagerRelationsWhenNoResultsAreReturned <ide> } <ide> <ide> <add> public function testPluckMethodWithModelFound() <add> { <add> $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', array($this->getMockQueryBuilder())); <add> $mockModel = new StdClass; <add> $mockModel->name = 'foo'; <add> $builder->shouldReceive('first')->with(array('name'))->andReturn($mockModel); <add> <add> $this->assertEquals('foo', $builder->pluck('name')); <add> } <add> <add> public function testPluckMethodWithModelNotFound() <add> { <add> $builder = m::mock('Illuminate\Database\Eloquent\Builder[first]', array($this->getMockQueryBuilder())); <add> $builder->shouldReceive('first')->with(array('name'))->andReturn(null); <add> <add> $this->assertNull($builder->pluck('name')); <add> } <add> <add> <add> public function testChunkExecuteCallbackOverPaginatedRequest() <add> { <add> $builder = m::mock('Illuminate\Database\Eloquent\Builder[forPage,get]', array($this->getMockQueryBuilder())); <add> $builder->shouldReceive('forPage')->once()->with(1, 2)->andReturn($builder); <add> $builder->shouldReceive('forPage')->once()->with(2, 2)->andReturn($builder); <add> $builder->shouldReceive('forPage')->once()->with(3, 2)->andReturn($builder); <add> $builder->shouldReceive('get')->times(3)->andReturn(array('foo1', 'foo2'), array('foo3'), array()); <add> <add> $callbackExecutionAssertor = m::mock('StdClass'); <add> $callbackExecutionAssertor->shouldReceive('doSomething')->with('foo1')->once(); <add> $callbackExecutionAssertor->shouldReceive('doSomething')->with('foo2')->once(); <add> $callbackExecutionAssertor->shouldReceive('doSomething')->with('foo3')->once(); <add> <add> $builder->chunk(2, function($results) use($callbackExecutionAssertor) { <add> foreach ($results as $result) { <add> $callbackExecutionAssertor->doSomething($result); <add> } <add> }); <add> } <add> <add> <add> public function testListsReturnsTheMutatedAttributesOfAModel() <add> { <add> $builder = $this->getBuilder(); <add> $builder->getQuery()->shouldReceive('lists')->with('name', '')->andReturn(array('bar', 'baz')); <add> $builder->setModel($this->getMockModel()); <add> $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(true); <add> $builder->getModel()->shouldReceive('newFromBuilder')->with(array('name' => 'bar'))->andReturn(new EloquentBuilderTestListsStub(array('name' => 'bar'))); <add> $builder->getModel()->shouldReceive('newFromBuilder')->with(array('name' => 'baz'))->andReturn(new EloquentBuilderTestListsStub(array('name' => 'baz'))); <add> <add> $this->assertEquals(array('foo_bar', 'foo_baz'), $builder->lists('name')); <add> } <add> <add> public function testListsWithoutModelGetterJustReturnTheAttributesFoundInDatabase() <add> { <add> $builder = $this->getBuilder(); <add> $builder->getQuery()->shouldReceive('lists')->with('name', '')->andReturn(array('bar', 'baz')); <add> $builder->setModel($this->getMockModel()); <add> $builder->getModel()->shouldReceive('hasGetMutator')->with('name')->andReturn(false); <add> <add> $this->assertEquals(array('bar', 'baz'), $builder->lists('name')); <add> } <add> <add> <ide> public function testWithDeletedProperlyRemovesDeletedClause() <ide> { <ide> $builder = new Illuminate\Database\Eloquent\Builder(new Illuminate\Database\Query\Builder( <ide> class EloquentBuilderTestNestedStub extends Illuminate\Database\Eloquent\Model { <ide> protected $table = 'table'; <ide> protected $softDelete = true; <ide> } <add>class EloquentBuilderTestListsStub { <add> protected $attributes; <add> public function __construct($attributes) <add> { <add> $this->attributes = $attributes; <add> } <add> public function __get($key) <add> { <add> return 'foo_' . $this->attributes[$key]; <add> } <add>}
1
Text
Text
update collaborator email in readme
069a24464a168138fb0c9894eb054e750f851582
<ide><path>README.md <ide> For information about the governance of the Node.js project, see <ide> * [cjihrig](https://github.com/cjihrig) - <ide> **Colin Ihrig** &lt;[email protected]&gt; (he/him) <ide> * [codebytere](https://github.com/codebytere) - <del>**Shelley Vohr** &lt;[email protected]&gt; (she/her) <add>**Shelley Vohr** &lt;[email protected]&gt; (she/her) <ide> * [danbev](https://github.com/danbev) - <ide> **Daniel Bevenius** &lt;[email protected]&gt; (he/him) <ide> * [danielleadams](https://github.com/danielleadams) - <ide> For information about the governance of the Node.js project, see <ide> * [cjihrig](https://github.com/cjihrig) - <ide> **Colin Ihrig** &lt;[email protected]&gt; (he/him) <ide> * [codebytere](https://github.com/codebytere) - <del>**Shelley Vohr** &lt;[email protected]&gt; (she/her) <add>**Shelley Vohr** &lt;[email protected]&gt; (she/her) <ide> * [danbev](https://github.com/danbev) - <ide> **Daniel Bevenius** &lt;[email protected]&gt; (he/him) <ide> * [danielleadams](https://github.com/danielleadams) -
1
PHP
PHP
remove views constant
e31344899823951943df967fc9ae50298859e6ac
<ide><path>lib/Cake/Console/Command/Task/ViewTask.php <ide> class ViewTask extends BakeTask { <ide> public $tasks = array('Project', 'Controller', 'DbConfig', 'Template'); <ide> <ide> /** <del> * path to VIEWS directory <add> * path to View directory <ide> * <ide> * @var array <ide> * @access public <ide> */ <del> public $path = VIEWS; <add> public $path = null; <ide> <ide> /** <ide> * Name of the controller being used <ide> class ViewTask extends BakeTask { <ide> * <ide> */ <ide> public function initialize() { <add> $this->path = App::path('View'); <ide> } <ide> <ide> /** <ide> public function getTemplate($action) { <ide> } <ide> if (!empty($this->template) && $action != $this->template) { <ide> return $this->template; <del> } <add> } <ide> $template = $action; <ide> $prefixes = Configure::read('Routing.prefixes'); <ide> foreach ((array)$prefixes as $prefix) { <ide><path>lib/Cake/bootstrap.php <ide> */ <ide> define('APPLIBS', APP.'Lib'.DS); <ide> <del>/** <del> * Path to the application's views directory. <del> */ <del> define('VIEWS', APP.'View'.DS); <del> <ide> /** <ide> * Path to the application's helpers directory. <ide> */
2
Python
Python
allow subclasses through vectorize
b1ff17a473ca58a18452ad1c0e7fd05ea239f016
<ide><path>numpy/lib/function_base.py <ide> def __call__(self, *args): <ide> self.ufunc = frompyfunc(self.thefunc, nargs, self.nout) <ide> <ide> # Convert to object arrays first <del> newargs = [asarray(arg,dtype=object) for arg in args] <add> newargs = [asanyarray(arg,dtype=object) for arg in args] <ide> if self.nout == 1: <ide> _res = array(self.ufunc(*newargs),copy=False).astype(self.otypes[0]) <ide> else:
1
Python
Python
move morphologizer under spacy/pipes
fc1cc4c529e08c887287a3f449fc181fee9a8b6d
<ide><path>setup.py <ide> def is_new_osx(): <ide> "spacy.vocab", <ide> "spacy.attrs", <ide> "spacy.morphology", <del> "spacy._morphologizer", <ide> "spacy.pipeline.pipes", <add> "spacy.pipelines.morphologizer", <ide> "spacy.syntax.stateclass", <ide> "spacy.syntax._state", <ide> "spacy.tokenizer", <ide><path>spacy/language.py <ide> from .pipeline import SimilarityHook, TextCategorizer, SentenceSegmenter <ide> from .pipeline import merge_noun_chunks, merge_entities, merge_subtokens <ide> from .pipeline import EntityRuler <del>from ._morphologizer import Morphologizer <add>from .pipeline import Morphologizer <ide> from .compat import izip, basestring_ <ide> from .gold import GoldParse <ide> from .scorer import Scorer <ide><path>spacy/pipeline/__init__.py <ide> <ide> from .pipes import Tagger, DependencyParser, EntityRecognizer # noqa <ide> from .pipes import TextCategorizer, Tensorizer, Pipe # noqa <add>from .morphologizer import Morphologizer <ide> from .entityruler import EntityRuler # noqa <ide> from .hooks import SentenceSegmenter, SimilarityHook # noqa <ide> from .functions import merge_entities, merge_noun_chunks, merge_subtokens # noqa
3
Mixed
Javascript
fix default `length` parameter for `fs.read`
246227f4bca1afe06af5a766fc41e251b7d3700a
<ide><path>doc/api/fs.md <ide> added: <ide> * `offset` {integer} The location in the buffer at which to start filling. <ide> **Default:** `0` <ide> * `length` {integer} The number of bytes to read. **Default:** <del> `buffer.byteLength` <add> `buffer.byteLength - offset` <ide> * `position` {integer} The location where to begin reading data from the <ide> file. If `null`, data will be read from the current file position, and <ide> the position will be updated. If `position` is an integer, the current <ide> changes: <ide> * `options` {Object} <ide> * `buffer` {Buffer|TypedArray|DataView} **Default:** `Buffer.alloc(16384)` <ide> * `offset` {integer} **Default:** `0` <del> * `length` {integer} **Default:** `buffer.byteLength` <add> * `length` {integer} **Default:** `buffer.byteLength - offset` <ide> * `position` {integer|bigint} **Default:** `null` <ide> * `callback` {Function} <ide> * `err` {Error} <ide><path>lib/fs.js <ide> function read(fd, buffer, offset, length, position, callback) { <ide> ({ <ide> buffer = Buffer.alloc(16384), <ide> offset = 0, <del> length = buffer.byteLength, <add> length = buffer.byteLength - offset, <ide> position <ide> } = options); <ide> }
2
Text
Text
add refack to collaborators
ca8ccb917637a1b54b49419e7392099ac1bfb929
<ide><path>README.md <ide> more information about the governance of the Node.js project, see <ide> **Prince John Wesley** &lt;[email protected]&gt; <ide> * [qard](https://github.com/qard) - <ide> **Stephen Belanger** &lt;[email protected]&gt; (he/him) <add>* [refack](https://github.com/refack) - <add>**Refael Ackermann** &lt;[email protected]&gt; (he/him) <ide> * [richardlau](https://github.com/richardlau) - <ide> **Richard Lau** &lt;[email protected]&gt; <ide> * [rlidwka](https://github.com/rlidwka) -
1
Python
Python
fix setup.py with new __init__.py boilerplate
79596dc613bbf24aac7b5c56179cbc5c46eacdf3
<ide><path>setup.py <ide> def get_version(package): <ide> Return package version as listed in `__version__` in `init.py`. <ide> """ <ide> init_py = open(os.path.join(package, '__init__.py')).read() <del> return re.match("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) <add> return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1) <ide> <ide> <ide> def get_packages(package):
1
Ruby
Ruby
fix prepared statements disabled test again
8b77d8e387079da2d5d4cf2f6fcc4864195852bc
<ide><path>activerecord/test/cases/adapters/postgresql/prepared_statements_disabled_test.rb <add>require "cases/helper" <add>require "models/computer" <add>require "models/developer" <add> <add>class PreparedStatementsDisabledTest < ActiveRecord::PostgreSQLTestCase <add> fixtures :developers <add> <add> def setup <add> @conn = ActiveRecord::Base.establish_connection :arunit_without_prepared_statements <add> end <add> <add> def teardown <add> @conn.release_connection <add> ActiveRecord::Base.establish_connection :arunit <add> end <add> <add> def test_select_query_works_even_when_prepared_statements_are_disabled <add> assert_not Developer.connection.prepared_statements <add> <add> david = developers(:david) <add> <add> assert_equal david, Developer.where(name: "David").last # With Binds <add> assert_operator Developer.count, :>, 0 # Without Binds <add> end <add>end <ide><path>activerecord/test/cases/adapters/postgresql/prepared_statements_test.rb <del>require "cases/helper" <del>require "models/computer" <del>require "models/developer" <del> <del>class PreparedStatementsTest < ActiveRecord::PostgreSQLTestCase <del> fixtures :developers <del> <del> def setup <del> @conn = ActiveRecord::Base.establish_connection :arunit_without_prepared_statements <del> end <del> <del> def teardown <del> @conn.release_connection <del> ActiveRecord::Base.establish_connection :arunit <del> end <del> <del> def test_nothing_raised_with_falsy_prepared_statements <del> assert_nothing_raised do <del> Developer.where(id: 1).to_a <del> end <del> end <del>end
2
PHP
PHP
remove tests that are no longer applicable
8752235048bb03126b5ac44657a3c56c609818de
<ide><path>Cake/Test/TestCase/Controller/Component/PaginatorComponentTest.php <ide> public function testDefaultPaginateParams() { <ide> $this->Paginator->paginate($table, $settings); <ide> } <ide> <del>/** <del> * test paginate() and virtualField interactions <del> * <del> * @return void <del> */ <del> public function testPaginateOrderVirtualField() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <del> $Controller = new PaginatorTestController($this->request); <del> $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); <del> $Controller->request->query = []; <del> $Controller->constructClasses(); <del> $Controller->PaginatorControllerPost->virtualFields = array( <del> 'offset_test' => 'PaginatorControllerPost.id + 1' <del> ); <del> <del> $Controller->Paginator->settings = array( <del> 'fields' => array('id', 'title', 'offset_test'), <del> 'order' => array('offset_test' => 'DESC'), <del> 'maxLimit' => 10, <del> ); <del> $result = $Controller->Paginator->paginate('PaginatorControllerPost'); <del> $this->assertEquals(array(4, 3, 2), Hash::extract($result, '{n}.PaginatorControllerPost.offset_test')); <del> <del> $Controller->request->query = array('sort' => 'offset_test', 'direction' => 'asc'); <del> $result = $Controller->Paginator->paginate('PaginatorControllerPost'); <del> $this->assertEquals(array(2, 3, 4), Hash::extract($result, '{n}.PaginatorControllerPost.offset_test')); <del> } <del> <del>/** <del> * test paginate() and virtualField on joined model <del> * <del> * @return void <del> */ <del> public function testPaginateOrderVirtualFieldJoinedModel() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <del> $Controller = new PaginatorTestController($this->request); <del> $Controller->uses = array('PaginatorControllerPost'); <del> $Controller->request->query = []; <del> $Controller->constructClasses(); <del> $Controller->PaginatorControllerPost->recursive = 0; <del> $Controller->Paginator->settings = array( <del> 'order' => array('PaginatorAuthor.joined_offset' => 'DESC'), <del> 'maxLimit' => 10, <del> ); <del> $result = $Controller->Paginator->paginate('PaginatorControllerPost'); <del> $this->assertEquals(array(4, 2, 2), Hash::extract($result, '{n}.PaginatorAuthor.joined_offset')); <del> <del> $Controller->request->query = array('sort' => 'PaginatorAuthor.joined_offset', 'direction' => 'asc'); <del> $result = $Controller->Paginator->paginate('PaginatorControllerPost'); <del> $this->assertEquals(array(2, 2, 4), Hash::extract($result, '{n}.PaginatorAuthor.joined_offset')); <del> } <del> <ide> /** <ide> * test that option merging prefers specific models <ide> * <ide> public function testValidateSortWhitelistTrusted() { <ide> $this->assertEquals($expected, $result['order']); <ide> } <ide> <del>/** <del> * test that virtual fields work. <del> * <del> * @return void <del> */ <del> public function testValidateSortVirtualField() { <del> $model = $this->getMock('Cake\ORM\Table'); <del> $model->expects($this->any()) <del> ->method('alias') <del> ->will($this->returnValue('model')); <del> <del> $model->expects($this->at(1)) <del> ->method('hasField') <del> ->with('something') <del> ->will($this->returnValue(false)); <del> <del> $model->expects($this->at(2)) <del> ->method('hasField') <del> ->with('something', true) <del> ->will($this->returnValue(true)); <del> <del> $options = array('sort' => 'something', 'direction' => 'desc'); <del> $result = $this->Paginator->validateSort($model, $options); <del> <del> $this->assertEquals('desc', $result['order']['something']); <del> } <del> <del>/** <del> * test that sorting fields is alias specific <del> * <del> * @return void <del> */ <del> public function testValidateSortSharedFields() { <del> $model = $this->getMock('Cake\ORM\Table'); <del> $model->expects($this->any()) <del> ->method('alias') <del> ->will($this->returnValue('model')); <del> $model->Child = $this->getMock('Cake\ORM\Table'); <del> $model->Child->expects($this->any()) <del> ->method('alias') <del> ->will($this->returnValue('Child')); <del> <del> $model->expects($this->never()) <del> ->method('hasField'); <del> <del> $model->Child->expects($this->at(0)) <del> ->method('hasField') <del> ->with('something') <del> ->will($this->returnValue(true)); <del> <del> $options = array('sort' => 'Child.something', 'direction' => 'desc'); <del> $result = $this->Paginator->validateSort($model, $options); <del> <del> $this->assertEquals('desc', $result['order']['Child.something']); <del> } <ide> /** <ide> * test that multiple sort works. <ide> * <ide> public function testPaginateMaxLimit() { <ide> $this->assertEquals(10, $this->request->params['paging']['PaginatorPosts']['limit']); <ide> } <ide> <del>/** <del> * test paginate() and virtualField overlapping with real fields. <del> * <del> * @return void <del> */ <del> public function testPaginateOrderVirtualFieldSharedWithRealField() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <del> $Controller = new Controller($this->request); <del> $Controller->uses = array('PaginatorControllerPost', 'PaginatorControllerComment'); <del> $Controller->constructClasses(); <del> $Controller->PaginatorControllerComment->virtualFields = array( <del> 'title' => 'PaginatorControllerComment.comment' <del> ); <del> $Controller->PaginatorControllerComment->bindModel(array( <del> 'belongsTo' => array( <del> 'PaginatorControllerPost' => array( <del> 'className' => 'PaginatorControllerPost', <del> 'foreignKey' => 'article_id' <del> ) <del> ) <del> ), false); <del> <del> $Controller->paginate = array( <del> 'fields' => array( <del> 'PaginatorControllerComment.id', <del> 'title', <del> 'PaginatorControllerPost.title' <del> ), <del> ); <del> $Controller->request->params['named'] = array( <del> 'sort' => 'PaginatorControllerPost.title', <del> 'direction' => 'desc' <del> ); <del> $result = Hash::extract( <del> $Controller->paginate('PaginatorControllerComment'), <del> '{n}.PaginatorControllerComment.id' <del> ); <del> $result1 = array_splice($result, 0, 2); <del> sort($result1); <del> $this->assertEquals(array(5, 6), $result1); <del> <del> sort($result); <del> $this->assertEquals(array(1, 2, 3, 4), $result); <del> } <del> <ide> /** <ide> * test paginate() and custom find, to make sure the correct count is returned. <ide> *
1
Text
Text
fix grammatical errors
9aa5627deae64ad66a4a227a3f0c4ddba0615603
<ide><path>threejs/lessons/fr/threejs-fundamentals.md <ide> Titre: Three.js, principes de base <ide> Description: Votre première leçon sur Three.js, commençant par les principes de base <ide> TOC: Principes de base <ide> <del>Ceci est le premier article d'une série consacrée à three.js. <add>Ceci est le premier article d'une série consacrée à Three.js. <ide> [Three.js](https://threejs.org) est une bibliothèque 3D qui a pour objectif <ide> de rendre aussi facile que possible l'inclusion de contenu 3D dans une page web. <ide> <ide> Three.js est souvent confondu avec WebGL puisque la plupart du temps, mais <ide> pas toujours, elle exploite WebGL pour dessiner en 3D. <ide> [WebGL est un système très bas niveau qui ne dessine que des points, des lignes et des triangles](https://webglfundamentals.org). <ide> Faire quelque chose d'exploitable avec WebGL requiert une certaine quantité de code <del>et c'est là que three.js intervient. Elle prend en charge des choses <add>et c'est là que Three.js intervient. Elle prend en charge des choses <ide> telles que les scènes, lumières, ombres, matériaux, textures, mathématiques 3D, en bref, <ide> tout ce que vous avez à écrire par vous même si vous aviez à utiliser WebGL directement. <ide> <ide> donc la plupart des utilisateurs devraient être capables d'exécuter ce code. <ide> Si vous souhaitez exécuter ce code sur un très vieux navigateur, nous vous recommandons <ide> un transpileur tel que [Babel](https://babel.io). <ide> Bien sûr, les utilisateurs exécutant de très vieux navigateurs ont probablement <del>des machines incapables de faire tourner three.js. <add>des machines incapables de faire tourner Three.js. <ide> <ide> Lors de l'apprentissage de la plupart des langages de programmation, <ide> la première tâche que les gens font est de faire afficher à l'ordinateur <ide> `"Hello World!"`. Pour la programmation 3D, l'équivalent est de faire afficher <ide> un cube en 3D. Donc, nous commencerons par "Hello Cube!". <ide> <ide> Avant de débuter, nous allons tenter de vous donner un idée de la structure <del>d'une application three.js. Elle requiert de créer un ensemble d'objets <add>d'une application Three.js. Elle requiert de créer un ensemble d'objets <ide> et de les connecter. Voici un diagramme qui représente une application <del>three.js de petite taille: <add>Three.js de petite taille: <ide> <ide> <div class="threejs_center"><img src="resources/images/threejs-structure.svg" style="width: 768px;"></div> <ide> <ide> Voici ce qui est à remarquer dans le diagramme ci-dessus : <ide> <del>* Il y a un `Renderer`. C'est sans doute l'objet principal de three.js. Vous passez <add>* Il y a un `Renderer`. C'est sans doute l'objet principal de Three.js. Vous passez <ide> une `Scene` et une `Camera` à un `Renderer` et il effectue le rendu (dessine) de la <ide> partie de la scène 3D qui est à l'intérieur de l'espace visible (en réalité une pyramide tronquée ou *frustum*) <ide> de la caméra dans une image 2D affichée dans un canevas (*canvas*). <ide> Voici ce qui est à remarquer dans le diagramme ci-dessus : <ide> hiérarchique de type parent/enfant, arborescente, et indique où les objets apparaissent et <ide> comment ils sont orientés. Les enfants sont positionnés et orientés par rapport à leur parent. <ide> Par exemple, les roues d'une voiture sont les enfants du châssis impliquant que si l'on déplace <del> ou oriente la voiture, les roues suiveront automatiquement son déplacement. Plus de <add> ou oriente la voiture, les roues suivront automatiquement son déplacement. Plus de <ide> détails sont donnés dans [l'article sur les graphes de scène](threejs-scenegraph.html). <ide> <del> Il est à noter sur que ce diagramme `Camera` est patiellement placée dans le graphe de scène. <del> Cela permet d'attirer l'attention qu'en three.js, contrairement aux autres objets, une `Camera` ne doit <add> Il est à noter sur que ce diagramme `Camera` est patiellement placé dans le graphe de scène. <add> Cela permet d'attirer l'attention qu'en Three.js, contrairement aux autres objets, une `Camera` ne doit <ide> pas forcément faire partie du graphe de scène pour être opérationnelle. Une `Camera`, de la même <ide> façon que les autres objets, enfant d'un autre objet, se déplace et s'oriente par rapport à son <ide> objet parent. A la fin de [l'article sur les graphes de scène](threejs-scenegraph.html), l'inclusion <ide> Voici ce qui est à remarquer dans le diagramme ci-dessus : <ide> [propriétés de surface utilisées pour dessiner la géométrie](threejs-materials.html) <ide> telles que la couleur à utiliser ou le pouvoir réfléchissant (brillance). Un matériau (`Material`) <ide> peut aussi se référer à un ou plusieurs objets `Texture` dont l'utilité est, par exemple, de plaquer <del> une image sur la surface d'un géométrie. <add> une image sur la surface d'une géométrie. <ide> <ide> * Les objets `Texture` représentent généralement des images soit [chargées de fichiers image](threejs-textures.html), <ide> soit [générées par le biais d'un canevas](threejs-canvas-textures.html) ou <del> [résultent du rendu d'une autre scène](threejs-rendertargets.html). <add> [résultant du rendu d'une autre scène](threejs-rendertargets.html). <ide> <ide> * Les objets `Light` représentent [différentes sortent de lumière](threejs-lights.html). <ide> <ide> Maintenant que tout cela a été défini, nous allons présenter un exemple de type *"Hello Cube"* utilisant un <del>nombre minimum d'élements three.js : <add>nombre minimum d'élements Three.js : <ide> <ide> <div class="threejs_center"><img src="resources/images/threejs-1cube-no-light-scene.svg" style="width: 500px;"></div> <ide> <del>Tout d'abord, chargeons three.js : <add>Tout d'abord, chargeons Three.js : <ide> <ide> ```html <ide> <script type="module"> <del>import * as THREE from './resources/threejs/r127/build/three.module.js'; <add>import * as THREE from './resources/threejs/r130/build/three.module.js'; <ide> </script> <ide> ``` <ide> <ide> Il est important d'écrire `type="module"` dans la balise script. <del>Cela nous autorise l'utilisation du mot-clé `import` pour charger three.js. <add>Cela nous autorise l'utilisation du mot-clé `import` pour charger Three.js. <ide> Il y a d'autres manières de le réaliser, mais depuis la version 106 (r106), <ide> l'utilisation des modules est recommandée. Ils ont l'avantage de pouvoir <ide> facilement importer les autres modules dont ils ont besoin. Cela nous <ide> Ensuite, nous avons besoin d'une balise `<canvas>` : <ide> </body> <ide> ``` <ide> <del>Nous allons demander à three.js de dessiner dans ce canevas donc nous devons le rechercher <add>Nous allons demander à Three.js de dessiner dans ce canevas donc nous devons le rechercher <ide> dans le document html : <ide> <ide> ```html <ide> dans le canevas. Par le passé, il y a eu aussi d'autre *renderers* tels que <ide> qui utiliser WebGL pour effectuer une rendu 3D dans le canevas. <ide> <ide> Notez qu'il y a quelques détails ésotériques ici. Si vous ne passez pas un <del>canevas à three.js, il va en créer un pour vous mais vous aurez à l'ajouter <del>au document. Où l'ajouter peut dépendre de contexte d'utilisation et vous aurez <del>à modifier votre code en conséquence. Passer un canevas à three.js nous apparaît donc <add>canevas à Three.js, il va en créer un pour vous mais vous aurez à l'ajouter <add>au document. Où l'ajouter peut dépendre du contexte d'utilisation et vous aurez <add>à modifier votre code en conséquence. Passer un canevas à Three.js nous apparaît donc <ide> plus flexible. Nous pouvons mettre le canevas n'importe où et le code le retrouvera. <ide> Dans le cas contraire, nous aurons à coder où insérer le canevas, ce qui amènera <ide> probablement à changer le code si le contexte d'utilisation change. <ide> <del>Ensuite, nous avons besoin d'une caméra. Nous créerons une `PerspectiveCamera`. <add>Ensuite, nous avons besoin d'une caméra. Nous créons une `PerspectiveCamera`. <ide> <ide> ```js <ide> const fov = 75; <ide> const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); <ide> <ide> `fov` est le raccourci pour `field of view` ou champ de vision. <ide> Dans ce cas, 75 degrés d'ouverture verticale. Il est à noter que <del>la plupart des angles dans three.js sont exprimés en radians à l'exception <add>la plupart des angles dans Three.js sont exprimés en radians à l'exception <ide> de la caméra perspective. <ide> <ide> `aspect` est l'aspect de l'affichage dans le canevas. Cela sera détaillé <ide> cubes et prismes. <ide> <img src="resources/frustum-3d.svg" width="500" class="threejs_center"/> <ide> <ide> L'espacement entre les plans *near* et *far* est déterminé <del>par le champ de vue. La largeur est fixée par le champ de vue et l'aspect. <add>par le champ de vision. La largeur est fixée par le champ de vision et l'aspect. <ide> <ide> Tout ce qui est dans le *frustum* est dessiné. Ce qui est à l'extérieur ne l'est pas. <ide> <ide> Voici ce que nous voudrions voir : <ide> <ide> <img src="resources/scene-down.svg" width="500" class="threejs_center"/> <ide> <del>Dans le schéma ci-dessous, nous pouvons voir que notre caméra est placée <add>Dans le schéma ci-dessus, nous pouvons voir que notre caméra est placée <ide> en `z = 2`. Elle regarde le long de la direction -Z. <ide> Notre *frustum* démarre à 0.1 unités de la caméra et s'étend jusqu'à 5 unités devant elle. <ide> Comme le schéma est vu du haut, le champ de vue est affecté par l'aspect. <ide> Notre canvas est deux fois plus large que haut donc le champ de vue horizontal <ide> est plus grand que les 75 degrés spécifié pour le champ vertical. <ide> <del>Ensuite, nous créons une `Scene`. Dans three.js, une `Scene` est la racine <del>du graphe de scène. Tout ce que nous voulons que three.js dessine doit être ajouté <add>Ensuite, nous créons une `Scene`. Dans Three.js, une `Scene` est la racine <add>du graphe de scène. Tout ce que nous voulons que Three.js dessine doit être ajouté <ide> à la scène. Cela sera davantage détaillé dans [un futur article sur le fonctionnement des scènes](threejs-scenegraph.html). <ide> <ide> ```js <ide> const boxHeight = 1; <ide> const boxDepth = 1; <ide> const geometry = new THREE.BoxGeometry(boxWidth, boxHeight, boxDepth); <ide> ``` <del>Puis nous créons un matériau basique et fixons sa couleur. <del>Elle peut être spécifiée au format hexadécimal (6 chiffres) du standard CSS. <add>Puis nous créons un matériau basique et fixons sa couleur, qui peut être spécifiée au format hexadécimal (6 chiffres) du standard CSS. <ide> <ide> ```js <ide> const material = new THREE.MeshBasicMaterial({color: 0x44aa88}); <ide> ``` <ide> <del>Nous créons ensuite un maillage (`Mesh`). Dans three.js, il représente la combinaison <add>Nous créons ensuite un maillage (`Mesh`). Dans Three.js, il représente la combinaison <ide> d'une `Geometry` (forme de l'objet) et d'un matériau (`Material` - aspect <ide> d'un objet, brillant ou plat, quelle couleur, quelle texture appliquer, etc.) <ide> ainsi que la position, l'orientation et l'échelle de l'objet dans la scène. <ide> Finalement, nous ajoutons le maillage à la scène. <ide> scene.add(cube); <ide> ``` <ide> <del>Nous alors effectuer le rendu de la scène en appelant la fonction *render* du *renderer* <add>Nous pouvons, maintenant, effectuer le rendu de la scène en appelant la fonction *render* du *renderer* <ide> et en lui passant la scène et la caméra. <ide> <ide> ```js <ide> Voici un exemple fonctionnel : <ide> {{{example url="../threejs-fundamentals.html" }}} <ide> <ide> Il est difficile de déterminer s'il s'agit d'un cube 3D puisque nous <del>l'observons suivant l'axe -Z auquel le cube est lui même aligné. <add>l'observons suivant l'axe -Z sur lequel le cube est lui même aligné. <ide> Nous n'en voyons donc qu'une face. <ide> <del>Nous nous proposons de l'animer en le faisant tourner et cela fera clairement <add>Animons notre cube en le faisant tourner et cela fera clairement <ide> apparaître qu'il est dessiné en 3D. Pour l'animation, nous effectuerons son rendu <ide> dans une boucle de rendu en utilisant <ide> [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame). <ide> requestAnimationFrame(render); <ide> voulez animer quelque chose. Nous lui passons une fonction à appeler. <ide> Dans notre cas, c'est la fonction `render`. Le navigateur appellera cette fonction <ide> et, si nous mettons à jour l'affichage de la page, le navigateur refera le rendu <del>de la page. Dans notre cas, nous appelons la fonction `renderer.render` de three <add>de la page. Dans notre cas, nous appelons la fonction `renderer.render` de Three.js <ide> qui dessinera notre scène. <ide> <ide> `requestAnimationFrame` passe à notre fonction le temps depuis lequel la page est chargée. <ide> avec des secondes. C'est pourquoi, nous l'avons converti. <ide> <ide> A présent, nous appliquons sur le cube des rotations le long des axes X et Y en fonction du temps écoulé. <ide> Les angles de rotation sont exprimés en [radians](https://en.wikipedia.org/wiki/Radian). <del>Sachant que 2 pi radians fait faire un tour complet, notre cube effectuera une rotation complète <del>sur chaque axe en à peu près 6.28 secondes. <add>Sachant que 2 PI radians fait faire un tour complet, notre cube effectuera une rotation complète <add>sur chaque axe en, à peu près, 6,28 secondes. <ide> <ide> Nous effectuons alors le rendu de la scène et <ide> demandons une autre image pour l'animation afin de poursuivre notre boucle. <ide> Cela devrait à présent apparaître très clairement en 3D. <ide> Pour le sport, ajoutons 2 cubes supplémentaires. <ide> <ide> Nous partageons la même géométrie pour chaque cube mais un matériau différent par cube <del>de sorte que chacun d'eux soit affecté d'une couleur différente. <add>afin qu'ils aient une couleur différente. <ide> <del>Tout d'abord, nous définissons une fonction qui crée une nouveau matériau <add>Tout d'abord, nous définissons une fonction qui crée un nouveau matériau <ide> avec la couleur spécifiée. Ensuite, elle créé un maillage à partir de la <ide> géométrie spécifiée, l'ajoute à la scène et change sa position en X. <ide> <ide> function makeInstance(geometry, color, x) { <ide> } <ide> ``` <ide> <del>Ensuite, nous l'appellerons à 3 reprises avec 3 différentes couleurs <del>et positions en X, puis nous conserverons ces instances de `Mesh` dans un tableau. <add>Ensuite, nous l'appellons à 3 reprises avec 3 différentes couleurs <add>et positions en X, puis nous conservons ces instances de `Mesh` dans un tableau. <ide> <ide> ```js <ide> const cubes = [ <ide> const cubes = [ <ide> ]; <ide> ``` <ide> <del>Enfin, nous ferons tourner ces 3 cubes dans notre fonction de rendu. <add>Enfin, nous faisons tourner ces 3 cubes dans notre fonction de rendu. <ide> Nous calculons une rotation légèrement différente pour chacun d'eux. <ide> <ide> ```js <ide> et voilà le résultat. <ide> <ide> Si nous le comparons au schéma précédent, nous constatons qu'il <ide> est conforme à nos attentes. Les cubes en X = -2 et X = +2 <del>sont partiellement en dehors du *frustum*. Ils sont également <del>exagérément déformés puisque le champ de vue dépeint au travers du <add>sont partiellement en dehors du *frustum*. Ils sont, de plus, <add>exagérément déformés puisque le champ de vision dépeint au travers du <ide> canevas est extrême. <ide> <ide> A présent, notre programme est schématisé par la figure suivante : <ide> Nous espérons que cette courte introduction vous aide à débuter. <ide> [La prochaine étape consiste à rendre notre code réactif et donc adaptable à de multiples situations](threejs-responsive.html). <ide> <ide> <div class="threejs_bottombar"> <del><h3>es6 modules, three.js et structure de dossiers</h3> <del><p>Depuis la version 106 (r106), l'utilisation de three.js privilégie les <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">modules es6</a>.</p> <add><h3>es6 modules, Three.js et structure de dossiers</h3> <add><p>Depuis la version 106 (r106), l'utilisation de Three.js privilégie les <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">modules es6</a>.</p> <ide> <p> <ide> Ils sont chargés via le mot-clé <code>import</code> dans un script ou en ligne <ide> par le biais d'une balise <code>&lt;script type="module"&gt;</code>. Voici un exemple d'utilisation avec les deux : <ide> ce qui est différent des autres balises telles que <code>&lt;img&gt;</code> et <ide> </p> <ide> <p> <ide> Les références à un même script ne seront chargées qu'une seule fois à partir du <del>moment où leur chemin absolu est exactement identique. Pour three.js, cela veut <add>moment où leur chemin absolu est exactement identique. Pour Three.js, cela veut <ide> dire qu'il est nécessaire de mettre toutes les bibliothèques d'exemples dans une <ide> structure correcte pour les dossiers : <ide> </p> <ide> import * as THREE from '../../../build/three.module.js'; <ide> </pre> <ide> <p> <ide> Utiliser la même structure permet de s'assurer, lors de l'importation de <del>three et d'une autre bibliothèque d'exemple, qu'ils référenceront le même fichier <add>Three.js et d'une autre bibliothèque d'exemple, qu'ils référenceront le même fichier <ide> three.module.js. <ide> </p> <ide> <pre class="prettyprint"> <ide> import {OrbitControls} from 'https://unpkg.com/[email protected]/examples/jsm/contro <ide> vous pouvez consulter <a href="https://r105.threejsfundamentals.org">une version plus ancienne de ce site</a>. <ide> Three.js a pour politique de ne pas s'embarrasser avec la rétro compatibilité. <ide> Cela suppose que vous utilisez une version spécifique de la bibliothèque que vous aurez téléchargé et <del>incorporé à votre projet. Lors de la mise à jour vers une nouvelle version de three.js, <add>incorporé à votre projet. Lors de la mise à jour vers une nouvelle version de Three.js, <ide> vous pouvez lire le <a href="https://github.com/mrdoob/three.js/wiki/Migration-Guide">guide de migration</a> <ide> pour voir ce que vous avez à changer. Cela nécessiterait beaucoup de travail de maintenir <ide> à la fois une version de ce site avec les modules es6 et une autre avec le script global.
1
Ruby
Ruby
improve class overview for tabledefinition
b810349c8dbc8d27602181832466bb2a518191a0
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb <ide> def add_column_options!(sql, options) <ide> end <ide> end <ide> <del> # Represents a SQL table in an abstract way. <del> # Columns are stored as a ColumnDefinition in the +columns+ attribute. <add> # Represents the schema of an SQL table in an abstract way. This class <add> # provides methods for manipulating the schema representation. <add> # <add> # Inside migration files, the +t+ object in +create_table+ and <add> # +change_table+ is actually of this type: <add> # <add> # class SomeMigration < ActiveRecord::Migration <add> # def self.up <add> # create_table :foo do |t| <add> # puts t.class # => "ActiveRecord::ConnectionAdapters::TableDefinition" <add> # end <add> # end <add> # <add> # def self.down <add> # ... <add> # end <add> # end <add> # <add> # The table definitions <add> # The Columns are stored as a ColumnDefinition in the +columns+ attribute. <ide> class TableDefinition <add> # An array of ColumnDefinition objects, representing the column changes <add> # that have been defined. <ide> attr_accessor :columns <ide> <ide> def initialize(base)
1
Python
Python
add extra links endpoint
2b6191287f0ba3f45bfd82aa8c7849ca77145fca
<ide><path>airflow/api_connexion/endpoints/extra_link_endpoint.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> <del># TODO(mik-laj): We have to implement it. <del># Do you want to help? Please look at: https://github.com/apache/airflow/issues/8140 <add>from flask import current_app <ide> <add>from airflow import DAG <add>from airflow.api_connexion.exceptions import NotFound <add>from airflow.exceptions import TaskNotFound <add>from airflow.models.dagbag import DagBag <add>from airflow.models.dagrun import DagRun as DR <add>from airflow.utils.session import provide_session <ide> <del>def get_extra_links(): <add> <add>@provide_session <add>def get_extra_links(dag_id: str, dag_run_id: str, task_id: str, session): <ide> """ <ide> Get extra links for task instance <ide> """ <del> raise NotImplementedError("Not implemented yet.") <add> dagbag: DagBag = current_app.dag_bag <add> dag: DAG = dagbag.get_dag(dag_id) <add> if not dag: <add> raise NotFound("DAG not found", detail=f'DAG with ID = "{dag_id}" not found') <add> <add> try: <add> task = dag.get_task(task_id) <add> except TaskNotFound: <add> raise NotFound("Task not found", detail=f'Task with ID = "{task_id}" not found') <add> <add> execution_date = ( <add> session.query(DR.execution_date).filter(DR.dag_id == dag_id).filter(DR.run_id == dag_run_id).scalar() <add> ) <add> if not execution_date: <add> raise NotFound("DAG Run not found", detail=f'DAG Run with ID = "{dag_run_id}" not found') <add> <add> all_extra_link_pairs = ( <add> (link_name, task.get_extra_links(execution_date, link_name)) for link_name in task.extra_links <add> ) <add> all_extra_links = { <add> link_name: link_url if link_url else None for link_name, link_url in all_extra_link_pairs <add> } <add> return all_extra_links <ide><path>tests/api_connexion/endpoints/test_extra_link_endpoint.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> import unittest <add>from unittest import mock <add>from urllib.parse import quote_plus <ide> <del>import pytest <add>from parameterized import parameterized <ide> <add>from airflow import DAG <add>from airflow.models.baseoperator import BaseOperatorLink <add>from airflow.models.dagrun import DagRun <add>from airflow.models.xcom import XCom <add>from airflow.plugins_manager import AirflowPlugin <add>from airflow.providers.google.cloud.operators.bigquery import BigQueryExecuteQueryOperator <add>from airflow.utils.dates import days_ago <add>from airflow.utils.session import provide_session <add>from airflow.utils.timezone import datetime <add>from airflow.utils.types import DagRunType <ide> from airflow.www import app <add>from tests.test_utils.db import clear_db_runs, clear_db_xcom <add>from tests.test_utils.mock_plugins import mock_plugin_manager <ide> <ide> <ide> class TestGetExtraLinks(unittest.TestCase): <ide> @classmethod <ide> def setUpClass(cls) -> None: <ide> super().setUpClass() <del> cls.app = app.create_app(testing=True) # type:ignore <add> with mock.patch.dict("os.environ", SKIP_DAGS_PARSING="True"): <add> cls.app = app.create_app(testing=True) # type:ignore <add> <add> @provide_session <add> def setUp(self, session) -> None: <add> self.default_time = datetime(2020, 1, 1) <add> <add> clear_db_runs() <add> clear_db_xcom() <add> <add> self.dag = self._create_dag() <add> self.app.dag_bag.dags = {self.dag.dag_id: self.dag} # type: ignore # pylint: disable=no-member <add> self.app.dag_bag.sync_to_db() # type: ignore # pylint: disable=no-member <add> <add> dr = DagRun( <add> dag_id=self.dag.dag_id, <add> run_id="TEST_DAG_RUN_ID", <add> execution_date=self.default_time, <add> run_type=DagRunType.MANUAL.value, <add> ) <add> session.add(dr) <add> session.commit() <ide> <del> def setUp(self) -> None: <ide> self.client = self.app.test_client() # type:ignore <ide> <del> @pytest.mark.skip(reason="Not implemented yet") <add> def tearDown(self) -> None: <add> super().tearDown() <add> clear_db_runs() <add> clear_db_xcom() <add> <add> @staticmethod <add> def _create_dag(): <add> with DAG(dag_id="TEST_DAG_ID", default_args=dict(start_date=days_ago(2),)) as dag: <add> BigQueryExecuteQueryOperator(task_id="TEST_SINGLE_QUERY", sql="SELECT 1") <add> BigQueryExecuteQueryOperator(task_id="TEST_MULTIPLE_QUERY", sql=["SELECT 1", "SELECT 2"]) <add> return dag <add> <add> @parameterized.expand( <add> [ <add> ( <add> "missing_dag", <add> "/api/v1/dags/INVALID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links", <add> "DAG not found", <add> 'DAG with ID = "INVALID" not found', <add> ), <add> ( <add> "missing_dag_run", <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/INVALID/taskInstances/TEST_SINGLE_QUERY/links", <add> "DAG Run not found", <add> 'DAG Run with ID = "INVALID" not found', <add> ), <add> ( <add> "missing_task", <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/INVALID/links", <add> "Task not found", <add> 'Task with ID = "INVALID" not found', <add> ), <add> ] <add> ) <add> def test_should_response_404(self, name, url, expected_title, expected_detail): <add> del name <add> response = self.client.get(url) <add> <add> self.assertEqual(404, response.status_code) <add> self.assertEqual( <add> {"detail": expected_detail, "status": 404, "title": expected_title, "type": "about:blank"}, <add> response.json, <add> ) <add> <add> @mock_plugin_manager(plugins=[]) <ide> def test_should_response_200(self): <add> XCom.set( <add> key="job_id", <add> value="TEST_JOB_ID", <add> execution_date=self.default_time, <add> task_id="TEST_SINGLE_QUERY", <add> dag_id=self.dag.dag_id, <add> ) <add> response = self.client.get( <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links" <add> ) <add> <add> self.assertEqual(200, response.status_code, response.data) <add> self.assertEqual( <add> {"BigQuery Console": "https://console.cloud.google.com/bigquery?j=TEST_JOB_ID"}, response.json <add> ) <add> <add> @mock_plugin_manager(plugins=[]) <add> def test_should_response_200_missing_xcom(self): <add> response = self.client.get( <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links" <add> ) <add> <add> self.assertEqual(200, response.status_code, response.data) <add> self.assertEqual( <add> {"BigQuery Console": None}, response.json, <add> ) <add> <add> @mock_plugin_manager(plugins=[]) <add> def test_should_response_200_multiple_links(self): <add> XCom.set( <add> key="job_id", <add> value=["TEST_JOB_ID_1", "TEST_JOB_ID_2"], <add> execution_date=self.default_time, <add> task_id="TEST_MULTIPLE_QUERY", <add> dag_id=self.dag.dag_id, <add> ) <add> response = self.client.get( <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_MULTIPLE_QUERY/links" <add> ) <add> <add> self.assertEqual(200, response.status_code, response.data) <add> self.assertEqual( <add> { <add> "BigQuery Console #1": "https://console.cloud.google.com/bigquery?j=TEST_JOB_ID_1", <add> "BigQuery Console #2": "https://console.cloud.google.com/bigquery?j=TEST_JOB_ID_2", <add> }, <add> response.json, <add> ) <add> <add> @mock_plugin_manager(plugins=[]) <add> def test_should_response_200_multiple_links_missing_xcom(self): <ide> response = self.client.get( <del> "/dags/TEST_DG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_TASK_ID/links" <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_MULTIPLE_QUERY/links" <ide> ) <del> assert response.status_code == 200 <add> <add> self.assertEqual(200, response.status_code, response.data) <add> self.assertEqual( <add> {"BigQuery Console #1": None, "BigQuery Console #2": None}, response.json, <add> ) <add> <add> def test_should_response_200_support_plugins(self): <add> class GoogleLink(BaseOperatorLink): <add> name = "Google" <add> <add> def get_link(self, operator, dttm): <add> return "https://www.google.com" <add> <add> class S3LogLink(BaseOperatorLink): <add> name = "S3" <add> operators = [BigQueryExecuteQueryOperator] <add> <add> def get_link(self, operator, dttm): <add> return "https://s3.amazonaws.com/airflow-logs/{dag_id}/{task_id}/{execution_date}".format( <add> dag_id=operator.dag_id, <add> task_id=operator.task_id, <add> execution_date=quote_plus(dttm.isoformat()), <add> ) <add> <add> class AirflowTestPlugin(AirflowPlugin): <add> name = "test_plugin" <add> global_operator_extra_links = [ <add> GoogleLink(), <add> ] <add> operator_extra_links = [ <add> S3LogLink(), <add> ] <add> <add> with mock_plugin_manager(plugins=[AirflowTestPlugin]): <add> response = self.client.get( <add> "/api/v1/dags/TEST_DAG_ID/dagRuns/TEST_DAG_RUN_ID/taskInstances/TEST_SINGLE_QUERY/links" <add> ) <add> <add> self.assertEqual(200, response.status_code, response.data) <add> self.assertEqual( <add> { <add> "BigQuery Console": None, <add> "Google": "https://www.google.com", <add> "S3": ( <add> "https://s3.amazonaws.com/airflow-logs/" <add> "TEST_DAG_ID/TEST_SINGLE_QUERY/2020-01-01T00%3A00%3A00%2B00%3A00" <add> ), <add> }, <add> response.json, <add> ) <ide><path>tests/cli/commands/test_plugins_command.py <ide> <ide> import io <ide> import unittest <del>from contextlib import ExitStack, contextmanager, redirect_stdout <del>from unittest import mock <add>from contextlib import redirect_stdout <ide> <ide> from airflow.cli import cli_parser <ide> from airflow.cli.commands import plugins_command <ide> from airflow.models.baseoperator import BaseOperator <ide> from airflow.plugins_manager import AirflowPlugin <add>from tests.test_utils.mock_plugins import mock_plugin_manager <ide> <ide> <ide> class PluginOperator(BaseOperator): <ide> class TestPlugin(AirflowPlugin): <ide> operators = [PluginOperator] <ide> <ide> <del>PLUGINS_MANAGER_NULLABLE_ATTRIBUTES = [ <del> "plugins", <del> "operators_modules", <del> "sensors_modules", <del> "hooks_modules", <del> "macros_modules", <del> "executors_modules", <del> "admin_views", <del> "flask_blueprints", <del> "menu_links", <del> "flask_appbuilder_views", <del> "flask_appbuilder_menu_links", <del> "global_operator_extra_links", <del> "operator_extra_links", <del> "registered_operator_link_classes", <del>] <del> <del> <del>@contextmanager <del>def keep_plugin_manager_state(): <del> """ <del> Protects the initial state and sets the default state for the airflow.plugins module. <del> <del> airflow.plugins_manager uses many global variables. To avoid side effects, this decorator performs <del> the following operations: <del> <del> 1. saves variables state, <del> 2. set variables to default value, <del> 3. executes context code, <del> 4. restores the state of variables to the state from point 1. <del> <del> Use this context if you want your test to not have side effects in airflow.plugins_manager, and <del> other tests do not affect the results of this test. <del> """ <del> with ExitStack() as exit_stack: <del> for attr in PLUGINS_MANAGER_NULLABLE_ATTRIBUTES: <del> exit_stack.enter_context( # pylint: disable=no-member <del> mock.patch(f"airflow.plugins_manager.{attr}", None) <del> ) <del> exit_stack.enter_context( # pylint: disable=no-member <del> mock.patch("airflow.plugins_manager.import_errors", {}) <del> ) <del> <del> yield <del> <del> <ide> class TestPluginsCommand(unittest.TestCase): <ide> @classmethod <ide> def setUpClass(cls): <ide> cls.parser = cli_parser.get_parser() <ide> <del> @keep_plugin_manager_state() <del> @mock.patch('airflow.plugins_manager.plugins', []) <add> @mock_plugin_manager(plugins=[]) <ide> def test_should_display_no_plugins(self): <ide> with redirect_stdout(io.StringIO()) as temp_stdout: <ide> plugins_command.dump_plugins(self.parser.parse_args(['plugins'])) <ide> def test_should_display_no_plugins(self): <ide> self.assertIn("PLUGINS MANGER:", stdout) <ide> self.assertIn("PLUGINS:", stdout) <ide> <del> @keep_plugin_manager_state() <del> @mock.patch('airflow.plugins_manager.plugins', [TestPlugin]) <add> @mock_plugin_manager(plugins=[TestPlugin]) <ide> def test_should_display_one_plugins(self): <ide> with redirect_stdout(io.StringIO()) as temp_stdout: <ide> plugins_command.dump_plugins(self.parser.parse_args(['plugins'])) <ide><path>tests/test_utils/db.py <ide> # under the License. <ide> from airflow.models import ( <ide> Connection, DagModel, DagRun, DagTag, Pool, RenderedTaskInstanceFields, SlaMiss, TaskInstance, Variable, <del> errors, <add> XCom, errors, <ide> ) <ide> from airflow.models.dagcode import DagCode <ide> from airflow.utils.db import add_default_pool_if_not_exists, create_default_connections <ide> def clear_rendered_ti_fields(): <ide> def clear_db_import_errors(): <ide> with create_session() as session: <ide> session.query(errors.ImportError).delete() <add> <add> <add>def clear_db_xcom(): <add> with create_session() as session: <add> session.query(XCom).delete() <ide><path>tests/test_utils/mock_plugins.py <add># Licensed to the Apache Software Foundation (ASF) under one <add># or more contributor license agreements. See the NOTICE file <add># distributed with this work for additional information <add># regarding copyright ownership. The ASF licenses this file <add># to you under the Apache License, Version 2.0 (the <add># "License"); you may not use this file except in compliance <add># with the License. You may obtain a copy of the License at <add># <add># http://www.apache.org/licenses/LICENSE-2.0 <add># <add># Unless required by applicable law or agreed to in writing, <add># software distributed under the License is distributed on an <add># "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY <add># KIND, either express or implied. See the License for the <add># specific language governing permissions and limitations <add># under the License. <add> <add>from contextlib import ExitStack, contextmanager <add>from unittest import mock <add> <add>PLUGINS_MANAGER_NULLABLE_ATTRIBUTES = [ <add> "plugins", <add> "operators_modules", <add> "sensors_modules", <add> "hooks_modules", <add> "macros_modules", <add> "executors_modules", <add> "admin_views", <add> "flask_blueprints", <add> "menu_links", <add> "flask_appbuilder_views", <add> "flask_appbuilder_menu_links", <add> "global_operator_extra_links", <add> "operator_extra_links", <add> "registered_operator_link_classes", <add>] <add> <add> <add>@contextmanager <add>def mock_plugin_manager(**kwargs): <add> """ <add> Protects the initial state and sets the default state for the airflow.plugins module. <add> <add> You can also overwrite variables by passing a keyword argument. <add> <add> airflow.plugins_manager uses many global variables. To avoid side effects, this decorator performs <add> the following operations: <add> <add> 1. saves variables state, <add> 2. set variables to default value, <add> 3. executes context code, <add> 4. restores the state of variables to the state from point 1. <add> <add> Use this context if you want your test to not have side effects in airflow.plugins_manager, and <add> other tests do not affect the results of this test. <add> """ <add> illegal_arguments = set(kwargs.keys()) - set(PLUGINS_MANAGER_NULLABLE_ATTRIBUTES) - {"import_errors"} <add> if illegal_arguments: <add> raise TypeError( <add> f"TypeError: mock_plugin_manager got an unexpected keyword arguments: {illegal_arguments}" <add> ) <add> with ExitStack() as exit_stack: <add> for attr in PLUGINS_MANAGER_NULLABLE_ATTRIBUTES: <add> exit_stack.enter_context( # pylint: disable=no-member <add> mock.patch(f"airflow.plugins_manager.{attr}", kwargs.get(attr, None)) <add> ) <add> exit_stack.enter_context( # pylint: disable=no-member <add> mock.patch("airflow.plugins_manager.import_errors", kwargs.get("import_errors", {})) <add> ) <add> <add> yield
5
PHP
PHP
add test for overwriting scalar values with load()
037382ebff35e1ee6c46d872b14f5e728168d83b
<ide><path>tests/TestCase/Core/ConfigureTest.php <ide> public function testLoadMergeWithExistingData() { <ide> Configure::write('my_key', 'value'); <ide> Configure::write('Read', 'old'); <ide> Configure::write('Deep.old', 'old'); <add> Configure::write('TestAcl.classname', 'old'); <ide> <ide> Configure::load('var_test', 'test', true); <ide> $this->assertEquals('value', Configure::read('Read'), 'Should load new data.'); <ide> $this->assertEquals('buried', Configure::read('Deep.Deeper.Deepest'), 'Should load new data'); <ide> $this->assertEquals('old', Configure::read('Deep.old'), 'Should not destroy old data.'); <ide> $this->assertEquals('value', Configure::read('my_key'), 'Should not destroy data.'); <add> $this->assertEquals('Original', Configure::read('TestAcl.classname'), 'No arrays'); <ide> } <ide> <ide> /**
1
PHP
PHP
bind container into itself
d73fbbc7be29c584ed5545c8d6f673ef84584a6b
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function __construct(Request $request = null) <ide> $this->instance('request', $request = Request::createFromGlobals()); <ide> <ide> $this->registerBaseServiceProviders(); <add> <add> $this->instance('Illuminate\Container\Container', $this); <ide> } <ide> <ide> /**
1
PHP
PHP
add test case for
f2c84bca82a731147f191835040a316d2ee76862
<ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testInputTemplateVars() <ide> $this->assertHtml($expected, $result); <ide> } <ide> <add> /** <add> * Test ensuring template variables work in template files loaded <add> * during input(). <add> * <add> * @return void <add> */ <add> public function testInputTemplatesFromFile() <add> { <add> $result = $this->Form->input('title', [ <add> 'templates' => 'test_templates', <add> 'templateVars' => [ <add> 'forcontainer' => 'container-data' <add> ] <add> ]); <add> $expected = [ <add> 'div' => ['class'], <add> 'label' => ['for'], <add> 'Title', <add> '/label', <add> 'input' => ['name', 'type' => 'text', 'id'], <add> 'container-data', <add> '/div', <add> ]; <add> $this->assertHtml($expected, $result); <add> } <add> <ide> /** <ide> * Test using template vars in inputSubmit and submitContainer template. <ide> * <ide><path>tests/test_app/config/test_templates.php <ide> */ <ide> return [ <ide> 'link' => '<a href="{{url}}">{{text}}</a>', <add> 'inputContainer' => '<div class="input {{type}}{{required}}">{{content}}{{forcontainer}}</div>' <ide> ];
2
Go
Go
add err checks for port allocator tests
555416fd02b9e062385dcdaf0c4b9f5de61df388
<ide><path>runtime/networkdriver/portallocator/portallocator_test.go <ide> func TestPortAllocation(t *testing.T) { <ide> } <ide> <ide> port, err = RequestPort(ip, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <ide> port2, err := RequestPort(ip, "tcp", port+1) <add> if err != nil { <add> t.Fatal(err) <add> } <ide> port3, err := RequestPort(ip, "tcp", 0) <add> if err != nil { <add> t.Fatal(err) <add> } <ide> if port3 == port2 { <ide> t.Fatal("Requesting a dynamic port should never allocate a used port") <ide> }
1
Ruby
Ruby
add missing require
4c3a6c6022b2ad5e71b7315c275860400af85f20
<ide><path>Library/Homebrew/cmd/outdated.rb <ide> require "formula" <ide> require "keg" <del>require "migrator" <ide> <ide> module Homebrew <ide> def outdated <ide><path>Library/Homebrew/formula.rb <ide> require "tap" <ide> require "formula_renames" <ide> require "keg" <add>require "migrator" <ide> <ide> # A formula provides instructions and metadata for Homebrew to install a piece <ide> # of software. Every Homebrew formula is a {Formula}.
2
PHP
PHP
update redis tests
2ed9ff925a5dda66063d335a20eac3262d688d4e
<ide><path>lib/Cake/Cache/Engine/RedisEngine.php <ide> <?php <ide> /** <del> * Redis storage engine for cache <del> * <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) : Rapid Development Framework (http://cakephp.org) <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> * <ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://cakephp.org CakePHP(tm) Project <del> * @package Cake.Cache.Engine <ide> * @since CakePHP(tm) v 2.2 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <ide> <ide> namespace Cake\Cache\Engine; <add> <ide> use Cake\Cache\CacheEngine; <ide> <ide> /** <ide><path>lib/Cake/Test/TestCase/Cache/Engine/RedisEngineTest.php <ide> <?php <ide> /** <del> * RedisEngineTest file <del> * <del> * PHP 5 <del> * <ide> * CakePHP(tm) Tests <http://book.cakephp.org/view/1196/Testing> <ide> * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * <ide> * <ide> * @copyright Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org) <ide> * @link http://book.cakephp.org/view/1196/Testing CakePHP(tm) Tests <del> * @package Cake.Test.Case.Cache.Engine <ide> * @since CakePHP(tm) v 2.2 <ide> * @license MIT License (http://www.opensource.org/licenses/mit-license.php) <ide> */ <ide> class RegisEngineTest extends TestCase { <ide> * @return void <ide> */ <ide> public function setUp() { <add> parent::setUp(); <ide> $this->skipIf(!class_exists('Redis'), 'Redis is not installed or configured properly.'); <ide> <del> $this->_cacheDisable = Configure::read('Cache.disable'); <ide> Configure::write('Cache.disable', false); <del> Cache::config('redis', array( <del> 'engine' => 'Cake\Cache\Redis', <add> Configure::write('Cache.redis', array( <add> 'engine' => 'Cake\Cache\Engine\RedisEngine', <ide> 'prefix' => 'cake_', <ide> 'duration' => 3600 <ide> )); <ide> public function setUp() { <ide> * @return void <ide> */ <ide> public function tearDown() { <del> Configure::write('Cache.disable', $this->_cacheDisable); <del> Cache::drop(''); <add> parent::tearDown(); <add> Cache::drop('redis'); <ide> Cache::drop('redis_groups'); <ide> Cache::drop('redis_helper'); <del> Cache::config('default'); <ide> } <ide> <ide> /** <ide> public function testSettings() { <ide> 'duration' => 3600, <ide> 'probability' => 100, <ide> 'groups' => array(), <del> 'engine' => 'Redis', <add> 'engine' => 'Cake\Cache\Engine\RedisEngine', <ide> 'server' => '127.0.0.1', <ide> 'port' => 6379, <ide> 'timeout' => 0, <ide> public function testConnect() { <ide> * @return void <ide> */ <ide> public function testReadAndWriteCache() { <del> Cache::set(array('duration' => 1), null, 'redis'); <add> Cache::set(['duration' => 1], 'redis'); <ide> <ide> $result = Cache::read('test', 'redis'); <ide> $expecting = ''; <ide> public function testExpiry() { <ide> $result = Cache::read('other_test', 'redis'); <ide> $this->assertFalse($result); <ide> <del> Cache::config('redis', array('duration' => '+1 second')); <add> Cache::set(['duration' => '+1 second'], 'redis'); <ide> sleep(2); <ide> <ide> $result = Cache::read('other_test', 'redis'); <ide> $this->assertFalse($result); <ide> <del> Cache::config('redis', array('duration' => '+29 days')); <add> Cache::set(['duration' => '+29 days'], 'redis'); <ide> $data = 'this is a test of the emergency broadcasting system'; <ide> $result = Cache::write('long_expiry_test', $data, 'redis'); <ide> $this->assertTrue($result); <ide> public function testExpiry() { <ide> $result = Cache::read('long_expiry_test', 'redis'); <ide> $expecting = $data; <ide> $this->assertEquals($expecting, $result); <del> <del> Cache::config('redis', array('duration' => 3600)); <ide> } <ide> <ide> /** <ide> public function testIncrement() { <ide> * @return void <ide> */ <ide> public function testClear() { <del> Cache::config('redis2', array( <add> Configure::write('Cache.redis2', array( <ide> 'engine' => 'Redis', <ide> 'prefix' => 'cake2_', <ide> 'duration' => 3600 <ide> public function testClear() { <ide> * @return void <ide> */ <ide> public function testZeroDuration() { <del> Cache::config('redis', array('duration' => 0)); <add> Cache::set(['duration' => 0], 'redis'); <ide> $result = Cache::write('test_key', 'written!', 'redis'); <ide> <ide> $this->assertTrue($result); <ide> public function testZeroDuration() { <ide> * @return void <ide> */ <ide> public function testGroupReadWrite() { <del> Cache::config('redis_groups', array( <add> Configure::write('Cache.redis_groups', [ <ide> 'engine' => 'Redis', <ide> 'duration' => 3600, <del> 'groups' => array('group_a', 'group_b'), <add> 'groups' => ['group_a', 'group_b'], <ide> 'prefix' => 'test_' <del> )); <del> Cache::config('redis_helper', array( <add> ]); <add> Configure::write('Cache.redis_helper', [ <ide> 'engine' => 'Redis', <ide> 'duration' => 3600, <ide> 'prefix' => 'test_' <del> )); <add> ]); <ide> $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); <ide> $this->assertEquals('value', Cache::read('test_groups', 'redis_groups')); <ide> <ide> public function testGroupReadWrite() { <ide> * @return void <ide> */ <ide> public function testGroupDelete() { <del> Cache::config('redis_groups', array( <add> Configure::write('Cache.redis_groups', [ <ide> 'engine' => 'Redis', <ide> 'duration' => 3600, <del> 'groups' => array('group_a', 'group_b') <del> )); <add> 'groups' => ['group_a', 'group_b'] <add> ]); <ide> $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); <ide> $this->assertEquals('value', Cache::read('test_groups', 'redis_groups')); <ide> $this->assertTrue(Cache::delete('test_groups', 'redis_groups')); <ide> public function testGroupDelete() { <ide> * @return void <ide> **/ <ide> public function testGroupClear() { <del> Cache::config('redis_groups', array( <add> Configure::write('Cache.redis_groups', [ <ide> 'engine' => 'Redis', <ide> 'duration' => 3600, <del> 'groups' => array('group_a', 'group_b') <del> )); <add> 'groups' => ['group_a', 'group_b'] <add> ]); <ide> <ide> $this->assertTrue(Cache::write('test_groups', 'value', 'redis_groups')); <ide> $this->assertTrue(Cache::clearGroup('group_a', 'redis_groups'));
2
Text
Text
add retry-after to release notes. refs
21a0a826bba3df01e72ea8b0390e05d50cf9a854
<ide><path>docs/topics/2.4-accouncement.md <ide> There are also a number of other features and bugfixes as [listed in the release <ide> <ide> Smarter [client IP identification for throttling][client-ip-identification], with the addition of the `NUM_PROXIES` setting. <ide> <add>Added the standardized `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Trottle-Wait-Seconds` header which will be fully deprecated in 3.0. <add> <ide> ## Deprecations <ide> <ide> All API changes in 2.3 that previously raised `PendingDeprecationWarning` will now raise a `DeprecationWarning`, which is loud by default. <ide><path>docs/topics/release-notes.md <ide> You can determine your currently installed version using `pip freeze`: <ide> * Support customizable view name and description functions, using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings. <ide> * Added `NUM_PROXIES` setting for smarter client IP identification. <ide> * Added `MAX_PAGINATE_BY` setting and `max_paginate_by` generic view attribute. <add>* Added `Retry-After` header to throttled responses, as per [RFC 6585](http://tools.ietf.org/html/rfc6585). This should now be used in preference to the custom `X-Trottle-Wait-Seconds` header which will be fully deprecated in 3.0. <ide> * Added `cache` attribute to throttles to allow overriding of default cache. <ide> * Added `lookup_value_regex` attribute to routers, to allow the URL argument matching to be constrainted by the user. <ide> * Added `allow_none` option to `CharField`.
2
Javascript
Javascript
flow strict touchablebounce
45c51835d69e111b67b4fcf1af39a13f7df1ee48
<ide><path>Libraries/Components/Touchable/TouchableBounce.js <ide> const createReactClass = require('create-react-class'); <ide> import type {EdgeInsetsProp} from 'EdgeInsetsPropType'; <ide> import type {ViewStyleProp} from 'StyleSheet'; <ide> import type {Props as TouchableWithoutFeedbackProps} from 'TouchableWithoutFeedback'; <del> <del>type Event = Object; <add>import type {PressEvent} from 'CoreEventTypes'; <ide> <ide> type State = { <ide> animationID: ?number, <ide> const PRESS_RETENTION_OFFSET = {top: 20, left: 20, right: 20, bottom: 30}; <ide> type Props = $ReadOnly<{| <ide> ...TouchableWithoutFeedbackProps, <ide> <del> onPressWithCompletion?: ?Function, <del> onPressAnimationComplete?: ?Function, <add> onPressWithCompletion?: ?(fn: () => void) => void, <add> onPressAnimationComplete?: ?() => void, <ide> pressRetentionOffset?: ?EdgeInsetsProp, <ide> releaseVelocity?: ?number, <ide> releaseBounciness?: ?number, <ide> const TouchableBounce = ((createReactClass({ <ide> value: number, <ide> velocity: number, <ide> bounciness: number, <del> callback?: ?Function, <add> callback?: ?() => void, <ide> ) { <ide> Animated.spring(this.state.scale, { <ide> toValue: value, <ide> const TouchableBounce = ((createReactClass({ <ide> * `Touchable.Mixin` self callbacks. The mixin will invoke these if they are <ide> * defined on your component. <ide> */ <del> touchableHandleActivePressIn: function(e: Event) { <add> touchableHandleActivePressIn: function(e: PressEvent) { <ide> this.bounceTo(0.93, 0.1, 0); <ide> this.props.onPressIn && this.props.onPressIn(e); <ide> }, <ide> <del> touchableHandleActivePressOut: function(e: Event) { <add> touchableHandleActivePressOut: function(e: PressEvent) { <ide> this.bounceTo(1, 0.4, 0); <ide> this.props.onPressOut && this.props.onPressOut(e); <ide> }, <ide> <del> touchableHandlePress: function(e: Event) { <add> touchableHandlePress: function(e: PressEvent) { <ide> const onPressWithCompletion = this.props.onPressWithCompletion; <ide> if (onPressWithCompletion) { <ide> onPressWithCompletion(() => { <ide> const TouchableBounce = ((createReactClass({ <ide> return this.props.pressRetentionOffset || PRESS_RETENTION_OFFSET; <ide> }, <ide> <del> touchableGetHitSlop: function(): ?Object { <add> touchableGetHitSlop: function(): ?EdgeInsetsProp { <ide> return this.props.hitSlop; <ide> }, <ide>
1
Javascript
Javascript
add name to prop hooks as well
217a7abc43967cb860fc0dccee13b475de81b07d
<ide><path>src/attributes.js <ide> jQuery.extend({ <ide> hooks = jQuery.propHooks[ name ]; <ide> <ide> if ( value !== undefined ) { <del> if ( hooks && "set" in hooks && (ret = hooks.set( elem, value )) !== undefined ) { <add> if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { <ide> return ret; <ide> <ide> } else { <ide> return (elem[ name ] = value); <ide> } <ide> <ide> } else { <del> if ( hooks && "get" in hooks && (ret = hooks.get( elem )) !== undefined ) { <add> if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== undefined ) { <ide> return ret; <ide> <ide> } else {
1
Ruby
Ruby
fix formula#<=> on trunk ruby
b78308d2d5a8dd26818eba88bb58ee547d6dfdb0
<ide><path>Library/Homebrew/formula.rb <ide> def == other <ide> def hash <ide> name.hash <ide> end <del> def <=> b <del> name <=> b.name <add> <add> def <=>(other) <add> return unless Formula === other <add> name <=> other.name <ide> end <add> <ide> def to_s <ide> name <ide> end <ide><path>Library/Homebrew/test/test_formula.rb <ide> def test_comparison_with_non_formula_objects_does_not_raise <ide> refute_equal TestBall.new, Object.new <ide> end <ide> <add> def test_sort_operator <add> assert_nil TestBall.new <=> Object.new <add> end <add> <ide> def test_class_naming <ide> assert_equal 'ShellFm', Formulary.class_s('shell.fm') <ide> assert_equal 'Fooxx', Formulary.class_s('foo++')
2
Text
Text
update shallow routing docs
6202a7f3bd913670cff5fd43523aad764678f10b
<ide><path>docs/routing/shallow-routing.md <ide> function Page() { <ide> <ide> useEffect(() => { <ide> // Always do navigations after the first render <del> router.push('/?counter=10', null, { shallow: true }) <add> router.push('/?counter=10', undefined, { shallow: true }) <ide> }, []) <ide> <ide> useEffect(() => { <ide> If you don't need to add the router object to the page, you can also use the [Ro <ide> ```jsx <ide> import Router from 'next/router' <ide> // Inside your page <del>Router.push('/?counter=10', null, { shallow: true }) <add>Router.push('/?counter=10', undefined, { shallow: true }) <ide> ``` <ide> <ide> The URL will get updated to `/?counter=10`. and the page won't get replaced, only the state of the route is changed.
1
Text
Text
add a note on running both examples
58bb294301a1c05b3d78bacc3f5c9a480d50f3e5
<ide><path>README.md <ide> Atomic Flux with hot reloading. <ide> - [Why another Flux framework?](#why-another-flux-framework) <ide> - [Philosophy & Design Goals](#philosophy--design-goals) <ide> - [Demo](#demo) <del>- [Running TodoMVC](#running-todomvc) <add>- [Running Examples](#running-examples) <ide> - [What does it look like?](#what-does-it-look-like) <ide> - [Actions](#actions) <ide> - [Stores](#stores) <ide> Read **[The Evolution of Flux Frameworks](https://medium.com/@dan_abramov/the-ev <ide> <ide> <img src='https://s3.amazonaws.com/f.cl.ly/items/2Z2D3U260d2A311k2B0z/Screen%20Recording%202015-06-03%20at%2003.22%20pm.gif' width='500'> <ide> <del>## Running TodoMVC <add>## Running Examples <ide> <del>``` <del>git clone https://github.com/gaearon/redux.git redux <add>First, clone the repo: <ide> <add>``` <add>git clone https://github.com/gaearon/redux.git <ide> cd redux <add>``` <add> <add>Run the Counter example: <add> <add>``` <add>cd redux/examples/counter <ide> npm install <add>npm start <add>``` <ide> <del>cd examples/todomvc <add>Run the TodoMVC example: <add> <add>``` <add>cd ../todomvc <ide> npm install <ide> npm start <ide> ```
1
PHP
PHP
remove deprecated defer property
810b3d91b2eecf922562e68b52ca3b6a7b076e7a
<ide><path>src/Illuminate/Support/ServiceProvider.php <ide> abstract class ServiceProvider <ide> */ <ide> protected $app; <ide> <del> /** <del> * Indicates if loading of the provider is deferred. <del> * <del> * @deprecated Implement the \Illuminate\Contracts\Support\DeferrableProvider interface instead. Will be removed in Laravel 5.9. <del> * <del> * @var bool <del> */ <del> protected $defer = false; <del> <ide> /** <ide> * The paths that should be published. <ide> * <ide> public function when() <ide> */ <ide> public function isDeferred() <ide> { <del> return $this->defer || $this instanceof DeferrableProvider; <add> return $this instanceof DeferrableProvider; <ide> } <ide> } <ide><path>tests/Foundation/FoundationApplicationTest.php <ide> use Illuminate\Foundation\Application; <ide> use Illuminate\Support\ServiceProvider; <ide> use Illuminate\Foundation\Events\LocaleUpdated; <add>use Illuminate\Contracts\Support\DeferrableProvider; <ide> use Illuminate\Foundation\Bootstrap\RegisterFacades; <ide> <ide> class FoundationApplicationTest extends TestCase <ide> public function register() <ide> } <ide> } <ide> <del>class ApplicationDeferredSharedServiceProviderStub extends ServiceProvider <add>class ApplicationDeferredSharedServiceProviderStub extends ServiceProvider implements DeferrableProvider <ide> { <del> protected $defer = true; <del> <ide> public function register() <ide> { <ide> $this->app->singleton('foo', function () { <ide> public function register() <ide> } <ide> } <ide> <del>class ApplicationDeferredServiceProviderCountStub extends ServiceProvider <add>class ApplicationDeferredServiceProviderCountStub extends ServiceProvider implements DeferrableProvider <ide> { <ide> public static $count = 0; <del> protected $defer = true; <ide> <ide> public function register() <ide> { <ide> public function register() <ide> } <ide> } <ide> <del>class ApplicationDeferredServiceProviderStub extends ServiceProvider <add>class ApplicationDeferredServiceProviderStub extends ServiceProvider implements DeferrableProvider <ide> { <ide> public static $initialized = false; <del> protected $defer = true; <ide> <ide> public function register() <ide> { <ide> public function register() <ide> } <ide> } <ide> <del>class ApplicationFactoryProviderStub extends ServiceProvider <add>class ApplicationFactoryProviderStub extends ServiceProvider implements DeferrableProvider <ide> { <del> protected $defer = true; <del> <ide> public function register() <ide> { <ide> $this->app->bind('foo', function () { <ide> public function register() <ide> } <ide> } <ide> <del>class ApplicationMultiProviderStub extends ServiceProvider <add>class ApplicationMultiProviderStub extends ServiceProvider implements DeferrableProvider <ide> { <del> protected $defer = true; <del> <ide> public function register() <ide> { <ide> $this->app->singleton('foo', function () {
2
Python
Python
use linspace instead of arange in some examples
ccbf5cf2fc35ec0a3e2c184fb846bb808aee3610
<ide><path>numpy/lib/function_base.py <ide> def piecewise(x, condlist, funclist, *args, **kw): <ide> -------- <ide> Define the sigma function, which is -1 for ``x < 0`` and +1 for ``x >= 0``. <ide> <del> >>> x = np.arange(6) - 2.5 <add> >>> x = np.linspace(-2.5, 2.5, 6) <ide> >>> np.piecewise(x, [x < 0, x >= 0], [-1, 1]) <ide> array([-1., -1., -1., 1., 1., 1.]) <ide> <ide> def sinc(x): <ide> <ide> Examples <ide> -------- <del> >>> x = np.arange(-20., 21.)/5. <add> >>> x = np.linspace(-4, 4, 41) <ide> >>> np.sinc(x) <ide> array([ -3.89804309e-17, -4.92362781e-02, -8.40918587e-02, <ide> -8.90384387e-02, -5.84680802e-02, 3.89804309e-17, <ide> def sinc(x): <ide> <ide> It works in 2-D as well: <ide> <del> >>> x = np.arange(-200., 201.)/50. <add> >>> x = np.linspace(-4, 4, 401) <ide> >>> xx = np.outer(x, x) <ide> >>> plt.imshow(np.sinc(xx)) <ide> <matplotlib.image.AxesImage object at 0x...>
1
PHP
PHP
raise phpstan to level 3. wip
b63ca3c8c1fd14c81045a964e4859b5ef31cc633
<ide><path>src/Database/SchemaCache.php <ide> namespace Cake\Database; <ide> <ide> use Cake\Cache\Cache; <del>use Cake\Datasource\ConnectionInterface; <ide> <ide> /** <ide> * Schema Cache. <ide> class SchemaCache <ide> /** <ide> * Constructor <ide> * <del> * @param \Cake\Datasource\ConnectionInterface $connection Connection name to get the schema for or a connection instance <add> * @param \Cake\Database\Connection $connection Connection name to get the schema for or a connection instance <ide> */ <del> public function __construct(ConnectionInterface $connection) <add> public function __construct(Connection $connection) <ide> { <ide> $this->_schema = $this->getSchema($connection); <ide> } <ide> public function clear(?string $name = null): array <ide> /** <ide> * Helper method to get the schema collection. <ide> * <del> * @param \Cake\Datasource\ConnectionInterface $connection Connection object <add> * @param \Cake\Database\Connection $connection Connection object <ide> * @return \Cake\Database\Schema\Collection|\Cake\Database\Schema\CachedCollection <ide> * @throws \RuntimeException If given connection object is not compatible with schema caching <ide> */ <del> public function getSchema(ConnectionInterface $connection) <add> public function getSchema(Connection $connection) <ide> { <ide> $config = $connection->config(); <ide> if (empty($config['cacheMetadata'])) { <ide><path>src/Shell/SchemaCacheShell.php <ide> public function clear(?string $name = null): bool <ide> protected function _getSchemaCache(): SchemaCache <ide> { <ide> try { <add> /** @var \Cake\Database\Connection $connection */ <ide> $connection = ConnectionManager::get($this->params['connection']); <ide> <ide> return new SchemaCache($connection);
2
Ruby
Ruby
ignore order when doing count
bbad7523f08936f38938c7d4ff18f4084f008244
<ide><path>activerecord/lib/active_record/relation/calculations.rb <ide> def operation_over_aggregate_column(column, operation, distinct) <ide> <ide> def execute_simple_calculation(operation, column_name, distinct) #:nodoc: <ide> # Postgresql doesn't like ORDER BY when there are no GROUP BY <del> relation = reorder(nil) <add> relation = unscope(:order) <ide> <ide> column_alias = column_name <ide> <ide><path>activerecord/test/cases/calculations_test.rb <ide> def test_count_with_too_many_parameters_raises <ide> assert_raise(ArgumentError) { Account.count(1, 2, 3) } <ide> end <ide> <add> def test_count_with_order <add> assert_equal 6, Account.order(:credit_limit).count <add> end <add> <add> def test_count_with_reverse_order <add> assert_equal 6, Account.order(:credit_limit).reverse_order.count <add> end <add> <add> def test_count_with_where_and_order <add> assert_equal 1, Account.where(firm_name: '37signals').count <add> assert_equal 1, Account.where(firm_name: '37signals').order(:firm_name).count <add> assert_equal 1, Account.where(firm_name: '37signals').order(:firm_name).reverse_order.count <add> end <add> <ide> def test_should_sum_expression <ide> # Oracle adapter returns floating point value 636.0 after SUM <ide> if current_adapter?(:OracleAdapter)
2
Javascript
Javascript
remove most comments from html generation output
e955008b9bbee93fcaf423d4afaf4d22023e2c3f
<ide><path>src/renderers/dom/fiber/ReactDOMFiberEntry.js <ide> function shouldReuseContent(container) { <ide> const rootElement = getReactRootElementInContainer(container); <ide> return !!(rootElement && <ide> rootElement.nodeType === ELEMENT_NODE && <del> rootElement.getAttribute(ID_ATTRIBUTE_NAME)); <add> rootElement.hasAttribute(ID_ATTRIBUTE_NAME)); <ide> } <ide> <ide> function shouldAutoFocusHostComponent(type: string, props: Props): boolean { <ide> var DOMRenderer = ReactFiberReconciler({ <ide> return instance.nodeType === 1 && type === instance.nodeName.toLowerCase(); <ide> }, <ide> <del> canHydrateTextInstance(instance: Instance | TextInstance): boolean { <add> canHydrateTextInstance( <add> instance: Instance | TextInstance, <add> text: string, <add> ): boolean { <add> if (text === '') { <add> // Empty strings are not parsed by HTML so there won't be a correct match here. <add> return false; <add> } <ide> return instance.nodeType === 3; <ide> }, <ide> <ide> var DOMRenderer = ReactFiberReconciler({ <ide> ): null | Instance | TextInstance { <ide> let node = instance.nextSibling; <ide> // Skip non-hydratable nodes. <del> /* <ide> while (node && node.nodeType !== 1 && node.nodeType !== 3) { <ide> node = node.nextSibling; <ide> } <del> */ <ide> return (node: any); <ide> }, <ide> <ide> var DOMRenderer = ReactFiberReconciler({ <ide> ): null | Instance | TextInstance { <ide> let next = parentInstance.firstChild; <ide> // Skip non-hydratable nodes. <del> /* <ide> while (next && next.nodeType !== 1 && next.nodeType !== 3) { <ide> next = next.nextSibling; <ide> } <del> */ <ide> return (next: any); <ide> }, <ide> <ide><path>src/renderers/dom/shared/__tests__/ReactDOMServerIntegration-test.js <ide> describe('ReactDOMServerIntegration', () => { <ide> // with Fiber, there are just three separate text node children, <ide> // each of which is blank. <ide> if (render === serverRender || render === streamRender) { <del> // For plain server markup result we expect six comment nodes. <del> expect(e.childNodes.length).toBe(6); <add> // For plain server markup result we should have no text nodes if <add> // they're all empty. <add> expect(e.childNodes.length).toBe(0); <ide> expect(e.textContent).toBe(''); <ide> } else { <ide> expect(e.childNodes.length).toBe(3); <ide> describe('ReactDOMServerIntegration', () => { <ide> itRenders('a div with multiple whitespace children', async render => { <ide> const e = await render(<div>{' '}{' '}{' '}</div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <del> // with Fiber, there are just three text nodes. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(9); <del> expectTextNode(e.childNodes[1], ' '); <add> // with Fiber, there are normally just three text nodes <add> if ( <add> render === serverRender || <add> render === clientRenderOnServerString || <add> render === streamRender <add> ) { <add> // For plain server markup result we have comments between. <add> // If we're able to hydrate, they remain. <add> expect(e.childNodes.length).toBe(5); <add> expectTextNode(e.childNodes[0], ' '); <add> expectTextNode(e.childNodes[2], ' '); <ide> expectTextNode(e.childNodes[4], ' '); <del> expectTextNode(e.childNodes[7], ' '); <ide> } else { <ide> expect(e.childNodes.length).toBe(3); <ide> expectTextNode(e.childNodes[0], ' '); <ide> describe('ReactDOMServerIntegration', () => { <ide> itRenders('a div with text sibling to a node', async render => { <ide> const e = await render(<div>Text<span>More Text</span></div>); <ide> let spanNode; <del> if ( <del> ReactDOMFeatureFlags.useFiber && <del> (render !== serverRender && render !== streamRender) <del> ) { <add> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are only two children, the "Text" text node and <ide> // the span element. <ide> expect(e.childNodes.length).toBe(2); <ide> describe('ReactDOMServerIntegration', () => { <ide> expect(e.childNodes.length).toBe(4); <ide> spanNode = e.childNodes[3]; <ide> } <del> if ( <del> ReactDOMFeatureFlags.useFiber && <del> (render === serverRender || render === streamRender) <del> ) { <del> expectTextNode(e.childNodes[1], 'Text'); <del> } else { <del> expectTextNode(e.childNodes[0], 'Text'); <del> } <add> expectTextNode(e.childNodes[0], 'Text'); <ide> expect(spanNode.tagName).toBe('SPAN'); <ide> expect(spanNode.childNodes.length).toBe(1); <ide> expectNode(spanNode.firstChild, TEXT_NODE_TYPE, 'More Text'); <ide> describe('ReactDOMServerIntegration', () => { <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are just two text nodes. <ide> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(5); <del> expectTextNode(e.childNodes[3], 'foo'); <add> expect(e.childNodes.length).toBe(1); <add> expectTextNode(e.childNodes[0], 'foo'); <ide> } else { <ide> expect(e.childNodes.length).toBe(2); <ide> expectTextNode(e.childNodes[0], ''); <ide> describe('ReactDOMServerIntegration', () => { <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are just two text nodes. <ide> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(5); <del> expectTextNode(e.childNodes[1], 'foo'); <add> expect(e.childNodes.length).toBe(1); <add> expectTextNode(e.childNodes[0], 'foo'); <ide> } else { <ide> expect(e.childNodes.length).toBe(2); <ide> expectTextNode(e.childNodes[0], 'foo'); <ide> describe('ReactDOMServerIntegration', () => { <ide> const e = await render(<div>{'foo'}{'bar'}</div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are just two text nodes. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(6); <del> expectTextNode(e.childNodes[1], 'foo'); <del> expectTextNode(e.childNodes[4], 'bar'); <add> if ( <add> render === serverRender || <add> render === clientRenderOnServerString || <add> render === streamRender <add> ) { <add> // In the server render output there's a comment between them. <add> expect(e.childNodes.length).toBe(3); <add> expectTextNode(e.childNodes[0], 'foo'); <add> expectTextNode(e.childNodes[2], 'bar'); <ide> } else { <ide> expect(e.childNodes.length).toBe(2); <ide> expectTextNode(e.childNodes[0], 'foo'); <ide> describe('ReactDOMServerIntegration', () => { <ide> const e = await render(<div>{'foo'}{40}</div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are just two text nodes. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(6); <del> expectTextNode(e.childNodes[1], 'foo'); <del> expectTextNode(e.childNodes[4], '40'); <add> if ( <add> render === serverRender || <add> render === clientRenderOnServerString || <add> render === streamRender <add> ) { <add> // In the server markup there's a comment between. <add> expect(e.childNodes.length).toBe(3); <add> expectTextNode(e.childNodes[0], 'foo'); <add> expectTextNode(e.childNodes[2], '40'); <ide> } else { <ide> expect(e.childNodes.length).toBe(2); <ide> expectTextNode(e.childNodes[0], 'foo'); <ide> describe('ReactDOMServerIntegration', () => { <ide> const e = await render(<div><NullComponent /></div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, an empty component results in no markup. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(1); <del> expectEmptyNode(e.firstChild); <del> } else { <del> expect(e.childNodes.length).toBe(0); <del> } <add> expect(e.childNodes.length).toBe(0); <ide> } else { <ide> // with Stack, an empty component results in one react-empty comment <ide> // node. <ide> describe('ReactDOMServerIntegration', () => { <ide> const e = await render(<div>{null}foo</div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there is just one text node. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(3); <del> expectTextNode(e.childNodes[1], 'foo'); <del> } else { <del> expect(e.childNodes.length).toBe(1); <del> expectTextNode(e.childNodes[0], 'foo'); <del> } <add> expect(e.childNodes.length).toBe(1); <add> expectTextNode(e.childNodes[0], 'foo'); <ide> } else { <ide> // with Stack, there's a text node surronded by react-text comment nodes. <ide> expect(e.childNodes.length).toBe(3); <ide> describe('ReactDOMServerIntegration', () => { <ide> const e = await render(<div>{false}foo</div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there is just one text node. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(3); <del> expectTextNode(e.childNodes[1], 'foo'); <del> } else { <del> expect(e.childNodes.length).toBe(1); <del> expectTextNode(e.childNodes[0], 'foo'); <del> } <add> expect(e.childNodes.length).toBe(1); <add> expectTextNode(e.childNodes[0], 'foo'); <ide> } else { <ide> // with Stack, there's a text node surronded by react-text comment nodes. <ide> expect(e.childNodes.length).toBe(3); <ide> describe('ReactDOMServerIntegration', () => { <ide> const e = await render(<div>{false}{null}foo{null}{false}</div>); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there is just one text node. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(3); <del> expectTextNode(e.childNodes[1], 'foo'); <del> } else { <del> expect(e.childNodes.length).toBe(1); <del> expectTextNode(e.childNodes[0], 'foo'); <del> } <add> expect(e.childNodes.length).toBe(1); <add> expectTextNode(e.childNodes[0], 'foo'); <ide> } else { <ide> // with Stack, there's a text node surronded by react-text comment nodes. <ide> expect(e.childNodes.length).toBe(3); <ide> describe('ReactDOMServerIntegration', () => { <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are three children: the child1 element, a <ide> // single space text node, and the child2 element. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(5); <del> child1 = e.childNodes[0]; <del> textNode = e.childNodes[2]; <del> child2 = e.childNodes[4]; <del> } else { <del> expect(e.childNodes.length).toBe(3); <del> child1 = e.childNodes[0]; <del> textNode = e.childNodes[1]; <del> child2 = e.childNodes[2]; <del> } <add> expect(e.childNodes.length).toBe(3); <add> child1 = e.childNodes[0]; <add> textNode = e.childNodes[1]; <add> child2 = e.childNodes[2]; <ide> } else { <ide> // with Stack, there are five children: the child1 element, a single <ide> // space surrounded by react-text comments, and the child2 element. <ide> describe('ReactDOMServerIntegration', () => { <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are three children: a one-space text node, the <ide> // child element, and a two-space text node. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(7); <del> textNode1 = e.childNodes[1]; <del> child = e.childNodes[3]; <del> textNode2 = e.childNodes[5]; <del> } else { <del> expect(e.childNodes.length).toBe(3); <del> textNode1 = e.childNodes[0]; <del> child = e.childNodes[1]; <del> textNode2 = e.childNodes[2]; <del> } <add> expect(e.childNodes.length).toBe(3); <add> textNode1 = e.childNodes[0]; <add> child = e.childNodes[1]; <add> textNode2 = e.childNodes[2]; <ide> } else { <ide> // with Stack, there are 7 children: a one-space text node surrounded <ide> // by react-text comments, the child element, and a two-space text node <ide> describe('ReactDOMServerIntegration', () => { <ide> ); <ide> if (ReactDOMFeatureFlags.useFiber) { <ide> // with Fiber, there are just two text nodes. <del> if (render === serverRender || render === streamRender) { <del> expect(e.childNodes.length).toBe(6); <del> expectTextNode(e.childNodes[1], '<span>Text1&quot;</span>'); <del> expectTextNode(e.childNodes[4], '<span>Text2&quot;</span>'); <add> if ( <add> render === serverRender || <add> render === clientRenderOnServerString || <add> render === streamRender <add> ) { <add> expect(e.childNodes.length).toBe(3); <add> expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); <add> expectTextNode(e.childNodes[2], '<span>Text2&quot;</span>'); <ide> } else { <ide> expect(e.childNodes.length).toBe(2); <ide> expectTextNode(e.childNodes[0], '<span>Text1&quot;</span>'); <ide><path>src/renderers/dom/shared/__tests__/ReactServerRendering-test.js <ide> describe('ReactDOMServer', () => { <ide> ROOT_ATTRIBUTE_NAME + <ide> '="" ' + <ide> ID_ATTRIBUTE_NAME + <del> '="[^"]+" ' + <add> '="[^"]*" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + <ide> '="[^"]+">hello world</span>', <ide> ), <ide> describe('ReactDOMServer', () => { <ide> ROOT_ATTRIBUTE_NAME + <ide> '="" ' + <ide> ID_ATTRIBUTE_NAME + <del> '="[^"]+" ' + <add> '="[^"]*" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + <ide> '="[^"]+"/>', <ide> ), <ide> describe('ReactDOMServer', () => { <ide> ROOT_ATTRIBUTE_NAME + <ide> '="" ' + <ide> ID_ATTRIBUTE_NAME + <del> '="[^"]+" ' + <add> '="[^"]*" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + <ide> '="[^"]+"/>', <ide> ), <ide> describe('ReactDOMServer', () => { <ide> } <ide> <ide> var response = ReactDOMServer.renderToString(<NullComponent />); <del> expect(response).toBe('<!-- react-empty: 1 -->'); <add> if (ReactDOMFeatureFlags.useFiber) { <add> expect(response).toBe(''); <add> } else { <add> expect(response).toBe('<!-- react-empty: 1 -->'); <add> } <ide> }); <ide> <ide> // TODO: Test that listeners are not registered onto any document/container. <ide> describe('ReactDOMServer', () => { <ide> ROOT_ATTRIBUTE_NAME + <ide> '="" ' + <ide> ID_ATTRIBUTE_NAME + <del> '="[^"]+" ' + <add> '="[^"]*" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + <ide> '="[^"]+">' + <ide> '<span ' + <ide> ID_ATTRIBUTE_NAME + <del> '="[^"]+">' + <del> '<!-- react-text: [0-9]+ -->My name is <!-- /react-text -->' + <del> '<!-- react-text: [0-9]+ -->child<!-- /react-text -->' + <add> '="[^"]*">' + <add> (ReactDOMFeatureFlags.useFiber <add> ? 'My name is <!-- -->child' <add> : '<!-- react-text: [0-9]+ -->My name is <!-- /react-text -->' + <add> '<!-- react-text: [0-9]+ -->child<!-- /react-text -->') + <ide> '</span>' + <ide> '</div>', <ide> ), <ide> describe('ReactDOMServer', () => { <ide> ROOT_ATTRIBUTE_NAME + <ide> '="" ' + <ide> ID_ATTRIBUTE_NAME + <del> '="[^"]+" ' + <add> '="[^"]*" ' + <ide> ReactMarkupChecksum.CHECKSUM_ATTR_NAME + <ide> '="[^"]+">' + <del> '<!-- react-text: [0-9]+ -->Component name: <!-- /react-text -->' + <del> '<!-- react-text: [0-9]+ -->TestComponent<!-- /react-text -->' + <add> (ReactDOMFeatureFlags.useFiber <add> ? 'Component name: <!-- -->TestComponent' <add> : '<!-- react-text: [0-9]+ -->Component name: <!-- /react-text -->' + <add> '<!-- react-text: [0-9]+ -->TestComponent<!-- /react-text -->') + <ide> '</span>', <ide> ), <ide> ); <ide><path>src/renderers/shared/fiber/ReactFiberHydrationContext.js <ide> module.exports = function<T, P, I, TI, PI, C, CX, PL>( <ide> switch (fiber.tag) { <ide> case HostComponent: { <ide> const type = fiber.type; <del> const props = fiber.memoizedProps; <add> const props = fiber.pendingProps; <ide> return canHydrateInstance(nextInstance, type, props); <ide> } <ide> case HostText: { <del> return canHydrateTextInstance(nextInstance); <add> const text = fiber.pendingProps; <add> return canHydrateTextInstance(nextInstance, text); <ide> } <ide> default: <ide> return false; <ide><path>src/renderers/shared/fiber/ReactFiberReconciler.js <ide> export type HostConfig<T, P, I, TI, PI, C, CX, PL> = { <ide> <ide> // Optional hydration <ide> canHydrateInstance?: (instance: I | TI, type: T, props: P) => boolean, <del> canHydrateTextInstance?: (instance: I | TI) => boolean, <add> canHydrateTextInstance?: (instance: I | TI, text: string) => boolean, <ide> getNextHydratableSibling?: (instance: I | TI) => null | I | TI, <ide> getFirstHydratableChild?: (parentInstance: I | C) => null | I | TI, <ide> hydrateInstance?: ( <ide><path>src/renderers/shared/server/ReactPartialRenderer.js <ide> function createOpenTagMarkup( <ide> props, <ide> makeStaticMarkup, <ide> isRootElement, <del> domID, <ide> instForDebug, <ide> ) { <ide> var ret = '<' + tagVerbatim; <ide> function createOpenTagMarkup( <ide> if (isRootElement) { <ide> ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); <ide> } <del> ret += ' ' + DOMPropertyOperations.createMarkupForID(domID); <add> ret += ' ' + DOMPropertyOperations.createMarkupForID(''); <ide> return ret; <ide> } <ide> <ide> class ReactDOMServerRenderer { <ide> footer: '', <ide> }, <ide> ]; <del> this.idCounter = 1; <ide> this.exhausted = false; <ide> this.currentSelectValue = null; <add> this.previousWasTextNode = false; <ide> this.makeStaticMarkup = makeStaticMarkup; <ide> } <ide> <ide> class ReactDOMServerRenderer { <ide> var frame = this.stack[this.stack.length - 1]; <ide> if (frame.childIndex >= frame.children.length) { <ide> out += frame.footer; <add> this.previousWasTextNode = false; <ide> this.stack.pop(); <ide> if (frame.tag === 'select') { <ide> this.currentSelectValue = null; <ide> class ReactDOMServerRenderer { <ide> <ide> render(child, context) { <ide> if (typeof child === 'string' || typeof child === 'number') { <add> var text = '' + child; <add> if (text === '') { <add> return ''; <add> } <ide> if (this.makeStaticMarkup) { <del> return escapeTextContentForBrowser('' + child); <add> return escapeTextContentForBrowser(text); <ide> } <del> return ( <del> '<!-- react-text: ' + <del> this.idCounter++ + <del> ' -->' + <del> escapeTextContentForBrowser('' + child) + <del> '<!-- /react-text -->' <del> ); <add> if (this.previousWasTextNode) { <add> return '<!-- -->' + escapeTextContentForBrowser(text); <add> } <add> this.previousWasTextNode = true; <add> return escapeTextContentForBrowser(text); <ide> } else { <ide> ({child, context} = resolve(child, context)); <ide> if (child === null || child === false) { <del> if (this.makeStaticMarkup) { <del> // Normally we'd insert a comment node, but since this is a situation <del> // where React won't take over (static pages), we can simply return <del> // nothing. <del> return ''; <del> } <del> return '<!-- react-empty: ' + this.idCounter++ + ' -->'; <add> return ''; <ide> } else { <ide> return this.renderDOM(child, context); <ide> } <ide> class ReactDOMServerRenderer { <ide> props, <ide> this.makeStaticMarkup, <ide> this.stack.length === 1, <del> this.idCounter++, <ide> null, <ide> ); <ide> var footer = '';
6
Text
Text
update changelog for 1.7.0-beta.1
6222b5d46005cf70ad9ea66faf67bca1be9796f5
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### Ember 1.7.0-beta.1 (July, 8, 2014) <add> <add>* Fix components inside group helper. <add>* [BUGFIX] Fix wrong view keyword in a component block. <add>* Update to RSVP 3.0.7. <add>* [FEATURE query-params-new] <add>* [FEATURE ember-routing-consistent-resources] <ide> * `uuid` is now consistently used across the project. <ide> * `Ember.uuid` is now an internal function instead of a property on `Ember` itself. <del>* [Bugfix beta] sync back burner: workaround IE's issue with try/finally <del> without Catch. Also no longer force deoptimization of the run loop <del> queue flush. <del>* [BREAKING BUGFIX] An empty array are treated as falsy value in `bind-attr` to be in consistent with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty array as truthy value in `bind-attr`. <del>* [Bugfix beta] On Controllers, the content property is now derived from <del> model. This reduces many caveats with model/content, and also sets a <del> simple ground rule: Never set a controllers content, rather always set <del> it's model and ember will do the right thing. <add>* [BUGFIX] sync back burner: workaround IE's issue with try/finally without Catch. <add> Also no longer force deoptimization of the run loop queue flush. <add>* [BREAKING BUGFIX] An empty array are treated as falsy value in `bind-attr` to be in consistent <add> with `if` helper. Breaking for apps that relies on the previous behaviour which treats an empty <add> array as truthy value in `bind-attr`. <add>* [BREAKING BUGFIX] On Controllers, the content property is now derived from model. This reduces many <add> caveats with model/content, and also sets a simple ground rule: Never set a controllers content, <add> rather always set it's model and ember will do the right thing. <ide> <ide> ### Ember 1.6.0 (July, 7, 2014) <ide>
1
Ruby
Ruby
convert time extension modules to class reopens
1c5a6944d38e6818d254f272057b513b038b2270
<ide><path>activesupport/lib/active_support/core_ext/time.rb <ide> require 'active_support/core_ext/time/publicize_conversion_methods' <ide> require 'active_support/core_ext/time/marshal_with_utc_flag' <ide> <add>require 'active_support/core_ext/time/calculations' <add>require 'active_support/core_ext/time/zones' <add> <ide> require 'active_support/core_ext/util' <del>ActiveSupport.core_ext Time, %w(behavior calculations conversions zones) <add>ActiveSupport.core_ext Time, %w(behavior conversions) <ide><path>activesupport/lib/active_support/core_ext/time/calculations.rb <ide> require 'active_support/duration' <ide> <del>module ActiveSupport #:nodoc: <del> module CoreExtensions #:nodoc: <del> module Time #:nodoc: <del> # Enables the use of time calculations within Time itself <del> module Calculations <del> def self.included(base) #:nodoc: <del> base.extend ClassMethods <del> <del> base.class_eval do <del> alias_method :plus_without_duration, :+ <del> alias_method :+, :plus_with_duration <del> <del> alias_method :minus_without_duration, :- <del> alias_method :-, :minus_with_duration <del> <del> alias_method :minus_without_coercion, :- <del> alias_method :-, :minus_with_coercion <del> <del> alias_method :compare_without_coercion, :<=> <del> alias_method :<=>, :compare_with_coercion <del> end <del> end <del> <del> COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] <del> <del> module ClassMethods <del> # Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances <del> def ===(other) <del> other.is_a?(::Time) <del> end <del> <del> # Return the number of days in the given month. <del> # If no year is specified, it will use the current year. <del> def days_in_month(month, year = now.year) <del> return 29 if month == 2 && ::Date.gregorian_leap?(year) <del> COMMON_YEAR_DAYS_IN_MONTH[month] <del> end <del> <del> # Returns a new Time if requested year can be accommodated by Ruby's Time class <del> # (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture); <del> # otherwise returns a DateTime <del> def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0) <del> ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec) <del> rescue <del> offset = utc_or_local.to_sym == :local ? ::DateTime.local_offset : 0 <del> ::DateTime.civil(year, month, day, hour, min, sec, offset) <del> end <del> <del> # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>. <del> def utc_time(*args) <del> time_with_datetime_fallback(:utc, *args) <del> end <del> <del> # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>. <del> def local_time(*args) <del> time_with_datetime_fallback(:local, *args) <del> end <del> end <del> <del> # Tells whether the Time object's time lies in the past <del> def past? <del> self < ::Time.current <del> end <del> <del> # Tells whether the Time object's time is today <del> def today? <del> self.to_date == ::Date.current <del> end <del> <del> # Tells whether the Time object's time lies in the future <del> def future? <del> self > ::Time.current <del> end <del> <del> # Seconds since midnight: Time.now.seconds_since_midnight <del> def seconds_since_midnight <del> self.to_i - self.change(:hour => 0).to_i + (self.usec/1.0e+6) <del> end <del> <del> # Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options <del> # (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and <del> # minute is passed, then sec and usec is set to 0. <del> def change(options) <del> ::Time.send( <del> self.utc? ? :utc_time : :local_time, <del> options[:year] || self.year, <del> options[:month] || self.month, <del> options[:day] || self.day, <del> options[:hour] || self.hour, <del> options[:min] || (options[:hour] ? 0 : self.min), <del> options[:sec] || ((options[:hour] || options[:min]) ? 0 : self.sec), <del> options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : self.usec) <del> ) <del> end <del> <del> # Uses Date to provide precise Time calculations for years, months, and days. <del> # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, <del> # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <del> # <tt>:minutes</tt>, <tt>:seconds</tt>. <del> def advance(options) <del> unless options[:weeks].nil? <del> options[:weeks], partial_weeks = options[:weeks].divmod(1) <del> options[:days] = (options[:days] || 0) + 7 * partial_weeks <del> end <del> <del> unless options[:days].nil? <del> options[:days], partial_days = options[:days].divmod(1) <del> options[:hours] = (options[:hours] || 0) + 24 * partial_days <del> end <del> <del> d = to_date.advance(options) <del> time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day) <del> seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600 <del> seconds_to_advance == 0 ? time_advanced_by_date : time_advanced_by_date.since(seconds_to_advance) <del> end <del> <del> # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension <del> def ago(seconds) <del> self.since(-seconds) <del> end <del> <del> # Returns a new Time representing the time a number of seconds since the instance time, this is basically a wrapper around <del> # the Numeric extension. <del> def since(seconds) <del> f = seconds.since(self) <del> if ActiveSupport::Duration === seconds <del> f <del> else <del> initial_dst = self.dst? ? 1 : 0 <del> final_dst = f.dst? ? 1 : 0 <del> (seconds.abs >= 86400 && initial_dst != final_dst) ? f + (initial_dst - final_dst).hours : f <del> end <del> rescue <del> self.to_datetime.since(seconds) <del> end <del> alias :in :since <del> <del> # Returns a new Time representing the time a number of specified months ago <del> def months_ago(months) <del> advance(:months => -months) <del> end <del> <del> # Returns a new Time representing the time a number of specified months in the future <del> def months_since(months) <del> advance(:months => months) <del> end <del> <del> # Returns a new Time representing the time a number of specified years ago <del> def years_ago(years) <del> advance(:years => -years) <del> end <del> <del> # Returns a new Time representing the time a number of specified years in the future <del> def years_since(years) <del> advance(:years => years) <del> end <del> <del> # Short-hand for years_ago(1) <del> def last_year <del> years_ago(1) <del> end <del> <del> # Short-hand for years_since(1) <del> def next_year <del> years_since(1) <del> end <del> <del> <del> # Short-hand for months_ago(1) <del> def last_month <del> months_ago(1) <del> end <del> <del> # Short-hand for months_since(1) <del> def next_month <del> months_since(1) <del> end <del> <del> # Returns a new Time representing the "start" of this week (Monday, 0:00) <del> def beginning_of_week <del> days_to_monday = self.wday!=0 ? self.wday-1 : 6 <del> (self - days_to_monday.days).midnight <del> end <del> alias :monday :beginning_of_week <del> alias :at_beginning_of_week :beginning_of_week <del> <del> # Returns a new Time representing the end of this week (Sunday, 23:59:59) <del> def end_of_week <del> days_to_sunday = self.wday!=0 ? 7-self.wday : 0 <del> (self + days_to_sunday.days).end_of_day <del> end <del> alias :at_end_of_week :end_of_week <del> <del> # Returns a new Time representing the start of the given day in next week (default is Monday). <del> def next_week(day = :monday) <del> days_into_week = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6} <del> since(1.week).beginning_of_week.since(days_into_week[day].day).change(:hour => 0) <del> end <del> <del> # Returns a new Time representing the start of the day (0:00) <del> def beginning_of_day <del> (self - self.seconds_since_midnight).change(:usec => 0) <del> end <del> alias :midnight :beginning_of_day <del> alias :at_midnight :beginning_of_day <del> alias :at_beginning_of_day :beginning_of_day <del> <del> # Returns a new Time representing the end of the day (23:59:59) <del> def end_of_day <del> change(:hour => 23, :min => 59, :sec => 59) <del> end <del> <del> # Returns a new Time representing the start of the month (1st of the month, 0:00) <del> def beginning_of_month <del> #self - ((self.mday-1).days + self.seconds_since_midnight) <del> change(:day => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0) <del> end <del> alias :at_beginning_of_month :beginning_of_month <del> <del> # Returns a new Time representing the end of the month (last day of the month, 0:00) <del> def end_of_month <del> #self - ((self.mday-1).days + self.seconds_since_midnight) <del> last_day = ::Time.days_in_month( self.month, self.year ) <del> change(:day => last_day, :hour => 23, :min => 59, :sec => 59, :usec => 0) <del> end <del> alias :at_end_of_month :end_of_month <del> <del> # Returns a new Time representing the start of the quarter (1st of january, april, july, october, 0:00) <del> def beginning_of_quarter <del> beginning_of_month.change(:month => [10, 7, 4, 1].detect { |m| m <= self.month }) <del> end <del> alias :at_beginning_of_quarter :beginning_of_quarter <del> <del> # Returns a new Time representing the end of the quarter (last day of march, june, september, december, 23:59:59) <del> def end_of_quarter <del> beginning_of_month.change(:month => [3, 6, 9, 12].detect { |m| m >= self.month }).end_of_month <del> end <del> alias :at_end_of_quarter :end_of_quarter <del> <del> # Returns a new Time representing the start of the year (1st of january, 0:00) <del> def beginning_of_year <del> change(:month => 1,:day => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0) <del> end <del> alias :at_beginning_of_year :beginning_of_year <del> <del> # Returns a new Time representing the end of the year (31st of december, 23:59:59) <del> def end_of_year <del> change(:month => 12,:day => 31,:hour => 23, :min => 59, :sec => 59) <del> end <del> alias :at_end_of_year :end_of_year <del> <del> # Convenience method which returns a new Time representing the time 1 day ago <del> def yesterday <del> advance(:days => -1) <del> end <del> <del> # Convenience method which returns a new Time representing the time 1 day since the instance time <del> def tomorrow <del> advance(:days => 1) <del> end <del> <del> def plus_with_duration(other) #:nodoc: <del> if ActiveSupport::Duration === other <del> other.since(self) <del> else <del> plus_without_duration(other) <del> end <del> end <del> <del> def minus_with_duration(other) #:nodoc: <del> if ActiveSupport::Duration === other <del> other.until(self) <del> else <del> minus_without_duration(other) <del> end <del> end <del> <del> # Time#- can also be used to determine the number of seconds between two Time instances. <del> # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances <del> # are coerced into values that Time#- will recognize <del> def minus_with_coercion(other) <del> other = other.comparable_time if other.respond_to?(:comparable_time) <del> minus_without_coercion(other) <del> end <del> <del> # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances <del> # can be chronologically compared with a Time <del> def compare_with_coercion(other) <del> # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparison <del> other = other.comparable_time if other.respond_to?(:comparable_time) <del> if other.acts_like?(:date) <del> # other is a Date/DateTime, so coerce self #to_datetime and hand off to DateTime#<=> <del> to_datetime.compare_without_coercion(other) <del> else <del> compare_without_coercion(other) <del> end <del> end <del> end <add>class Time <add> COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] <add> DAYS_INTO_WEEK = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6 } <add> <add> class << self <add> # Overriding case equality method so that it returns true for ActiveSupport::TimeWithZone instances <add> def ===(other) <add> other.is_a?(::Time) <add> end <add> <add> # Return the number of days in the given month. <add> # If no year is specified, it will use the current year. <add> def days_in_month(month, year = now.year) <add> return 29 if month == 2 && ::Date.gregorian_leap?(year) <add> COMMON_YEAR_DAYS_IN_MONTH[month] <add> end <add> <add> # Returns a new Time if requested year can be accommodated by Ruby's Time class <add> # (i.e., if year is within either 1970..2038 or 1902..2038, depending on system architecture); <add> # otherwise returns a DateTime <add> def time_with_datetime_fallback(utc_or_local, year, month=1, day=1, hour=0, min=0, sec=0, usec=0) <add> ::Time.send(utc_or_local, year, month, day, hour, min, sec, usec) <add> rescue <add> offset = utc_or_local.to_sym == :local ? ::DateTime.local_offset : 0 <add> ::DateTime.civil(year, month, day, hour, min, sec, offset) <add> end <add> <add> # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:utc</tt>. <add> def utc_time(*args) <add> time_with_datetime_fallback(:utc, *args) <add> end <add> <add> # Wraps class method +time_with_datetime_fallback+ with +utc_or_local+ set to <tt>:local</tt>. <add> def local_time(*args) <add> time_with_datetime_fallback(:local, *args) <add> end <add> end <add> <add> # Tells whether the Time object's time lies in the past <add> def past? <add> self < ::Time.current <add> end <add> <add> # Tells whether the Time object's time is today <add> def today? <add> to_date == ::Date.current <add> end <add> <add> # Tells whether the Time object's time lies in the future <add> def future? <add> self > ::Time.current <add> end <add> <add> # Seconds since midnight: Time.now.seconds_since_midnight <add> def seconds_since_midnight <add> to_i - change(:hour => 0).to_i + (usec / 1.0e+6) <add> end <add> <add> # Returns a new Time where one or more of the elements have been changed according to the +options+ parameter. The time options <add> # (hour, minute, sec, usec) reset cascadingly, so if only the hour is passed, then minute, sec, and usec is set to 0. If the hour and <add> # minute is passed, then sec and usec is set to 0. <add> def change(options) <add> ::Time.send( <add> utc? ? :utc_time : :local_time, <add> options[:year] || year, <add> options[:month] || month, <add> options[:day] || day, <add> options[:hour] || hour, <add> options[:min] || (options[:hour] ? 0 : min), <add> options[:sec] || ((options[:hour] || options[:min]) ? 0 : sec), <add> options[:usec] || ((options[:hour] || options[:min] || options[:sec]) ? 0 : usec) <add> ) <add> end <add> <add> # Uses Date to provide precise Time calculations for years, months, and days. <add> # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, <add> # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, <add> # <tt>:minutes</tt>, <tt>:seconds</tt>. <add> def advance(options) <add> unless options[:weeks].nil? <add> options[:weeks], partial_weeks = options[:weeks].divmod(1) <add> options[:days] = (options[:days] || 0) + 7 * partial_weeks <add> end <add> <add> unless options[:days].nil? <add> options[:days], partial_days = options[:days].divmod(1) <add> options[:hours] = (options[:hours] || 0) + 24 * partial_days <add> end <add> <add> d = to_date.advance(options) <add> time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day) <add> seconds_to_advance = (options[:seconds] || 0) + (options[:minutes] || 0) * 60 + (options[:hours] || 0) * 3600 <add> seconds_to_advance == 0 ? time_advanced_by_date : time_advanced_by_date.since(seconds_to_advance) <add> end <add> <add> # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension <add> def ago(seconds) <add> since(-seconds) <add> end <add> <add> # Returns a new Time representing the time a number of seconds since the instance time, this is basically a wrapper around <add> # the Numeric extension. <add> def since(seconds) <add> f = seconds.since(self) <add> if ActiveSupport::Duration === seconds <add> f <add> else <add> initial_dst = dst? ? 1 : 0 <add> final_dst = f.dst? ? 1 : 0 <add> (seconds.abs >= 86400 && initial_dst != final_dst) ? f + (initial_dst - final_dst).hours : f <add> end <add> rescue <add> self.to_datetime.since(seconds) <add> end <add> alias :in :since <add> <add> # Returns a new Time representing the time a number of specified months ago <add> def months_ago(months) <add> advance(:months => -months) <add> end <add> <add> # Returns a new Time representing the time a number of specified months in the future <add> def months_since(months) <add> advance(:months => months) <add> end <add> <add> # Returns a new Time representing the time a number of specified years ago <add> def years_ago(years) <add> advance(:years => -years) <add> end <add> <add> # Returns a new Time representing the time a number of specified years in the future <add> def years_since(years) <add> advance(:years => years) <add> end <add> <add> # Short-hand for years_ago(1) <add> def last_year <add> years_ago(1) <add> end <add> <add> # Short-hand for years_since(1) <add> def next_year <add> years_since(1) <add> end <add> <add> <add> # Short-hand for months_ago(1) <add> def last_month <add> months_ago(1) <add> end <add> <add> # Short-hand for months_since(1) <add> def next_month <add> months_since(1) <add> end <add> <add> # Returns a new Time representing the "start" of this week (Monday, 0:00) <add> def beginning_of_week <add> days_to_monday = wday!=0 ? wday-1 : 6 <add> (self - days_to_monday.days).midnight <add> end <add> alias :monday :beginning_of_week <add> alias :at_beginning_of_week :beginning_of_week <add> <add> # Returns a new Time representing the end of this week (Sunday, 23:59:59) <add> def end_of_week <add> days_to_sunday = wday!=0 ? 7-wday : 0 <add> (self + days_to_sunday.days).end_of_day <add> end <add> alias :at_end_of_week :end_of_week <add> <add> # Returns a new Time representing the start of the given day in next week (default is Monday). <add> def next_week(day = :monday) <add> since(1.week).beginning_of_week.since(DAYS_INTO_WEEK[day].day).change(:hour => 0) <add> end <add> <add> # Returns a new Time representing the start of the day (0:00) <add> def beginning_of_day <add> (self - seconds_since_midnight).change(:usec => 0) <add> end <add> alias :midnight :beginning_of_day <add> alias :at_midnight :beginning_of_day <add> alias :at_beginning_of_day :beginning_of_day <add> <add> # Returns a new Time representing the end of the day (23:59:59) <add> def end_of_day <add> change(:hour => 23, :min => 59, :sec => 59) <add> end <add> <add> # Returns a new Time representing the start of the month (1st of the month, 0:00) <add> def beginning_of_month <add> #self - ((self.mday-1).days + self.seconds_since_midnight) <add> change(:day => 1,:hour => 0, :min => 0, :sec => 0, :usec => 0) <add> end <add> alias :at_beginning_of_month :beginning_of_month <add> <add> # Returns a new Time representing the end of the month (last day of the month, 0:00) <add> def end_of_month <add> #self - ((self.mday-1).days + self.seconds_since_midnight) <add> last_day = ::Time.days_in_month(month, year) <add> change(:day => last_day, :hour => 23, :min => 59, :sec => 59, :usec => 0) <add> end <add> alias :at_end_of_month :end_of_month <add> <add> # Returns a new Time representing the start of the quarter (1st of january, april, july, october, 0:00) <add> def beginning_of_quarter <add> beginning_of_month.change(:month => [10, 7, 4, 1].detect { |m| m <= month }) <add> end <add> alias :at_beginning_of_quarter :beginning_of_quarter <add> <add> # Returns a new Time representing the end of the quarter (last day of march, june, september, december, 23:59:59) <add> def end_of_quarter <add> beginning_of_month.change(:month => [3, 6, 9, 12].detect { |m| m >= month }).end_of_month <add> end <add> alias :at_end_of_quarter :end_of_quarter <add> <add> # Returns a new Time representing the start of the year (1st of january, 0:00) <add> def beginning_of_year <add> change(:month => 1, :day => 1, :hour => 0, :min => 0, :sec => 0, :usec => 0) <add> end <add> alias :at_beginning_of_year :beginning_of_year <add> <add> # Returns a new Time representing the end of the year (31st of december, 23:59:59) <add> def end_of_year <add> change(:month => 12, :day => 31, :hour => 23, :min => 59, :sec => 59) <add> end <add> alias :at_end_of_year :end_of_year <add> <add> # Convenience method which returns a new Time representing the time 1 day ago <add> def yesterday <add> advance(:days => -1) <add> end <add> <add> # Convenience method which returns a new Time representing the time 1 day since the instance time <add> def tomorrow <add> advance(:days => 1) <add> end <add> <add> def plus_with_duration(other) #:nodoc: <add> if ActiveSupport::Duration === other <add> other.since(self) <add> else <add> plus_without_duration(other) <add> end <add> end <add> alias_method :plus_without_duration, :+ <add> alias_method :+, :plus_with_duration <add> <add> def minus_with_duration(other) #:nodoc: <add> if ActiveSupport::Duration === other <add> other.until(self) <add> else <add> minus_without_duration(other) <add> end <add> end <add> alias_method :minus_without_duration, :- <add> alias_method :-, :minus_with_duration <add> <add> # Time#- can also be used to determine the number of seconds between two Time instances. <add> # We're layering on additional behavior so that ActiveSupport::TimeWithZone instances <add> # are coerced into values that Time#- will recognize <add> def minus_with_coercion(other) <add> other = other.comparable_time if other.respond_to?(:comparable_time) <add> minus_without_coercion(other) <add> end <add> alias_method :minus_without_coercion, :- <add> alias_method :-, :minus_with_coercion <add> <add> # Layers additional behavior on Time#<=> so that DateTime and ActiveSupport::TimeWithZone instances <add> # can be chronologically compared with a Time <add> def compare_with_coercion(other) <add> # if other is an ActiveSupport::TimeWithZone, coerce a Time instance from it so we can do <=> comparison <add> other = other.comparable_time if other.respond_to?(:comparable_time) <add> if other.acts_like?(:date) <add> # other is a Date/DateTime, so coerce self #to_datetime and hand off to DateTime#<=> <add> to_datetime.compare_without_coercion(other) <add> else <add> compare_without_coercion(other) <ide> end <ide> end <add> alias_method :compare_without_coercion, :<=> <add> alias_method :<=>, :compare_with_coercion <ide> end <ide><path>activesupport/lib/active_support/core_ext/time/zones.rb <del>module ActiveSupport #:nodoc: <del> module CoreExtensions #:nodoc: <del> module Time #:nodoc: <del> module Zones <del> def self.included(base) #:nodoc: <del> base.extend(ClassMethods) if base == ::Time # i.e., don't include class methods in DateTime <del> end <del> <del> module ClassMethods <del> attr_accessor :zone_default <del> <del> # Returns the TimeZone for the current request, if this has been set (via Time.zone=). <del> # If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>. <del> def zone <del> Thread.current[:time_zone] || zone_default <del> end <add>class Time <add> class << self <add> attr_accessor :zone_default <add> <add> # Returns the TimeZone for the current request, if this has been set (via Time.zone=). <add> # If <tt>Time.zone</tt> has not been set for the current request, returns the TimeZone specified in <tt>config.time_zone</tt>. <add> def zone <add> Thread.current[:time_zone] || zone_default <add> end <add> <add> # Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread. <add> # <add> # This method accepts any of the following: <add> # <add> # * A Rails TimeZone object. <add> # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>). <add> # * A TZInfo::Timezone object. <add> # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). <add> # <add> # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt> <add> # just needs to return a string identifying the user's preferred TimeZone: <add> # <add> # class ApplicationController < ActionController::Base <add> # before_filter :set_time_zone <add> # <add> # def set_time_zone <add> # Time.zone = current_user.time_zone <add> # end <add> # end <add> def zone=(time_zone) <add> Thread.current[:time_zone] = get_zone(time_zone) <add> end <add> <add> # Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done. <add> def use_zone(time_zone) <add> old_zone, ::Time.zone = ::Time.zone, get_zone(time_zone) <add> yield <add> ensure <add> ::Time.zone = old_zone <add> end <add> <add> # Returns <tt>Time.zone.now</tt> when <tt>config.time_zone</tt> is set, otherwise just returns <tt>Time.now</tt>. <add> def current <add> ::Time.zone_default ? ::Time.zone.now : ::Time.now <add> end <ide> <del> # Sets <tt>Time.zone</tt> to a TimeZone object for the current request/thread. <del> # <del> # This method accepts any of the following: <del> # <del> # * A Rails TimeZone object. <del> # * An identifier for a Rails TimeZone object (e.g., "Eastern Time (US & Canada)", <tt>-5.hours</tt>). <del> # * A TZInfo::Timezone object. <del> # * An identifier for a TZInfo::Timezone object (e.g., "America/New_York"). <del> # <del> # Here's an example of how you might set <tt>Time.zone</tt> on a per request basis -- <tt>current_user.time_zone</tt> <del> # just needs to return a string identifying the user's preferred TimeZone: <del> # <del> # class ApplicationController < ActionController::Base <del> # before_filter :set_time_zone <del> # <del> # def set_time_zone <del> # Time.zone = current_user.time_zone <del> # end <del> # end <del> def zone=(time_zone) <del> Thread.current[:time_zone] = get_zone(time_zone) <del> end <del> <del> # Allows override of <tt>Time.zone</tt> locally inside supplied block; resets <tt>Time.zone</tt> to existing value when done. <del> def use_zone(time_zone) <del> old_zone, ::Time.zone = ::Time.zone, get_zone(time_zone) <del> yield <del> ensure <del> ::Time.zone = old_zone <del> end <del> <del> # Returns <tt>Time.zone.now</tt> when <tt>config.time_zone</tt> is set, otherwise just returns <tt>Time.now</tt>. <del> def current <del> ::Time.zone_default ? ::Time.zone.now : ::Time.now <del> end <del> <del> private <del> def get_zone(time_zone) <del> return time_zone if time_zone.nil? || time_zone.is_a?(TimeZone) <del> # lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone) <del> unless time_zone.respond_to?(:period_for_local) <del> time_zone = TimeZone[time_zone] || TZInfo::Timezone.get(time_zone) rescue nil <del> end <del> # Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone <del> if time_zone <del> time_zone.is_a?(TimeZone) ? time_zone : TimeZone.create(time_zone.name, nil, time_zone) <del> end <del> end <add> private <add> def get_zone(time_zone) <add> return time_zone if time_zone.nil? || time_zone.is_a?(ActiveSupport::TimeZone) <add> # lookup timezone based on identifier (unless we've been passed a TZInfo::Timezone) <add> unless time_zone.respond_to?(:period_for_local) <add> time_zone = ActiveSupport::TimeZone[time_zone] || TZInfo::Timezone.get(time_zone) rescue nil <ide> end <del> <del> # Returns the simultaneous time in <tt>Time.zone</tt>. <del> # <del> # Time.zone = 'Hawaii' # => 'Hawaii' <del> # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 <del> # <del> # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone <del> # instead of the operating system's time zone. <del> # <del> # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument, <del> # and the conversion will be based on that zone instead of <tt>Time.zone</tt>. <del> # <del> # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 <del> def in_time_zone(zone = ::Time.zone) <del> ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.__send__(:get_zone, zone)) <add> # Return if a TimeZone instance, or wrap in a TimeZone instance if a TZInfo::Timezone <add> if time_zone <add> time_zone.is_a?(ActiveSupport::TimeZone) ? time_zone : ActiveSupport::TimeZone.create(time_zone.name, nil, time_zone) <ide> end <ide> end <del> end <ide> end <del>end <ide>\ No newline at end of file <add> <add> # Returns the simultaneous time in <tt>Time.zone</tt>. <add> # <add> # Time.zone = 'Hawaii' # => 'Hawaii' <add> # Time.utc(2000).in_time_zone # => Fri, 31 Dec 1999 14:00:00 HST -10:00 <add> # <add> # This method is similar to Time#localtime, except that it uses <tt>Time.zone</tt> as the local zone <add> # instead of the operating system's time zone. <add> # <add> # You can also pass in a TimeZone instance or string that identifies a TimeZone as an argument, <add> # and the conversion will be based on that zone instead of <tt>Time.zone</tt>. <add> # <add> # Time.utc(2000).in_time_zone('Alaska') # => Fri, 31 Dec 1999 15:00:00 AKST -09:00 <add> def in_time_zone(zone = ::Time.zone) <add> ActiveSupport::TimeWithZone.new(utc? ? self : getutc, ::Time.__send__(:get_zone, zone)) <add> end <add>end
3
Python
Python
fix train/test samples in mnist_tfrecords
c8bef99ec7a2032b9bea6e9a1260d05a2b6a80f1
<ide><path>examples/mnist_tfrecord.py <ide> tensors, save the model weights, and then evaluate the <ide> model using the numpy based Keras API. <ide> <del>Gets to ~99.1% validation accuracy after 5 epochs <add>Gets to ~99.1% test accuracy after 5 epochs <ide> (high variance from run to run: 98.9-99.3). <ide> ''' <ide> import numpy as np <del> <add>import os <ide> import tensorflow as tf <ide> import keras <ide> from keras import backend as K <ide> def cnn_layers(x_train_input): <ide> <ide> batch_size = 100 <ide> batch_shape = (batch_size, 28, 28, 1) <del>steps_per_epoch = 600 <ide> epochs = 5 <ide> num_classes = 10 <ide> <ide> def cnn_layers(x_train_input): <ide> # output will have shape `[batch_size, x, y, z]`. <ide> enqueue_many = True <ide> <del>data = mnist.load_mnist() <add>cache_dir = os.path.expanduser( <add> os.path.join('~', '.keras', 'datasets', 'MNIST-data')) <add>data = mnist.read_data_sets(cache_dir, validation_size=0) <add> <ide> x_train_batch, y_train_batch = tf.train.shuffle_batch( <ide> tensors=[data.train.images, data.train.labels.astype(np.int32)], <ide> batch_size=batch_size, <ide> def cnn_layers(x_train_input): <ide> threads = tf.train.start_queue_runners(sess, coord) <ide> <ide> train_model.fit(epochs=epochs, <del> steps_per_epoch=steps_per_epoch, <add> steps_per_epoch=int(np.ceil(data.train.num_examples / float(batch_size))), <ide> callbacks=[EvaluateInputTensor(test_model, steps=100)]) <ide> <ide> # Save the model weights. <ide> def cnn_layers(x_train_input): <ide> K.clear_session() <ide> <ide> # Second Session to test loading trained model without tensors <del>x_test = np.reshape(data.validation.images, (data.validation.images.shape[0], 28, 28, 1)) <del>y_test = data.validation.labels <add>x_test = np.reshape(data.test.images, (data.test.images.shape[0], 28, 28, 1)) <add>y_test = data.test.labels <ide> x_test_inp = layers.Input(shape=(x_test.shape[1:])) <ide> test_out = cnn_layers(x_test_inp) <ide> test_model = keras.models.Model(inputs=x_test_inp, outputs=test_out)
1
Javascript
Javascript
remove unnecessary processupdatequeue
c486dc1a46c47ad276140a51b1155eb1f8900dd8
<ide><path>packages/react-reconciler/src/ReactFiberClassComponent.new.js <ide> function mountClassInstance( <ide> } <ide> } <ide> <del> processUpdateQueue(workInProgress, newProps, instance, renderLanes); <ide> instance.state = workInProgress.memoizedState; <ide> <ide> const getDerivedStateFromProps = ctor.getDerivedStateFromProps; <ide><path>packages/react-reconciler/src/ReactFiberClassComponent.old.js <ide> function mountClassInstance( <ide> } <ide> } <ide> <del> processUpdateQueue(workInProgress, newProps, instance, renderLanes); <ide> instance.state = workInProgress.memoizedState; <ide> <ide> const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
2
Javascript
Javascript
mention "controller as" syntax
fa0d8c47c3050a5732291bcaa77e086bb3ad8569
<ide><path>src/ng/controller.js <ide> function $ControllerProvider() { <ide> * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global <ide> * `window` object (not recommended) <ide> * <add> * The string can use the `controller as property` syntax, where the controller instance is published <add> * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this <add> * to work correctly. <add> * <ide> * @param {Object} locals Injection locals for Controller. <ide> * @return {Object} Instance of given controller. <ide> *
1
Ruby
Ruby
change error messages
473bdadbcd0f87fdeda98f73b25bb47a14221281
<ide><path>Library/Homebrew/cask/lib/hbc/audit.rb <ide> def check_version_and_checksum <ide> return unless previous_cask.version == cask.version <ide> return if previous_cask.sha256 == cask.sha256 <ide> <del> add_error "only sha256 changed; needs to be confirmed by the developer" <add> add_error "only sha256 changed (see: https://github.com/caskroom/homebrew-cask/blob/master/doc/cask_language_reference/stanzas/sha256.md)" <ide> end <ide> <ide> def check_version <ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_revision_and_version_scheme <ide> next unless spec = formula.send(spec_sym) <ide> next unless previous_version_and_checksum[spec_sym][:version] == spec.version <ide> next if previous_version_and_checksum[spec_sym][:checksum] == spec.checksum <del> problem "#{spec_sym}: only sha256 changed; needs to be confirmed by the developer" <add> problem "#{spec_sym}: sha256 changed without the version also changing; please create an issue upstream to rule out malicious circumstances and to find out why the file changed." <ide> end <ide> <ide> attributes = [:revision, :version_scheme]
2
Text
Text
remove stray please
012bdac6d68f006351e43b11b258259f4af26e20
<ide><path>docs/articles/basics.md <ide> installed, use the following command: <ide> If you get `docker: command not found` or something like <ide> `/var/lib/docker/repositories: permission denied` you may have an <ide> incomplete Docker installation or insufficient privileges to access <del>Docker on your machine. Please <add>Docker on your machine. <ide> <ide> Additionally, depending on your Docker system configuration, you may be required <ide> to preface each `docker` command with `sudo`. To avoid having to use `sudo` with
1
Ruby
Ruby
exclude .github from unbrewed
6b6159a858009b6d82b858830533a4a3ce135a28
<ide><path>Library/Homebrew/cmd/list.rb <ide> def list <ide> <ide> UNBREWED_EXCLUDE_FILES = %w[.DS_Store] <ide> UNBREWED_EXCLUDE_PATHS = %w[ <add> .github/* <ide> bin/brew <ide> lib/gdk-pixbuf-2.0/* <ide> lib/gio/*
1
PHP
PHP
fix cs error
ef6642e6ff61c0492bae11eea23267c63061ca00
<ide><path>tests/TestCase/Http/Middleware/CsrfProtectionMiddlewareTest.php <ide> public function testValidTokenRequestData($method) <ide> // No exception means everything is OK <ide> $middleware = new CsrfProtectionMiddleware(); <ide> $middleware($request, $response, $closure); <del> <ide> } <ide> <ide> /**
1