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 a network test
249f5a65a55ac9f68c65d57a7e7b5ac486060b97
<ide><path>container_test.go <ide> func TestOutput(t *testing.T) { <ide> } <ide> } <ide> <add>func TestContainerNetwork(t *testing.T) { <add> runtime := mkRuntime(t) <add> defer nuke(runtime) <add> container, err := runtime.Create( <add> &Config{ <add> Image: GetTestImage(runtime).ID, <add> Cmd: []string{"ping", "-c", "1", "127.0.0.1"}, <add> }, <add> ) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer runtime.Destroy(container) <add> if err := container.Run(); err != nil { <add> t.Fatal(err) <add> } <add> if container.State.ExitCode != 0 { <add> t.Errorf("Unexpected ping 127.0.0.1 exit code %d (expected 0)", container.State.ExitCode) <add> } <add> <add> container, err = runtime.Create( <add> &Config{ <add> Image: GetTestImage(runtime).ID, <add> Cmd: []string{"ping", "-c", "1", "8.8.8.8"}, <add> }, <add> ) <add> if err != nil { <add> t.Fatal(err) <add> } <add> defer runtime.Destroy(container) <add> if err := container.Run(); err != nil { <add> t.Fatal(err) <add> } <add> if container.State.ExitCode != 0 { <add> t.Errorf("Unexpected ping 8.8.8.8 exit code %d (expected 0)", container.State.ExitCode) <add> } <add>} <add> <ide> func TestKillDifferentUser(t *testing.T) { <ide> runtime := mkRuntime(t) <ide> defer nuke(runtime)
1
Ruby
Ruby
check github tags for prerelease status
1c10f51f9855076b541001b4b033800977d31a7b
<ide><path>Library/Homebrew/dev-cmd/audit.rb <ide> def audit_specs <ide> return if stable_url_minor_version.even? <ide> <ide> problem "#{stable.version} is a development release" <del> when %r{^https://github.com/([\w-]+)/([\w-]+)/} <add> when %r{^https://github.com/([\w-]+)/([\w-]+)} <ide> owner = Regexp.last_match(1) <ide> repo = Regexp.last_match(2) <ide> tag = url.match(%r{^https://github\.com/[\w-]+/[\w-]+/archive/([^/]+)\.(tar\.gz|zip)$}) <ide> def audit_specs <ide> tag ||= url.match(%r{^https://github\.com/[\w-]+/[\w-]+/releases/download/([^/]+)/}) <ide> .to_a <ide> .second <add> tag ||= formula.stable.specs[:tag] <ide> <ide> begin <ide> if @online && (release = GitHub.open_api("#{GitHub::API_URL}/repos/#{owner}/#{repo}/releases/tags/#{tag}"))
1
Python
Python
add kernel capabilities in dockeroperator
b4b84a1933d055a2803b80b990482a7257a203ff
<ide><path>airflow/providers/docker/operators/docker.py <ide> class DockerOperator(BaseOperator): <ide> :param tty: Allocate pseudo-TTY to the container <ide> This needs to be set see logs of the Docker container. <ide> :type tty: bool <add> :param cap_add: Include container capabilities <add> :type cap_add: list[str] <ide> """ <ide> template_fields = ('command', 'environment', 'container_name') <ide> template_ext = ('.sh', '.bash',) <ide> def __init__( <ide> auto_remove: bool = False, <ide> shm_size: Optional[int] = None, <ide> tty: Optional[bool] = False, <add> cap_add: Optional[Iterable[str]] = None, <ide> *args, <ide> **kwargs) -> None: <ide> <ide> def __init__( <ide> self.docker_conn_id = docker_conn_id <ide> self.shm_size = shm_size <ide> self.tty = tty <add> self.cap_add = cap_add <ide> if kwargs.get('xcom_push') is not None: <ide> raise AirflowException("'xcom_push' was deprecated, use 'BaseOperator.do_xcom_push' instead") <ide> <ide> def _run_image(self): <ide> dns=self.dns, <ide> dns_search=self.dns_search, <ide> cpu_shares=int(round(self.cpus * 1024)), <del> mem_limit=self.mem_limit), <add> mem_limit=self.mem_limit, <add> cap_add=self.cap_add), <ide> image=self.image, <ide> user=self.user, <ide> working_dir=self.working_dir, <ide><path>tests/providers/docker/operators/test_docker.py <ide> def test_execute(self, client_class_mock, tempdir_mock): <ide> mem_limit=None, <ide> auto_remove=False, <ide> dns=None, <del> dns_search=None) <add> dns_search=None, <add> cap_add=None) <ide> tempdir_mock.assert_called_once_with(dir='/host/airflow', prefix='airflowtmp') <ide> client_mock.images.assert_called_once_with(name='ubuntu:latest') <ide> client_mock.attach.assert_called_once_with(container='some_id', stdout=True,
2
Ruby
Ruby
remove single element array preprocess
21c0e0e89176b832a286bc6381b6ca2a9a56f1de
<ide><path>activerecord/lib/active_record/associations/preloader/association.rb <ide> def load_records(&block) <ide> end <ide> <ide> def records_for(ids, &block) <del> scope.where(association_key_name => ids.size == 1 ? ids.first : ids).load(&block) <add> scope.where(association_key_name => ids).load(&block) <ide> end <ide> <ide> def scope <ide><path>activerecord/lib/active_record/relation/predicate_builder/polymorphic_array_value.rb <ide> def queries <ide> type_to_ids_mapping.map do |type, ids| <ide> { <ide> associated_table.association_foreign_type.to_s => type, <del> associated_table.association_foreign_key.to_s => ids.size > 1 ? ids : ids.first <add> associated_table.association_foreign_key.to_s => ids <ide> } <ide> end <ide> end
2
Text
Text
update suffixes example
9002bea29f30438ed85cc61a11e5547de8318acb
<ide><path>.github/contributors/jgutix.md <add># spaCy contributor agreement <add> <add>This spaCy Contributor Agreement (**"SCA"**) is based on the <add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf). <add>The SCA applies to any contribution that you make to any product or project <add>managed by us (the **"project"**), and sets out the intellectual property rights <add>you grant to us in the contributed materials. The term **"us"** shall mean <add>[ExplosionAI GmbH](https://explosion.ai/legal). The term <add>**"you"** shall mean the person or entity identified below. <add> <add>If you agree to be bound by these terms, fill in the information requested <add>below and include the filled-in version with your first pull request, under the <add>folder [`.github/contributors/`](/.github/contributors/). The name of the file <add>should be your GitHub username, with the extension `.md`. For example, the user <add>example_user would create the file `.github/contributors/example_user.md`. <add> <add>Read this agreement carefully before signing. These terms and conditions <add>constitute a binding legal agreement. <add> <add>## Contributor Agreement <add> <add>1. The term "contribution" or "contributed materials" means any source code, <add>object code, patch, tool, sample, graphic, specification, manual, <add>documentation, or any other material posted or submitted by you to the project. <add> <add>2. With respect to any worldwide copyrights, or copyright applications and <add>registrations, in your contribution: <add> <add> * you hereby assign to us joint ownership, and to the extent that such <add> assignment is or becomes invalid, ineffective or unenforceable, you hereby <add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, <add> royalty-free, unrestricted license to exercise all rights under those <add> copyrights. This includes, at our option, the right to sublicense these same <add> rights to third parties through multiple levels of sublicensees or other <add> licensing arrangements; <add> <add> * you agree that each of us can do all things in relation to your <add> contribution as if each of us were the sole owners, and if one of us makes <add> a derivative work of your contribution, the one who makes the derivative <add> work (or has it made will be the sole owner of that derivative work; <add> <add> * you agree that you will not assert any moral rights in your contribution <add> against us, our licensees or transferees; <add> <add> * you agree that we may register a copyright in your contribution and <add> exercise all ownership rights associated with it; and <add> <add> * you agree that neither of us has any duty to consult with, obtain the <add> consent of, pay or render an accounting to the other for any use or <add> distribution of your contribution. <add> <add>3. With respect to any patents you own, or that you can license without payment <add>to any third party, you hereby grant to us a perpetual, irrevocable, <add>non-exclusive, worldwide, no-charge, royalty-free license to: <add> <add> * make, have made, use, sell, offer to sell, import, and otherwise transfer <add> your contribution in whole or in part, alone or in combination with or <add> included in any product, work or materials arising out of the project to <add> which your contribution was submitted, and <add> <add> * at our option, to sublicense these same rights to third parties through <add> multiple levels of sublicensees or other licensing arrangements. <add> <add>4. Except as set out above, you keep all right, title, and interest in your <add>contribution. The rights that you grant to us under these terms are effective <add>on the date you first submitted a contribution to us, even if your submission <add>took place before the date you sign these terms. <add> <add>5. You covenant, represent, warrant and agree that: <add> <add> * Each contribution that you submit is and shall be an original work of <add> authorship and you can legally grant the rights set out in this SCA; <add> <add> * to the best of your knowledge, each contribution will not violate any <add> third party's copyrights, trademarks, patents, or other intellectual <add> property rights; and <add> <add> * each contribution shall be in compliance with U.S. export control laws and <add> other applicable export and import laws. You agree to notify us if you <add> become aware of any circumstance which would make any of the foregoing <add> representations inaccurate in any respect. We may publicly disclose your <add> participation in the project, including the fact that you have signed the SCA. <add> <add>6. This SCA is governed by the laws of the State of California and applicable <add>U.S. Federal law. Any choice of law rules will not apply. <add> <add>7. Please place an “x” on one of the applicable statement below. Please do NOT <add>mark both statements: <add> <add> * [x] I am signing on behalf of myself as an individual and no other person <add> or entity, including my employer, has or will have rights with respect to my <add> contributions. <add> <add> * [ ] I am signing on behalf of my employer or a legal entity and I have the <add> actual authority to contractually bind that entity. <add> <add>## Contributor Details <add> <add>| Field | Entry | <add>|------------------------------- | -------------------- | <add>| Name | Juan Gutiérrez | <add>| Company name (if applicable) | Ojtli | <add>| Title or role (if applicable) | | <add>| Date | 2020-08-28 | <add>| GitHub username | jgutix | <add>| Website (optional) | ojtli.app | <ide><path>website/docs/usage/linguistic-features.md <ide> expressions – for example, <ide> [`compile_suffix_regex`](/api/top-level#util.compile_suffix_regex): <ide> <ide> ```python <del>suffixes = nlp.Defaults.suffixes + (r'''-+$''',) <add>suffixes = nlp.Defaults.suffixes + [r'''-+$''',] <ide> suffix_regex = spacy.util.compile_suffix_regex(suffixes) <ide> nlp.tokenizer.suffix_search = suffix_regex.search <ide> ```
2
Mixed
Go
add networks placeholder to ps --format
a43d9bb9c399958e64deb5e827e6716ad1ef0e41
<ide><path>cli/command/container/list.go <ide> func (p *preProcessor) Size() bool { <ide> return true <ide> } <ide> <add>// Networks does nothing but return true. <add>// It is needed to avoid the template check to fail as this field <add>// doesn't exist in `types.Container` <add>func (p *preProcessor) Networks() bool { <add> return true <add>} <add> <ide> func buildContainerListOptions(opts *psOptions) (*types.ContainerListOptions, error) { <ide> options := &types.ContainerListOptions{ <ide> All: opts.all, <ide><path>cli/command/formatter/container.go <ide> const ( <ide> portsHeader = "PORTS" <ide> mountsHeader = "MOUNTS" <ide> localVolumes = "LOCAL VOLUMES" <add> networksHeader = "NETWORKS" <ide> ) <ide> <ide> // NewContainerFormat returns a Format for rendering using a Context <ide> func (c *containerContext) LocalVolumes() string { <ide> <ide> return fmt.Sprintf("%d", count) <ide> } <add> <add>func (c *containerContext) Networks() string { <add> c.AddHeader(networksHeader) <add> <add> if c.c.NetworkSettings == nil { <add> return "" <add> } <add> <add> networks := []string{} <add> for k := range c.c.NetworkSettings.Networks { <add> networks = append(networks, k) <add> } <add> <add> return strings.Join(networks, ",") <add>} <ide><path>cli/command/formatter/container_test.go <ide> func TestContainerContextWriteJSON(t *testing.T) { <ide> } <ide> expectedCreated := time.Unix(unix, 0).String() <ide> expectedJSONs := []map[string]interface{}{ <del> {"Command": "\"\"", "CreatedAt": expectedCreated, "ID": "containerID1", "Image": "ubuntu", "Labels": "", "LocalVolumes": "0", "Mounts": "", "Names": "foobar_baz", "Ports": "", "RunningFor": "About a minute", "Size": "0 B", "Status": ""}, <del> {"Command": "\"\"", "CreatedAt": expectedCreated, "ID": "containerID2", "Image": "ubuntu", "Labels": "", "LocalVolumes": "0", "Mounts": "", "Names": "foobar_bar", "Ports": "", "RunningFor": "About a minute", "Size": "0 B", "Status": ""}, <add> {"Command": "\"\"", "CreatedAt": expectedCreated, "ID": "containerID1", "Image": "ubuntu", "Labels": "", "LocalVolumes": "0", "Mounts": "", "Names": "foobar_baz", "Networks": "", "Ports": "", "RunningFor": "About a minute", "Size": "0 B", "Status": ""}, <add> {"Command": "\"\"", "CreatedAt": expectedCreated, "ID": "containerID2", "Image": "ubuntu", "Labels": "", "LocalVolumes": "0", "Mounts": "", "Names": "foobar_bar", "Networks": "", "Ports": "", "RunningFor": "About a minute", "Size": "0 B", "Status": ""}, <ide> } <ide> out := bytes.NewBufferString("") <ide> err := ContainerWrite(Context{Format: "{{json .}}", Output: out}, containers) <ide><path>docs/reference/commandline/ps.md <ide> Placeholder | Description <ide> `.Labels` | All labels assigned to the container. <ide> `.Label` | Value of a specific label for this container. For example `'{{.Label "com.docker.swarm.cpu"}}'` <ide> `.Mounts` | Names of the volumes mounted in this container. <add>`.Networks` | Names of the networks attached to this container. <ide> <ide> When using the `--format` option, the `ps` command will either output the data <ide> exactly as the template declares or, when using the `table` directive, includes
4
Java
Java
improve api for rfc 7807 in functional endpoints
0348a7bf2e712ad8488f24a289fb2a1c487db17d
<ide><path>spring-web/src/main/java/org/springframework/http/ResponseEntity.java <ide> public static <T> ResponseEntity<T> of(Optional<T> body) { <ide> } <ide> <ide> /** <del> * Create a builder for a {@code ResponseEntity} with the given <del> * {@link ProblemDetail} as the body, and its <del> * {@link ProblemDetail#getStatus() status} as the status. <del> * <p>Note that {@code ProblemDetail} is supported as a return value from <del> * controller methods and from {@code @ExceptionHandler} methods. The method <del> * here is convenient to also add response headers. <del> * @param body the details for an HTTP error response <add> * Create a new {@link HeadersBuilder} with its status set to <add> * {@link ProblemDetail#getStatus()} and its body is set to <add> * {@link ProblemDetail}. <add> * <p><strong>Note:</strong> If there are no headers to add, there is usually <add> * no need to create a {@link ResponseEntity} since {@code ProblemDetail} <add> * is also supported as a return value from controller methods. <add> * @param body the problem detail to use <ide> * @return the created builder <ide> * @since 6.0 <ide> */ <ide><path>spring-web/src/main/java/org/springframework/web/DefaultErrorResponseBuilder.java <add>/* <add> * Copyright 2002-2022 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * https://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web; <add> <add>import java.net.URI; <add>import java.util.function.Consumer; <add> <add>import org.springframework.http.HttpHeaders; <add>import org.springframework.http.HttpStatusCode; <add>import org.springframework.http.ProblemDetail; <add>import org.springframework.lang.Nullable; <add>import org.springframework.util.Assert; <add> <add> <add>/** <add> * Default implementation of {@link ErrorResponse.Builder}. <add> * <add> * @author Rossen Stoyanchev <add> * @since 6.0 <add> */ <add>final class DefaultErrorResponseBuilder implements ErrorResponse.Builder { <add> <add> private final Throwable exception; <add> <add> private final HttpStatusCode statusCode; <add> <add> @Nullable <add> private HttpHeaders headers; <add> <add> private final ProblemDetail problemDetail; <add> <add> private String detailMessageCode; <add> <add> @Nullable <add> private Object[] detailMessageArguments; <add> <add> private String titleMessageCode; <add> <add> <add> DefaultErrorResponseBuilder(Throwable ex, HttpStatusCode statusCode, String detail) { <add> Assert.notNull(ex, "Throwable is required"); <add> Assert.notNull(ex, "HttpStatusCode is required"); <add> Assert.notNull(ex, "`detail` is required"); <add> this.exception = ex; <add> this.statusCode = statusCode; <add> this.problemDetail = ProblemDetail.forStatusAndDetail(statusCode, detail); <add> this.detailMessageCode = ErrorResponse.getDefaultDetailMessageCode(ex.getClass(), null); <add> this.titleMessageCode = ErrorResponse.getDefaultTitleMessageCode(ex.getClass()); <add> } <add> <add> <add> @Override <add> public ErrorResponse.Builder header(String headerName, String... headerValues) { <add> this.headers = (this.headers != null ? this.headers : new HttpHeaders()); <add> for (String headerValue : headerValues) { <add> this.headers.add(headerName, headerValue); <add> } <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder headers(Consumer<HttpHeaders> headersConsumer) { <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder detail(String detail) { <add> this.problemDetail.setDetail(detail); <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder detailMessageCode(String messageCode) { <add> Assert.notNull(messageCode, "`detailMessageCode` is required"); <add> this.detailMessageCode = messageCode; <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder detailMessageArguments(Object... messageArguments) { <add> this.detailMessageArguments = messageArguments; <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder type(URI type) { <add> this.problemDetail.setType(type); <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder title(@Nullable String title) { <add> this.problemDetail.setTitle(title); <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder titleMessageCode(String messageCode) { <add> Assert.notNull(messageCode, "`titleMessageCode` is required"); <add> this.titleMessageCode = messageCode; <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder instance(@Nullable URI instance) { <add> this.problemDetail.setInstance(instance); <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse.Builder property(String name, Object value) { <add> this.problemDetail.setProperty(name, value); <add> return this; <add> } <add> <add> @Override <add> public ErrorResponse build() { <add> return new SimpleErrorResponse( <add> this.exception, this.statusCode, this.headers, this.problemDetail, <add> this.detailMessageCode, this.detailMessageArguments, this.titleMessageCode); <add> } <add> <add> <add> /** <add> * Simple container for {@code ErrorResponse} values. <add> */ <add> private static class SimpleErrorResponse implements ErrorResponse { <add> <add> private final Throwable exception; <add> <add> private final HttpStatusCode statusCode; <add> <add> private final HttpHeaders headers; <add> <add> private final ProblemDetail problemDetail; <add> <add> private final String detailMessageCode; <add> <add> @Nullable <add> private final Object[] detailMessageArguments; <add> <add> private final String titleMessageCode; <add> <add> SimpleErrorResponse( <add> Throwable ex, HttpStatusCode statusCode, @Nullable HttpHeaders headers, ProblemDetail problemDetail, <add> String detailMessageCode, @Nullable Object[] detailMessageArguments, String titleMessageCode) { <add> <add> this.exception = ex; <add> this.statusCode = statusCode; <add> this.headers = (headers != null ? headers : HttpHeaders.EMPTY); <add> this.problemDetail = problemDetail; <add> this.detailMessageCode = detailMessageCode; <add> this.detailMessageArguments = detailMessageArguments; <add> this.titleMessageCode = titleMessageCode; <add> } <add> <add> @Override <add> public HttpStatusCode getStatusCode() { <add> return this.statusCode; <add> } <add> <add> @Override <add> public HttpHeaders getHeaders() { <add> return this.headers; <add> } <add> <add> @Override <add> public ProblemDetail getBody() { <add> return this.problemDetail; <add> } <add> <add> @Override <add> public String getDetailMessageCode() { <add> return this.detailMessageCode; <add> } <add> <add> @Override <add> public Object[] getDetailMessageArguments() { <add> return this.detailMessageArguments; <add> } <add> <add> @Override <add> public String getTitleMessageCode() { <add> return this.titleMessageCode; <add> } <add> <add> @Override <add> public String toString() { <add> return "ErrorResponse{status=" + this.statusCode + ", " + <add> "headers=" + this.headers + ", body=" + this.problemDetail + ", " + <add> "exception=" + this.exception + "}"; <add> } <add> } <add> <add>} <ide><path>spring-web/src/main/java/org/springframework/web/ErrorResponse.java <ide> <ide> package org.springframework.web; <ide> <add>import java.net.URI; <ide> import java.util.Locale; <add>import java.util.function.Consumer; <ide> <ide> import org.springframework.context.MessageSource; <ide> import org.springframework.http.HttpHeaders; <ide> static String getDefaultTitleMessageCode(Class<?> exceptionType) { <ide> return "problemDetail.title." + exceptionType.getName(); <ide> } <ide> <add> <ide> /** <del> * Map the given Exception to an {@link ErrorResponse}. <del> * @param ex the Exception, mostly to derive message codes, if not provided <del> * @param status the response status to use <del> * @param headers optional headers to add to the response <del> * @param defaultDetail default value for the "detail" field <del> * @param detailMessageCode the code to use to look up the "detail" field <del> * through a {@code MessageSource}, falling back on <del> * {@link #getDefaultDetailMessageCode(Class, String)} <del> * @param detailMessageArguments the arguments to go with the detailMessageCode <del> * @return the created {@code ErrorResponse} instance <add> * Static factory method to build an instance via <add> * {@link #builder(Throwable, HttpStatusCode, String)}. <ide> */ <del> static ErrorResponse createFor( <del> Exception ex, HttpStatusCode status, @Nullable HttpHeaders headers, <del> String defaultDetail, @Nullable String detailMessageCode, @Nullable Object[] detailMessageArguments) { <add> static ErrorResponse create(Throwable ex, HttpStatusCode statusCode, String detail) { <add> return builder(ex, statusCode, detail).build(); <add> } <ide> <del> if (detailMessageCode == null) { <del> detailMessageCode = ErrorResponse.getDefaultDetailMessageCode(ex.getClass(), null); <del> } <add> /** <add> * Return a builder to create an {@code ErrorResponse} instance. <add> * @param ex the underlying exception that lead to the error response; <add> * mainly to derive default values for the <add> * {@link #getDetailMessageCode() detail message code} and for the <add> * {@link #getTitleMessageCode() title message code}. <add> * @param statusCode the status code to set the response to <add> * @param detail the default value for the <add> * {@link ProblemDetail#setDetail(String) detail} field, unless overridden <add> * by a {@link MessageSource} lookup with {@link #getDetailMessageCode()} <add> */ <add> static Builder builder(Throwable ex, HttpStatusCode statusCode, String detail) { <add> return new DefaultErrorResponseBuilder(ex, statusCode, detail); <add> } <ide> <del> ErrorResponseException errorResponse = new ErrorResponseException( <del> status, ProblemDetail.forStatusAndDetail(status, defaultDetail), null, <del> detailMessageCode, detailMessageArguments); <ide> <del> if (headers != null) { <del> errorResponse.getHeaders().putAll(headers); <del> } <add> /** <add> * Builder for an {@code ErrorResponse}. <add> */ <add> interface Builder { <add> <add> /** <add> * Add the given header value(s) under the given name. <add> * @param headerName the header name <add> * @param headerValues the header value(s) <add> * @return the same builder instance <add> * @see HttpHeaders#add(String, String) <add> */ <add> Builder header(String headerName, String... headerValues); <add> <add> /** <add> * Manipulate this response's headers with the given consumer. This is <add> * useful to {@linkplain HttpHeaders#set(String, String) overwrite} or <add> * {@linkplain HttpHeaders#remove(Object) remove} existing values, or <add> * use any other {@link HttpHeaders} methods. <add> * @param headersConsumer a function that consumes the {@code HttpHeaders} <add> * @return the same builder instance <add> */ <add> Builder headers(Consumer<HttpHeaders> headersConsumer); <add> <add> /** <add> * Set the underlying {@link ProblemDetail#setDetail(String)}. <add> * @return the same builder instance <add> */ <add> Builder detail(String detail); <add> <add> /** <add> * Customize the {@link MessageSource} code for looking up the value for <add> * the underlying {@link #detail(String)}. <add> * <p>By default, this is set to <add> * {@link ErrorResponse#getDefaultDetailMessageCode(Class, String)} with the <add> * associated Exception type. <add> * @param messageCode the message code to use <add> * @return the same builder instance <add> * @see ErrorResponse#getDetailMessageCode() <add> */ <add> Builder detailMessageCode(String messageCode); <add> <add> /** <add> * Set the arguments to provide to the {@link MessageSource} lookup for <add> * {@link #detailMessageCode(String)}. <add> * @param messageArguments the arguments to provide <add> * @return the same builder instance <add> * @see ErrorResponse#getDetailMessageArguments() <add> */ <add> Builder detailMessageArguments(Object... messageArguments); <add> <add> /** <add> * Set the underlying {@link ProblemDetail#setTitle(String)} field. <add> * @return the same builder instance <add> */ <add> Builder type(URI type); <add> <add> /** <add> * Set the underlying {@link ProblemDetail#setTitle(String)} field. <add> * @return the same builder instance <add> */ <add> Builder title(@Nullable String title); <add> <add> /** <add> * Customize the {@link MessageSource} code for looking up the value for <add> * the underlying {@link ProblemDetail#setTitle(String)}. <add> * <p>By default, set via <add> * {@link ErrorResponse#getDefaultTitleMessageCode(Class)} with the <add> * associated Exception type. <add> * @param messageCode the message code to use <add> * @return the same builder instance <add> * @see ErrorResponse#getTitleMessageCode() <add> */ <add> Builder titleMessageCode(String messageCode); <add> <add> /** <add> * Set the underlying {@link ProblemDetail#setInstance(URI)} field. <add> * @return the same builder instance <add> */ <add> Builder instance(@Nullable URI instance); <add> <add> /** <add> * Set a "dynamic" {@link ProblemDetail#setProperty(String, Object) <add> * property} on the underlying {@code ProblemDetail}. <add> * @return the same builder instance <add> */ <add> Builder property(String name, Object value); <add> <add> /** <add> * Build the {@code ErrorResponse} instance. <add> */ <add> ErrorResponse build(); <ide> <del> return errorResponse; <ide> } <ide> <ide> } <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/ServerResponse.java <ide> import org.springframework.http.codec.json.Jackson2CodecSupport; <ide> import org.springframework.http.server.reactive.ServerHttpResponse; <ide> import org.springframework.util.MultiValueMap; <add>import org.springframework.web.ErrorResponse; <ide> import org.springframework.web.reactive.function.BodyInserter; <ide> import org.springframework.web.reactive.function.BodyInserters; <ide> import org.springframework.web.reactive.result.view.ViewResolver; <ide> static BodyBuilder from(ServerResponse other) { <ide> return new DefaultServerResponseBuilder(other); <ide> } <ide> <add> /** <add> * Create a {@code ServerResponse} from the given {@link ErrorResponse}. <add> * @param response the {@link ErrorResponse} to initialize from <add> * @return {@code Mono} with the built response <add> * @since 6.0 <add> */ <add> static Mono<ServerResponse> from(ErrorResponse response) { <add> return status(response.getStatusCode()) <add> .headers(headers -> headers.putAll(response.getHeaders())) <add> .bodyValue(response.getBody()); <add> } <add> <ide> /** <ide> * Create a builder with the given HTTP status. <ide> * @param status the response status <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityExceptionHandler.java <ide> protected ProblemDetail createProblemDetail( <ide> Exception ex, HttpStatusCode status, String defaultDetail, @Nullable String detailMessageCode, <ide> @Nullable Object[] detailMessageArguments, ServerWebExchange exchange) { <ide> <del> ErrorResponse response = ErrorResponse.createFor( <del> ex, status, null, defaultDetail, detailMessageCode, detailMessageArguments); <del> <del> return response.updateAndGetBody(this.messageSource, getLocale(exchange)); <add> ErrorResponse.Builder builder = ErrorResponse.builder(ex, status, defaultDetail); <add> if (detailMessageCode != null) { <add> builder.detailMessageCode(detailMessageCode); <add> } <add> if (detailMessageArguments != null) { <add> builder.detailMessageArguments(detailMessageArguments); <add> } <add> return builder.build().updateAndGetBody(this.messageSource, getLocale(exchange)); <ide> } <ide> <ide> private static Locale getLocale(ServerWebExchange exchange) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/function/ServerResponse.java <ide> import org.springframework.http.converter.HttpMessageConverter; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.MultiValueMap; <add>import org.springframework.web.ErrorResponse; <ide> import org.springframework.web.servlet.ModelAndView; <ide> <ide> /** <ide> static BodyBuilder from(ServerResponse other) { <ide> return new DefaultServerResponseBuilder(other); <ide> } <ide> <add> /** <add> * Create a {@code ServerResponse} from the given {@link ErrorResponse}. <add> * @param response the {@link ErrorResponse} to initialize from <add> * @return the built response <add> * @since 6.0 <add> */ <add> static ServerResponse from(ErrorResponse response) { <add> return status(response.getStatusCode()) <add> .headers(headers -> headers.putAll(response.getHeaders())) <add> .body(response.getBody()); <add> } <add> <ide> /** <ide> * Create a builder with the given HTTP status. <ide> * @param status the response status <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ResponseEntityExceptionHandler.java <ide> protected ProblemDetail createProblemDetail( <ide> Exception ex, HttpStatusCode status, String defaultDetail, @Nullable String detailMessageCode, <ide> @Nullable Object[] detailMessageArguments, WebRequest request) { <ide> <del> ErrorResponse errorResponse = ErrorResponse.createFor( <del> ex, status, null, defaultDetail, detailMessageCode, detailMessageArguments); <del> <del> return errorResponse.updateAndGetBody(this.messageSource, LocaleContextHolder.getLocale()); <add> ErrorResponse.Builder builder = ErrorResponse.builder(ex, status, defaultDetail); <add> if (detailMessageCode != null) { <add> builder.detailMessageCode(detailMessageCode); <add> } <add> if (detailMessageArguments != null) { <add> builder.detailMessageArguments(detailMessageArguments); <add> } <add> return builder.build().updateAndGetBody(this.messageSource, LocaleContextHolder.getLocale()); <ide> } <ide> <ide> /**
7
Javascript
Javascript
tweak the logic for fixing event.which. fixes
e3c4e5789743eecb3cbe2b626f3a5f09c616ee4b
<ide><path>src/event.js <ide> jQuery.event = { <ide> } <ide> <ide> // Add which for key events <del> if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) { <del> event.which = event.charCode || event.keyCode; <add> if ( event.which == null && (event.charCode != null || event.charCode != null) ) { <add> event.which = event.charCode != null ? event.charCode : event.keyCode; <ide> } <ide> <ide> // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
1
Text
Text
add missing info to routing.md about anchors
7a7e0a9afcb2bd4e305438765634ca3c6f6a3319
<ide><path>guides/source/routing.md <ide> get 'photos/:id', to: 'photos#show', id: /[A-Z]\d{5}/ <ide> get '/:id', to: 'articles#show', constraints: { id: /^\d/ } <ide> ``` <ide> <del>However, note that you don't need to use anchors because all routes are anchored at the start. <add>However, note that you don't need to use anchors because all routes are anchored at the start and the end. <ide> <ide> For example, the following routes would allow for `articles` with `to_param` values like `1-hello-world` that always begin with a number and `users` with `to_param` values like `david` that never begin with a number to share the root namespace: <ide>
1
Javascript
Javascript
add more error checking for font translation
49c4196ec0c6f1ca5459412a0f10ab1cd72b5fe8
<ide><path>pdf.js <ide> var CanvasGraphics = (function() { <ide> constructor.prototype = { <ide> translateFont: function(fontDict, xref, resources) { <ide> var descriptor = xref.fetch(fontDict.get("FontDescriptor")); <del> var fontName = descriptor.get("FontName").name; <del> fontName = fontName.replace("+", "_"); <add> <add> var fontName = descriptor.get("FontName"); <add> assertWellFormed(IsName(fontName), "invalid font name"); <add> fontName = fontName.name.replace("+", "_"); <ide> <ide> var fontFile = descriptor.get2("FontFile", "FontFile2"); <ide> if (!fontFile) <ide> var CanvasGraphics = (function() { <ide> <ide> // Get the font charset if any <ide> var charset = descriptor.get("CharSet"); <del> if (charset) <del> charset = charset.split("/"); <add> assertWellFormed(IsString(charset), "invalid charset"); <ide> <add> charset = charset.split("/"); <ide> } else if (IsName(encoding)) { <del> var encoding = Encodings[encoding]; <add> var encoding = Encodings[encoding.name]; <ide> if (!encoding) <ide> error("Unknown encoding"); <ide> <ide> var widths = xref.fetchIfRef(fontDict.get("Widths")); <ide> var firstChar = xref.fetchIfRef(fontDict.get("FirstChar")); <del> alert(firstchar); <ide> assertWellFormed(IsArray(widths) && IsInteger(firstChar), <ide> "invalid Widths or FirstChar"); <ide> var charset = []; <ide> var CanvasGraphics = (function() { <ide> <ide> return { <ide> name: fontName, <del> file: fontFile, <del> properties: properties <add> file: fontFile, <add> properties: properties <ide> } <ide> }, <ide>
1
Text
Text
add annotation to writefile `data` as `object`
6a4b4ce4880f6f4e37adce9dd4bcdf87af8cd0e0
<ide><path>doc/api/fs.md <ide> changes: <ide> <ide> Write `buffer` to the file. <ide> <add>If `buffer` is a plain object, it must have an own (not inherited) `toString` <add>function property. <add> <ide> The promise is resolved with an object containing two properties: <ide> <ide> * `bytesWritten` {integer} the number of bytes written <ide> changes: <ide> * Returns: {Promise} Fulfills with `undefined` upon success. <ide> <ide> Asynchronously writes data to a file, replacing the file if it already exists. <del>`data` can be a string, a {Buffer}, or an object with an own `toString` function <del>property. <add>`data` can be a string, a {Buffer}, or, an object with an own (not inherited) <add>`toString` function property. <ide> <ide> The `encoding` option is ignored if `data` is a buffer. <ide> <ide> When `file` is a file descriptor, the behavior is similar to calling <ide> a file descriptor. <ide> <ide> The `encoding` option is ignored if `data` is a buffer. <del>If `data` is a normal object, it must have an own `toString` function property. <add> <add>If `data` is a plain object, it must have an own (not inherited) `toString` <add>function property. <ide> <ide> ```mjs <ide> import { writeFile } from 'fs'; <ide> changes: <ide> <ide> Returns `undefined`. <ide> <add>If `data` is a plain object, it must have an own (not inherited) `toString` <add>function property. <add> <ide> For detailed information, see the documentation of the asynchronous version of <ide> this API: [`fs.writeFile()`][]. <ide> <ide> changes: <ide> * `position` {integer} <ide> * Returns: {number} The number of bytes written. <ide> <add>If `buffer` is a plain object, it must have an own (not inherited) `toString` <add>function property. <add> <ide> For detailed information, see the documentation of the asynchronous version of <ide> this API: [`fs.write(fd, buffer...)`][]. <ide> <ide> changes: <ide> * `encoding` {string} <ide> * Returns: {number} The number of bytes written. <ide> <add>If `string` is a plain object, it must have an own (not inherited) `toString` <add>function property. <add> <ide> For detailed information, see the documentation of the asynchronous version of <ide> this API: [`fs.write(fd, string...)`][]. <ide>
1
Javascript
Javascript
fix incorrect use of int_max in validation
761bbfbd76a54f9e1bfcab7f903f0522a015d153
<ide><path>lib/internal/crypto/pbkdf2.js <ide> const { internalBinding } = require('internal/bootstrap/loaders'); <ide> const { AsyncWrap, Providers } = internalBinding('async_wrap'); <ide> const { Buffer } = require('buffer'); <del>const { INT_MAX, pbkdf2: _pbkdf2 } = internalBinding('crypto'); <del>const { validateInt32 } = require('internal/validators'); <add>const { pbkdf2: _pbkdf2 } = internalBinding('crypto'); <add>const { validateUint32 } = require('internal/validators'); <ide> const { <ide> ERR_CRYPTO_INVALID_DIGEST, <ide> ERR_CRYPTO_PBKDF2_ERROR, <ide> function check(password, salt, iterations, keylen, digest, callback) { <ide> <ide> password = validateArrayBufferView(password, 'password'); <ide> salt = validateArrayBufferView(salt, 'salt'); <del> iterations = validateInt32(iterations, 'iterations', 0, INT_MAX); <del> keylen = validateInt32(keylen, 'keylen', 0, INT_MAX); <add> iterations = validateUint32(iterations, 'iterations', 0); <add> keylen = validateUint32(keylen, 'keylen', 0); <ide> <ide> return { password, salt, iterations, keylen, digest }; <ide> } <ide><path>lib/internal/crypto/scrypt.js <ide> const { internalBinding } = require('internal/bootstrap/loaders'); <ide> const { AsyncWrap, Providers } = internalBinding('async_wrap'); <ide> const { Buffer } = require('buffer'); <del>const { INT_MAX, scrypt: _scrypt } = internalBinding('crypto'); <del>const { validateInt32 } = require('internal/validators'); <add>const { scrypt: _scrypt } = internalBinding('crypto'); <add>const { validateUint32 } = require('internal/validators'); <ide> const { <ide> ERR_CRYPTO_SCRYPT_INVALID_PARAMETER, <ide> ERR_CRYPTO_SCRYPT_NOT_SUPPORTED, <ide> function check(password, salt, keylen, options, callback) { <ide> <ide> password = validateArrayBufferView(password, 'password'); <ide> salt = validateArrayBufferView(salt, 'salt'); <del> keylen = validateInt32(keylen, 'keylen', 0, INT_MAX); <add> keylen = validateUint32(keylen, 'keylen'); <ide> <ide> let { N, r, p, maxmem } = defaults; <ide> if (options && options !== defaults) { <ide> let has_N, has_r, has_p; <ide> if (has_N = (options.N !== undefined)) <del> N = validateInt32(options.N, 'N', 0, INT_MAX); <add> N = validateUint32(options.N, 'N'); <ide> if (options.cost !== undefined) { <ide> if (has_N) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER(); <del> N = validateInt32(options.cost, 'cost', 0, INT_MAX); <add> N = validateUint32(options.cost, 'cost'); <ide> } <ide> if (has_r = (options.r !== undefined)) <del> r = validateInt32(options.r, 'r', 0, INT_MAX); <add> r = validateUint32(options.r, 'r'); <ide> if (options.blockSize !== undefined) { <ide> if (has_r) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER(); <del> r = validateInt32(options.blockSize, 'blockSize', 0, INT_MAX); <add> r = validateUint32(options.blockSize, 'blockSize'); <ide> } <ide> if (has_p = (options.p !== undefined)) <del> p = validateInt32(options.p, 'p', 0, INT_MAX); <add> p = validateUint32(options.p, 'p'); <ide> if (options.parallelization !== undefined) { <ide> if (has_p) throw new ERR_CRYPTO_SCRYPT_INVALID_PARAMETER(); <del> p = validateInt32(options.parallelization, 'parallelization', 0, INT_MAX); <add> p = validateUint32(options.parallelization, 'parallelization'); <ide> } <ide> if (options.maxmem !== undefined) <del> maxmem = validateInt32(options.maxmem, 'maxmem', 0, INT_MAX); <add> maxmem = validateUint32(options.maxmem, 'maxmem'); <ide> if (N === 0) N = defaults.N; <ide> if (r === 0) r = defaults.r; <ide> if (p === 0) p = defaults.p; <ide><path>test/parallel/test-crypto-pbkdf2.js <ide> if (!common.hasCrypto) <ide> const assert = require('assert'); <ide> const crypto = require('crypto'); <ide> <del>const { INT_MAX } = process.binding('constants').crypto; <del> <ide> // <ide> // Test PBKDF2 with RFC 6070 test vectors (except #4) <ide> // <ide> assert.throws( <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError [ERR_OUT_OF_RANGE]', <ide> message: 'The value of "iterations" is out of range. ' + <del> 'It must be >= 0 && <= 2147483647. Received -1' <add> 'It must be >= 0 && < 4294967296. Received -1' <ide> } <ide> ); <ide> <ide> assert.throws( <ide> }); <ide> }); <ide> <del>[-1, 4073741824, INT_MAX + 1].forEach((input) => { <add>[-1, 4294967297].forEach((input) => { <ide> assert.throws( <ide> () => { <ide> crypto.pbkdf2('password', 'salt', 1, input, 'sha256', <ide> assert.throws( <ide> code: 'ERR_OUT_OF_RANGE', <ide> name: 'RangeError [ERR_OUT_OF_RANGE]', <ide> message: 'The value of "keylen" is out of range. It ' + <del> `must be >= 0 && <= 2147483647. Received ${input}` <add> `must be >= 0 && < 4294967296. Received ${input}` <ide> }); <ide> }); <ide>
3
Python
Python
drop unneeded comment
f51bb5ac8bf17fb03ab8c765c14b6e01ae3d0121
<ide><path>rest_framework/schemas.py <ide> def get_path_fields(self, path, method, view): <ide> try: <ide> model_field = model._meta.get_field(variable) <ide> except: <del> model_field = None # Set model_field to None so it doesn't fail test <add> model_field = None <ide> <ide> if model_field is not None and model_field.verbose_name: <ide> title = force_text(model_field.verbose_name)
1
Javascript
Javascript
add capture to supported attributes
3092454940dd4ffae6e47d6540f8dc124c576371
<ide><path>src/renderers/dom/shared/HTMLDOMPropertyConfig.js <ide> var HTMLDOMPropertyConfig = { <ide> // autoFocus is polyfilled/normalized by AutoFocusMixin <ide> // autoFocus: HAS_BOOLEAN_VALUE, <ide> autoPlay: HAS_BOOLEAN_VALUE, <add> capture: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, <ide> cellPadding: null, <ide> cellSpacing: null, <ide> charSet: MUST_USE_ATTRIBUTE,
1
Javascript
Javascript
add a test for index()
8e54b167cf60a6efa0e572d31f3886c3cfe74c0b
<ide><path>test/unit/core.js <ide> test("each(Function)", function() { <ide> ok( pass, "Execute a function, Relative" ); <ide> }); <ide> <add>test("index()", function() { <add> expect(1); <add> <add> equals( jQuery("#text2").index(), 2, "Returns the index of a child amongst its siblings" ) <add>}); <add> <ide> test("index(Object|String|undefined)", function() { <ide> expect(16); <ide>
1
PHP
PHP
use mb_string function
a7d16c006099a706a0403fafcb87bdeff9dea325
<ide><path>src/Utility/Text.php <ide> public static function wrapBlock($text, $options = []) <ide> $wrapped = self::wrap($text, $options); <ide> <ide> if (!empty($options['indent'])) { <del> $indentationLength = strlen($options['indent']); <add> $indentationLength = mb_strlen($options['indent']); <ide> $chunks = explode("\n", $wrapped); <ide> $count = count($chunks); <ide> if ($count < 2) { <ide> return $wrapped; <ide> } <ide> $toRewrap = ''; <ide> for ($i = $options['indentAt']; $i < $count; $i++) { <del> $toRewrap .= substr($chunks[$i], $indentationLength) . ' '; <add> $toRewrap .= mb_substr($chunks[$i], $indentationLength) . ' '; <ide> unset($chunks[$i]); <ide> } <ide> $options['width'] -= $indentationLength; <ide><path>tests/TestCase/Utility/TextTest.php <ide> public function testWrapBlockWithIndentAt1() <ide> $this->assertTextEquals($expected, $result); <ide> } <ide> <add> /** <add> * test wrapBlock() indenting with multibyte caracters <add> * <add> * @return void <add> */ <add> public function testWrapBlockIndentWithMultibyte() <add> { <add> $text = 'This is the song that never ends. 这是永远不会结束的歌曲。 This is the song that never ends.'; <add> $result = Text::wrapBlock($text, ['width' => 33, 'indent' => " → ", 'indentAt' => 1]); <add> $expected = <<<TEXT <add>This is the song that never ends. <add> → 这是永远不会结束的歌曲。 This is the song <add> → that never ends. <add>TEXT; <add> $this->assertTextEquals($expected, $result); <add> } <add> <ide> /** <ide> * testTruncate method <ide> *
2
Text
Text
fix typo in changelog for 1.8.3
b5aa42586e5750b780324bb50e6a0bffda8cb6be
<ide><path>CHANGELOG.md <ide> and [read the end of life announcement](https://goo.gle/angularjs-end-of-life).* <ide> **Visit [angular.io](https://angular.io) for the actively supported Angular.** <ide> <ide> <a name="1.8.3"></a> <del># 1.8.2 ultimate-farewell (2020-10-21) <add># 1.8.3 ultimate-farewell (2020-10-21) <ide> <ide> One final release of AngularJS in order to update package README files on npm. <ide>
1
Javascript
Javascript
follow jquery logic for nested params
2420a0a77e27b530dbb8c41319b2995eccf76791
<ide><path>src/ng/http.js <ide> var JSON_ENDS = { <ide> }; <ide> var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/; <ide> <del>function paramSerializerFactory(jQueryMode) { <del> <del> function serializeValue(v) { <del> if (isObject(v)) { <del> return isDate(v) ? v.toISOString() : toJson(v); <del> } <del> return v; <add>function serializeValue(v) { <add> if (isObject(v)) { <add> return isDate(v) ? v.toISOString() : toJson(v); <ide> } <del> <del> return function paramSerializer(params) { <del> if (!params) return ''; <del> var parts = []; <del> forEachSorted(params, function(value, key) { <del> if (value === null || isUndefined(value)) return; <del> if (isArray(value) || isObject(value) && jQueryMode) { <del> forEach(value, function(v, k) { <del> var keySuffix = jQueryMode ? '[' + (!isArray(value) ? k : '') + ']' : ''; <del> parts.push(encodeUriQuery(key + keySuffix) + '=' + encodeUriQuery(serializeValue(v))); <del> }); <del> } else { <del> parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); <del> } <del> }); <del> <del> return parts.length > 0 ? parts.join('&') : ''; <del> }; <add> return v; <ide> } <ide> <add> <ide> function $HttpParamSerializerProvider() { <ide> /** <ide> * @ngdoc service <ide> function $HttpParamSerializerProvider() { <ide> * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object) <ide> * */ <ide> this.$get = function() { <del> return paramSerializerFactory(false); <add> return function ngParamSerializer(params) { <add> if (!params) return ''; <add> var parts = []; <add> forEachSorted(params, function(value, key) { <add> if (value === null || isUndefined(value)) return; <add> if (isArray(value)) { <add> forEach(value, function(v, k) { <add> parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v))); <add> }); <add> } else { <add> parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value))); <add> } <add> }); <add> <add> return parts.join('&'); <add> }; <ide> }; <ide> } <ide> <ide> function $HttpParamSerializerJQLikeProvider() { <ide> * Alternative $http params serializer that follows jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic. <ide> * */ <ide> this.$get = function() { <del> return paramSerializerFactory(true); <add> return function jQueryLikeParamSerializer(params) { <add> if (!params) return ''; <add> var parts = []; <add> serialize(params, '', true); <add> return parts.join('&'); <add> <add> function serialize(toSerialize, prefix, topLevel) { <add> if (toSerialize === null || isUndefined(toSerialize)) return; <add> if (isArray(toSerialize)) { <add> forEach(toSerialize, function(value) { <add> serialize(value, prefix + '[]'); <add> }); <add> } else if (isObject(toSerialize) && !isDate(toSerialize)) { <add> forEachSorted(toSerialize, function(value, key) { <add> serialize(value, prefix + <add> (topLevel ? '' : '[') + <add> key + <add> (topLevel ? '' : ']')); <add> }); <add> } else { <add> parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize))); <add> } <add> } <add> } <ide> }; <ide> } <ide> <ide><path>test/ng/httpSpec.js <ide> describe('$http param serializers', function() { <ide> it('should serialize objects', function() { <ide> expect(defSer({foo: 'foov', bar: 'barv'})).toEqual('bar=barv&foo=foov'); <ide> expect(jqrSer({foo: 'foov', bar: 'barv'})).toEqual('bar=barv&foo=foov'); <add> expect(defSer({someDate: new Date('2014-07-15T17:30:00.000Z')})).toEqual('someDate=2014-07-15T17:30:00.000Z'); <add> expect(jqrSer({someDate: new Date('2014-07-15T17:30:00.000Z')})).toEqual('someDate=2014-07-15T17:30:00.000Z'); <ide> }); <ide> <ide> }); <ide> describe('$http param serializers', function() { <ide> expect(decodeURIComponent(jqrSer({a: 'b', foo: ['bar', 'baz']}))).toEqual('a=b&foo[]=bar&foo[]=baz'); <ide> }); <ide> <del> it('should serialize objects by repeating param name with [kay] suffix', function() { <add> it('should serialize objects by repeating param name with [key] suffix', function() { <ide> expect(jqrSer({a: 'b', foo: {'bar': 'barv', 'baz': 'bazv'}})).toEqual('a=b&foo%5Bbar%5D=barv&foo%5Bbaz%5D=bazv'); <ide> //a=b&foo[bar]=barv&foo[baz]=bazv <ide> }); <add> <add> it('should serialize nested objects by repeating param name with [key] suffix', function() { <add> expect(jqrSer({a: ['b', {c: 'd'}], e: {f: 'g', 'h': ['i', 'j']}})).toEqual( <add> 'a%5B%5D=b&a%5B%5D%5Bc%5D=d&e%5Bf%5D=g&e%5Bh%5D%5B%5D=i&e%5Bh%5D%5B%5D=j'); <add> //a[]=b&a[][c]=d&e[f]=g&e[h][]=i&e[h][]=j <add> }); <ide> }); <ide> <ide> });
2
Python
Python
add levenshtein distance metric
ae7660161c38a0630fcff124a8efc0a2102a14b0
<ide><path>strings/levenshtein-distance.py <add>""" <add>This is a Python implementation of the levenshtein distance. <add>Levenshtein distance is a string metric for measuring the <add>difference between two sequences. <add> <add>For doctests run following command: <add>python -m doctest -v levenshtein-distance.py <add>or <add>python3 -m doctest -v levenshtein-distance.py <add> <add>For manual testing run: <add>python levenshtein-distance.py <add>""" <add> <add> <add>def levenshtein_distance(first_word, second_word): <add> """Implementation of the levenshtein distance in Python. <add> :param first_word: the first word to measure the difference. <add> :param second_word: the second word to measure the difference. <add> :return: the levenshtein distance between the two words. <add> Examples: <add> >>> levenshtein_distance("planet", "planetary") <add> 3 <add> >>> levenshtein_distance("", "test") <add> 4 <add> >>> levenshtein_distance("book", "back") <add> 2 <add> >>> levenshtein_distance("book", "book") <add> 0 <add> >>> levenshtein_distance("test", "") <add> 4 <add> >>> levenshtein_distance("", "") <add> 0 <add> >>> levenshtein_distance("orchestration", "container") <add> 10 <add> """ <add> # The longer word should come first <add> if len(first_word) < len(second_word): <add> return levenshtein_distance(second_word, first_word) <add> <add> if len(second_word) == 0: <add> return len(first_word) <add> <add> previous_row = range(len(second_word) + 1) <add> <add> for i, c1 in enumerate(first_word): <add> <add> current_row = [i + 1] <add> <add> for j, c2 in enumerate(second_word): <add> <add> # Calculate insertions, deletions and substitutions <add> insertions = previous_row[j + 1] + 1 <add> deletions = current_row[j] + 1 <add> substitutions = previous_row[j] + (c1 != c2) <add> <add> # Get the minimum to append to the current row <add> current_row.append(min(insertions, deletions, substitutions)) <add> <add> # Store the previous row <add> previous_row = current_row <add> <add> # Returns the last element (distance) <add> return previous_row[-1] <add> <add> <add>if __name__ == '__main__': <add> try: <add> raw_input # Python 2 <add> except NameError: <add> raw_input = input # Python 3 <add> <add> first_word = raw_input('Enter the first word:\n').strip() <add> second_word = raw_input('Enter the second word:\n').strip() <add> <add> result = levenshtein_distance(first_word, second_word) <add> print('Levenshtein distance between {} and {} is {}'.format( <add> first_word, second_word, result))
1
Mixed
Javascript
invoke callback before emitting error always"
95792a79892471e2c691c071e85d7fea29aa40cd
<ide><path>doc/api/stream.md <ide> The `writable.write()` method writes some data to the stream, and calls the <ide> supplied `callback` once the data has been fully handled. If an error <ide> occurs, the `callback` *may or may not* be called with the error as its <ide> first argument. To reliably detect write errors, add a listener for the <del>`'error'` event. If `callback` is called with an error, it will be called <del>before the `'error'` event is emitted. <add>`'error'` event. <ide> <ide> The return value is `true` if the internal buffer is less than the <ide> `highWaterMark` configured when the stream was created after admitting `chunk`. <ide><path>lib/_stream_writable.js <ide> function WritableState(options, stream, isDuplex) { <ide> // Should .destroy() be called after 'finish' (and potentially 'end') <ide> this.autoDestroy = !!(options && options.autoDestroy); <ide> <del> // Indicates whether the stream has errored. When true all write() calls <del> // should return false. This is needed since when autoDestroy <del> // is disabled we need a way to tell whether the stream has failed. <del> this.errored = false; <del> <ide> // Count buffered requests <ide> this.bufferedRequestCount = 0; <ide> <ide> function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { <ide> if (!ret) <ide> state.needDrain = true; <ide> <del> if (state.writing || state.corked || state.errored) { <add> if (state.writing || state.corked) { <ide> var last = state.lastBufferedRequest; <ide> state.lastBufferedRequest = { <ide> chunk, <ide> function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { <ide> doWrite(stream, state, false, len, chunk, encoding, cb); <ide> } <ide> <del> // Return false if errored or destroyed in order to break <del> // any synchronous while(stream.write(data)) loops. <del> return ret && !state.errored && !state.destroyed; <add> return ret; <ide> } <ide> <ide> function doWrite(stream, state, writev, len, chunk, encoding, cb) { <ide> function doWrite(stream, state, writev, len, chunk, encoding, cb) { <ide> state.sync = false; <ide> } <ide> <del>function onwriteError(stream, state, er, cb) { <add>function onwriteError(stream, state, sync, er, cb) { <ide> --state.pendingcb; <ide> <del> cb(er); <del> // This can emit error, but error must always follow cb. <add> if (sync) { <add> // Defer the callback if we are being called synchronously <add> // to avoid piling up things on the stack <add> process.nextTick(cb, er); <add> } else { <add> // The caller expect this to happen before if <add> // it is async <add> cb(er); <add> } <ide> errorOrDestroy(stream, er); <ide> } <ide> <ide> function onwrite(stream, er) { <ide> state.length -= state.writelen; <ide> state.writelen = 0; <ide> <del> if (er) { <del> state.errored = true; <del> if (sync) { <del> process.nextTick(onwriteError, stream, state, er, cb); <del> } else { <del> onwriteError(stream, state, er, cb); <del> } <del> } else { <add> if (er) <add> onwriteError(stream, state, sync, er, cb); <add> else { <ide> // Check if we're actually ready to finish, but don't emit yet <ide> var finished = needFinish(state) || stream.destroyed; <ide> <ide> Object.defineProperty(Writable.prototype, 'writableLength', { <ide> function needFinish(state) { <ide> return (state.ending && <ide> state.length === 0 && <del> !state.errored && <add> !state.errorEmitted && <ide> state.bufferedRequest === null && <ide> !state.finished && <ide> !state.writing); <ide><path>lib/internal/streams/destroy.js <ide> function destroy(err, cb) { <ide> const r = this._readableState; <ide> const w = this._writableState; <ide> <del> if (w && err) { <del> w.errored = true; <del> } <del> <ide> if ((w && w.destroyed) || (r && r.destroyed)) { <ide> if (cb) { <ide> cb(err); <ide> function destroy(err, cb) { <ide> this._destroy(err || null, (err) => { <ide> const emitClose = (w && w.emitClose) || (r && r.emitClose); <ide> if (cb) { <del> // Invoke callback before scheduling emitClose so that callback <del> // can schedule before. <del> cb(err); <ide> if (emitClose) { <ide> process.nextTick(emitCloseNT, this); <ide> } <add> cb(err); <ide> } else if (needError(this, err)) { <ide> process.nextTick(emitClose ? emitErrorCloseNT : emitErrorNT, this, err); <ide> } else if (emitClose) { <ide> function undestroy() { <ide> <ide> if (w) { <ide> w.destroyed = false; <del> w.errored = false; <ide> w.ended = false; <ide> w.ending = false; <ide> w.finalCalled = false; <ide> function errorOrDestroy(stream, err) { <ide> const r = stream._readableState; <ide> const w = stream._writableState; <ide> <del> if (w & err) { <del> w.errored = true; <del> } <del> <ide> if ((r && r.autoDestroy) || (w && w.autoDestroy)) <ide> stream.destroy(err); <ide> else if (needError(stream, err)) <ide><path>test/parallel/test-http2-reset-flood.js <ide> const worker = new Worker(__filename).on('message', common.mustCall((port) => { <ide> h2header.writeIntBE(1, 0, 3); // Length: 1 <ide> h2header.writeIntBE(i, 5, 4); // Stream ID <ide> // 0x88 = :status: 200 <del> if (!conn.write(Buffer.concat([h2header, Buffer.from([0x88])]))) { <del> process.nextTick(writeRequests); <del> break; <del> } <add> conn.write(Buffer.concat([h2header, Buffer.from([0x88])])); <ide> } <ide> } <ide> <ide><path>test/parallel/test-stream-writable-destroy.js <ide> const assert = require('assert'); <ide> assert.strictEqual(write.destroyed, true); <ide> } <ide> <del>{ <del> const write = new Writable({ <del> write(chunk, enc, cb) { <del> this.destroy(new Error('asd')); <del> cb(); <del> } <del> }); <del> <del> write.on('error', common.mustCall()); <del> write.on('finish', common.mustNotCall()); <del> write.end('asd'); <del> assert.strictEqual(write.destroyed, true); <del>} <del> <ide> { <ide> const write = new Writable({ <ide> write(chunk, enc, cb) { cb(); } <ide><path>test/parallel/test-stream-writable-write-cb-error.js <del>'use strict'; <del>const common = require('../common'); <del>const { Writable } = require('stream'); <del>const assert = require('assert'); <del> <del>// Ensure callback is always invoked before <del>// error is emitted. Regardless if error was <del>// sync or async. <del> <del>{ <del> let callbackCalled = false; <del> // Sync Error <del> const writable = new Writable({ <del> write: common.mustCall((buf, enc, cb) => { <del> cb(new Error()); <del> }) <del> }); <del> writable.on('error', common.mustCall(() => { <del> assert.strictEqual(callbackCalled, true); <del> })); <del> writable.write('hi', common.mustCall(() => { <del> callbackCalled = true; <del> })); <del>} <del> <del>{ <del> let callbackCalled = false; <del> // Async Error <del> const writable = new Writable({ <del> write: common.mustCall((buf, enc, cb) => { <del> process.nextTick(cb, new Error()); <del> }) <del> }); <del> writable.on('error', common.mustCall(() => { <del> assert.strictEqual(callbackCalled, true); <del> })); <del> writable.write('hi', common.mustCall(() => { <del> callbackCalled = true; <del> })); <del>} <del> <del>{ <del> // Sync Error <del> const writable = new Writable({ <del> write: common.mustCall((buf, enc, cb) => { <del> cb(new Error()); <del> }) <del> }); <del> <del> writable.on('error', common.mustCall()); <del> <del> let cnt = 0; <del> // Ensure we don't live lock on sync error <del> while (writable.write('a')) <del> cnt++; <del> <del> assert.strictEqual(cnt, 0); <del>} <ide><path>test/parallel/test-wrap-js-stream-exceptions.js <ide> const socket = new JSStreamWrap(new Duplex({ <ide> }) <ide> })); <ide> <del>socket.end('foo'); <del>socket.on('error', common.expectsError({ <del> type: Error, <del> message: 'write EPROTO' <del>})); <add>assert.throws(() => socket.end('foo'), /Error: write EPROTO/); <ide><path>test/parallel/test-zlib-write-after-close.js <ide> const zlib = require('zlib'); <ide> zlib.gzip('hello', common.mustCall(function(err, out) { <ide> const unzip = zlib.createGunzip(); <ide> unzip.close(common.mustCall()); <del> <del> unzip.write(out); <del> unzip.on('error', common.expectsError({ <del> code: 'ERR_STREAM_DESTROYED', <del> type: Error <del> })); <add> common.expectsError( <add> () => unzip.write(out), <add> { <add> code: 'ERR_STREAM_DESTROYED', <add> type: Error, <add> message: 'Cannot call write after a stream was destroyed' <add> } <add> ); <ide> }));
8
Text
Text
add moduledirectories for ts jest config
2be207a288e3ddda882901c218c2e3e6f78fa131
<ide><path>docs/testing.md <ide> const createJestConfig = nextJest({ <ide> // Add any custom config to be passed to Jest <ide> const customJestConfig = { <ide> setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], <add> // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work <add> moduleDirectories: ['node_modules', '<rootDir>/'], <ide> } <ide> <ide> // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
1
Ruby
Ruby
handle nil manifests_annotations
195e4d0f89ad53d72ac0ebd4823a41fdfb8d9e2a
<ide><path>Library/Homebrew/software_spec.rb <ide> def github_packages_manifest_resource_tab(github_packages_manifest_resource) <ide> manifests = json["manifests"] <ide> raise ArgumentError, "Missing 'manifests' section." if manifests.blank? <ide> <del> manifests_annotations = manifests.map { |m| m["annotations"] } <add> manifests_annotations = manifests.map { |m| m["annotations"] }.compact <ide> raise ArgumentError, "Missing 'annotations' section." if manifests_annotations.blank? <ide> <ide> bottle_digest = @resource.checksum.hexdigest
1
PHP
PHP
fix typo in comments
c659a926034da8e724e2766b90aef48c8fbb3018
<ide><path>laravel/auth/drivers/eloquent.php <ide> public function retrieve($id) <ide> /** <ide> * Attempt to log a user into the application. <ide> * <del> * @param array $arguments <add> * @param array $arguments <ide> * @return void <ide> */ <ide> public function attempt($arguments = array()) <ide><path>laravel/auth/drivers/fluent.php <ide> public function retrieve($id) <ide> /** <ide> * Attempt to log a user into the application. <ide> * <del> * @param array $arguments <add> * @param array $arguments <ide> * @return void <ide> */ <ide> public function attempt($arguments = array()) <ide> public function attempt($arguments = array()) <ide> /** <ide> * Get the user from the database table. <ide> * <del> * @param mixed $array <add> * @param array $arguments <ide> * @return mixed <ide> */ <ide> protected function get_user($arguments)
2
Javascript
Javascript
add failing test for stdout flush on exit
a695065305b710044569e0ee24b15b932fd2bd67
<ide><path>test/mjsunit/fixtures/print-chars.js <add>process.mixin(require("../common")); <add> <add>var n = parseInt(process.argv[2]); <add> <add>var s = ""; <add>for (var i = 0; i < n-1; i++) { <add> s += 'c'; <add>} <add> <add>puts(s); // \n is the nth char. <add> <add>process.exit(0); <ide><path>test/mjsunit/test-readdir.js <ide> promise.addCallback(function (files) { <ide> , 'echo.js' <ide> , 'multipart.js' <ide> , 'nested-index' <add> , 'print-chars.js' <ide> , 'test_ca.pem' <ide> , 'test_cert.pem' <ide> , 'test_key.pem' <ide><path>test/mjsunit/test-stdout-flush.js <add>process.mixin(require("./common")); <add> <add>var sub = path.join(fixturesDir, 'print-chars.js'); <add> <add>completedTests = 0; <add> <add>function test (n, cb) { <add> var child = process.createChildProcess(process.argv[0], [sub, n]); <add> <add> var count = 0; <add> <add> child.addListener("error", function (data){ <add> if (data) { <add> puts("parent stderr: " + data); <add> assert.ok(false); <add> } <add> }); <add> <add> child.addListener("output", function (data){ <add> if (data) { <add> count += data.length; <add> } <add> }); <add> <add> child.addListener("exit", function (data) { <add> assert.equal(n, count); <add> puts(n + " okay"); <add> completedTests++; <add> if (cb) cb(); <add> }); <add>} <add> <add> <add> <add>test(5000, function () { <add> test(50000, function () { <add> test(500000); <add> }); <add>}); <add> <add> <add>process.addListener('exit', function () { <add> assert.equal(3, completedTests); <add>});
3
PHP
PHP
register core class aliases
7e3a99ebbab959324eebd88bdc38667f3fd35461
<ide><path>src/Illuminate/Foundation/Application.php <ide> public static function onRequest($method, $parameters = array()) <ide> return forward_static_call_array(array(static::requestClass(), $method), $parameters); <ide> } <ide> <add> /** <add> * Register the core class aliases in the container. <add> * <add> * @return void <add> */ <add> public function registerCoreContainerAliases() <add> { <add> $aliases = array( <add> 'app' => 'Illuminate\Foundation\Application', <add> 'artisan' => 'Illuminate\Console\Application', <add> 'auth' => 'Illuminate\Auth\AuthManager', <add> 'blade.compiler' => 'Illuminate\View\Compilers\BladeCompiler', <add> 'cache' => 'Illuminate\Cache\Repository', <add> 'config' => 'Illuminate\Config\Repository', <add> 'cookie' => 'Illuminate\Cookie\CookieJar', <add> 'encrypter' => 'Illuminate\Encryption\Encrypter', <add> 'db' => 'Illuminate\Database\DatabaseManager', <add> 'events' => 'Illuminate\Events\Dispatacher', <add> 'files' => 'Illuminate\Filesystem\Filesystem', <add> 'form' => 'Illuminate\Html\FormBuilder', <add> 'hash' => 'Illuminate\Hashing\HasherInterface', <add> 'html' => 'Illuminate\Html\HtmlBuilder', <add> 'translator' => 'Illuminate\Translation\Translator', <add> 'log' => 'Illuminate\Log\Writer', <add> 'mailer' => 'Illuminate\Mail\Mailer', <add> 'paginator' => 'Illuminate\Pagination\Environment', <add> 'auth.reminder' => 'Illuminate\Auth\Reminders\PasswordBroker', <add> 'queue' => 'Illuminate\Queue\QueueManager', <add> 'redirect' => 'Illuminate\Routing\Redirector', <add> 'redis' => 'Illuminate\Redis\Database', <add> 'request' => 'Illuminate\Http\Requset', <add> 'router' => 'Illuminate\Routing\Router', <add> 'session' => 'Illuminate\Session\SessionManager', <add> 'remote' => 'Illuminate\Remote\RemoteManager', <add> 'url' => 'Illuminate\Routing\UrlGenerator', <add> 'validator' => 'Illuminate\Validation\Factory', <add> 'view' => 'Illuminate\View\Environment', <add> ); <add> <add> foreach ($aliases as $key => $alias) <add> { <add> $this->alias($key, $alias); <add> } <add> } <add> <ide> /** <ide> * Dynamically access application services. <ide> * <ide><path>src/Illuminate/Foundation/start.php <ide> <ide> Facade::setFacadeApplication($app); <ide> <add>/* <add>|-------------------------------------------------------------------------- <add>| Register Facade Aliases To Full Classes <add>|-------------------------------------------------------------------------- <add>| <add>| By default, we use short keys in the container for each of the core <add>| pieces of the framework. Here we will register the aliases for a <add>| list of all of the fully qualified class names making DI easy. <add>| <add>*/ <add> <add>$app->registerCoreContainerAliases(); <add> <ide> /* <ide> |-------------------------------------------------------------------------- <ide> | Register The Configuration Repository
2
Javascript
Javascript
improve ie support
986647be59259125750fd44dbb429658d67dc156
<ide><path>lib/adapters/xhr.js <ide> 'use strict'; <ide> <del>/*global ActiveXObject:true*/ <del> <ide> var utils = require('./../utils'); <ide> var buildURL = require('./../helpers/buildURL'); <ide> var parseHeaders = require('./../helpers/parseHeaders'); <ide> var transformData = require('./../helpers/transformData'); <ide> var isURLSameOrigin = require('./../helpers/isURLSameOrigin'); <del>var ieVersion = require('./../helpers/ieVersion'); <ide> var btoa = window.btoa || require('./../helpers/btoa'); <ide> <ide> module.exports = function xhrAdapter(resolve, reject, config) { <ide> module.exports = function xhrAdapter(resolve, reject, config) { <ide> delete requestHeaders['Content-Type']; // Let the browser set it <ide> } <ide> <del> var Adapter = (XMLHttpRequest || ActiveXObject); <del> var loadEvent = 'onreadystatechange'; <del> var xDomain = false; <add> var request = new XMLHttpRequest(); <ide> <ide> // For IE 8/9 CORS support <del> if (ieVersion() <= 9 && !isURLSameOrigin(config.url) && window.XDomainRequest) { <del> Adapter = window.XDomainRequest; <del> loadEvent = 'onload'; <del> xDomain = true; <add> // Only supports POST and GET calls and doesn't returns the response headers. <add> if (window.XDomainRequest && !("withCredentials" in request) && !isURLSameOrigin(config.url)) { <add> request = new window.XDomainRequest(); <ide> } <ide> <ide> // HTTP basic authentication <ide> module.exports = function xhrAdapter(resolve, reject, config) { <ide> requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); <ide> } <ide> <del> // Create the request <del> var request = new Adapter('Microsoft.XMLHTTP'); <ide> request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); <ide> <ide> // Set the request timeout in MS <ide> request.timeout = config.timeout; <ide> <ide> // Listen for ready state <del> request[loadEvent] = function handleReadyState() { <del> if (request && (request.readyState === 4 || xDomain)) { <del> // Prepare the response <del> var responseHeaders = xDomain ? null : parseHeaders(request.getAllResponseHeaders()); <del> var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; <del> var response = { <del> data: transformData( <del> responseData, <del> responseHeaders, <del> config.transformResponse <del> ), <del> status: request.status, <del> statusText: request.statusText, <del> headers: responseHeaders, <del> config: config <del> }; <del> // Resolve or reject the Promise based on the status <del> ((request.status >= 200 && request.status < 300) || (xDomain && request.responseText) ? <del> resolve : <del> reject)(response); <del> <del> // Clean up request <del> request = null; <add> request.onload = function handleLoad() { <add> if (!request) { <add> return; <ide> } <add> // Prepare the response <add> var responseHeaders = "getAllResponseHeaders" in request ? parseHeaders(request.getAllResponseHeaders()) : null; <add> var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; <add> var response = { <add> data: transformData( <add> responseData, <add> responseHeaders, <add> config.transformResponse <add> ), <add> status: request.status, <add> statusText: request.statusText, <add> headers: responseHeaders, <add> config: config <add> }; <add> // Resolve or reject the Promise based on the status <add> ((request.status >= 200 && request.status < 300) || (!("status" in request) && request.responseText) ? <add> resolve : <add> reject)(response); <add> <add> // Clean up request <add> request = null; <ide> }; <ide> <ide> // Add xsrf header <ide> module.exports = function xhrAdapter(resolve, reject, config) { <ide> } <ide> <ide> // Add headers to the request <del> if (!xDomain) { <add> if ("setRequestHeader" in request) { <ide> utils.forEach(requestHeaders, function setRequestHeader(val, key) { <ide> if (!requestData && key.toLowerCase() === 'content-type') { <ide> // Remove Content-Type if data is undefined <ide><path>lib/helpers/ieVersion.js <del>'use strict'; <del> <del>/** <del> * https://gist.github.com/padolsey/527683 <del> * <del> * A short snippet for detecting versions of IE in JavaScript <del> * without resorting to user-agent sniffing <del> * <del> * @returns {Number|undefined} Number of IE version (5-9), otherwise undefined <del> */ <del>module.exports = function ieVersion() { <del> var undef; <del> var v = 3; <del> var div = document.createElement('div'); <del> var all = div.getElementsByTagName('i'); <del> <del> while (( <del> div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', <del> all[0] <del> )); <del> <del> return v > 4 ? v : undef; <del>};
2
Javascript
Javascript
add some todo code
1cd530cdf06e4865a91f159fffc0e687ff78610c
<ide><path>src/auto-update-manager.js <ide> export default class AutoUpdateManager { <ide> return this.emitter.on('did-complete-downloading-update', callback) <ide> } <ide> <add> // TODO: When https://github.com/atom/electron/issues/4587 is closed, we can <add> // add an update-available event. <add> // onUpdateAvailable (callback) { <add> // return this.emitter.on('update-available', callback) <add> // } <add> <ide> onUpdateNotAvailable (callback) { <ide> return this.emitter.on('update-not-available', callback) <ide> }
1
Ruby
Ruby
install plist before linking
5437a480ebd34246db43a875c799f591d3cbf40d
<ide><path>Library/Homebrew/formula_installer.rb <ide> def caveats <ide> def finish <ide> ohai 'Finishing up' if ARGV.verbose? <ide> <add> install_plist <add> <ide> if f.keg_only? <ide> begin <ide> Keg.new(f.prefix).optlink <ide> def finish <ide> check_PATH unless f.keg_only? <ide> end <ide> <del> install_plist <ide> fix_install_names <ide> <ide> ohai "Summary" if ARGV.verbose? or show_summary_heading
1
Go
Go
implement regression test for stdin attach
5190f7f33a9e36f1f5991a385f4db198e9f1b3a6
<ide><path>api.go <ide> func postContainersAttach(srv *Server, version float64, w http.ResponseWriter, r <ide> if err != nil { <ide> return err <ide> } <del> defer in.Close() <add> defer func() { <add> if tcpc, ok := in.(*net.TCPConn); ok { <add> tcpc.CloseWrite() <add> } else { <add> in.Close() <add> } <add> }() <add> defer func() { <add> if tcpc, ok := out.(*net.TCPConn); ok { <add> tcpc.CloseWrite() <add> } else if closer, ok := out.(io.Closer); ok { <add> closer.Close() <add> } <add> }() <ide> <ide> fmt.Fprintf(out, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n") <ide> if err := srv.ContainerAttach(name, logs, stream, stdin, stdout, stderr, in, out); err != nil { <ide><path>commands.go <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> } <ide> <ide> if !config.AttachStdout && !config.AttachStderr { <del> fmt.Fprintf(cli.out, "%s\n", runResult.ID) <add> // Make this asynchrone in order to let the client write to stdin before having to read the ID <add> go fmt.Fprintf(cli.out, "%s\n", runResult.ID) <ide> } <add> <ide> if config.AttachStdin || config.AttachStdout || config.AttachStderr { <ide> if config.Tty { <ide> if err := cli.monitorTtySize(runResult.ID); err != nil { <ide> func (cli *DockerCli) CmdRun(args ...string) error { <ide> if config.AttachStderr { <ide> v.Set("stderr", "1") <ide> } <add> <ide> if err := cli.hijack("POST", "/containers/"+runResult.ID+"/attach?"+v.Encode(), config.Tty, cli.in, cli.out); err != nil { <ide> utils.Debugf("Error hijack: %s", err) <ide> return err <ide> func (cli *DockerCli) hijack(method, path string, setRawTerminal bool, in io.Rea <ide> } <ide> defer term.RestoreTerminal(cli.terminalFd, oldState) <ide> } <add> <ide> sendStdin := utils.Go(func() error { <ide> if in != nil { <ide> io.Copy(rwc, in) <ide><path>commands_test.go <ide> package docker <ide> import ( <ide> "bufio" <ide> "fmt" <add> "github.com/dotcloud/docker/utils" <ide> "io" <del> _ "io/ioutil" <add> "io/ioutil" <ide> "strings" <ide> "testing" <ide> "time" <ide> func assertPipe(input, output string, r io.Reader, w io.Writer, count int) error <ide> } <ide> <ide> /*TODO <del>func cmdWait(srv *Server, container *Container) error { <del> stdout, stdoutPipe := io.Pipe() <del> <del> go func() { <del> srv.CmdWait(nil, stdoutPipe, container.Id) <del> }() <del> <del> if _, err := bufio.NewReader(stdout).ReadString('\n'); err != nil { <del> return err <del> } <del> // Cleanup pipes <del> return closeWrap(stdout, stdoutPipe) <del>} <del> <ide> func cmdImages(srv *Server, args ...string) (string, error) { <ide> stdout, stdoutPipe := io.Pipe() <ide> <ide> func TestImages(t *testing.T) { <ide> // todo: add checks for -a <ide> } <ide> <add>*/ <ide> // TestRunHostname checks that 'docker run -h' correctly sets a custom hostname <ide> func TestRunHostname(t *testing.T) { <del> runtime, err := newTestRuntime() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer nuke(runtime) <del> <del> srv := &Server{runtime: runtime} <del> <del> stdin, _ := io.Pipe() <ide> stdout, stdoutPipe := io.Pipe() <ide> <add> cli := NewDockerCli(nil, stdoutPipe, nil, testDaemonProto, testDaemonAddr) <add> defer cleanup(globalRuntime) <add> <ide> c := make(chan struct{}) <ide> go func() { <del> if err := srv.CmdRun(stdin, rcli.NewDockerLocalConn(stdoutPipe), "-h", "foobar", GetTestImage(runtime).Id, "hostname"); err != nil { <add> defer close(c) <add> if err := cli.CmdRun("-h", "foobar", unitTestImageId, "hostname"); err != nil { <ide> t.Fatal(err) <ide> } <del> close(c) <ide> }() <del> cmdOutput, err := bufio.NewReader(stdout).ReadString('\n') <del> if err != nil { <del> t.Fatal(err) <del> } <del> if cmdOutput != "foobar\n" { <del> t.Fatalf("'hostname' should display '%s', not '%s'", "foobar\n", cmdOutput) <del> } <add> utils.Debugf("--") <add> setTimeout(t, "Reading command output time out", 2*time.Second, func() { <add> cmdOutput, err := bufio.NewReader(stdout).ReadString('\n') <add> if err != nil { <add> t.Fatal(err) <add> } <add> if cmdOutput != "foobar\n" { <add> t.Fatalf("'hostname' should display '%s', not '%s'", "foobar\n", cmdOutput) <add> } <add> }) <ide> <del> setTimeout(t, "CmdRun timed out", 2*time.Second, func() { <add> setTimeout(t, "CmdRun timed out", 5*time.Second, func() { <ide> <-c <del> cmdWait(srv, srv.runtime.List()[0]) <ide> }) <ide> <ide> } <ide> <add>/* <ide> func TestRunExit(t *testing.T) { <ide> runtime, err := newTestRuntime() <ide> if err != nil { <ide> func TestRunDisconnectTty(t *testing.T) { <ide> } <ide> } <ide> */ <del>/* <add> <ide> // TestAttachStdin checks attaching to stdin without stdout and stderr. <ide> // 'docker run -i -a stdin' should sends the client's stdin to the command, <ide> // then detach from it and print the container id. <ide> func TestRunAttachStdin(t *testing.T) { <del> runtime, err := newTestRuntime() <del> if err != nil { <del> t.Fatal(err) <del> } <del> defer nuke(runtime) <del> srv := &Server{runtime: runtime} <del> // enableCors: false, <del> // lock: &sync.Mutex{}, <del> // pullingPool: make(map[string]struct{}), <del> // pushingPool: make(map[string]struct{}), <ide> <ide> stdin, stdinPipe := io.Pipe() <ide> stdout, stdoutPipe := io.Pipe() <ide> <add> cli := NewDockerCli(stdin, stdoutPipe, nil, testDaemonProto, testDaemonAddr) <add> defer cleanup(globalRuntime) <add> <ide> ch := make(chan struct{}) <ide> go func() { <del> srv.CmdRun(stdin, rcli.NewDockerLocalConn(stdoutPipe), "-i", "-a", "stdin", GetTestImage(runtime).Id, "sh", "-c", "echo hello; cat") <del> close(ch) <add> defer close(ch) <add> cli.CmdRun("-i", "-a", "stdin", unitTestImageId, "sh", "-c", "echo hello && cat") <ide> }() <ide> <ide> // Send input to the command, close stdin <del> setTimeout(t, "Write timed out", 2*time.Second, func() { <add> setTimeout(t, "Write timed out", 10*time.Second, func() { <ide> if _, err := stdinPipe.Write([]byte("hi there\n")); err != nil { <ide> t.Fatal(err) <ide> } <ide> func TestRunAttachStdin(t *testing.T) { <ide> } <ide> }) <ide> <del> container := runtime.List()[0] <add> container := globalRuntime.List()[0] <ide> <ide> // Check output <del> cmdOutput, err := bufio.NewReader(stdout).ReadString('\n') <del> if err != nil { <del> t.Fatal(err) <del> } <del> if cmdOutput != container.ShortId()+"\n" { <del> t.Fatalf("Wrong output: should be '%s', not '%s'\n", container.ShortId()+"\n", cmdOutput) <del> } <add> setTimeout(t, "Reading command output time out", 10*time.Second, func() { <add> cmdOutput, err := bufio.NewReader(stdout).ReadString('\n') <add> if err != nil { <add> t.Fatal(err) <add> } <add> if cmdOutput != container.ShortID()+"\n" { <add> t.Fatalf("Wrong output: should be '%s', not '%s'\n", container.ShortID()+"\n", cmdOutput) <add> } <add> }) <ide> <ide> // wait for CmdRun to return <del> setTimeout(t, "Waiting for CmdRun timed out", 2*time.Second, func() { <add> setTimeout(t, "Waiting for CmdRun timed out", 5*time.Second, func() { <add> // Unblock hijack end <add> stdout.Read([]byte{}) <ide> <-ch <ide> }) <ide> <del> setTimeout(t, "Waiting for command to exit timed out", 2*time.Second, func() { <add> setTimeout(t, "Waiting for command to exit timed out", 5*time.Second, func() { <ide> container.Wait() <ide> }) <ide> <ide> func TestRunAttachStdin(t *testing.T) { <ide> } <ide> } <ide> } <del>*/ <add> <ide> /* <ide> // Expected behaviour, the process stays alive when the client disconnects <ide> func TestAttachDisconnect(t *testing.T) { <ide><path>runtime_test.go <ide> const ( <ide> testDaemonProto = "tcp" <ide> ) <ide> <add>var globalRuntime *Runtime <add> <ide> func nuke(runtime *Runtime) error { <ide> var wg sync.WaitGroup <ide> for _, container := range runtime.List() { <ide> func nuke(runtime *Runtime) error { <ide> return os.RemoveAll(runtime.root) <ide> } <ide> <add>func cleanup(runtime *Runtime) error { <add> for _, container := range runtime.List() { <add> container.Kill() <add> runtime.Destroy(container) <add> } <add> images, err := runtime.graph.All() <add> if err != nil { <add> return err <add> } <add> for _, image := range images { <add> if image.ID != unitTestImageId { <add> runtime.graph.Delete(image.ID) <add> } <add> } <add> return nil <add>} <add> <ide> func layerArchive(tarfile string) (io.Reader, error) { <ide> // FIXME: need to close f somewhere <ide> f, err := os.Open(tarfile) <ide> func init() { <ide> if err != nil { <ide> panic(err) <ide> } <add> globalRuntime = runtime <ide> <ide> // Create the "Server" <ide> srv := &Server{ <ide> func init() { <ide> panic(err) <ide> } <ide> }() <add> <add> // Give some time to ListenAndServer to actually start <add> time.Sleep(time.Second) <ide> } <ide> <ide> // FIXME: test that ImagePull(json=true) send correct json output <ide><path>z_final_test.go <add>package docker <add> <add>import ( <add> "github.com/dotcloud/docker/utils" <add> "runtime" <add> "testing" <add>) <add> <add>func TestFinal(t *testing.T) { <add> cleanup(globalRuntime) <add> t.Logf("Fds: %d, Goroutines: %d", utils.GetTotalUsedFds(), runtime.NumGoroutine()) <add>}
5
Java
Java
avoid potential npe (spr-5930)
68363f17a796e174012d2de99070e39a205b3ca7
<ide><path>org.springframework.beans/src/main/java/org/springframework/beans/propertyeditors/FileEditor.java <ide> /* <del> * Copyright 2002-2006 the original author or authors. <add> * Copyright 2002-2009 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> public FileEditor(ResourceEditor resourceEditor) { <ide> <ide> @Override <ide> public void setAsText(String text) throws IllegalArgumentException { <add> if (!StringUtils.hasText(text)) { <add> setValue(null); <add> return; <add> } <add> <ide> // Check whether we got an absolute file path without "file:" prefix. <ide> // For backwards compatibility, we'll consider those as straight file path. <del> if (StringUtils.hasText(text) && !ResourceUtils.isUrl(text)) { <add> if (!ResourceUtils.isUrl(text)) { <ide> File file = new File(text); <ide> if (file.isAbsolute()) { <ide> setValue(file); <ide> public void setAsText(String text) throws IllegalArgumentException { <ide> // Proceed with standard resource location parsing. <ide> this.resourceEditor.setAsText(text); <ide> Resource resource = (Resource) this.resourceEditor.getValue(); <del> // Non URLs will be treated as relative paths if the resource was not found <del> if(ResourceUtils.isUrl(text) || resource.exists()) { <add> <add> // If it's a URL or a path pointing to an existing resource, use it as-is. <add> if (ResourceUtils.isUrl(text) || resource.exists()) { <ide> try { <del> setValue(resource != null ? resource.getFile() : null); <add> setValue(resource.getFile()); <ide> } <ide> catch (IOException ex) { <ide> throw new IllegalArgumentException( <ide> "Could not retrieve File for " + resource + ": " + ex.getMessage()); <ide> } <ide> } <ide> else { <del> // Create a relative File reference and hope for the best <del> File file = new File(text); <del> setValue(file); <add> // Create a relative File reference and hope for the best. <add> setValue(new File(text)); <ide> } <ide> } <ide>
1
Python
Python
fix bug with test_suite being called incorrectly
85eeb4732ea7e49c01db4f7981ee07c8fc1c90c3
<ide><path>numpy/testing/numpytest.py <ide> def _get_suite_list(self, test_module, level, module_name='__main__', <ide> mstr = self._module_str <ide> suite_list = [] <ide> if hasattr(test_module,'test_suite'): <del> suite_list.extend(test_module.test_suite(level)._tests) <add> suite_list.extend(test_module.test_suite._tests) <ide> for name in dir(test_module): <ide> obj = getattr(test_module, name) <ide> if type(obj) is not type(unittest.TestCase) \
1
Javascript
Javascript
use map to track handles in cluster child
5a50989f5bde1e7cd495922444a3ce5a4c680897
<ide><path>lib/internal/cluster/child.js <ide> const { owner_symbol } = require('internal/async_hooks').symbols; <ide> const Worker = require('internal/cluster/worker'); <ide> const { internal, sendHelper } = require('internal/cluster/utils'); <ide> const cluster = new EventEmitter(); <del>const handles = {}; <add>const handles = new Map(); <ide> const indexes = new Map(); <ide> const noop = () => {}; <ide> <ide> function shared(message, handle, indexesKey, cb) { <ide> <ide> handle.close = function() { <ide> send({ act: 'close', key }); <del> delete handles[key]; <add> handles.delete(key); <ide> indexes.delete(indexesKey); <ide> return close.apply(this, arguments); <ide> }.bind(handle); <del> assert(handles[key] === undefined); <del> handles[key] = handle; <add> assert(handles.has(key) === false); <add> handles.set(key, handle); <ide> cb(message.errno, handle); <ide> } <ide> <ide> function rr(message, indexesKey, cb) { <ide> return; <ide> <ide> send({ act: 'close', key }); <del> delete handles[key]; <add> handles.delete(key); <ide> indexes.delete(indexesKey); <ide> key = undefined; <ide> } <ide> function rr(message, indexesKey, cb) { <ide> handle.getsockname = getsockname; // TCP handles only. <ide> } <ide> <del> assert(handles[key] === undefined); <del> handles[key] = handle; <add> assert(handles.has(key) === false); <add> handles.set(key, handle); <ide> cb(0, handle); <ide> } <ide> <ide> // Round-robin connection. <ide> function onconnection(message, handle) { <ide> const key = message.key; <del> const server = handles[key]; <add> const server = handles.get(key); <ide> const accepted = server !== undefined; <ide> <ide> send({ ack: message.seq, accepted }); <ide> function _disconnect(masterInitiated) { <ide> } <ide> } <ide> <del> for (var key in handles) { <del> const handle = handles[key]; <del> delete handles[key]; <add> handles.forEach((handle) => { <ide> waitingCount++; <ide> <ide> if (handle[owner_symbol]) <ide> handle[owner_symbol].close(checkWaitingCount); <ide> else <ide> handle.close(checkWaitingCount); <del> } <add> }); <ide> <add> handles.clear(); <ide> checkWaitingCount(); <ide> } <ide>
1
Ruby
Ruby
fix stupid typo in bottle fix
fe4e73db323c7245f26b973ce78fa28f7e4433d4
<ide><path>Library/Homebrew/macos.rb <ide> def pkgutil_info id <ide> <ide> def bottles_supported? raise_if_failed=false <ide> # We support bottles on all versions of OS X except 32-bit Snow Leopard. <del> if Hardware.is_32_bit? and MacOS.version = :snow_leopard <add> if Hardware.is_32_bit? and MacOS.version == :snow_leopard <ide> return false unless raise_if_failed <ide> raise "Bottles are not supported on 32-bit Snow Leopard." <ide> end
1
Ruby
Ruby
fix broken number_to_currency tests
1b46a1158c221c3910f80f183f6591f14e68c236
<ide><path>activesupport/lib/active_support/number_helper/number_to_currency_converter.rb <add>require 'active_support/core_ext/numeric/inquiry' <add> <ide> module ActiveSupport <ide> module NumberHelper <ide> class NumberToCurrencyConverter < NumberConverter # :nodoc:
1
Ruby
Ruby
convert fixtures to a list of hashes to insert
bc3c3453d485a098c91d96b6f0a8e2c9a1e9b17b
<ide><path>activerecord/lib/active_record/fixtures.rb <ide> def insert_fixtures <ide> Fixtures.find_table_name(habtm.options[:join_table]), nil) <ide> end <ide> <del> fixtures.each do |label, fixture| <add> rows = fixtures.map do |label, fixture| <ide> row = fixture.to_hash <ide> <ide> if model_class && model_class < ActiveRecord::Base <ide> def insert_fixtures <ide> end <ide> end <ide> <del> @connection.insert_fixture(fixture, @table_name) <add> row <add> end <add> <add> rows.each do |row| <add> @connection.insert_fixture(row, table_name) <ide> end <ide> <ide> # insert any HABTM join tables we discovered
1
Javascript
Javascript
fix compiler tests
e225d1005cb17994f024a6cfcfc2c8b5ac6218c4
<ide><path>test/Compiler.test.js <ide> describe("Compiler", () => { <ide> compiler.outputFileSystem = new MemoryFs(); <ide> const watching = compiler.watch({}, (err, stats) => { <ide> if (err) return done(err); <del> done(); <ide> }); <ide> watching.close(() => { <ide> compiler.run((err, stats) => { <ide> describe("Compiler", () => { <ide> }); <ide> }); <ide> }); <add> it("should watch again correctly after first closed watch", function(done) { <add> const compiler = webpack({ <add> context: __dirname, <add> mode: "production", <add> entry: "./c", <add> output: { <add> path: "/", <add> filename: "bundle.js" <add> } <add> }); <add> compiler.outputFileSystem = new MemoryFs(); <add> const watching = compiler.watch({}, (err, stats) => { <add> if (err) return done(err); <add> }); <add> watching.close(() => { <add> compiler.watch({}, (err, stats) => { <add> if (err) return done(err); <add> done(); <add> }); <add> }); <add> }); <ide> });
1
Javascript
Javascript
remove toolbarandroid, move to fb internal
31ab94770311f56182734b57c48ffcd765096dc5
<ide><path>Libraries/Components/ToolbarAndroid/ToolbarAndroid.android.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> * @flow <del> */ <del> <del>'use strict'; <del> <del>const React = require('react'); <del>const UIManager = require('../../ReactNative/UIManager'); <del> <del>const ToolbarAndroidNativeComponent = require('./ToolbarAndroidNativeComponent'); <del>const resolveAssetSource = require('../../Image/resolveAssetSource'); <del> <del>import type {SyntheticEvent} from '../../Types/CoreEventTypes'; <del>import type {ImageSource} from '../../Image/ImageSource'; <del>import type {ColorValue} from '../../StyleSheet/StyleSheetTypes'; <del>import type {ViewProps} from '../View/ViewPropTypes'; <del>import type {NativeComponent} from '../../Renderer/shims/ReactNative'; <del> <del>/** <del> * React component that wraps the Android-only [`Toolbar` widget][0]. A Toolbar can display a logo, <del> * navigation icon (e.g. hamburger menu), a title & subtitle and a list of actions. The title and <del> * subtitle are expanded so the logo and navigation icons are displayed on the left, title and <del> * subtitle in the middle and the actions on the right. <del> * <del> * If the toolbar has an only child, it will be displayed between the title and actions. <del> * <del> * Although the Toolbar supports remote images for the logo, navigation and action icons, this <del> * should only be used in DEV mode where `require('./some_icon.png')` translates into a packager <del> * URL. In release mode you should always use a drawable resource for these icons. Using <del> * `require('./some_icon.png')` will do this automatically for you, so as long as you don't <del> * explicitly use e.g. `{uri: 'http://...'}`, you will be good. <del> * <del> * Example: <del> * <del> * ``` <del> * render: function() { <del> * return ( <del> * <ToolbarAndroid <del> * logo={require('./app_logo.png')} <del> * title="AwesomeApp" <del> * actions={[{title: 'Settings', icon: require('./icon_settings.png'), show: 'always'}]} <del> * onActionSelected={this.onActionSelected} /> <del> * ) <del> * }, <del> * onActionSelected: function(position) { <del> * if (position === 0) { // index of 'Settings' <del> * showSettings(); <del> * } <del> * } <del> * ``` <del> * <del> * [0]: https://developer.android.com/reference/android/support/v7/widget/Toolbar.html <del> */ <del> <del>type Action = $ReadOnly<{| <del> title: string, <del> icon?: ?ImageSource, <del> show?: 'always' | 'ifRoom' | 'never', <del> showWithText?: boolean, <del>|}>; <del> <del>type ToolbarAndroidChangeEvent = SyntheticEvent< <del> $ReadOnly<{| <del> position: number, <del> |}>, <del>>; <del> <del>type ToolbarAndroidProps = $ReadOnly<{| <del> ...ViewProps, <del> /** <del> * or text on the right side of the widget. If they don't fit they are placed in an 'overflow' <del> * Sets possible actions on the toolbar as part of the action menu. These are displayed as icons <del> * menu. <del> * <del> * This property takes an array of objects, where each object has the following keys: <del> * <del> * * `title`: **required**, the title of this action <del> * * `icon`: the icon for this action, e.g. `require('./some_icon.png')` <del> * * `show`: when to show this action as an icon or hide it in the overflow menu: `always`, <del> * `ifRoom` or `never` <del> * * `showWithText`: boolean, whether to show text alongside the icon or not <del> */ <del> actions?: ?Array<Action>, <del> /** <del> * Sets the toolbar logo. <del> */ <del> logo?: ?ImageSource, <del> /** <del> * Sets the navigation icon. <del> */ <del> navIcon?: ?ImageSource, <del> /** <del> * Callback that is called when an action is selected. The only argument that is passed to the <del> * callback is the position of the action in the actions array. <del> */ <del> onActionSelected?: ?(position: number) => void, <del> /** <del> * Callback called when the icon is selected. <del> */ <del> onIconClicked?: ?() => void, <del> /** <del> * Sets the overflow icon. <del> */ <del> overflowIcon?: ?ImageSource, <del> /** <del> * Sets the toolbar subtitle. <del> */ <del> subtitle?: ?string, <del> /** <del> * Sets the toolbar subtitle color. <del> */ <del> subtitleColor?: ?ColorValue, <del> /** <del> * Sets the toolbar title. <del> */ <del> title?: ?Stringish, <del> /** <del> * Sets the toolbar title color. <del> */ <del> titleColor?: ?ColorValue, <del> /** <del> * Sets the content inset for the toolbar starting edge. <del> * <del> * The content inset affects the valid area for Toolbar content other than <del> * the navigation button and menu. Insets define the minimum margin for <del> * these components and can be used to effectively align Toolbar content <del> * along well-known gridlines. <del> */ <del> contentInsetStart?: ?number, <del> /** <del> * Sets the content inset for the toolbar ending edge. <del> * <del> * The content inset affects the valid area for Toolbar content other than <del> * the navigation button and menu. Insets define the minimum margin for <del> * these components and can be used to effectively align Toolbar content <del> * along well-known gridlines. <del> */ <del> contentInsetEnd?: ?number, <del> /** <del> * Used to set the toolbar direction to RTL. <del> * In addition to this property you need to add <del> * <del> * android:supportsRtl="true" <del> * <del> * to your application AndroidManifest.xml and then call <del> * `setLayoutDirection(LayoutDirection.RTL)` in your MainActivity <del> * `onCreate` method. <del> */ <del> rtl?: ?boolean, <del> /** <del> * Used to locate this view in end-to-end tests. <del> */ <del> testID?: ?string, <del>|}>; <del> <del>type Props = $ReadOnly<{| <del> ...ToolbarAndroidProps, <del> forwardedRef: ?React.Ref<typeof ToolbarAndroidNativeComponent>, <del>|}>; <del> <del>class ToolbarAndroid extends React.Component<Props> { <del> _onSelect = (event: ToolbarAndroidChangeEvent) => { <del> const position = event.nativeEvent.position; <del> if (position === -1) { <del> this.props.onIconClicked && this.props.onIconClicked(); <del> } else { <del> this.props.onActionSelected && this.props.onActionSelected(position); <del> } <del> }; <del> <del> render() { <del> const { <del> onIconClicked, <del> onActionSelected, <del> forwardedRef, <del> ...otherProps <del> } = this.props; <del> <del> const nativeProps: {...typeof otherProps, nativeActions?: Array<Action>} = { <del> ...otherProps, <del> }; <del> <del> if (this.props.logo) { <del> nativeProps.logo = resolveAssetSource(this.props.logo); <del> } <del> <del> if (this.props.navIcon) { <del> nativeProps.navIcon = resolveAssetSource(this.props.navIcon); <del> } <del> <del> if (this.props.overflowIcon) { <del> nativeProps.overflowIcon = resolveAssetSource(this.props.overflowIcon); <del> } <del> <del> if (this.props.actions) { <del> const nativeActions = []; <del> for (let i = 0; i < this.props.actions.length; i++) { <del> const action = { <del> icon: this.props.actions[i].icon, <del> show: this.props.actions[i].show, <del> }; <del> <del> if (action.icon) { <del> action.icon = resolveAssetSource(action.icon); <del> } <del> if (action.show) { <del> action.show = UIManager.getViewManagerConfig( <del> 'ToolbarAndroid', <del> ).Constants.ShowAsAction[action.show]; <del> } <del> <del> nativeActions.push({ <del> ...this.props.actions[i], <del> ...action, <del> }); <del> } <del> <del> nativeProps.nativeActions = nativeActions; <del> } <del> <del> return ( <del> <ToolbarAndroidNativeComponent <del> onSelect={this._onSelect} <del> {...nativeProps} <del> ref={forwardedRef} <del> /> <del> ); <del> } <del>} <del> <del>const ToolbarAndroidToExport = React.forwardRef( <del> ( <del> props: ToolbarAndroidProps, <del> forwardedRef: ?React.Ref<typeof ToolbarAndroidNativeComponent>, <del> ) => { <del> return <ToolbarAndroid {...props} forwardedRef={forwardedRef} />; <del> }, <del>); <del> <del>/* $FlowFixMe(>=0.89.0 site=react_native_android_fb) This comment suppresses an <del> * error found when Flow v0.89 was deployed. To see the error, delete this <del> * comment and run Flow. */ <del>module.exports = (ToolbarAndroidToExport: Class< <del> NativeComponent<ToolbarAndroidProps>, <del>>); <ide><path>Libraries/Components/ToolbarAndroid/ToolbarAndroid.ios.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> */ <del> <del>'use strict'; <del> <del>module.exports = require('../UnimplementedViews/UnimplementedView'); <ide><path>Libraries/Components/ToolbarAndroid/ToolbarAndroidNativeComponent.js <del>/** <del> * Copyright (c) Facebook, Inc. and its affiliates. <del> * <del> * This source code is licensed under the MIT license found in the <del> * LICENSE file in the root directory of this source tree. <del> * <del> * @format <del> * @flow <del> */ <del> <del>'use strict'; <del> <del>const requireNativeComponent = require('../../ReactNative/requireNativeComponent'); <del> <del>import type {SyntheticEvent} from '../../Types/CoreEventTypes'; <del>import type {ImageSource} from '../../Image/ImageSource'; <del>import type {ViewProps} from '../View/ViewPropTypes'; <del>import type {NativeComponent} from '../../Renderer/shims/ReactNative'; <del> <del>type Action = $ReadOnly<{| <del> title: string, <del> icon?: ?ImageSource, <del> show?: 'always' | 'ifRoom' | 'never', <del> showWithText?: boolean, <del>|}>; <del> <del>type ToolbarAndroidChangeEvent = SyntheticEvent< <del> $ReadOnly<{| <del> position: number, <del> |}>, <del>>; <del> <del>type NativeProps = $ReadOnly<{| <del> onSelect: (event: ToolbarAndroidChangeEvent) => mixed, <del> nativeActions?: Array<Action>, <del>|}>; <del> <del>type ColorValue = null | string; <del> <del>type ToolbarAndroidProps = $ReadOnly<{| <del> ...ViewProps, <del> ...NativeProps, <del> /** <del> * or text on the right side of the widget. If they don't fit they are placed in an 'overflow' <del> * Sets possible actions on the toolbar as part of the action menu. These are displayed as icons <del> * menu. <del> * <del> * This property takes an array of objects, where each object has the following keys: <del> * <del> * * `title`: **required**, the title of this action <del> * * `icon`: the icon for this action, e.g. `require('./some_icon.png')` <del> * * `show`: when to show this action as an icon or hide it in the overflow menu: `always`, <del> * `ifRoom` or `never` <del> * * `showWithText`: boolean, whether to show text alongside the icon or not <del> */ <del> actions?: ?Array<Action>, <del> /** <del> * Sets the toolbar logo. <del> */ <del> logo?: ?ImageSource, <del> /** <del> * Sets the navigation icon. <del> */ <del> navIcon?: ?ImageSource, <del> /** <del> * Callback that is called when an action is selected. The only argument that is passed to the <del> * callback is the position of the action in the actions array. <del> */ <del> onActionSelected?: ?(position: number) => void, <del> /** <del> * Callback called when the icon is selected. <del> */ <del> onIconClicked?: ?() => void, <del> /** <del> * Sets the overflow icon. <del> */ <del> overflowIcon?: ?ImageSource, <del> /** <del> * Sets the toolbar subtitle. <del> */ <del> subtitle?: ?string, <del> /** <del> * Sets the toolbar subtitle color. <del> */ <del> subtitleColor?: ?ColorValue, <del> /** <del> * Sets the toolbar title. <del> */ <del> title?: ?Stringish, <del> /** <del> * Sets the toolbar title color. <del> */ <del> titleColor?: ?ColorValue, <del> /** <del> * Sets the content inset for the toolbar starting edge. <del> * <del> * The content inset affects the valid area for Toolbar content other than <del> * the navigation button and menu. Insets define the minimum margin for <del> * these components and can be used to effectively align Toolbar content <del> * along well-known gridlines. <del> */ <del> contentInsetStart?: ?number, <del> /** <del> * Sets the content inset for the toolbar ending edge. <del> * <del> * The content inset affects the valid area for Toolbar content other than <del> * the navigation button and menu. Insets define the minimum margin for <del> * these components and can be used to effectively align Toolbar content <del> * along well-known gridlines. <del> */ <del> contentInsetEnd?: ?number, <del> /** <del> * Used to set the toolbar direction to RTL. <del> * In addition to this property you need to add <del> * <del> * android:supportsRtl="true" <del> * <del> * to your application AndroidManifest.xml and then call <del> * `setLayoutDirection(LayoutDirection.RTL)` in your MainActivity <del> * `onCreate` method. <del> */ <del> rtl?: ?boolean, <del> /** <del> * Used to locate this view in end-to-end tests. <del> */ <del> testID?: ?string, <del>|}>; <del> <del>type NativeToolbarAndroidProps = Class<NativeComponent<ToolbarAndroidProps>>; <del> <del>module.exports = ((requireNativeComponent( <del> 'ToolbarAndroid', <del>): any): NativeToolbarAndroidProps); <ide><path>Libraries/react-native/react-native-implementation.js <ide> module.exports = { <ide> get TextInput() { <ide> return require('TextInput'); <ide> }, <del> get ToolbarAndroid() { <del> return require('ToolbarAndroid'); <del> }, <ide> get Touchable() { <ide> return require('Touchable'); <ide> },
4
Text
Text
fix typos in code-splitting readme
73c1951c7004e7915c69a41d24d525a0955520c7
<ide><path>examples/code-splitting/README.md <del>This example illustrate a very simple case of Code Splitting with `require.ensure`. <add>This example illustrates a very simple case of Code Splitting with `require.ensure`. <ide> <del>* `a` and `b` are required normally via CommonsJs <add>* `a` and `b` are required normally via CommonJS <ide> * `c` is depdended through the `require.ensure` array. <ide> * This means: make it available, but don't execute it <ide> * webpack will load it on demand <ide> This example illustrate a very simple case of Code Splitting with `require.ensur <ide> <ide> You can see that webpack outputs two files/chunks: <ide> <del>* `output.js` is the entry chunks and contains <add>* `output.js` is the entry chunk and contains <ide> * the module system <ide> * chunk loading logic <ide> * the entry point `example.js`
1
Javascript
Javascript
expose reactfibertreereflection in fb build
f1abc3cd12f42c3498530c483e4bf77f4f0b6121
<ide><path>src/fb/ReactDOMFiberFBEntry.js <ide> Object.assign( <ide> ReactBrowserEventEmitter: require('ReactBrowserEventEmitter'), <ide> ReactErrorUtils: require('ReactErrorUtils'), <ide> ReactFiberErrorLogger: require('ReactFiberErrorLogger'), <add> ReactFiberTreeReflection: require('ReactFiberTreeReflection'), <ide> ReactDOMComponentTree: require('ReactDOMComponentTree'), <ide> ReactInstanceMap: require('ReactInstanceMap'), <ide> // This is used for ajaxify on www:
1
Text
Text
clarify http.agent constructor options
8a291a8e83313c42cc8c755a4d3125c6c07a1322
<ide><path>doc/api/http.md <ide> added: v0.3.4 <ide> Can have the following fields: <ide> * `keepAlive` {boolean} Keep sockets around even when there are no <ide> outstanding requests, so they can be used for future requests without <del> having to reestablish a TCP connection. **Default:** `false`. <add> having to reestablish a TCP connection. Not to be confused with the <add> `keep-alive` value of the `Connection` header. The `Connection: keep-alive` <add> header is always sent when using an agent except when the `Connection` <add> header is explicitly specified or when the `keepAlive` and `maxSockets` <add> options are respectively set to `false` and `Infinity`, in which case <add> `Connection: close` will be used. **Default:** `false`. <ide> * `keepAliveMsecs` {number} When using the `keepAlive` option, specifies <ide> the [initial delay](net.html#net_socket_setkeepalive_enable_initialdelay) <ide> for TCP Keep-Alive packets. Ignored when the <ide> `keepAlive` option is `false` or `undefined`. **Default:** `1000`. <ide> * `maxSockets` {number} Maximum number of sockets to allow per <del> host. **Default:** `Infinity`. <add> host. Each request will use a new socket until the maximum is reached. <add> **Default:** `Infinity`. <ide> * `maxFreeSockets` {number} Maximum number of sockets to leave open <ide> in a free state. Only relevant if `keepAlive` is set to `true`. <ide> **Default:** `256`.
1
Go
Go
use bufio for compression detection
77c2b76e44f77eee2ca89ff551ac64f8c6b8bd23
<ide><path>archive/archive.go <ide> package archive <ide> <ide> import ( <del> "bytes" <add> "bufio" <ide> "compress/bzip2" <ide> "compress/gzip" <ide> "errors" <ide> "fmt" <del> "github.com/dotcloud/docker/pkg/system" <del> "github.com/dotcloud/docker/utils" <del> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> "io" <ide> "io/ioutil" <ide> "os" <ide> import ( <ide> "path/filepath" <ide> "strings" <ide> "syscall" <add> <add> "github.com/dotcloud/docker/pkg/system" <add> "github.com/dotcloud/docker/utils" <add> "github.com/dotcloud/docker/vendor/src/code.google.com/p/go/src/pkg/archive/tar" <ide> ) <ide> <ide> type ( <ide> func xzDecompress(archive io.Reader) (io.ReadCloser, error) { <ide> } <ide> <ide> func DecompressStream(archive io.Reader) (io.ReadCloser, error) { <del> buf := make([]byte, 10) <del> totalN := 0 <del> for totalN < 10 { <del> n, err := archive.Read(buf[totalN:]) <del> if err != nil { <del> if err == io.EOF { <del> return nil, fmt.Errorf("Tarball too short") <del> } <del> return nil, err <del> } <del> totalN += n <del> utils.Debugf("[tar autodetect] n: %d", n) <add> buf := bufio.NewReader(archive) <add> bs, err := buf.Peek(10) <add> if err != nil { <add> return nil, err <ide> } <del> compression := DetectCompression(buf) <del> wrap := io.MultiReader(bytes.NewReader(buf), archive) <add> utils.Debugf("[tar autodetect] n: %v", bs) <add> <add> compression := DetectCompression(bs) <ide> <ide> switch compression { <ide> case Uncompressed: <del> return ioutil.NopCloser(wrap), nil <add> return ioutil.NopCloser(buf), nil <ide> case Gzip: <del> return gzip.NewReader(wrap) <add> return gzip.NewReader(buf) <ide> case Bzip2: <del> return ioutil.NopCloser(bzip2.NewReader(wrap)), nil <add> return ioutil.NopCloser(bzip2.NewReader(buf)), nil <ide> case Xz: <del> return xzDecompress(wrap) <add> return xzDecompress(buf) <ide> default: <ide> return nil, fmt.Errorf("Unsupported compression format %s", (&compression).Extension()) <ide> }
1
PHP
PHP
fix trailing whitespace
61dd1c3f9d178b1f52c1e2623663d80a76f10490
<ide><path>lib/Cake/Test/Case/Model/Behavior/TranslateBehaviorTest.php <ide> public function testLocaleSingleWithConditions() { <ide> ); <ide> $this->assertEquals($expected, $result); <ide> } <del> <add> <ide> /** <ide> * testLocaleSingleCountWithConditions method <ide> *
1
Text
Text
fix some errant links
9ed6cec8ff91ff100c268fa21817fdc111e77e43
<ide><path>docs/installation/SUSE.md <ide> You must delete the user created configuration files manually. <ide> <ide> ## Where to go from here <ide> <del>You can find more details about Docker on openSUSE or SUSE Linux Enterprise in <del>the [Docker quick start guide](https://www.suse.com/documentation/sles-12/dockerquick/data/dockerquick. <del>html) on the SUSE website. The document targets SUSE Linux Enterprise, but its contents apply also to openSUSE. <add>You can find more details about Docker on openSUSE or SUSE Linux Enterprise in the <add>[Docker quick start guide](https://www.suse.com/documentation/sles-12/dockerquick/data/dockerquick.html) <add>on the SUSE website. The document targets SUSE Linux Enterprise, but its contents apply also to openSUSE. <ide> <ide> Continue to the [User Guide](../userguide/). <ide><path>docs/misc/deprecated.md <ide> The built-in LXC execution driver is deprecated for an external implementation. <ide> The lxc-conf flag and API fields will also be removed. <ide> <ide> ### Old Command Line Options <del>**Deprecated In Release: [v1.8.0](../release-notes.md#docker-engine-1-8-0)** <add>**Deprecated In Release: [v1.8.0](release-notes.md#docker-engine-1-8-0)** <ide> <ide> **Target For Removal In Release: v1.10** <ide> <ide><path>docs/reference/run.md <ide> and pass along signals. All of that is configurable: <ide> -i=false : Keep STDIN open even if not attached <ide> <ide> If you do not specify `-a` then Docker will [attach all standard <del>streams]( https://github.com/docker/docker/blob/ <del>75a7f4d90cde0295bcfb7213004abce8d4779b75/commands.go#L1797). You can <del>specify to which of the three standard streams (`STDIN`, `STDOUT`, <add>streams]( https://github.com/docker/docker/blob/75a7f4d90cde0295bcfb7213004abce8d4779b75/commands.go#L1797). <add>You can specify to which of the three standard streams (`STDIN`, `STDOUT`, <ide> `STDERR`) you'd like to connect instead, as in: <ide> <ide> $ docker run -a stdin -a stdout -i -t ubuntu /bin/bash <ide><path>docs/security/trust/trust_sandbox.md <ide> have `sudo` privileges on your local machine or in the VM. <ide> This sandbox requires you to install two Docker tools: Docker Engine and Docker <ide> Compose. To install the Docker Engine, choose from the [list of supported <ide> platforms](../../installation). To install Docker Compose, see the <del>[detailed instructions here](https://docs.docker.com/compose/install.md). <add>[detailed instructions here](https://docs.docker.com/compose/install/). <ide> <ide> Finally, you'll need to have `git` installed on your local system or VM. <ide> <ide><path>docs/userguide/dockervolumes.md <ide> Here we've mounted the same `/src/webapp` directory but we've added the `ro` <ide> option to specify that the mount should be read-only. <ide> <ide> Because of [limitations in the `mount` <del>function](http://lists.linuxfoundation.org/pipermail/containers/2015-April/ <del>035788.html), moving subdirectories within the host's source directory can give <add>function](http://lists.linuxfoundation.org/pipermail/containers/2015-April/035788.html), <add>moving subdirectories within the host's source directory can give <ide> access from the container to the host's file system. This requires a malicious <ide> user with access to host and its mounted directory. <ide>
5
Javascript
Javascript
add test for selectors with commas
d7af36676b89a15ad0571cbf0d2a7d8b93470e58
<ide><path>test/unit/selector.js <ide> test("name", function() { <ide> form.remove(); <ide> }); <ide> <add>test( "comma selectors", function() { <add> expect( 4 ); <add> <add> var fixture = jQuery( "<div><h2><span/></h2><div><p><span/></p><p/></div></div>" ); <add> <add> equal( fixture.find( "h2, div p" ).filter( "p" ).length, 2, "has to find two <p>" ); <add> equal( fixture.find( "h2, div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); <add> equal( fixture.find( "h2 , div p" ).filter( "p" ).length, 2, "has to find two <p>" ); <add> equal( fixture.find( "h2 , div p" ).filter( "h2" ).length, 1, "has to find one <h2>" ); <add>}); <add> <add> <ide> test("attributes - jQuery only", function() { <ide> expect( 5 ); <ide>
1
Javascript
Javascript
use full url to github issues in comments
8a8416f84169c553380704ab3a754db0a1735877
<ide><path>lib/internal/event_target.js <ide> function initEventTarget(self) { <ide> <ide> class EventTarget { <ide> // Used in checking whether an object is an EventTarget. This is a well-known <del> // symbol as EventTarget may be used cross-realm. See discussion in #33661. <add> // symbol as EventTarget may be used cross-realm. <add> // Ref: https://github.com/nodejs/node/pull/33661 <ide> static [kIsEventTarget] = true; <ide> <ide> constructor() { <ide> function validateEventListenerOptions(options) { <ide> // Test whether the argument is an event object. This is far from a fool-proof <ide> // test, for example this input will result in a false positive: <ide> // > isEventTarget({ constructor: EventTarget }) <del>// It stands in its current implementation as a compromise. For the relevant <del>// discussion, see #33661. <add>// It stands in its current implementation as a compromise. <add>// Ref: https://github.com/nodejs/node/pull/33661 <ide> function isEventTarget(obj) { <ide> return obj && obj.constructor && obj.constructor[kIsEventTarget]; <ide> } <ide><path>lib/internal/stream_base_commons.js <ide> function onStreamRead(arrayBuffer) { <ide> } <ide> <ide> if (nread !== UV_EOF) { <del> // #34375 CallJSOnreadMethod expects the return value to be a buffer. <add> // CallJSOnreadMethod expects the return value to be a buffer. <add> // Ref: https://github.com/nodejs/node/pull/34375 <ide> stream.destroy(errnoException(nread, 'read')); <ide> return; <ide> } <ide> function onStreamRead(arrayBuffer) { <ide> if (handle.readStop) { <ide> const err = handle.readStop(); <ide> if (err) { <del> // #34375 CallJSOnreadMethod expects the return value to be a buffer. <add> // CallJSOnreadMethod expects the return value to be a buffer. <add> // Ref: https://github.com/nodejs/node/pull/34375 <ide> stream.destroy(errnoException(err, 'read')); <ide> return; <ide> }
2
Javascript
Javascript
sanitize values bound to img[src]
1adf29af13890d61286840177607edd552a9df97
<ide><path>src/ng/compile.js <ide> function $CompileProvider($provide) { <ide> * <ide> * @description <ide> * Retrieves or overrides the default regular expression that is used for whitelisting of safe <del> * urls during a[href] sanitization. <add> * urls during a[href] and img[src] sanitization. <ide> * <ide> * The sanitization is a security measure aimed at prevent XSS attacks via html links. <ide> * <del> * Any url about to be assigned to a[href] via data-binding is first normalized and turned into an <del> * absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular <del> * expression. If a match is found the original url is written into the dom. Otherwise the <del> * absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM. <add> * Any url about to be assigned to a[href] or img[src] via data-binding is first normalized and <add> * turned into an absolute url. Afterwards, the url is matched against the <add> * `urlSanitizationWhitelist` regular expression. If a match is found, the original url is written <add> * into the dom. Otherwise, the absolute url is prefixed with `'unsafe:'` string and only then is <add> * it written into the DOM. <ide> * <ide> * @param {RegExp=} regexp New regexp to whitelist urls with. <ide> * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for <ide> function $CompileProvider($provide) { <ide> $set: function(key, value, writeAttr, attrName) { <ide> var booleanKey = getBooleanAttrName(this.$$element[0], key), <ide> $$observers = this.$$observers, <del> normalizedVal; <add> normalizedVal, <add> nodeName; <ide> <ide> if (booleanKey) { <ide> this.$$element.prop(key, value); <ide> function $CompileProvider($provide) { <ide> } <ide> <ide> <del> // sanitize a[href] values <del> if (nodeName_(this.$$element[0]) === 'A' && key === 'href') { <add> // sanitize a[href] and img[src] values <add> nodeName = nodeName_(this.$$element); <add> if ((nodeName === 'A' && key === 'href') || <add> (nodeName === 'IMG' && key === 'src')){ <ide> urlSanitizationNode.setAttribute('href', value); <ide> <ide> // href property always returns normalized absolute url, so we can match against that <ide><path>test/ng/compileSpec.js <ide> describe('$compile', function() { <ide> }); <ide> <ide> <del> describe('href sanitization', function() { <add> describe('img[src] sanitization', function() { <add> it('should NOT require trusted values for img src', inject(function($rootScope, $compile) { <add> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <add> $rootScope.testUrl = 'http://example.com/image.png'; <add> $rootScope.$digest(); <add> expect(element.attr('src')).toEqual('http://example.com/image.png'); <add> })); <add> <add> it('should sanitize javascript: urls', inject(function($compile, $rootScope) { <add> element = $compile('<img src="{{testUrl}}"></a>')($rootScope); <add> $rootScope.testUrl = "javascript:doEvilStuff()"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('unsafe:javascript:doEvilStuff()'); <add> })); <add> <add> it('should sanitize data: urls', inject(function($compile, $rootScope) { <add> element = $compile('<img src="{{testUrl}}"></a>')($rootScope); <add> $rootScope.testUrl = "data:evilPayload"; <add> $rootScope.$apply(); <add> <add> expect(element.attr('src')).toBe('unsafe:data:evilPayload'); <add> })); <add> <add> <add> it('should sanitize obfuscated javascript: urls', inject(function($compile, $rootScope) { <add> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <add> <add> // case-sensitive <add> $rootScope.testUrl = "JaVaScRiPt:doEvilStuff()"; <add> $rootScope.$apply(); <add> expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); <add> <add> // tab in protocol <add> $rootScope.testUrl = "java\u0009script:doEvilStuff()"; <add> $rootScope.$apply(); <add> expect(element[0].src).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); <add> <add> // space before <add> $rootScope.testUrl = " javascript:doEvilStuff()"; <add> $rootScope.$apply(); <add> expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); <add> <add> // ws chars before <add> $rootScope.testUrl = " \u000e javascript:doEvilStuff()"; <add> $rootScope.$apply(); <add> expect(element[0].src).toMatch(/(http:\/\/|unsafe:javascript:doEvilStuff\(\))/); <add> <add> // post-fixed with proper url <add> $rootScope.testUrl = "javascript:doEvilStuff(); http://make.me/look/good"; <add> $rootScope.$apply(); <add> expect(element[0].src).toBeOneOf( <add> 'unsafe:javascript:doEvilStuff(); http://make.me/look/good', <add> 'unsafe:javascript:doEvilStuff();%20http://make.me/look/good' <add> ); <add> })); <add> <add> it('should sanitize ng-src bindings as well', inject(function($compile, $rootScope) { <add> element = $compile('<img ng-src="{{testUrl}}"></img>')($rootScope); <add> $rootScope.testUrl = "javascript:doEvilStuff()"; <add> $rootScope.$apply(); <add> <add> expect(element[0].src).toBe('unsafe:javascript:doEvilStuff()'); <add> })); <add> <add> <add> it('should not sanitize valid urls', inject(function($compile, $rootScope) { <add> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <add> <add> $rootScope.testUrl = "foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('foo/bar'); <add> <add> $rootScope.testUrl = "/foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('/foo/bar'); <add> <add> $rootScope.testUrl = "../foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('../foo/bar'); <add> <add> $rootScope.testUrl = "#foo"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('#foo'); <add> <add> $rootScope.testUrl = "http://foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('http://foo/bar'); <add> <add> $rootScope.testUrl = " http://foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe(' http://foo/bar'); <add> <add> $rootScope.testUrl = "https://foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('https://foo/bar'); <add> <add> $rootScope.testUrl = "ftp://foo/bar"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('ftp://foo/bar'); <add> <add> // Fails on IE < 10 with "TypeError: Access is denied" when trying to set img[src] <add> if (!msie || msie > 10) { <add> $rootScope.testUrl = "mailto:foo@bar.com"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('mailto:foo@bar.com'); <add> } <add> <add> $rootScope.testUrl = "file:///foo/bar.html"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('file:///foo/bar.html'); <add> })); <add> <add> <add> it('should not sanitize attributes other than src', inject(function($compile, $rootScope) { <add> element = $compile('<img title="{{testUrl}}"></img>')($rootScope); <add> $rootScope.testUrl = "javascript:doEvilStuff()"; <add> $rootScope.$apply(); <add> <add> expect(element.attr('title')).toBe('javascript:doEvilStuff()'); <add> })); <add> <add> <add> it('should allow reconfiguration of the src whitelist', function() { <add> module(function($compileProvider) { <add> expect($compileProvider.urlSanitizationWhitelist() instanceof RegExp).toBe(true); <add> var returnVal = $compileProvider.urlSanitizationWhitelist(/javascript:/); <add> expect(returnVal).toBe($compileProvider); <add> }); <add> <add> inject(function($compile, $rootScope) { <add> element = $compile('<img src="{{testUrl}}"></img>')($rootScope); <add> <add> // Fails on IE < 10 with "TypeError: Object doesn't support this property or method" when <add> // trying to set img[src] <add> if (!msie || msie > 10) { <add> $rootScope.testUrl = "javascript:doEvilStuff()"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('javascript:doEvilStuff()'); <add> } <add> <add> $rootScope.testUrl = "http://recon/figured"; <add> $rootScope.$apply(); <add> expect(element.attr('src')).toBe('unsafe:http://recon/figured'); <add> }); <add> }); <add> <add> }); <add> <add> <add> describe('a[href] sanitization', function() { <ide> <ide> it('should sanitize javascript: urls', inject(function($compile, $rootScope) { <ide> element = $compile('<a href="{{testUrl}}"></a>')($rootScope);
2
Javascript
Javascript
move suspenselist to experimental channel
83564712b6e2907dcffdbf5f99b4713cf6c950de
<ide><path>packages/react-dom/src/__tests__/ReactDOMFizzServer-test.js <ide> describe('ReactDOMFizzServer', () => { <ide> } <ide> Stream = require('stream'); <ide> Suspense = React.Suspense; <del> SuspenseList = React.SuspenseList; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> <ide> PropTypes = require('prop-types'); <ide> <ide> describe('ReactDOMFizzServer', () => { <ide> expect(ref.current).toBe(b); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> // @gate experimental <ide> it('shows inserted items before pending in a SuspenseList as fallbacks while hydrating', async () => { <ide> const ref = React.createRef(); <ide><path>packages/react-dom/src/__tests__/ReactDOMServerPartialHydration-test.internal.js <ide> describe('ReactDOMServerPartialHydration', () => { <ide> ReactDOMServer = require('react-dom/server'); <ide> Scheduler = require('scheduler'); <ide> Suspense = React.Suspense; <del> SuspenseList = React.SuspenseList; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> <ide> IdleEventPriority = require('react-reconciler/constants').IdleEventPriority; <ide> }); <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(ref.current).toBe(span); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('shows inserted items in a SuspenseList before content is hydrated', async () => { <ide> let suspend = false; <ide> let resolve; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(ref.current).toBe(spanB); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('shows is able to hydrate boundaries even if others in a list are pending', async () => { <ide> let suspend = false; <ide> let resolve; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(container.textContent).toBe('ALoading B'); <ide> }); <ide> <del> // @gate experimental || www <add> // @gate enableSuspenseList <ide> it('clears server boundaries when SuspenseList runs out of time hydrating', async () => { <ide> let suspend = false; <ide> let resolve; <ide> describe('ReactDOMServerPartialHydration', () => { <ide> expect(ref.current).toBe(b); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('clears server boundaries when SuspenseList suspends last row hydrating', async () => { <ide> let suspend = false; <ide> let resolve; <ide><path>packages/react-dom/src/__tests__/ReactDOMServerSuspense-test.internal.js <ide> let ReactDOM; <ide> let ReactDOMServer; <ide> let ReactTestUtils; <ide> let act; <add>let SuspenseList; <ide> <ide> function initModules() { <ide> // Reset warning cache. <ide> function initModules() { <ide> ReactDOMServer = require('react-dom/server'); <ide> ReactTestUtils = require('react-dom/test-utils'); <ide> act = require('jest-react').act; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> <ide> // Make them available to the helpers. <ide> return { <ide> describe('ReactDOMServerSuspense', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('server renders a SuspenseList component and its children', async () => { <ide> const example = ( <del> <React.SuspenseList> <add> <SuspenseList> <ide> <React.Suspense fallback="Loading A"> <ide> <div>A</div> <ide> </React.Suspense> <ide> <React.Suspense fallback="Loading B"> <ide> <div>B</div> <ide> </React.Suspense> <del> </React.SuspenseList> <add> </SuspenseList> <ide> ); <ide> const element = await serverRender(example); <ide> const parent = element.parentNode; <ide><path>packages/react-dom/src/__tests__/ReactWrongReturnPointer-test.js <ide> beforeEach(() => { <ide> act = require('jest-react').act; <ide> <ide> Suspense = React.Suspense; <del> SuspenseList = React.SuspenseList; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> <ide> getCacheForType = React.unstable_getCacheForType; <ide> <ide> test('warns in DEV if return pointer is inconsistent', async () => { <ide> }); <ide> <ide> // @gate enableCache <add>// @gate enableSuspenseList <ide> test('regression (#20932): return pointer is correct before entering deleted tree', async () => { <ide> // Based on a production bug. Designed to trigger a very specific <ide> // implementation path. <ide><path>packages/react-is/src/__tests__/ReactIs-test.js <ide> let React; <ide> let ReactDOM; <ide> let ReactIs; <add>let SuspenseList; <ide> <ide> describe('ReactIs', () => { <ide> beforeEach(() => { <ide> describe('ReactIs', () => { <ide> React = require('react'); <ide> ReactDOM = require('react-dom'); <ide> ReactIs = require('react-is'); <add> <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> }); <ide> <ide> it('should return undefined for unknown/invalid types', () => { <ide> describe('ReactIs', () => { <ide> expect(ReactIs.isSuspense(<div />)).toBe(false); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('should identify suspense list', () => { <del> expect(ReactIs.isValidElementType(React.SuspenseList)).toBe(true); <del> expect(ReactIs.typeOf(<React.SuspenseList />)).toBe(ReactIs.SuspenseList); <del> expect(ReactIs.isSuspenseList(<React.SuspenseList />)).toBe(true); <add> expect(ReactIs.isValidElementType(SuspenseList)).toBe(true); <add> expect(ReactIs.typeOf(<SuspenseList />)).toBe(ReactIs.SuspenseList); <add> expect(ReactIs.isSuspenseList(<SuspenseList />)).toBe(true); <ide> expect(ReactIs.isSuspenseList({type: ReactIs.SuspenseList})).toBe(false); <ide> expect(ReactIs.isSuspenseList('React.SuspenseList')).toBe(false); <ide> expect(ReactIs.isSuspenseList(<div />)).toBe(false); <ide><path>packages/react-reconciler/src/__tests__/ReactContextPropagation-test.js <ide> describe('ReactLazyContextPropagation', () => { <ide> useState = React.useState; <ide> useContext = React.useContext; <ide> Suspense = React.Suspense; <del> SuspenseList = React.SuspenseList; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> <ide> getCacheForType = React.unstable_getCacheForType; <ide> <ide> describe('ReactLazyContextPropagation', () => { <ide> expect(root).toMatchRenderedOutput('BBB'); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> test('contexts are propagated through SuspenseList', async () => { <ide> // This kinda tests an implementation detail. SuspenseList has an early <ide> // bailout that doesn't use `bailoutOnAlreadyFinishedWork`. It probably <ide><path>packages/react-reconciler/src/__tests__/ReactHooksWithNoopRenderer-test.js <ide> let forwardRef; <ide> let memo; <ide> let act; <ide> let ContinuousEventPriority; <add>let SuspenseList; <ide> <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> beforeEach(() => { <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> Suspense = React.Suspense; <ide> ContinuousEventPriority = require('react-reconciler/constants') <ide> .ContinuousEventPriority; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> <ide> textCache = new Map(); <ide> <ide> describe('ReactHooksWithNoopRenderer', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('regression: SuspenseList causes unmounts to be dropped on deletion', async () => { <del> const SuspenseList = React.SuspenseList; <del> <ide> function Row({label}) { <ide> useEffect(() => { <ide> Scheduler.unstable_yieldValue('Mount ' + label); <ide><path>packages/react-reconciler/src/__tests__/ReactSuspenseList-test.js <ide> describe('ReactSuspenseList', () => { <ide> act = require('jest-react').act; <ide> Profiler = React.Profiler; <ide> Suspense = React.Suspense; <del> SuspenseList = React.SuspenseList; <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> }); <ide> <ide> function Text(props) { <ide> describe('ReactSuspenseList', () => { <ide> return Component; <ide> } <ide> <add> // @gate enableSuspenseList <ide> it('warns if an unsupported revealOrder option is used', () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if a upper case revealOrder option is used', () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if a misspelled revealOrder option is used', () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if a single element is passed to a "forwards" list', () => { <ide> function Foo({children}) { <ide> return <SuspenseList revealOrder="forwards">{children}</SuspenseList>; <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if a single fragment is passed to a "backwards" list', () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if a nested array is passed to a "forwards" list', () => { <ide> function Foo({items}) { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('shows content independently by default', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('shows content independently in legacy mode regardless of option', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays all "together"', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays all "together" even when nested as siblings', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays all "together" in nested SuspenseLists', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays all "together" in nested SuspenseLists where the inner is default', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays all "together" during an update', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('avoided boundaries can be coordinate with SuspenseList', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('boundaries without fallbacks can be coordinate with SuspenseList', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays each items in "forwards" order', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays each items in "backwards" order', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays added row at the top "together" and the bottom in "forwards" order', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('displays added row at the top "together" and the bottom in "backwards" order', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('switches to rendering fallbacks if the tail takes long CPU time', async () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('only shows one loading state at a time for "collapsed" tail insertions', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if an unsupported tail option is used', () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('warns if a tail option is used with "together"', () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ]); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('renders one "collapsed" fallback even if CPU time elapsed', async () => { <ide> function Foo() { <ide> return ( <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('adding to the middle does not collapse insertions (forwards)', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('adding to the middle does not collapse insertions (backwards)', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('adding to the middle of committed tail does not collapse insertions', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('only shows no initial loading state "hidden" tail insertions', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('eventually resolves a nested forwards suspense list', async () => { <ide> const B = createAsyncText('B'); <ide> <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('eventually resolves a nested forwards suspense list with a hidden tail', async () => { <ide> const B = createAsyncText('B'); <ide> <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('eventually resolves two nested forwards suspense lists with a hidden tail', async () => { <ide> const B = createAsyncText('B'); <ide> <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('can do unrelated adjacent updates', async () => { <ide> let updateAdjacent; <ide> function Adjacent() { <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('is able to re-suspend the last rows during an update with hidden', async () => { <ide> const AsyncB = createAsyncText('B'); <ide> <ide> describe('ReactSuspenseList', () => { <ide> expect(previousInst).toBe(setAsyncB); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('is able to re-suspend the last rows during an update with hidden', async () => { <ide> const AsyncB = createAsyncText('B'); <ide> <ide> describe('ReactSuspenseList', () => { <ide> expect(previousInst).toBe(setAsyncB); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('is able to interrupt a partially rendered tree and continue later', async () => { <ide> const AsyncA = createAsyncText('A'); <ide> <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('can resume class components when revealed together', async () => { <ide> const A = createAsyncText('A'); <ide> const B = createAsyncText('B'); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('should be able to progressively show CPU expensive rows with two pass rendering', async () => { <ide> function TwoPass({text}) { <ide> const [pass, setPass] = React.useState(0); <ide> describe('ReactSuspenseList', () => { <ide> ); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('should be able to progressively show rows with two pass rendering and visible', async () => { <ide> function TwoPass({text}) { <ide> const [pass, setPass] = React.useState(0); <ide> describe('ReactSuspenseList', () => { <ide> }); <ide> <ide> // @gate enableProfilerTimer <add> // @gate enableSuspenseList <ide> it('counts the actual duration when profiling a SuspenseList', async () => { <ide> // Order of parameters: id, phase, actualDuration, treeBaseDuration <ide> const onRender = jest.fn(); <ide><path>packages/react-server-dom-relay/src/__tests__/ReactFlightDOMRelay-test.internal.js <ide> let ReactDOM; <ide> let JSResourceReference; <ide> let ReactDOMFlightRelayServer; <ide> let ReactDOMFlightRelayClient; <add>let SuspenseList; <ide> <ide> describe('ReactFlightDOMRelay', () => { <ide> beforeEach(() => { <ide> describe('ReactFlightDOMRelay', () => { <ide> ReactDOMFlightRelayServer = require('react-server-dom-relay/server'); <ide> ReactDOMFlightRelayClient = require('react-server-dom-relay'); <ide> JSResourceReference = require('JSResourceReference'); <add> if (gate(flags => flags.enableSuspenseList)) { <add> SuspenseList = React.SuspenseList; <add> } <ide> }); <ide> <ide> function readThrough(data) { <ide> describe('ReactFlightDOMRelay', () => { <ide> expect(container.innerHTML).toEqual('<span>Hello, Seb Smith</span>'); <ide> }); <ide> <add> // @gate enableSuspenseList <ide> it('can reasonably handle different element types', () => { <del> const { <del> forwardRef, <del> memo, <del> Fragment, <del> StrictMode, <del> Profiler, <del> Suspense, <del> SuspenseList, <del> } = React; <add> const {forwardRef, memo, Fragment, StrictMode, Profiler, Suspense} = React; <ide> <ide> const Inner = memo( <ide> forwardRef((props, ref) => { <ide><path>packages/react/index.stable.js <ide> export { <ide> PureComponent, <ide> StrictMode, <ide> Suspense, <del> SuspenseList, <ide> cloneElement, <ide> createContext, <ide> createElement, <ide><path>scripts/jest/TestFlags.js <ide> function getTestFlags() { <ide> <ide> // This isn't a flag, just a useful alias for tests. <ide> enableUseSyncExternalStoreShim: !__VARIANT__, <add> enableSuspenseList: releaseChannel === 'experimental' || www, <ide> <ide> // If there's a naming conflict between scheduler and React feature flags, the <ide> // React ones take precedence.
11
Javascript
Javascript
replace loader with use for the etp
8f9b4721eb252250635a049f4c8969f2726b4a22
<ide><path>examples/code-splitted-css-bundle/webpack.config.js <ide> module.exports = { <ide> loaders: [ <ide> { <ide> test: /\.css$/, <del> loader: ExtractTextPlugin.extract({ <add> use: ExtractTextPlugin.extract({ <ide> fallback: "style-loader", <ide> use: "css-loader" <ide> }) <ide><path>examples/css-bundle/webpack.config.js <ide> module.exports = { <ide> loaders: [ <ide> { <ide> test: /\.css$/, <del> loader: ExtractTextPlugin.extract({ <add> use: ExtractTextPlugin.extract({ <ide> use: "css-loader" <ide> }) <ide> }, <ide><path>examples/multiple-entry-points-commons-chunk-css-bundle/webpack.config.js <ide> module.exports = { <ide> loaders: [ <ide> { <ide> test: /\.css$/, <del> loader: ExtractTextPlugin.extract({ <add> use: ExtractTextPlugin.extract({ <ide> fallback: "style-loader", <ide> use: "css-loader" <ide> }) <ide><path>test/HotTestCases.test.js <ide> describe("HotTestCases", function() { <ide> enforce: "pre" <ide> }, { <ide> test: /\.css$/, <del> loader: ExtractTextPlugin.extract({ <add> use: ExtractTextPlugin.extract({ <ide> fallback: "style-loader", <ide> loader: "css-loader" <ide> }) <ide><path>test/statsCases/separate-css-bundle/webpack.config.js <ide> var moduleConfig = { <ide> loaders: [ <ide> { <ide> test: /\.css$/, <del> loader: ExtractTextPlugin.extract({ <add> use: ExtractTextPlugin.extract({ <ide> fallback: "style-loader", <ide> loader: "css-loader" <ide> })
5
Text
Text
add new css documentation
4e71121f3c329cd2f3340acb058fd83dcbb050bb
<ide><path>docs/basic-features/built-in-css-support.md <ide> --- <del>description: Next.js includes styled-jsx by default for isolated and scoped CSS support, but you can also use any other CSS-in-JS solution!. Learn more here. <add>description: Next.js supports including CSS files as Global CSS or CSS Modules, using `styled-jsx` for CSS-in-JS, or any other CSS-in-JS solution! Learn more here. <ide> --- <ide> <del># Built-in CSS Support <add># Built-In CSS Support <add> <add>Next.js allows you to import CSS files from a JavaScript file. <add>This is possible because Next.js extends the concept of [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) beyond JavaScript. <add> <add>## Adding a Global Stylesheet <add> <add>To add a stylesheet to your application, import the CSS file within `pages/_app.js`. <add> <add>For example, consider the following stylesheet named `styles.css`: <add> <add>```css <add>body { <add> font-family: 'SF Pro Text', 'SF Pro Icons', system-ui; <add> padding: 20px 20px 60px; <add> max-width: 680px; <add> margin: 0 auto; <add>} <add>``` <add> <add>Create a [`pages/_app.js` file](https://nextjs.org/docs/advanced-features/custom-app) if not already present. <add>Then, [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) the `styles.css` file. <add> <add>```jsx <add>import '../styles.css' <add> <add>// This default export is required in a new `pages/_app.js` file. <add>export default function MyApp({ Component, pageProps }) { <add> return <Component {...pageProps} /> <add>} <add>``` <add> <add>These styles (`styles.css`) will apply to all pages and components in your application. <add>Due to the global nature of stylesheets, and to avoid conflicts, you may **only import them inside [`pages/_app.js`](https://nextjs.org/docs/advanced-features/custom-app)**. <add> <add>In development, expressing stylesheets this way allows your styles to be hot reloaded as you edit them—meaning you can keep application state. <add> <add>In production, all CSS files will be automatically concatenated into a single minified `.css` file. <add> <add>## Adding Component-Level CSS <add> <add>Next.js supports [CSS Modules](https://github.com/css-modules/css-modules) using the `[name].module.css` file naming convention. <add> <add>CSS Modules locally scope CSS by automatically creating a unique class name. <add>This allows you to use the same CSS class name in different files without worrying about collisions. <add> <add>This behavior makes CSS Modules the ideal way to include component-level CSS. <add>CSS Module files **can be imported anywhere in your application**. <add> <add>For example, consider a reusable `Button` component in the `components/` folder: <add> <add>First, create `components/Button.module.css` with the following content: <add> <add>```css <add>/* <add>You do not need to worry about .error {} colliding with any other `.css` or <add>`.module.css` files! <add>*/ <add>.error { <add> color: white; <add> background-color: red; <add>} <add>``` <add> <add>Then, create `components/Button.js`, importing and using the above CSS file: <add> <add>```jsx <add>import styles from './Button.module.css' <add> <add>export function Button() { <add> return ( <add> <button <add> type="button" <add> // Note how the "error" class is accessed as a property on the imported <add> // `styles` object. <add> className={styles.error} <add> > <add> Destroy <add> </button> <add> ) <add>} <add>``` <add> <add>CSS Modules are an _optional feature_ and are **only enabled for files with the `.module.css` extension**. <add>Regular `<link>` stylesheets and global CSS files are still supported. <add> <add>In production, all CSS Module files will be automatically concatenated into **many minified and code-split** `.css` files. <add>These `.css` files represent hot execution paths in your application, ensuring the minimal amount of CSS is loaded for your application to paint. <add> <add>## CSS-in-JS <ide> <ide> <details> <ide> <summary><b>Examples</b></summary> <ide> <ul> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/basic-css">Basic CSS</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/basic-css">Styled JSX</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-styled-components">Styled Components</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-styletron">Styletron</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-glamor">Glamor</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-cxs">Cxs</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-aphrodite">Aphrodite</a></li> <add> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-fela">Fela</a></li> <ide> </ul> <ide> </details> <ide> <del>We bundle [styled-jsx](https://github.com/zeit/styled-jsx) to provide support for isolated scoped CSS. The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71). <add>It's possible to use any existing CSS-in-JS solution. <add>The simplest one is inline styles: <add> <add>```jsx <add>function HiThere() { <add> return <p style={{ color: 'red' }}>hi there</p> <add>} <add> <add>export default HiThere <add>``` <add> <add>We bundle [styled-jsx](https://github.com/zeit/styled-jsx) to provide support for isolated scoped CSS. <add>The aim is to support "shadow CSS" similar to Web Components, which unfortunately [do not support server-rendering and are JS-only](https://github.com/w3c/webcomponents/issues/71). <add> <add>See the above examples for other popular CSS-in-JS solutions (like Styled Components). <ide> <ide> A component using `styled-jsx` looks like this: <ide> <ide> export default HelloWorld <ide> <ide> Please see the [styled-jsx documentation](https://github.com/zeit/styled-jsx) for more examples. <ide> <del>## CSS-in-JS <del> <del><details> <del> <summary><b>Examples</b></summary> <del> <ul> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-styled-components">Styled components</a></li> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-styletron">Styletron</a></li> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-glamor">Glamor</a></li> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-cxs">Cxs</a></li> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-aphrodite">Aphrodite</a></li> <del> <li><a href="https://github.com/zeit/next.js/tree/canary/examples/with-fela">Fela</a></li> <del> </ul> <del></details> <del> <del>It's possible to use any existing CSS-in-JS solution. The simplest one is inline styles: <del> <del>```jsx <del>function HiThere() { <del> return <p style={{ color: 'red' }}>hi there</p> <del>} <del> <del>export default HiThere <del>``` <del> <del>## CSS Plugins <add>## Sass, Less, and Stylus Support <ide> <del>To support importing `.css`, `.scss`, `.less` or `.styl` files you can use the following modules, which configure sensible defaults for server rendered applications: <add>To support importing `.scss`, `.less` or `.styl` files you can use the following plugins: <ide> <del>- [@zeit/next-css](https://github.com/zeit/next-plugins/tree/master/packages/next-css) <ide> - [@zeit/next-sass](https://github.com/zeit/next-plugins/tree/master/packages/next-sass) <ide> - [@zeit/next-less](https://github.com/zeit/next-plugins/tree/master/packages/next-less) <ide> - [@zeit/next-stylus](https://github.com/zeit/next-plugins/tree/master/packages/next-stylus)
1
Text
Text
clarify optional catch all vs catch all routes
3bfc25db9fc6fb21875510d5d9ada9896b87a80c
<ide><path>docs/api-routes/dynamic-api-routes.md <ide> Catch all routes can be made optional by including the parameter in double brack <ide> <ide> For example, `pages/api/post/[[...slug]].js` will match `/api/post`, `/api/post/a`, `/api/post/a/b`, and so on. <ide> <add>The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (`/api/post` in the example above). <add> <ide> The `query` objects are as follows: <ide> <ide> ```json <ide><path>docs/routing/dynamic-routes.md <ide> Catch all routes can be made optional by including the parameter in double brack <ide> <ide> For example, `pages/post/[[...slug]].js` will match `/post`, `/post/a`, `/post/a/b`, and so on. <ide> <add>The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (`/post` in the example above). <add> <ide> The `query` objects are as follows: <ide> <ide> ```json
2
PHP
PHP
fix a typo
8b1026fb4577e2615bce39afc158d2a31da3c144
<ide><path>src/ORM/LazyEagerLoader.php <ide> class LazyEagerLoader <ide> * <ide> * @param \Cake\Datasource\EntityInterface|array $entities a single entity or list of entities <ide> * @param array $contain A `contain()` compatible array. <del> * @see \Cake\ORM\Query\contain() <add> * @see \Cake\ORM\Query::contain() <ide> * @param \Cake\ORM\Table $source The table to use for fetching the top level entities <ide> * @return \Cake\Datasource\EntityInterface|array <ide> */
1
Python
Python
remove another useless check
2c96373a411b1a9754ccad16ab5d23b80ed35d25
<ide><path>tests/keras/layers/test_recurrent_convolutional.py <ide> def test_recurrent_convolutional(): <ide> assert output.shape == tuple(output_shape) <ide> <ide> # No need to check statefulness for both <del> if dim_ordering == 'th': <add> if dim_ordering == 'th' or return_sequences: <ide> continue <ide> <ide> # Tests for statefulness
1
Mixed
Javascript
add support for option groups
f768954f38a7077abfd291eaafc0500d2d1e8007
<ide><path>CHANGELOG.md <ide> - Issue #464: [ng:options] incorrectly re-grew options on datasource change <ide> - Issue #448: [ng:options] should support iterating over objects <ide> - Issue #463: [ng:options] should support firing ng:change event <add>- Issue #450: [ng:options] should support group by (select option groups) <ide> <ide> ### Breaking changes <ide> - no longer support MMMMM in filter.date as we need to follow UNICODE LOCALE DATA formats. <ide><path>src/widgets.js <ide> angularWidget('button', inputWidgetSelector); <ide> * @element select <ide> * @param {comprehension_expression} comprehension in following form <ide> * <del> * * _select_ `for` _value_ `in` _array_ <add> * * _label_ `for` _value_ `in` _array_ <ide> * * _select_ `as` _label_ `for` _value_ `in` _array_ <del> * * _select_ `for` `(`_key_`,` _value_`)` `in` _object_ <add> * * _select_ `as` _label_ `group by` _group_ `for` _value_ `in` _array_ <add> * * _select_ `group by` _group_ `for` _value_ `in` _array_ <add> * * _label_ `for` `(`_key_`,` _value_`)` `in` _object_ <ide> * * _select_ `as` _label_ `for` `(`_key_`,` _value_`)` `in` _object_ <add> * * _select_ `as` _label_ `group by` _group_ `for` `(`_key_`,` _value_`)` `in` _object_ <add> * * _select_ `group by` _group_ `for` `(`_key_`,` _value_`)` `in` _object_ <ide> * <ide> * Where: <ide> * <ide> * * _array_ / _object_: an expression which evaluates to an array / object to iterate over. <del> * * _value_: local variable which will reffer to the item in the _array_ or _object_ during <del> * iteration <del> * * _key_: local variable which will refer to the key in the _object_ during the iteration <del> * * _select_: The result of this expression will be assigned to the scope. <del> * The _select_ can be ommited, in which case the _item_ itself will be assigned. <add> * * _value_: local variable which will refer to each item in the _array_ or each value of <add> * _object_ during itteration. <add> * * _key_: local variable which will refer to the key in the _object_ during the iteration. <ide> * * _label_: The result of this expression will be the `option` label. The <del> * `expression` most likely refers to the _item_ variable. (optional) <add> * `expression` will most likely refer to the _value_ variable. <add> * * _select_: The result of this expression will be bound to the scope. If not specified, <add> * _select_ expression will default to _value_. <add> * * _group_: The result of this expression will be used to group options using the `optgroup` <add> * DOM element. <ide> * <ide> * @example <ide> <doc:example> <ide> angularWidget('button', inputWidgetSelector); <ide> </doc:scenario> <ide> </doc:example> <ide> */ <del>// 000012222111111111133330000000004555555555555555554666666777777777777777776666666888888888888888888888864000000009999 <del>var NG_OPTIONS_REGEXP = /^\s*((.*)\s+as\s+)?(.*)\s+for\s+(([\$\w][\$\w\d]*)|(\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; <add>// 00001111100000000000222200000000000000000000003333000000000000044444444444444444000000000555555555555555550000000666666666666666660000000000000007777 <add>var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/; <ide> angularWidget('select', function(element){ <ide> this.descend(true); <ide> this.directives(true); <ide> angularWidget('select', function(element){ <ide> "Expected ng:options in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_' but got '" + <ide> expression + "'."); <ide> } <del> var displayFn = expressionCompile(match[3]).fnSelf; <del> var valueName = match[5] || match[8]; <del> var keyName = match[7]; <del> var valueFn = expressionCompile(match[2] || valueName).fnSelf; <del> var valuesFn = expressionCompile(match[9]).fnSelf; <add> var displayFn = expressionCompile(match[2] || match[1]).fnSelf; <add> var valueName = match[4] || match[6]; <add> var keyName = match[5]; <add> var groupByFn = expressionCompile(match[3] || '').fnSelf; <add> var valueFn = expressionCompile(match[2] ? match[1] : valueName).fnSelf; <add> var valuesFn = expressionCompile(match[7]).fnSelf; <ide> // we can't just jqLite('<option>') since jqLite is not smart enough <ide> // to create it in <select> and IE barfs otherwise. <del> var option = jqLite(document.createElement('option')); <del> return function(select){ <add> var optionTemplate = jqLite(document.createElement('option')); <add> var optGroupTemplate = jqLite(document.createElement('optgroup')); <add> var nullOption = false; // if false then user will not be able to select it <add> return function(selectElement){ <ide> var scope = this; <del> var optionElements = []; <del> var optionTexts = []; <del> var lastSelectValue = isMultiselect ? {} : false; <del> var nullOption = option.clone().val(''); <del> var missingOption = option.clone().val('?'); <add> <add> // This is an array of array of existing option groups in DOM. We try to reuse these if possible <add> // optionGroupsCache[0] is the options with no option group <add> // optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element <add> var optionGroupsCache = [[{element: selectElement, label:''}]]; <ide> var model = modelAccessor(scope, element); <ide> <ide> // find existing special options <del> forEach(select.children(), function(option){ <del> if (option.value == '') nullOption = false; <add> forEach(selectElement.children(), function(option){ <add> if (option.value == '') <add> // User is allowed to select the null. <add> nullOption = {label:jqLite(option).text(), id:''}; <ide> }); <add> selectElement.html(''); // clear contents <ide> <del> select.bind('change', function(){ <add> selectElement.bind('change', function(){ <add> var optionGroup; <ide> var collection = valuesFn(scope) || []; <del> var value = select.val(); <del> var index, length; <add> var key = selectElement.val(); <add> var value; <add> var optionElement; <add> var index, groupIndex, length, groupLength; <ide> var tempScope = scope.$new(); <ide> try { <ide> if (isMultiselect) { <ide> value = []; <del> for (index = 0, length = optionElements.length; index < length; index++) { <del> if (optionElements[index][0].selected) { <del> tempScope[valueName] = collection[index]; <del> value.push(valueFn(tempScope)); <add> for (groupIndex = 0, groupLength = optionGroupsCache.length; <add> groupIndex < groupLength; <add> groupIndex++) { <add> // list of options for that group. (first item has the parent) <add> optionGroup = optionGroupsCache[groupIndex]; <add> <add> for(index = 1, length = optionGroup.length; index < length; index++) { <add> if ((optionElement = optionGroup[index].element)[0].selected) { <add> if (keyName) tempScope[keyName] = key; <add> tempScope[valueName] = collection[optionElement.val()]; <add> value.push(valueFn(tempScope)); <add> } <ide> } <ide> } <ide> } else { <del> if (value == '?') { <add> if (key == '?') { <ide> value = undefined; <del> } else if (value == ''){ <add> } else if (key == ''){ <ide> value = null; <ide> } else { <del> tempScope[valueName] = collection[value]; <add> tempScope[valueName] = collection[key]; <add> if (keyName) tempScope[keyName] = key; <ide> value = valueFn(tempScope); <ide> } <ide> } <del> if (!isUndefined(value) && model.get() !== value) { <add> if (isDefined(value) && model.get() !== value) { <ide> onChange(scope); <ide> model.set(value); <ide> } <ide> angularWidget('select', function(element){ <ide> <ide> scope.$onEval(function(){ <ide> var scope = this; <add> <add> // Temporary location for the option groups before we render them <add> var optionGroups = { <add> '':[] <add> }; <add> var optionGroupNames = ['']; <add> var optionGroupName; <add> var optionGroup; <add> var option; <add> var existingParent, existingOptions, existingOption; <ide> var values = valuesFn(scope) || []; <ide> var keys = values; <ide> var key; <del> var value; <del> var length; <add> var groupLength, length; <ide> var fragment; <del> var index; <del> var optionText; <add> var groupIndex, index; <ide> var optionElement; <ide> var optionScope = scope.$new(); <ide> var modelValue = model.get(); <del> var currentItem; <del> var selectValue = ''; <add> var selected; <add> var selectedSet = false; // nothing is selected yet <ide> var isMulti = isMultiselect; <add> var lastElement; <add> var element; <ide> <ide> try { <ide> if (isMulti) { <del> selectValue = new HashMap(); <add> selectedSet = new HashMap(); <ide> if (modelValue && isNumber(length = modelValue.length)) { <ide> for (index = 0; index < length; index++) { <del> selectValue.put(modelValue[index], true); <add> selectedSet.put(modelValue[index], true); <ide> } <ide> } <add> } else if (modelValue === null || nullOption) { <add> // if we are not multiselect, and we are null then we have to add the nullOption <add> optionGroups[''].push(extend({selected:modelValue === null, id:'', label:''}, nullOption)); <add> selectedSet = true; <ide> } <ide> <del> // If we have a keyName then we are itterating over on object. We <add> // If we have a keyName then we are iterating over on object. We <ide> // grab the keys and sort them. <ide> if(keyName) { <ide> keys = []; <ide> angularWidget('select', function(element){ <ide> keys.sort(); <ide> } <ide> <add> // We now build up the list of options we need (we merge later) <ide> for (index = 0; length = keys.length, index < length; index++) { <ide> optionScope[valueName] = values[keyName ? optionScope[keyName]=keys[index]:index]; <del> currentItem = valueFn(optionScope); <del> optionText = displayFn(optionScope); <del> if (optionTexts.length > index) { <del> // reuse <del> optionElement = optionElements[index]; <del> if (optionText != optionTexts[index]) { <del> (optionElement).text(optionTexts[index] = optionText); <del> } <del> } else { <del> // grow <del> if (!fragment) { <del> fragment = document.createDocumentFragment(); <del> } <del> optionTexts.push(optionText); <del> optionElements.push(optionElement = option.clone()); <del> optionElement.attr('value', index).text(optionText); <del> fragment.appendChild(optionElement[0]); <add> optionGroupName = groupByFn(optionScope) || ''; <add> if (!(optionGroup = optionGroups[optionGroupName])) { <add> optionGroup = optionGroups[optionGroupName] = []; <add> optionGroupNames.push(optionGroupName); <ide> } <ide> if (isMulti) { <del> if (lastSelectValue[index] != (value = selectValue.remove(currentItem))) { <del> optionElement[0].selected = !!(lastSelectValue[index] = value); <del> } <add> selected = !!selectedSet.remove(valueFn(optionScope)); <ide> } else { <del> if (modelValue == currentItem) { <del> selectValue = index; <del> } <add> selected = modelValue === valueFn(optionScope); <add> selectedSet = selectedSet || selected; // see if at least one item is selected <ide> } <add> optionGroup.push({ <add> id: keyName ? keys[index] : index, // either the index into array or key from object <add> label: displayFn(optionScope) || '', // what will be seen by the user <add> selected: selected // determine if we should be selected <add> }); <ide> } <del> if (fragment) { <del> select.append(jqLite(fragment)); <del> } <del> // shrink children <del> while(optionElements.length > index) { <del> optionElements.pop().remove(); <del> optionTexts.pop(); <del> delete lastSelectValue[optionElements.length]; <add> optionGroupNames.sort(); <add> if (!isMulti && !selectedSet) { <add> // nothing was selected, we have to insert the undefined item <add> optionGroups[''].unshift({id:'?', label:'', selected:true}); <ide> } <ide> <del> if (!isMulti) { <del> if (selectValue === '' && modelValue) { <del> // We could not find a match <del> selectValue = '?'; <del> } <add> // Now we need to update the list of DOM nodes to match the optionGroups we computed above <add> for (groupIndex = 0, groupLength = optionGroupNames.length; <add> groupIndex < groupLength; <add> groupIndex++) { <add> // current option group name or '' if no group <add> optionGroupName = optionGroupNames[groupIndex]; <add> <add> // list of options for that group. (first item has the parent) <add> optionGroup = optionGroups[optionGroupName]; <add> <add> if (optionGroupsCache.length <= groupIndex) { <add> // we need to grow the optionGroups <add> optionGroupsCache.push( <add> existingOptions = [ <add> existingParent = { <add> element: optGroupTemplate.clone().attr('label', optionGroupName), <add> label: optionGroup.label <add> } <add> ] <add> ); <add> selectElement.append(existingParent.element); <add> } else { <add> existingOptions = optionGroupsCache[groupIndex]; <add> existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element <ide> <del> // update the selected item <del> if (lastSelectValue !== selectValue) { <del> if (nullOption) { <del> if (lastSelectValue == '') nullOption.remove(); <del> if (selectValue === '') select.prepend(nullOption); <add> // update the OPTGROUP label if not the same. <add> if (existingParent.label != optionGroupName) { <add> existingParent.element.attr('label', existingParent.label = optionGroupName); <ide> } <add> } <ide> <del> if (missingOption) { <del> if (lastSelectValue == '?') missingOption.remove(); <del> if (selectValue === '?') select.prepend(missingOption); <add> lastElement = null; // start at the begining <add> for(index = 0, length = optionGroup.length; index < length; index++) { <add> option = optionGroup[index]; <add> if (existingOption = existingOptions[index+1]) { <add> // reuse elements <add> lastElement = existingOption.element; <add> if (existingOption.label !== option.label) { <add> lastElement.text(existingOption.label = option.label); <add> } <add> if (existingOption.id !== option.id) { <add> lastElement.val(existingOption.id = option.id); <add> } <add> if (existingOption.selected !== option.selected) { <add> lastElement.attr('selected', option.selected); <add> } <add> } else { <add> // grow elements <add> // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but <add> // in this version of jQuery on some browser the .text() returns a string <add> // rather then the element. <add> (element = optionTemplate.clone()) <add> .val(option.id) <add> .attr('selected', option.selected) <add> .text(option.label); <add> existingOptions.push(existingOption = { <add> element: element, <add> label: option.label, <add> id: option.id, <add> checked: option.selected <add> }); <add> if (lastElement) { <add> lastElement.after(element); <add> } else { <add> existingParent.element.append(element); <add> } <add> lastElement = element; <ide> } <del> <del> select.val(lastSelectValue = selectValue); <add> } <add> // remove any excessive OPTIONs in a group <add> index++; // increment since the existingOptions[0] is parent element not OPTION <add> while(existingOptions.length > index) { <add> existingOptions.pop().element.remove(); <ide> } <ide> } <del> <add> // remove any excessive OPTGROUPs from select <add> while(optionGroupsCache.length > groupIndex) { <add> optionGroupsCache.pop()[0].element.remove(); <add> } <ide> } finally { <ide> optionScope = null; // TODO(misko): needs to be $destroy() <ide> } <ide><path>test/widgetsSpec.js <ide> describe("widget", function(){ <ide> function createSelect(attrs, blank, unknown){ <ide> var html = '<select'; <ide> forEach(attrs, function(value, key){ <del> if (typeof value == 'boolean') { <add> if (isBoolean(value)) { <ide> if (value) html += ' ' + key; <ide> } else { <ide> html+= ' ' + key + '="' + value + '"'; <ide> describe("widget", function(){ <ide> scope.$eval(); <ide> var options = select.find('option'); <ide> expect(options.length).toEqual(3); <del> expect(sortedHtml(options[0])).toEqual('<option value="0">blue</option>'); <del> expect(sortedHtml(options[1])).toEqual('<option value="1">green</option>'); <del> expect(sortedHtml(options[2])).toEqual('<option value="2">red</option>'); <add> expect(sortedHtml(options[0])).toEqual('<option value="blue">blue</option>'); <add> expect(sortedHtml(options[1])).toEqual('<option value="green">green</option>'); <add> expect(sortedHtml(options[2])).toEqual('<option value="red">red</option>'); <ide> expect(options[2].selected).toEqual(true); <ide> <ide> scope.object.azur = '8888FF'; <ide> describe("widget", function(){ <ide> scope.values = []; <ide> scope.$eval(); <ide> expect(select.find('option').length).toEqual(1); // because we add special empty option <del> expect(sortedHtml(select.find('option')[0])).toEqual('<option></option>'); <add> expect(sortedHtml(select.find('option')[0])).toEqual('<option value="?"></option>'); <ide> <ide> scope.values.push({name:'A'}); <ide> scope.selected = scope.values[0]; <ide> describe("widget", function(){ <ide> expect(select.val()).toEqual('1'); <ide> }); <ide> <add> it('should bind to scope value and group', function(){ <add> createSelect({ <add> name:'selected', <add> 'ng:options':'item.name group by item.group for item in values'}); <add> scope.values = [{name:'A'}, <add> {name:'B', group:'first'}, <add> {name:'C', group:'second'}, <add> {name:'D', group:'first'}, <add> {name:'E', group:'second'}]; <add> scope.selected = scope.values[3]; <add> scope.$eval(); <add> expect(select.val()).toEqual('3'); <add> <add> var first = jqLite(select.find('optgroup')[0]); <add> var b = jqLite(first.find('option')[0]); <add> var d = jqLite(first.find('option')[1]); <add> expect(first.attr('label')).toEqual('first'); <add> expect(b.text()).toEqual('B'); <add> expect(d.text()).toEqual('D'); <add> <add> var second = jqLite(select.find('optgroup')[1]); <add> var c = jqLite(second.find('option')[0]); <add> var e = jqLite(second.find('option')[1]); <add> expect(second.attr('label')).toEqual('second'); <add> expect(c.text()).toEqual('C'); <add> expect(e.text()).toEqual('E'); <add> <add> scope.selected = scope.values[0]; <add> scope.$eval(); <add> expect(select.val()).toEqual('0'); <add> }); <add> <ide> it('should bind to scope value through experession', function(){ <ide> createSelect({name:'selected', 'ng:options':'item.id as item.name for item in values'}); <ide> scope.values = [{id:10, name:'A'}, {id:20, name:'B'}]; <ide> describe("widget", function(){ <ide> scope.object = {'red':'FF0000', 'green':'00FF00', 'blue':'0000FF'}; <ide> scope.selected = 'green'; <ide> scope.$eval(); <del> expect(select.val()).toEqual('1'); <add> expect(select.val()).toEqual('green'); <ide> <ide> scope.selected = 'blue'; <ide> scope.$eval(); <del> expect(select.val()).toEqual('0'); <add> expect(select.val()).toEqual('blue'); <ide> }); <ide> <ide> it('should bind to object value', function(){ <ide> describe("widget", function(){ <ide> scope.object = {'red':'FF0000', 'green':'00FF00', 'blue':'0000FF'}; <ide> scope.selected = '00FF00'; <ide> scope.$eval(); <del> expect(select.val()).toEqual('1'); <add> expect(select.val()).toEqual('green'); <ide> <ide> scope.selected = '0000FF'; <ide> scope.$eval(); <del> expect(select.val()).toEqual('0'); <add> expect(select.val()).toEqual('blue'); <ide> }); <ide> <ide> it('should insert a blank option if bound to null', function(){
3
Python
Python
add __all__ to ec2 module
9548848cba3a3a9b9ffe6cd5ec4ca1736fa87c06
<ide><path>libcloud/compute/drivers/ec2.py <ide> from libcloud.compute.base import KeyPair <ide> from libcloud.compute.types import NodeState, KeyPairDoesNotExistError <ide> <add>__all__ = [ <add> 'API_VERSION', <add> 'NAMESPACE', <add> 'INSTANCE_TYPES', <add> <add> 'EC2NodeDriver', <add> 'BaseEC2NodeDriver', <add> <add> 'NimbusNodeDriver', <add> 'EucNodeDriver', <add> <add> 'EC2NodeLocation', <add> 'EC2ReservedNode', <add> 'EC2Network', <add> 'EC2NetworkSubnet', <add> 'EC2NetworkInterface', <add> 'ExEC2AvailabilityZone', <add> <add> 'IdempotentParamError' <add>] <add> <ide> API_VERSION = '2013-10-15' <ide> NAMESPACE = 'http://ec2.amazonaws.com/doc/%s/' % (API_VERSION) <ide>
1
PHP
PHP
remove spaces around declare statement
3eeaa21ccd9a8f182829641ee1562817ca600bd4
<ide><path>src/Controller/Component.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Component/AuthComponent.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Component/FlashComponent.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Component/PaginatorComponent.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Component/RequestHandlerComponent.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Component/SecurityComponent.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/ComponentRegistry.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Controller.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/ErrorController.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Exception/AuthSecurityException.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Exception/MissingActionException.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Exception/MissingComponentException.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>src/Controller/Exception/SecurityException.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/PHPStan/AssociationTableMixinClassReflectionExtension.php <del><?php declare(strict_types = 1); <add><?php declare(strict_types=1); <ide> <ide> namespace Cake\PHPStan; <ide> <ide><path>tests/TestCase/Controller/Component/AuthComponentTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/Component/FlashComponentTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/Component/RequestHandlerComponentTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/Component/SecurityComponentTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/ComponentRegistryTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/ComponentTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) Tests <https://book.cakephp.org/view/1196/Testing> <ide> * Copyright 2005-2011, Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/ControllerTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/Exception/AuthSecurityExceptionTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <ide><path>tests/TestCase/Controller/Exception/SecurityExceptionTest.php <ide> <?php <del>declare(strict_types = 1); <add>declare(strict_types=1); <ide> /** <ide> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <ide> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
24
Python
Python
add theano floatx dtype
4e78c9e7588fb10ed26349cd036eb3ea2f6bc5f0
<ide><path>keras/layers/recurrent.py <ide> def __init__(self, input_dim, output_dim=128, <ide> <ide> # P_h used to project X onto different dimension, using sparse random projections <ide> if self.input_dim == self.output_dim: <del> self.Pmat = theano.shared(np.identity(self.output_dim), name=None) <add> self.Pmat = theano.shared(np.identity(self.output_dim, dtype=theano.config.floatX), name=None) <ide> else: <del> P = np.random.binomial(1, 0.5, size=(self.input_dim, self.output_dim)) * 2 - 1 <add> P = np.random.binomial(1, 0.5, size=(self.input_dim, self.output_dim)).astype(theano.config.floatX) * 2 - 1 <ide> P = 1 / np.sqrt(self.input_dim) * P <ide> self.Pmat = theano.shared(P, name=None) <ide> <ide> def __init__(self, input_dim, output_dim=128, <ide> <ide> # P_h used to project X onto different dimension, using sparse random projections <ide> if self.input_dim == self.output_dim: <del> self.Pmat = theano.shared(np.identity(self.output_dim), name=None) <add> self.Pmat = theano.shared(np.identity(self.output_dim, dtype=theano.config.floatX), name=None) <ide> else: <del> P = np.random.binomial(1, 0.5, size=(self.input_dim, self.output_dim)) * 2 - 1 <add> P = np.random.binomial(1, 0.5, size=(self.input_dim, self.output_dim)).astype(theano.config.floatX) * 2 - 1 <ide> P = 1 / np.sqrt(self.input_dim) * P <ide> self.Pmat = theano.shared(P, name=None) <ide>
1
Javascript
Javascript
pass additional arguments to the callback
3a4b6b83efdb8051e5c4803c0892c19ceb2cba50
<ide><path>src/ng/timeout.js <ide> function $TimeoutProvider() { <ide> * @param {number=} [delay=0] Delay in milliseconds. <ide> * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise <ide> * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block. <add> * @param {...*=} Pass additional parameters to the executed function. <ide> * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this <ide> * promise will be resolved with is the return value of the `fn` function. <ide> * <ide> function $TimeoutProvider() { <ide> fn = noop; <ide> } <ide> <del> var skipApply = (isDefined(invokeApply) && !invokeApply), <add> var args = sliceArgs(arguments, 3), <add> skipApply = (isDefined(invokeApply) && !invokeApply), <ide> deferred = (skipApply ? $$q : $q).defer(), <ide> promise = deferred.promise, <ide> timeoutId; <ide> <ide> timeoutId = $browser.defer(function() { <ide> try { <del> deferred.resolve(fn()); <add> deferred.resolve(fn.apply(null, args)); <ide> } catch (e) { <ide> deferred.reject(e); <ide> $exceptionHandler(e); <ide><path>test/ng/timeoutSpec.js <ide> describe('$timeout', function() { <ide> it('should call $apply after each callback is executed', inject(function($timeout, $rootScope) { <ide> var applySpy = spyOn($rootScope, '$apply').andCallThrough(); <ide> <del> $timeout(function() {}); <add> $timeout(noop); <ide> expect(applySpy).not.toHaveBeenCalled(); <ide> <ide> $timeout.flush(); <ide> expect(applySpy).toHaveBeenCalledOnce(); <ide> <ide> applySpy.reset(); <ide> <del> $timeout(function() {}); <del> $timeout(function() {}); <add> $timeout(noop); <add> $timeout(noop); <ide> $timeout.flush(); <ide> expect(applySpy.callCount).toBe(2); <ide> })); <ide> describe('$timeout', function() { <ide> it('should NOT call $apply if skipApply is set to true', inject(function($timeout, $rootScope) { <ide> var applySpy = spyOn($rootScope, '$apply').andCallThrough(); <ide> <del> $timeout(function() {}, 12, false); <add> $timeout(noop, 12, false); <ide> expect(applySpy).not.toHaveBeenCalled(); <ide> <ide> $timeout.flush(); <ide> describe('$timeout', function() { <ide> // $browser.defer.cancel is only called on cancel if the deferred object is still referenced <ide> var cancelSpy = spyOn($browser.defer, 'cancel').andCallThrough(); <ide> <del> var promise1 = $timeout(function() {}, 0, false); <del> var promise2 = $timeout(function() {}, 100, false); <add> var promise1 = $timeout(noop, 0, false); <add> var promise2 = $timeout(noop, 100, false); <ide> expect(cancelSpy).not.toHaveBeenCalled(); <ide> <ide> $timeout.flush(0); <ide> describe('$timeout', function() { <ide> expect(cancelSpy).toHaveBeenCalled(); <ide> })); <ide> <del> <ide> it('should allow the `fn` parameter to be optional', inject(function($timeout, log) { <ide> <ide> $timeout().then(function(value) { log('promise success: ' + value); }, log.fn('promise error')); <ide> describe('$timeout', function() { <ide> expect(log).toEqual(['promise success: undefined']); <ide> })); <ide> <add> it('should pass the timeout arguments in the timeout callback', <add> inject(function($timeout, $browser, log) { <add> var task1 = jasmine.createSpy('Nappa'), <add> task2 = jasmine.createSpy('Vegeta'); <add> <add> $timeout(task1, 9000, true, 'What does', 'the timeout', 'say about', 'its delay level'); <add> expect($browser.deferredFns.length).toBe(1); <add> <add> $timeout(task2, 9001, false, 'It\'s', 'over', 9000); <add> expect($browser.deferredFns.length).toBe(2); <add> <add> $timeout(9000, false, 'What!', 9000).then(function(value) { log('There\'s no way that can be right! ' + value); }, log.fn('It can\'t!')); <add> expect($browser.deferredFns.length).toBe(3); <add> expect(log).toEqual([]); <add> <add> $timeout.flush(0); <add> expect(task1).not.toHaveBeenCalled(); <add> <add> $timeout.flush(9000); <add> expect(task1).toHaveBeenCalledWith('What does', 'the timeout', 'say about', 'its delay level'); <add> <add> $timeout.flush(1); <add> expect(task2).toHaveBeenCalledWith('It\'s', 'over', 9000); <add> <add> $timeout.flush(9000); <add> expect(log).toEqual(['There\'s no way that can be right! undefined']); <add> <add> })); <add> <ide> <ide> describe('exception handling', function() { <ide> <ide> describe('$timeout', function() { <ide> <ide> it('should delegate exception to the $exceptionHandler service', inject( <ide> function($timeout, $exceptionHandler) { <del> $timeout(function() {throw "Test Error";}); <add> $timeout(function() { throw "Test Error"; }); <ide> expect($exceptionHandler.errors).toEqual([]); <ide> <ide> $timeout.flush(); <ide> describe('$timeout', function() { <ide> function($timeout, $rootScope) { <ide> var applySpy = spyOn($rootScope, '$apply').andCallThrough(); <ide> <del> $timeout(function() {throw "Test Error";}); <add> $timeout(function() { throw "Test Error"; }); <ide> expect(applySpy).not.toHaveBeenCalled(); <ide> <ide> $timeout.flush(); <ide> describe('$timeout', function() { <ide> })); <ide> <ide> <add> it('should pass the timeout arguments in the timeout callback even if an exception is thrown', <add> inject(function($timeout, log) { <add> var promise1 = $timeout(function(arg) { throw arg; }, 9000, true, 'Some Arguments'); <add> var promise2 = $timeout(function(arg1, args2) { throw arg1 + ' ' + args2; }, 9001, false, 'Are Meant', 'To Be Thrown'); <add> <add> promise1.then(log.fn('success'), function(reason) { log('error: ' + reason); }); <add> promise2.then(log.fn('success'), function(reason) { log('error: ' + reason); }); <add> <add> $timeout.flush(0); <add> expect(log).toEqual(''); <add> <add> $timeout.flush(9000); <add> expect(log).toEqual('error: Some Arguments'); <add> <add> $timeout.flush(1); <add> expect(log).toEqual('error: Some Arguments; error: Are Meant To Be Thrown'); <add> })); <add> <add> <ide> it('should forget references to relevant deferred even when exception is thrown', <ide> inject(function($timeout, $browser) { <ide> // $browser.defer.cancel is only called on cancel if the deferred object is still referenced <ide> describe('$timeout', function() { <ide> // $browser.defer.cancel is only called on cancel if the deferred object is still referenced <ide> var cancelSpy = spyOn($browser.defer, 'cancel').andCallThrough(); <ide> <del> var promise = $timeout(function() {}, 0, false); <add> var promise = $timeout(noop, 0, false); <ide> <ide> expect(cancelSpy).not.toHaveBeenCalled(); <ide> $timeout.cancel(promise);
2
Go
Go
use activation.listeners instead of files
def09526066001eefe16dbc6475b93bc1a9af0a2
<ide><path>pkg/systemd/listendfd.go <ide> package systemd <ide> <ide> import ( <ide> "errors" <del> "fmt" <ide> "net" <ide> "strconv" <ide> <ide> import ( <ide> // ListenFD returns the specified socket activated files as a slice of <ide> // net.Listeners or all of the activated files if "*" is given. <ide> func ListenFD(addr string) ([]net.Listener, error) { <del> files := activation.Files(false) <del> if files == nil || len(files) == 0 { <add> // socket activation <add> listeners, err := activation.Listeners(false) <add> if err != nil { <add> return nil, err <add> } <add> <add> if listeners == nil || len(listeners) == 0 { <ide> return nil, errors.New("No sockets found") <ide> } <ide> <ide> func ListenFD(addr string) ([]net.Listener, error) { <ide> <ide> fdNum, _ := strconv.Atoi(addr) <ide> fdOffset := fdNum - 3 <del> if (addr != "*") && (len(files) < int(fdOffset)+1) { <add> if (addr != "*") && (len(listeners) < int(fdOffset)+1) { <ide> return nil, errors.New("Too few socket activated files passed in") <ide> } <ide> <del> // socket activation <del> listeners := make([]net.Listener, len(files)) <del> for i, f := range files { <del> var err error <del> listeners[i], err = net.FileListener(f) <del> if err != nil { <del> return nil, fmt.Errorf("Error setting up FileListener for fd %d: %s", f.Fd(), err.Error()) <del> } <del> } <del> <ide> if addr == "*" { <ide> return listeners, nil <ide> }
1
Go
Go
add test testrestartpolicywithliverestore
89f034093a771fc1d3d161d23e018c25ae4e2ee3
<ide><path>integration-cli/docker_cli_daemon_test.go <ide> import ( <ide> "github.com/docker/docker/pkg/stringid" <ide> "github.com/docker/docker/pkg/testutil" <ide> icmd "github.com/docker/docker/pkg/testutil/cmd" <del> "github.com/docker/go-units" <add> units "github.com/docker/go-units" <ide> "github.com/docker/libnetwork/iptables" <ide> "github.com/docker/libtrust" <ide> "github.com/go-check/check" <ide> func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { <ide> <ide> out, err = s.d.Cmd("rm", "top") <ide> c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) <add>} <add> <add>// #29598 <add>func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { <add> testRequires(c, DaemonIsLinux, SameHostDaemon) <add> s.d.StartWithBusybox(c, "--live-restore") <add> <add> out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") <add> c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) <add> id := strings.TrimSpace(out) <ide> <add> type state struct { <add> Running bool <add> StartedAt time.Time <add> } <add> out, err = s.d.Cmd("inspect", "-f", "{{json .State}}", id) <add> c.Assert(err, checker.IsNil, check.Commentf("output: %s", out)) <add> <add> var origState state <add> err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState) <add> c.Assert(err, checker.IsNil) <add> <add> s.d.Restart(c, "--live-restore") <add> <add> pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id) <add> c.Assert(err, check.IsNil) <add> pidint, err := strconv.Atoi(strings.TrimSpace(pid)) <add> c.Assert(err, check.IsNil) <add> c.Assert(pidint, checker.GreaterThan, 0) <add> c.Assert(syscall.Kill(pidint, syscall.SIGKILL), check.IsNil) <add> <add> ticker := time.NewTicker(50 * time.Millisecond) <add> timeout := time.After(10 * time.Second) <add> <add> for range ticker.C { <add> select { <add> case <-timeout: <add> c.Fatal("timeout waiting for container restart") <add> default: <add> } <add> <add> out, err := s.d.Cmd("inspect", "-f", "{{json .State}}", id) <add> c.Assert(err, checker.IsNil, check.Commentf("output: %s", out)) <add> <add> var newState state <add> err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState) <add> c.Assert(err, checker.IsNil) <add> <add> if !newState.Running { <add> continue <add> } <add> if newState.StartedAt.After(origState.StartedAt) { <add> break <add> } <add> } <add> <add> out, err = s.d.Cmd("stop", id) <add> c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) <ide> }
1
Javascript
Javascript
allow 0 as a lowwatermark value
02f017d24f8cd93939bb4bd178b878d15cc5a08c
<ide><path>lib/_stream_readable.js <ide> function ReadableState(options, stream) { <ide> // cast to an int <ide> this.bufferSize = ~~this.bufferSize; <ide> <del> this.lowWaterMark = options.lowWaterMark || 1024; <add> this.lowWaterMark = options.hasOwnProperty('lowWaterMark') ? <add> options.lowWaterMark : 1024; <ide> this.buffer = []; <ide> this.length = 0; <ide> this.pipes = []; <ide> Readable.prototype.read = function(n) { <ide> // but then it won't ever cause _read to be called, so in that case, <ide> // we just return what we have, and let the programmer deal with it. <ide> if (n > state.length) { <del> if (!state.ended && state.length < state.lowWaterMark) { <add> if (!state.ended && state.length <= state.lowWaterMark) { <ide> state.needReadable = true; <ide> n = 0; <ide> } else <ide> Readable.prototype.read = function(n) { <ide> state.length -= n; <ide> <ide> if (!state.ended && <del> state.length < state.lowWaterMark && <add> state.length <= state.lowWaterMark && <ide> !state.reading) { <ide> state.reading = true; <ide> // call internal read method <ide> Readable.prototype.read = function(n) { <ide> // that it's time to read more data. Otherwise, that'll <ide> // probably kick off another stream.read(), which can trigger <ide> // another _read(n,cb) before this one returns! <del> if (state.length < state.lowWaterMark) { <add> if (state.length <= state.lowWaterMark) { <ide> state.reading = true; <ide> this._read(state.bufferSize, onread.bind(this)); <ide> return; <ide> Readable.prototype.wrap = function(stream) { <ide> var ret = fromList(n, state.buffer, state.length, !!state.decoder); <ide> state.length -= n; <ide> <del> if (state.length < state.lowWaterMark && paused) { <add> if (state.length <= state.lowWaterMark && paused) { <ide> stream.resume(); <ide> paused = false; <ide> } <ide><path>lib/_stream_writable.js <ide> util.inherits(Writable, Stream); <ide> function WritableState(options) { <ide> options = options || {}; <ide> this.highWaterMark = options.highWaterMark || 16 * 1024; <del> this.lowWaterMark = options.lowWaterMark || 1024; <add> this.highWaterMark = options.hasOwnProperty('highWaterMark') ? <add> options.highWaterMark : 16 * 1024; <add> this.lowWaterMark = options.hasOwnProperty('lowWaterMark') ? <add> options.lowWaterMark : 1024; <ide> this.needDrain = false; <ide> this.ended = false; <ide> this.ending = false; <ide> Writable.prototype.write = function(chunk, encoding) { <ide> this._write(chunk, writecb.bind(this)); <ide> } <ide> <del> if (state.length < state.lowWaterMark && state.needDrain) { <add> if (state.length <= state.lowWaterMark && state.needDrain) { <ide> // Must force callback to be called on nextTick, so that we don't <ide> // emit 'drain' before the write() consumer gets the 'false' return <ide> // value, and has a chance to attach a 'drain' listener.
2
PHP
PHP
fix return type
cbbe9ee2268d5d37fd9a936c79a97fe8380d7276
<ide><path>src/Shell/Task/UnloadTask.php <ide> class UnloadTask extends Shell <ide> * Execution method always used for tasks. <ide> * <ide> * @param string $plugin The plugin name. <del> * @return boolean if action passed. <add> * @return bool if action passed. <ide> */ <ide> public function main($plugin = null) <ide> {
1
Javascript
Javascript
remove outdated todo
cc1ff874e5aa63e6bedf77e75a88373a09a555ae
<ide><path>packages/react-reconciler/src/__tests__/ReactFiberHostContext-test.js <ide> describe('ReactFiberHostContext', () => { <ide> beforeEach(() => { <ide> jest.resetModules(); <ide> React = require('react'); <del> // TODO: can we express this test with only public API? <ide> ReactFiberReconciler = require('react-reconciler'); <ide> }); <ide>
1
Ruby
Ruby
remove unused method
929fd12650b5f01f7f5aee1338cc25d993f59389
<ide><path>Library/Homebrew/os/mac.rb <ide> def default_compiler <ide> end <ide> end <ide> <del> def default_cxx_stdlib <del> version >= :mavericks ? :libcxx : :libstdcxx <del> end <del> <ide> def gcc_40_build_version <ide> @gcc_40_build_version ||= <ide> if (path = locate("gcc-4.0"))
1
Java
Java
improve coverage & related cleanup 03/05
cb05a2614c11ebb7b86e723556f98e50546a50ed
<ide><path>src/main/java/io/reactivex/internal/operators/flowable/BlockingFlowableIterable.java <ide> public T next() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(batchSize); <del> } <add> SubscriptionHelper.setOnce(this, s, batchSize); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableBufferBoundary.java <ide> void drain() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide> public boolean isDisposed() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableCache.java <ide> public void removeChild(ReplaySubscription<T> p) { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(connection, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(connection, s, Long.MAX_VALUE); <ide> } <ide> <ide> /** <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableCombineLatest.java <ide> public boolean isEmpty() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(prefetch); <del> } <add> SubscriptionHelper.setOnce(this, s, prefetch); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableGroupJoin.java <ide> public boolean isDisposed() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide> public boolean isDisposed() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithMaybe.java <ide> protected void subscribeActual(Subscriber<? super T> observer) { <ide> } <ide> <ide> @Override <del> public void onSubscribe(Subscription d) { <del> if (SubscriptionHelper.setOnce(mainSubscription, d)) { <del> d.request(prefetch); <del> } <add> public void onSubscribe(Subscription s) { <add> SubscriptionHelper.setOnce(mainSubscription, s, prefetch); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableMergeWithSingle.java <ide> protected void subscribeActual(Subscriber<? super T> observer) { <ide> } <ide> <ide> @Override <del> public void onSubscribe(Subscription d) { <del> if (SubscriptionHelper.setOnce(mainSubscription, d)) { <del> d.request(prefetch); <del> } <add> public void onSubscribe(Subscription s) { <add> SubscriptionHelper.setOnce(mainSubscription, s, prefetch); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableReplay.java <ide> void manageRequests() { <ide> public void request(long n) { <ide> // ignore negative requests <ide> if (SubscriptionHelper.validate(n)) { <del> // In general, RxJava doesn't prevent concurrent requests (with each other or with <del> // a cancel) so we need a CAS-loop, but we need to handle <del> // request overflow and cancelled/not requested state as well. <del> for (;;) { <del> // get the current request amount <del> long r = get(); <del> // if child called cancel() do nothing <del> if (r == CANCELLED) { <del> return; <del> } <del> // ignore zero requests except any first that sets in zero <del> if (r >= 0L && n == 0) { <del> return; <del> } <del> // otherwise, increase the request count <del> long u = BackpressureHelper.addCap(r, n); <del> <del> // try setting the new request value <del> if (compareAndSet(r, u)) { <del> // increment the total request counter <del> BackpressureHelper.add(totalRequested, n); <del> // if successful, notify the parent dispatcher this child can receive more <del> // elements <del> parent.manageRequests(); <del> <del> parent.buffer.replay(this); <del> return; <del> } <del> // otherwise, someone else changed the state (perhaps a concurrent <del> // request or cancellation) so retry <add> // add to the current requested and cap it at MAX_VALUE <add> // except when there was a concurrent cancellation <add> if (BackpressureHelper.addCancel(this, n) != CANCELLED) { <add> // increment the total request counter <add> BackpressureHelper.add(totalRequested, n); <add> // if successful, notify the parent dispatcher this child can receive more <add> // elements <add> parent.manageRequests(); <add> // try replaying any cached content <add> parent.buffer.replay(this); <ide> } <ide> } <ide> } <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableSamplePublisher.java <ide> public void onComplete() { <ide> completeMain(); <ide> } <ide> <del> boolean setOther(Subscription o) { <del> return SubscriptionHelper.setOnce(other, o); <add> void setOther(Subscription o) { <add> SubscriptionHelper.setOnce(other, o, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide> void emit() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (parent.setOther(s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> parent.setOther(s); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableSkipUntil.java <ide> final class OtherSubscriber extends AtomicReference<Subscription> <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableTakeUntil.java <ide> final class OtherSubscriber extends AtomicReference<Subscription> implements Flo <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableTimeout.java <ide> static final class TimeoutConsumer extends AtomicReference<Subscription> <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWindowBoundary.java <ide> protected void subscribeActual(Subscriber<? super Flowable<T>> subscriber) { <ide> <ide> @Override <ide> public void onSubscribe(Subscription d) { <del> if (SubscriptionHelper.setOnce(upstream, d)) { <del> d.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(upstream, d, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/flowable/FlowableWithLatestFromMany.java <ide> void cancelAllBut(int index) { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherPublisher.java <ide> void subscribeNext() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeFromFuture.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.Exceptions; <ide> <ide> /** <ide> * Waits until the source Future completes or the wait times out; treats a {@code null} <ide> protected void subscribeActual(MaybeObserver<? super T> observer) { <ide> } else { <ide> v = future.get(timeout, unit); <ide> } <del> } catch (InterruptedException ex) { <del> if (!d.isDisposed()) { <del> observer.onError(ex); <del> } <del> return; <del> } catch (ExecutionException ex) { <del> if (!d.isDisposed()) { <del> observer.onError(ex.getCause()); <add> } catch (Throwable ex) { <add> if (ex instanceof ExecutionException) { <add> ex = ex.getCause(); <ide> } <del> return; <del> } catch (TimeoutException ex) { <add> Exceptions.throwIfFatal(ex); <ide> if (!d.isDisposed()) { <ide> observer.onError(ex); <ide> } <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeTakeUntilPublisher.java <ide> void otherComplete() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeTimeoutPublisher.java <ide> public void otherComplete() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/observable/ObservableSkip.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.internal.disposables.DisposableHelper; <ide> <ide> public final class ObservableSkip<T> extends AbstractObservableWithUpstream<T, T> { <ide> final long n; <ide> public void subscribeActual(Observer<? super T> s) { <ide> } <ide> <ide> @Override <del> public void onSubscribe(Disposable s) { <del> this.d = s; <del> actual.onSubscribe(this); <add> public void onSubscribe(Disposable d) { <add> if (DisposableHelper.validate(this.d, d)) { <add> this.d = d; <add> actual.onSubscribe(this); <add> } <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/parallel/ParallelJoin.java <ide> void drainLoop() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(prefetch); <del> } <add> SubscriptionHelper.setOnce(this, s, prefetch); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/parallel/ParallelReduceFull.java <ide> void innerComplete(T value) { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/parallel/ParallelSortedJoin.java <ide> void drain() { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleDelayWithSingle.java <ide> protected void subscribeActual(SingleObserver<? super T> subscriber) { <ide> <ide> @Override <ide> public void onSubscribe(Disposable d) { <del> if (DisposableHelper.set(this, d)) { <add> if (DisposableHelper.setOnce(this, d)) { <ide> <ide> actual.onSubscribe(this); <ide> } <ide><path>src/main/java/io/reactivex/internal/operators/single/SingleTakeUntil.java <ide> void otherError(Throwable e) { <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/schedulers/SchedulerPoolFactory.java <ide> import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.AtomicReference; <ide> <del>import io.reactivex.plugins.RxJavaPlugins; <del> <ide> /** <ide> * Manages the creating of ScheduledExecutorServices and sets up purging. <ide> */ <ide> private SchedulerPoolFactory() { <ide> * Starts the purge thread if not already started. <ide> */ <ide> public static void start() { <del> if (!PURGE_ENABLED) { <del> return; <del> } <del> for (;;) { <del> ScheduledExecutorService curr = PURGE_THREAD.get(); <del> if (curr != null && !curr.isShutdown()) { <del> return; <del> } <del> ScheduledExecutorService next = Executors.newScheduledThreadPool(1, new RxThreadFactory("RxSchedulerPurge")); <del> if (PURGE_THREAD.compareAndSet(curr, next)) { <add> tryStart(PURGE_ENABLED); <add> } <ide> <del> next.scheduleAtFixedRate(new ScheduledTask(), PURGE_PERIOD_SECONDS, PURGE_PERIOD_SECONDS, TimeUnit.SECONDS); <add> static void tryStart(boolean purgeEnabled) { <add> if (purgeEnabled) { <add> for (;;) { <add> ScheduledExecutorService curr = PURGE_THREAD.get(); <add> if (curr != null) { <add> return; <add> } <add> ScheduledExecutorService next = Executors.newScheduledThreadPool(1, new RxThreadFactory("RxSchedulerPurge")); <add> if (PURGE_THREAD.compareAndSet(curr, next)) { <ide> <del> return; <del> } else { <del> next.shutdownNow(); <add> next.scheduleAtFixedRate(new ScheduledTask(), PURGE_PERIOD_SECONDS, PURGE_PERIOD_SECONDS, TimeUnit.SECONDS); <add> <add> return; <add> } else { <add> next.shutdownNow(); <add> } <ide> } <ide> } <ide> } <ide> public static void start() { <ide> * Stops the purge thread. <ide> */ <ide> public static void shutdown() { <del> ScheduledExecutorService exec = PURGE_THREAD.get(); <add> ScheduledExecutorService exec = PURGE_THREAD.getAndSet(null); <ide> if (exec != null) { <ide> exec.shutdownNow(); <ide> } <ide> POOLS.clear(); <ide> } <ide> <ide> static { <del> boolean purgeEnable = true; <del> int purgePeriod = 1; <del> <ide> Properties properties = System.getProperties(); <ide> <del> if (properties.containsKey(PURGE_ENABLED_KEY)) { <del> purgeEnable = Boolean.getBoolean(PURGE_ENABLED_KEY); <del> } <add> PurgeProperties pp = new PurgeProperties(); <add> pp.load(properties); <ide> <del> if (purgeEnable && properties.containsKey(PURGE_PERIOD_SECONDS_KEY)) { <del> purgePeriod = Integer.getInteger(PURGE_PERIOD_SECONDS_KEY, purgePeriod); <del> } <del> <del> PURGE_ENABLED = purgeEnable; <del> PURGE_PERIOD_SECONDS = purgePeriod; <add> PURGE_ENABLED = pp.purgeEnable; <add> PURGE_PERIOD_SECONDS = pp.purgePeriod; <ide> <ide> start(); <ide> } <ide> <add> static final class PurgeProperties { <add> <add> boolean purgeEnable; <add> <add> int purgePeriod; <add> <add> void load(Properties properties) { <add> if (properties.containsKey(PURGE_ENABLED_KEY)) { <add> purgeEnable = Boolean.parseBoolean(properties.getProperty(PURGE_ENABLED_KEY)); <add> } else { <add> purgeEnable = true; <add> } <add> <add> if (purgeEnable && properties.containsKey(PURGE_PERIOD_SECONDS_KEY)) { <add> try { <add> purgePeriod = Integer.parseInt(properties.getProperty(PURGE_PERIOD_SECONDS_KEY)); <add> } catch (NumberFormatException ex) { <add> purgePeriod = 1; <add> } <add> } else { <add> purgePeriod = 1; <add> } <add> } <add> } <add> <ide> /** <ide> * Creates a ScheduledExecutorService with the given factory. <ide> * @param factory the thread factory <ide> * @return the ScheduledExecutorService <ide> */ <ide> public static ScheduledExecutorService create(ThreadFactory factory) { <ide> final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1, factory); <del> if (PURGE_ENABLED && exec instanceof ScheduledThreadPoolExecutor) { <add> tryPutIntoPool(PURGE_ENABLED, exec); <add> return exec; <add> } <add> <add> static void tryPutIntoPool(boolean purgeEnabled, ScheduledExecutorService exec) { <add> if (purgeEnabled && exec instanceof ScheduledThreadPoolExecutor) { <ide> ScheduledThreadPoolExecutor e = (ScheduledThreadPoolExecutor) exec; <ide> POOLS.put(e, exec); <ide> } <del> return exec; <ide> } <ide> <ide> static final class ScheduledTask implements Runnable { <ide> @Override <ide> public void run() { <del> try { <del> for (ScheduledThreadPoolExecutor e : new ArrayList<ScheduledThreadPoolExecutor>(POOLS.keySet())) { <del> if (e.isShutdown()) { <del> POOLS.remove(e); <del> } else { <del> e.purge(); <del> } <add> for (ScheduledThreadPoolExecutor e : new ArrayList<ScheduledThreadPoolExecutor>(POOLS.keySet())) { <add> if (e.isShutdown()) { <add> POOLS.remove(e); <add> } else { <add> e.purge(); <ide> } <del> } catch (Throwable e) { <del> // Exceptions.throwIfFatal(e); nowhere to go <del> RxJavaPlugins.onError(e); <ide> } <ide> } <ide> } <ide><path>src/main/java/io/reactivex/internal/schedulers/TrampolineScheduler.java <ide> public void run() { <ide> long t = worker.now(TimeUnit.MILLISECONDS); <ide> if (execTime > t) { <ide> long delay = execTime - t; <del> if (delay > 0) { <del> try { <del> Thread.sleep(delay); <del> } catch (InterruptedException e) { <del> Thread.currentThread().interrupt(); <del> RxJavaPlugins.onError(e); <del> return; <del> } <add> try { <add> Thread.sleep(delay); <add> } catch (InterruptedException e) { <add> Thread.currentThread().interrupt(); <add> RxJavaPlugins.onError(e); <add> return; <ide> } <ide> } <ide> <ide><path>src/main/java/io/reactivex/internal/subscribers/ForEachWhileSubscriber.java <ide> public ForEachWhileSubscriber(Predicate<? super T> onNext, <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/subscribers/FutureSubscriber.java <ide> public T get(long timeout, TimeUnit unit) throws InterruptedException, Execution <ide> <ide> @Override <ide> public void onSubscribe(Subscription s) { <del> if (SubscriptionHelper.setOnce(this.s, s)) { <del> s.request(Long.MAX_VALUE); <del> } <add> SubscriptionHelper.setOnce(this.s, s, Long.MAX_VALUE); <ide> } <ide> <ide> @Override <ide><path>src/main/java/io/reactivex/internal/subscriptions/SubscriptionHelper.java <ide> public static void deferredRequest(AtomicReference<Subscription> field, AtomicLo <ide> } <ide> } <ide> } <add> <add> /** <add> * Atomically sets the subscription on the field if it is still null and issues a positive request <add> * to the given {@link Subscription}. <add> * <p> <add> * If the field is not null and doesn't contain the {@link #CANCELLED} <add> * instance, the {@link #reportSubscriptionSet()} is called. <add> * @param field the target field <add> * @param s the new subscription to set <add> * @param request the amount to request, positive (not verified) <add> * @return true if the operation succeeded, false if the target field was not null. <add> * @since 2.1.11 <add> */ <add> public static boolean setOnce(AtomicReference<Subscription> field, Subscription s, long request) { <add> if (setOnce(field, s)) { <add> s.request(request); <add> return true; <add> } <add> return false; <add> } <ide> } <ide><path>src/test/java/io/reactivex/TestHelper.java <ide> protected void subscribeActual(CompletableObserver observer) { <ide> } <ide> } <ide> <add> /** <add> * Check if the given transformed reactive type reports multiple onSubscribe calls to <add> * RxJavaPlugins. <add> * @param transform the transform to drive an operator <add> */ <add> public static void checkDoubleOnSubscribeCompletableToFlowable(Function<Completable, ? extends Publisher<?>> transform) { <add> List<Throwable> errors = trackPluginErrors(); <add> try { <add> final Boolean[] b = { null, null }; <add> final CountDownLatch cdl = new CountDownLatch(1); <add> <add> Completable source = new Completable() { <add> @Override <add> protected void subscribeActual(CompletableObserver observer) { <add> try { <add> Disposable d1 = Disposables.empty(); <add> <add> observer.onSubscribe(d1); <add> <add> Disposable d2 = Disposables.empty(); <add> <add> observer.onSubscribe(d2); <add> <add> b[0] = d1.isDisposed(); <add> b[1] = d2.isDisposed(); <add> } finally { <add> cdl.countDown(); <add> } <add> } <add> }; <add> <add> Publisher<?> out = transform.apply(source); <add> <add> out.subscribe(NoOpConsumer.INSTANCE); <add> <add> try { <add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS)); <add> } catch (InterruptedException ex) { <add> throw ExceptionHelper.wrapOrThrow(ex); <add> } <add> <add> assertEquals("First disposed?", false, b[0]); <add> assertEquals("Second not disposed?", true, b[1]); <add> <add> assertError(errors, 0, IllegalStateException.class, "Disposable already set!"); <add> } catch (Throwable ex) { <add> throw ExceptionHelper.wrapOrThrow(ex); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <add> /** <add> * Check if the given transformed reactive type reports multiple onSubscribe calls to <add> * RxJavaPlugins. <add> * @param transform the transform to drive an operator <add> */ <add> public static void checkDoubleOnSubscribeCompletableToObservable(Function<Completable, ? extends ObservableSource<?>> transform) { <add> List<Throwable> errors = trackPluginErrors(); <add> try { <add> final Boolean[] b = { null, null }; <add> final CountDownLatch cdl = new CountDownLatch(1); <add> <add> Completable source = new Completable() { <add> @Override <add> protected void subscribeActual(CompletableObserver observer) { <add> try { <add> Disposable d1 = Disposables.empty(); <add> <add> observer.onSubscribe(d1); <add> <add> Disposable d2 = Disposables.empty(); <add> <add> observer.onSubscribe(d2); <add> <add> b[0] = d1.isDisposed(); <add> b[1] = d2.isDisposed(); <add> } finally { <add> cdl.countDown(); <add> } <add> } <add> }; <add> <add> ObservableSource<?> out = transform.apply(source); <add> <add> out.subscribe(NoOpConsumer.INSTANCE); <add> <add> try { <add> assertTrue("Timed out", cdl.await(5, TimeUnit.SECONDS)); <add> } catch (InterruptedException ex) { <add> throw ExceptionHelper.wrapOrThrow(ex); <add> } <add> <add> assertEquals("First disposed?", false, b[0]); <add> assertEquals("Second not disposed?", true, b[1]); <add> <add> assertError(errors, 0, IllegalStateException.class, "Disposable already set!"); <add> } catch (Throwable ex) { <add> throw ExceptionHelper.wrapOrThrow(ex); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <add> <ide> /** <ide> * Check if the operator applied to a Maybe source propagates dispose properly. <ide> * @param <T> the source value type <ide><path>src/test/java/io/reactivex/flowable/FlowableBackpressureTests.java <ide> public void doAfterTest() { <ide> <ide> @Test <ide> public void testObserveOn() { <del> int NUM = (int) (Flowable.bufferSize() * 2.1); <add> int num = (int) (Flowable.bufferSize() * 2.1); <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <del> incrementingIntegers(c).observeOn(Schedulers.computation()).take(NUM).subscribe(ts); <add> incrementingIntegers(c).observeOn(Schedulers.computation()).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testObserveOn => Received: " + ts.valueCount() + " Emitted: " + c.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> assertTrue(c.get() < Flowable.bufferSize() * 4); <ide> } <ide> <ide> @Test <ide> public void testObserveOnWithSlowConsumer() { <del> int NUM = (int) (Flowable.bufferSize() * 0.2); <add> int num = (int) (Flowable.bufferSize() * 0.2); <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> incrementingIntegers(c).observeOn(Schedulers.computation()).map( <ide> public Integer apply(Integer i) { <ide> return i; <ide> } <ide> } <del> ).take(NUM).subscribe(ts); <add> ).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testObserveOnWithSlowConsumer => Received: " + ts.valueCount() + " Emitted: " + c.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> assertTrue(c.get() < Flowable.bufferSize() * 2); <ide> } <ide> <ide> @Test <ide> public void testMergeSync() { <del> int NUM = (int) (Flowable.bufferSize() * 4.1); <add> int num = (int) (Flowable.bufferSize() * 4.1); <ide> AtomicInteger c1 = new AtomicInteger(); <ide> AtomicInteger c2 = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> Flowable<Integer> merged = Flowable.merge(incrementingIntegers(c1), incrementingIntegers(c2)); <ide> <del> merged.take(NUM).subscribe(ts); <add> merged.take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <del> System.out.println("Expected: " + NUM + " got: " + ts.valueCount()); <add> System.out.println("Expected: " + num + " got: " + ts.valueCount()); <ide> System.out.println("testMergeSync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> // either one can starve the other, but neither should be capable of doing more than 5 batches (taking 4.1) <ide> // TODO is it possible to make this deterministic rather than one possibly starving the other? <ide> // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" algoritms generally take a performance hit <ide> public void testMergeSync() { <ide> <ide> @Test <ide> public void testMergeAsync() { <del> int NUM = (int) (Flowable.bufferSize() * 4.1); <add> int num = (int) (Flowable.bufferSize() * 4.1); <ide> AtomicInteger c1 = new AtomicInteger(); <ide> AtomicInteger c2 = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> Flowable<Integer> merged = Flowable.merge( <ide> incrementingIntegers(c1).subscribeOn(Schedulers.computation()), <ide> incrementingIntegers(c2).subscribeOn(Schedulers.computation())); <ide> <del> merged.take(NUM).subscribe(ts); <add> merged.take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testMergeAsync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> // either one can starve the other, but neither should be capable of doing more than 5 batches (taking 4.1) <ide> // TODO is it possible to make this deterministic rather than one possibly starving the other? <ide> // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" algoritms generally take a performance hit <ide> public void testMergeAsyncThenObserveOnLoop() { <ide> System.out.println("testMergeAsyncThenObserveOnLoop >> " + i); <ide> } <ide> // Verify there is no MissingBackpressureException <del> int NUM = (int) (Flowable.bufferSize() * 4.1); <add> int num = (int) (Flowable.bufferSize() * 4.1); <ide> AtomicInteger c1 = new AtomicInteger(); <ide> AtomicInteger c2 = new AtomicInteger(); <ide> <ide> public void testMergeAsyncThenObserveOnLoop() { <ide> <ide> merged <ide> .observeOn(Schedulers.io()) <del> .take(NUM) <add> .take(num) <ide> .subscribe(ts); <ide> <ide> <ide> ts.awaitTerminalEvent(5, TimeUnit.SECONDS); <ide> ts.assertComplete(); <ide> ts.assertNoErrors(); <ide> System.out.println("testMergeAsyncThenObserveOn => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> } <ide> } <ide> <ide> @Test <ide> public void testMergeAsyncThenObserveOn() { <del> int NUM = (int) (Flowable.bufferSize() * 4.1); <add> int num = (int) (Flowable.bufferSize() * 4.1); <ide> AtomicInteger c1 = new AtomicInteger(); <ide> AtomicInteger c2 = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> Flowable<Integer> merged = Flowable.merge( <ide> incrementingIntegers(c1).subscribeOn(Schedulers.computation()), <ide> incrementingIntegers(c2).subscribeOn(Schedulers.computation())); <ide> <del> merged.observeOn(Schedulers.newThread()).take(NUM).subscribe(ts); <add> merged.observeOn(Schedulers.newThread()).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testMergeAsyncThenObserveOn => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> // either one can starve the other, but neither should be capable of doing more than 5 batches (taking 4.1) <ide> // TODO is it possible to make this deterministic rather than one possibly starving the other? <ide> // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" algoritms generally take a performance hit <ide> public void testMergeAsyncThenObserveOn() { <ide> <ide> @Test <ide> public void testFlatMapSync() { <del> int NUM = (int) (Flowable.bufferSize() * 2.1); <add> int num = (int) (Flowable.bufferSize() * 2.1); <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> <ide> public Publisher<Integer> apply(Integer i) { <ide> return incrementingIntegers(new AtomicInteger()).take(10); <ide> } <ide> }) <del> .take(NUM).subscribe(ts); <add> .take(num).subscribe(ts); <ide> <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testFlatMapSync => Received: " + ts.valueCount() + " Emitted: " + c.get()); <del> assertEquals(NUM, ts.valueCount()); <del> // expect less than 1 buffer since the flatMap is emitting 10 each time, so it is NUM/10 that will be taken. <add> assertEquals(num, ts.valueCount()); <add> // expect less than 1 buffer since the flatMap is emitting 10 each time, so it is num/10 that will be taken. <ide> assertTrue(c.get() < Flowable.bufferSize()); <ide> } <ide> <ide> @Test <ide> @Ignore("The test is non-deterministic and can't be made deterministic") <ide> public void testFlatMapAsync() { <del> int NUM = (int) (Flowable.bufferSize() * 2.1); <add> int num = (int) (Flowable.bufferSize() * 2.1); <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> <ide> public Publisher<Integer> apply(Integer i) { <ide> } <ide> } <ide> ) <del> .take(NUM).subscribe(ts); <add> .take(num).subscribe(ts); <ide> <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testFlatMapAsync => Received: " + ts.valueCount() + " Emitted: " + c.get() + " Size: " + Flowable.bufferSize()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> // even though we only need 10, it will request at least Flowable.bufferSize(), and then as it drains keep requesting more <ide> // and then it will be non-deterministic when the take() causes the unsubscribe as it is scheduled on 10 different schedulers (threads) <ide> // normally this number is ~250 but can get up to ~1200 when Flowable.bufferSize() == 1024 <ide> public Publisher<Integer> apply(Integer i) { <ide> <ide> @Test <ide> public void testZipSync() { <del> int NUM = (int) (Flowable.bufferSize() * 4.1); <add> int num = (int) (Flowable.bufferSize() * 4.1); <ide> AtomicInteger c1 = new AtomicInteger(); <ide> AtomicInteger c2 = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> public Integer apply(Integer t1, Integer t2) { <ide> } <ide> }); <ide> <del> zipped.take(NUM) <add> zipped.take(num) <ide> .subscribe(ts); <ide> <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testZipSync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> assertTrue(c1.get() < Flowable.bufferSize() * 7); <ide> assertTrue(c2.get() < Flowable.bufferSize() * 7); <ide> } <ide> <ide> @Test <ide> public void testZipAsync() { <del> int NUM = (int) (Flowable.bufferSize() * 2.1); <add> int num = (int) (Flowable.bufferSize() * 2.1); <ide> AtomicInteger c1 = new AtomicInteger(); <ide> AtomicInteger c2 = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> public Integer apply(Integer t1, Integer t2) { <ide> } <ide> }); <ide> <del> zipped.take(NUM).subscribe(ts); <add> zipped.take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testZipAsync => Received: " + ts.valueCount() + " Emitted: " + c1.get() + " / " + c2.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> int max = Flowable.bufferSize() * 5; <ide> assertTrue("" + c1.get() + " >= " + max, c1.get() < max); <ide> assertTrue("" + c2.get() + " >= " + max, c2.get() < max); <ide> public Integer apply(Integer t1, Integer t2) { <ide> public void testSubscribeOnScheduling() { <ide> // in a loop for repeating the concurrency in this to increase chance of failure <ide> for (int i = 0; i < 100; i++) { <del> int NUM = (int) (Flowable.bufferSize() * 2.1); <add> int num = (int) (Flowable.bufferSize() * 2.1); <ide> AtomicInteger c = new AtomicInteger(); <ide> ConcurrentLinkedQueue<Thread> threads = new ConcurrentLinkedQueue<Thread>(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> // observeOn is there to make it async and need backpressure <del> incrementingIntegers(c, threads).subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).take(NUM).subscribe(ts); <add> incrementingIntegers(c, threads).subscribeOn(Schedulers.computation()).observeOn(Schedulers.computation()).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testSubscribeOnScheduling => Received: " + ts.valueCount() + " Emitted: " + c.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> assertTrue(c.get() < Flowable.bufferSize() * 4); <ide> Thread first = null; <ide> for (Thread t : threads) { <ide> public void testSubscribeOnScheduling() { <ide> <ide> @Test <ide> public void testTakeFilterSkipChainAsync() { <del> int NUM = (int) (Flowable.bufferSize() * 2.1); <add> int num = (int) (Flowable.bufferSize() * 2.1); <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> incrementingIntegers(c).observeOn(Schedulers.computation()) <ide> public void testTakeFilterSkipChainAsync() { <ide> public boolean test(Integer i) { <ide> return i > 11000; <ide> } <del> }).take(NUM).subscribe(ts); <add> }).take(num).subscribe(ts); <ide> <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> <ide> // emit 10000 that are skipped <ide> // emit next 1000 that are filtered out <del> // take NUM <del> // so emitted is at least 10000+1000+NUM + extra for buffer size/threshold <add> // take num <add> // so emitted is at least 10000+1000+num + extra for buffer size/threshold <ide> int expected = 10000 + 1000 + Flowable.bufferSize() * 3 + Flowable.bufferSize() / 2; <ide> <ide> System.out.println("testTakeFilterSkipChain => Received: " + ts.valueCount() + " Emitted: " + c.get() + " Expected: " + expected); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> assertTrue(c.get() < expected); <ide> } <ide> <ide> public void testOnBackpressureDrop() { <ide> if (System.currentTimeMillis() - t > TimeUnit.SECONDS.toMillis(9)) { <ide> break; <ide> } <del> int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <add> int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> firehose(c).onBackpressureDrop() <ide> .observeOn(Schedulers.computation()) <del> .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); <add> .map(SLOW_PASS_THRU).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> <ide> List<Integer> onNextEvents = ts.values(); <del> assertEquals(NUM, onNextEvents.size()); <add> assertEquals(num, onNextEvents.size()); <ide> <del> Integer lastEvent = onNextEvents.get(NUM - 1); <add> Integer lastEvent = onNextEvents.get(num - 1); <ide> <ide> System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Emitted: " + c.get() + " Last value: " + lastEvent); <ide> // it drop, so we should get some number far higher than what would have sequentially incremented <del> assertTrue(NUM - 1 <= lastEvent.intValue()); <add> assertTrue(num - 1 <= lastEvent.intValue()); <ide> } <ide> } <ide> <ide> public void testOnBackpressureDropWithAction() { <ide> final AtomicInteger emitCount = new AtomicInteger(); <ide> final AtomicInteger dropCount = new AtomicInteger(); <ide> final AtomicInteger passCount = new AtomicInteger(); <del> final int NUM = Flowable.bufferSize() * 3; // > 1 so that take doesn't prevent buffer overflow <add> final int num = Flowable.bufferSize() * 3; // > 1 so that take doesn't prevent buffer overflow <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> <ide> firehose(emitCount) <ide> public void accept(Integer v) { <ide> }) <ide> .observeOn(Schedulers.computation()) <ide> .map(SLOW_PASS_THRU) <del> .take(NUM).subscribe(ts); <add> .take(num).subscribe(ts); <ide> <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> <ide> List<Integer> onNextEvents = ts.values(); <del> Integer lastEvent = onNextEvents.get(NUM - 1); <add> Integer lastEvent = onNextEvents.get(num - 1); <ide> System.out.println(testName.getMethodName() + " => Received: " + onNextEvents.size() + " Passed: " + passCount.get() + " Dropped: " + dropCount.get() + " Emitted: " + emitCount.get() + " Last value: " + lastEvent); <del> assertEquals(NUM, onNextEvents.size()); <del> // in reality, NUM < passCount <del> assertTrue(NUM <= passCount.get()); <add> assertEquals(num, onNextEvents.size()); <add> // in reality, num < passCount <add> assertTrue(num <= passCount.get()); <ide> // it drop, so we should get some number far higher than what would have sequentially incremented <del> assertTrue(NUM - 1 <= lastEvent.intValue()); <add> assertTrue(num - 1 <= lastEvent.intValue()); <ide> assertTrue(0 < dropCount.get()); <ide> assertEquals(emitCount.get(), passCount.get() + dropCount.get()); <ide> } <ide> public void accept(Integer v) { <ide> @Test(timeout = 10000) <ide> public void testOnBackpressureDropSynchronous() { <ide> for (int i = 0; i < 100; i++) { <del> int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <add> int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> firehose(c).onBackpressureDrop() <del> .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); <add> .map(SLOW_PASS_THRU).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> <ide> List<Integer> onNextEvents = ts.values(); <del> assertEquals(NUM, onNextEvents.size()); <add> assertEquals(num, onNextEvents.size()); <ide> <del> Integer lastEvent = onNextEvents.get(NUM - 1); <add> Integer lastEvent = onNextEvents.get(num - 1); <ide> <ide> System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Emitted: " + c.get() + " Last value: " + lastEvent); <ide> // it drop, so we should get some number far higher than what would have sequentially incremented <del> assertTrue(NUM - 1 <= lastEvent.intValue()); <add> assertTrue(num - 1 <= lastEvent.intValue()); <ide> } <ide> } <ide> <ide> @Test(timeout = 10000) <ide> public void testOnBackpressureDropSynchronousWithAction() { <ide> for (int i = 0; i < 100; i++) { <ide> final AtomicInteger dropCount = new AtomicInteger(); <del> int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <add> int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> firehose(c).onBackpressureDrop(new Consumer<Integer>() { <ide> public void accept(Integer j) { <ide> dropCount.incrementAndGet(); <ide> } <ide> }) <del> .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); <add> .map(SLOW_PASS_THRU).take(num).subscribe(ts); <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> <ide> List<Integer> onNextEvents = ts.values(); <del> assertEquals(NUM, onNextEvents.size()); <add> assertEquals(num, onNextEvents.size()); <ide> <del> Integer lastEvent = onNextEvents.get(NUM - 1); <add> Integer lastEvent = onNextEvents.get(num - 1); <ide> <ide> System.out.println("testOnBackpressureDrop => Received: " + onNextEvents.size() + " Dropped: " + dropCount.get() + " Emitted: " + c.get() + " Last value: " + lastEvent); <ide> // it drop, so we should get some number far higher than what would have sequentially incremented <del> assertTrue(NUM - 1 <= lastEvent.intValue()); <add> assertTrue(num - 1 <= lastEvent.intValue()); <ide> // no drop in synchronous mode <ide> assertEquals(0, dropCount.get()); <ide> assertEquals(c.get(), onNextEvents.size()); <ide> public void accept(Integer j) { <ide> <ide> @Test(timeout = 2000) <ide> public void testOnBackpressureBuffer() { <del> int NUM = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <add> int num = (int) (Flowable.bufferSize() * 1.1); // > 1 so that take doesn't prevent buffer overflow <ide> AtomicInteger c = new AtomicInteger(); <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <ide> <ide> public boolean test(Integer t1) { <ide> }) <ide> .onBackpressureBuffer() <ide> .observeOn(Schedulers.computation()) <del> .map(SLOW_PASS_THRU).take(NUM).subscribe(ts); <add> .map(SLOW_PASS_THRU).take(num).subscribe(ts); <ide> <ide> ts.awaitTerminalEvent(); <ide> ts.assertNoErrors(); <ide> System.out.println("testOnBackpressureBuffer => Received: " + ts.valueCount() + " Emitted: " + c.get()); <del> assertEquals(NUM, ts.valueCount()); <add> assertEquals(num, ts.valueCount()); <ide> // it buffers, so we should get the right value sequentially <del> assertEquals(NUM - 1, ts.values().get(NUM - 1).intValue()); <add> assertEquals(num - 1, ts.values().get(num - 1).intValue()); <ide> } <ide> <ide> /** <ide> public void request(long n) { <ide> if (threadsSeen != null) { <ide> threadsSeen.offer(Thread.currentThread()); <ide> } <del> long _c = BackpressureHelper.add(requested, n); <del> if (_c == 0) { <add> long c = BackpressureHelper.add(requested, n); <add> if (c == 0) { <ide> while (!cancelled) { <ide> counter.incrementAndGet(); <ide> s.onNext(i++); <ide><path>src/test/java/io/reactivex/flowable/FlowableCovarianceTest.java <ide> public void testCovarianceOfFrom() { <ide> <ide> @Test <ide> public void testSortedList() { <del> Comparator<Media> SORT_FUNCTION = new Comparator<Media>() { <add> Comparator<Media> sortFunction = new Comparator<Media>() { <ide> @Override <ide> public int compare(Media t1, Media t2) { <ide> return 1; <ide> public int compare(Media t1, Media t2) { <ide> <ide> // this one would work without the covariance generics <ide> Flowable<Media> o = Flowable.just(new Movie(), new TVSeason(), new Album()); <del> o.toSortedList(SORT_FUNCTION); <add> o.toSortedList(sortFunction); <ide> <ide> // this one would NOT work without the covariance generics <ide> Flowable<Movie> o2 = Flowable.just(new Movie(), new ActionMovie(), new HorrorMovie()); <del> o2.toSortedList(SORT_FUNCTION); <add> o2.toSortedList(sortFunction); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/internal/observers/BlockingFirstObserverTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.observers; <add> <add>import static org.junit.Assert.*; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.TestException; <add> <add>public class BlockingFirstObserverTest { <add> <add> @Test <add> public void firstValueOnly() { <add> BlockingFirstObserver<Integer> bf = new BlockingFirstObserver<Integer>(); <add> Disposable d = Disposables.empty(); <add> bf.onSubscribe(d); <add> <add> bf.onNext(1); <add> <add> assertTrue(d.isDisposed()); <add> <add> assertEquals(1, bf.value.intValue()); <add> assertEquals(0, bf.getCount()); <add> <add> bf.onNext(2); <add> <add> assertEquals(1, bf.value.intValue()); <add> assertEquals(0, bf.getCount()); <add> <add> bf.onError(new TestException()); <add> assertEquals(1, bf.value.intValue()); <add> assertNull(bf.error); <add> assertEquals(0, bf.getCount()); <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/observers/BlockingObserverTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.observers; <add> <add>import static org.junit.Assert.*; <add> <add>import java.util.*; <add> <add>import org.junit.Test; <add> <add>public class BlockingObserverTest { <add> <add> @Test <add> public void dispose() { <add> Queue<Object> q = new ArrayDeque<Object>(); <add> <add> BlockingObserver<Object> bo = new BlockingObserver<Object>(q); <add> <add> bo.dispose(); <add> <add> assertEquals(BlockingObserver.TERMINATED, q.poll()); <add> <add> bo.dispose(); <add> <add> assertNull(q.poll()); <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableAmbTest.java <ide> import static org.junit.Assert.*; <ide> <ide> import java.util.*; <add>import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.disposables.*; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.internal.operators.completable.CompletableAmb.Amb; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.PublishProcessor; <ide> public void ambArrayOrder() { <ide> Completable.ambArray(Completable.complete(), error).test().assertComplete(); <ide> } <ide> <add> @Test <add> public void ambRace() { <add> TestObserver<Void> to = new TestObserver<Void>(); <add> to.onSubscribe(Disposables.empty()); <add> <add> CompositeDisposable cd = new CompositeDisposable(); <add> AtomicBoolean once = new AtomicBoolean(); <add> Amb a = new Amb(once, cd, to); <add> <add> a.onComplete(); <add> a.onComplete(); <add> <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> a.onError(new TestException()); <add> <add> TestHelper.assertUndeliverable(errors, 0, TestException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableFromActionTest.java <ide> <ide> package io.reactivex.internal.operators.completable; <ide> <del>import io.reactivex.Completable; <del>import io.reactivex.functions.Action; <add>import static org.junit.Assert.assertEquals; <add> <ide> import java.util.concurrent.atomic.AtomicInteger; <add> <ide> import org.junit.Test; <ide> <del>import static org.junit.Assert.assertEquals; <add>import io.reactivex.Completable; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Action; <ide> <ide> public class CompletableFromActionTest { <ide> @Test(expected = NullPointerException.class) <ide> public void run() throws Exception { <ide> .test() <ide> .assertFailure(UnsupportedOperationException.class); <ide> } <add> <add> @Test <add> public void fromActionDisposed() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> calls.incrementAndGet(); <add> } <add> }) <add> .test(true) <add> .assertEmpty(); <add> <add> assertEquals(1, calls.get()); <add> } <add> <add> @Test <add> public void fromActionErrorsDisposed() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Completable.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> calls.incrementAndGet(); <add> throw new TestException(); <add> } <add> }) <add> .test(true) <add> .assertEmpty(); <add> <add> assertEquals(1, calls.get()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableFromCallableTest.java <ide> <ide> package io.reactivex.internal.operators.completable; <ide> <del>import io.reactivex.Completable; <del>import java.util.concurrent.Callable; <del>import java.util.concurrent.CountDownLatch; <add>import static org.junit.Assert.assertEquals; <add>import static org.mockito.ArgumentMatchers.any; <add>import static org.mockito.Mockito.*; <add> <add>import java.util.concurrent.*; <ide> import java.util.concurrent.atomic.AtomicInteger; <ide> <del>import io.reactivex.Observer; <del>import io.reactivex.TestHelper; <del>import io.reactivex.disposables.Disposable; <del>import io.reactivex.observers.TestObserver; <del>import io.reactivex.schedulers.Schedulers; <ide> import org.junit.Test; <ide> import org.mockito.invocation.InvocationOnMock; <ide> import org.mockito.stubbing.Answer; <ide> <del>import static org.junit.Assert.assertEquals; <del>import static org.mockito.ArgumentMatchers.any; <del>import static org.mockito.Mockito.*; <add>import io.reactivex.*; <add>import io.reactivex.disposables.Disposable; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.observers.TestObserver; <add>import io.reactivex.schedulers.Schedulers; <ide> <ide> public class CompletableFromCallableTest { <ide> @Test(expected = NullPointerException.class) <ide> public String answer(InvocationOnMock invocation) throws Throwable { <ide> verify(observer).onSubscribe(any(Disposable.class)); <ide> verifyNoMoreInteractions(observer); <ide> } <add> <add> @Test <add> public void fromActionErrorsDisposed() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Completable.fromCallable(new Callable<Object>() { <add> @Override <add> public Object call() throws Exception { <add> calls.incrementAndGet(); <add> throw new TestException(); <add> } <add> }) <add> .test(true) <add> .assertEmpty(); <add> <add> assertEquals(1, calls.get()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableFromPublisherTest.java <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.functions.Function; <ide> <ide> public class CompletableFromPublisherTest { <ide> @Test(expected = NullPointerException.class) <ide> public void fromPublisherThrows() { <ide> public void dispose() { <ide> TestHelper.checkDisposed(Completable.fromPublisher(Flowable.just(1))); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowableToCompletable(new Function<Flowable<Object>, Completable>() { <add> @Override <add> public Completable apply(Flowable<Object> f) throws Exception { <add> return Completable.fromPublisher(f); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableFromRunnableTest.java <ide> <ide> package io.reactivex.internal.operators.completable; <ide> <del>import io.reactivex.Completable; <add>import static org.junit.Assert.assertEquals; <add> <ide> import java.util.concurrent.atomic.AtomicInteger; <add> <ide> import org.junit.Test; <ide> <del>import static org.junit.Assert.assertEquals; <add>import io.reactivex.Completable; <add>import io.reactivex.exceptions.TestException; <ide> <ide> public class CompletableFromRunnableTest { <ide> @Test(expected = NullPointerException.class) <ide> public void run() { <ide> .test() <ide> .assertFailure(UnsupportedOperationException.class); <ide> } <add> <add> @Test <add> public void fromRunnableDisposed() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Completable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> calls.incrementAndGet(); <add> } <add> }) <add> .test(true) <add> .assertEmpty(); <add> <add> assertEquals(1, calls.get()); <add> } <add> <add> @Test <add> public void fromRunnableErrorsDisposed() { <add> final AtomicInteger calls = new AtomicInteger(); <add> Completable.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> calls.incrementAndGet(); <add> throw new TestException(); <add> } <add> }) <add> .test(true) <add> .assertEmpty(); <add> <add> assertEquals(1, calls.get()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableTimeoutTest.java <ide> <ide> import java.util.List; <ide> import java.util.concurrent.*; <add>import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.disposables.*; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Action; <add>import io.reactivex.internal.operators.completable.CompletableTimeout.TimeOutObserver; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.schedulers.*; <ide> public void run() { <ide> } <ide> } <ide> } <add> <add> @Test <add> public void ambRace() { <add> TestObserver<Void> to = new TestObserver<Void>(); <add> to.onSubscribe(Disposables.empty()); <add> <add> CompositeDisposable cd = new CompositeDisposable(); <add> AtomicBoolean once = new AtomicBoolean(); <add> TimeOutObserver a = new TimeOutObserver(cd, once, to); <add> <add> a.onComplete(); <add> a.onComplete(); <add> <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> a.onError(new TestException()); <add> <add> TestHelper.assertUndeliverable(errors, 0, TestException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableToFlowableTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.completable; <add> <add>import org.junit.Test; <add>import org.reactivestreams.Publisher; <add> <add>import io.reactivex.*; <add>import io.reactivex.functions.Function; <add> <add>public class CompletableToFlowableTest { <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeCompletableToFlowable(new Function<Completable, Publisher<?>>() { <add> @Override <add> public Publisher<?> apply(Completable c) throws Exception { <add> return c.toFlowable(); <add> } <add> }); <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableAmbTest.java <ide> public void run() { <ide> <ide> @Test <ide> public void testAmb() { <del> Flowable<String> Flowable1 = createFlowable(new String[] { <add> Flowable<String> flowable1 = createFlowable(new String[] { <ide> "1", "11", "111", "1111" }, 2000, null); <del> Flowable<String> Flowable2 = createFlowable(new String[] { <add> Flowable<String> flowable2 = createFlowable(new String[] { <ide> "2", "22", "222", "2222" }, 1000, null); <del> Flowable<String> Flowable3 = createFlowable(new String[] { <add> Flowable<String> flowable3 = createFlowable(new String[] { <ide> "3", "33", "333", "3333" }, 3000, null); <ide> <ide> @SuppressWarnings("unchecked") <del> Flowable<String> o = Flowable.ambArray(Flowable1, <del> Flowable2, Flowable3); <add> Flowable<String> o = Flowable.ambArray(flowable1, <add> flowable2, flowable3); <ide> <ide> @SuppressWarnings("unchecked") <ide> DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); <ide> public void testAmb() { <ide> public void testAmb2() { <ide> IOException expectedException = new IOException( <ide> "fake exception"); <del> Flowable<String> Flowable1 = createFlowable(new String[] {}, <add> Flowable<String> flowable1 = createFlowable(new String[] {}, <ide> 2000, new IOException("fake exception")); <del> Flowable<String> Flowable2 = createFlowable(new String[] { <add> Flowable<String> flowable2 = createFlowable(new String[] { <ide> "2", "22", "222", "2222" }, 1000, expectedException); <del> Flowable<String> Flowable3 = createFlowable(new String[] {}, <add> Flowable<String> flowable3 = createFlowable(new String[] {}, <ide> 3000, new IOException("fake exception")); <ide> <ide> @SuppressWarnings("unchecked") <del> Flowable<String> o = Flowable.ambArray(Flowable1, <del> Flowable2, Flowable3); <add> Flowable<String> o = Flowable.ambArray(flowable1, <add> flowable2, flowable3); <ide> <ide> @SuppressWarnings("unchecked") <ide> DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); <ide> public void testAmb2() { <ide> <ide> @Test <ide> public void testAmb3() { <del> Flowable<String> Flowable1 = createFlowable(new String[] { <add> Flowable<String> flowable1 = createFlowable(new String[] { <ide> "1" }, 2000, null); <del> Flowable<String> Flowable2 = createFlowable(new String[] {}, <add> Flowable<String> flowable2 = createFlowable(new String[] {}, <ide> 1000, null); <del> Flowable<String> Flowable3 = createFlowable(new String[] { <add> Flowable<String> flowable3 = createFlowable(new String[] { <ide> "3" }, 3000, null); <ide> <ide> @SuppressWarnings("unchecked") <del> Flowable<String> o = Flowable.ambArray(Flowable1, <del> Flowable2, Flowable3); <add> Flowable<String> o = Flowable.ambArray(flowable1, <add> flowable2, flowable3); <ide> <ide> @SuppressWarnings("unchecked") <ide> DefaultSubscriber<String> observer = mock(DefaultSubscriber.class); <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableCombineLatestTest.java <ide> public void testBackpressureLoop() { <ide> public void testBackpressure() { <ide> BiFunction<String, Integer, String> combineLatestFunction = getConcatStringIntegerCombineLatestFunction(); <ide> <del> int NUM = Flowable.bufferSize() * 4; <add> int num = Flowable.bufferSize() * 4; <ide> TestSubscriber<String> ts = new TestSubscriber<String>(); <ide> Flowable.combineLatest( <ide> Flowable.just("one", "two"), <del> Flowable.range(2, NUM), <add> Flowable.range(2, num), <ide> combineLatestFunction <ide> ) <ide> .observeOn(Schedulers.computation()) <ide> public void testBackpressure() { <ide> assertEquals("two2", events.get(0)); <ide> assertEquals("two3", events.get(1)); <ide> assertEquals("two4", events.get(2)); <del> assertEquals(NUM, events.size()); <add> assertEquals(num, events.size()); <ide> } <ide> <ide> @Test <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableConcatMapTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.flowable; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.internal.operators.flowable.FlowableConcatMap.WeakScalarSubscription; <add>import io.reactivex.subscribers.TestSubscriber; <add> <add>public class FlowableConcatMapTest { <add> <add> @Test <add> public void weakSubscriptionRequest() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(0); <add> WeakScalarSubscription<Integer> ws = new WeakScalarSubscription<Integer>(1, ts); <add> ts.onSubscribe(ws); <add> <add> ws.request(0); <add> <add> ts.assertEmpty(); <add> <add> ws.request(1); <add> <add> ts.assertResult(1); <add> <add> ws.request(1); <add> <add> ts.assertResult(1); <add> } <add> <add>} <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableDebounceTest.java <ide> package io.reactivex.internal.operators.flowable; <ide> <ide> import static org.junit.Assert.*; <add>import static org.mockito.ArgumentMatchers.*; <ide> import static org.mockito.Mockito.*; <ide> <ide> import java.util.List; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.junit.*; <ide> import org.mockito.InOrder; <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.disposables.*; <add>import io.reactivex.disposables.Disposable; <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Function; <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.plugins.RxJavaPlugins; <del>import io.reactivex.processors.PublishProcessor; <add>import io.reactivex.processors.*; <ide> import io.reactivex.schedulers.TestScheduler; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public class FlowableDebounceTest { <ide> <ide> private TestScheduler scheduler; <del> private Subscriber<String> observer; <add> private Subscriber<String> Subscriber; <ide> private Scheduler.Worker innerScheduler; <ide> <ide> @Before <ide> public void before() { <ide> scheduler = new TestScheduler(); <del> observer = TestHelper.mockSubscriber(); <add> Subscriber = TestHelper.mockSubscriber(); <ide> innerScheduler = scheduler.createWorker(); <ide> } <ide> <ide> @Test <ide> public void testDebounceWithCompleted() { <ide> Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { <ide> @Override <del> public void subscribe(Subscriber<? super String> observer) { <del> observer.onSubscribe(new BooleanSubscription()); <del> publishNext(observer, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. <del> publishNext(observer, 400, "two"); // Should be published since "three" will arrive after the timeout expires. <del> publishNext(observer, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. <del> publishCompleted(observer, 1000); // Should be published as soon as the timeout expires. <add> public void subscribe(Subscriber<? super String> subscriber) { <add> subscriber.onSubscribe(new BooleanSubscription()); <add> publishNext(subscriber, 100, "one"); // Should be skipped since "two" will arrive before the timeout expires. <add> publishNext(subscriber, 400, "two"); // Should be published since "three" will arrive after the timeout expires. <add> publishNext(subscriber, 900, "three"); // Should be skipped since onComplete will arrive before the timeout expires. <add> publishCompleted(subscriber, 1000); // Should be published as soon as the timeout expires. <ide> } <ide> }); <ide> <ide> Flowable<String> sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler); <del> sampled.subscribe(observer); <add> sampled.subscribe(Subscriber); <ide> <ide> scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); <del> InOrder inOrder = inOrder(observer); <add> InOrder inOrder = inOrder(Subscriber); <ide> // must go to 800 since it must be 400 after when two is sent, which is at 400 <ide> scheduler.advanceTimeTo(800, TimeUnit.MILLISECONDS); <del> inOrder.verify(observer, times(1)).onNext("two"); <add> inOrder.verify(Subscriber, times(1)).onNext("two"); <ide> scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); <del> inOrder.verify(observer, times(1)).onComplete(); <add> inOrder.verify(Subscriber, times(1)).onComplete(); <ide> inOrder.verifyNoMoreInteractions(); <ide> } <ide> <ide> @Test <ide> public void testDebounceNeverEmits() { <ide> Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { <ide> @Override <del> public void subscribe(Subscriber<? super String> observer) { <del> observer.onSubscribe(new BooleanSubscription()); <add> public void subscribe(Subscriber<? super String> subscriber) { <add> subscriber.onSubscribe(new BooleanSubscription()); <ide> // all should be skipped since they are happening faster than the 200ms timeout <del> publishNext(observer, 100, "a"); // Should be skipped <del> publishNext(observer, 200, "b"); // Should be skipped <del> publishNext(observer, 300, "c"); // Should be skipped <del> publishNext(observer, 400, "d"); // Should be skipped <del> publishNext(observer, 500, "e"); // Should be skipped <del> publishNext(observer, 600, "f"); // Should be skipped <del> publishNext(observer, 700, "g"); // Should be skipped <del> publishNext(observer, 800, "h"); // Should be skipped <del> publishCompleted(observer, 900); // Should be published as soon as the timeout expires. <add> publishNext(subscriber, 100, "a"); // Should be skipped <add> publishNext(subscriber, 200, "b"); // Should be skipped <add> publishNext(subscriber, 300, "c"); // Should be skipped <add> publishNext(subscriber, 400, "d"); // Should be skipped <add> publishNext(subscriber, 500, "e"); // Should be skipped <add> publishNext(subscriber, 600, "f"); // Should be skipped <add> publishNext(subscriber, 700, "g"); // Should be skipped <add> publishNext(subscriber, 800, "h"); // Should be skipped <add> publishCompleted(subscriber, 900); // Should be published as soon as the timeout expires. <ide> } <ide> }); <ide> <ide> Flowable<String> sampled = source.debounce(200, TimeUnit.MILLISECONDS, scheduler); <del> sampled.subscribe(observer); <add> sampled.subscribe(Subscriber); <ide> <ide> scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); <del> InOrder inOrder = inOrder(observer); <del> inOrder.verify(observer, times(0)).onNext(anyString()); <add> InOrder inOrder = inOrder(Subscriber); <add> inOrder.verify(Subscriber, times(0)).onNext(anyString()); <ide> scheduler.advanceTimeTo(1000, TimeUnit.MILLISECONDS); <del> inOrder.verify(observer, times(1)).onComplete(); <add> inOrder.verify(Subscriber, times(1)).onComplete(); <ide> inOrder.verifyNoMoreInteractions(); <ide> } <ide> <ide> @Test <ide> public void testDebounceWithError() { <ide> Flowable<String> source = Flowable.unsafeCreate(new Publisher<String>() { <ide> @Override <del> public void subscribe(Subscriber<? super String> observer) { <del> observer.onSubscribe(new BooleanSubscription()); <add> public void subscribe(Subscriber<? super String> subscriber) { <add> subscriber.onSubscribe(new BooleanSubscription()); <ide> Exception error = new TestException(); <del> publishNext(observer, 100, "one"); // Should be published since "two" will arrive after the timeout expires. <del> publishNext(observer, 600, "two"); // Should be skipped since onError will arrive before the timeout expires. <del> publishError(observer, 700, error); // Should be published as soon as the timeout expires. <add> publishNext(subscriber, 100, "one"); // Should be published since "two" will arrive after the timeout expires. <add> publishNext(subscriber, 600, "two"); // Should be skipped since onError will arrive before the timeout expires. <add> publishError(subscriber, 700, error); // Should be published as soon as the timeout expires. <ide> } <ide> }); <ide> <ide> Flowable<String> sampled = source.debounce(400, TimeUnit.MILLISECONDS, scheduler); <del> sampled.subscribe(observer); <add> sampled.subscribe(Subscriber); <ide> <ide> scheduler.advanceTimeTo(0, TimeUnit.MILLISECONDS); <del> InOrder inOrder = inOrder(observer); <add> InOrder inOrder = inOrder(Subscriber); <ide> // 100 + 400 means it triggers at 500 <ide> scheduler.advanceTimeTo(500, TimeUnit.MILLISECONDS); <del> inOrder.verify(observer).onNext("one"); <add> inOrder.verify(Subscriber).onNext("one"); <ide> scheduler.advanceTimeTo(701, TimeUnit.MILLISECONDS); <del> inOrder.verify(observer).onError(any(TestException.class)); <add> inOrder.verify(Subscriber).onError(any(TestException.class)); <ide> inOrder.verifyNoMoreInteractions(); <ide> } <ide> <del> private <T> void publishCompleted(final Subscriber<T> observer, long delay) { <add> private <T> void publishCompleted(final Subscriber<T> subscriber, long delay) { <ide> innerScheduler.schedule(new Runnable() { <ide> @Override <ide> public void run() { <del> observer.onComplete(); <add> subscriber.onComplete(); <ide> } <ide> }, delay, TimeUnit.MILLISECONDS); <ide> } <ide> <del> private <T> void publishError(final Subscriber<T> observer, long delay, final Exception error) { <add> private <T> void publishError(final Subscriber<T> subscriber, long delay, final Exception error) { <ide> innerScheduler.schedule(new Runnable() { <ide> @Override <ide> public void run() { <del> observer.onError(error); <add> subscriber.onError(error); <ide> } <ide> }, delay, TimeUnit.MILLISECONDS); <ide> } <ide> <del> private <T> void publishNext(final Subscriber<T> observer, final long delay, final T value) { <add> private <T> void publishNext(final Subscriber<T> subscriber, final long delay, final T value) { <ide> innerScheduler.schedule(new Runnable() { <ide> @Override <ide> public void run() { <del> observer.onNext(value); <add> subscriber.onNext(value); <ide> } <ide> }, delay, TimeUnit.MILLISECONDS); <ide> } <ide> public void badSource() { <ide> try { <ide> new Flowable<Integer>() { <ide> @Override <del> protected void subscribeActual(Subscriber<? super Integer> observer) { <del> observer.onSubscribe(new BooleanSubscription()); <del> observer.onComplete(); <del> observer.onNext(1); <del> observer.onError(new TestException()); <del> observer.onComplete(); <add> protected void subscribeActual(Subscriber<? super Integer> subscriber) { <add> subscriber.onSubscribe(new BooleanSubscription()); <add> subscriber.onComplete(); <add> subscriber.onNext(1); <add> subscriber.onError(new TestException()); <add> subscriber.onComplete(); <ide> } <ide> } <ide> .debounce(1, TimeUnit.SECONDS, new TestScheduler()) <ide> public void backpressureNoRequestTimed() { <ide> .awaitDone(5, TimeUnit.SECONDS) <ide> .assertFailure(MissingBackpressureException.class); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) throws Exception { <add> return o.debounce(Functions.justFunction(Flowable.never())); <add> } <add> }); <add> } <add> <add> @Test <add> public void disposeInOnNext() { <add> final TestSubscriber<Integer> to = new TestSubscriber<Integer>(); <add> <add> BehaviorProcessor.createDefault(1) <add> .debounce(new Function<Integer, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Integer o) throws Exception { <add> to.cancel(); <add> return Flowable.never(); <add> } <add> }) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void disposedInOnComplete() { <add> final TestSubscriber<Integer> to = new TestSubscriber<Integer>(); <add> <add> new Flowable<Integer>() { <add> @Override <add> protected void subscribeActual(Subscriber<? super Integer> subscriber) { <add> subscriber.onSubscribe(new BooleanSubscription()); <add> to.cancel(); <add> subscriber.onComplete(); <add> } <add> } <add> .debounce(Functions.justFunction(Flowable.never())) <add> .subscribeWith(to) <add> .assertEmpty(); <add> } <add> <add> @Test <add> public void emitLate() { <add> final AtomicReference<Subscriber<? super Integer>> ref = new AtomicReference<Subscriber<? super Integer>>(); <add> <add> TestSubscriber<Integer> to = Flowable.range(1, 2) <add> .debounce(new Function<Integer, Flowable<Integer>>() { <add> @Override <add> public Flowable<Integer> apply(Integer o) throws Exception { <add> if (o != 1) { <add> return Flowable.never(); <add> } <add> return new Flowable<Integer>() { <add> @Override <add> protected void subscribeActual(Subscriber<? super Integer> subscriber) { <add> subscriber.onSubscribe(new BooleanSubscription()); <add> ref.set(subscriber); <add> } <add> }; <add> } <add> }) <add> .test(); <add> <add> ref.get().onNext(1); <add> <add> to <add> .assertResult(2); <add> } <add> <add> @Test <add> public void badRequestReported() { <add> TestHelper.assertBadRequestReported(Flowable.never().debounce(Functions.justFunction(Flowable.never()))); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableFilterTest.java <ide> public class FlowableFilterTest { <ide> @Test <ide> public void testFilter() { <ide> Flowable<String> w = Flowable.just("one", "two", "three"); <del> Flowable<String> Flowable = w.filter(new Predicate<String>() { <add> Flowable<String> flowable = w.filter(new Predicate<String>() { <ide> <ide> @Override <ide> public boolean test(String t1) { <ide> return t1.equals("two"); <ide> } <ide> }); <ide> <del> Subscriber<String> Subscriber = TestHelper.mockSubscriber(); <add> Subscriber<String> subscriber = TestHelper.mockSubscriber(); <ide> <del> Flowable.subscribe(Subscriber); <add> flowable.subscribe(subscriber); <ide> <del> verify(Subscriber, Mockito.never()).onNext("one"); <del> verify(Subscriber, times(1)).onNext("two"); <del> verify(Subscriber, Mockito.never()).onNext("three"); <del> verify(Subscriber, Mockito.never()).onError(any(Throwable.class)); <del> verify(Subscriber, times(1)).onComplete(); <add> verify(subscriber, Mockito.never()).onNext("one"); <add> verify(subscriber, times(1)).onNext("two"); <add> verify(subscriber, Mockito.never()).onNext("three"); <add> verify(subscriber, Mockito.never()).onError(any(Throwable.class)); <add> verify(subscriber, times(1)).onComplete(); <ide> } <ide> <ide> /** <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupByTest.java <ide> public V remove(Object key) { <ide> @Override <ide> public void putAll(Map<? extends K, ? extends V> m) { <ide> for (Entry<? extends K, ? extends V> entry: m.entrySet()) { <del> put(entry.getKey(), entry.getValue()); <add> put(entry.getKey(), entry.getValue()); <ide> } <ide> } <ide> <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableGroupJoinTest.java <ide> */ <ide> package io.reactivex.internal.operators.flowable; <ide> <add>import static org.junit.Assert.*; <ide> import static org.mockito.ArgumentMatchers.any; <ide> import static org.mockito.Mockito.*; <ide> <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions; <add>import io.reactivex.internal.operators.flowable.FlowableGroupJoin.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> public Flowable<Object> apply(Object r, Flowable<Object> l) throws Exception { <ide> <ide> to.assertResult(2); <ide> } <add> <add> @Test <add> public void leftRightState() { <add> JoinSupport js = mock(JoinSupport.class); <add> <add> LeftRightSubscriber o = new LeftRightSubscriber(js, false); <add> <add> assertFalse(o.isDisposed()); <add> <add> o.onNext(1); <add> o.onNext(2); <add> <add> o.dispose(); <add> <add> assertTrue(o.isDisposed()); <add> <add> verify(js).innerValue(false, 1); <add> verify(js).innerValue(false, 2); <add> } <add> <add> @Test <add> public void leftRightEndState() { <add> JoinSupport js = mock(JoinSupport.class); <add> <add> LeftRightEndSubscriber o = new LeftRightEndSubscriber(js, false, 0); <add> <add> assertFalse(o.isDisposed()); <add> <add> o.onNext(1); <add> o.onNext(2); <add> <add> assertTrue(o.isDisposed()); <add> <add> verify(js).innerClose(false, o); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableHideTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.flowable; <add> <add>import static org.junit.Assert.assertFalse; <add>import static org.mockito.ArgumentMatchers.any; <add>import static org.mockito.Mockito.*; <add> <add>import org.junit.Test; <add>import org.reactivestreams.Subscriber; <add> <add>import io.reactivex.*; <add>import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <add>import io.reactivex.processors.PublishProcessor; <add> <add>public class FlowableHideTest { <add> @Test <add> public void testHiding() { <add> PublishProcessor<Integer> src = PublishProcessor.create(); <add> <add> Flowable<Integer> dst = src.hide(); <add> <add> assertFalse(dst instanceof PublishProcessor); <add> <add> Subscriber<Object> o = TestHelper.mockSubscriber(); <add> <add> dst.subscribe(o); <add> <add> src.onNext(1); <add> src.onComplete(); <add> <add> verify(o).onNext(1); <add> verify(o).onComplete(); <add> verify(o, never()).onError(any(Throwable.class)); <add> } <add> <add> @Test <add> public void testHidingError() { <add> PublishProcessor<Integer> src = PublishProcessor.create(); <add> <add> Flowable<Integer> dst = src.hide(); <add> <add> assertFalse(dst instanceof PublishProcessor); <add> <add> Subscriber<Object> o = TestHelper.mockSubscriber(); <add> <add> dst.subscribe(o); <add> <add> src.onError(new TestException()); <add> <add> verify(o, never()).onNext(any()); <add> verify(o, never()).onComplete(); <add> verify(o).onError(any(TestException.class)); <add> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) <add> throws Exception { <add> return o.hide(); <add> } <add> }); <add> } <add> <add> @Test <add> public void disposed() { <add> TestHelper.checkDisposed(PublishProcessor.create().hide()); <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableIgnoreElementsTest.java <ide> public void dispose() { <ide> <ide> TestHelper.checkDisposed(Flowable.just(1).ignoreElements().toFlowable()); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) <add> throws Exception { <add> return o.ignoreElements().toFlowable(); <add> } <add> }); <add> <add> TestHelper.checkDoubleOnSubscribeFlowableToCompletable(new Function<Flowable<Object>, Completable>() { <add> @Override <add> public Completable apply(Flowable<Object> o) <add> throws Exception { <add> return o.ignoreElements(); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableIntervalTest.java <ide> <ide> import org.junit.Test; <ide> <del>import io.reactivex.Flowable; <add>import io.reactivex.*; <add>import io.reactivex.internal.operators.flowable.FlowableInterval.IntervalSubscriber; <ide> import io.reactivex.schedulers.Schedulers; <add>import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public class FlowableIntervalTest { <ide> <ide> public void cancel() { <ide> .test() <ide> .assertResult(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); <ide> } <add> <add> @Test <add> public void badRequest() { <add> TestHelper.assertBadRequestReported(Flowable.interval(1, TimeUnit.MILLISECONDS, Schedulers.trampoline())); <add> } <add> <add> @Test <add> public void cancelledOnRun() { <add> TestSubscriber<Long> ts = new TestSubscriber<Long>(); <add> IntervalSubscriber is = new IntervalSubscriber(ts); <add> ts.onSubscribe(is); <add> <add> is.cancel(); <add> <add> is.run(); <add> <add> ts.assertEmpty(); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeDelayErrorTest.java <ide> public void testMergeFlowableOfFlowables() { <ide> final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); <ide> final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); <ide> <del> Flowable<Flowable<String>> FlowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { <add> Flowable<Flowable<String>> flowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super Flowable<String>> observer) { <ide> public void subscribe(Subscriber<? super Flowable<String>> observer) { <ide> } <ide> <ide> }); <del> Flowable<String> m = Flowable.mergeDelayError(FlowableOfFlowables); <add> Flowable<String> m = Flowable.mergeDelayError(flowableOfFlowables); <ide> m.subscribe(stringObserver); <ide> <ide> verify(stringObserver, never()).onError(any(Throwable.class)); <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableMergeTest.java <ide> public void testMergeFlowableOfFlowables() { <ide> final Flowable<String> o1 = Flowable.unsafeCreate(new TestSynchronousFlowable()); <ide> final Flowable<String> o2 = Flowable.unsafeCreate(new TestSynchronousFlowable()); <ide> <del> Flowable<Flowable<String>> FlowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { <add> Flowable<Flowable<String>> flowableOfFlowables = Flowable.unsafeCreate(new Publisher<Flowable<String>>() { <ide> <ide> @Override <ide> public void subscribe(Subscriber<? super Flowable<String>> observer) { <ide> public void subscribe(Subscriber<? super Flowable<String>> observer) { <ide> } <ide> <ide> }); <del> Flowable<String> m = Flowable.merge(FlowableOfFlowables); <add> Flowable<String> m = Flowable.merge(flowableOfFlowables); <ide> m.subscribe(stringObserver); <ide> <ide> verify(stringObserver, never()).onError(any(Throwable.class)); <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRepeatTest.java <ide> public class FlowableRepeatTest { <ide> <ide> @Test(timeout = 2000) <ide> public void testRepetition() { <del> int NUM = 10; <add> int num = 10; <ide> final AtomicInteger count = new AtomicInteger(); <ide> int value = Flowable.unsafeCreate(new Publisher<Integer>() { <ide> <ide> public void subscribe(final Subscriber<? super Integer> o) { <ide> o.onComplete(); <ide> } <ide> }).repeat().subscribeOn(Schedulers.computation()) <del> .take(NUM).blockingLast(); <add> .take(num).blockingLast(); <ide> <del> assertEquals(NUM, value); <add> assertEquals(num, value); <ide> } <ide> <ide> @Test(timeout = 2000) <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableReplayTest.java <ide> public ConnectableFlowable<Object> call() throws Exception { <ide> .test() <ide> .assertFailure(TestException.class); <ide> } <add> <add> @Test <add> public void badRequest() { <add> TestHelper.assertBadRequestReported( <add> Flowable.never() <add> .replay() <add> ); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableRetryTest.java <ide> public static class Tuple { <ide> @Test <ide> public void testRetryIndefinitely() { <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> int NUM_RETRIES = 20; <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> int numRetries = 20; <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> origin.retry().subscribe(new TestSubscriber<String>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testRetryIndefinitely() { <ide> @Test <ide> public void testSchedulingNotificationHandler() { <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> int NUM_RETRIES = 2; <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> int numRetries = 2; <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> TestSubscriber<String> subscriber = new TestSubscriber<String>(observer); <ide> origin.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() { <ide> @Override <ide> public void accept(Throwable e) { <ide> subscriber.awaitTerminalEvent(); <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void accept(Throwable e) { <ide> @Test <ide> public void testOnNextFromNotificationHandler() { <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> int NUM_RETRIES = 2; <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> int numRetries = 2; <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> origin.retryWhen(new Function<Flowable<? extends Throwable>, Flowable<Object>>() { <ide> @Override <ide> public Flowable<Object> apply(Flowable<? extends Throwable> t1) { <ide> public Integer apply(Throwable t1) { <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testOriginFails() { <ide> <ide> @Test <ide> public void testRetryFail() { <del> int NUM_RETRIES = 1; <del> int NUM_FAILURES = 2; <add> int numRetries = 1; <add> int numFailures = 2; <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); <del> origin.retry(NUM_RETRIES).subscribe(observer); <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); <add> origin.retry(numRetries).subscribe(observer); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 2 attempts (first time fail, second time (1st retry) fail) <del> inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); <ide> // should only retry once, fail again and emit onError <ide> inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); <ide> // no success <ide> public void testRetryFail() { <ide> <ide> @Test <ide> public void testRetrySuccess() { <del> int NUM_FAILURES = 1; <add> int numFailures = 1; <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); <ide> origin.retry(3).subscribe(observer); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testRetrySuccess() { <ide> <ide> @Test <ide> public void testInfiniteRetry() { <del> int NUM_FAILURES = 20; <add> int numFailures = 20; <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numFailures)); <ide> origin.retry().subscribe(observer); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testTimeoutWithRetry() { <ide> public void testRetryWithBackpressure() throws InterruptedException { <ide> final int NUM_LOOPS = 1; <ide> for (int j = 0;j < NUM_LOOPS; j++) { <del> final int NUM_RETRIES = Flowable.bufferSize() * 2; <add> final int numRetries = Flowable.bufferSize() * 2; <ide> for (int i = 0; i < 400; i++) { <ide> Subscriber<String> observer = TestHelper.mockSubscriber(); <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> TestSubscriber<String> ts = new TestSubscriber<String>(observer); <ide> origin.retry().observeOn(Schedulers.computation()).subscribe(ts); <ide> ts.awaitTerminalEvent(5, TimeUnit.SECONDS); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should have no errors <ide> verify(observer, never()).onError(any(Throwable.class)); <del> // should show NUM_RETRIES attempts <del> inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); <add> // should show numRetries attempts <add> inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); <ide> // should have a single success <ide> inOrder.verify(observer, times(1)).onNext("onSuccessOnly"); <ide> // should have a single successful onComplete <ide> public void testRetryWithBackpressure() throws InterruptedException { <ide> @Test//(timeout = 15000) <ide> public void testRetryWithBackpressureParallel() throws InterruptedException { <ide> final int NUM_LOOPS = 1; <del> final int NUM_RETRIES = Flowable.bufferSize() * 2; <add> final int numRetries = Flowable.bufferSize() * 2; <ide> int ncpu = Runtime.getRuntime().availableProcessors(); <ide> ExecutorService exec = Executors.newFixedThreadPool(Math.max(ncpu / 2, 2)); <ide> try { <ide> public void testRetryWithBackpressureParallel() throws InterruptedException { <ide> public void run() { <ide> final AtomicInteger nexts = new AtomicInteger(); <ide> try { <del> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> Flowable<String> origin = Flowable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> TestSubscriber<String> ts = new TestSubscriber<String>(); <ide> origin.retry() <ide> .observeOn(Schedulers.computation()).subscribe(ts); <ide> ts.awaitTerminalEvent(2500, TimeUnit.MILLISECONDS); <ide> List<String> onNextEvents = new ArrayList<String>(ts.values()); <del> if (onNextEvents.size() != NUM_RETRIES + 2) { <add> if (onNextEvents.size() != numRetries + 2) { <ide> for (Throwable t : ts.errors()) { <ide> onNextEvents.add(t.toString()); <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSampleTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.*; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.processors.*; <ide> import io.reactivex.schedulers.*; <ide> public void run() { <ide> ts.assertResult(1); <ide> } <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) <add> throws Exception { <add> return o.sample(1, TimeUnit.SECONDS); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipLastTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.schedulers.Schedulers; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public void error() { <ide> .assertFailure(TestException.class); <ide> } <ide> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) <add> throws Exception { <add> return o.skipLast(1); <add> } <add> }); <add> } <add> <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableSkipTest.java <ide> import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <del>import io.reactivex.functions.LongConsumer; <add>import io.reactivex.functions.*; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public class FlowableSkipTest { <ide> public void dispose() { <ide> TestHelper.checkDisposed(Flowable.just(1).skip(2)); <ide> } <ide> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) <add> throws Exception { <add> return o.skip(1); <add> } <add> }); <add> } <add> <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeTest.java <ide> public Flowable<Object> apply(Flowable<Object> o) throws Exception { <ide> }); <ide> } <ide> <add> <add> @Test <add> public void badRequest() { <add> TestHelper.assertBadRequestReported(Flowable.never().take(1)); <add> } <add> <add> @Test <add> public void requestRace() { <add> for (int i = 0; i < TestHelper.RACE_LONG_LOOPS; i++) { <add> <add> final TestSubscriber<Integer> ts = Flowable.range(1, 2).take(2).test(0L); <add> <add> Runnable r1 = new Runnable() { <add> @Override <add> public void run() { <add> ts.request(1); <add> } <add> }; <add> <add> TestHelper.race(r1, r1); <add> <add> ts.assertResult(1, 2); <add> } <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTakeUntilTest.java <ide> import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public void testBackpressure() { <ide> public void dispose() { <ide> TestHelper.checkDisposed(PublishProcessor.create().takeUntil(Flowable.never())); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Integer>, Flowable<Integer>>() { <add> @Override <add> public Flowable<Integer> apply(Flowable<Integer> c) throws Exception { <add> return c.takeUntil(Flowable.never()); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableTimeIntervalTest.java <ide> <ide> import org.junit.*; <ide> import org.mockito.InOrder; <del>import org.reactivestreams.Subscriber; <add>import org.reactivestreams.*; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <ide> public void error() { <ide> .assertFailure(TestException.class); <ide> } <ide> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<Timed<Object>>>() { <add> @Override <add> public Publisher<Timed<Object>> apply(Flowable<Object> f) <add> throws Exception { <add> return f.timeInterval(); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableToListTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.processors.PublishProcessor; <ide> import io.reactivex.schedulers.Schedulers; <ide> public void run() { <ide> } <ide> } <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<List<Object>>>() { <add> @Override <add> public Flowable<List<Object>> apply(Flowable<Object> f) <add> throws Exception { <add> return f.toList().toFlowable(); <add> } <add> }); <add> TestHelper.checkDoubleOnSubscribeFlowableToSingle(new Function<Flowable<Object>, Single<List<Object>>>() { <add> @Override <add> public Single<List<Object>> apply(Flowable<Object> f) <add> throws Exception { <add> return f.toList(); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/flowable/FlowableUnsubscribeOnTest.java <ide> public class FlowableUnsubscribeOnTest { <ide> <ide> @Test(timeout = 5000) <ide> public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnSameThread() throws InterruptedException { <del> UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); <add> UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); <ide> try { <ide> final ThreadSubscription subscription = new ThreadSubscription(); <ide> final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); <ide> public void subscribe(Subscriber<? super Integer> t1) { <ide> }); <ide> <ide> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <del> w.subscribeOn(UI_EVENT_LOOP).observeOn(Schedulers.computation()) <del> .unsubscribeOn(UI_EVENT_LOOP) <add> w.subscribeOn(uiEventLoop).observeOn(Schedulers.computation()) <add> .unsubscribeOn(uiEventLoop) <ide> .take(2) <ide> .subscribe(ts); <ide> <ide> public void subscribe(Subscriber<? super Integer> t1) { <ide> <ide> System.out.println("unsubscribeThread: " + unsubscribeThread); <ide> System.out.println("subscribeThread.get(): " + subscribeThread.get()); <del> assertTrue(unsubscribeThread == UI_EVENT_LOOP.getThread()); <add> assertTrue(unsubscribeThread == uiEventLoop.getThread()); <ide> <ide> ts.assertValues(1, 2); <ide> ts.assertTerminated(); <ide> } finally { <del> UI_EVENT_LOOP.shutdown(); <add> uiEventLoop.shutdown(); <ide> } <ide> } <ide> <ide> @Test(timeout = 5000) <ide> public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnDifferentThreads() throws InterruptedException { <del> UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); <add> UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); <ide> try { <ide> final ThreadSubscription subscription = new ThreadSubscription(); <ide> final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); <ide> public void subscribe(Subscriber<? super Integer> t1) { <ide> <ide> TestSubscriber<Integer> observer = new TestSubscriber<Integer>(); <ide> w.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.computation()) <del> .unsubscribeOn(UI_EVENT_LOOP) <add> .unsubscribeOn(uiEventLoop) <ide> .take(2) <ide> .subscribe(observer); <ide> <ide> public void subscribe(Subscriber<? super Integer> t1) { <ide> assertNotSame(Thread.currentThread(), subscribeThread.get()); <ide> // True for Schedulers.newThread() <ide> <del> System.out.println("UI Thread: " + UI_EVENT_LOOP.getThread()); <add> System.out.println("UI Thread: " + uiEventLoop.getThread()); <ide> System.out.println("unsubscribeThread: " + unsubscribeThread); <ide> System.out.println("subscribeThread.get(): " + subscribeThread.get()); <del> assertSame(unsubscribeThread, UI_EVENT_LOOP.getThread()); <add> assertSame(unsubscribeThread, uiEventLoop.getThread()); <ide> <ide> observer.assertValues(1, 2); <ide> observer.assertTerminated(); <ide> } finally { <del> UI_EVENT_LOOP.shutdown(); <add> uiEventLoop.shutdown(); <ide> } <ide> } <ide> <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeAmbTest.java <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.disposables.Disposables; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> public void run() { <ide> } <ide> } <ide> } <add> <add> @Test <add> public void disposeNoFurtherSignals() { <add> @SuppressWarnings("unchecked") <add> TestObserver<Integer> to = Maybe.ambArray(new Maybe<Integer>() { <add> @Override <add> protected void subscribeActual( <add> MaybeObserver<? super Integer> observer) { <add> observer.onSubscribe(Disposables.empty()); <add> observer.onSuccess(1); <add> observer.onSuccess(2); <add> observer.onComplete(); <add> } <add> }, Maybe.<Integer>never()) <add> .test(); <add> <add> to.cancel(); <add> <add> to.assertResult(1); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeDelayOtherTest.java <ide> import java.util.List; <ide> <ide> import org.junit.Test; <add>import org.reactivestreams.Subscriber; <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.Function; <add>import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.processors.PublishProcessor; <ide> <ide> public MaybeSource<Integer> apply(Completable c) throws Exception { <ide> public void withOtherPublisherDispose() { <ide> TestHelper.checkDisposed(Maybe.just(1).delay(Flowable.just(1))); <ide> } <add> <add> @Test <add> public void withOtherPublisherDoubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Integer>, MaybeSource<Integer>>() { <add> @Override <add> public MaybeSource<Integer> apply(Maybe<Integer> c) throws Exception { <add> return c.delay(Flowable.never()); <add> } <add> }); <add> } <add> <add> @Test <add> public void otherPublisherNextSlipsThrough() { <add> Maybe.just(1).delay(new Flowable<Integer>() { <add> @Override <add> protected void subscribeActual(Subscriber<? super Integer> s) { <add> s.onSubscribe(new BooleanSubscription()); <add> s.onNext(1); <add> s.onNext(2); <add> } <add> }) <add> .test() <add> .assertResult(1); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromActionTest.java <ide> package io.reactivex.internal.operators.maybe; <ide> <ide> import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <ide> <ide> import java.util.List; <ide> import java.util.concurrent.*; <ide> public void run() throws Exception { <ide> RxJavaPlugins.reset(); <ide> } <ide> } <add> <add> @Test <add> public void disposedUpfront() throws Exception { <add> Action run = mock(Action.class); <add> <add> Maybe.fromAction(run) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<Object>(); <add> <add> Maybe.fromAction(new Action() { <add> @Override <add> public void run() throws Exception { <add> to.dispose(); <add> } <add> }) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromFutureTest.java <ide> <ide> package io.reactivex.internal.operators.maybe; <ide> <add>import static org.junit.Assert.assertTrue; <add> <ide> import java.util.concurrent.*; <ide> <ide> import org.junit.Test; <ide> <ide> import io.reactivex.Maybe; <add>import io.reactivex.exceptions.TestException; <ide> import io.reactivex.internal.functions.Functions; <add>import io.reactivex.observers.TestObserver; <add>import io.reactivex.schedulers.Schedulers; <ide> <ide> public class MaybeFromFutureTest { <ide> <ide> public void interrupt() { <ide> Maybe.fromFuture(ft, 1, TimeUnit.MILLISECONDS).test() <ide> .assertFailure(InterruptedException.class); <ide> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<Object>(); <add> <add> FutureTask<Object> ft = new FutureTask<Object>(new Runnable() { <add> @Override <add> public void run() { <add> to.cancel(); <add> } <add> }, null); <add> <add> Schedulers.single().scheduleDirect(ft, 100, TimeUnit.MILLISECONDS); <add> <add> Maybe.fromFuture(ft) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void cancelAndCrashWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<Object>(); <add> <add> FutureTask<Object> ft = new FutureTask<Object>(new Runnable() { <add> @Override <add> public void run() { <add> to.cancel(); <add> throw new TestException(); <add> } <add> }, null); <add> <add> Schedulers.single().scheduleDirect(ft, 100, TimeUnit.MILLISECONDS); <add> <add> Maybe.fromFuture(ft) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void futureNull() { <add> FutureTask<Object> ft = new FutureTask<Object>(new Runnable() { <add> @Override <add> public void run() { <add> } <add> }, null); <add> <add> Schedulers.single().scheduleDirect(ft, 100, TimeUnit.MILLISECONDS); <add> <add> Maybe.fromFuture(ft) <add> .test() <add> .assertResult(); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeFromRunnableTest.java <ide> package io.reactivex.internal.operators.maybe; <ide> <ide> import static org.junit.Assert.*; <add>import static org.mockito.Mockito.*; <ide> <ide> import java.util.List; <ide> import java.util.concurrent.*; <ide> public void run() { <ide> RxJavaPlugins.reset(); <ide> } <ide> } <add> <add> @Test <add> public void disposedUpfront() { <add> Runnable run = mock(Runnable.class); <add> <add> Maybe.fromRunnable(run) <add> .test(true) <add> .assertEmpty(); <add> <add> verify(run, never()).run(); <add> } <add> <add> @Test <add> public void cancelWhileRunning() { <add> final TestObserver<Object> to = new TestObserver<Object>(); <add> <add> Maybe.fromRunnable(new Runnable() { <add> @Override <add> public void run() { <add> to.dispose(); <add> } <add> }) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeMapTest.java <add>/** <add> * Copyright (c) 2016-present, RxJava Contributors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in <add> * compliance with the License. You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software distributed under the License is <add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See <add> * the License for the specific language governing permissions and limitations under the License. <add> */ <add> <add>package io.reactivex.internal.operators.maybe; <add> <add>import org.junit.Test; <add> <add>import io.reactivex.*; <add>import io.reactivex.functions.Function; <add>import io.reactivex.internal.functions.Functions; <add> <add>public class MaybeMapTest { <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Object>, MaybeSource<Object>>() { <add> @Override <add> public MaybeSource<Object> apply(Maybe<Object> m) throws Exception { <add> return m.map(Functions.identity()); <add> } <add> }); <add> } <add>} <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDebounceTest.java <ide> <ide> import java.util.List; <ide> import java.util.concurrent.TimeUnit; <add>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.junit.*; <ide> import org.mockito.InOrder; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.schedulers.TestScheduler; <del>import io.reactivex.subjects.PublishSubject; <add>import io.reactivex.subjects.*; <ide> <ide> public class ObservableDebounceTest { <ide> <ide> public void debounceWithEmpty() { <ide> .test() <ide> .assertResult(1); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() { <add> @Override <add> public Observable<Object> apply(Observable<Object> o) throws Exception { <add> return o.debounce(Functions.justFunction(Observable.never())); <add> } <add> }); <add> } <add> <add> @Test <add> public void disposeInOnNext() { <add> final TestObserver<Integer> to = new TestObserver<Integer>(); <add> <add> BehaviorSubject.createDefault(1) <add> .debounce(new Function<Integer, ObservableSource<Object>>() { <add> @Override <add> public ObservableSource<Object> apply(Integer o) throws Exception { <add> to.cancel(); <add> return Observable.never(); <add> } <add> }) <add> .subscribeWith(to) <add> .assertEmpty(); <add> <add> assertTrue(to.isDisposed()); <add> } <add> <add> @Test <add> public void disposedInOnComplete() { <add> final TestObserver<Integer> to = new TestObserver<Integer>(); <add> <add> new Observable<Integer>() { <add> @Override <add> protected void subscribeActual(Observer<? super Integer> observer) { <add> observer.onSubscribe(Disposables.empty()); <add> to.cancel(); <add> observer.onComplete(); <add> } <add> } <add> .debounce(Functions.justFunction(Observable.never())) <add> .subscribeWith(to) <add> .assertEmpty(); <add> } <add> <add> @Test <add> public void emitLate() { <add> final AtomicReference<Observer<? super Integer>> ref = new AtomicReference<Observer<? super Integer>>(); <add> <add> TestObserver<Integer> to = Observable.range(1, 2) <add> .debounce(new Function<Integer, ObservableSource<Integer>>() { <add> @Override <add> public ObservableSource<Integer> apply(Integer o) throws Exception { <add> if (o != 1) { <add> return Observable.never(); <add> } <add> return new Observable<Integer>() { <add> @Override <add> protected void subscribeActual(Observer<? super Integer> observer) { <add> observer.onSubscribe(Disposables.empty()); <add> ref.set(observer); <add> } <add> }; <add> } <add> }) <add> .test(); <add> <add> ref.get().onNext(1); <add> <add> to <add> .assertResult(2); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableDoAfterNextTest.java <ide> import io.reactivex.internal.functions.Functions; <ide> import io.reactivex.internal.fuseable.QueueSubscription; <ide> import io.reactivex.observers.*; <del>import io.reactivex.processors.UnicastProcessor; <del>import io.reactivex.subscribers.*; <add>import io.reactivex.subjects.UnicastSubject; <ide> <ide> public class ObservableDoAfterNextTest { <ide> <ide> public void just() { <ide> assertEquals(Arrays.asList(1, -1), values); <ide> } <ide> <add> @Test <add> public void justHidden() { <add> Observable.just(1) <add> .hide() <add> .doAfterNext(afterNext) <add> .subscribeWith(ts) <add> .assertResult(1); <add> <add> assertEquals(Arrays.asList(1, -1), values); <add> } <add> <ide> @Test <ide> public void range() { <ide> Observable.range(1, 5) <ide> public void asyncFusedRejected() { <ide> <ide> @Test <ide> public void asyncFused() { <del> TestSubscriber<Integer> ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); <add> TestObserver<Integer> ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); <ide> <del> UnicastProcessor<Integer> up = UnicastProcessor.create(); <add> UnicastSubject<Integer> up = UnicastSubject.create(); <ide> <ide> TestHelper.emit(up, 1, 2, 3, 4, 5); <ide> <ide> up <ide> .doAfterNext(afterNext) <ide> .subscribe(ts0); <ide> <del> SubscriberFusion.assertFusion(ts0, QueueSubscription.ASYNC) <add> ObserverFusion.assertFusion(ts0, QueueSubscription.ASYNC) <ide> .assertResult(1, 2, 3, 4, 5); <ide> <ide> assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); <ide> public void asyncFusedRejectedConditional() { <ide> <ide> @Test <ide> public void asyncFusedConditional() { <del> TestSubscriber<Integer> ts0 = SubscriberFusion.newTest(QueueSubscription.ASYNC); <add> TestObserver<Integer> ts0 = ObserverFusion.newTest(QueueSubscription.ASYNC); <ide> <del> UnicastProcessor<Integer> up = UnicastProcessor.create(); <add> UnicastSubject<Integer> up = UnicastSubject.create(); <ide> <ide> TestHelper.emit(up, 1, 2, 3, 4, 5); <ide> <ide> public void asyncFusedConditional() { <ide> .filter(Functions.alwaysTrue()) <ide> .subscribe(ts0); <ide> <del> SubscriberFusion.assertFusion(ts0, QueueSubscription.ASYNC) <add> ObserverFusion.assertFusion(ts0, QueueSubscription.ASYNC) <ide> .assertResult(1, 2, 3, 4, 5); <ide> <ide> assertEquals(Arrays.asList(-1, -2, -3, -4, -5), values); <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableGroupJoinTest.java <ide> */ <ide> package io.reactivex.internal.operators.observable; <ide> <add>import static org.junit.Assert.*; <ide> import static org.mockito.ArgumentMatchers.any; <ide> import static org.mockito.Mockito.*; <ide> <ide> import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.*; <ide> import io.reactivex.internal.functions.Functions; <add>import io.reactivex.internal.operators.observable.ObservableGroupJoin.*; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.subjects.PublishSubject; <ide> public Observable<Object> apply(Object r, Observable<Object> l) throws Exception <ide> <ide> to.assertResult(2); <ide> } <add> <add> @Test <add> public void leftRightState() { <add> JoinSupport js = mock(JoinSupport.class); <add> <add> LeftRightObserver o = new LeftRightObserver(js, false); <add> <add> assertFalse(o.isDisposed()); <add> <add> o.onNext(1); <add> o.onNext(2); <add> <add> o.dispose(); <add> <add> assertTrue(o.isDisposed()); <add> <add> verify(js).innerValue(false, 1); <add> verify(js).innerValue(false, 2); <add> } <add> <add> @Test <add> public void leftRightEndState() { <add> JoinSupport js = mock(JoinSupport.class); <add> <add> LeftRightEndObserver o = new LeftRightEndObserver(js, false, 0); <add> <add> assertFalse(o.isDisposed()); <add> <add> o.onNext(1); <add> o.onNext(2); <add> <add> assertTrue(o.isDisposed()); <add> <add> verify(js).innerClose(false, o); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableIntervalTest.java <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.internal.operators.observable.ObservableInterval.IntervalObserver; <add>import io.reactivex.observers.TestObserver; <ide> import io.reactivex.schedulers.*; <ide> <ide> public class ObservableIntervalTest { <ide> public void cancel() { <ide> .test() <ide> .assertResult(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L); <ide> } <add> <add> @Test <add> public void cancelledOnRun() { <add> TestObserver<Long> ts = new TestObserver<Long>(); <add> IntervalObserver is = new IntervalObserver(ts); <add> ts.onSubscribe(is); <add> <add> is.dispose(); <add> <add> is.run(); <add> <add> ts.assertEmpty(); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservablePublishTest.java <ide> protected void subscribeActual(Observer<? super Integer> s) { <ide> <ide> assertTrue(bs.isDisposed()); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, ObservableSource<Object>>() { <add> @Override <add> public ObservableSource<Object> apply(final Observable<Object> o) <add> throws Exception { <add> return Observable.<Integer>never().publish(new Function<Observable<Integer>, ObservableSource<Object>>() { <add> @Override <add> public ObservableSource<Object> apply(Observable<Integer> v) <add> throws Exception { <add> return o; <add> } <add> }); <add> } <add> } <add> ); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRepeatTest.java <ide> public class ObservableRepeatTest { <ide> <ide> @Test(timeout = 2000) <ide> public void testRepetition() { <del> int NUM = 10; <add> int num = 10; <ide> final AtomicInteger count = new AtomicInteger(); <ide> int value = Observable.unsafeCreate(new ObservableSource<Integer>() { <ide> <ide> public void subscribe(final Observer<? super Integer> o) { <ide> o.onComplete(); <ide> } <ide> }).repeat().subscribeOn(Schedulers.computation()) <del> .take(NUM).blockingLast(); <add> .take(num).blockingLast(); <ide> <del> assertEquals(NUM, value); <add> assertEquals(num, value); <ide> } <ide> <ide> @Test(timeout = 2000) <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableRetryTest.java <ide> public static class Tuple { <ide> @Test <ide> public void testRetryIndefinitely() { <ide> Observer<String> observer = TestHelper.mockObserver(); <del> int NUM_RETRIES = 20; <del> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> int numRetries = 20; <add> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> origin.retry().subscribe(new TestObserver<String>(observer)); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testRetryIndefinitely() { <ide> @Test <ide> public void testSchedulingNotificationHandler() { <ide> Observer<String> observer = TestHelper.mockObserver(); <del> int NUM_RETRIES = 2; <del> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> int numRetries = 2; <add> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> TestObserver<String> to = new TestObserver<String>(observer); <ide> origin.retryWhen(new Function<Observable<? extends Throwable>, Observable<Object>>() { <ide> @Override <ide> public void accept(Throwable e) { <ide> to.awaitTerminalEvent(); <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void accept(Throwable e) { <ide> @Test <ide> public void testOnNextFromNotificationHandler() { <ide> Observer<String> observer = TestHelper.mockObserver(); <del> int NUM_RETRIES = 2; <del> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(NUM_RETRIES)); <add> int numRetries = 2; <add> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(numRetries)); <ide> origin.retryWhen(new Function<Observable<? extends Throwable>, Observable<Object>>() { <ide> @Override <ide> public Observable<Object> apply(Observable<? extends Throwable> t1) { <ide> public Integer apply(Throwable t1) { <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(NUM_RETRIES + 1)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(numRetries + 1)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testOriginFails() { <ide> <ide> @Test <ide> public void testRetryFail() { <del> int NUM_RETRIES = 1; <del> int NUM_FAILURES = 2; <add> int numRetries = 1; <add> int numFailures = 2; <ide> Observer<String> observer = TestHelper.mockObserver(); <del> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); <del> origin.retry(NUM_RETRIES).subscribe(observer); <add> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(numFailures)); <add> origin.retry(numRetries).subscribe(observer); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 2 attempts (first time fail, second time (1st retry) fail) <del> inOrder.verify(observer, times(1 + NUM_RETRIES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numRetries)).onNext("beginningEveryTime"); <ide> // should only retry once, fail again and emit onError <ide> inOrder.verify(observer, times(1)).onError(any(RuntimeException.class)); <ide> // no success <ide> public void testRetryFail() { <ide> <ide> @Test <ide> public void testRetrySuccess() { <del> int NUM_FAILURES = 1; <add> int numFailures = 1; <ide> Observer<String> observer = TestHelper.mockObserver(); <del> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); <add> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(numFailures)); <ide> origin.retry(3).subscribe(observer); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide> public void testRetrySuccess() { <ide> <ide> @Test <ide> public void testInfiniteRetry() { <del> int NUM_FAILURES = 20; <add> int numFailures = 20; <ide> Observer<String> observer = TestHelper.mockObserver(); <del> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(NUM_FAILURES)); <add> Observable<String> origin = Observable.unsafeCreate(new FuncWithErrors(numFailures)); <ide> origin.retry().subscribe(observer); <ide> <ide> InOrder inOrder = inOrder(observer); <ide> // should show 3 attempts <del> inOrder.verify(observer, times(1 + NUM_FAILURES)).onNext("beginningEveryTime"); <add> inOrder.verify(observer, times(1 + numFailures)).onNext("beginningEveryTime"); <ide> // should have no errors <ide> inOrder.verify(observer, never()).onError(any(Throwable.class)); <ide> // should have a single success <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSampleTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.*; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.schedulers.*; <ide> import io.reactivex.subjects.PublishSubject; <ide> public void run() { <ide> } <ide> } <ide> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() { <add> @Override <add> public Observable<Object> apply(Observable<Object> o) <add> throws Exception { <add> return o.sample(1, TimeUnit.SECONDS); <add> } <add> }); <add> } <add> <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSkipLastTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.schedulers.Schedulers; <ide> <ide> public void error() { <ide> .test() <ide> .assertFailure(TestException.class); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() { <add> @Override <add> public Observable<Object> apply(Observable<Object> o) <add> throws Exception { <add> return o.skipLast(1); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableSkipTest.java <ide> import org.junit.Test; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.observers.TestObserver; <ide> <ide> public class ObservableSkipTest { <ide> public void testRequestOverflowDoesNotOccur() { <ide> public void dispose() { <ide> TestHelper.checkDisposed(Observable.just(1).skip(2)); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Object>>() { <add> @Override <add> public Observable<Object> apply(Observable<Object> o) <add> throws Exception { <add> return o.skip(1); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTakeUntilTest.java <ide> <ide> import io.reactivex.*; <ide> import io.reactivex.disposables.Disposable; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.subjects.PublishSubject; <ide> <ide> public void testDownstreamUnsubscribes() { <ide> public void dispose() { <ide> TestHelper.checkDisposed(PublishSubject.create().takeUntil(Observable.never())); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Integer>, Observable<Integer>>() { <add> @Override <add> public Observable<Integer> apply(Observable<Integer> c) throws Exception { <add> return c.takeUntil(Observable.never()); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTimeIntervalTest.java <ide> public void error() { <ide> .test() <ide> .assertFailure(TestException.class); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<Timed<Object>>>() { <add> @Override <add> public Observable<Timed<Object>> apply(Observable<Object> f) <add> throws Exception { <add> return f.timeInterval(); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableTimerTest.java <ide> package io.reactivex.internal.operators.observable; <ide> <ide> import static org.junit.Assert.assertTrue; <add>import static org.mockito.ArgumentMatchers.*; <ide> import static org.mockito.Mockito.*; <ide> <ide> import java.util.List; <ide> import org.mockito.*; <ide> <ide> import io.reactivex.*; <add>import io.reactivex.disposables.Disposables; <ide> import io.reactivex.exceptions.TestException; <ide> import io.reactivex.functions.Function; <add>import io.reactivex.internal.operators.observable.ObservableTimer.TimerObserver; <ide> import io.reactivex.observables.ConnectableObservable; <ide> import io.reactivex.observers.*; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> public Long apply(Long v) throws Exception { <ide> } <ide> } <ide> <add> @Test <add> public void cancelledAndRun() { <add> TestObserver<Long> to = new TestObserver<Long>(); <add> to.onSubscribe(Disposables.empty()); <add> TimerObserver tm = new TimerObserver(to); <add> <add> tm.dispose(); <add> <add> tm.run(); <add> <add> to.assertEmpty(); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableToListTest.java <ide> import io.reactivex.Observable; <ide> import io.reactivex.Observer; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <ide> <ide> public class ObservableToListTest { <ide> <ide> public Collection<Integer> call() throws Exception { <ide> .assertFailure(NullPointerException.class) <ide> .assertErrorMessage("The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeObservable(new Function<Observable<Object>, Observable<List<Object>>>() { <add> @Override <add> public Observable<List<Object>> apply(Observable<Object> f) <add> throws Exception { <add> return f.toList().toObservable(); <add> } <add> }); <add> TestHelper.checkDoubleOnSubscribeObservableToSingle(new Function<Observable<Object>, Single<List<Object>>>() { <add> @Override <add> public Single<List<Object>> apply(Observable<Object> f) <add> throws Exception { <add> return f.toList(); <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/operators/observable/ObservableUnsubscribeOnTest.java <ide> public class ObservableUnsubscribeOnTest { <ide> <ide> @Test(timeout = 5000) <ide> public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnSameThread() throws InterruptedException { <del> UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); <add> UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); <ide> try { <ide> final ThreadSubscription subscription = new ThreadSubscription(); <ide> final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); <ide> public void subscribe(Observer<? super Integer> t1) { <ide> }); <ide> <ide> TestObserver<Integer> observer = new TestObserver<Integer>(); <del> w.subscribeOn(UI_EVENT_LOOP).observeOn(Schedulers.computation()) <del> .unsubscribeOn(UI_EVENT_LOOP) <add> w.subscribeOn(uiEventLoop).observeOn(Schedulers.computation()) <add> .unsubscribeOn(uiEventLoop) <ide> .take(2) <ide> .subscribe(observer); <ide> <ide> public void subscribe(Observer<? super Integer> t1) { <ide> <ide> System.out.println("unsubscribeThread: " + unsubscribeThread); <ide> System.out.println("subscribeThread.get(): " + subscribeThread.get()); <del> assertTrue(unsubscribeThread.toString(), unsubscribeThread == UI_EVENT_LOOP.getThread()); <add> assertTrue(unsubscribeThread.toString(), unsubscribeThread == uiEventLoop.getThread()); <ide> <ide> observer.assertValues(1, 2); <ide> observer.assertTerminated(); <ide> } finally { <del> UI_EVENT_LOOP.shutdown(); <add> uiEventLoop.shutdown(); <ide> } <ide> } <ide> <ide> @Test(timeout = 5000) <ide> public void unsubscribeWhenSubscribeOnAndUnsubscribeOnAreOnDifferentThreads() throws InterruptedException { <del> UIEventLoopScheduler UI_EVENT_LOOP = new UIEventLoopScheduler(); <add> UIEventLoopScheduler uiEventLoop = new UIEventLoopScheduler(); <ide> try { <ide> final ThreadSubscription subscription = new ThreadSubscription(); <ide> final AtomicReference<Thread> subscribeThread = new AtomicReference<Thread>(); <ide> public void subscribe(Observer<? super Integer> t1) { <ide> <ide> TestObserver<Integer> observer = new TestObserver<Integer>(); <ide> w.subscribeOn(Schedulers.newThread()).observeOn(Schedulers.computation()) <del> .unsubscribeOn(UI_EVENT_LOOP) <add> .unsubscribeOn(uiEventLoop) <ide> .take(2) <ide> .subscribe(observer); <ide> <ide> public void subscribe(Observer<? super Integer> t1) { <ide> assertNotSame(Thread.currentThread(), subscribeThread.get()); <ide> // True for Schedulers.newThread() <ide> <del> System.out.println("UI Thread: " + UI_EVENT_LOOP.getThread()); <add> System.out.println("UI Thread: " + uiEventLoop.getThread()); <ide> System.out.println("unsubscribeThread: " + unsubscribeThread); <ide> System.out.println("subscribeThread.get(): " + subscribeThread.get()); <del> assertSame(unsubscribeThread, UI_EVENT_LOOP.getThread()); <add> assertSame(unsubscribeThread, uiEventLoop.getThread()); <ide> <ide> observer.assertValues(1, 2); <ide> observer.assertTerminated(); <ide> } finally { <del> UI_EVENT_LOOP.shutdown(); <add> uiEventLoop.shutdown(); <ide> } <ide> } <ide> <ide><path>src/test/java/io/reactivex/internal/operators/single/SingleDelayTest.java <ide> <ide> package io.reactivex.internal.operators.single; <ide> <del>import static org.junit.Assert.*; <add>import static org.junit.Assert.assertNotEquals; <ide> <ide> import java.util.List; <ide> import java.util.concurrent.*; <del>import java.util.concurrent.atomic.*; <add>import java.util.concurrent.atomic.AtomicReference; <ide> <ide> import org.junit.Test; <ide> import org.reactivestreams.Subscriber; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.observers.TestObserver; <ide> import io.reactivex.plugins.RxJavaPlugins; <del>import io.reactivex.schedulers.Schedulers; <del>import io.reactivex.schedulers.TestScheduler; <add>import io.reactivex.schedulers.*; <ide> import io.reactivex.subjects.PublishSubject; <ide> <ide> public class SingleDelayTest { <ide> public void withSingleDispose() { <ide> public void withCompletableDispose() { <ide> TestHelper.checkDisposed(Completable.complete().andThen(Single.just(1))); <ide> } <add> <add> @Test <add> public void withCompletableDoubleOnSubscribe() { <add> <add> TestHelper.checkDoubleOnSubscribeCompletableToSingle(new Function<Completable, Single<Object>>() { <add> @Override <add> public Single<Object> apply(Completable c) throws Exception { <add> return c.andThen(Single.just((Object)1)); <add> } <add> }); <add> <add> } <add> <add> @Test <add> public void withSingleDoubleOnSubscribe() { <add> <add> TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Object>, Single<Object>>() { <add> @Override <add> public Single<Object> apply(Single<Object> s) throws Exception { <add> return Single.just((Object)1).delaySubscription(s); <add> } <add> }); <add> <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/schedulers/SchedulerPoolFactoryTest.java <ide> <ide> package io.reactivex.internal.schedulers; <ide> <add>import static org.junit.Assert.*; <add> <add>import java.util.Properties; <add> <ide> import org.junit.Test; <ide> <ide> import io.reactivex.TestHelper; <add>import io.reactivex.internal.schedulers.SchedulerPoolFactory.PurgeProperties; <add>import io.reactivex.schedulers.Schedulers; <ide> <ide> public class SchedulerPoolFactoryTest { <ide> <ide> @Test <ide> public void utilityClass() { <ide> TestHelper.checkUtilityClass(SchedulerPoolFactory.class); <ide> } <add> <add> @Test <add> public void multiStartStop() { <add> SchedulerPoolFactory.shutdown(); <add> <add> SchedulerPoolFactory.shutdown(); <add> <add> SchedulerPoolFactory.tryStart(false); <add> <add> assertNull(SchedulerPoolFactory.PURGE_THREAD.get()); <add> <add> SchedulerPoolFactory.start(); <add> <add> // restart schedulers <add> Schedulers.shutdown(); <add> <add> Schedulers.start(); <add> } <add> <add> @Test <add> public void startRace() throws InterruptedException { <add> try { <add> for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { <add> SchedulerPoolFactory.shutdown(); <add> <add> Runnable r1 = new Runnable() { <add> @Override <add> public void run() { <add> SchedulerPoolFactory.start(); <add> } <add> }; <add> <add> TestHelper.race(r1, r1); <add> } <add> <add> } finally { <add> // restart schedulers <add> Schedulers.shutdown(); <add> <add> Thread.sleep(200); <add> <add> Schedulers.start(); <add> } <add> } <add> <add> @Test <add> public void loadPurgeProperties() { <add> Properties props1 = new Properties(); <add> <add> PurgeProperties pp = new PurgeProperties(); <add> pp.load(props1); <add> <add> assertTrue(pp.purgeEnable); <add> assertEquals(pp.purgePeriod, 1); <add> } <add> <add> @Test <add> public void loadPurgePropertiesDisabled() { <add> Properties props1 = new Properties(); <add> props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "false"); <add> <add> PurgeProperties pp = new PurgeProperties(); <add> pp.load(props1); <add> <add> assertFalse(pp.purgeEnable); <add> assertEquals(pp.purgePeriod, 1); <add> } <add> <add> @Test <add> public void loadPurgePropertiesEnabledCustomPeriod() { <add> Properties props1 = new Properties(); <add> props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "true"); <add> props1.setProperty(SchedulerPoolFactory.PURGE_PERIOD_SECONDS_KEY, "2"); <add> <add> PurgeProperties pp = new PurgeProperties(); <add> pp.load(props1); <add> <add> assertTrue(pp.purgeEnable); <add> assertEquals(pp.purgePeriod, 2); <add> } <add> <add> @Test <add> public void loadPurgePropertiesEnabledCustomPeriodNaN() { <add> Properties props1 = new Properties(); <add> props1.setProperty(SchedulerPoolFactory.PURGE_ENABLED_KEY, "true"); <add> props1.setProperty(SchedulerPoolFactory.PURGE_PERIOD_SECONDS_KEY, "abc"); <add> <add> PurgeProperties pp = new PurgeProperties(); <add> pp.load(props1); <add> <add> assertTrue(pp.purgeEnable); <add> assertEquals(pp.purgePeriod, 1); <add> } <add> <add> @Test <add> public void putIntoPoolNoPurge() { <add> int s = SchedulerPoolFactory.POOLS.size(); <add> <add> SchedulerPoolFactory.tryPutIntoPool(false, null); <add> <add> assertEquals(s, SchedulerPoolFactory.POOLS.size()); <add> } <add> <add> @Test <add> public void putIntoPoolNonThreadPool() { <add> int s = SchedulerPoolFactory.POOLS.size(); <add> <add> SchedulerPoolFactory.tryPutIntoPool(true, null); <add> <add> assertEquals(s, SchedulerPoolFactory.POOLS.size()); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/schedulers/TrampolineSchedulerInternalTest.java <ide> import io.reactivex.Scheduler.Worker; <ide> import io.reactivex.internal.disposables.EmptyDisposable; <ide> import io.reactivex.internal.functions.Functions; <add>import io.reactivex.internal.schedulers.TrampolineScheduler.*; <ide> import io.reactivex.schedulers.Schedulers; <add>import static org.mockito.Mockito.*; <ide> <ide> public class TrampolineSchedulerInternalTest { <ide> <ide> public void run() { <ide> w.dispose(); <ide> } <ide> } <add> <add> @Test <add> public void sleepingRunnableDisposedOnRun() { <add> TrampolineWorker w = new TrampolineWorker(); <add> <add> Runnable r = mock(Runnable.class); <add> <add> SleepingRunnable run = new SleepingRunnable(r, w, 0); <add> w.dispose(); <add> run.run(); <add> <add> verify(r, never()).run(); <add> } <add> <add> @Test <add> public void sleepingRunnableNoDelayRun() { <add> TrampolineWorker w = new TrampolineWorker(); <add> <add> Runnable r = mock(Runnable.class); <add> <add> SleepingRunnable run = new SleepingRunnable(r, w, 0); <add> <add> run.run(); <add> <add> verify(r).run(); <add> } <add> <add> @Test <add> public void sleepingRunnableDisposedOnDelayedRun() { <add> final TrampolineWorker w = new TrampolineWorker(); <add> <add> Runnable r = mock(Runnable.class); <add> <add> SleepingRunnable run = new SleepingRunnable(r, w, System.currentTimeMillis() + 200); <add> <add> Schedulers.single().scheduleDirect(new Runnable() { <add> @Override <add> public void run() { <add> w.dispose(); <add> } <add> }, 100, TimeUnit.MILLISECONDS); <add> <add> run.run(); <add> <add> verify(r, never()).run(); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/subscribers/DeferredScalarSubscriberTest.java <ide> import io.reactivex.*; <ide> import io.reactivex.Scheduler.Worker; <ide> import io.reactivex.exceptions.TestException; <del>import io.reactivex.internal.subscribers.DeferredScalarSubscriber; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> import io.reactivex.processors.PublishProcessor; <ide> public void downstreamRequest(long n) { <ide> request(n); <ide> } <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.doubleOnSubscribe(new DeferredScalarSubscriber<Integer, Integer>(new TestSubscriber<Integer>()) { <add> private static final long serialVersionUID = -4445381578878059054L; <add> <add> @Override <add> public void onNext(Integer t) { <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/subscribers/SubscriberResourceWrapperTest.java <ide> import static org.junit.Assert.*; <ide> <ide> import org.junit.Test; <add>import org.reactivestreams.Subscriber; <ide> <add>import io.reactivex.*; <ide> import io.reactivex.disposables.*; <ide> import io.reactivex.exceptions.TestException; <add>import io.reactivex.functions.Function; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public void complete() { <ide> <ide> ts.assertResult(); <ide> } <add> <add> @Test <add> public void doubleOnSubscribe() { <add> TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() { <add> @Override <add> public Flowable<Object> apply(Flowable<Object> o) throws Exception { <add> return o.lift(new FlowableOperator<Object, Object>() { <add> @Override <add> public Subscriber<? super Object> apply( <add> Subscriber<? super Object> s) throws Exception { <add> return new SubscriberResourceWrapper<Object>(s); <add> } <add> }); <add> } <add> }); <add> } <add> <add> @Test <add> public void badRequest() { <add> TestHelper.assertBadRequestReported(Flowable.never().lift(new FlowableOperator<Object, Object>() { <add> @Override <add> public Subscriber<? super Object> apply( <add> Subscriber<? super Object> s) throws Exception { <add> return new SubscriberResourceWrapper<Object>(s); <add> } <add> })); <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/subscriptions/SubscriptionHelperTest.java <ide> package io.reactivex.internal.subscriptions; <ide> <ide> import static org.junit.Assert.*; <del> <add>import static org.mockito.Mockito.*; <ide> import java.util.List; <ide> import java.util.concurrent.atomic.*; <ide> <ide> import org.junit.Test; <ide> import org.reactivestreams.Subscription; <ide> <ide> import io.reactivex.TestHelper; <add>import io.reactivex.exceptions.ProtocolViolationException; <ide> import io.reactivex.plugins.RxJavaPlugins; <ide> <ide> public class SubscriptionHelperTest { <ide> public void run() { <ide> assertEquals(0, r.get()); <ide> } <ide> } <add> <add> @Test <add> public void setOnceAndRequest() { <add> AtomicReference<Subscription> ref = new AtomicReference<Subscription>(); <add> <add> Subscription sub = mock(Subscription.class); <add> <add> assertTrue(SubscriptionHelper.setOnce(ref, sub, 1)); <add> <add> verify(sub).request(1); <add> verify(sub, never()).cancel(); <add> <add> List<Throwable> errors = TestHelper.trackPluginErrors(); <add> try { <add> sub = mock(Subscription.class); <add> <add> assertFalse(SubscriptionHelper.setOnce(ref, sub, 1)); <add> <add> verify(sub, never()).request(anyLong()); <add> verify(sub).cancel(); <add> <add> TestHelper.assertError(errors, 0, ProtocolViolationException.class); <add> } finally { <add> RxJavaPlugins.reset(); <add> } <add> } <ide> } <ide><path>src/test/java/io/reactivex/internal/util/QueueDrainHelperTest.java <ide> import static org.junit.Assert.*; <ide> <ide> import java.io.IOException; <del>import java.util.ArrayDeque; <add>import java.util.*; <ide> import java.util.concurrent.atomic.AtomicLong; <ide> <ide> import org.junit.Test; <del>import org.reactivestreams.Subscription; <add>import org.reactivestreams.*; <ide> <add>import io.reactivex.Observer; <ide> import io.reactivex.TestHelper; <add>import io.reactivex.disposables.*; <add>import io.reactivex.exceptions.*; <ide> import io.reactivex.functions.BooleanSupplier; <add>import io.reactivex.internal.queue.SpscArrayQueue; <ide> import io.reactivex.internal.subscriptions.BooleanSubscription; <add>import io.reactivex.observers.TestObserver; <ide> import io.reactivex.subscribers.TestSubscriber; <ide> <ide> public class QueueDrainHelperTest { <ide> public boolean getAsBoolean() throws Exception { <ide> <ide> ts.assertValue(1).assertNoErrors().assertNotComplete(); <ide> } <add> <add> @Test <add> public void drainMaxLoopMissingBackpressure() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 0; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> q.offer(1); <add> <add> QueueDrainHelper.drainMaxLoop(q, ts, false, null, qd); <add> <add> ts.assertFailure(MissingBackpressureException.class); <add> } <add> <add> @Test <add> public void drainMaxLoopMissingBackpressureWithResource() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 0; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> q.offer(1); <add> <add> Disposable d = Disposables.empty(); <add> <add> QueueDrainHelper.drainMaxLoop(q, ts, false, d, qd); <add> <add> ts.assertFailure(MissingBackpressureException.class); <add> <add> assertTrue(d.isDisposed()); <add> } <add> <add> @Test <add> public void drainMaxLoopDontAccept() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 1; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> q.offer(1); <add> <add> QueueDrainHelper.drainMaxLoop(q, ts, false, null, qd); <add> <add> ts.assertEmpty(); <add> } <add> <add> @Test <add> public void checkTerminatedDelayErrorEmpty() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 0; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, true, ts, true, q, qd); <add> <add> ts.assertResult(); <add> } <add> <add> @Test <add> public void checkTerminatedDelayErrorNonEmpty() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 0; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, false, ts, true, q, qd); <add> <add> ts.assertEmpty(); <add> } <add> <add> @Test <add> public void checkTerminatedDelayErrorEmptyError() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return new TestException(); <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 0; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, true, ts, true, q, qd); <add> <add> ts.assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void checkTerminatedNonDelayErrorError() { <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> ts.onSubscribe(new BooleanSubscription()); <add> <add> QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return new TestException(); <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public long requested() { <add> return 0; <add> } <add> <add> @Override <add> public long produced(long n) { <add> return 0; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public boolean accept(Subscriber<? super Integer> a, Integer v) { <add> return false; <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, false, ts, false, q, qd); <add> <add> ts.assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void observerCheckTerminatedDelayErrorEmpty() { <add> TestObserver<Integer> ts = new TestObserver<Integer>(); <add> ts.onSubscribe(Disposables.empty()); <add> <add> ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public void accept(Observer<? super Integer> a, Integer v) { <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, true, ts, true, q, null, qd); <add> <add> ts.assertResult(); <add> } <add> <add> @Test <add> public void observerCheckTerminatedDelayErrorEmptyResource() { <add> TestObserver<Integer> ts = new TestObserver<Integer>(); <add> ts.onSubscribe(Disposables.empty()); <add> <add> ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public void accept(Observer<? super Integer> a, Integer v) { <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> Disposable d = Disposables.empty(); <add> <add> QueueDrainHelper.checkTerminated(true, true, ts, true, q, d, qd); <add> <add> ts.assertResult(); <add> <add> assertTrue(d.isDisposed()); <add> } <add> <add> @Test <add> public void observerCheckTerminatedDelayErrorNonEmpty() { <add> TestObserver<Integer> ts = new TestObserver<Integer>(); <add> ts.onSubscribe(Disposables.empty()); <add> <add> ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return null; <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public void accept(Observer<? super Integer> a, Integer v) { <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, false, ts, true, q, null, qd); <add> <add> ts.assertEmpty(); <add> } <add> <add> @Test <add> public void observerCheckTerminatedDelayErrorEmptyError() { <add> TestObserver<Integer> ts = new TestObserver<Integer>(); <add> ts.onSubscribe(Disposables.empty()); <add> <add> ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return new TestException(); <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public void accept(Observer<? super Integer> a, Integer v) { <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, true, ts, true, q, null, qd); <add> <add> ts.assertFailure(TestException.class); <add> } <add> <add> @Test <add> public void observerCheckTerminatedNonDelayErrorError() { <add> TestObserver<Integer> ts = new TestObserver<Integer>(); <add> ts.onSubscribe(Disposables.empty()); <add> <add> ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return new TestException(); <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public void accept(Observer<? super Integer> a, Integer v) { <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> QueueDrainHelper.checkTerminated(true, false, ts, false, q, null, qd); <add> <add> ts.assertFailure(TestException.class); <add> } <add> @Test <add> public void observerCheckTerminatedNonDelayErrorErrorResource() { <add> TestObserver<Integer> ts = new TestObserver<Integer>(); <add> ts.onSubscribe(Disposables.empty()); <add> <add> ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { <add> @Override <add> public boolean cancelled() { <add> return false; <add> } <add> <add> @Override <add> public boolean done() { <add> return false; <add> } <add> <add> @Override <add> public Throwable error() { <add> return new TestException(); <add> } <add> <add> @Override <add> public boolean enter() { <add> return true; <add> } <add> <add> @Override <add> public int leave(int m) { <add> return 0; <add> } <add> <add> @Override <add> public void accept(Observer<? super Integer> a, Integer v) { <add> } <add> }; <add> <add> SpscArrayQueue<Integer> q = new SpscArrayQueue<Integer>(32); <add> <add> Disposable d = Disposables.empty(); <add> <add> QueueDrainHelper.checkTerminated(true, false, ts, false, q, d, qd); <add> <add> ts.assertFailure(TestException.class); <add> <add> assertTrue(d.isDisposed()); <add> } <add> <add> @Test <add> public void postCompleteAlreadyComplete() { <add> <add> TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); <add> <add> Queue<Integer> q = new ArrayDeque<Integer>(); <add> q.offer(1); <add> <add> AtomicLong state = new AtomicLong(QueueDrainHelper.COMPLETED_MASK); <add> <add> QueueDrainHelper.postComplete(ts, q, state, new BooleanSupplier() { <add> @Override <add> public boolean getAsBoolean() throws Exception { <add> return false; <add> } <add> }); <add> } <ide> } <ide><path>src/test/java/io/reactivex/observable/ObservableCovarianceTest.java <ide> public void testCovarianceOfFrom() { <ide> <ide> @Test <ide> public void testSortedList() { <del> Comparator<Media> SORT_FUNCTION = new Comparator<Media>() { <add> Comparator<Media> sortFunction = new Comparator<Media>() { <ide> @Override <ide> public int compare(Media t1, Media t2) { <ide> return 1; <ide> public int compare(Media t1, Media t2) { <ide> <ide> // this one would work without the covariance generics <ide> Observable<Media> o = Observable.just(new Movie(), new TVSeason(), new Album()); <del> o.toSortedList(SORT_FUNCTION); <add> o.toSortedList(sortFunction); <ide> <ide> // this one would NOT work without the covariance generics <ide> Observable<Movie> o2 = Observable.just(new Movie(), new ActionMovie(), new HorrorMovie()); <del> o2.toSortedList(SORT_FUNCTION); <add> o2.toSortedList(sortFunction); <ide> } <ide> <ide> @Test
93
Ruby
Ruby
defer loading xmlmini until it's needed
a45a4203acdd8149a82fe0485c2173cc8beaa78a
<ide><path>activesupport/lib/active_support/core_ext/array/conversions.rb <ide> # frozen_string_literal: true <ide> <del>require "active_support/xml_mini" <ide> require "active_support/core_ext/hash/keys" <ide> require "active_support/core_ext/string/inflections" <ide> require "active_support/core_ext/object/to_param" <ide><path>activesupport/lib/active_support/core_ext/hash/conversions.rb <ide> # frozen_string_literal: true <ide> <del>require "active_support/xml_mini" <ide> require "active_support/core_ext/object/blank" <ide> require "active_support/core_ext/object/to_param" <ide> require "active_support/core_ext/object/to_query"
2
PHP
PHP
change method visibility
3673354d70b860078d0c88e1d89439e65db9af70
<ide><path>src/Illuminate/Http/Resources/Json/ResourceCollection.php <ide> public function toResponse($request) <ide> * @param \Illuminate\Http\Request $request <ide> * @return \Illuminate\Http\JsonResponse <ide> */ <del> private function preparePaginatedResponse($request) <add> protected function preparePaginatedResponse($request) <ide> { <ide> if ($this->queryParameters) { <ide> $this->resource->appends($request->query());
1
Go
Go
remove unused commandline
b7106a92f26271e0d2c6623446ce4a8bc987c445
<ide><path>libcontainerd/client_windows.go <ide> func (clnt *client) Create(containerID string, checkpoint string, checkpointDir <ide> client: clnt, <ide> friendlyName: InitFriendlyName, <ide> }, <del> commandLine: strings.Join(spec.Process.Args, " "), <ide> }, <ide> processes: make(map[string]*process), <ide> }, <ide> func (clnt *client) AddProcess(ctx context.Context, containerID, processFriendly <ide> client: clnt, <ide> systemPid: uint32(pid), <ide> }, <del> commandLine: createProcessParms.CommandLine, <del> hcsProcess: newProcess, <add> hcsProcess: newProcess, <ide> } <ide> <ide> // Add the process to the container's list of processes <ide><path>libcontainerd/process_windows.go <ide> type process struct { <ide> processCommon <ide> <ide> // Platform specific fields are below here. <del> <del> // commandLine is to support returning summary information for docker top <del> commandLine string <del> hcsProcess hcsshim.Process <add> hcsProcess hcsshim.Process <ide> } <ide> <ide> type autoClosingReader struct {
2
PHP
PHP
apply fixes from styleci
03b673db7f3505d81ce737b2019133a250317bc8
<ide><path>src/Illuminate/Console/Concerns/InteractsWithIO.php <ide> public function alert($string) <ide> public function newLine($count = 1) <ide> { <ide> $this->output->newLine($count); <del> <add> <ide> return $this; <ide> } <ide>
1
Javascript
Javascript
remove trailing whitespace
842b6ccc0e009b3c06b998ea8d69c4d2a0b31e2a
<ide><path>test/Compiler.test.js <ide> describe("Compiler", function() { <ide> var files = {}; <ide> c.outputFileSystem = { <ide> join: function() { <del> return [].join.call(arguments, "/").replace(/\/+/g, "/"); <add> return [].join.call(arguments, "/").replace(/\/+/g, "/"); <ide> }, <ide> mkdirp: function(path, callback) { <ide> logs.mkdirp.push(path);
1
Python
Python
fix integration of zero polynomials
6b9762c0a918acb583bee7e387863123e339e46c
<ide><path>numpy/polynomial/chebyshev.py <ide> def chebder(cs, m=1, scl=1) : <ide> raise ValueError, "The order of derivation must be integer" <ide> if cnt < 0 : <ide> raise ValueError, "The order of derivation must be non-negative" <del> if not np.isscalar(scl) : <del> raise ValueError, "The scl parameter must be a scalar" <ide> <ide> # cs is a trimmed copy <ide> [cs] = pu.as_series([cs]) <ide> def chebint(cs, m=1, k=[], lbnd=0, scl=1): <ide> raise ValueError, "The order of integration must be non-negative" <ide> if len(k) > cnt : <ide> raise ValueError, "Too many integration constants" <del> if not np.isscalar(lbnd) : <del> raise ValueError, "The lbnd parameter must be a scalar" <del> if not np.isscalar(scl) : <del> raise ValueError, "The scl parameter must be a scalar" <ide> <ide> # cs is a trimmed copy <ide> [cs] = pu.as_series([cs]) <ide> if cnt == 0: <ide> return cs <del> else: <del> k = list(k) + [0]*(cnt - len(k)) <del> for i in range(cnt) : <del> zs = _cseries_to_zseries(cs)*scl <add> <add> k = list(k) + [0]*(cnt - len(k)) <add> for i in range(cnt) : <add> n = len(cs) <add> cs *= scl <add> if n == 1 and cs[0] == 0: <add> cs[0] += k[i] <add> else: <add> zs = _cseries_to_zseries(cs) <ide> zs = _zseries_int(zs) <ide> cs = _zseries_to_cseries(zs) <ide> cs[0] += k[i] - chebval(lbnd, cs) <del> return cs <add> return cs <ide> <ide> def chebval(x, cs): <ide> """Evaluate a Chebyshev series. <ide><path>numpy/polynomial/polynomial.py <ide> def polyder(cs, m=1, scl=1): <ide> raise ValueError, "The order of derivation must be integer" <ide> if cnt < 0: <ide> raise ValueError, "The order of derivation must be non-negative" <del> if not np.isscalar(scl): <del> raise ValueError, "The scl parameter must be a scalar" <ide> <ide> # cs is a trimmed copy <ide> [cs] = pu.as_series([cs]) <ide> def polyint(cs, m=1, k=[], lbnd=0, scl=1): <ide> raise ValueError, "The order of integration must be non-negative" <ide> if len(k) > cnt : <ide> raise ValueError, "Too many integration constants" <del> if not np.isscalar(lbnd) : <del> raise ValueError, "The lbnd parameter must be a scalar" <del> if not np.isscalar(scl) : <del> raise ValueError, "The scl parameter must be a scalar" <ide> <ide> # cs is a trimmed copy <ide> [cs] = pu.as_series([cs]) <ide> if cnt == 0: <ide> return cs <del> else: <del> k = list(k) + [0]*(cnt - len(k)) <del> fac = np.arange(1, len(cs) + cnt)/scl <del> ret = np.zeros(len(cs) + cnt, dtype=cs.dtype) <del> ret[cnt:] = cs <del> for i in range(cnt) : <del> ret[cnt - i:] /= fac[:len(cs) + i] <del> ret[cnt - i - 1] += k[i] - polyval(lbnd, ret[cnt - i - 1:]) <del> return ret <add> <add> k = list(k) + [0]*(cnt - len(k)) <add> for i in range(cnt): <add> n = len(cs) <add> cs *= scl <add> if n == 1 and cs[0] == 0: <add> cs[0] += k[i] <add> else: <add> tmp = np.empty(n + 1, dtype=cs.dtype) <add> tmp[0] = cs[0]*0 <add> tmp[1:] = cs/np.arange(1, n + 1) <add> tmp[0] += k[i] - polyval(lbnd, tmp) <add> cs = tmp <add> return cs <ide> <ide> def polyval(x, cs): <ide> """ <ide><path>numpy/polynomial/tests/test_chebyshev.py <ide> def test_chebint(self) : <ide> assert_raises(ValueError, ch.chebint, [0], .5) <ide> assert_raises(ValueError, ch.chebint, [0], -1) <ide> assert_raises(ValueError, ch.chebint, [0], 1, [0,0]) <del> assert_raises(ValueError, ch.chebint, [0], 1, lbnd=[0,0]) <del> assert_raises(ValueError, ch.chebint, [0], 1, scl=[0,0]) <add> <add> # test integration of zero polynomial <add> for i in range(2, 5): <add> k = [0]*(i - 2) + [1] <add> res = ch.chebint([0], m=i, k=k) <add> assert_almost_equal(res, [0, 1]) <ide> <ide> # check single integration with integration constant <ide> for i in range(5) : <ide><path>numpy/polynomial/tests/test_polynomial.py <ide> def test_polyint(self) : <ide> assert_raises(ValueError, poly.polyint, [0], .5) <ide> assert_raises(ValueError, poly.polyint, [0], -1) <ide> assert_raises(ValueError, poly.polyint, [0], 1, [0,0]) <del> assert_raises(ValueError, poly.polyint, [0], 1, lbnd=[0,0]) <del> assert_raises(ValueError, poly.polyint, [0], 1, scl=[0,0]) <add> <add> # test integration of zero polynomial <add> for i in range(2, 5): <add> k = [0]*(i - 2) + [1] <add> res = poly.polyint([0], m=i, k=k) <add> assert_almost_equal(res, [0, 1]) <ide> <ide> # check single integration with integration constant <ide> for i in range(5) :
4
Python
Python
display all containers logs
ab80880fedb7843baa5b6e0f11d3fd99ded4b5cc
<ide><path>airflow/operators/docker_operator.py <ide> def _run_image(self): <ide> working_dir=self.working_dir, <ide> tty=self.tty, <ide> ) <add> <add> lines = self.cli.attach(container=self.container['Id'], <add> stdout=True, <add> stderr=True, <add> stream=True) <add> <ide> self.cli.start(self.container['Id']) <ide> <ide> line = '' <del> for line in self.cli.attach(container=self.container['Id'], <del> stdout=True, <del> stderr=True, <del> stream=True): <add> for line in lines: <ide> line = line.strip() <ide> if hasattr(line, 'decode'): <ide> line = line.decode('utf-8')
1
Go
Go
use local rand.random in test
c2c45d77691d1ca501a68d20885d040415477c92
<ide><path>daemon/execdriver/lxc/lxc_template_unit_test.go <ide> func TestLXCConfig(t *testing.T) { <ide> os.MkdirAll(path.Join(root, "containers", "1"), 0777) <ide> <ide> // Memory is allocated randomly for testing <del> rand.Seed(time.Now().UTC().UnixNano()) <add> r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) <ide> var ( <ide> memMin = 33554432 <ide> memMax = 536870912 <del> mem = memMin + rand.Intn(memMax-memMin) <add> mem = memMin + r.Intn(memMax-memMin) <ide> cpuMin = 100 <ide> cpuMax = 10000 <del> cpu = cpuMin + rand.Intn(cpuMax-cpuMin) <add> cpu = cpuMin + r.Intn(cpuMax-cpuMin) <ide> ) <ide> <ide> driver, err := NewDriver(root, root, "", false)
1
Text
Text
use secure sfc links
a0855fde264786e5f13169a5e22321793ec1effd
<ide><path>README.md <ide> Our bottles (binary packages) are hosted by Bintray. <ide> <ide> [![Downloads by Bintray](https://bintray.com/docs/images/downloads_by_bintray_96.png)](https://bintray.com/homebrew) <ide> <del>Homebrew is a member of the [Software Freedom Conservancy](http://sfconservancy.org) <add>Homebrew is a member of the [Software Freedom Conservancy](https://sfconservancy.org) <ide> <del>[![Software Freedom Conservancy](http://sfconservancy.org/img/conservancy_64x64.png)](http://sfconservancy.org) <add>[![Software Freedom Conservancy](https://sfconservancy.org/img/conservancy_64x64.png)](https://sfconservancy.org)
1
Ruby
Ruby
improve strongparameters documentation [ci skip]
2aa08e313d3cc3562a3651977c428f7ca9182810
<ide><path>actionpack/lib/action_controller/metal/strong_parameters.rb <ide> def initialize(param) # :nodoc: <ide> # params.permit(:c) <ide> # # => ActionController::UnpermittedParameters: found unpermitted keys: a, b <ide> class UnpermittedParameters < IndexError <del> attr_reader :params <add> attr_reader :params # :nodoc: <ide> <del> def initialize(params) <add> def initialize(params) # :nodoc: <ide> @params = params <ide> super("found unpermitted keys: #{params.join(", ")}") <ide> end <ide> def initialize(params) <ide> # It provides two options that controls the top-level behavior of new instances: <ide> # <ide> # * +permit_all_parameters+ - If it's +true+, all the parameters will be <del> # permitted by default. The default value for +permit_all_parameters+ <del> # option is +false+. <del> # * +raise_on_unpermitted_parameters+ - If it's +true+, it will raise an exception <del> # if parameters that are not explicitly permitted are found. The default value for <del> # +raise_on_unpermitted_parameters+ # option is +true+ in test and development <del> # environments, +false+ otherwise. <add> # permitted by default. The default is +false+. <add> # * +raise_on_unpermitted_parameters+ - If it's +true+, it will raise an <add> # ActionController::UnpermittedParameters exception if parameters that are not <add> # explicitly permitted are found. The default value is +true+ in test and <add> # development environments, +false+ otherwise. <ide> # <ide> # params = ActionController::Parameters.new <ide> # params.permitted? # => false
1
Python
Python
add configure flag to build v8 with dchecks
d1587dcd0af155deb36ee51290b2f9842c2a570b
<ide><path>configure.py <ide> default=False, <ide> help='compile V8 with minimal optimizations and with runtime checks') <ide> <add>parser.add_option('--v8-with-dchecks', <add> action='store_true', <add> dest='v8_with_dchecks', <add> default=False, <add> help='compile V8 with debug checks and runtime debugging features enabled') <add> <ide> parser.add_option('--node-builtin-modules-path', <ide> action='store', <ide> dest='node_builtin_modules_path', <ide> def configure_v8(o): <ide> o['variables']['v8_enable_gdbjit'] = 1 if options.gdb else 0 <ide> o['variables']['v8_no_strict_aliasing'] = 1 # Work around compiler bugs. <ide> o['variables']['v8_optimized_debug'] = 0 if options.v8_non_optimized_debug else 1 <add> o['variables']['dcheck_always_on'] = 1 if options.v8_with_dchecks else 0 <ide> o['variables']['v8_random_seed'] = 0 # Use a random seed for hash tables. <ide> o['variables']['v8_promise_internal_field_count'] = 1 # Add internal field to promises for async hooks. <ide> o['variables']['v8_use_siphash'] = 0 if options.without_siphash else 1
1
Javascript
Javascript
standardize the path before copying it
8df13c584981a2c3475acdd406c59afb5e3c37e0
<ide><path>src/git-repository-async.js <ide> export default class GitRepositoryAsync { <ide> <ide> workingDirectory = workingDirectory.replace(/\/$/, '') <ide> <add> // Depending on where the paths come from, they may have a '/private/' <add> // prefix. Standardize by stripping that out. <add> _path = _path.replace(/^\/private\//i, '/') <add> workingDirectory = workingDirectory.replace(/^\/private\//i, '/') <add> <ide> const originalPath = _path <add> const originalWorkingDirectory = workingDirectory <ide> if (this.isCaseInsensitive) { <ide> _path = _path.toLowerCase() <ide> workingDirectory = workingDirectory.toLowerCase() <ide> } <ide> <del> // Depending on where the paths come from, they may have a '/private/' <del> // prefix. Standardize by stripping that out. <del> _path = _path.replace(/^\/private\//, '/') <del> workingDirectory = workingDirectory.replace(/^\/private\//, '/') <del> <ide> if (_path.indexOf(workingDirectory) === 0) { <del> return originalPath.substring(workingDirectory.length + 1) <add> return originalPath.substring(originalWorkingDirectory.length + 1) <ide> } else if (_path === workingDirectory) { <ide> return '' <ide> } <ide> <ide> if (openedWorkingDirectory) { <add> openedWorkingDirectory = openedWorkingDirectory.replace(/\/$/, '') <add> openedWorkingDirectory = openedWorkingDirectory.replace(/^\/private\//i, '/') <add> <add> const originalOpenedWorkingDirectory = openedWorkingDirectory <ide> if (this.isCaseInsensitive) { <ide> openedWorkingDirectory = openedWorkingDirectory.toLowerCase() <ide> } <del> openedWorkingDirectory = openedWorkingDirectory.replace(/\/$/, '') <del> openedWorkingDirectory = openedWorkingDirectory.replace(/^\/private\//, '/') <ide> <ide> if (_path.indexOf(openedWorkingDirectory) === 0) { <del> return originalPath.substring(openedWorkingDirectory.length + 1) <add> return originalPath.substring(originalOpenedWorkingDirectory.length + 1) <ide> } else if (_path === openedWorkingDirectory) { <ide> return '' <ide> }
1
Javascript
Javascript
prevent animation on initial page load
570463a465fae02efc33e5a1fa963437cdc275dd
<ide><path>src/ng/animator.js <ide> * <ide> * The `event1` and `event2` attributes refer to the animation events specific to the directive that has been assigned. <ide> * <del> * Keep in mind that, by default, **all** initial animations will be skipped until the first digest cycle has fully <del> * passed. This helps prevent any unexpected animations from occurring while the application or directive is initializing. To <del> * override this behavior, you may pass "animateFirst: true" into the ngAnimate attribute expression. <add> * Keep in mind that if an animation is running, no child element of such animation can also be animated. <ide> * <ide> * <h2>CSS-defined Animations</h2> <ide> * By default, ngAnimate attaches two CSS3 classes per animation event to the DOM element to achieve the animation. <ide> */ <ide> <ide> var $AnimatorProvider = function() { <del> var globalAnimationEnabled = true; <add> var NG_ANIMATE_CONTROLLER = '$ngAnimateController'; <add> var rootAnimateController = {running:true}; <ide> <del> this.$get = ['$animation', '$window', '$sniffer', '$rootScope', function($animation, $window, $sniffer, $rootScope) { <del> /** <del> * @ngdoc function <del> * @name ng.$animator <del> * @function <del> * <del> * @description <del> * The $animator.create service provides the DOM manipulation API which is decorated with animations. <del> * <del> * @param {Scope} scope the scope for the ng-animate. <del> * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are <del> * passed into the linking function of the directive using the `$animator`.) <del> * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods. <del> */ <del> var AnimatorService = function(scope, attrs) { <del> var ngAnimateAttr = attrs.ngAnimate; <del> <del> // avoid running animations on start <del> var animationEnabled = false; <del> var ngAnimateValue = ngAnimateAttr && scope.$eval(ngAnimateAttr); <del> <del> if (!animationEnabled) { <del> if(isObject(ngAnimateValue) && ngAnimateValue['animateFirst']) { <del> animationEnabled = true; <del> } else { <del> var enableSubsequent = function() { <del> removeWatch(); <del> scope.$evalAsync(function() { <del> animationEnabled = true; <del> }); <del> }; <del> var removeWatch = noop; <del> <del> if (scope.$$phase) { <del> enableSubsequent(); <del> } else { <del> removeWatch = scope.$watch(enableSubsequent); <del> } <del> } <add> this.$get = ['$animation', '$window', '$sniffer', '$rootElement', '$rootScope', <add> function($animation, $window, $sniffer, $rootElement, $rootScope) { <add> $rootElement.data(NG_ANIMATE_CONTROLLER, rootAnimateController); <add> var unregister = $rootScope.$watch(function() { <add> unregister(); <add> if (rootAnimateController.running) { <add> $window.setTimeout(function() { <add> rootAnimateController.running = false; <add> }, 0); <ide> } <del> var animator = {}; <del> <del> /** <del> * @ngdoc function <del> * @name ng.animator#enter <del> * @methodOf ng.$animator <del> * @function <del> * <del> * @description <del> * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation. <del> * <del> * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation <del> * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation <del> * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation <del> */ <del> animator.enter = animateActionFactory('enter', insert, noop); <del> <del> /** <del> * @ngdoc function <del> * @name ng.animator#leave <del> * @methodOf ng.$animator <del> * @function <del> * <del> * @description <del> * Runs the leave animation operation and, upon completion, removes the element from the DOM. <del> * <del> * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation <del> * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation <del> */ <del> animator.leave = animateActionFactory('leave', noop, remove); <del> <del> /** <del> * @ngdoc function <del> * @name ng.animator#move <del> * @methodOf ng.$animator <del> * @function <del> * <del> * @description <del> * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or <del> * add the element directly after the after element if present. Then the move animation will be run. <del> * <del> * @param {jQuery/jqLite element} element the element that will be the focus of the move animation <del> * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation <del> * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation <del> */ <del> animator.move = animateActionFactory('move', move, noop); <del> <del> /** <del> * @ngdoc function <del> * @name ng.animator#show <del> * @methodOf ng.$animator <del> * @function <del> * <del> * @description <del> * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after. <del> * <del> * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden <del> */ <del> animator.show = animateActionFactory('show', show, noop); <del> <del> /** <del> * @ngdoc function <del> * @name ng.animator#hide <del> * @methodOf ng.$animator <del> * <del> * @description <del> * Starts the hide animation first and sets the CSS `display` property to `none` upon completion. <del> * <del> * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden <del> */ <del> animator.hide = animateActionFactory('hide', noop, hide); <del> return animator; <del> <del> function animateActionFactory(type, beforeFn, afterFn) { <del> var className = ngAnimateAttr <del> ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type <del> : ''; <del> var animationPolyfill = $animation(className); <del> <del> var polyfillSetup = animationPolyfill && animationPolyfill.setup; <del> var polyfillStart = animationPolyfill && animationPolyfill.start; <add> }); <ide> <del> if (!className) { <del> return function(element, parent, after) { <del> beforeFn(element, parent, after); <del> afterFn(element, parent, after); <del> } <del> } else { <del> var setupClass = className + '-setup'; <del> var startClass = className + '-start'; <del> <del> return function(element, parent, after) { <del> if (!animationEnabled || !globalAnimationEnabled || <del> (!$sniffer.supportsTransitions && !polyfillSetup && !polyfillStart)) { <add> /** <add> * @ngdoc function <add> * @name ng.$animator <add> * @function <add> * <add> * @description <add> * The $animator.create service provides the DOM manipulation API which is decorated with animations. <add> * <add> * @param {Scope} scope the scope for the ng-animate. <add> * @param {Attributes} attr the attributes object which contains the ngAnimate key / value pair. (The attributes are <add> * passed into the linking function of the directive using the `$animator`.) <add> * @return {object} the animator object which contains the enter, leave, move, show, hide and animate methods. <add> */ <add> var AnimatorService = function(scope, attrs) { <add> var ngAnimateAttr = attrs.ngAnimate; <add> var ngAnimateValue = ngAnimateAttr && scope.$eval(ngAnimateAttr); <add> var animator = {}; <add> <add> /** <add> * @ngdoc function <add> * @name ng.animator#enter <add> * @methodOf ng.$animator <add> * @function <add> * <add> * @description <add> * Injects the element object into the DOM (inside of the parent element) and then runs the enter animation. <add> * <add> * @param {jQuery/jqLite element} element the element that will be the focus of the enter animation <add> * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the enter animation <add> * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the enter animation <add> */ <add> animator.enter = animateActionFactory('enter', insert, noop); <add> <add> /** <add> * @ngdoc function <add> * @name ng.animator#leave <add> * @methodOf ng.$animator <add> * @function <add> * <add> * @description <add> * Runs the leave animation operation and, upon completion, removes the element from the DOM. <add> * <add> * @param {jQuery/jqLite element} element the element that will be the focus of the leave animation <add> * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the leave animation <add> */ <add> animator.leave = animateActionFactory('leave', noop, remove); <add> <add> /** <add> * @ngdoc function <add> * @name ng.animator#move <add> * @methodOf ng.$animator <add> * @function <add> * <add> * @description <add> * Fires the move DOM operation. Just before the animation starts, the animator will either append it into the parent container or <add> * add the element directly after the after element if present. Then the move animation will be run. <add> * <add> * @param {jQuery/jqLite element} element the element that will be the focus of the move animation <add> * @param {jQuery/jqLite element} parent the parent element of the element that will be the focus of the move animation <add> * @param {jQuery/jqLite element} after the sibling element (which is the previous element) of the element that will be the focus of the move animation <add> */ <add> animator.move = animateActionFactory('move', move, noop); <add> <add> /** <add> * @ngdoc function <add> * @name ng.animator#show <add> * @methodOf ng.$animator <add> * @function <add> * <add> * @description <add> * Reveals the element by setting the CSS property `display` to `block` and then starts the show animation directly after. <add> * <add> * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden <add> */ <add> animator.show = animateActionFactory('show', show, noop); <add> <add> /** <add> * @ngdoc function <add> * @name ng.animator#hide <add> * @methodOf ng.$animator <add> * <add> * @description <add> * Starts the hide animation first and sets the CSS `display` property to `none` upon completion. <add> * <add> * @param {jQuery/jqLite element} element the element that will be rendered visible or hidden <add> */ <add> animator.hide = animateActionFactory('hide', noop, hide); <add> return animator; <add> <add> function animateActionFactory(type, beforeFn, afterFn) { <add> var className = ngAnimateAttr <add> ? isObject(ngAnimateValue) ? ngAnimateValue[type] : ngAnimateValue + '-' + type <add> : ''; <add> var animationPolyfill = $animation(className); <add> <add> var polyfillSetup = animationPolyfill && animationPolyfill.setup; <add> var polyfillStart = animationPolyfill && animationPolyfill.start; <add> <add> if (!className) { <add> return function(element, parent, after) { <ide> beforeFn(element, parent, after); <ide> afterFn(element, parent, after); <del> return; <ide> } <del> <del> element.addClass(setupClass); <del> beforeFn(element, parent, after); <del> if (element.length == 0) return done(); <del> <del> var memento = (polyfillSetup || noop)(element); <del> <del> // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate <del> // keep at 1 for animation dom rerender <del> $window.setTimeout(beginAnimation, 1); <del> <del> function beginAnimation() { <del> element.addClass(startClass); <del> if (polyfillStart) { <del> polyfillStart(element, done, memento); <del> } else if (isFunction($window.getComputedStyle)) { <del> var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition'; <del> var w3cTransitionProp = 'transition'; //one day all browsers will have this <del> <del> var durationKey = 'Duration'; <del> var duration = 0; <del> //we want all the styles defined before and after <del> forEach(element, function(element) { <del> var globalStyles = $window.getComputedStyle(element) || {}; <del> duration = Math.max( <del> parseFloat(globalStyles[w3cTransitionProp + durationKey]) || <del> parseFloat(globalStyles[vendorTransitionProp + durationKey]) || <del> 0, <del> duration); <del> }); <del> $window.setTimeout(done, duration * 1000); <del> } else { <del> done(); <add> } else { <add> var setupClass = className + '-setup'; <add> var startClass = className + '-start'; <add> <add> return function(element, parent, after) { <add> if (!parent) { <add> parent = after ? after.parent() : element.parent(); <add> } <add> if ((!$sniffer.supportsTransitions && !polyfillSetup && !polyfillStart) || <add> (parent.inheritedData(NG_ANIMATE_CONTROLLER) || noop).running) { <add> beforeFn(element, parent, after); <add> afterFn(element, parent, after); <add> return; <ide> } <del> } <ide> <del> function done() { <del> afterFn(element, parent, after); <del> element.removeClass(setupClass); <del> element.removeClass(startClass); <add> element.data(NG_ANIMATE_CONTROLLER, {running:true}); <add> element.addClass(setupClass); <add> beforeFn(element, parent, after); <add> if (element.length == 0) return done(); <add> <add> var memento = (polyfillSetup || noop)(element); <add> <add> // $window.setTimeout(beginAnimation, 0); this was causing the element not to animate <add> // keep at 1 for animation dom rerender <add> $window.setTimeout(beginAnimation, 1); <add> <add> function beginAnimation() { <add> element.addClass(startClass); <add> if (polyfillStart) { <add> polyfillStart(element, done, memento); <add> } else if (isFunction($window.getComputedStyle)) { <add> var vendorTransitionProp = $sniffer.vendorPrefix + 'Transition'; <add> var w3cTransitionProp = 'transition'; //one day all browsers will have this <add> <add> var durationKey = 'Duration'; <add> var duration = 0; <add> //we want all the styles defined before and after <add> forEach(element, function(element) { <add> var globalStyles = $window.getComputedStyle(element) || {}; <add> duration = Math.max( <add> parseFloat(globalStyles[w3cTransitionProp + durationKey]) || <add> parseFloat(globalStyles[vendorTransitionProp + durationKey]) || <add> 0, <add> duration); <add> }); <add> $window.setTimeout(done, duration * 1000); <add> } else { <add> done(); <add> } <add> } <add> <add> function done() { <add> afterFn(element, parent, after); <add> element.removeClass(setupClass); <add> element.removeClass(startClass); <add> element.removeData(NG_ANIMATE_CONTROLLER); <add> } <ide> } <ide> } <ide> } <del> } <del> <del> function show(element) { <del> element.css('display', ''); <del> } <del> <del> function hide(element) { <del> element.css('display', 'none'); <del> } <del> <del> function insert(element, parent, after) { <del> if (after) { <del> after.after(element); <del> } else { <del> parent.append(element); <add> <add> function show(element) { <add> element.css('display', ''); <ide> } <del> } <del> <del> function remove(element) { <del> element.remove(); <del> } <del> <del> function move(element, parent, after) { <del> // Do not remove element before insert. Removing will cause data associated with the <del> // element to be dropped. Insert will implicitly do the remove. <del> insert(element, parent, after); <del> } <del> }; <add> <add> function hide(element) { <add> element.css('display', 'none'); <add> } <add> <add> function insert(element, parent, after) { <add> if (after) { <add> after.after(element); <add> } else { <add> parent.append(element); <add> } <add> } <add> <add> function remove(element) { <add> element.remove(); <add> } <add> <add> function move(element, parent, after) { <add> // Do not remove element before insert. Removing will cause data associated with the <add> // element to be dropped. Insert will implicitly do the remove. <add> insert(element, parent, after); <add> } <add> }; <ide> <ide> /** <ide> * @ngdoc function <ide> var $AnimatorProvider = function() { <ide> */ <ide> AnimatorService.enabled = function(value) { <ide> if (arguments.length) { <del> globalAnimationEnabled = !!value; <add> rootAnimateController.running = !value; <ide> } <del> return globalAnimationEnabled; <add> return !rootAnimateController.running; <ide> }; <ide> <ide> return AnimatorService; <ide><path>test/ng/animatorSpec.js <ide> <ide> describe("$animator", function() { <ide> <del> var body, element; <add> var body, element, $rootElement; <ide> <ide> function html(html) { <del> body.html(html); <del> element = body.children().eq(0); <add> body.append($rootElement); <add> $rootElement.html(html); <add> element = $rootElement.children().eq(0); <ide> return element; <ide> } <ide> <ide> describe("$animator", function() { <ide> <ide> describe("enable / disable", function() { <ide> <del> it("should disable and enable the animations", inject(function($animator) { <add> beforeEach(function() { <add> module(function($animationProvider, $provide) { <add> $provide.value('$window', angular.mock.createMockWindow()); <add> }); <add> }); <add> <add> it("should disable and enable the animations", inject(function($animator, $rootScope, $window) { <add> expect($animator.enabled()).toBe(false); <add> <add> $rootScope.$digest(); <add> $window.setTimeout.expect(0).process(); <add> <ide> expect($animator.enabled()).toBe(true); <ide> <ide> expect($animator.enabled(0)).toBe(false); <ide> describe("$animator", function() { <ide> module(function($animationProvider, $provide) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <ide> }) <del> inject(function($animator, $compile, $rootScope) { <add> inject(function($animator, $compile, $rootScope, _$rootElement_) { <ide> animator = $animator($rootScope, {}); <ide> element = $compile('<div></div>')($rootScope); <add> $rootElement = _$rootElement_; <ide> }) <ide> }); <ide> <ide> describe("$animator", function() { <ide> animator = $animator($rootScope, { <ide> ngAnimate : '{enter: \'custom\'}' <ide> }); <add> <ide> $rootScope.$digest(); // re-enable the animations; <add> window.setTimeout.expect(0).process(); <add> <ide> expect(element.contents().length).toBe(0); <ide> animator.enter(child, element); <ide> window.setTimeout.expect(1).process(); <ide> describe("$animator", function() { <ide> animator = $animator($rootScope, { <ide> ngAnimate : '{leave: \'custom\'}' <ide> }); <del> $rootScope.$digest(); <add> <add> $rootScope.$digest(); // re-enable the animations; <add> window.setTimeout.expect(0).process(); <add> <ide> element.append(child); <ide> expect(element.contents().length).toBe(1); <ide> animator.leave(child, element); <ide> describe("$animator", function() { <ide> })); <ide> <ide> it("should animate the move animation event", inject(function($animator, $compile, $rootScope) { <add> $animator.enabled(true); <ide> animator = $animator($rootScope, { <ide> ngAnimate : '{move: \'custom\'}' <ide> }); <ide> describe("$animator", function() { <ide> })); <ide> <ide> it("should animate the show animation event", inject(function($animator, $rootScope) { <add> $animator.enabled(true); <ide> animator = $animator($rootScope, { <ide> ngAnimate : '{show: \'custom\'}' <ide> }); <ide> describe("$animator", function() { <ide> })); <ide> <ide> it("should animate the hide animation event", inject(function($animator, $rootScope) { <add> $animator.enabled(true); <ide> animator = $animator($rootScope, { <ide> ngAnimate : '{hide: \'custom\'}' <ide> }); <ide> describe("$animator", function() { <ide> <ide> it("should assign the ngAnimate string to all events if a string is given", <ide> inject(function($animator, $sniffer, $rootScope) { <add> $animator.enabled(true); <ide> if (!$sniffer.supportsTransitions) return; <ide> animator = $animator($rootScope, { <ide> ngAnimate : '"custom"' <ide> describe("$animator", function() { <ide> })); <ide> <ide> it("should run polyfillSetup and return the memento", inject(function($animator, $rootScope) { <add> $animator.enabled(true); <ide> animator = $animator($rootScope, { <ide> ngAnimate : '{show: \'setup-memo\'}' <ide> }); <ide> describe("$animator", function() { <ide> })); <ide> <ide> it("should not run if animations are disabled", inject(function($animator, $rootScope) { <add> $animator.enabled(true); <add> $rootScope.$digest(); // clear initial animation suppression <ide> $animator.enabled(false); <ide> <ide> animator = $animator($rootScope, { <ide> describe("$animator", function() { <ide> beforeEach(function() { <ide> module(function($animationProvider, $provide) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <del> return function($sniffer) { <add> return function($sniffer, _$rootElement_, $animator) { <ide> vendorPrefix = '-' + $sniffer.vendorPrefix + '-'; <add> $rootElement = _$rootElement_; <add> $animator.enabled(true); <ide> }; <ide> }) <ide> }); <ide> describe("$animator", function() { <ide> ngAnimate : '{show: \'inline-show\'}' <ide> }); <ide> <del> $rootScope.$digest(); // skip no-animate on first digest. <del> <ide> element.css('display','none'); <ide> expect(element.css('display')).toBe('none'); <ide> animator.show(element); <ide><path>test/ng/directive/ngIncludeSpec.js <ide> describe('ngInclude ngAnimate', function() { <ide> <ide> beforeEach(module(function($animationProvider, $provide) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <del> return function($sniffer) { <add> return function($sniffer, $animator) { <ide> vendorPrefix = '-' + $sniffer.vendorPrefix + '-'; <add> $animator.enabled(true); <ide> }; <ide> })); <ide> <ide><path>test/ng/directive/ngRepeatSpec.js <ide> describe('ngRepeat ngAnimate', function() { <ide> <ide> beforeEach(module(function($animationProvider, $provide) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <del> return function($sniffer) { <add> return function($sniffer, $animator) { <ide> vendorPrefix = '-' + $sniffer.vendorPrefix + '-'; <add> $animator.enabled(true); <ide> }; <ide> })); <ide> <ide><path>test/ng/directive/ngShowHideSpec.js <ide> describe('ngShow / ngHide', function() { <ide> describe('ngShow / ngHide - ngAnimate', function() { <ide> var window; <ide> var vendorPrefix; <del> var body, element; <add> var body, element, $rootElement; <ide> <ide> function html(html) { <del> body.html(html); <del> element = body.children().eq(0); <add> body.append($rootElement); <add> $rootElement.html(html); <add> element = $rootElement.children().eq(0); <ide> return element; <ide> } <ide> <ide> describe('ngShow / ngHide - ngAnimate', function() { <ide> afterEach(function(){ <ide> dealoc(body); <ide> dealoc(element); <add> body.removeAttr('ng-animation-running'); <ide> }); <ide> <ide> beforeEach(module(function($animationProvider, $provide) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <del> return function($sniffer) { <add> return function($sniffer, _$rootElement_, $animator) { <ide> vendorPrefix = '-' + $sniffer.vendorPrefix + '-'; <add> $rootElement = _$rootElement_; <add> $animator.enabled(true); <ide> }; <ide> })); <ide> <ide> describe('ngShow / ngHide - ngAnimate', function() { <ide> expect(element.attr('class')).not.toContain('custom-hide-setup'); <ide> })); <ide> <del> it('should skip the initial show state on the first digest', function() { <add> it('should skip animation if parent animation running', function() { <ide> var fired = false; <del> inject(function($compile, $rootScope, $sniffer) { <add> inject(function($animator, $compile, $rootScope, $sniffer) { <add> $animator.enabled(true); <add> $rootScope.$digest(); <ide> $rootScope.val = true; <ide> var element = $compile(html('<div ng-show="val" ng-animate="\'animation\'">123</div>'))($rootScope); <add> $rootElement.controller('ngAnimate').running = true; <ide> element.css('display','none'); <ide> expect(element.css('display')).toBe('none'); <ide> <ide> $rootScope.$digest(); <ide> expect(element[0].style.display).toBe(''); <ide> expect(fired).toBe(false); <ide> <add> $rootElement.controller('ngAnimate').running = false; <ide> $rootScope.val = false; <ide> $rootScope.$digest(); <ide> if ($sniffer.supportsTransitions) { <ide> describe('ngShow / ngHide - ngAnimate', function() { <ide> expect(element.attr('class')).not.toContain('custom-show-setup'); <ide> })); <ide> <del> it('should skip the initial hide state on the first digest', function() { <add> it('should disable animation when parent animation is running', function() { <ide> var fired = false; <ide> module(function($animationProvider) { <ide> $animationProvider.register('destructive-animation', function() { <ide> describe('ngShow / ngHide - ngAnimate', function() { <ide> inject(function($compile, $rootScope) { <ide> $rootScope.val = false; <ide> var element = $compile(html('<div ng-hide="val" ng-animate="{ hide:\'destructive-animation\' }">123</div>'))($rootScope); <add> $rootElement.controller('ngAnimate').running = true; <ide> element.css('display','block'); <ide> expect(element.css('display')).toBe('block'); <ide> <ide><path>test/ng/directive/ngSwitchSpec.js <ide> describe('ngSwitch ngAnimate', function() { <ide> <ide> beforeEach(module(function($animationProvider, $provide) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <del> return function($sniffer) { <add> return function($sniffer, $animator) { <ide> vendorPrefix = '-' + $sniffer.vendorPrefix + '-'; <add> $animator.enabled(true); <ide> }; <ide> })); <ide> <ide><path>test/ng/directive/ngViewSpec.js <ide> describe('ngView', function() { <ide> var element; <ide> <ide> beforeEach(module(function() { <del> return function($rootScope, $compile) { <add> return function($rootScope, $compile, $animator) { <ide> element = $compile('<ng:view onload="load()"></ng:view>')($rootScope); <add> $animator.enabled(true); <ide> }; <ide> })); <ide> <ide> describe('ngAnimate', function() { <ide> beforeEach(module(function($provide, $routeProvider) { <ide> $provide.value('$window', window = angular.mock.createMockWindow()); <ide> $routeProvider.when('/foo', {controller: noop, templateUrl: '/foo.html'}); <del> return function($templateCache) { <add> return function($templateCache, $animator) { <ide> $templateCache.put('/foo.html', [200, '<div>data</div>', {}]); <add> $animator.enabled(true); <ide> } <ide> })); <ide> <ide> describe('ngAnimate', function() { <ide> element = $compile(html( <ide> '<div ' + <ide> 'ng-view ' + <del> 'ng-animate="{enter: \'customEnter\', animateFirst: false}">' + <del> '</div>' <add> 'ng-animate="{enter: \'customEnter\'}">' + <add> '</div>' <ide> ))($rootScope); <ide> <ide> $location.path('/foo'); <ide><path>test/testabilityPatch.js <ide> beforeEach(function() { <ide> <ide> // reset to jQuery or default to us. <ide> bindJQuery(); <del> jqLite(document.body).html(''); <add> jqLite(document.body).html('').removeData(); <ide> }); <ide> <ide> afterEach(function() { <ide> if (this.$injector) { <ide> var $rootScope = this.$injector.get('$rootScope'); <add> var $rootElement = this.$injector.get('$rootElement'); <ide> var $log = this.$injector.get('$log'); <ide> // release the injector <ide> dealoc($rootScope); <add> dealoc($rootElement); <ide> <ide> // check $log mock <ide> $log.assertEmpty && $log.assertEmpty();
8
PHP
PHP
simplify booltype php conversion
c46c3da122dc307c354aac0eb87ed0a849e70b87
<ide><path>src/Database/Type/BoolType.php <ide> public function toDatabase($value, DriverInterface $driver): ?bool <ide> */ <ide> public function toPHP($value, DriverInterface $driver): ?bool <ide> { <del> if ($value === null || $value === true || $value === false) { <add> if ($value === null || is_bool($value)) { <ide> return $value; <ide> } <ide> <ide> public function toPHP($value, DriverInterface $driver): ?bool <ide> public function manyToPHP(array $values, array $fields, DriverInterface $driver): array <ide> { <ide> foreach ($fields as $field) { <del> if (!isset($values[$field]) || $values[$field] === true || $values[$field] === false) { <add> $value = $values[$field] ?? null; <add> if ($value === null || is_bool($value)) { <ide> continue; <ide> } <ide> <del> if ($values[$field] === '1') { <del> $values[$field] = true; <del> continue; <del> } <del> <del> if ($values[$field] === '0') { <del> $values[$field] = false; <del> continue; <del> } <del> <del> $value = $values[$field]; <ide> if (!is_numeric($value)) { <ide> $values[$field] = strtolower($value) === 'true'; <ide> continue;
1
Text
Text
add detailed example of env dict usage
bf83f6872a55e307da289fb901db3c16dd35e8d1
<ide><path>website/docs/usage/projects.md <ide> pipelines. <ide> > python -m spacy project run test . --vars.foo bar <ide> > ``` <ide> <add>> #### Tip: Environment Variables <add>> <add>> Commands in a project file are not executed in a shell, so they don't have <add>> direct access to environment variables. But you can insert environment <add>> variables using the `env` dictionary to make values available for <add>> interpolation, just like values in `vars`. Here's an example `env` dict that <add>> makes `$PATH` available as `ENV_PATH`: <add>> <add>> ```yaml <add>> env: <add>> ENV_PATH: PATH <add>> ``` <add>> <add>> This can be used in a project command like so: <add>> <add>> ```yaml <add>> - name: "echo-path" <add>> script: <add>> - "echo ${env.ENV_PATH}" <add>> ``` <add> <ide> | Section | Description | <ide> | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | <ide> | `title` | An optional project title used in `--help` message and [auto-generated docs](#custom-docs). |
1
Python
Python
add __len__() function and tests
321b1425e34d850cca84ca94ce64dae3f52c3d9a
<ide><path>data_structures/linked_list/__init__.py <ide> def __init__(self, item, next): <ide> class LinkedList: <ide> def __init__(self): <ide> self.head = None <add> self.size = 0 <ide> <ide> def add(self, item): <ide> self.head = Node(item, self.head) <add> self.size += 1 <ide> <ide> def remove(self): <ide> if self.is_empty(): <ide> return None <ide> else: <ide> item = self.head.item <ide> self.head = self.head.next <add> self.size -= 1 <ide> return item <ide> <ide> def is_empty(self): <ide> return self.head is None <add> <add> def __len__(self): <add> """ <add> >>> linked_list = LinkedList() <add> >>> len(linked_list) <add> 0 <add> >>> linked_list.add("a") <add> >>> len(linked_list) <add> 1 <add> >>> linked_list.add("b") <add> >>> len(linked_list) <add> 2 <add> >>> _ = linked_list.remove() <add> >>> len(linked_list) <add> 1 <add> >>> _ = linked_list.remove() <add> >>> len(linked_list) <add> 0 <add> """ <add> return self.size
1
Python
Python
add depthwiseconv1d layer
e96176aa0323583f3c1a08ca8e546e92e7ad628e
<ide><path>keras/layers/__init__.py <ide> from keras.layers.convolutional import Convolution3DTranspose <ide> from keras.layers.convolutional import SeparableConvolution1D <ide> from keras.layers.convolutional import SeparableConvolution2D <add>from keras.layers.convolutional import DepthwiseConv1D <ide> from keras.layers.convolutional import DepthwiseConv2D <ide> <ide> # Image processing layers. <ide><path>keras/layers/convolutional.py <ide> def call(self, inputs): <ide> return outputs <ide> <ide> <del>@keras_export('keras.layers.DepthwiseConv2D') <del>class DepthwiseConv2D(Conv2D): <del> """Depthwise 2D convolution. <add>class DepthwiseConv(Conv): <add> """Depthwise convolution. <ide> <ide> Depthwise convolution is a type of convolution in which a single convolutional <ide> filter is apply to each input channel (i.e. in a depthwise way). <ide> class DepthwiseConv2D(Conv2D): <ide> - Convolve each input with the layer's kernel (called a depthwise kernel). <ide> - Stack the convolved outputs together (along the channels axis). <ide> <del> Unlike a regular 2D convolution, depthwise convolution does not mix <add> Unlike a regular convolution, depthwise convolution does not mix <ide> information across different input channels. <ide> <ide> The `depth_multiplier` argument controls how many <ide> output channels are generated per input channel in the depthwise step. <ide> <ide> Args: <del> kernel_size: An integer or tuple/list of 2 integers, specifying the <del> height and width of the 2D convolution window. <del> Can be a single integer to specify the same value for <del> all spatial dimensions. <del> strides: An integer or tuple/list of 2 integers, <del> specifying the strides of the convolution along the height and width. <del> Can be a single integer to specify the same value for <add> kernel_size: A tuple or list of integers specifying the spatial <add> dimensions of the filters. Can be a single integer to specify the same <add> value for all spatial dimensions. <add> strides: A tuple or list of integers specifying the strides <add> of the convolution. Can be a single integer to specify the same value for <ide> all spatial dimensions. <del> Specifying any stride value != 1 is incompatible with specifying <add> Specifying any `stride` value != 1 is incompatible with specifying <ide> any `dilation_rate` value != 1. <del> padding: one of `'valid'` or `'same'` (case-insensitive). <add> padding: One of `"valid"` or `"same"` (case-insensitive). <ide> `"valid"` means no padding. `"same"` results in padding with zeros evenly <ide> to the left/right or up/down of the input such that output has the same <ide> height/width dimension as the input. <ide> class DepthwiseConv2D(Conv2D): <ide> """ <ide> <ide> def __init__(self, <add> rank, <ide> kernel_size, <del> strides=(1, 1), <add> strides=1, <ide> padding='valid', <ide> depth_multiplier=1, <ide> data_format=None, <del> dilation_rate=(1, 1), <add> dilation_rate=1, <ide> activation=None, <ide> use_bias=True, <ide> depthwise_initializer='glorot_uniform', <ide> def __init__(self, <ide> depthwise_constraint=None, <ide> bias_constraint=None, <ide> **kwargs): <del> super(DepthwiseConv2D, self).__init__( <add> super(DepthwiseConv, self).__init__( <add> rank, <ide> filters=None, <ide> kernel_size=kernel_size, <ide> strides=strides, <ide> def __init__(self, <ide> self.bias_initializer = initializers.get(bias_initializer) <ide> <ide> def build(self, input_shape): <del> if len(input_shape) < 4: <del> raise ValueError('Inputs to `DepthwiseConv2D` should have rank 4. ' <add> if len(input_shape) != self.rank + 2: <add> raise ValueError('Inputs to `DepthwiseConv` should have rank ', <add> str(self.rank + 2), '. ', <ide> 'Received input shape:', str(input_shape)) <ide> input_shape = tf.TensorShape(input_shape) <ide> channel_axis = self._get_channel_axis() <ide> if input_shape.dims[channel_axis].value is None: <ide> raise ValueError('The channel dimension of the inputs to ' <del> '`DepthwiseConv2D` ' <add> '`DepthwiseConv` ' <ide> 'should be defined. Found `None`.') <ide> input_dim = int(input_shape[channel_axis]) <del> depthwise_kernel_shape = (self.kernel_size[0], <del> self.kernel_size[1], <del> input_dim, <del> self.depth_multiplier) <add> depthwise_kernel_shape = self.kernel_size + (input_dim, <add> self.depth_multiplier) <ide> <ide> self.depthwise_kernel = self.add_weight( <ide> shape=depthwise_kernel_shape, <ide> def build(self, input_shape): <ide> else: <ide> self.bias = None <ide> # Set input spec. <del> self.input_spec = InputSpec(ndim=4, axes={channel_axis: input_dim}) <add> self.input_spec = InputSpec(min_ndim=self.rank + 2, <add> axes={channel_axis: input_dim}) <ide> self.built = True <ide> <add> def call(self, inputs): <add> raise NotImplementedError <add> <add> def get_config(self): <add> config = super(DepthwiseConv, self).get_config() <add> config.pop('filters') <add> config.pop('kernel_initializer') <add> config.pop('kernel_regularizer') <add> config.pop('kernel_constraint') <add> config['depth_multiplier'] = self.depth_multiplier <add> config['depthwise_initializer'] = initializers.serialize( <add> self.depthwise_initializer) <add> config['depthwise_regularizer'] = regularizers.serialize( <add> self.depthwise_regularizer) <add> config['depthwise_constraint'] = constraints.serialize( <add> self.depthwise_constraint) <add> return config <add> <add> <add>@keras_export('keras.layers.DepthwiseConv1D') <add>class DepthwiseConv1D(DepthwiseConv): <add> """Depthwise 1D convolution. <add> <add> Depthwise convolution is a type of convolution in which a single convolutional <add> filter is apply to each input channel (i.e. in a depthwise way). <add> You can understand depthwise convolution as being <add> the first step in a depthwise separable convolution. <add> <add> It is implemented via the following steps: <add> <add> - Split the input into individual channels. <add> - Convolve each input with the layer's kernel (called a depthwise kernel). <add> - Stack the convolved outputs together (along the channels axis). <add> <add> Unlike a regular 1D convolution, depthwise convolution does not mix <add> information across different input channels. <add> <add> The `depth_multiplier` argument controls how many <add> output channels are generated per input channel in the depthwise step. <add> <add> Args: <add> kernel_size: An integer, specifying the <add> height and width of the 1D convolution window. <add> Can be a single integer to specify the same value for <add> all spatial dimensions. <add> strides: An integer, <add> specifying the strides of the convolution along the height and width. <add> Can be a single integer to specify the same value for <add> all spatial dimensions. <add> Specifying any stride value != 1 is incompatible with specifying <add> any `dilation_rate` value != 1. <add> padding: one of `'valid'` or `'same'` (case-insensitive). <add> `"valid"` means no padding. `"same"` results in padding with zeros evenly <add> to the left/right or up/down of the input such that output has the same <add> height/width dimension as the input. <add> depth_multiplier: The number of depthwise convolution output channels <add> for each input channel. <add> The total number of depthwise convolution output <add> channels will be equal to `filters_in * depth_multiplier`. <add> data_format: A string, <add> one of `channels_last` (default) or `channels_first`. <add> The ordering of the dimensions in the inputs. <add> `channels_last` corresponds to inputs with shape <add> `(batch_size, height, width, channels)` while `channels_first` <add> corresponds to inputs with shape <add> `(batch_size, channels, height, width)`. <add> It defaults to the `image_data_format` value found in your <add> Keras config file at `~/.keras/keras.json`. <add> If you never set it, then it will be 'channels_last'. <add> dilation_rate: A single integer, specifying <add> the dilation rate to use for dilated convolution. <add> Currently, specifying any `dilation_rate` value != 1 is <add> incompatible with specifying any stride value != 1. <add> activation: Activation function to use. <add> If you don't specify anything, no activation is applied ( <add> see `keras.activations`). <add> use_bias: Boolean, whether the layer uses a bias vector. <add> depthwise_initializer: Initializer for the depthwise kernel matrix ( <add> see `keras.initializers`). If None, the default initializer ( <add> 'glorot_uniform') will be used. <add> bias_initializer: Initializer for the bias vector ( <add> see `keras.initializers`). If None, the default initializer ( <add> 'zeros') will bs used. <add> depthwise_regularizer: Regularizer function applied to <add> the depthwise kernel matrix (see `keras.regularizers`). <add> bias_regularizer: Regularizer function applied to the bias vector ( <add> see `keras.regularizers`). <add> activity_regularizer: Regularizer function applied to <add> the output of the layer (its 'activation') ( <add> see `keras.regularizers`). <add> depthwise_constraint: Constraint function applied to <add> the depthwise kernel matrix ( <add> see `keras.constraints`). <add> bias_constraint: Constraint function applied to the bias vector ( <add> see `keras.constraints`). <add> <add> Input shape: <add> 4D tensor with shape: <add> `[batch_size, channels, rows, cols]` if data_format='channels_first' <add> or 4D tensor with shape: <add> `[batch_size, rows, cols, channels]` if data_format='channels_last'. <add> <add> Output shape: <add> 4D tensor with shape: <add> `[batch_size, channels * depth_multiplier, new_rows, new_cols]` if <add> data_format='channels_first' or 4D tensor with shape: <add> `[batch_size, new_rows, new_cols, channels * depth_multiplier]` if <add> data_format='channels_last'. `rows` and `cols` values might have <add> changed due to padding. <add> <add> Returns: <add> A tensor of rank 4 representing <add> `activation(depthwiseconv2d(inputs, kernel) + bias)`. <add> <add> Raises: <add> ValueError: if `padding` is "causal". <add> ValueError: when both `strides` > 1 and `dilation_rate` > 1. <add> """ <add> <add> def __init__(self, <add> kernel_size, <add> strides=1, <add> padding='valid', <add> depth_multiplier=1, <add> data_format=None, <add> dilation_rate=1, <add> activation=None, <add> use_bias=True, <add> depthwise_initializer='glorot_uniform', <add> bias_initializer='zeros', <add> depthwise_regularizer=None, <add> bias_regularizer=None, <add> activity_regularizer=None, <add> depthwise_constraint=None, <add> bias_constraint=None, <add> **kwargs): <add> super(DepthwiseConv1D, self).__init__( <add> 1, <add> kernel_size=kernel_size, <add> strides=strides, <add> padding=padding, <add> depth_multiplier=depth_multiplier, <add> data_format=data_format, <add> dilation_rate=dilation_rate, <add> activation=activation, <add> use_bias=use_bias, <add> depthwise_initializer=depthwise_initializer, <add> bias_initializer=bias_initializer, <add> depthwise_regularizer=depthwise_regularizer, <add> bias_regularizer=bias_regularizer, <add> activity_regularizer=activity_regularizer, <add> depthwise_constraint=depthwise_constraint, <add> bias_constraint=bias_constraint, <add> **kwargs) <add> <add> def call(self, inputs): <add> if self.data_format == 'channels_last': <add> strides = (1,) + self.strides * 2 + (1,) <add> spatial_start_dim = 1 <add> else: <add> strides = (1, 1) + self.strides * 2 <add> spatial_start_dim = 2 <add> inputs = tf.expand_dims(inputs, spatial_start_dim) <add> depthwise_kernel = tf.expand_dims(self.depthwise_kernel, axis=0) <add> dilation_rate = (1,) + self.dilation_rate <add> <add> outputs = tf.nn.depthwise_conv2d( <add> inputs, <add> depthwise_kernel, <add> strides=strides, <add> padding=self.padding.upper(), <add> dilations=dilation_rate, <add> data_format=conv_utils.convert_data_format(self.data_format, <add> ndim=4)) <add> <add> if self.use_bias: <add> outputs = tf.nn.bias_add( <add> outputs, <add> self.bias, <add> data_format=conv_utils.convert_data_format(self.data_format, <add> ndim=4)) <add> <add> outputs = tf.squeeze(outputs, [spatial_start_dim]) <add> <add> if self.activation is not None: <add> return self.activation(outputs) <add> <add> return outputs <add> <add> @tf_utils.shape_type_conversion <add> def compute_output_shape(self, input_shape): <add> if self.data_format == 'channels_first': <add> rows = input_shape[2] <add> out_filters = input_shape[1] * self.depth_multiplier <add> elif self.data_format == 'channels_last': <add> rows = input_shape[1] <add> out_filters = input_shape[2] * self.depth_multiplier <add> <add> rows = conv_utils.conv_output_length(rows, self.kernel_size[0], <add> self.padding, <add> self.strides[0], <add> self.dilation_rate[0]) <add> if self.data_format == 'channels_first': <add> return (input_shape[0], out_filters, rows) <add> elif self.data_format == 'channels_last': <add> return (input_shape[0], rows, out_filters) <add> <add> <add>@keras_export('keras.layers.DepthwiseConv2D') <add>class DepthwiseConv2D(DepthwiseConv): <add> """Depthwise 2D convolution. <add> <add> Depthwise convolution is a type of convolution in which a single convolutional <add> filter is apply to each input channel (i.e. in a depthwise way). <add> You can understand depthwise convolution as being <add> the first step in a depthwise separable convolution. <add> <add> It is implemented via the following steps: <add> <add> - Split the input into individual channels. <add> - Convolve each input with the layer's kernel (called a depthwise kernel). <add> - Stack the convolved outputs together (along the channels axis). <add> <add> Unlike a regular 2D convolution, depthwise convolution does not mix <add> information across different input channels. <add> <add> The `depth_multiplier` argument controls how many <add> output channels are generated per input channel in the depthwise step. <add> <add> Args: <add> kernel_size: An integer or tuple/list of 2 integers, specifying the <add> height and width of the 2D convolution window. <add> Can be a single integer to specify the same value for <add> all spatial dimensions. <add> strides: An integer or tuple/list of 2 integers, <add> specifying the strides of the convolution along the height and width. <add> Can be a single integer to specify the same value for <add> all spatial dimensions. <add> Specifying any stride value != 1 is incompatible with specifying <add> any `dilation_rate` value != 1. <add> padding: one of `'valid'` or `'same'` (case-insensitive). <add> `"valid"` means no padding. `"same"` results in padding with zeros evenly <add> to the left/right or up/down of the input such that output has the same <add> height/width dimension as the input. <add> depth_multiplier: The number of depthwise convolution output channels <add> for each input channel. <add> The total number of depthwise convolution output <add> channels will be equal to `filters_in * depth_multiplier`. <add> data_format: A string, <add> one of `channels_last` (default) or `channels_first`. <add> The ordering of the dimensions in the inputs. <add> `channels_last` corresponds to inputs with shape <add> `(batch_size, height, width, channels)` while `channels_first` <add> corresponds to inputs with shape <add> `(batch_size, channels, height, width)`. <add> It defaults to the `image_data_format` value found in your <add> Keras config file at `~/.keras/keras.json`. <add> If you never set it, then it will be 'channels_last'. <add> dilation_rate: An integer or tuple/list of 2 integers, specifying <add> the dilation rate to use for dilated convolution. <add> Currently, specifying any `dilation_rate` value != 1 is <add> incompatible with specifying any `strides` value != 1. <add> activation: Activation function to use. <add> If you don't specify anything, no activation is applied ( <add> see `keras.activations`). <add> use_bias: Boolean, whether the layer uses a bias vector. <add> depthwise_initializer: Initializer for the depthwise kernel matrix ( <add> see `keras.initializers`). If None, the default initializer ( <add> 'glorot_uniform') will be used. <add> bias_initializer: Initializer for the bias vector ( <add> see `keras.initializers`). If None, the default initializer ( <add> 'zeros') will bs used. <add> depthwise_regularizer: Regularizer function applied to <add> the depthwise kernel matrix (see `keras.regularizers`). <add> bias_regularizer: Regularizer function applied to the bias vector ( <add> see `keras.regularizers`). <add> activity_regularizer: Regularizer function applied to <add> the output of the layer (its 'activation') ( <add> see `keras.regularizers`). <add> depthwise_constraint: Constraint function applied to <add> the depthwise kernel matrix ( <add> see `keras.constraints`). <add> bias_constraint: Constraint function applied to the bias vector ( <add> see `keras.constraints`). <add> <add> Input shape: <add> 4D tensor with shape: <add> `[batch_size, channels, rows, cols]` if data_format='channels_first' <add> or 4D tensor with shape: <add> `[batch_size, rows, cols, channels]` if data_format='channels_last'. <add> <add> Output shape: <add> 4D tensor with shape: <add> `[batch_size, channels * depth_multiplier, new_rows, new_cols]` if <add> data_format='channels_first' or 4D tensor with shape: <add> `[batch_size, new_rows, new_cols, channels * depth_multiplier]` if <add> data_format='channels_last'. `rows` and `cols` values might have <add> changed due to padding. <add> <add> Returns: <add> A tensor of rank 4 representing <add> `activation(depthwiseconv2d(inputs, kernel) + bias)`. <add> <add> Raises: <add> ValueError: if `padding` is "causal". <add> ValueError: when both `strides` > 1 and `dilation_rate` > 1. <add> """ <add> <add> def __init__(self, <add> kernel_size, <add> strides=(1, 1), <add> padding='valid', <add> depth_multiplier=1, <add> data_format=None, <add> dilation_rate=(1, 1), <add> activation=None, <add> use_bias=True, <add> depthwise_initializer='glorot_uniform', <add> bias_initializer='zeros', <add> depthwise_regularizer=None, <add> bias_regularizer=None, <add> activity_regularizer=None, <add> depthwise_constraint=None, <add> bias_constraint=None, <add> **kwargs): <add> super(DepthwiseConv2D, self).__init__( <add> 2, <add> kernel_size=kernel_size, <add> strides=strides, <add> padding=padding, <add> depth_multiplier=depth_multiplier, <add> data_format=data_format, <add> dilation_rate=dilation_rate, <add> activation=activation, <add> use_bias=use_bias, <add> depthwise_initializer=depthwise_initializer, <add> bias_initializer=bias_initializer, <add> depthwise_regularizer=depthwise_regularizer, <add> bias_regularizer=bias_regularizer, <add> activity_regularizer=activity_regularizer, <add> depthwise_constraint=depthwise_constraint, <add> bias_constraint=bias_constraint, <add> **kwargs) <add> <ide> def call(self, inputs): <ide> outputs = backend.depthwise_conv2d( <ide> inputs, <ide> def compute_output_shape(self, input_shape): <ide> elif self.data_format == 'channels_last': <ide> return (input_shape[0], rows, cols, out_filters) <ide> <del> def get_config(self): <del> config = super(DepthwiseConv2D, self).get_config() <del> config.pop('filters') <del> config.pop('kernel_initializer') <del> config.pop('kernel_regularizer') <del> config.pop('kernel_constraint') <del> config['depth_multiplier'] = self.depth_multiplier <del> config['depthwise_initializer'] = initializers.serialize( <del> self.depthwise_initializer) <del> config['depthwise_regularizer'] = regularizers.serialize( <del> self.depthwise_regularizer) <del> config['depthwise_constraint'] = constraints.serialize( <del> self.depthwise_constraint) <del> return config <del> <ide> <ide> @keras_export('keras.layers.UpSampling1D') <ide> class UpSampling1D(Layer): <ide><path>keras/layers/convolutional_test.py <ide> def test_cropping_3d(self): <ide> keras.layers.Cropping3D(cropping=None) <ide> <ide> <add>@keras_parameterized.run_all_keras_modes <add>class DepthwiseConv1DTest(keras_parameterized.TestCase): <add> <add> def _run_test(self, kwargs, expected_output_shape=None): <add> num_samples = 2 <add> stack_size = 3 <add> num_row = 7 <add> <add> with self.cached_session(): <add> testing_utils.layer_test( <add> keras.layers.DepthwiseConv1D, <add> kwargs=kwargs, <add> input_shape=(num_samples, num_row, stack_size), <add> expected_output_shape=expected_output_shape) <add> <add> @parameterized.named_parameters( <add> ('padding_valid', {'padding': 'valid'}), <add> ('padding_same', {'padding': 'same'}), <add> ('strides', {'strides': 2}), <add> # Only runs on GPU with CUDA, channels_first is not supported on CPU. <add> # TODO(b/62340061): Support channels_first on CPU. <add> ('data_format', {'data_format': 'channels_first'}), <add> ('depth_multiplier_1', {'depth_multiplier': 1}), <add> ('depth_multiplier_2', {'depth_multiplier': 2}), <add> ('dilation_rate', {'dilation_rate': 2}, (None, 3, 3)), <add> ) <add> def test_depthwise_conv1d(self, kwargs, expected_output_shape=None): <add> kwargs['kernel_size'] = 3 <add> if 'data_format' not in kwargs or tf.test.is_gpu_available(cuda_only=True): <add> self._run_test(kwargs, expected_output_shape) <add> <add> def test_depthwise_conv1d_full(self): <add> kwargs = { <add> 'kernel_size': 3, <add> 'padding': 'valid', <add> 'data_format': 'channels_last', <add> 'dilation_rate': 1, <add> 'activation': None, <add> 'depthwise_regularizer': 'l2', <add> 'bias_regularizer': 'l2', <add> 'activity_regularizer': 'l2', <add> 'depthwise_constraint': 'unit_norm', <add> 'use_bias': True, <add> 'strides': 2, <add> 'depth_multiplier': 1, <add> } <add> self._run_test(kwargs) <add> <add> <ide> @keras_parameterized.run_all_keras_modes <ide> class DepthwiseConv2DTest(keras_parameterized.TestCase): <ide>
3
Python
Python
extend comments _block_check_depths_match
ff7f72690f810d00c13d071fc5c4205c6a21cccf
<ide><path>numpy/core/shape_base.py <ide> def stack(arrays, axis=0, out=None): <ide> return _nx.concatenate(expanded_arrays, axis=axis, out=out) <ide> <ide> <del>def _block_check_depths_match(arrays, index=[]): <del> # Recursive function checking that the depths of nested lists in `arrays` <del> # all match. Mismatch raises a ValueError as described in the block <del> # docstring below. <del> # The entire index (rather than just the depth) is calculated for each <del> # innermost list, in case an error needs to be raised, so that the index <del> # of the offending list can be printed as part of the error. <add>def _block_check_depths_match(arrays, parent_index=[]): <add> """ <add> Recursive function checking that the depths of nested lists in `arrays` <add> all match. Mismatch raises a ValueError as described in the block <add> docstring below. <add> <add> The entire index (rather than just the depth) needs to be calculated <add> for each innermost list, in case an error needs to be raised, so that <add> the index of the offending list can be printed as part of the error. <add> <add> The parameter `parent_index` is the full index of `arrays` within the <add> nested lists passed to _block_check_depths_match at the top of the <add> recursion. <add> The return value is the full index of an element (specifically the <add> first element) from the bottom of the nesting in `arrays`. An empty <add> list at the bottom of the nesting is represented by a `None` index. <add> """ <ide> def format_index(index): <ide> idx_str = ''.join('[{}]'.format(i) for i in index if i is not None) <ide> return 'arrays' + idx_str <ide> def format_index(index): <ide> '{} is a tuple. ' <ide> 'Only lists can be used to arrange blocks, and np.block does ' <ide> 'not allow implicit conversion from tuple to ndarray.'.format( <del> format_index(index) <add> format_index(parent_index) <ide> ) <ide> ) <ide> elif type(arrays) is list and len(arrays) > 0: <del> indexes = [_block_check_depths_match(arr, index + [i]) <add> indexes = [_block_check_depths_match(arr, parent_index + [i]) <ide> for i, arr in enumerate(arrays)] <ide> <ide> first_index = indexes[0] <ide> def format_index(index): <ide> return first_index <ide> elif type(arrays) is list and len(arrays) == 0: <ide> # We've 'bottomed out' on an empty list <del> return index + [None] <add> return parent_index + [None] <ide> else: <del> # We've 'bottomed out' <del> return index <add> # We've 'bottomed out' - arrays is either a scalar or an array <add> return parent_index <ide> <ide> <ide> def _block(arrays, depth=0): <ide> def atleast_nd(a, ndim): <ide> arrs = [atleast_nd(a, ndim) for a in arrs] <ide> return _nx.concatenate(arrs, axis=depth+ndim-list_ndim), list_ndim <ide> else: <del> # We've 'bottomed out' <add> # We've 'bottomed out' - arrays is either a scalar or an array <ide> return atleast_nd(arrays, depth), depth <ide> <ide>
1
Python
Python
remove unnecessary parens after 'del' keyword
02613f322322c89ce0bf71cba7226831d3c227c3
<ide><path>glances/plugins/glances_docker.py <ide> def update(self): <ide> logger.debug("{0} plugin - Stop thread for old container {1}".format(self.plugin_name, container_id[:12])) <ide> self.thread_list[container_id].stop() <ide> # Delete the item from the dict <del> del(self.thread_list[container_id]) <add> del self.thread_list[container_id] <ide> <ide> # Get stats for all containers <ide> for container in self.stats['containers']:
1
Python
Python
fix a test
e790601f9969e4a51247ca5184546eba6e93e196
<ide><path>libcloud/test/storage/test_local.py <ide> except ImportError: <ide> print('lockfile library is not available, skipping local_storage tests...') <ide> LocalStorageDriver = None <add> LockTimeout = None <ide> <ide> from libcloud.storage.drivers.dummy import DummyIterator <ide>
1
Ruby
Ruby
remove unused mget_capable? flag
c617b8f8fdb1a0e905a3ea91f900d17ad55ea78d
<ide><path>activesupport/lib/active_support/cache/redis_cache_store.rb <ide> def inspect <ide> # Read multiple values at once. Returns a hash of requested keys -> <ide> # fetched values. <ide> def read_multi(*names) <del> if mget_capable? <del> instrument(:read_multi, names, options) do |payload| <del> read_multi_mget(*names).tap do |results| <del> payload[:hits] = results.keys <del> end <add> options = names.extract_options! <add> instrument(:read_multi, names, options) do |payload| <add> read_multi_entries(names, **options).tap do |results| <add> payload[:hits] = results.keys <ide> end <del> else <del> super <ide> end <ide> end <ide> <ide> def stats <ide> redis.with { |c| c.info } <ide> end <ide> <del> def mget_capable? # :nodoc: <del> set_redis_capabilities unless defined? @mget_capable <del> @mget_capable <del> end <del> <ide> def mset_capable? # :nodoc: <ide> set_redis_capabilities unless defined? @mset_capable <ide> @mset_capable <ide> def mset_capable? # :nodoc: <ide> def set_redis_capabilities <ide> case redis <ide> when Redis::Distributed <del> @mget_capable = true <ide> @mset_capable = false <ide> else <del> @mget_capable = true <ide> @mset_capable = true <ide> end <ide> end <ide> def read_serialized_entry(key, raw: false, **options) <ide> end <ide> <ide> def read_multi_entries(names, **options) <del> if mget_capable? <del> read_multi_mget(*names, **options) <del> else <del> super <del> end <del> end <del> <del> def read_multi_mget(*names) <del> options = names.extract_options! <ide> options = merged_options(options) <ide> return {} if names == [] <ide> raw = options&.fetch(:raw, false) <ide> <ide> keys = names.map { |name| normalize_key(name, options) } <ide> <del> values = failsafe(:read_multi_mget, returning: {}) do <add> values = failsafe(:read_multi_entries, returning: {}) do <ide> redis.with { |c| c.mget(*keys) } <ide> end <ide>
1
Text
Text
use the same case as the section heading
359c93d3ab37443c27143c86ad84d5e130fe066c
<ide><path>README.md <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys 108F52B48DB57BB0CC439B2997B0 <ide> gpg --keyserver pool.sks-keyservers.net --recv-keys B9E2F5981AA6E0CD28160D9FF13993A75599653C <ide> ``` <ide> <del>See the section above on [Verifying Binaries](#verifying-binaries) for how to <add>See the section above on [Verifying binaries](#verifying-binaries) for how to <ide> use these keys to verify a downloaded file. <ide> <ide> <details>
1
Javascript
Javascript
set evt.src to empty string or src attr from load
46d8b3738567c43a4818dd0abe086fc4bd041dbd
<ide><path>src/js/player.js <ide> class Player extends Component { <ide> } <ide> <ide> /** <del> * Fired when the source is set or changed on the {@link Tech} <add> * *EXPERIMENTAL* Fired when the source is set or changed on the {@link Tech} <ide> * causing the media element to reload. <ide> * <ide> * It will fire for the initial source and each subsequent source. <ide> class Player extends Component { <ide> * <ide> * It is also fired when `load` is called on the player (or media element) <ide> * because the {@link https://html.spec.whatwg.org/multipage/media.html#dom-media-load|specification for `load`} <del> * says that the resource selection algorithm <del> * needs to be aborted and restarted. <add> * says that the resource selection algorithm needs to be aborted and restarted. <add> * In this case, it is very likely that the `src` property will be set to the <add> * empty string `""` to indicate we do not know what the source will be but <add> * that it is changing. <add> * <add> * *This event is currently still experimental and may change in minor releases.* <ide> * <ide> * @event Player#sourceset <ide> * @type {EventTarget~Event} <del> * @prop {string} src The source url available when the `sourceset` was triggered <add> * @prop {string} src <add> * The source url available when the `sourceset` was triggered. <add> * It will be an empty string if we cannot know what the source is <add> * but know that the source will change. <ide> */ <ide> /** <ide> * Retrigger the `sourceset` event that was triggered by the {@link Tech}. <ide><path>src/js/tech/html5.js <ide> class Html5 extends Tech { <ide> el.load = () => { <ide> const retval = oldLoad.call(el); <ide> <del> this.triggerSourceset(el.src || el.currentSrc); <add> // if `el.src` is set, that source will be loaded <add> // otherwise, we can't know for sure what source will be set because <add> // source elements will be used but implementing the source selection algorithm <add> // is laborious and asynchronous, so, <add> // instead return an empty string to basically indicate source may change <add> this.triggerSourceset(el.src || ''); <ide> <ide> return retval; <ide> }; <ide><path>test/karma.conf.js <ide> function getCustomLaunchers(){ <ide> base: 'BrowserStack', <ide> browser: 'safari', <ide> os: 'OS X', <del> os_version: 'Yosemite' <add> os_version: 'El Capitan' <ide> }, <ide> <ide> edge_bs: { <ide><path>test/unit/sourceset.test.js <ide> QUnit[qunitFn]('sourceset', function(hooks) { <ide> const done = assert.async(); <ide> <ide> this.player = videojs(this.mediaEl); <del> this.player.src(this.testSrc); <del> <ide> this.player.one('sourceset', () => { <ide> validateSource(assert, this.player, [this.testSrc]); <ide> done(); <ide> }); <add> <add> this.player.src(this.testSrc); <ide> }); <ide> <ide> // TODO: unskip when https://github.com/videojs/video.js/pull/4861 is merged <ide> QUnit[qunitFn]('sourceset', function(hooks) { <ide> <ide> this.mediaEl.setAttribute('preload', 'auto'); <ide> this.player = videojs(this.mediaEl); <del> this.player.src(this.testSrc); <ide> <ide> this.player.one('sourceset', () => { <ide> validateSource(assert, this.player, [this.testSrc]); <ide> done(); <ide> }); <add> <add> this.player.src(this.testSrc); <ide> }); <ide> <ide> QUnit.test('player.src({...}) two sources', function(assert) { <ide> const done = assert.async(); <ide> <ide> this.player = videojs(this.mediaEl); <del> this.player.src([this.sourceOne, this.sourceTwo]); <ide> <ide> this.player.one('sourceset', () => { <ide> validateSource(assert, this.player, [this.sourceOne, this.sourceTwo]); <ide> done(); <ide> }); <add> <add> this.player.src([this.sourceOne, this.sourceTwo]); <ide> }); <ide> <ide> QUnit.test('mediaEl.src = ...;', function(assert) { <ide> QUnit[qunitFn]('sourceset', function(hooks) { <ide> this.mediaEl.setAttribute('src', this.sourceTwo.src); <ide> }); <ide> <del> QUnit.test('mediaEl.load()', function(assert) { <add> QUnit.test('load() with a src attribute', function(assert) { <ide> const done = assert.async(); <add> <add> this.player = videojs(this.mediaEl); <add> <add> this.totalSourcesets = 1; <add> <add> window.setTimeout(() => { <add> this.sourcesets = 0; <add> this.totalSourcesets = 1; <add> <add> this.player.one('sourceset', (e) => { <add> assert.equal(e.src, this.mediaEl.src, "the sourceset event's src matches the src attribute"); <add> <add> done(); <add> }); <add> <add> this.player.load(); <add> }, wait); <add> }); <add> <add> QUnit.test('mediaEl.load()', function(assert) { <ide> const source = document.createElement('source'); <ide> <ide> source.src = this.testSrc.src; <ide> QUnit[qunitFn]('sourceset', function(hooks) { <ide> // elements instead <ide> this.mediaEl.removeAttribute('src'); <ide> <del> this.player.one('sourceset', () => { <del> validateSource(assert, this.player, [this.testSrc], false); <add> this.player.one('sourceset', (e1) => { <add> assert.equal(e1.src, '', 'we got a sourceset with an empty src'); <ide> <del> this.player.one('sourceset', () => { <del> validateSource(assert, this.player, [this.sourceOne], false); <del> done(); <add> this.player.one('sourceset', (e2) => { <add> assert.equal(e2.src, '', 'we got a sourceset with an empty src'); <ide> }); <ide> <ide> source.src = this.sourceOne.src; <ide> QUnit[qunitFn]('sourceset', function(hooks) { <ide> }); <ide> <ide> QUnit.test('mediaEl.load() x2 at the same time', function(assert) { <del> const done = assert.async(); <ide> const source = document.createElement('source'); <ide> <ide> source.src = this.sourceOne.src; <ide> source.type = this.sourceOne.type; <ide> <del> this.player.one('sourceset', () => { <del> validateSource(assert, this.player, [this.sourceOne], false); <add> this.player.one('sourceset', (e1) => { <add> assert.equal(e1.src, '', 'we got a sourceset with an empty src'); <ide> <del> this.player.one('sourceset', () => { <del> validateSource(assert, this.player, [this.sourceTwo], false); <del> done(); <add> this.player.one('sourceset', (e2) => { <add> assert.equal(e2.src, '', 'we got a sourceset with an empty src'); <ide> }); <ide> }); <ide>
4
PHP
PHP
replace 4 spaces with tabs
bd2533d93595edefc2b6e9afed23cef83f062b14
<ide><path>src/Illuminate/Foundation/Testing/ApplicationTrait.php <ide> <ide> trait ApplicationTrait { <ide> <del> /** <del> * The Illuminate application instance. <del> * <del> * @var \Illuminate\Foundation\Application <del> */ <del> protected $app; <del> <del> /** <del> * The HttpKernel client instance. <del> * <del> * @var \Illuminate\Foundation\Testing\Client <del> */ <del> protected $client; <del> <del> /** <del> * Refresh the application instance. <del> * <del> * @return void <del> */ <del> protected function refreshApplication() <del> { <del> $this->app = $this->createApplication(); <del> <del> $this->client = $this->createClient(); <del> <del> $this->app->setRequestForConsoleEnvironment(); <del> <del> $this->app->boot(); <del> } <del> <del> /** <del> * Call the given URI and return the Response. <del> * <del> * @param string $method <del> * @param string $uri <del> * @param array $parameters <del> * @param array $files <del> * @param array $server <del> * @param string $content <del> * @param bool $changeHistory <del> * @return \Illuminate\Http\Response <del> */ <del> public function call($method, $uri, $parameters = [], $files = [], $server = [], $content = null, $changeHistory = true) <del> { <del> $this->client->request($method, $uri, $parameters, $files, $server, $content, $changeHistory); <del> <del> return $this->client->getResponse(); <del> } <del> <del> /** <del> * Call the given HTTPS URI and return the Response. <del> * <del> * @param string $method <del> * @param string $uri <del> * @param array $parameters <del> * @param array $files <del> * @param array $server <del> * @param string $content <del> * @param bool $changeHistory <del> * @return \Illuminate\Http\Response <del> */ <del> public function callSecure($method, $uri, $parameters = [], $files = [], $server = [], $content = null, $changeHistory = true) <del> { <del> $uri = 'https://localhost/'.ltrim($uri, '/'); <del> <del> return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory); <del> } <del> <del> /** <del> * Call a controller action and return the Response. <del> * <del> * @param string $method <del> * @param string $action <del> * @param array $wildcards <del> * @param array $parameters <del> * @param array $files <del> * @param array $server <del> * @param string $content <del> * @param bool $changeHistory <del> * @return \Illuminate\Http\Response <del> */ <del> public function action($method, $action, $wildcards = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true) <del> { <del> $uri = $this->app['url']->action($action, $wildcards, true); <del> <del> return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory); <del> } <del> <del> /** <del> * Call a named route and return the Response. <del> * <del> * @param string $method <del> * @param string $name <del> * @param array $routeParameters <del> * @param array $parameters <del> * @param array $files <del> * @param array $server <del> * @param string $content <del> * @param bool $changeHistory <del> * @return \Illuminate\Http\Response <del> */ <del> public function route($method, $name, $routeParameters = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true) <del> { <del> $uri = $this->app['url']->route($name, $routeParameters); <del> <del> return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory); <del> } <del> <del> /** <del> * Set the session to the given array. <del> * <del> * @param array $data <del> * @return void <del> */ <del> public function session(array $data) <del> { <del> $this->startSession(); <del> <del> foreach ($data as $key => $value) <del> { <del> $this->app['session']->put($key, $value); <del> } <del> } <del> <del> /** <del> * Flush all of the current session data. <del> * <del> * @return void <del> */ <del> public function flushSession() <del> { <del> $this->startSession(); <del> <del> $this->app['session']->flush(); <del> } <del> <del> /** <del> * Start the session for the application. <del> * <del> * @return void <del> */ <del> protected function startSession() <del> { <del> if ( ! $this->app['session']->isStarted()) <del> { <del> $this->app['session']->start(); <del> } <del> } <del> <del> /** <del> * Set the currently logged in user for the application. <del> * <del> * @param \Illuminate\Auth\UserInterface $user <del> * @param string $driver <del> * @return void <del> */ <del> public function be(UserInterface $user, $driver = null) <del> { <del> $this->app['auth']->driver($driver)->setUser($user); <del> } <del> <del> /** <del> * Seed a given database connection. <del> * <del> * @param string $class <del> * @return void <del> */ <del> public function seed($class = 'DatabaseSeeder') <del> { <del> $this->app['artisan']->call('db:seed', array('--class' => $class)); <del> } <del> <del> /** <del> * Create a new HttpKernel client instance. <del> * <del> * @param array $server <del> * @return \Symfony\Component\HttpKernel\Client <del> */ <del> protected function createClient(array $server = array()) <del> { <del> return new Client($this->app, $server); <del> } <add> /** <add> * The Illuminate application instance. <add> * <add> * @var \Illuminate\Foundation\Application <add> */ <add> protected $app; <add> <add> /** <add> * The HttpKernel client instance. <add> * <add> * @var \Illuminate\Foundation\Testing\Client <add> */ <add> protected $client; <add> <add> /** <add> * Refresh the application instance. <add> * <add> * @return void <add> */ <add> protected function refreshApplication() <add> { <add> $this->app = $this->createApplication(); <add> <add> $this->client = $this->createClient(); <add> <add> $this->app->setRequestForConsoleEnvironment(); <add> <add> $this->app->boot(); <add> } <add> <add> /** <add> * Call the given URI and return the Response. <add> * <add> * @param string $method <add> * @param string $uri <add> * @param array $parameters <add> * @param array $files <add> * @param array $server <add> * @param string $content <add> * @param bool $changeHistory <add> * @return \Illuminate\Http\Response <add> */ <add> public function call($method, $uri, $parameters = [], $files = [], $server = [], $content = null, $changeHistory = true) <add> { <add> $this->client->request($method, $uri, $parameters, $files, $server, $content, $changeHistory); <add> <add> return $this->client->getResponse(); <add> } <add> <add> /** <add> * Call the given HTTPS URI and return the Response. <add> * <add> * @param string $method <add> * @param string $uri <add> * @param array $parameters <add> * @param array $files <add> * @param array $server <add> * @param string $content <add> * @param bool $changeHistory <add> * @return \Illuminate\Http\Response <add> */ <add> public function callSecure($method, $uri, $parameters = [], $files = [], $server = [], $content = null, $changeHistory = true) <add> { <add> $uri = 'https://localhost/'.ltrim($uri, '/'); <add> <add> return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory); <add> } <add> <add> /** <add> * Call a controller action and return the Response. <add> * <add> * @param string $method <add> * @param string $action <add> * @param array $wildcards <add> * @param array $parameters <add> * @param array $files <add> * @param array $server <add> * @param string $content <add> * @param bool $changeHistory <add> * @return \Illuminate\Http\Response <add> */ <add> public function action($method, $action, $wildcards = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true) <add> { <add> $uri = $this->app['url']->action($action, $wildcards, true); <add> <add> return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory); <add> } <add> <add> /** <add> * Call a named route and return the Response. <add> * <add> * @param string $method <add> * @param string $name <add> * @param array $routeParameters <add> * @param array $parameters <add> * @param array $files <add> * @param array $server <add> * @param string $content <add> * @param bool $changeHistory <add> * @return \Illuminate\Http\Response <add> */ <add> public function route($method, $name, $routeParameters = array(), $parameters = array(), $files = array(), $server = array(), $content = null, $changeHistory = true) <add> { <add> $uri = $this->app['url']->route($name, $routeParameters); <add> <add> return $this->call($method, $uri, $parameters, $files, $server, $content, $changeHistory); <add> } <add> <add> /** <add> * Set the session to the given array. <add> * <add> * @param array $data <add> * @return void <add> */ <add> public function session(array $data) <add> { <add> $this->startSession(); <add> <add> foreach ($data as $key => $value) <add> { <add> $this->app['session']->put($key, $value); <add> } <add> } <add> <add> /** <add> * Flush all of the current session data. <add> * <add> * @return void <add> */ <add> public function flushSession() <add> { <add> $this->startSession(); <add> <add> $this->app['session']->flush(); <add> } <add> <add> /** <add> * Start the session for the application. <add> * <add> * @return void <add> */ <add> protected function startSession() <add> { <add> if ( ! $this->app['session']->isStarted()) <add> { <add> $this->app['session']->start(); <add> } <add> } <add> <add> /** <add> * Set the currently logged in user for the application. <add> * <add> * @param \Illuminate\Auth\UserInterface $user <add> * @param string $driver <add> * @return void <add> */ <add> public function be(UserInterface $user, $driver = null) <add> { <add> $this->app['auth']->driver($driver)->setUser($user); <add> } <add> <add> /** <add> * Seed a given database connection. <add> * <add> * @param string $class <add> * @return void <add> */ <add> public function seed($class = 'DatabaseSeeder') <add> { <add> $this->app['artisan']->call('db:seed', array('--class' => $class)); <add> } <add> <add> /** <add> * Create a new HttpKernel client instance. <add> * <add> * @param array $server <add> * @return \Symfony\Component\HttpKernel\Client <add> */ <add> protected function createClient(array $server = array()) <add> { <add> return new Client($this->app, $server); <add> } <ide> <ide> } <ide><path>src/Illuminate/Foundation/Testing/AssertionsTrait.php <ide> <ide> trait AssertionsTrait { <ide> <del> /** <del> * Assert that the client response has an OK status code. <del> * <del> * @return void <del> */ <del> public function assertResponseOk() <del> { <del> $response = $this->client->getResponse(); <del> <del> $actual = $response->getStatusCode(); <del> <del> return $this->assertTrue($response->isOk(), 'Expected status code 200, got ' .$actual); <del> } <del> <del> /** <del> * Assert that the client response has a given code. <del> * <del> * @param int $code <del> * @return void <del> */ <del> public function assertResponseStatus($code) <del> { <del> return $this->assertEquals($code, $this->client->getResponse()->getStatusCode()); <del> } <del> <del> /** <del> * Assert that the response view has a given piece of bound data. <del> * <del> * @param string|array $key <del> * @param mixed $value <del> * @return void <del> */ <del> public function assertViewHas($key, $value = null) <del> { <del> if (is_array($key)) return $this->assertViewHasAll($key); <del> <del> $response = $this->client->getResponse(); <del> <del> if ( ! isset($response->original) || ! $response->original instanceof View) <del> { <del> return $this->assertTrue(false, 'The response was not a view.'); <del> } <del> <del> if (is_null($value)) <del> { <del> $this->assertArrayHasKey($key, $response->original->getData()); <del> } <del> else <del> { <del> $this->assertEquals($value, $response->original->$key); <del> } <del> } <del> <del> /** <del> * Assert that the view has a given list of bound data. <del> * <del> * @param array $bindings <del> * @return void <del> */ <del> public function assertViewHasAll(array $bindings) <del> { <del> foreach ($bindings as $key => $value) <del> { <del> if (is_int($key)) <del> { <del> $this->assertViewHas($value); <del> } <del> else <del> { <del> $this->assertViewHas($key, $value); <del> } <del> } <del> } <del> <del> /** <del> * Assert that the response view is missing a piece of bound data. <del> * <del> * @param string $key <del> * @return void <del> */ <del> public function assertViewMissing($key) <del> { <del> $response = $this->client->getResponse(); <del> <del> if ( ! isset($response->original) || ! $response->original instanceof View) <del> { <del> return $this->assertTrue(false, 'The response was not a view.'); <del> } <del> <del> $this->assertArrayNotHasKey($key, $response->original->getData()); <del> } <del> <del> /** <del> * Assert whether the client was redirected to a given URI. <del> * <del> * @param string $uri <del> * @param array $with <del> * @return void <del> */ <del> public function assertRedirectedTo($uri, $with = array()) <del> { <del> $response = $this->client->getResponse(); <del> <del> $this->assertInstanceOf('Illuminate\Http\RedirectResponse', $response); <del> <del> $this->assertEquals($this->app['url']->to($uri), $response->headers->get('Location')); <del> <del> $this->assertSessionHasAll($with); <del> } <del> <del> /** <del> * Assert whether the client was redirected to a given route. <del> * <del> * @param string $name <del> * @param array $parameters <del> * @param array $with <del> * @return void <del> */ <del> public function assertRedirectedToRoute($name, $parameters = array(), $with = array()) <del> { <del> $this->assertRedirectedTo($this->app['url']->route($name, $parameters), $with); <del> } <del> <del> /** <del> * Assert whether the client was redirected to a given action. <del> * <del> * @param string $name <del> * @param array $parameters <del> * @param array $with <del> * @return void <del> */ <del> public function assertRedirectedToAction($name, $parameters = array(), $with = array()) <del> { <del> $this->assertRedirectedTo($this->app['url']->action($name, $parameters), $with); <del> } <del> <del> /** <del> * Assert that the session has a given list of values. <del> * <del> * @param string|array $key <del> * @param mixed $value <del> * @return void <del> */ <del> public function assertSessionHas($key, $value = null) <del> { <del> if (is_array($key)) return $this->assertSessionHasAll($key); <del> <del> if (is_null($value)) <del> { <del> $this->assertTrue($this->app['session.store']->has($key), "Session missing key: $key"); <del> } <del> else <del> { <del> $this->assertEquals($value, $this->app['session.store']->get($key)); <del> } <del> } <del> <del> /** <del> * Assert that the session has a given list of values. <del> * <del> * @param array $bindings <del> * @return void <del> */ <del> public function assertSessionHasAll(array $bindings) <del> { <del> foreach ($bindings as $key => $value) <del> { <del> if (is_int($key)) <del> { <del> $this->assertSessionHas($value); <del> } <del> else <del> { <del> $this->assertSessionHas($key, $value); <del> } <del> } <del> } <del> <del> /** <del> * Assert that the session has errors bound. <del> * <del> * @param string|array $bindings <del> * @param mixed $format <del> * @return void <del> */ <del> public function assertSessionHasErrors($bindings = array(), $format = null) <del> { <del> $this->assertSessionHas('errors'); <del> <del> $bindings = (array) $bindings; <del> <del> $errors = $this->app['session.store']->get('errors'); <del> <del> foreach ($bindings as $key => $value) <del> { <del> if (is_int($key)) <del> { <del> $this->assertTrue($errors->has($value), "Session missing error: $value"); <del> } <del> else <del> { <del> $this->assertContains($value, $errors->get($key, $format)); <del> } <del> } <del> } <del> <del> /** <del> * Assert that the session has old input. <del> * <del> * @return void <del> */ <del> public function assertHasOldInput() <del> { <del> $this->assertSessionHas('_old_input'); <del> } <add> /** <add> * Assert that the client response has an OK status code. <add> * <add> * @return void <add> */ <add> public function assertResponseOk() <add> { <add> $response = $this->client->getResponse(); <add> <add> $actual = $response->getStatusCode(); <add> <add> return $this->assertTrue($response->isOk(), 'Expected status code 200, got ' .$actual); <add> } <add> <add> /** <add> * Assert that the client response has a given code. <add> * <add> * @param int $code <add> * @return void <add> */ <add> public function assertResponseStatus($code) <add> { <add> return $this->assertEquals($code, $this->client->getResponse()->getStatusCode()); <add> } <add> <add> /** <add> * Assert that the response view has a given piece of bound data. <add> * <add> * @param string|array $key <add> * @param mixed $value <add> * @return void <add> */ <add> public function assertViewHas($key, $value = null) <add> { <add> if (is_array($key)) return $this->assertViewHasAll($key); <add> <add> $response = $this->client->getResponse(); <add> <add> if ( ! isset($response->original) || ! $response->original instanceof View) <add> { <add> return $this->assertTrue(false, 'The response was not a view.'); <add> } <add> <add> if (is_null($value)) <add> { <add> $this->assertArrayHasKey($key, $response->original->getData()); <add> } <add> else <add> { <add> $this->assertEquals($value, $response->original->$key); <add> } <add> } <add> <add> /** <add> * Assert that the view has a given list of bound data. <add> * <add> * @param array $bindings <add> * @return void <add> */ <add> public function assertViewHasAll(array $bindings) <add> { <add> foreach ($bindings as $key => $value) <add> { <add> if (is_int($key)) <add> { <add> $this->assertViewHas($value); <add> } <add> else <add> { <add> $this->assertViewHas($key, $value); <add> } <add> } <add> } <add> <add> /** <add> * Assert that the response view is missing a piece of bound data. <add> * <add> * @param string $key <add> * @return void <add> */ <add> public function assertViewMissing($key) <add> { <add> $response = $this->client->getResponse(); <add> <add> if ( ! isset($response->original) || ! $response->original instanceof View) <add> { <add> return $this->assertTrue(false, 'The response was not a view.'); <add> } <add> <add> $this->assertArrayNotHasKey($key, $response->original->getData()); <add> } <add> <add> /** <add> * Assert whether the client was redirected to a given URI. <add> * <add> * @param string $uri <add> * @param array $with <add> * @return void <add> */ <add> public function assertRedirectedTo($uri, $with = array()) <add> { <add> $response = $this->client->getResponse(); <add> <add> $this->assertInstanceOf('Illuminate\Http\RedirectResponse', $response); <add> <add> $this->assertEquals($this->app['url']->to($uri), $response->headers->get('Location')); <add> <add> $this->assertSessionHasAll($with); <add> } <add> <add> /** <add> * Assert whether the client was redirected to a given route. <add> * <add> * @param string $name <add> * @param array $parameters <add> * @param array $with <add> * @return void <add> */ <add> public function assertRedirectedToRoute($name, $parameters = array(), $with = array()) <add> { <add> $this->assertRedirectedTo($this->app['url']->route($name, $parameters), $with); <add> } <add> <add> /** <add> * Assert whether the client was redirected to a given action. <add> * <add> * @param string $name <add> * @param array $parameters <add> * @param array $with <add> * @return void <add> */ <add> public function assertRedirectedToAction($name, $parameters = array(), $with = array()) <add> { <add> $this->assertRedirectedTo($this->app['url']->action($name, $parameters), $with); <add> } <add> <add> /** <add> * Assert that the session has a given list of values. <add> * <add> * @param string|array $key <add> * @param mixed $value <add> * @return void <add> */ <add> public function assertSessionHas($key, $value = null) <add> { <add> if (is_array($key)) return $this->assertSessionHasAll($key); <add> <add> if (is_null($value)) <add> { <add> $this->assertTrue($this->app['session.store']->has($key), "Session missing key: $key"); <add> } <add> else <add> { <add> $this->assertEquals($value, $this->app['session.store']->get($key)); <add> } <add> } <add> <add> /** <add> * Assert that the session has a given list of values. <add> * <add> * @param array $bindings <add> * @return void <add> */ <add> public function assertSessionHasAll(array $bindings) <add> { <add> foreach ($bindings as $key => $value) <add> { <add> if (is_int($key)) <add> { <add> $this->assertSessionHas($value); <add> } <add> else <add> { <add> $this->assertSessionHas($key, $value); <add> } <add> } <add> } <add> <add> /** <add> * Assert that the session has errors bound. <add> * <add> * @param string|array $bindings <add> * @param mixed $format <add> * @return void <add> */ <add> public function assertSessionHasErrors($bindings = array(), $format = null) <add> { <add> $this->assertSessionHas('errors'); <add> <add> $bindings = (array) $bindings; <add> <add> $errors = $this->app['session.store']->get('errors'); <add> <add> foreach ($bindings as $key => $value) <add> { <add> if (is_int($key)) <add> { <add> $this->assertTrue($errors->has($value), "Session missing error: $value"); <add> } <add> else <add> { <add> $this->assertContains($value, $errors->get($key, $format)); <add> } <add> } <add> } <add> <add> /** <add> * Assert that the session has old input. <add> * <add> * @return void <add> */ <add> public function assertHasOldInput() <add> { <add> $this->assertSessionHas('_old_input'); <add> } <ide> <ide> } <ide><path>src/Illuminate/Queue/Capsule/Manager.php <ide> <ide> class Manager { <ide> <del> /** <del> * The current globally used instance. <del> * <del> * @var \Illuminate\Queue\Capsule\Manager <del> */ <del> protected static $instance; <del> <del> /** <del> * The queue manager instance. <del> * <del> * @var \Illuminate\Queue\QueueManager <del> */ <del> protected $manager; <del> <del> /** <del> * Create a new queue capsule manager. <del> * <del> * @param \Illuminate\Container\Container $container <del> * @return void <del> */ <del> public function __construct(Container $container = null) <del> { <del> $this->setupContainer($container); <del> <del> // Once we have the container setup, we will setup the default configuration <del> // options in the container "config" bindings. This just makes this queue <del> // manager behave correctly since all the correct binding are in place. <del> $this->setupDefaultConfiguration(); <del> <del> $this->setupManager(); <del> <del> $this->registerConnectors(); <del> } <del> <del> /** <del> * Setup the IoC container instance. <del> * <del> * @param \Illuminate\Container\Container $container <del> * @return void <del> */ <del> protected function setupContainer($container) <del> { <del> $this->container = $container ?: new Container; <del> <del> if ( ! $this->container->bound('config')) <del> { <del> $this->container->instance('config', new Fluent); <del> } <del> } <del> <del> /** <del> * Setup the default queue configuration options. <del> * <del> * @return void <del> */ <del> protected function setupDefaultConfiguration() <del> { <del> $this->container['config']['queue.default'] = 'default'; <del> } <del> <del> /** <del> * Build the queue manager instance. <del> * <del> * @return void <del> */ <del> protected function setupManager() <del> { <del> $this->manager = new QueueManager($this->container); <del> } <del> <del> /** <del> * Register the default connectors that the component ships with. <del> * <del> * @return void <del> */ <del> protected function registerConnectors() <del> { <del> $provider = new QueueServiceProvider($this->container); <del> <del> $provider->registerConnectors($this->manager); <del> } <del> <del> /** <del> * Get a connection instance from the global manager. <del> * <del> * @param string $connection <del> * @return \Illuminate\Queue\QueueInterface <del> */ <del> public static function connection($connection = null) <del> { <del> return static::$instance->getConnection($connection); <del> } <del> <del> /** <del> * Push a new job onto the queue. <del> * <del> * @param string $job <del> * @param mixed $data <del> * @param string $queue <del> * @param string $connection <del> * @return mixed <del> */ <del> public static function push($job, $data = '', $queue = null, $connection = null) <del> { <del> return static::$instance->connection($connection)->push($job, $data, $queue); <del> } <del> <del> /** <del> * Push a new an array of jobs onto the queue. <del> * <del> * @param array $jobs <del> * @param mixed $data <del> * @param string $queue <del> * @param string $connection <del> * @return mixed <del> */ <del> public static function bulk($jobs, $data = '', $queue = null, $connection = null) <del> { <del> return static::$instance->connection($connection)->bulk($jobs, $data, $queue); <del> } <del> <del> /** <del> * Push a new job onto the queue after a delay. <del> * <del> * @param \DateTime|int $delay <del> * @param string $job <del> * @param mixed $data <del> * @param string $queue <del> * @param string $connection <del> * @return mixed <del> */ <del> public static function later($delay, $job, $data = '', $queue = null, $connection = null) <del> { <del> return static::$instance->connection($connection)->later($delay, $job, $data, $queue); <del> } <del> <del> /** <del> * Get a registered connection instance. <del> * <del> * @param string $name <del> * @return \Illuminate\Queue\QueueInterface <del> */ <del> public function getConnection($name = null) <del> { <del> return $this->manager->connection($name); <del> } <del> <del> /** <del> * Register a connection with the manager. <del> * <del> * @param array $config <del> * @param string $name <del> * @return void <del> */ <del> public function addConnection(array $config, $name = 'default') <del> { <del> $this->container['config']["queue.connections.{$name}"] = $config; <del> } <del> <del> /** <del> * Make this capsule instance available globally. <del> * <del> * @return void <del> */ <del> public function setAsGlobal() <del> { <del> static::$instance = $this; <del> } <del> <del> /** <del> * Get the queue manager instance. <del> * <del> * @return \Illuminate\Queue\Manager <del> */ <del> public function getQueueManager() <del> { <del> return $this->manager; <del> } <del> <del> /** <del> * Get the IoC container instance. <del> * <del> * @return \Illuminate\Container\Container <del> */ <del> public function getContainer() <del> { <del> return $this->container; <del> } <del> <del> /** <del> * Set the IoC container instance. <del> * <del> * @param \Illuminate\Container\Container $container <del> * @return void <del> */ <del> public function setContainer(Container $container) <del> { <del> $this->container = $container; <del> } <del> <del> /** <del> * Pass dynamic instance methods to the manager. <del> * <del> * @param string $method <del> * @param array $parameters <del> * @return mixed <del> */ <del> public function __call($method, $parameters) <del> { <del> return call_user_func_array(array($this->manager, $method), $parameters); <del> } <del> <del> /** <del> * Dynamically pass methods to the default connection. <del> * <del> * @param string $method <del> * @param array $parameters <del> * @return mixed <del> */ <del> public static function __callStatic($method, $parameters) <del> { <del> return call_user_func_array(array(static::connection(), $method), $parameters); <del> } <add> /** <add> * The current globally used instance. <add> * <add> * @var \Illuminate\Queue\Capsule\Manager <add> */ <add> protected static $instance; <add> <add> /** <add> * The queue manager instance. <add> * <add> * @var \Illuminate\Queue\QueueManager <add> */ <add> protected $manager; <add> <add> /** <add> * Create a new queue capsule manager. <add> * <add> * @param \Illuminate\Container\Container $container <add> * @return void <add> */ <add> public function __construct(Container $container = null) <add> { <add> $this->setupContainer($container); <add> <add> // Once we have the container setup, we will setup the default configuration <add> // options in the container "config" bindings. This just makes this queue <add> // manager behave correctly since all the correct binding are in place. <add> $this->setupDefaultConfiguration(); <add> <add> $this->setupManager(); <add> <add> $this->registerConnectors(); <add> } <add> <add> /** <add> * Setup the IoC container instance. <add> * <add> * @param \Illuminate\Container\Container $container <add> * @return void <add> */ <add> protected function setupContainer($container) <add> { <add> $this->container = $container ?: new Container; <add> <add> if ( ! $this->container->bound('config')) <add> { <add> $this->container->instance('config', new Fluent); <add> } <add> } <add> <add> /** <add> * Setup the default queue configuration options. <add> * <add> * @return void <add> */ <add> protected function setupDefaultConfiguration() <add> { <add> $this->container['config']['queue.default'] = 'default'; <add> } <add> <add> /** <add> * Build the queue manager instance. <add> * <add> * @return void <add> */ <add> protected function setupManager() <add> { <add> $this->manager = new QueueManager($this->container); <add> } <add> <add> /** <add> * Register the default connectors that the component ships with. <add> * <add> * @return void <add> */ <add> protected function registerConnectors() <add> { <add> $provider = new QueueServiceProvider($this->container); <add> <add> $provider->registerConnectors($this->manager); <add> } <add> <add> /** <add> * Get a connection instance from the global manager. <add> * <add> * @param string $connection <add> * @return \Illuminate\Queue\QueueInterface <add> */ <add> public static function connection($connection = null) <add> { <add> return static::$instance->getConnection($connection); <add> } <add> <add> /** <add> * Push a new job onto the queue. <add> * <add> * @param string $job <add> * @param mixed $data <add> * @param string $queue <add> * @param string $connection <add> * @return mixed <add> */ <add> public static function push($job, $data = '', $queue = null, $connection = null) <add> { <add> return static::$instance->connection($connection)->push($job, $data, $queue); <add> } <add> <add> /** <add> * Push a new an array of jobs onto the queue. <add> * <add> * @param array $jobs <add> * @param mixed $data <add> * @param string $queue <add> * @param string $connection <add> * @return mixed <add> */ <add> public static function bulk($jobs, $data = '', $queue = null, $connection = null) <add> { <add> return static::$instance->connection($connection)->bulk($jobs, $data, $queue); <add> } <add> <add> /** <add> * Push a new job onto the queue after a delay. <add> * <add> * @param \DateTime|int $delay <add> * @param string $job <add> * @param mixed $data <add> * @param string $queue <add> * @param string $connection <add> * @return mixed <add> */ <add> public static function later($delay, $job, $data = '', $queue = null, $connection = null) <add> { <add> return static::$instance->connection($connection)->later($delay, $job, $data, $queue); <add> } <add> <add> /** <add> * Get a registered connection instance. <add> * <add> * @param string $name <add> * @return \Illuminate\Queue\QueueInterface <add> */ <add> public function getConnection($name = null) <add> { <add> return $this->manager->connection($name); <add> } <add> <add> /** <add> * Register a connection with the manager. <add> * <add> * @param array $config <add> * @param string $name <add> * @return void <add> */ <add> public function addConnection(array $config, $name = 'default') <add> { <add> $this->container['config']["queue.connections.{$name}"] = $config; <add> } <add> <add> /** <add> * Make this capsule instance available globally. <add> * <add> * @return void <add> */ <add> public function setAsGlobal() <add> { <add> static::$instance = $this; <add> } <add> <add> /** <add> * Get the queue manager instance. <add> * <add> * @return \Illuminate\Queue\Manager <add> */ <add> public function getQueueManager() <add> { <add> return $this->manager; <add> } <add> <add> /** <add> * Get the IoC container instance. <add> * <add> * @return \Illuminate\Container\Container <add> */ <add> public function getContainer() <add> { <add> return $this->container; <add> } <add> <add> /** <add> * Set the IoC container instance. <add> * <add> * @param \Illuminate\Container\Container $container <add> * @return void <add> */ <add> public function setContainer(Container $container) <add> { <add> $this->container = $container; <add> } <add> <add> /** <add> * Pass dynamic instance methods to the manager. <add> * <add> * @param string $method <add> * @param array $parameters <add> * @return mixed <add> */ <add> public function __call($method, $parameters) <add> { <add> return call_user_func_array(array($this->manager, $method), $parameters); <add> } <add> <add> /** <add> * Dynamically pass methods to the default connection. <add> * <add> * @param string $method <add> * @param array $parameters <add> * @return mixed <add> */ <add> public static function __callStatic($method, $parameters) <add> { <add> return call_user_func_array(array(static::connection(), $method), $parameters); <add> } <ide> <ide> }
3
PHP
PHP
fix undefined variable
55f415bcff70c991a6accee9a17deee46a9e29c1
<ide><path>src/Illuminate/Database/Query/Builder.php <ide> public function avg($column) <ide> */ <ide> public function average($column) <ide> { <del> return $this->avg($key); <add> return $this->avg($column); <ide> } <ide> <ide> /**
1
Javascript
Javascript
add test for gh-2867
a8c0194d3d58fd064e2c4f8b3cad17f7eb77ebfc
<ide><path>test/unit/css.js <ide> QUnit.test( "can't get css for disconnected in IE<9, see #10254 and #8388", func <ide> assert.equal( div.css( "top" ), "10px", "can't get top in IE<9, see #8388" ); <ide> } ); <ide> <add>QUnit.test( "Ensure styles are retrieving from parsed html on document fragments", function( assert ) { <add> assert.expect( 1 ); <add> <add> var $span = jQuery( <add> jQuery.parseHTML( "<span style=\"font-family: Cuprum,sans-serif; font-size: 14px; color: #999999;\">some text</span>" ) <add> ); <add> <add> assert.equal( $span.css( "font-size" ), "14px", "Font-size retrievable on parsed HTML node" ); <add>} ); <add> <ide> QUnit.test( "can't get background-position in IE<9, see #10796", function( assert ) { <ide> var div = jQuery( "<div/>" ).appendTo( "#qunit-fixture" ), <ide> units = [
1
Ruby
Ruby
use extract_options! in cycle helper
fd3f550c949fda5d3f9d008bf90091dc151d006f
<ide><path>actionpack/lib/action_view/helpers/text_helper.rb <ide> require 'active_support/core_ext/object/blank' <ide> require 'active_support/core_ext/string/filters' <add>require 'active_support/core_ext/array/extract_options' <ide> <ide> module ActionView <ide> # = Action View Text Helpers <ide> def simple_format(text, html_options={}, options={}) <ide> # </tr> <ide> # <% end %> <ide> def cycle(first_value, *values) <del> if (values.last.instance_of? Hash) <del> params = values.pop <del> name = params[:name] <del> else <del> name = "default" <del> end <add> options = values.extract_options! <add> name = options.fetch(:name, "default") <add> <ide> values.unshift(first_value) <ide> <ide> cycle = get_cycle(name)
1
Python
Python
break long line
e7df4a4e2f0e21f110b177241f32c84548a95bd4
<ide><path>numpy/random/tests/test_random.py <ide> def test_shuffle_no_object_unpacking(self, random, use_array_like): <ide> class MyArr(np.ndarray): <ide> pass <ide> <del> items = [None, np.array([3]), np.float64(3), np.array(10), np.float64(7)] <add> items = [None, np.array([3]), np.float64(3), np.array(10), <add> np.float64(7) <add> ] <ide> arr = np.array(items, dtype=object) <ide> item_ids = {id(i) for i in items} <ide> if use_array_like:
1
Javascript
Javascript
remove unnecessary error overriding in
cc77be957e502ca6b855f1600d7fd11748dceb18
<ide><path>packages/shared/__tests__/ReactErrorProd-test.internal.js <ide> let formatProdErrorMessage; <ide> <ide> describe('ReactErrorProd', () => { <del> let globalErrorMock; <del> <ide> beforeEach(() => { <del> if (!__DEV__) { <del> // In production, our Jest environment overrides the global Error <del> // class in order to decode error messages automatically. However <del> // this is a single test where we actually *don't* want to decode <del> // them. So we assert that the OriginalError exists, and temporarily <del> // set the global Error object back to it. <del> globalErrorMock = global.Error; <del> global.Error = globalErrorMock.OriginalError; <del> expect(typeof global.Error).toBe('function'); <del> } <ide> jest.resetModules(); <ide> formatProdErrorMessage = require('shared/formatProdErrorMessage').default; <ide> }); <ide> <del> afterEach(() => { <del> if (!__DEV__) { <del> global.Error = globalErrorMock; <del> } <del> }); <del> <ide> it('should throw with the correct number of `%s`s in the URL', () => { <ide> expect(formatProdErrorMessage(124, 'foo', 'bar')).toEqual( <ide> 'Minified React error #124; visit ' +
1
PHP
PHP
apply fixes from styleci
0deda1a8780b57d7a26b9317de90556432029df2
<ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php <ide> use Illuminate\Container\Container; <ide> use Illuminate\Contracts\Foundation\Application; <ide> use Illuminate\Contracts\View\Factory; <del>use Illuminate\Filesystem\Filesystem; <ide> use Illuminate\View\Compilers\BladeCompiler; <ide> use Illuminate\View\Compilers\ComponentTagCompiler; <ide> use Illuminate\View\Component;
1
Text
Text
add note about standalone + runtimeconfig caveat
1c1fbeb4decf31ff8fd6ea274758eb36c25d5af1
<ide><path>docs/advanced-features/output-file-tracing.md <ide> This will create a folder at `.next/standalone` which can then be deployed on it <ide> <ide> Additionally, a minimal `server.js` file is also output which can be used instead of `next start`. This minimal server does not copy the `public` or `.next/static` folders by default as these should ideally be handled by a CDN instead, although these folders can be copied to the `standalone/public` and `standalone/.next/static` folders manually, after which `server.js` file will serve these automatically. <ide> <add>Note: `next.config.js` is read during `next build` and serialized into the `server.js` output file. If the legacy [`serverRuntimeConfig` or `publicRuntimeConfig` options](/docs/api-reference/next.config.js/runtime-configuration.md) are being used, the values will be specific to values at build time. <add> <ide> ## Caveats <ide> <ide> - While tracing in monorepo setups, the project directory is used for tracing by default. For `next build packages/web-app`, `packages/web-app` would be the tracing root and any files outside of that folder will not be included. To include files outside of this folder you can set `experimental.outputFileTracingRoot` in your `next.config.js`.
1
Go
Go
return error when iptables is not found
c66d2b6a532c657b554ffa3c80b2cf15e218ee8e
<ide><path>network.go <ide> func networkSize(mask net.IPMask) (int32, error) { <ide> func iptables(args ...string) error { <ide> path, err := exec.LookPath("iptables") <ide> if err != nil { <del> log.Fatal("command not found: iptables") <add> return fmt.Errorf("command not found: iptables") <ide> } <ide> if err := exec.Command(path, args...).Run(); err != nil { <ide> return fmt.Errorf("iptables failed: iptables %v", strings.Join(args, " "))
1
Text
Text
fix typo cppu
260bbef84a057ac232a3d16c297a40731a072b3a
<ide><path>guide/portuguese/computer-hardware/cpu/index.md <ide> As velocidades da CPU são medidas em gigahertz (GHz). Para cada gigahertz de ve <ide> <ide> Gigahertz não é o único fator determinante na velocidade real de um processador, já que diferentes processadores com a mesma velocidade gigahertz (também conhecida como velocidade de clock) podem executar tarefas reais em velocidades diferentes devido ao uso de diferentes conjuntos de instruções para executar essas tarefas. Esses conjuntos de instruções são chamados de arquiteturas. <ide> <del>As CPUs mais modernas usam uma arquitetura de 64 bits, o que significa que usam endereços de memória de 64 bits. CPUs mais antigas usavam arquiteturas de 32 bits, 16 bits e até 8 bits. O maior número que uma CPU de 64 bits pode armazenar é 18.446.744.073.709.552.000. Um CPPU precisa de endereços de memória para obter valores especificados da RAM. Se chamarmos o comprimento dos endereços de memória n, 2 ^ n é a quantidade de células de memória que uma CPU pode endereçar. <add>As CPUs mais modernas usam uma arquitetura de 64 bits, o que significa que usam endereços de memória de 64 bits. CPUs mais antigas usavam arquiteturas de 32 bits, 16 bits e até 8 bits. O maior número que uma CPU de 64 bits pode armazenar é 18.446.744.073.709.552.000. Um CPU precisa de endereços de memória para obter valores especificados da RAM. Se chamarmos o comprimento dos endereços de memória n, 2 ^ n é a quantidade de células de memória que uma CPU pode endereçar. <ide> <ide> Um ciclo de instrução para uma CPU é chamado de ciclo de busca e decodificação-execução, em que o computador recupera uma instrução de sua memória, determina qual instrução ela coletou e o que faz, e então executa as instruções mencionadas. <ide>
1
Javascript
Javascript
ignore hidden files
0f59e5d49d295c521f0a26b83f7a59668d26c6f1
<ide><path>lib/ContextModuleFactory.js <ide> ContextModuleFactory.prototype.resolveDependencies = function resolveDependencie <ide> (function addDirectory(directory, callback) { <ide> fs.readdir(directory, function(err, files) { <ide> if(!files || files.length === 0) return callback(null, []); <del> async.map(files, function(seqment, callback) { <add> async.map(files.filter(function(p) { <add> return p.indexOf(".") !== 0; <add> }), function(seqment, callback) { <ide> <ide> var subResource = path.join(directory, seqment) <ide> <ide><path>test/cases/context/ignore-hidden-files/folder/.file.js <add>module.exports = "fail"; <ide>\ No newline at end of file <ide><path>test/cases/context/ignore-hidden-files/index.js <add>it("should ignore hidden files", function() { <add> (function() { <add> var name = "./file.js"; <add> require("./folder/" + name); <add> }).should.throw(); <add>}); <ide>\ No newline at end of file
3
Text
Text
fix typos in esm.md
f458f1b93b9302d76382b390c82e0e0d3ec6678a
<ide><path>doc/api/esm.md <ide> _internal_, _conditions_) <ide> > 1. Set _scopeURL_ to the parent URL of _scopeURL_. <ide> > 2. If _scopeURL_ ends in a _"node\_modules"_ path segment, return **null**. <ide> > 3. Let _pjsonURL_ be the resolution of _"package.json"_ within <del>> _packageURL_. <add>> _scopeURL_. <ide> > 4. if the file at _pjsonURL_ exists, then <ide> > 1. Return _scopeURL_. <ide> > 3. Return **null**.
1
Ruby
Ruby
improve shorthand matching for routes
572bbab2e63916b4bb5e835d403856767b7f4be5
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def match(path, *rest) <ide> end <ide> <ide> def using_match_shorthand?(path, options) <del> path && (options[:to] || options[:action]).nil? && path =~ %r{/[\w/]+$} <add> path && (options[:to] || options[:action]).nil? && path =~ %r{^/?[-\w]+/[-\w/]+$} <ide> end <ide> <ide> def decomposed_match(path, options) # :nodoc: <ide><path>actionpack/test/dispatch/routing_test.rb <ide> def test_match_shorthand_inside_nested_namespaces_and_scopes_with_controller <ide> assert_equal 'api/v3/products#list', @response.body <ide> end <ide> <add> def test_not_matching_shorthand_with_dynamic_parameters <add> draw do <add> get ':controller/:action/admin' <add> end <add> <add> get '/finances/overview/admin' <add> assert_equal 'finances#overview', @response.body <add> end <add> <ide> def test_controller_option_with_nesting_and_leading_slash <ide> draw do <ide> scope '/job', controller: 'job' do
2