content_type
stringclasses
8 values
main_lang
stringclasses
7 values
message
stringlengths
1
50
sha
stringlengths
40
40
patch
stringlengths
52
962k
file_count
int64
1
300
Python
Python
use list to allow indexing
e7ee93ff8c4553d60c10d3f2d483c0c77cf78723
<ide><path>airflow/macros/hive.py <ide> def closest_ds_partition( <ide> partitions = hh.get_partitions(schema=schema, table_name=table) <ide> if not partitions: <ide> return None <del> part_vals = [p.values()[0] for p in partitions] <add> part_vals = [list(p.values())[0] for p in partitions] <ide> if ds in part_vals: <ide> return ds <ide> else:
1
Javascript
Javascript
remove irrelevant note
df8d9507aaf8882b87117c9117b17119e6a9d738
<ide><path>src/ngRoute/route.js <ide> function $RouteProvider(){ <ide> * This example shows how changing the URL hash causes the `$route` to match a route against the <ide> * URL, and the `ngView` pulls in the partial. <ide> * <del> * Note that this example is using {@link ng.directive:script inlined templates} <del> * to get it working on jsfiddle as well. <del> * <ide> * <example name="$route-service" module="ngRouteExample" <ide> * deps="angular-route.js" fixBase="true"> <ide> * <file name="index.html">
1
Mixed
Javascript
add maxheadersize option to http2
3b84048260ba57277b327c1913ca19d826c49158
<ide><path>doc/api/http2.md <ide> properties. <ide> * `maxHeaderListSize` {number} Specifies the maximum size (uncompressed octets) <ide> of header list that will be accepted. The minimum allowed value is 0. The <ide> maximum allowed value is 2<sup>32</sup>-1. **Default:** `65535`. <add>* `maxHeaderSize` {number} Alias for `maxHeaderListSize`. <ide> * `enableConnectProtocol`{boolean} Specifies `true` if the "Extended Connect <ide> Protocol" defined by [RFC 8441][] is to be enabled. This setting is only <ide> meaningful if sent by the server. Once the `enableConnectProtocol` setting <ide><path>lib/internal/http2/core.js <ide> const validateSettings = hideStackFrames((settings) => { <ide> assertWithinRange('maxHeaderListSize', <ide> settings.maxHeaderListSize, <ide> 0, kMaxInt); <add> assertWithinRange('maxHeaderSize', <add> settings.maxHeaderSize, <add> 0, kMaxInt); <ide> if (settings.enablePush !== undefined && <ide> typeof settings.enablePush !== 'boolean') { <ide> throw new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush', <ide> function getUnpackedSettings(buf, options = {}) { <ide> settings.maxFrameSize = value; <ide> break; <ide> case NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: <del> settings.maxHeaderListSize = value; <add> settings.maxHeaderListSize = settings.maxHeaderSize = value; <ide> break; <ide> case NGHTTP2_SETTINGS_ENABLE_CONNECT_PROTOCOL: <ide> settings.enableConnectProtocol = value !== 0; <ide><path>lib/internal/http2/util.js <ide> function getDefaultSettings() { <ide> <ide> if ((flags & (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE)) === <ide> (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE)) { <del> holder.maxHeaderListSize = <add> holder.maxHeaderListSize = holder.maxHeaderSize = <ide> settingsBuffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE]; <ide> } <ide> <ide> function getSettings(session, remote) { <ide> maxFrameSize: settingsBuffer[IDX_SETTINGS_MAX_FRAME_SIZE], <ide> maxConcurrentStreams: settingsBuffer[IDX_SETTINGS_MAX_CONCURRENT_STREAMS], <ide> maxHeaderListSize: settingsBuffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE], <add> maxHeaderSize: settingsBuffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE], <ide> enableConnectProtocol: <ide> !!settingsBuffer[IDX_SETTINGS_ENABLE_CONNECT_PROTOCOL] <ide> }; <ide> function updateSettingsBuffer(settings) { <ide> settingsBuffer[IDX_SETTINGS_MAX_FRAME_SIZE] = <ide> settings.maxFrameSize; <ide> } <del> if (typeof settings.maxHeaderListSize === 'number') { <add> if (typeof settings.maxHeaderListSize === 'number' || <add> typeof settings.maxHeaderSize === 'number') { <ide> flags |= (1 << IDX_SETTINGS_MAX_HEADER_LIST_SIZE); <del> settingsBuffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] = <del> settings.maxHeaderListSize; <add> if (settings.maxHeaderSize !== undefined && <add> (settings.maxHeaderSize !== settings.maxHeaderListSize)) { <add> process.emitWarning( <add> 'settings.maxHeaderSize overwrite settings.maxHeaderListSize' <add> ); <add> settingsBuffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] = <add> settings.maxHeaderSize; <add> } else { <add> settingsBuffer[IDX_SETTINGS_MAX_HEADER_LIST_SIZE] = <add> settings.maxHeaderListSize; <add> } <ide> } <ide> if (typeof settings.enablePush === 'boolean') { <ide> flags |= (1 << IDX_SETTINGS_ENABLE_PUSH); <ide><path>test/parallel/test-http2-client-settings-before-connect.js <ide> server.listen(0, common.mustCall(() => { <ide> ['maxConcurrentStreams', 2 ** 32, RangeError], <ide> ['maxHeaderListSize', -1, RangeError], <ide> ['maxHeaderListSize', 2 ** 32, RangeError], <add> ['maxHeaderSize', -1, RangeError], <add> ['maxHeaderSize', 2 ** 32, RangeError], <ide> ['enablePush', 'a', TypeError], <ide> ['enablePush', 1, TypeError], <ide> ['enablePush', 0, TypeError], <ide><path>test/parallel/test-http2-getpackedsettings.js <ide> assert.deepStrictEqual(val, check); <ide> ['maxConcurrentStreams', 0], <ide> ['maxConcurrentStreams', 2 ** 31 - 1], <ide> ['maxHeaderListSize', 0], <del> ['maxHeaderListSize', 2 ** 32 - 1] <add> ['maxHeaderListSize', 2 ** 32 - 1], <add> ['maxHeaderSize', 0], <add> ['maxHeaderSize', 2 ** 32 - 1] <ide> ].forEach((i) => { <ide> // Valid options should not throw. <ide> http2.getPackedSettings({ [i[0]]: i[1] }); <ide> http2.getPackedSettings({ enablePush: false }); <ide> ['maxConcurrentStreams', -1], <ide> ['maxConcurrentStreams', 2 ** 32], <ide> ['maxHeaderListSize', -1], <del> ['maxHeaderListSize', 2 ** 32] <add> ['maxHeaderListSize', 2 ** 32], <add> ['maxHeaderSize', -1], <add> ['maxHeaderSize', 2 ** 32] <ide> ].forEach((i) => { <ide> assert.throws(() => { <ide> http2.getPackedSettings({ [i[0]]: i[1] }); <ide> http2.getPackedSettings({ enablePush: false }); <ide> maxFrameSize: 20000, <ide> maxConcurrentStreams: 200, <ide> maxHeaderListSize: 100, <add> maxHeaderSize: 100, <ide> enablePush: true, <ide> enableConnectProtocol: false, <ide> foo: 'ignored' <ide> http2.getPackedSettings({ enablePush: false }); <ide> assert.strictEqual(settings.maxFrameSize, 20000); <ide> assert.strictEqual(settings.maxConcurrentStreams, 200); <ide> assert.strictEqual(settings.maxHeaderListSize, 100); <add> assert.strictEqual(settings.maxHeaderSize, 100); <ide> assert.strictEqual(settings.enablePush, true); <ide> assert.strictEqual(settings.enableConnectProtocol, false); <ide> } <ide><path>test/parallel/test-http2-session-settings.js <ide> server.on( <ide> assert.strictEqual(typeof settings.maxFrameSize, 'number'); <ide> assert.strictEqual(typeof settings.maxConcurrentStreams, 'number'); <ide> assert.strictEqual(typeof settings.maxHeaderListSize, 'number'); <add> assert.strictEqual(typeof settings.maxHeaderSize, 'number'); <ide> }; <ide> <ide> const localSettings = stream.session.localSettings; <ide> server.listen( <ide> ['maxFrameSize', 16383], <ide> ['maxFrameSize', 2 ** 24], <ide> ['maxHeaderListSize', -1], <del> ['maxHeaderListSize', 2 ** 32] <add> ['maxHeaderListSize', 2 ** 32], <add> ['maxHeaderSize', -1], <add> ['maxHeaderSize', 2 ** 32] <ide> ].forEach((i) => { <ide> const settings = {}; <ide> settings[i[0]] = i[1]; <ide><path>test/parallel/test-http2-too-large-headers.js <ide> const { <ide> NGHTTP2_ENHANCE_YOUR_CALM <ide> } = http2.constants; <ide> <del>const server = http2.createServer({ settings: { maxHeaderListSize: 100 } }); <del>server.on('stream', common.mustNotCall()); <add>for (const prototype of ['maxHeaderListSize', 'maxHeaderSize']) { <add> const server = http2.createServer({ settings: { [prototype]: 100 } }); <add> server.on('stream', common.mustNotCall()); <ide> <del>server.listen(0, common.mustCall(() => { <del> const client = http2.connect(`http://localhost:${server.address().port}`); <add> server.listen(0, common.mustCall(() => { <add> const client = http2.connect(`http://localhost:${server.address().port}`); <ide> <del> client.on('remoteSettings', () => { <del> const req = client.request({ 'foo': 'a'.repeat(1000) }); <del> req.on('error', common.expectsError({ <del> code: 'ERR_HTTP2_STREAM_ERROR', <del> name: 'Error', <del> message: 'Stream closed with error code NGHTTP2_ENHANCE_YOUR_CALM' <del> })); <del> req.on('close', common.mustCall(() => { <del> assert.strictEqual(req.rstCode, NGHTTP2_ENHANCE_YOUR_CALM); <del> server.close(); <del> client.close(); <del> })); <del> }); <add> client.on('remoteSettings', () => { <add> const req = client.request({ 'foo': 'a'.repeat(1000) }); <add> req.on('error', common.expectsError({ <add> code: 'ERR_HTTP2_STREAM_ERROR', <add> name: 'Error', <add> message: 'Stream closed with error code NGHTTP2_ENHANCE_YOUR_CALM' <add> })); <add> req.on('close', common.mustCall(() => { <add> assert.strictEqual(req.rstCode, NGHTTP2_ENHANCE_YOUR_CALM); <add> server.close(); <add> client.close(); <add> })); <add> }); <ide> <del>})); <add> })); <add>}
7
Python
Python
use coalesce when ordering runs to handle null
22d52c00f6397fde8d97cf2479c0614671f5b5ba
<ide><path>airflow/www/utils.py <ide> import json <ide> import textwrap <ide> import time <del>from typing import Any <add>from typing import TYPE_CHECKING, Any, Sequence <ide> from urllib.parse import urlencode <ide> <del>import sqlalchemy as sqla <ide> from flask import request, url_for <ide> from flask.helpers import flash <ide> from flask_appbuilder.forms import FieldConverter <ide> from pendulum.datetime import DateTime <ide> from pygments import highlight, lexers <ide> from pygments.formatters import HtmlFormatter <add>from sqlalchemy import func, types <ide> from sqlalchemy.ext.associationproxy import AssociationProxy <ide> <del>from airflow import models <ide> from airflow.exceptions import RemovedInAirflow3Warning <ide> from airflow.models import errors <add>from airflow.models.dagrun import DagRun <ide> from airflow.models.dagwarning import DagWarning <ide> from airflow.models.taskinstance import TaskInstance <ide> from airflow.utils import timezone <ide> from airflow.www.forms import DateTimeWithTimezoneField <ide> from airflow.www.widgets import AirflowDateTimePickerWidget <ide> <add>if TYPE_CHECKING: <add> from sqlalchemy.orm.query import Query <add> from sqlalchemy.sql.operators import ColumnOperators <add> <ide> <ide> def datetime_to_string(value: DateTime | None) -> str | None: <ide> if value is None: <ide> def get_mapped_summary(parent_instance, task_instances): <ide> } <ide> <ide> <del>def encode_dag_run(dag_run: models.DagRun | None) -> dict[str, Any] | None: <add>def encode_dag_run(dag_run: DagRun | None) -> dict[str, Any] | None: <ide> if not dag_run: <ide> return None <ide> <ide> def dag_run_link(attr): <ide> return Markup('<a href="{url}">{run_id}</a>').format(url=url, run_id=run_id) <ide> <ide> <add>def _get_run_ordering_expr(name: str) -> ColumnOperators: <add> expr = DagRun.__table__.columns[name] <add> # Data interval columns are NULL for runs created before 2.3, but SQL's <add> # NULL-sorting logic would make those old runs always appear first. In a <add> # perfect world we'd want to sort by ``get_run_data_interval()``, but that's <add> # not efficient, so instead the columns are coalesced into execution_date, <add> # which is good enough in most cases. <add> if name in ("data_interval_start", "data_interval_end"): <add> expr = func.coalesce(expr, DagRun.execution_date) <add> return expr.desc() <add> <add> <add>def sorted_dag_runs(query: Query, *, ordering: Sequence[str], limit: int) -> Sequence[DagRun]: <add> """Produce DAG runs sorted by specified columns. <add> <add> :param query: An ORM query object against *DagRun*. <add> :param ordering: Column names to sort the runs. should generally come from a <add> timetable's ``run_ordering``. <add> :param limit: Number of runs to limit to. <add> :return: A list of DagRun objects ordered by the specified columns. The list <add> contains only the *last* objects, but in *ascending* order. <add> """ <add> ordering_exprs = (_get_run_ordering_expr(name) for name in ordering) <add> runs = query.order_by(*ordering_exprs, DagRun.id.desc()).limit(limit).all() <add> runs.reverse() <add> return runs <add> <add> <ide> def format_map_index(attr: dict) -> str: <ide> """Format map index for list columns in model view.""" <ide> value = attr['map_index'] <ide> def is_utcdatetime(self, col_name): <ide> obj = self.list_columns[col_name].type <ide> return ( <ide> isinstance(obj, UtcDateTime) <del> or isinstance(obj, sqla.types.TypeDecorator) <add> or isinstance(obj, types.TypeDecorator) <ide> and isinstance(obj.impl, UtcDateTime) <ide> ) <ide> return False <ide> def is_extendedjson(self, col_name): <ide> obj = self.list_columns[col_name].type <ide> return ( <ide> isinstance(obj, ExtendedJSON) <del> or isinstance(obj, sqla.types.TypeDecorator) <add> or isinstance(obj, types.TypeDecorator) <ide> and isinstance(obj.impl, ExtendedJSON) <ide> ) <ide> return False <ide><path>airflow/www/views.py <ide> def grid_data(self): <ide> if run_state: <ide> query = query.filter(DagRun.state == run_state) <ide> <del> ordering = (DagRun.__table__.columns[name].desc() for name in dag.timetable.run_ordering) <del> dag_runs = query.order_by(*ordering, DagRun.id.desc()).limit(num_runs).all() <del> dag_runs.reverse() <del> <add> dag_runs = wwwutils.sorted_dag_runs(query, ordering=dag.timetable.run_ordering, limit=num_runs) <ide> encoded_runs = [wwwutils.encode_dag_run(dr) for dr in dag_runs] <ide> data = { <ide> 'groups': dag_to_grid(dag, dag_runs, session),
2
Ruby
Ruby
fix active model observer tests
1924cff93402160f4db4eea5c1b14bb9d1f85d91
<ide><path>activemodel/lib/active_model/observing.rb <ide> def notify_observers(*arg) <ide> end <ide> end <ide> <add> def count_observers <add> @observer_instances.size <add> end <add> <ide> protected <ide> def instantiate_observer(observer) #:nodoc: <ide> # string/symbol <ide><path>activemodel/test/cases/observing_test.rb <ide> def teardown <ide> foo = Foo.new <ide> FooObserver.instance.stub = stub <ide> FooObserver.instance.stub.expects(:event_with).with(foo) <del> Foo.send(:changed) <ide> Foo.send(:notify_observers, :on_spec, foo) <ide> end <ide> <ide> test "skips nonexistent observer event" do <ide> foo = Foo.new <del> Foo.send(:changed) <ide> Foo.send(:notify_observers, :whatever, foo) <ide> end <ide> end
2
Java
Java
execute handlerinterceptors in registration order
c36435c0427c75d4dcee382a88a466ad96241faa
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMapping.java <ide> import java.io.IOException; <ide> import java.util.ArrayList; <ide> import java.util.Arrays; <del>import java.util.HashMap; <ide> import java.util.LinkedHashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> public abstract class AbstractHandlerMapping extends WebApplicationObjectSupport <ide> <ide> private final List<Object> interceptors = new ArrayList<Object>(); <ide> <del> private final List<HandlerInterceptor> adaptedInterceptors = new ArrayList<HandlerInterceptor>(); <add> private final List<HandlerInterceptor> handlerInterceptors = new ArrayList<HandlerInterceptor>(); <ide> <del> private final List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>(); <add> private final List<MappedInterceptor> detectedMappedInterceptors = new ArrayList<MappedInterceptor>(); <ide> <ide> private CorsProcessor corsProcessor = new DefaultCorsProcessor(); <ide> <ide> public Map<String, CorsConfiguration> getCorsConfiguration() { <ide> @Override <ide> protected void initApplicationContext() throws BeansException { <ide> extendInterceptors(this.interceptors); <del> detectMappedInterceptors(this.mappedInterceptors); <add> detectMappedInterceptors(this.detectedMappedInterceptors); <ide> initInterceptors(); <ide> } <ide> <ide> protected void initInterceptors() { <ide> if (interceptor == null) { <ide> throw new IllegalArgumentException("Entry number " + i + " in interceptors array is null"); <ide> } <del> if (interceptor instanceof MappedInterceptor) { <del> this.mappedInterceptors.add((MappedInterceptor) interceptor); <del> } <del> else { <del> this.adaptedInterceptors.add(adaptInterceptor(interceptor)); <del> } <add> this.handlerInterceptors.add(adaptInterceptor(interceptor)); <ide> } <ide> } <add> this.handlerInterceptors.addAll(this.detectedMappedInterceptors); <add> this.interceptors.clear(); <ide> } <ide> <ide> /** <ide> else if (interceptor instanceof WebRequestInterceptor) { <ide> * @return the array of {@link HandlerInterceptor}s, or {@code null} if none <ide> */ <ide> protected final HandlerInterceptor[] getAdaptedInterceptors() { <del> int count = this.adaptedInterceptors.size(); <del> return (count > 0 ? this.adaptedInterceptors.toArray(new HandlerInterceptor[count]) : null); <add> List<HandlerInterceptor> adaptedInterceptors = new ArrayList<HandlerInterceptor>(); <add> for (HandlerInterceptor interceptor : this.handlerInterceptors) { <add> if (!(interceptor instanceof MappedInterceptor)) { <add> adaptedInterceptors.add(interceptor); <add> } <add> } <add> int count = adaptedInterceptors.size(); <add> return (count > 0 ? adaptedInterceptors.toArray(new HandlerInterceptor[count]) : null); <ide> } <ide> <ide> /** <ide> * Return all configured {@link MappedInterceptor}s as an array. <ide> * @return the array of {@link MappedInterceptor}s, or {@code null} if none <ide> */ <ide> protected final MappedInterceptor[] getMappedInterceptors() { <del> int count = this.mappedInterceptors.size(); <del> return (count > 0 ? this.mappedInterceptors.toArray(new MappedInterceptor[count]) : null); <add> List<MappedInterceptor> mappedInterceptors = new ArrayList<MappedInterceptor>(); <add> for (HandlerInterceptor interceptor : this.handlerInterceptors) { <add> if (interceptor instanceof MappedInterceptor) { <add> mappedInterceptors.add((MappedInterceptor) interceptor); <add> } <add> } <add> int count = mappedInterceptors.size(); <add> return (count > 0 ? mappedInterceptors.toArray(new MappedInterceptor[count]) : null); <ide> } <ide> <ide> /** <ide> public final HandlerExecutionChain getHandler(HttpServletRequest request) throws <ide> * applicable interceptors. <ide> * <p>The default implementation builds a standard {@link HandlerExecutionChain} <ide> * with the given handler, the handler mapping's common interceptors, and any <del> * {@link MappedInterceptor}s matching to the current request URL. Subclasses <del> * may override this in order to extend/rearrange the list of interceptors. <add> * {@link MappedInterceptor}s matching to the current request URL. Interceptors <add> * are added in the order they were registered. Subclasses may override this <add> * in order to extend/rearrange the list of interceptors. <ide> * <p><b>NOTE:</b> The passed-in handler object may be a raw handler or a <ide> * pre-built {@link HandlerExecutionChain}. This method should handle those <ide> * two cases explicitly, either building a new {@link HandlerExecutionChain} <ide> public final HandlerExecutionChain getHandler(HttpServletRequest request) throws <ide> protected HandlerExecutionChain getHandlerExecutionChain(Object handler, HttpServletRequest request) { <ide> HandlerExecutionChain chain = (handler instanceof HandlerExecutionChain ? <ide> (HandlerExecutionChain) handler : new HandlerExecutionChain(handler)); <del> chain.addInterceptors(getAdaptedInterceptors()); <ide> <ide> String lookupPath = this.urlPathHelper.getLookupPathForRequest(request); <del> for (MappedInterceptor mappedInterceptor : this.mappedInterceptors) { <del> if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) { <del> chain.addInterceptor(mappedInterceptor.getInterceptor()); <add> for (HandlerInterceptor interceptor : this.handlerInterceptors) { <add> if (interceptor instanceof MappedInterceptor) { <add> MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor; <add> if (mappedInterceptor.matches(lookupPath, this.pathMatcher)) { <add> chain.addInterceptor(mappedInterceptor.getInterceptor()); <add> } <add> } <add> else { <add> chain.addInterceptor(interceptor); <ide> } <ide> } <del> <ide> return chain; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/MappedInterceptor.java <ide> /* <del> * Copyright 2002-2012 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> <ide> package org.springframework.web.servlet.handler; <ide> <add>import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpServletResponse; <add> <ide> import org.springframework.util.PathMatcher; <ide> import org.springframework.web.context.request.WebRequestInterceptor; <ide> import org.springframework.web.servlet.HandlerInterceptor; <add>import org.springframework.web.servlet.ModelAndView; <ide> <ide> /** <del> * Contains a {@link HandlerInterceptor} along with include (and optionally <del> * exclude) path patterns to which the interceptor should apply. Also provides <del> * matching logic to test if the interceptor applies to a given request path. <add> * Contains and delegates calls to a {@link HandlerInterceptor} along with <add> * include (and optionally exclude) path patterns to which the interceptor should apply. <add> * Also provides matching logic to test if the interceptor applies to a given request path. <ide> * <ide> * <p>A MappedInterceptor can be registered directly with any <ide> * {@link org.springframework.web.servlet.handler.AbstractHandlerMethodMapping <ide> * <ide> * @author Keith Donald <ide> * @author Rossen Stoyanchev <add> * @author Brian Clozel <ide> * @since 3.0 <ide> */ <del>public final class MappedInterceptor { <add>public final class MappedInterceptor implements HandlerInterceptor { <ide> <ide> private final String[] includePatterns; <ide> <ide> public HandlerInterceptor getInterceptor() { <ide> return this.interceptor; <ide> } <ide> <add> @Override <add> public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { <add> return this.interceptor.preHandle(request, response, handler); <add> } <add> <add> @Override <add> public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { <add> this.interceptor.postHandle(request, response, handler, modelAndView); <add> } <add> <add> @Override <add> public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { <add> this.interceptor.afterCompletion(request, response, handler, ex); <add> } <add> <ide> /** <ide> * Returns {@code true} if the interceptor applies to the given request path. <ide> * @param lookupPath the current request path <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/handler/AbstractHandlerMappingTests.java <add>/* <add> * Copyright 2002-2015 the original author or authors. <add> * <add> * Licensed under the Apache License, Version 2.0 (the "License"); <add> * you may not use this file except in compliance with the License. <add> * You may obtain a copy of the License at <add> * <add> * http://www.apache.org/licenses/LICENSE-2.0 <add> * <add> * Unless required by applicable law or agreed to in writing, software <add> * distributed under the License is distributed on an "AS IS" BASIS, <add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <add> * See the License for the specific language governing permissions and <add> * limitations under the License. <add> */ <add> <add>package org.springframework.web.servlet.handler; <add> <add>import java.io.IOException; <add> <add>import javax.servlet.ServletException; <add>import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpServletResponse; <add> <add>import org.hamcrest.Matchers; <add>import org.junit.Assert; <add>import org.junit.Before; <add>import org.junit.Test; <add>import org.mockito.Mockito; <add> <add>import org.springframework.http.HttpStatus; <add>import org.springframework.mock.web.test.MockHttpServletRequest; <add>import org.springframework.mock.web.test.MockHttpServletResponse; <add>import org.springframework.web.HttpRequestHandler; <add>import org.springframework.web.context.support.StaticWebApplicationContext; <add>import org.springframework.web.servlet.HandlerExecutionChain; <add>import org.springframework.web.servlet.HandlerInterceptor; <add>import org.springframework.web.servlet.support.WebContentGenerator; <add> <add>/** <add> * @author Brian Clozel <add> */ <add>public class AbstractHandlerMappingTests { <add> <add> private MockHttpServletRequest request; <add> private AbstractHandlerMapping handlerMapping; <add> private StaticWebApplicationContext context; <add> <add> @Before <add> public void setup() { <add> this.context = new StaticWebApplicationContext(); <add> this.handlerMapping = new TestHandlerMapping(); <add> this.request = new MockHttpServletRequest(); <add> } <add> <add> @Test <add> public void orderedInterceptors() throws Exception { <add> MappedInterceptor firstMappedInterceptor = new MappedInterceptor(new String[]{"/**"}, Mockito.mock(HandlerInterceptor.class)); <add> HandlerInterceptor secondHandlerInterceptor = Mockito.mock(HandlerInterceptor.class); <add> MappedInterceptor thirdMappedInterceptor = new MappedInterceptor(new String[]{"/**"}, Mockito.mock(HandlerInterceptor.class)); <add> HandlerInterceptor fourthHandlerInterceptor = Mockito.mock(HandlerInterceptor.class); <add> <add> this.handlerMapping.setInterceptors(new Object[]{firstMappedInterceptor, secondHandlerInterceptor, <add> thirdMappedInterceptor, fourthHandlerInterceptor}); <add> this.handlerMapping.setApplicationContext(this.context); <add> HandlerExecutionChain chain = this.handlerMapping.getHandlerExecutionChain(new SimpleHandler(), this.request); <add> Assert.assertThat(chain.getInterceptors(), <add> Matchers.arrayContaining(firstMappedInterceptor, secondHandlerInterceptor, thirdMappedInterceptor, fourthHandlerInterceptor)); <add> } <add> <add> class TestHandlerMapping extends AbstractHandlerMapping { <add> <add> @Override <add> protected Object getHandlerInternal(HttpServletRequest request) throws Exception { <add> return new SimpleHandler(); <add> } <add> } <add> <add> class SimpleHandler extends WebContentGenerator implements HttpRequestHandler { <add> <add> public SimpleHandler() { <add> super(METHOD_GET); <add> } <add> <add> @Override <add> public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { <add> response.setStatus(HttpStatus.OK.value()); <add> } <add> <add> } <add> <add>} <ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/handler/MappedInterceptorTests.java <ide> */ <ide> package org.springframework.web.servlet.handler; <ide> <add>import static org.junit.Assert.*; <add>import static org.mockito.BDDMockito.any; <add>import static org.mockito.BDDMockito.*; <add>import static org.mockito.Mockito.mock; <add> <ide> import java.util.Comparator; <ide> import java.util.Map; <ide> <add>import javax.servlet.http.HttpServletRequest; <add>import javax.servlet.http.HttpServletResponse; <add> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> <ide> import org.springframework.util.AntPathMatcher; <ide> import org.springframework.util.PathMatcher; <add>import org.springframework.web.servlet.HandlerInterceptor; <add>import org.springframework.web.servlet.ModelAndView; <ide> import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; <ide> <del>import static org.junit.Assert.*; <del> <ide> /** <ide> * Test fixture for {@link MappedInterceptor} tests. <ide> * <ide> public void customPathMatcher() { <ide> assertFalse(mappedInterceptor.matches("/foo/bar", pathMatcher)); <ide> } <ide> <add> @Test <add> public void preHandle() throws Exception { <add> HandlerInterceptor interceptor = mock(HandlerInterceptor.class); <add> MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor); <add> mappedInterceptor.preHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), null); <add> <add> then(interceptor).should().preHandle(any(HttpServletRequest.class), any(HttpServletResponse.class), any()); <add> } <add> <add> @Test <add> public void postHandle() throws Exception { <add> HandlerInterceptor interceptor = mock(HandlerInterceptor.class); <add> MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor); <add> mappedInterceptor.postHandle(mock(HttpServletRequest.class), mock(HttpServletResponse.class), <add> null, mock(ModelAndView.class)); <add> <add> then(interceptor).should().postHandle(any(), any(), any(), any()); <add> } <add> <add> @Test <add> public void afterCompletion() throws Exception { <add> HandlerInterceptor interceptor = mock(HandlerInterceptor.class); <add> MappedInterceptor mappedInterceptor = new MappedInterceptor(new String[] { "/**" }, interceptor); <add> mappedInterceptor.afterCompletion(mock(HttpServletRequest.class), mock(HttpServletResponse.class), <add> null, mock(Exception.class)); <add> <add> then(interceptor).should().afterCompletion(any(), any(), any(), any()); <add> } <add> <ide> <ide> <ide> public static class TestPathMatcher implements PathMatcher {
4
Text
Text
improve release documentation
16d794dae64529f908659fca97370760bfd89fc2
<ide><path>doc/guides/releases.md <ide> official release builds for Node.js, hosted on <https://nodejs.org/>. <ide> * [10. Test the Build](#10-test-the-build) <ide> * [11. Tag and Sign the Release Commit](#11-tag-and-sign-the-release-commit) <ide> * [12. Set Up For the Next Release](#12-set-up-for-the-next-release) <del> * [13. Promote and Sign the Release Builds](#13-promote-and-sign-the-release-builds) <del> * [14. Check the Release](#14-check-the-release) <del> * [15. Create a Blog Post](#15-create-a-blog-post) <del> * [16. Create the release on GitHub](#16-create-the-release-on-github) <del> * [17. Cleanup](#17-cleanup) <del> * [18. Announce](#18-announce) <del> * [19. Celebrate](#19-celebrate) <add> * [13. Cherry-pick the Release Commit to `master`](#13-cherry-pick-the-release-commit-to-master) <add> * [14. Push the release tag](#14-push-the-release-tag) <add> * [15. Promote and Sign the Release Builds](#15-promote-and-sign-the-release-builds) <add> * [16. Check the Release](#16-check-the-release) <add> * [17. Create a Blog Post](#17-create-a-blog-post) <add> * [18. Create the release on GitHub](#18-create-the-release-on-github) <add> * [19. Cleanup](#19-cleanup) <add> * [20. Announce](#20-announce) <add> * [21. Celebrate](#21-celebrate) <ide> * [LTS Releases](#lts-releases) <ide> * [Major Releases](#major-releases) <ide> <ide> $ git rebase v1.x <ide> $ git push upstream v1.x-staging <ide> ``` <ide> <del>Cherry-pick the release commit to `master`. After cherry-picking, edit <del>`src/node_version.h` to ensure the version macros contain whatever values were <del>previously on `master`. `NODE_VERSION_IS_RELEASE` should be `0`. **Do not** <del>cherry-pick the "Working on vx.y.z" commit to `master`. <add>### 13. Cherry-pick the Release Commit to `master` <ide> <del>Run `make lint` before pushing to `master`, to make sure the Changelog <del>formatting passes the lint rules on `master`. <add>```console <add>$ git checkout master <add>$ git cherry-pick v1.x^ <add>``` <add> <add>Git should stop to let you fix conflicts. Revert all changes that were made to <add>`src/node_version.h`. If there are conflicts in `doc` due to updated `REPLACEME` <add>placeholders (that happens when a change previously landed on another release <add>branch), keep both version numbers. Convert the YAML field to an array if it is <add>not already one. <add> <add>Then finish cherry-picking and push the commit upstream: <add> <add>```console <add>$ git add src/node_version.h doc <add>$ git cherry-pick --continue <add>$ make lint <add>$ git push upstream master <add>``` <add> <add>**Do not** cherry-pick the "Working on vx.y.z" commit to `master`. <ide> <del>### 13. Push the release tag <add>### 14. Push the release tag <ide> <ide> Push the tag to the repo before you promote the builds. If you haven't pushed <ide> your tag first, then build promotion won't work properly. Push the tag using the <ide> $ git push <remote> <vx.y.z> <ide> *Note*: Please do not push the tag unless you are ready to complete the <ide> remainder of the release steps. <ide> <del>### 14. Promote and Sign the Release Builds <add>### 15. Promote and Sign the Release Builds <ide> <ide> **The same individual who signed the release tag must be the one <ide> to promote the builds as the `SHASUMS256.txt` file needs to be signed with the <ide> be prompted to re-sign `SHASUMS256.txt`. <ide> **It is possible to only sign a release by running `./tools/release.sh -s <ide> vX.Y.Z`.** <ide> <del>### 15. Check the Release <add>### 16. Check the Release <ide> <ide> Your release should be available at `https://nodejs.org/dist/vx.y.z/` and <ide> <https://nodejs.org/dist/latest/>. Check that the appropriate files are in <ide> have the right internal version strings. Check that the API docs are available <ide> at <https://nodejs.org/api/>. Check that the release catalog files are correct <ide> at <https://nodejs.org/dist/index.tab> and <https://nodejs.org/dist/index.json>. <ide> <del>### 16. Create a Blog Post <add>### 17. Create a Blog Post <ide> <ide> There is an automatic build that is kicked off when you promote new builds, so <ide> within a few minutes nodejs.org will be listing your new version as the latest <ide> This script will use the promoted builds and changelog to generate the post. Run <ide> * Changes to `master` on the [nodejs.org repository][] will trigger a new build <ide> of nodejs.org so your changes should appear a few minutes after pushing. <ide> <del>### 17. Create the release on GitHub <add>### 18. Create the release on GitHub <ide> <ide> * Go to the [New release page](https://github.com/nodejs/node/releases/new). <ide> * Select the tag version you pushed earlier. <ide> * For release title, copy the title from the changelog. <ide> * For the description, copy the rest of the changelog entry. <ide> * Click on the "Publish release" button. <ide> <del>### 18. Cleanup <add>### 19. Cleanup <ide> <ide> Close your release proposal PR and delete the proposal branch. <ide> <del>### 19. Announce <add>### 20. Announce <ide> <ide> The nodejs.org website will automatically rebuild and include the new version. <ide> To announce the build on Twitter through the official @nodejs account, email <ide> announcements. <ide> <ide> Ping the IRC ops and the other [Partner Communities][] liaisons. <ide> <del>### 20. Celebrate <add>### 21. Celebrate <ide> <ide> _In whatever form you do this..._ <ide>
1
Python
Python
fix the corner case for dtensor model layout map
e0a970d08ddba7f700876439c44b379e19d3cc33
<ide><path>keras/dtensor/layout_map_test.py <ide> def test_init_sequential_model_variable_with_layout(self): <ide> result = model(tf.zeros((10, 10), layout=self.layout_2d), training=True) <ide> self.assertAllClose(result, tf.zeros((10, 30), layout=self.layout_2d)) <ide> <add> def test_init_model_with_empty_layout_map(self): <add> # Create empty layout map, which means all the weights just default to <add> # all replicated. <add> layout_map = layout_map_lib.LayoutMap(mesh=self.mesh) <add> with layout_map_lib.layout_map_scope(layout_map): <add> model = tf.keras.Sequential([ <add> layers.Dense(20, name='d1', input_shape=(10,)), <add> layers.Dropout(0.1), <add> layers.Dense(30, name='d2') <add> ]) <add> <add> self.assertLen(model.layers, 3) <add> d1 = model.layers[0] <add> d2 = model.layers[2] <add> <add> self.assertEqual(d1.kernel.layout, self.layout_2d) <add> self.assertEqual(d1.bias.layout, self.layout_1d) <add> self.assertEqual(d2.kernel.layout, self.layout_2d) <add> self.assertEqual(d2.bias.layout, self.layout_1d) <add> <ide> <ide> if __name__ == '__main__': <ide> tf.test.main() <ide><path>keras/engine/functional.py <ide> def _init_graph_network(self, inputs, outputs): <ide> self._set_save_spec(self._nested_inputs) <ide> tf_utils.assert_no_legacy_layers(self.layers) <ide> <del> # Note that this method is used by both functional and sequential model, <del> # so we can't just this method in functional.__init__, which will miss the <del> # coverage of sequential model. <del> if self._layout_map: <add> # Note that this method is used by both functional and sequential models, <add> # so we can't just have this method in functional.__init__, which will miss <add> # the coverage of sequential model. <add> if self._layout_map is not None: <ide> layout_map_lib._map_functional_model_variable(self, self._layout_map) <ide> <ide> @property <ide><path>keras/engine/training.py <ide> def build(self, input_shape): <ide> <ide> @traceback_utils.filter_traceback <ide> def __call__(self, *args, **kwargs): <del> if self._layout_map and not self.built: <add> if self._layout_map is not None and not self.built: <ide> # Note that this method is only overridden for DTensor and layout <ide> # injection purpose. <ide> # Capture the inputs and create graph input as replacement for model
3
Javascript
Javascript
convert `containersassert` to es6 class
81347ab9bcd6738c4e49576efe3f942755648733
<ide><path>packages/internal-test-helpers/lib/ember-dev/containers.js <ide> import { Container } from '@ember/-internals/container'; <ide> <del>function ContainersAssert(env) { <del> this.env = env; <del>} <del> <ide> const { _leakTracking: containerLeakTracking } = Container; <ide> <del>ContainersAssert.prototype = { <del> reset: function() {}, <del> inject: function() {}, <del> assert: function() { <add>export default class ContainersAssert { <add> constructor(env) { <add> this.env = env; <add> } <add> <add> reset() {} <add> <add> inject() {} <add> <add> assert() { <ide> if (containerLeakTracking === undefined) return; <ide> let { config } = QUnit; <ide> let { <ide> ContainersAssert.prototype = { <ide> } <ide> }); <ide> }; <del> }, <del> restore: function() {}, <del>}; <add> } <ide> <del>export default ContainersAssert; <add> restore() {} <add>}
1
Text
Text
add descriptions to documentation pages
d1fdd2bbf8df7e12f561f3eec0c1f16897502045
<ide><path>docs/advanced-features/amp-support/adding-amp-components.md <add>--- <add>description: Add components from the AMP community to AMP pages, and make your pages more interactive. <add>--- <add> <ide> # Adding AMP Components <ide> <ide> The AMP community provide [many components](https://amp.dev/documentation/components/) to make AMP pages more interactive. You can add these components to your page by using `next/head`, as in the following example: <ide><path>docs/advanced-features/amp-support/amp-in-static-html-export.md <add>--- <add>description: Learn how AMP pages are created when used together with `next export`. <add>--- <add> <ide> # AMP in Static HTML export <ide> <ide> When using `next export` to do [Static HTML export](/docs/advanced-features/static-html-export.md) statically prerender pages, Next.js will detect if the page supports AMP and change the exporting behavior based on that. <ide><path>docs/advanced-features/amp-support/amp-validation.md <add>--- <add>description: AMP pages are automatically validated by Next.js during development and on build. Learn more about it here. <add>--- <add> <ide> # AMP Validation <ide> <ide> AMP pages are automatically validated with [amphtml-validator](https://www.npmjs.com/package/amphtml-validator) during development. Errors and warnings will appear in the terminal where you started Next.js. <ide><path>docs/advanced-features/amp-support/introduction.md <add>--- <add>description: With minimal config, and without leaving React, you can start adding AMP and improve the performance and speed of your pages. <add>--- <add> <ide> # AMP Support <ide> <ide> <details> <ide><path>docs/advanced-features/amp-support/typescript.md <add>--- <add>description: Using AMP with TypeScript? Extend your typings to allow AMP components. <add>--- <add> <ide> # TypeScript <ide> <ide> AMP currently doesn't have built-in types for TypeScript, but it's in their roadmap ([#13791](https://github.com/ampproject/amphtml/issues/13791)). <ide><path>docs/advanced-features/automatic-static-optimization.md <add>--- <add>description: Next.js automatically optimizes your app to be static HTML whenever possible. Learn how it works here. <add>--- <add> <ide> # Automatic Static Optimization <ide> <ide> Next.js automatically determines that a page is static (can be prerendered) if it has no blocking data requirements. This determination is made by the absence of `getInitialProps` in the page. <ide><path>docs/advanced-features/custom-app.md <add>--- <add>description: Control page initialization and add a layout that persists for all pages by overriding the default App component used by Next.js. <add>--- <add> <ide> # Custom `App` <ide> <ide> Next.js uses the `App` component to initialize pages. You can override it and control the page initialization. Which allows you to do amazing things like: <ide><path>docs/advanced-features/custom-document.md <add>--- <add>description: Extend the default document markup added by Next.js. <add>--- <add> <ide> # Custom `Document` <ide> <ide> A custom `Document` is commonly used to augment your application's `<html>` and `<body>` tags. This is necessary because Next.js pages skip the definition of the surrounding document's markup. <ide><path>docs/advanced-features/custom-error-page.md <add>--- <add>description: Override and extend the built-in Error page to handle custom errors. <add>--- <add> <ide> # Custom Error Page <ide> <ide> **404** or **500** errors are handled both client-side and server-side by the `Error` component. If you wish to override it, define the file `pages/_error.js` and add the following code: <ide><path>docs/advanced-features/custom-server.md <add>--- <add>description: Start a Next.js app programmatically using a custom server. <add>--- <add> <ide> # Custom Server <ide> <ide> <details> <ide><path>docs/advanced-features/customizing-babel-config.md <add>--- <add>description: Extend the babel preset added by Next.js with your own configs. <add>--- <add> <ide> # Customizing Babel Config <ide> <ide> <details> <ide><path>docs/advanced-features/dynamic-import.md <add>--- <add>description: Dynamically import JavaScript modules and React Components and split your code into manageable chunks. <add>--- <add> <ide> # Dynamic Import <ide> <ide> <details> <ide><path>docs/advanced-features/src-directory.md <add>--- <add>description: Save pages under the `src` directory as an alternative to the root `pages` directory. <add>--- <add> <ide> # `src` Directory <ide> <ide> Pages can also be added under `src/pages` as an alternative to the root `pages` directory. <ide><path>docs/advanced-features/static-html-export.md <add>--- <add>description: Export your Next.js app to static HTML, and run it standalone without the need of a Node.js server. <add>--- <add> <ide> # Static HTML Export <ide> <ide> <details> <ide><path>docs/api-reference/cli.md <add>--- <add>description: The Next.js CLI allows you to start, build, and export your application. Learn more about it here. <add>--- <add> <ide> # Next.js CLI <ide> <ide> The Next.js CLI allows you to start, build, and export your application. <ide><path>docs/api-reference/data-fetching/getInitialProps.md <add>--- <add>description: Enable Server-Side Rendering in a page and do initial data population with `getInitialProps`. <add>--- <add> <ide> # getInitialProps <ide> <ide> <details> <ide><path>docs/api-reference/next.config.js/build-target.md <add>--- <add>description: Learn more about the build targets used by Next.js, which decide the way your application is built and run. <add>--- <add> <ide> # Build Target <ide> <ide> Next.js supports various build targets, each changing the way your application is built and run. We'll explain each of the targets below. <ide><path>docs/api-reference/next.config.js/cdn-support-with-asset-prefix.md <add>--- <add>description: A custom asset prefix allows you serve static assets from a CDN. Learn more about it here. <add>--- <add> <ide> # CDN Support with Asset Prefix <ide> <ide> To set up a [CDN](https://en.wikipedia.org/wiki/Content_delivery_network), you can set up an asset prefix and configure your CDN's origin to resolve to the domain that Next.js is hosted on. <ide><path>docs/api-reference/next.config.js/compression.md <add>--- <add>description: Next.js provides gzip compression to compress rendered content and static files, it only works with the server target. Learn more about it here. <add>--- <add> <ide> # Compression <ide> <ide> Next.js provides [**gzip**](https://tools.ietf.org/html/rfc6713#section-3) compression to compress rendered content and static files. Compression only works with the [`server` target](/docs/api-reference/next.config.js/build-target.md#server-target). In general you will want to enable compression on a HTTP proxy like [nginx](https://www.nginx.com/), to offload load from the `Node.js` process. <ide><path>docs/api-reference/next.config.js/configuring-onDemandEntries.md <add>--- <add>description: Configure how Next.js will dispose and keep in memory pages created in development. <add>--- <add> <ide> # Configuring onDemandEntries <ide> <ide> Next.js exposes some options that give you some control over how the server will dispose or keep in memory built pages in development. <ide><path>docs/api-reference/next.config.js/configuring-the-build-id.md <add>--- <add>description: Configure the build id, which is used to identify the current build in which your application is being served. <add>--- <add> <ide> # Configuring the Build ID <ide> <ide> Next.js uses a constant id generated at build time to identify which version of your application is being served. This can cause problems in multi-server deployments when `next build` is ran on every server. In order to keep a static build id between builds you can provide your own build id. <ide><path>docs/api-reference/next.config.js/custom-page-extensions.md <add>--- <add>description: Extend the default page extensions used by Next.js when resolving pages in the pages directory. <add>--- <add> <ide> # Custom Page Extensions <ide> <ide> Aimed at modules like [@next/mdx](https://github.com/zeit/next.js/tree/canary/packages/next-mdx), which adds support for pages ending with `.mdx`. You can configure the extensions looked for in the `pages` directory when resolving pages. <ide><path>docs/api-reference/next.config.js/custom-webpack-config.md <add>--- <add>description: Extend the default webpack config added by Next.js. <add>--- <add> <ide> # Custom Webpack Config <ide> <ide> Some commonly asked for features are available as plugins: <ide><path>docs/api-reference/next.config.js/disabling-etag-generation.md <add>--- <add>description: Next.js will generate etags for every page by default. Learn more about how to disable etag generation here. <add>--- <add> <ide> # Disabling ETag Generation <ide> <ide> Next.js will generate [etags](https://en.wikipedia.org/wiki/HTTP_ETag) for every page by default. You may want to disable etag generation for HTML pages depending on your cache strategy. <ide><path>docs/api-reference/next.config.js/disabling-x-powered-by.md <add>--- <add>description: Next.js will add `x-powered-by` to the request headers by default. Learn to opt-out of it here. <add>--- <add> <ide> # Disabling x-powered-by <ide> <ide> By default Next.js will add `x-powered-by` to the request headers. To opt-out of it, open `next.config.js` and disable the `poweredByHeader` config: <ide><path>docs/api-reference/next.config.js/environment-variables.md <add>--- <add>description: Learn to add and access environment variables in your Next.js application at build time. <add>--- <add> <ide> # Environment Variables <ide> <ide> <details> <ide><path>docs/api-reference/next.config.js/exportPathMap.md <add>--- <add>description: Customize the pages that will be exported as HTML files when using `next export`. <add>--- <add> <ide> # exportPathMap <ide> <ide> > This feature is exclusive of `next export`. Please refer to [Static HTML export](/docs/advanced-features/static-html-export.md) if you want to learn more about it. <ide><path>docs/api-reference/next.config.js/ignoring-typescript-errors.md <add>--- <add>description: Next.js reports TypeScript errors by default. Learn to opt-out of this behavior here. <add>--- <add> <ide> # Ignoring TypeScript Errors <ide> <ide> Next.js reports TypeScript errors by default. If you don't want to leverage this behavior and prefer something else instead, like your editor's integration, you may want to disable it. <ide><path>docs/api-reference/next.config.js/introduction.md <add>--- <add>description: learn more about the configuration file used by Next.js to handle your application. <add>--- <add> <ide> # next.config.js <ide> <ide> For custom advanced behavior of Next.js, you can create a `next.config.js` in the root of your project directory (next to `package.json`). <ide><path>docs/api-reference/next.config.js/runtime-configuration.md <add>--- <add>description: Add client and server runtime configuration to your Next.js app. <add>--- <add> <ide> # Runtime Configuration <ide> <ide> > Generally you'll want to use [build-time environment variables](/docs/api-reference/next.config.js/environment-variables.md) to provide your configuration. The reason for this is that runtime configuration adds rendering / initialization overhead and is incompatible with [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md). <ide><path>docs/api-reference/next.config.js/setting-a-custom-build-directory.md <add>--- <add>description: Set a custom build directory to use instead of the default .next directory. <add>--- <add> <ide> # Setting a custom build directory <ide> <ide> You can specify a name to use for a custom build directory to use instead of `.next`. <ide><path>docs/api-reference/next.config.js/static-optimization-indicator.md <add>--- <add>description: Optimized pages include an indicator to let you know if it's being statically optimized. You can opt-out of it here. <add>--- <add> <ide> # Static Optimization Indicator <ide> <ide> When a page qualifies for [Automatic Static Optimization](/docs/advanced-features/automatic-static-optimization.md) we show an indicator to let you know. <ide><path>docs/api-reference/next/amp.md <add>--- <add>description: Enable AMP in a page, and control the way Next.js adds AMP to the page with the AMP config. <add>--- <add> <ide> # next/amp <ide> <ide> <details> <ide><path>docs/api-reference/next/head.md <add>--- <add>description: Add custom elements to the `head` of your page with the built-in Head component. <add>--- <add> <ide> # next/head <ide> <ide> <details> <ide><path>docs/api-reference/next/link.md <add>--- <add>description: Enable client-side transitions between routes with the built-in Link component. <add>--- <add> <ide> # next/link <ide> <ide> <details> <ide><path>docs/api-reference/next/router.md <add>--- <add>description: Learn more about the API of the Next.js Router, and access the router instance in your page with the useRouter hook. <add>--- <add> <ide> # next/router <ide> <ide> > Before moving forward, we recommend you to read [Routing Introduction](/docs/routing/introduction.md) first. <ide><path>docs/api-routes/api-middlewares.md <add>--- <add>description: API Routes provide built-in middlewares that parse the incoming request. Learn more about them here. <add>--- <add> <ide> # API Middlewares <ide> <ide> API routes provide built in middlewares which parse the incoming request (`req`). Those middlewares are: <ide><path>docs/api-routes/dynamic-api-routes.md <add>--- <add>description: You can add the dynamic routes used for pages to API Routes too. Learn how it works here. <add>--- <add> <ide> # Dynamic API Routes <ide> <del>API pages support [dynamic routes](/docs/routing/dynamic-routes.md), and follow the same file naming rules used for `pages`. <add>API routes support [dynamic routes](/docs/routing/dynamic-routes.md), and follow the same file naming rules used for `pages`. <ide> <ide> For example, the API route `pages/api/post/[pid].js` has the following code: <ide> <ide><path>docs/api-routes/introduction.md <add>--- <add>description: Next.js supports API Routes, which allow you to build your API without leaving your Next.js app. Learn how it works here. <add>--- <add> <ide> # API Routes <ide> <ide> <details> <ide><path>docs/api-routes/response-helpers.md <add>--- <add>description: API Routes include a set of Express.js-like methods for the response to help you creating new API endpoints. Learn how it works here. <add>--- <add> <ide> # Response Helpers <ide> <ide> The response (`res`) includes a set of Express.js-like methods to improve the developer experience and increase the speed of creating new API endpoints, take a look at the following example: <ide><path>docs/basic-features/built-in-css-support.md <add>--- <add>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>--- <add> <ide> # Built-in CSS Support <ide> <ide> <details> <ide><path>docs/basic-features/data-fetching.md <add>--- <add>description: Next.js can handle data fetching in multiple ways for server-rendered and static pages. Learn how it works here. <add>--- <add> <ide> # Data fetching <ide> <ide> Next.js has 2 pre-rendering modes built-in: <ide><path>docs/basic-features/pages.md <add>--- <add>description: Next.js pages are React Components exported in a file in the pages directory. Learn how they work here. <add>--- <add> <ide> # Pages <ide> <ide> A page is a [React Component](https://reactjs.org/docs/components-and-props.html) exported from a `.js`, `.ts`, or `.tsx` file in the `pages` directory. <ide><path>docs/basic-features/static-file-serving.md <add>--- <add>description: Next.js allows you to serve static files, like images, in the public directory. You can learn how it works here. <add>--- <add> <ide> # Static File Serving <ide> <ide> Next.js can serve static files, like images, under a folder called `public` in the root directory. Files inside `public` can then be referenced by your code starting from the base URL (`/`). <ide><path>docs/basic-features/typescript.md <add>--- <add>description: Next.js supports TypeScript by default and has built-in types for pages and the API. You can get started with Next.js and TypeScript here. <add>--- <add> <ide> # TypeScript <ide> <ide> <details> <ide><path>docs/deployment.md <add>--- <add>description: Compile and deploy your Next.js app to production with ZEIT Now and other hosting alternatives. <add>--- <add> <ide> # Deployment <ide> <ide> To go to production Next.js has a `next build` command. When ran it will compile your project and automatically apply numerous optimizations. <ide><path>docs/faq.md <add>--- <add>description: Get to know more about Next.js with the frequently asked questions. <add>--- <add> <ide> # Frequently Asked Questions <ide> <ide> <details> <ide><path>docs/getting-started.md <ide> --- <del>description: Getting started with Next.js. <add>description: Get started with Next.js in the official documentation, and learn more about all our features! <ide> --- <ide> <ide> # Getting Started <ide><path>docs/routing/dynamic-routes.md <add>--- <add>description: Dynamic Routes are pages that allow you to add custom params to your URLs. Start creating Dynamic Routes and learn more here. <add>--- <add> <ide> # Dynamic Routes <ide> <ide> <details> <ide><path>docs/routing/imperatively.md <add>--- <add>description: Client-side navigations are also possible using the Router API instead of the Link component. Learn more here. <add>--- <add> <ide> # Imperatively <ide> <ide> <details> <ide><path>docs/routing/introduction.md <add>--- <add>description: Next.js has a built-in, opinionated, and file-system based Router. You can learn how it works here. <add>--- <add> <ide> # Routing <ide> <ide> Next.js has a file-system based router built on the [concept of pages](/docs/basic-features/pages.md). <ide><path>docs/routing/shallow-routing.md <add>--- <add>description: You can use shallow routing to change the URL without triggering a new page change. Learn more here. <add>--- <add> <ide> # Shallow Routing <ide> <ide> <details>
52
Python
Python
expand get_flashed_messages tests
b9907b496911d0d8676225151a36c28fe4f4b72f
<ide><path>flask/testsuite/basic.py <ide> def index(): <ide> <ide> @app.route('/test') <ide> def test(): <add> messages = flask.get_flashed_messages() <add> self.assert_equal(len(messages), 3) <add> self.assert_equal(messages[0], u'Hello World') <add> self.assert_equal(messages[1], u'Hello World') <add> self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>')) <add> return '' <add> <add> @app.route('/test_with_categories') <add> def test_with_categories(): <ide> messages = flask.get_flashed_messages(with_categories=True) <ide> self.assert_equal(len(messages), 3) <ide> self.assert_equal(messages[0], ('message', u'Hello World')) <ide> self.assert_equal(messages[1], ('error', u'Hello World')) <ide> self.assert_equal(messages[2], ('warning', flask.Markup(u'<em>Testing</em>'))) <ide> return '' <del> messages = flask.get_flashed_messages() <del> self.assert_equal(len(messages), 3) <add> <add> @app.route('/test_filter') <add> def test_filter(): <add> messages = flask.get_flashed_messages(category_filter=['message'], with_categories=True) <add> self.assert_equal(len(messages), 1) <add> self.assert_equal(messages[0], ('message', u'Hello World')) <add> return '' <add> <add> @app.route('/test_filters') <add> def test_filters(): <add> messages = flask.get_flashed_messages(category_filter=['message', 'warning'], with_categories=True) <add> self.assert_equal(len(messages), 2) <add> self.assert_equal(messages[0], ('message', u'Hello World')) <add> self.assert_equal(messages[1], ('warning', flask.Markup(u'<em>Testing</em>'))) <add> return '' <add> <add> @app.route('/test_filters_without_returning_categories') <add> def test_filters(): <add> messages = flask.get_flashed_messages(category_filter=['message', 'warning']) <add> self.assert_equal(len(messages), 2) <ide> self.assert_equal(messages[0], u'Hello World') <del> self.assert_equal(messages[1], u'Hello World') <del> self.assert_equal(messages[2], flask.Markup(u'<em>Testing</em>')) <add> self.assert_equal(messages[1], flask.Markup(u'<em>Testing</em>')) <add> return '' <ide> <ide> c = app.test_client() <del> c.get('/') <add> c.get('/') # Flash some messages. <ide> c.get('/test') <ide> <add> c.get('/') # Flash more messages. <add> c.get('/test_with_categories') <add> <add> c.get('/') # Flash more messages. <add> c.get('/test_filter') <add> <add> c.get('/') # Flash more messages. <add> c.get('/test_filters') <add> <add> c.get('/') # Flash more messages. <add> c.get('/test_filters_without_returning_categories') <add> <ide> def test_request_processing(self): <ide> app = flask.Flask(__name__) <ide> evts = []
1
PHP
PHP
remove unused variables
42b16bfc934ca7b5c1f33c8438d0ab45a7484950
<ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> class RoutingUrlGeneratorTest extends TestCase <ide> public function testBasicGeneration() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> new RouteCollection, <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->to('foo/bar')); <ide> public function testBasicGeneration() <ide> * Test HTTPS request URL generation... <ide> */ <ide> $url = new UrlGenerator( <del> $routes = new RouteCollection, <del> $request = Request::create('https://www.foo.com/') <add> new RouteCollection, <add> Request::create('https://www.foo.com/') <ide> ); <ide> <ide> $this->assertEquals('https://www.foo.com/foo/bar', $url->to('foo/bar')); <ide> public function testBasicGeneration() <ide> * Test asset URL generation... <ide> */ <ide> $url = new UrlGenerator( <del> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/index.php/') <add> new RouteCollection, <add> Request::create('http://www.foo.com/index.php/') <ide> ); <ide> <ide> $this->assertEquals('http://www.foo.com/foo/bar', $url->asset('foo/bar')); <ide> public function testBasicGenerationWithHostFormatting() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], '/named-route', ['as' => 'plain']); <ide> public function testBasicGenerationWithPathFormatting() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], '/named-route', ['as' => 'plain']); <ide> public function testUrlFormattersShouldReceiveTargetRoute() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://abc.com/') <add> Request::create('http://abc.com/') <ide> ); <ide> <ide> $namedRoute = new Route(['GET'], '/bar', ['as' => 'plain', 'root' => 'bar.com', 'path' => 'foo']); <ide> public function testBasicRouteGeneration() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> /* <ide> public function testFluentRouteNameDefinitions() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> /* <ide> public function testControllerRoutesWithADefaultNamespace() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->setRootControllerNamespace('namespace'); <ide> public function testControllerRoutesOutsideOfDefaultNamespace() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->setRootControllerNamespace('namespace'); <ide> public function testRoutableInterfaceRouting() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/{bar}', ['as' => 'routable']); <ide> public function testRoutableInterfaceRoutingWithSingleParameter() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/{bar}', ['as' => 'routable']); <ide> public function testRoutesMaintainRequestScheme() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('https://www.foo.com/') <add> Request::create('https://www.foo.com/') <ide> ); <ide> <ide> /* <ide> public function testHttpOnlyRoutes() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('https://www.foo.com/') <add> Request::create('https://www.foo.com/') <ide> ); <ide> <ide> /* <ide> public function testRoutesWithDomains() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <ide> public function testRoutesWithDomainsAndPorts() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com:8080/') <add> Request::create('http://www.foo.com:8080/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <ide> public function testRoutesWithDomainsStripsProtocols() <ide> */ <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'http://sub.foo.com']); <ide> public function testRoutesWithDomainsStripsProtocols() <ide> */ <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('https://www.foo.com/') <add> Request::create('https://www.foo.com/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'https://sub.foo.com']); <ide> public function testHttpsRoutesWithDomains() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('https://foo.com/') <add> Request::create('https://foo.com/') <ide> ); <ide> <ide> /* <ide> public function testRoutesWithDomainsThroughProxy() <ide> <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_X_FORWARDED_PORT' => '80']) <add> Request::create('http://www.foo.com/', 'GET', [], [], [], ['REMOTE_ADDR' => '10.0.0.1', 'HTTP_X_FORWARDED_PORT' => '80']) <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/bar', ['as' => 'foo', 'domain' => 'sub.foo.com']); <ide> public function testUrlGenerationForControllersRequiresPassingOfRequiredParamete <ide> <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com:8080/') <add> Request::create('http://www.foo.com:8080/') <ide> ); <ide> <ide> $route = new Route(['GET'], 'foo/{one}/{two?}/{three?}', ['as' => 'foo', function () { <ide> public function testForceRootUrl() <ide> { <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->forceRootUrl('https://www.bar.com'); <ide> public function testForceRootUrl() <ide> */ <ide> $url = new UrlGenerator( <ide> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->forceScheme('https'); <ide> public function testForceRootUrl() <ide> public function testPrevious() <ide> { <ide> $url = new UrlGenerator( <del> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> new RouteCollection, <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->getRequest()->headers->set('referer', 'http://www.bar.com/'); <ide> public function testRouteNotDefinedException() <ide> $this->expectExceptionMessage('Route [not_exists_route] not defined.'); <ide> <ide> $url = new UrlGenerator( <del> $routes = new RouteCollection, <del> $request = Request::create('http://www.foo.com/') <add> new RouteCollection, <add> Request::create('http://www.foo.com/') <ide> ); <ide> <ide> $url->route('not_exists_route');
1
Ruby
Ruby
use arel instead of sql strings
475d1d1713faddee890e2367724a629169e079fe
<ide><path>activerecord/lib/active_record/locking/optimistic.rb <ide> def destroy #:nodoc: <ide> lock_col = self.class.locking_column <ide> previous_value = send(lock_col).to_i <ide> <del> affected_rows = connection.delete( <del> "DELETE FROM #{self.class.quoted_table_name} " + <del> "WHERE #{connection.quote_column_name(self.class.primary_key)} = #{quoted_id} " + <del> "AND #{self.class.quoted_locking_column} = #{quote_value(previous_value)}", <del> "#{self.class.name} Destroy" <del> ) <add> table = self.class.arel_table <add> predicate = table[self.class.primary_key].eq(id) <add> predicate = predicate.and(table[self.class.locking_column].eq(previous_value)) <add> <add> affected_rows = self.class.unscoped.where(predicate).delete_all <ide> <ide> unless affected_rows == 1 <ide> raise ActiveRecord::StaleObjectError, "Attempted to delete a stale object: #{self.class.name}"
1
Python
Python
make genv8constants.py python3-compatible
af03f4425e42c15e32e0bd9c42f56b3d38110e3c
<ide><path>tools/genv8constants.py <ide> def out_define(): <ide> out_reset() <ide> <ide> for line in pipe: <add> line = line.decode('utf-8') <ide> if curr_sym != None: <ide> # <ide> # This bit of code has nasty knowledge of the objdump text output
1
Javascript
Javascript
pass sandbox to vm.runinnewcontext()
4c6069bbc383d34261df280abaa967605215edc9
<ide><path>test/ConfigTestCases.test.js <ide> describe("ConfigTestCases", function() { <ide> var p = path.join(outputDirectory, module); <ide> var fn; <ide> if (options.target === "web") { <del> fn = vm.runInNewContext("(function(require, module, exports, __dirname, __filename, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p); <add> fn = vm.runInNewContext("(function(require, module, exports, __dirname, __filename, it) {" + fs.readFileSync(p, "utf-8") + "\n})", {}, p); <ide> } else { <ide> fn = vm.runInThisContext("(function(require, module, exports, __dirname, __filename, it) {" + fs.readFileSync(p, "utf-8") + "\n})", p); <ide> }
1
Text
Text
fix typo in changelog
4942b4126772b98ebb37d83d70372a2868042b65
<ide><path>activerecord/CHANGELOG.md <ide> <ide> *Sean Griffin* <ide> <del>* Give `AcriveRecord::Relation#update` its own deprecation warning when <add>* Give `ActiveRecord::Relation#update` its own deprecation warning when <ide> passed an `ActiveRecord::Base` instance. <ide> <ide> Fixes #21945.
1
Javascript
Javascript
add test for scale
d49b5b82c7d2f487cd858af278801aee3a564afe
<ide><path>test/scale.linear.tests.js <ide> describe('Linear Scale', function() { <ide> expect(scale.max).toBe(200); <ide> }); <ide> <add> it('Should correctly determine the min and max data values when stacked mode is turned on there are multiple types of datasets', function() { <add> var scaleID = 'myScale'; <add> <add> var mockData = { <add> datasets: [{ <add> type: 'bar', <add> yAxisID: scaleID, <add> data: [10, 5, 0, -5, 78, -100] <add> }, { <add> type: 'line', <add> yAxisID: scaleID, <add> data: [10, 10, 10, 10, 10, 10], <add> }, { <add> type: 'bar', <add> yAxisID: scaleID, <add> data: [150, 0, 0, -100, -10, 9] <add> }] <add> }; <add> <add> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('linear')); <add> config.stacked = true; // enable scale stacked mode <add> <add> var Constructor = Chart.scaleService.getScaleConstructor('linear'); <add> var scale = new Constructor({ <add> ctx: {}, <add> options: config, <add> chart: { <add> data: mockData <add> }, <add> id: scaleID <add> }); <add> <add> // Set arbitrary width and height for now <add> scale.width = 50; <add> scale.height = 400; <add> <add> scale.determineDataLimits(); <add> expect(scale.min).toBe(-105); <add> expect(scale.max).toBe(160); <add> }); <add> <ide> it('Should ensure that the scale has a max and min that are not equal', function() { <ide> var scaleID = 'myScale'; <ide>
1
Ruby
Ruby
ensure autocorrect when `desc` ends in `.`
6f2f97b98f1069fa299386fca31502e1101dbf13
<ide><path>Library/Homebrew/test/rubocops/formula_desc_spec.rb <ide> class Foo < Formula <ide> RUBY <ide> end <ide> <del> it "reports an offense when the description ends with a full stop" do <add> it "report and corrects an offense when the description ends with a full stop" do <ide> expect_offense(<<~RUBY, "/homebrew-core/Formula/foo.rb") <ide> class Foo < Formula <ide> url 'https://brew.sh/foo-1.0.tgz' <ide> desc 'Description with a full stop at the end.' <del> ^ Description shouldn\'t end with a full stop. <add> ^ Description shouldn't end with a full stop. <add> end <add> RUBY <add> <add> expect_correction(<<~RUBY) <add> class Foo < Formula <add> url 'https://brew.sh/foo-1.0.tgz' <add> desc 'Description with a full stop at the end' <ide> end <ide> RUBY <ide> end
1
Javascript
Javascript
update es longdateformats
2a1be653b32eeac6785821a6bfe3269c23d42558
<ide><path>lang/es.js <ide> longDateFormat : { <ide> LT : "H:mm", <ide> L : "DD/MM/YYYY", <del> LL : "D [de] MMMM [de] YYYY", <del> LLL : "D [de] MMMM [de] YYYY LT", <del> LLLL : "dddd, D [de] MMMM [de] YYYY LT" <add> LL : "D [de] MMMM [del] YYYY", <add> LLL : "D [de] MMMM [del] YYYY LT", <add> LLLL : "dddd, D [de] MMMM [del] YYYY LT" <ide> }, <ide> calendar : { <ide> sameDay : function () {
1
Javascript
Javascript
pass a dummy event into triggerhandler
0401a7f598ef9a36ffe1f217e1a98961046fa551
<ide><path>src/jqLite.js <ide> * - [replaceWith()](http://api.jquery.com/replaceWith/) <ide> * - [text()](http://api.jquery.com/text/) <ide> * - [toggleClass()](http://api.jquery.com/toggleClass/) <del> * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers. <add> * - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers. <ide> * - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces <ide> * - [val()](http://api.jquery.com/val/) <ide> * - [wrap()](http://api.jquery.com/wrap/) <ide> forEach({ <ide> <ide> triggerHandler: function(element, eventName) { <ide> var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName]; <add> var event; <ide> <ide> forEach(eventFns, function(fn) { <del> fn.call(element, null); <add> fn.call(element, {preventDefault: noop}); <ide> }); <ide> } <ide> }, function(fn, name){ <ide><path>test/jqLiteSpec.js <ide> describe('jqLite', function() { <ide> if (msie < 9){ <ide> var evnt = document.createEventObject(); <ide> evnt.srcElement = element; <del> evnt.relatedTarget = relatedTarget; <add> evnt.relatedTarget = relatedTarget; <ide> element.fireEvent('on' + type, evnt); <ide> return; <ide> }; <ide> describe('jqLite', function() { <ide> expect(clickSpy1).toHaveBeenCalledOnce(); <ide> expect(clickSpy2).toHaveBeenCalledOnce(); <ide> }); <add> <add> it('should pass in a dummy event', function() { <add> // we need the event to have at least preventDefault because angular will call it on <add> // all anchors with no href automatically <add> <add> var element = jqLite('<a>poke</a>'), <add> pokeSpy = jasmine.createSpy('poke'), <add> event; <add> <add> element.bind('click', pokeSpy); <add> <add> element.triggerHandler('click'); <add> event = pokeSpy.mostRecentCall.args[0]; <add> expect(event.preventDefault).toBeDefined(); <add> }); <ide> }); <ide> <ide>
2
Text
Text
clarify issues and pull requests guidance
c1d18a0728fc43036af47780414bb519b670a4d5
<ide><path>COLLABORATOR_GUIDE.md <ide> ## Contents <ide> <ide> * [Issues and Pull Requests](#issues-and-pull-requests) <del> - [Managing Issues and Pull Requests](#managing-issues-and-pull-requests) <ide> - [Welcoming First-Time Contributors](#welcoming-first-time-contributors) <ide> - [Closing Issues and Pull Requests](#closing-issues-and-pull-requests) <ide> - [Author ready pull requests](#author-ready-pull-requests) <ide> Collaborators should understand the <ide> <ide> ## Issues and Pull Requests <ide> <del>### Managing Issues and Pull Requests <del> <del>Collaborators should take full responsibility for managing issues and pull <del>requests they feel qualified to handle. Make sure this is done while being <del>mindful of these guidelines, the opinions of other Collaborators, and guidance <del>of the [TSC][]. They may also notify other qualified parties for more input on <del>an issue or a pull request. <del>See [Who to CC in the issue tracker](#who-to-cc-in-the-issue-tracker). <add>Mind these guidelines, the opinions of other Collaborators, and guidance of the <add>[TSC][]. Notify other qualified parties for more input on an issue or a pull <add>request. See [Who to CC in the issue tracker](#who-to-cc-in-the-issue-tracker). <ide> <ide> ### Welcoming First-Time Contributors <ide>
1
Javascript
Javascript
use clientrequest "aborted" value (#966)
f1fb3de38fc96287763aeb7c5fee23858c851955
<ide><path>lib/adapters/http.js <ide> module.exports = function httpAdapter(config) { <ide> var data = config.data; <ide> var headers = config.headers; <ide> var timer; <del> var aborted = false; <ide> <ide> // Set User-Agent (required by some servers) <ide> // Only set header if it hasn't been set in config <ide> module.exports = function httpAdapter(config) { <ide> <ide> // Create the request <ide> var req = transport.request(options, function handleResponse(res) { <del> if (aborted) return; <add> if (req.aborted) return; <ide> <ide> // Response has been received so kill timer that handles request timeout <ide> clearTimeout(timer); <ide> module.exports = function httpAdapter(config) { <ide> }); <ide> <ide> stream.on('error', function handleStreamError(err) { <del> if (aborted) return; <add> if (req.aborted) return; <ide> reject(enhanceError(err, config, null, lastRequest)); <ide> }); <ide> <ide> module.exports = function httpAdapter(config) { <ide> <ide> // Handle errors <ide> req.on('error', function handleRequestError(err) { <del> if (aborted) return; <add> if (req.aborted) return; <ide> reject(enhanceError(err, config, null, req)); <ide> }); <ide> <ide> module.exports = function httpAdapter(config) { <ide> timer = setTimeout(function handleRequestTimeout() { <ide> req.abort(); <ide> reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', req)); <del> aborted = true; <ide> }, config.timeout); <ide> } <ide> <ide> if (config.cancelToken) { <ide> // Handle cancellation <ide> config.cancelToken.promise.then(function onCanceled(cancel) { <del> if (aborted) { <del> return; <del> } <add> if (req.aborted) return; <ide> <ide> req.abort(); <ide> reject(cancel); <del> aborted = true; <ide> }); <ide> } <ide>
1
Javascript
Javascript
add setnodelay to cryptostream
4d0416caf6e9ff2f09494e1257fd714c65cf0da4
<ide><path>lib/tls.js <ide> CryptoStream.prototype.setTimeout = function(n) { <ide> }; <ide> <ide> <add>CryptoStream.prototype.setNoDelay = function() { <add> if (this.socket) this.socket.setNoDelay(); <add>}; <add> <add> <ide> // EG '/C=US/ST=CA/L=SF/O=Joyent/OU=Node.js/CN=ca1/emailAddress=ry@clouds.org' <ide> function parseCertString(s) { <ide> var out = {};
1
PHP
PHP
fix bug in belongtomany when using first
8c47b5b8f108de1fccc70727d9c013c57dd1a4fa
<ide><path>src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php <ide> public function getResults() <ide> return $this->get(); <ide> } <ide> <add> /** <add> * Execute the query and get the first result. <add> * <add> * @param array $columns <add> * @return mixed <add> */ <add> public function first($columns = array('*')) <add> { <add> $results = $this->take(1)->get($columns); <add> <add> return count($results) > 0 ? $results->first() : null; <add> } <add> <ide> /** <ide> * Execute the query as a "select" statement. <ide> *
1
Ruby
Ruby
add newline to new issue reporting instructions
8934fdbe82a34daa656ba185f197ea439a9b0797
<ide><path>Library/Homebrew/brew.h.rb <ide> FORMULA_META_FILES = %w[README README.md ChangeLog COPYING LICENSE LICENCE COPYRIGHT AUTHORS] <del>PLEASE_REPORT_BUG = "#{Tty.white}Please follow the instructions to report this bug at #{Tty.em}https://github.com/mxcl/homebrew/wiki/new-issue#{Tty.reset}" <add>PLEASE_REPORT_BUG = "#{Tty.white}Please follow the instructions to report this bug at: #{Tty.em}\nhttps://github.com/mxcl/homebrew/wiki/new-issue#{Tty.reset}" <ide> <ide> def check_for_blacklisted_formula names <ide> return if ARGV.force?
1
Python
Python
improve idempotency of bigqueryinsertjoboperator
be46d20fb431cc1d91c935e8894dfc7756c18993
<ide><path>airflow/providers/google/cloud/hooks/bigquery.py <ide> <ide> log = logging.getLogger(__name__) <ide> <add>BigQueryJob = Union[CopyJob, QueryJob, LoadJob, ExtractJob] <add> <ide> <ide> # pylint: disable=too-many-public-methods <ide> class BigQueryHook(GoogleBaseHook, DbApiHook): <ide> def insert_job( <ide> job_id: Optional[str] = None, <ide> project_id: Optional[str] = None, <ide> location: Optional[str] = None, <del> ) -> Union[CopyJob, QueryJob, LoadJob, ExtractJob]: <add> ) -> BigQueryJob: <ide> """ <ide> Executes a BigQuery job. Waits for the job to complete and returns job id. <ide> See here: <ide><path>airflow/providers/google/cloud/operators/bigquery.py <ide> This module contains Google BigQuery operators. <ide> """ <ide> import enum <add>import hashlib <ide> import json <add>import re <add>import uuid <ide> import warnings <del>from time import sleep, time <del>from typing import Any, Dict, Iterable, List, Optional, SupportsAbs, Union <add>from typing import Any, Dict, Iterable, List, Optional, Set, SupportsAbs, Union <ide> <ide> import attr <ide> from google.api_core.exceptions import Conflict <del>from google.api_core.retry import exponential_sleep_generator <ide> from google.cloud.bigquery import TableReference <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.models import BaseOperator, BaseOperatorLink <ide> from airflow.models.taskinstance import TaskInstance <ide> from airflow.operators.check_operator import CheckOperator, IntervalCheckOperator, ValueCheckOperator <del>from airflow.providers.google.cloud.hooks.bigquery import BigQueryHook <add>from airflow.providers.google.cloud.hooks.bigquery import BigQueryHook, BigQueryJob <ide> from airflow.providers.google.cloud.hooks.gcs import GCSHook, _parse_gcs_url <ide> from airflow.utils.decorators import apply_defaults <ide> <ide> def execute(self, context): <ide> class BigQueryInsertJobOperator(BaseOperator): <ide> """ <ide> Executes a BigQuery job. Waits for the job to complete and returns job id. <del> See here: <add> This operator work in the following way: <add> <add> - it calculates a unique hash of the job using job's configuration or uuid if ``force_rerun`` is True <add> - creates ``job_id`` in form of <add> ``[provided_job_id | airflow_{dag_id}_{task_id}_{exec_date}]_{uniqueness_suffix}`` <add> - submits a BigQuery job using the ``job_id`` <add> - if job with given id already exists then it tries to reattach to the job if its not done and its <add> state is in ``reattach_states``. If the job is done the operator will raise ``AirflowException``. <add> <add> Using ``force_rerun`` will submit a new job everytime without attaching to already existing ones. <add> <add> For job definition see here: <ide> <ide> https://cloud.google.com/bigquery/docs/reference/v2/jobs <ide> <ide> class BigQueryInsertJobOperator(BaseOperator): <ide> configuration field in the job object. For more details see <ide> https://cloud.google.com/bigquery/docs/reference/v2/jobs <ide> :type configuration: Dict[str, Any] <del> :param job_id: The ID of the job. The ID must contain only letters (a-z, A-Z), <del> numbers (0-9), underscores (_), or dashes (-). The maximum length is 1,024 <del> characters. If not provided then uuid will be generated. <add> :param job_id: The ID of the job. It will be suffixed with hash of job configuration <add> unless ``force_rerun`` is True. <add> The ID must contain only letters (a-z, A-Z), numbers (0-9), underscores (_), or <add> dashes (-). The maximum length is 1,024 characters. If not provided then uuid will <add> be generated. <ide> :type job_id: str <add> :param force_rerun: If True then operator will use hash of uuid as job id suffix <add> :type force_rerun: bool <add> :param reattach_states: Set of BigQuery job's states in case of which we should reattach <add> to the job. Should be other than final states. <ide> :param project_id: Google Cloud Project where the job is running <ide> :type project_id: str <ide> :param location: location the job is running <ide> :type location: str <del> :param gcp_conn_id: (Optional) The connection ID used to connect to Google Cloud Platform. <add> :param gcp_conn_id: The connection ID used to connect to Google Cloud Platform. <ide> :type gcp_conn_id: str <ide> """ <ide> <ide> def __init__( <ide> project_id: Optional[str] = None, <ide> location: Optional[str] = None, <ide> job_id: Optional[str] = None, <add> force_rerun: bool = True, <add> reattach_states: Optional[Set[str]] = None, <ide> gcp_conn_id: str = 'google_cloud_default', <ide> delegate_to: Optional[str] = None, <ide> **kwargs, <ide> def __init__( <ide> self.project_id = project_id <ide> self.gcp_conn_id = gcp_conn_id <ide> self.delegate_to = delegate_to <add> self.force_rerun = force_rerun <add> self.reattach_states: Set[str] = reattach_states or set() <ide> <ide> def prepare_template(self) -> None: <ide> # If .json is passed then we have to read the file <ide> if isinstance(self.configuration, str) and self.configuration.endswith('.json'): <ide> with open(self.configuration, 'r') as file: <ide> self.configuration = json.loads(file.read()) <ide> <add> def _submit_job( <add> self, <add> hook: BigQueryHook, <add> job_id: str, <add> ) -> BigQueryJob: <add> # Submit a new job <add> job = hook.insert_job( <add> configuration=self.configuration, <add> project_id=self.project_id, <add> location=self.location, <add> job_id=job_id, <add> ) <add> # Start the job and wait for it to complete and get the result. <add> job.result() <add> return job <add> <add> @staticmethod <add> def _handle_job_error(job: BigQueryJob) -> None: <add> if job.error_result: <add> raise AirflowException(f"BigQuery job {job.job_id} failed: {job.error_result}") <add> <add> def _job_id(self, context): <add> if self.force_rerun: <add> hash_base = str(uuid.uuid4()) <add> else: <add> hash_base = json.dumps(self.configuration, sort_keys=True) <add> <add> uniqueness_suffix = hashlib.md5(hash_base.encode()).hexdigest() <add> <add> if self.job_id: <add> return f"{self.job_id}_{uniqueness_suffix}" <add> <add> exec_date = re.sub(r"\:|-|\+", "_", context['execution_date'].isoformat()) <add> return f"airflow_{self.dag_id}_{self.task_id}_{exec_date}_{uniqueness_suffix}" <add> <ide> def execute(self, context: Any): <ide> hook = BigQueryHook( <ide> gcp_conn_id=self.gcp_conn_id, <ide> delegate_to=self.delegate_to, <ide> ) <ide> <del> job_id = self.job_id or f"airflow_{self.task_id}_{int(time())}" <add> job_id = self._job_id(context) <add> <ide> try: <del> job = hook.insert_job( <del> configuration=self.configuration, <del> project_id=self.project_id, <del> location=self.location, <del> job_id=job_id, <del> ) <del> # Start the job and wait for it to complete and get the result. <del> job.result() <add> job = self._submit_job(hook, job_id) <add> self._handle_job_error(job) <ide> except Conflict: <add> # If the job already exists retrieve it <ide> job = hook.get_job( <ide> project_id=self.project_id, <ide> location=self.location, <ide> job_id=job_id, <ide> ) <del> # Get existing job and wait for it to be ready <del> for time_to_wait in exponential_sleep_generator(initial=10, maximum=120): <del> sleep(time_to_wait) <del> job.reload() <del> if job.done(): <del> break <add> if job.state in self.reattach_states: <add> # We are reattaching to a job <add> job.result() <add> self._handle_job_error(job) <add> else: <add> # Same job configuration so we need force_rerun <add> raise AirflowException( <add> f"Job with id: {job_id} already exists and is in {job.state} state. If you " <add> f"want to force rerun it consider setting `force_rerun=True`." <add> f"Or, if you want to reattach in this scenario add {job.state} to `reattach_states`" <add> ) <add> <ide> return job.job_id <ide><path>tests/providers/google/cloud/operators/test_bigquery.py <ide> from unittest.mock import MagicMock <ide> <ide> import mock <add>import pytest <ide> from google.cloud.exceptions import Conflict <ide> from parameterized import parameterized <ide> <ide> def test_execute(self, mock_hook): <ide> <ide> <ide> class TestBigQueryInsertJobOperator: <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <ide> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <del> def test_execute(self, mock_hook): <add> def test_execute_success(self, mock_hook, mock_md5): <ide> job_id = "123456" <add> hash_ = "hash" <add> real_job_id = f"{job_id}_{hash_}" <add> mock_md5.return_value.hexdigest.return_value = hash_ <add> <ide> configuration = { <ide> "query": { <ide> "query": "SELECT * FROM any", <ide> "useLegacySql": False, <ide> } <ide> } <del> mock_hook.return_value.insert_job.return_value = MagicMock(job_id=job_id) <add> mock_hook.return_value.insert_job.return_value = MagicMock(job_id=real_job_id, error_result=False) <ide> <ide> op = BigQueryInsertJobOperator( <ide> task_id="insert_query_job", <ide> def test_execute(self, mock_hook): <ide> mock_hook.return_value.insert_job.assert_called_once_with( <ide> configuration=configuration, <ide> location=TEST_DATASET_LOCATION, <del> job_id=job_id, <add> job_id=real_job_id, <ide> project_id=TEST_GCP_PROJECT_ID, <ide> ) <ide> <del> assert result == job_id <add> assert result == real_job_id <ide> <del> @mock.patch('airflow.providers.google.cloud.operators.bigquery.exponential_sleep_generator') <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <ide> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <del> def test_execute_idempotency(self, mock_hook, mock_sleep_generator): <add> def test_execute_failure(self, mock_hook, mock_md5): <ide> job_id = "123456" <add> hash_ = "hash" <add> real_job_id = f"{job_id}_{hash_}" <add> mock_md5.return_value.hexdigest.return_value = hash_ <ide> <ide> configuration = { <ide> "query": { <ide> "query": "SELECT * FROM any", <ide> "useLegacySql": False, <ide> } <ide> } <add> mock_hook.return_value.insert_job.return_value = MagicMock(job_id=real_job_id, error_result=True) <ide> <del> class MockJob: <del> _call_no = 0 <del> _done = False <del> <del> def __init__(self): <del> pass <del> <del> def reload(self): <del> if MockJob._call_no == 3: <del> MockJob._done = True <del> else: <del> MockJob._call_no += 1 <add> op = BigQueryInsertJobOperator( <add> task_id="insert_query_job", <add> configuration=configuration, <add> location=TEST_DATASET_LOCATION, <add> job_id=job_id, <add> project_id=TEST_GCP_PROJECT_ID <add> ) <add> with pytest.raises(AirflowException): <add> op.execute({}) <ide> <del> def done(self): <del> return MockJob._done <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <add> def test_execute_reattach(self, mock_hook, mock_md5): <add> job_id = "123456" <add> hash_ = "hash" <add> real_job_id = f"{job_id}_{hash_}" <add> mock_md5.return_value.hexdigest.return_value = hash_ <ide> <del> @property <del> def job_id(self): <del> return job_id <add> configuration = { <add> "query": { <add> "query": "SELECT * FROM any", <add> "useLegacySql": False, <add> } <add> } <ide> <ide> mock_hook.return_value.insert_job.return_value.result.side_effect = Conflict("any") <del> mock_sleep_generator.return_value = [0, 0, 0, 0, 0] <del> mock_hook.return_value.get_job.return_value = MockJob() <add> job = MagicMock( <add> job_id=real_job_id, error_result=False, state="PENDING", done=lambda: False, <add> ) <add> mock_hook.return_value.get_job.return_value = job <ide> <ide> op = BigQueryInsertJobOperator( <ide> task_id="insert_query_job", <ide> configuration=configuration, <ide> location=TEST_DATASET_LOCATION, <ide> job_id=job_id, <del> project_id=TEST_GCP_PROJECT_ID <add> project_id=TEST_GCP_PROJECT_ID, <add> reattach_states={"PENDING"} <ide> ) <ide> result = op.execute({}) <ide> <del> assert MockJob._call_no == 3 <del> <ide> mock_hook.return_value.get_job.assert_called_once_with( <add> location=TEST_DATASET_LOCATION, <add> job_id=real_job_id, <add> project_id=TEST_GCP_PROJECT_ID, <add> ) <add> <add> job.result.assert_called_once_with() <add> <add> assert result == real_job_id <add> <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.uuid') <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <add> def test_execute_force_rerun(self, mock_hook, mock_uuid, mock_md5): <add> job_id = "123456" <add> hash_ = mock_uuid.uuid4.return_value.encode.return_value <add> real_job_id = f"{job_id}_{hash_}" <add> mock_md5.return_value.hexdigest.return_value = hash_ <add> <add> configuration = { <add> "query": { <add> "query": "SELECT * FROM any", <add> "useLegacySql": False, <add> } <add> } <add> <add> job = MagicMock( <add> job_id=real_job_id, error_result=False, <add> ) <add> mock_hook.return_value.insert_job.return_value = job <add> <add> op = BigQueryInsertJobOperator( <add> task_id="insert_query_job", <add> configuration=configuration, <ide> location=TEST_DATASET_LOCATION, <ide> job_id=job_id, <ide> project_id=TEST_GCP_PROJECT_ID, <add> force_rerun=True, <add> ) <add> result = op.execute({}) <add> <add> mock_hook.return_value.insert_job.assert_called_once_with( <add> configuration=configuration, <add> location=TEST_DATASET_LOCATION, <add> job_id=real_job_id, <add> project_id=TEST_GCP_PROJECT_ID, <add> ) <add> <add> assert result == real_job_id <add> <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.hashlib.md5') <add> @mock.patch('airflow.providers.google.cloud.operators.bigquery.BigQueryHook') <add> def test_execute_no_force_rerun(self, mock_hook, mock_md5): <add> job_id = "123456" <add> hash_ = "hash" <add> real_job_id = f"{job_id}_{hash_}" <add> mock_md5.return_value.hexdigest.return_value = hash_ <add> <add> configuration = { <add> "query": { <add> "query": "SELECT * FROM any", <add> "useLegacySql": False, <add> } <add> } <add> <add> mock_hook.return_value.insert_job.return_value.result.side_effect = Conflict("any") <add> job = MagicMock( <add> job_id=real_job_id, error_result=False, state="DONE", done=lambda: True, <ide> ) <add> mock_hook.return_value.get_job.return_value = job <ide> <del> assert result == job_id <add> op = BigQueryInsertJobOperator( <add> task_id="insert_query_job", <add> configuration=configuration, <add> location=TEST_DATASET_LOCATION, <add> job_id=job_id, <add> project_id=TEST_GCP_PROJECT_ID, <add> reattach_states={"PENDING"} <add> ) <add> # No force rerun <add> with pytest.raises(AirflowException): <add> op.execute({})
3
Java
Java
improve usage of advisedsupport.getadvisors()
8c3cab7eadcb07be11ed725bc82277f046a4fe7c
<ide><path>spring-aop/src/main/java/org/springframework/aop/framework/Advised.java <ide> /* <del> * Copyright 2002-2018 the original author or authors. <add> * Copyright 2002-2020 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 interface Advised extends TargetClassAware { <ide> */ <ide> String toProxyConfigString(); <ide> <add> /** <add> * Equivalent to {@code getAdvisors().length} <add> * @return count of advisors of this advised <add> */ <add> default int getAdvisorCount() { <add> return getAdvisors().length; <add> } <add> <ide> } <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/AdvisedSupport.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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 class AdvisedSupport extends ProxyConfig implements Advised { <ide> */ <ide> private List<Advisor> advisors = new ArrayList<>(); <ide> <del> /** <del> * Array updated on changes to the advisors list, which is easier <del> * to manipulate internally. <del> */ <del> private Advisor[] advisorArray = new Advisor[0]; <del> <ide> <ide> /** <ide> * No-arg constructor for use as a JavaBean. <ide> public boolean isInterfaceProxied(Class<?> intf) { <ide> <ide> @Override <ide> public final Advisor[] getAdvisors() { <del> return this.advisorArray; <add> return this.advisors.toArray(new Advisor[0]); <ide> } <ide> <ide> @Override <ide> public void removeAdvisor(int index) throws AopConfigException { <ide> } <ide> } <ide> <del> updateAdvisorArray(); <ide> adviceChanged(); <ide> } <ide> <ide> public void addAdvisors(Collection<Advisor> advisors) { <ide> Assert.notNull(advisor, "Advisor must not be null"); <ide> this.advisors.add(advisor); <ide> } <del> updateAdvisorArray(); <ide> adviceChanged(); <ide> } <ide> } <ide> private void addAdvisorInternal(int pos, Advisor advisor) throws AopConfigExcept <ide> "Illegal position " + pos + " in advisor list with size " + this.advisors.size()); <ide> } <ide> this.advisors.add(pos, advisor); <del> updateAdvisorArray(); <ide> adviceChanged(); <ide> } <ide> <del> /** <del> * Bring the array up to date with the list. <del> */ <del> protected final void updateAdvisorArray() { <del> this.advisorArray = this.advisors.toArray(new Advisor[0]); <del> } <del> <ide> /** <ide> * Allows uncontrolled access to the {@link List} of {@link Advisor Advisors}. <del> * <p>Use with care, and remember to {@link #updateAdvisorArray() refresh the advisor array} <del> * and {@link #adviceChanged() fire advice changed events} when making any modifications. <add> * <p>Use with care, and remember to {@link #adviceChanged() fire advice changed events} <add> * when making any modifications. <ide> */ <ide> protected final List<Advisor> getAdvisorsInternal() { <ide> return this.advisors; <ide> } <ide> <del> <ide> @Override <ide> public void addAdvice(Advice advice) throws AopConfigException { <ide> int pos = this.advisors.size(); <ide> protected void copyConfigurationFrom(AdvisedSupport other, TargetSource targetSo <ide> Assert.notNull(advisor, "Advisor must not be null"); <ide> this.advisors.add(advisor); <ide> } <del> updateAdvisorArray(); <ide> adviceChanged(); <ide> } <ide> <ide> AdvisedSupport getConfigurationOnlyCopy() { <ide> copy.advisorChainFactory = this.advisorChainFactory; <ide> copy.interfaces = this.interfaces; <ide> copy.advisors = this.advisors; <del> copy.updateAdvisorArray(); <ide> return copy; <ide> } <ide> <ide> private void readObject(ObjectInputStream ois) throws IOException, ClassNotFound <ide> this.methodCache = new ConcurrentHashMap<>(32); <ide> } <ide> <add> @Override <add> public int getAdvisorCount() { <add> return advisors.size(); <add> } <ide> <ide> @Override <ide> public String toProxyConfigString() { <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/AopProxyUtils.java <ide> /* <del> * Copyright 2002-2019 the original author or authors. <add> * Copyright 2002-2020 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 static boolean equalsProxiedInterfaces(AdvisedSupport a, AdvisedSupport b <ide> * Check equality of the advisors behind the given AdvisedSupport objects. <ide> */ <ide> public static boolean equalsAdvisors(AdvisedSupport a, AdvisedSupport b) { <del> return Arrays.equals(a.getAdvisors(), b.getAdvisors()); <add> return a.getAdvisorCount() == b.getAdvisorCount() && Arrays.equals(a.getAdvisors(), b.getAdvisors()); <ide> } <ide> <ide> <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/CglibAopProxy.java <ide> class CglibAopProxy implements AopProxy, Serializable { <ide> */ <ide> public CglibAopProxy(AdvisedSupport config) throws AopConfigException { <ide> Assert.notNull(config, "AdvisedSupport must not be null"); <del> if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { <add> if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { <ide> throw new AopConfigException("No advisors and no TargetSource specified"); <ide> } <ide> this.advised = config; <ide> public boolean equals(@Nullable Object other) { <ide> } <ide> // Advice instance identity is unimportant to the proxy class: <ide> // All that matters is type and ordering. <del> Advisor[] thisAdvisors = this.advised.getAdvisors(); <del> Advisor[] thatAdvisors = otherAdvised.getAdvisors(); <del> if (thisAdvisors.length != thatAdvisors.length) { <add> if (this.advised.getAdvisorCount() != otherAdvised.getAdvisorCount()) { <ide> return false; <ide> } <add> Advisor[] thisAdvisors = this.advised.getAdvisors(); <add> Advisor[] thatAdvisors = otherAdvised.getAdvisors(); <ide> for (int i = 0; i < thisAdvisors.length; i++) { <ide> Advisor thisAdvisor = thisAdvisors[i]; <ide> Advisor thatAdvisor = thatAdvisors[i]; <ide><path>spring-aop/src/main/java/org/springframework/aop/framework/JdkDynamicAopProxy.java <ide> final class JdkDynamicAopProxy implements AopProxy, InvocationHandler, Serializa <ide> */ <ide> public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException { <ide> Assert.notNull(config, "AdvisedSupport must not be null"); <del> if (config.getAdvisors().length == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { <add> if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) { <ide> throw new AopConfigException("No advisors and no TargetSource specified"); <ide> } <ide> this.advised = config;
5
Javascript
Javascript
fix a typo
d3c191ea637cc3ad56cd393ba1897f9d260709e9
<ide><path>src/ng/directive/input.js <ide> var inputType = { <ide> expect(valid.getText()).toContain('myForm.input.$valid = false'); <ide> }); <ide> </file> <del> </example>f <add> </example> <ide> */ <ide> 'date': createDateInputType('date', DATE_REGEXP, <ide> createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
1
Javascript
Javascript
remove name property from native modules
abca4660372b5055c4e0bc9591cbaf56ae477fdc
<ide><path>Libraries/Utilities/MessageQueue.js <ide> class MessageQueue { <ide> } <ide> <ide> processModuleConfig(config, moduleID) { <del> const module = this._genModule(config, moduleID); <del> this.RemoteModules[module.name] = module; <add> const info = this._genModule(config, moduleID); <add> this.RemoteModules[info.name] = info.module; <ide> this._genLookup(config, moduleID, this._remoteModuleTable, this._remoteMethodTable); <del> return module; <add> return info.module; <ide> } <ide> <ide> getEventLoopRunningTime() { <ide> class MessageQueue { <ide> let modules = {}; <ide> <ide> remoteModules.forEach((config, moduleID) => { <del> let module = this._genModule(config, moduleID); <del> if (module) { <del> modules[module.name] = module; <add> let info = this._genModule(config, moduleID); <add> if (info) { <add> modules[info.name] = info.module; <ide> } <ide> }); <ide> <ide> class MessageQueue { <ide> [moduleName, methods, asyncMethods, syncHooks] = config; <ide> } <ide> <del> let module = { <del> name: moduleName <del> }; <add> let module = {}; <ide> methods && methods.forEach((methodName, methodID) => { <ide> const isAsync = asyncMethods && arrayContains(asyncMethods, methodID); <ide> const isSyncHook = syncHooks && arrayContains(syncHooks, methodID); <ide> class MessageQueue { <ide> module.moduleID = moduleID; <ide> } <ide> <del> return module; <add> return { name: moduleName, module }; <ide> } <ide> <ide> _genMethod(module, method, type) {
1
Go
Go
show dmesg if mount fails
46833ee1c353c247e3ef817a08d5a35a2a43bdf3
<ide><path>daemon/graphdriver/devmapper/deviceset.go <ide> import ( <ide> "github.com/docker/docker/daemon/graphdriver" <ide> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/pkg/devicemapper" <add> "github.com/docker/docker/pkg/dmesg" <ide> "github.com/docker/docker/pkg/idtools" <ide> "github.com/docker/docker/pkg/loopback" <ide> "github.com/docker/docker/pkg/mount" <ide> func (devices *DeviceSet) growFS(info *devInfo) error { <ide> options = joinMountOptions(options, devices.mountOptions) <ide> <ide> if err := mount.Mount(info.DevName(), fsMountPoint, devices.BaseDeviceFilesystem, options); err != nil { <del> return fmt.Errorf("Error mounting '%s' on '%s': %s", info.DevName(), fsMountPoint, err) <add> return fmt.Errorf("Error mounting '%s' on '%s': %s\n%v", info.DevName(), fsMountPoint, err, string(dmesg.Dmesg(256))) <ide> } <ide> <ide> defer unix.Unmount(fsMountPoint, unix.MNT_DETACH) <ide> func (devices *DeviceSet) MountDevice(hash, path, mountLabel string) error { <ide> options = joinMountOptions(options, label.FormatMountLabel("", mountLabel)) <ide> <ide> if err := mount.Mount(info.DevName(), path, fstype, options); err != nil { <del> return fmt.Errorf("devmapper: Error mounting '%s' on '%s': %s", info.DevName(), path, err) <add> return fmt.Errorf("devmapper: Error mounting '%s' on '%s': %s\n%v", info.DevName(), path, err, string(dmesg.Dmesg(256))) <ide> } <ide> <ide> if fstype == "xfs" && devices.xfsNospaceRetries != "" { <ide><path>pkg/dmesg/dmesg_linux.go <add>// +build linux <add> <add>package dmesg <add> <add>import ( <add> "unsafe" <add> <add> "golang.org/x/sys/unix" <add>) <add> <add>// Dmesg returns last messages from the kernel log, up to size bytes <add>func Dmesg(size int) []byte { <add> t := uintptr(3) // SYSLOG_ACTION_READ_ALL <add> b := make([]byte, size) <add> amt, _, err := unix.Syscall(unix.SYS_SYSLOG, t, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b))) <add> if err != 0 { <add> return []byte{} <add> } <add> return b[:amt] <add>} <ide><path>pkg/dmesg/dmesg_linux_test.go <add>package dmesg <add> <add>import ( <add> "testing" <add>) <add> <add>func TestDmesg(t *testing.T) { <add> t.Logf("dmesg output follows:\n%v", string(Dmesg(512))) <add>}
3
Java
Java
remove unused method
f88c9d63828e975a9792969e27accd851ead3e86
<ide><path>ReactAndroid/src/main/java/com/facebook/react/devsupport/BundleDownloader.java <ide> public void execute(Map<String, String> headers, Buffer body, boolean finished) <ide> }); <ide> } <ide> <del> public void cancelDownloadBundleFromURL() { <del> if (mDownloadBundleFromURLCall != null) { <del> mDownloadBundleFromURLCall.cancel(); <del> mDownloadBundleFromURLCall = null; <del> } <del> } <del> <ide> private void processBundleResult( <ide> String url, <ide> int statusCode,
1
Python
Python
remove unused class definition
31aecd9b092d5bab27aac2288758eedbeda7bb81
<ide><path>numpy/testing/noseclasses.py <ide> from nose.plugins import doctests as npd <ide> from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin <ide> from nose.plugins.base import Plugin <del>from nose.util import src, getpackage <add>from nose.util import src <ide> import numpy <ide> from nosetester import get_package_name <ide> import inspect <ide> def _find(self, tests, obj, name, module, source_lines, globs, seen): <ide> globs, seen) <ide> <ide> <del>class NumpyDocTestCase(npd.DocTestCase): <del> """Proxy for DocTestCase: provides an address() method that <del> returns the correct address for the doctest case. Otherwise <del> acts as a proxy to the test case. To provide hints for address(), <del> an obj may also be passed -- this will be used as the test object <del> for purposes of determining the test address, if it is provided. <del> """ <del> <del> # doctests loaded via find(obj) omit the module name <del> # so we need to override id, __repr__ and shortDescription <del> # bonus: this will squash a 2.3 vs 2.4 incompatiblity <del> def id(self): <del> name = self._dt_test.name <del> filename = self._dt_test.filename <del> if filename is not None: <del> pk = getpackage(filename) <del> if pk is not None and not name.startswith(pk): <del> name = "%s.%s" % (pk, name) <del> return name <del> <del> <ide> # second-chance checker; if the default comparison doesn't <ide> # pass, then see if the expected output string contains flags that <ide> # tell us to ignore the output
1
Ruby
Ruby
remove unnecessary brackets in regex (closes )
01e389c965af85901ee8ea77fe099fd3081e07ea
<ide><path>activesupport/lib/active_support/inflections.rb <ide> inflect.singular(/(o)es$/i, '\1') <ide> inflect.singular(/(shoe)s$/i, '\1') <ide> inflect.singular(/(cris|ax|test)es$/i, '\1is') <del> inflect.singular(/([octop|vir])i$/i, '\1us') <add> inflect.singular(/(octop|vir)i$/i, '\1us') <ide> inflect.singular(/(alias|status)es$/i, '\1') <ide> inflect.singular(/^(ox)en/i, '\1') <ide> inflect.singular(/(vert|ind)ices$/i, '\1ex')
1
Python
Python
adjust wandb installation command
2affeb290554382042a5652bfa2a5639feb299a3
<ide><path>src/transformers/trainer_tf.py <ide> def __init__( <ide> elif os.getenv("WANDB_DISABLED", "").upper() not in ENV_VARS_TRUE_VALUES: <ide> logger.info( <ide> "You are instantiating a Trainer but W&B is not installed. To use wandb logging, " <del> "run `pip install wandb; wandb login` see https://docs.wandb.com/huggingface." <add> "run `pip install wandb && wandb login` see https://docs.wandb.com/huggingface." <ide> ) <ide> <ide> if is_comet_available():
1
Python
Python
improve clarity of window function docs
250245d49a62d9f26e755f1ba7b213f8cab2008c
<ide><path>numpy/lib/function_base.py <ide> def blackman(M): <ide> Returns <ide> ------- <ide> out : ndarray <del> The window, normalized to one (the value one appears only if the <del> number of samples is odd). <add> The window, with the maximum value normalized to one (the value one <add> appears only if the number of samples is odd). <ide> <ide> See Also <ide> -------- <ide> def blackman(M): <ide> <ide> Examples <ide> -------- <del> >>> from numpy import blackman <del> >>> blackman(12) <add> >>> np.blackman(12) <ide> array([ -1.38777878e-17, 3.26064346e-02, 1.59903635e-01, <ide> 4.14397981e-01, 7.36045180e-01, 9.67046769e-01, <ide> 9.67046769e-01, 7.36045180e-01, 4.14397981e-01, <ide> def blackman(M): <ide> <ide> Plot the window and the frequency response: <ide> <del> >>> from numpy import clip, log10, array, blackman, linspace <ide> >>> from numpy.fft import fft, fftshift <del> >>> import matplotlib.pyplot as plt <del> <del> >>> window = blackman(51) <add> >>> window = np.blackman(51) <ide> >>> plt.plot(window) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Blackman window") <ide> def blackman(M): <ide> >>> plt.figure() <ide> <matplotlib.figure.Figure object at 0x...> <ide> >>> A = fft(window, 2048) / 25.5 <del> >>> mag = abs(fftshift(A)) <del> >>> freq = linspace(-0.5,0.5,len(A)) <del> >>> response = 20*log10(mag) <del> >>> response = clip(response,-100,100) <add> >>> mag = np.abs(fftshift(A)) <add> >>> freq = np.linspace(-0.5, 0.5, len(A)) <add> >>> response = 20 * np.log10(mag) <add> >>> response = np.clip(response, -100, 100) <ide> >>> plt.plot(freq, response) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Frequency response of Blackman window") <ide> def bartlett(M): <ide> Returns <ide> ------- <ide> out : array <del> The triangular window, normalized to one (the value one <del> appears only if the number of samples is odd), with the first <del> and last samples equal to zero. <add> The triangular window, with the maximum value normalized to one <add> (the value one appears only if the number of samples is odd), with <add> the first and last samples equal to zero. <ide> <ide> See Also <ide> -------- <ide> def bartlett(M): <ide> <ide> Plot the window and its frequency response (requires SciPy and matplotlib): <ide> <del> >>> from numpy import clip, log10, array, bartlett, linspace <ide> >>> from numpy.fft import fft, fftshift <del> >>> import matplotlib.pyplot as plt <del> <del> >>> window = bartlett(51) <add> >>> window = np.bartlett(51) <ide> >>> plt.plot(window) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Bartlett window") <ide> def bartlett(M): <ide> >>> plt.figure() <ide> <matplotlib.figure.Figure object at 0x...> <ide> >>> A = fft(window, 2048) / 25.5 <del> >>> mag = abs(fftshift(A)) <del> >>> freq = linspace(-0.5,0.5,len(A)) <del> >>> response = 20*log10(mag) <del> >>> response = clip(response,-100,100) <add> >>> mag = np.abs(fftshift(A)) <add> >>> freq = np.linspace(-0.5, 0.5, len(A)) <add> >>> response = 20 * np.log10(mag) <add> >>> response = np.clip(response, -100, 100) <ide> >>> plt.plot(freq, response) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Frequency response of Bartlett window") <ide> def hanning(M): <ide> Returns <ide> ------- <ide> out : ndarray, shape(M,) <del> The window, normalized to one (the value one <del> appears only if `M` is odd). <add> The window, with the maximum value normalized to one (the value <add> one appears only if `M` is odd). <ide> <ide> See Also <ide> -------- <ide> def hanning(M): <ide> <ide> Examples <ide> -------- <del> >>> from numpy import hanning <del> >>> hanning(12) <add> >>> np.hanning(12) <ide> array([ 0. , 0.07937323, 0.29229249, 0.57115742, 0.82743037, <ide> 0.97974649, 0.97974649, 0.82743037, 0.57115742, 0.29229249, <ide> 0.07937323, 0. ]) <ide> <ide> Plot the window and its frequency response: <ide> <ide> >>> from numpy.fft import fft, fftshift <del> >>> import matplotlib.pyplot as plt <del> <ide> >>> window = np.hanning(51) <ide> >>> plt.plot(window) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> def hanning(M): <ide> >>> plt.figure() <ide> <matplotlib.figure.Figure object at 0x...> <ide> >>> A = fft(window, 2048) / 25.5 <del> >>> mag = abs(fftshift(A)) <del> >>> freq = np.linspace(-0.5,0.5,len(A)) <del> >>> response = 20*np.log10(mag) <del> >>> response = np.clip(response,-100,100) <add> >>> mag = np.abs(fftshift(A)) <add> >>> freq = np.linspace(-0.5, 0.5, len(A)) <add> >>> response = 20 * np.log10(mag) <add> >>> response = np.clip(response, -100, 100) <ide> >>> plt.plot(freq, response) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Frequency response of the Hann window") <ide> def hanning(M): <ide> >>> plt.show() <ide> <ide> """ <del> # XXX: this docstring is inconsistent with other filter windows, e.g. <del> # Blackman and Bartlett - they should all follow the same convention for <del> # clarity. Either use np. for all numpy members (as above), or import all <del> # numpy members (as in Blackman and Bartlett examples) <ide> if M < 1: <ide> return array([]) <ide> if M == 1: <ide> def hamming(M): <ide> Returns <ide> ------- <ide> out : ndarray <del> The window, normalized to one (the value one <del> appears only if the number of samples is odd). <add> The window, with the maximum value normalized to one (the value <add> one appears only if the number of samples is odd). <ide> <ide> See Also <ide> -------- <ide> def hamming(M): <ide> Plot the window and the frequency response: <ide> <ide> >>> from numpy.fft import fft, fftshift <del> >>> import matplotlib.pyplot as plt <del> <ide> >>> window = np.hamming(51) <ide> >>> plt.plot(window) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> def kaiser(M,beta): <ide> Returns <ide> ------- <ide> out : array <del> The window, normalized to one (the value one <del> appears only if the number of samples is odd). <add> The window, with the maximum value normalized to one (the value <add> one appears only if the number of samples is odd). <ide> <ide> See Also <ide> -------- <ide> def kaiser(M,beta): <ide> large enough to sample the increasingly narrow spike, otherwise nans will <ide> get returned. <ide> <del> <ide> Most references to the Kaiser window come from the signal processing <ide> literature, where it is used as one of many windowing functions for <ide> smoothing values. It is also known as an apodization (which means <ide> def kaiser(M,beta): <ide> <ide> Examples <ide> -------- <del> >>> from numpy import kaiser <del> >>> kaiser(12, 14) <add> >>> np.kaiser(12, 14) <ide> array([ 7.72686684e-06, 3.46009194e-03, 4.65200189e-02, <ide> 2.29737120e-01, 5.99885316e-01, 9.45674898e-01, <ide> 9.45674898e-01, 5.99885316e-01, 2.29737120e-01, <ide> def kaiser(M,beta): <ide> <ide> Plot the window and the frequency response: <ide> <del> >>> from numpy import clip, log10, array, kaiser, linspace <ide> >>> from numpy.fft import fft, fftshift <del> >>> import matplotlib.pyplot as plt <del> <del> >>> window = kaiser(51, 14) <add> >>> window = np.kaiser(51, 14) <ide> >>> plt.plot(window) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Kaiser window") <ide> def kaiser(M,beta): <ide> >>> plt.figure() <ide> <matplotlib.figure.Figure object at 0x...> <ide> >>> A = fft(window, 2048) / 25.5 <del> >>> mag = abs(fftshift(A)) <del> >>> freq = linspace(-0.5,0.5,len(A)) <del> >>> response = 20*log10(mag) <del> >>> response = clip(response,-100,100) <add> >>> mag = np.abs(fftshift(A)) <add> >>> freq = np.linspace(-0.5, 0.5, len(A)) <add> >>> response = 20 * np.log10(mag) <add> >>> response = np.clip(response, -100, 100) <ide> >>> plt.plot(freq, response) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Frequency response of Kaiser window") <ide> def sinc(x): <ide> -5.84680802e-02, -8.90384387e-02, -8.40918587e-02, <ide> -4.92362781e-02, -3.89804309e-17]) <ide> <del> >>> import matplotlib.pyplot as plt <ide> >>> plt.plot(x, np.sinc(x)) <ide> [<matplotlib.lines.Line2D object at 0x...>] <ide> >>> plt.title("Sinc Function")
1
Python
Python
apply ufunc signature and type test fixmes
7dc28c78005efaf6536e125461d96123083ea2db
<ide><path>numpy/core/tests/test_ufunc.py <ide> def test_generic_loops(self): <ide> just looked at the signatures registered in the build directory to find <ide> relevant functions. <ide> <del> Fixme, currently untested: <del> <del> PyUFunc_ff_f_As_dd_d <del> PyUFunc_FF_F_As_DD_D <del> PyUFunc_f_f_As_d_d <del> PyUFunc_F_F_As_D_D <del> PyUFunc_On_Om <del> <ide> """ <ide> fone = np.exp <ide> ftwo = lambda x, y: x**y <ide> fone_val = 1 <ide> ftwo_val = 1 <add> <add> # check unary PyUFunc_f_f_As_d_d <add> msg = "PyUFunc_f_f_As_d_d" <add> x = np.full(10, np.single(0), dtype=np.double) <add> assert_almost_equal(fone(x), fone_val, err_msg=msg) <add> # check unary PyUFunc_F_F_As_D_D <add> msg = "PyUFunc_F_F_As_D_D" <add> x = np.full(10, np.csingle(0), dtype=np.cdouble) <add> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> # check unary PyUFunc_f_f. <ide> msg = "PyUFunc_f_f" <del> x = np.zeros(10, dtype=np.single)[0::2] <add> x = np.zeros(10, dtype=np.single) <ide> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> # check unary PyUFunc_d_d. <ide> msg = "PyUFunc_d_d" <del> x = np.zeros(10, dtype=np.double)[0::2] <add> x = np.zeros(10, dtype=np.double) <ide> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> # check unary PyUFunc_g_g. <ide> msg = "PyUFunc_g_g" <del> x = np.zeros(10, dtype=np.longdouble)[0::2] <add> x = np.zeros(10, dtype=np.longdouble) <ide> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> # check unary PyUFunc_F_F. <ide> msg = "PyUFunc_F_F" <del> x = np.zeros(10, dtype=np.csingle)[0::2] <add> x = np.zeros(10, dtype=np.csingle) <ide> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> # check unary PyUFunc_D_D. <ide> msg = "PyUFunc_D_D" <del> x = np.zeros(10, dtype=np.cdouble)[0::2] <add> x = np.zeros(10, dtype=np.cdouble) <ide> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> # check unary PyUFunc_G_G. <ide> msg = "PyUFunc_G_G" <del> x = np.zeros(10, dtype=np.clongdouble)[0::2] <add> x = np.zeros(10, dtype=np.clongdouble) <ide> assert_almost_equal(fone(x), fone_val, err_msg=msg) <ide> <add> # check binary PyUFunc_FF_F_As_DD_D <add> msg = "PyUFunc_FF_F_As_DD_D" <add> x = np.full(10, np.csingle(1), dtype=np.cdouble) <add> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <add> # check binary PyUFunc_ff_f_As_dd_d <add> msg = "PyUFunc_ff_f_As_dd_d" <add> x = np.full(10, np.single(1), dtype=np.double) <add> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> # check binary PyUFunc_ff_f. <ide> msg = "PyUFunc_ff_f" <del> x = np.ones(10, dtype=np.single)[0::2] <add> x = np.ones(10, dtype=np.single) <ide> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> # check binary PyUFunc_dd_d. <ide> msg = "PyUFunc_dd_d" <del> x = np.ones(10, dtype=np.double)[0::2] <add> x = np.ones(10, dtype=np.double) <ide> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> # check binary PyUFunc_gg_g. <ide> msg = "PyUFunc_gg_g" <del> x = np.ones(10, dtype=np.longdouble)[0::2] <add> x = np.ones(10, dtype=np.longdouble) <ide> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> # check binary PyUFunc_FF_F. <ide> msg = "PyUFunc_FF_F" <del> x = np.ones(10, dtype=np.csingle)[0::2] <add> x = np.ones(10, dtype=np.csingle) <ide> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> # check binary PyUFunc_DD_D. <ide> msg = "PyUFunc_DD_D" <del> x = np.ones(10, dtype=np.cdouble)[0::2] <add> x = np.ones(10, dtype=np.cdouble) <ide> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> # check binary PyUFunc_GG_G. <ide> msg = "PyUFunc_GG_G" <del> x = np.ones(10, dtype=np.clongdouble)[0::2] <add> x = np.ones(10, dtype=np.clongdouble) <ide> assert_almost_equal(ftwo(x, x), ftwo_val, err_msg=msg) <ide> <ide> # class to use in testing object method loops <ide> def logical_xor(self, obj): <ide> <ide> # check unary PyUFunc_O_O <ide> msg = "PyUFunc_O_O" <del> x = np.ones(10, dtype=object)[0::2] <add> x = np.ones(10, dtype=object) <ide> assert_(np.all(np.abs(x) == 1), msg) <ide> # check unary PyUFunc_O_O_method <ide> msg = "PyUFunc_O_O_method" <del> x = np.zeros(10, dtype=object)[0::2] <del> for i in range(len(x)): <del> x[i] = foo() <add> x = np.full(10, foo(), dtype=object) <ide> assert_(np.all(np.conjugate(x) == True), msg) <ide> <ide> # check binary PyUFunc_OO_O <ide> msg = "PyUFunc_OO_O" <del> x = np.ones(10, dtype=object)[0::2] <add> x = np.ones(10, dtype=object) <ide> assert_(np.all(np.add(x, x) == 2), msg) <ide> # check binary PyUFunc_OO_O_method <ide> msg = "PyUFunc_OO_O_method" <del> x = np.zeros(10, dtype=object)[0::2] <del> for i in range(len(x)): <del> x[i] = foo() <add> x = np.full(10, foo(), dtype=object) <add> assert_(np.all(np.logical_xor(x, x)), msg) <add> # check binary PyUFunc_On_Om_method <add> msg = "PyUFunc_On_Om_method" <add> x = np.full((10, 2, 3), foo(), dtype=object) <ide> assert_(np.all(np.logical_xor(x, x)), msg) <del> <del> # check PyUFunc_On_Om <del> # fixme -- I don't know how to do this yet <ide> <ide> def test_all_ufunc(self): <ide> """Try to check presence and results of all ufuncs. <ide> def test_signature8(self): <ide> assert_equal(flags, (self.can_ignore, self.size_inferred, 0)) <ide> assert_equal(sizes, (3, -1, 9)) <ide> <del> def test_signature_failure0(self): <del> # in the following calls, a ValueError should be raised because <del> # of error in core signature <del> # FIXME These should be using assert_raises <add> def test_signature_failure_extra_parenthesis(self): <add> with assert_raises(ValueError): <add> umt.test_signature(2, 1, "((i)),(i)->()") <ide> <del> # error: extra parenthesis <del> msg = "core_sig: extra parenthesis" <del> try: <del> ret = umt.test_signature(2, 1, "((i)),(i)->()") <del> assert_equal(ret, None, err_msg=msg) <del> except ValueError: <del> pass <add> def test_signature_failure_mismatching_parenthesis(self): <add> with assert_raises(ValueError): <add> umt.test_signature(2, 1, "(i),)i(->()") <ide> <del> def test_signature_failure1(self): <del> # error: parenthesis matching <del> msg = "core_sig: parenthesis matching" <del> try: <del> ret = umt.test_signature(2, 1, "(i),)i(->()") <del> assert_equal(ret, None, err_msg=msg) <del> except ValueError: <del> pass <add> def test_signature_failure_signature_missing_input_arg(self): <add> with assert_raises(ValueError): <add> umt.test_signature(2, 1, "(i),->()") <ide> <del> def test_signature_failure2(self): <del> # error: incomplete signature. letters outside of parenthesis are ignored <del> msg = "core_sig: incomplete signature" <del> try: <del> ret = umt.test_signature(2, 1, "(i),->()") <del> assert_equal(ret, None, err_msg=msg) <del> except ValueError: <del> pass <del> <del> def test_signature_failure3(self): <del> # error: incomplete signature. 2 output arguments are specified <del> msg = "core_sig: incomplete signature" <del> try: <del> ret = umt.test_signature(2, 2, "(i),(i)->()") <del> assert_equal(ret, None, err_msg=msg) <del> except ValueError: <del> pass <add> def test_signature_failure_signature_missing_output_arg(self): <add> with assert_raises(ValueError): <add> umt.test_signature(2, 2, "(i),(i)->()") <ide> <ide> def test_get_signature(self): <ide> assert_equal(umt.inner1d.signature, "(i),(i)->()")
1
Java
Java
handle hints for cglib proxies consistently
4eca87baa3218ae36f3b17a41ffe85cf88711dd1
<ide><path>spring-context/src/main/java/org/springframework/context/aot/ApplicationContextAotGenerator.java <ide> public class ApplicationContextAotGenerator { <ide> */ <ide> public ClassName processAheadOfTime(GenericApplicationContext applicationContext, <ide> GenerationContext generationContext) { <del> return withGeneratedClassHandler(new GeneratedClassHandler(generationContext), () -> { <add> return withCglibClassHandler(new CglibClassHandler(generationContext), () -> { <ide> applicationContext.refreshForAotProcessing(generationContext.getRuntimeHints()); <ide> DefaultListableBeanFactory beanFactory = applicationContext.getDefaultListableBeanFactory(); <ide> ApplicationContextInitializationCodeGenerator codeGenerator = <ide> public ClassName processAheadOfTime(GenericApplicationContext applicationContext <ide> }); <ide> } <ide> <del> private <T> T withGeneratedClassHandler(GeneratedClassHandler generatedClassHandler, Supplier<T> task) { <add> private <T> T withCglibClassHandler(CglibClassHandler cglibClassHandler, Supplier<T> task) { <ide> try { <del> ReflectUtils.setGeneratedClassHandler(generatedClassHandler); <add> ReflectUtils.setLoadedClassHandler(cglibClassHandler::handleLoadedClass); <add> ReflectUtils.setGeneratedClassHandler(cglibClassHandler::handleGeneratedClass); <ide> return task.get(); <ide> } <ide> finally { <add> ReflectUtils.setLoadedClassHandler(null); <ide> ReflectUtils.setGeneratedClassHandler(null); <ide> } <ide> } <add><path>spring-context/src/main/java/org/springframework/context/aot/CglibClassHandler.java <del><path>spring-context/src/main/java/org/springframework/context/aot/GeneratedClassHandler.java <ide> import org.springframework.core.io.ByteArrayResource; <ide> <ide> /** <del> * Handle generated classes by adding them to a {@link GenerationContext}, <add> * Handle CGLIB classes by adding them to a {@link GenerationContext}, <ide> * and register the necessary hints so that they can be instantiated. <ide> * <ide> * @author Stephane Nicoll <ide> * @see ReflectUtils#setGeneratedClassHandler(BiConsumer) <add> * @see ReflectUtils#setLoadedClassHandler(Consumer) <ide> */ <del>class GeneratedClassHandler implements BiConsumer<String, byte[]> { <add>class CglibClassHandler { <ide> <del> private static final Consumer<Builder> asCglibProxy = hint -> <del> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, <del> MemberCategory.INVOKE_DECLARED_METHODS, <del> MemberCategory.DECLARED_FIELDS); <del> <del> private static final Consumer<Builder> asCglibProxyTargetType = hint -> <del> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS, <del> MemberCategory.INVOKE_DECLARED_METHODS); <add> private static final Consumer<Builder> instantiateCglibProxy = hint -> <add> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); <ide> <ide> private final RuntimeHints runtimeHints; <ide> <ide> private final GeneratedFiles generatedFiles; <ide> <del> GeneratedClassHandler(GenerationContext generationContext) { <add> CglibClassHandler(GenerationContext generationContext) { <ide> this.runtimeHints = generationContext.getRuntimeHints(); <ide> this.generatedFiles = generationContext.getGeneratedFiles(); <ide> } <ide> <del> @Override <del> public void accept(String className, byte[] content) { <del> this.runtimeHints.reflection().registerType(TypeReference.of(className), asCglibProxy) <del> .registerType(TypeReference.of(getTargetTypeClassName(className)), asCglibProxyTargetType); <del> String path = className.replace(".", "/") + ".class"; <add> /** <add> * Handle the specified generated CGLIB class. <add> * @param cglibClassName the name of the generated class <add> * @param content the bytecode of the generated class <add> */ <add> public void handleGeneratedClass(String cglibClassName, byte[] content) { <add> registerHints(TypeReference.of(cglibClassName)); <add> String path = cglibClassName.replace(".", "/") + ".class"; <ide> this.generatedFiles.addFile(Kind.CLASS, path, new ByteArrayResource(content)); <ide> } <ide> <del> private String getTargetTypeClassName(String proxyClassName) { <del> int index = proxyClassName.indexOf("$$SpringCGLIB$$"); <del> if (index == -1) { <del> throw new IllegalArgumentException("Failed to extract target type from " + proxyClassName); <del> } <del> return proxyClassName.substring(0, index); <add> /** <add> * Handle the specified loaded CGLIB class. <add> * @param cglibClass a cglib class that has been loaded <add> */ <add> public void handleLoadedClass(Class<?> cglibClass) { <add> registerHints(TypeReference.of(cglibClass)); <add> } <add> <add> private void registerHints(TypeReference cglibTypeReference) { <add> this.runtimeHints.reflection().registerType(cglibTypeReference, instantiateCglibProxy); <ide> } <ide> <ide> } <ide><path>spring-context/src/main/java/org/springframework/context/support/GenericApplicationContext.java <ide> import java.lang.reflect.Proxy; <ide> import java.util.List; <ide> import java.util.concurrent.atomic.AtomicBoolean; <add>import java.util.function.Consumer; <ide> import java.util.function.Supplier; <ide> <add>import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.RuntimeHints; <add>import org.springframework.aot.hint.TypeHint.Builder; <ide> import org.springframework.beans.BeanUtils; <ide> import org.springframework.beans.BeansException; <ide> import org.springframework.beans.factory.BeanDefinitionStoreException; <ide> import org.springframework.core.metrics.ApplicationStartup; <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.util.Assert; <add>import org.springframework.util.ClassUtils; <ide> <ide> /** <ide> * Generic ApplicationContext implementation that holds a single internal <ide> */ <ide> public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry { <ide> <add> private static final Consumer<Builder> asCglibProxy = hint -> <add> hint.withMembers(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, <add> MemberCategory.INVOKE_DECLARED_METHODS, <add> MemberCategory.DECLARED_FIELDS); <add> <add> private static final Consumer<Builder> asCglibProxyTarget = hint -> <add> hint.withMembers(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS, <add> MemberCategory.INVOKE_DECLARED_METHODS); <add> <add> <ide> private final DefaultListableBeanFactory beanFactory; <ide> <ide> @Nullable <ide> private void preDetermineBeanTypes(RuntimeHints runtimeHints) { <ide> if (Proxy.isProxyClass(beanType)) { <ide> runtimeHints.proxies().registerJdkProxy(beanType.getInterfaces()); <ide> } <add> else { <add> Class<?> userClass = ClassUtils.getUserClass(beanType); <add> if (userClass != beanType) { <add> runtimeHints.reflection() <add> .registerType(beanType, asCglibProxy) <add> .registerType(userClass, asCglibProxyTarget); <add> } <add> } <ide> } <ide> } <ide> } <ide><path>spring-context/src/test/java/org/springframework/context/annotation/AnnotationConfigApplicationContextTests.java <ide> <ide> import org.junit.jupiter.api.Test; <ide> <add>import org.springframework.aot.hint.MemberCategory; <ide> import org.springframework.aot.hint.RuntimeHints; <add>import org.springframework.aot.hint.TypeReference; <add>import org.springframework.aot.hint.predicate.RuntimeHintsPredicates; <ide> import org.springframework.beans.factory.FactoryBean; <ide> import org.springframework.beans.factory.NoSuchBeanDefinitionException; <ide> import org.springframework.beans.factory.annotation.Autowired; <ide> import org.springframework.context.annotation6.ComponentForScanning; <ide> import org.springframework.context.annotation6.ConfigForScanning; <ide> import org.springframework.context.annotation6.Jsr330NamedForScanning; <add>import org.springframework.context.testfixture.context.annotation.CglibConfiguration; <add>import org.springframework.context.testfixture.context.annotation.LambdaBeanConfiguration; <ide> import org.springframework.core.ResolvableType; <ide> import org.springframework.util.ObjectUtils; <ide> <ide> void refreshForAotCanInstantiateBeanWithFieldAutowiredApplicationContext() { <ide> assertThat(bean.applicationContext).isSameAs(context); <ide> } <ide> <add> @Test <add> void refreshForAotRegisterHintsForCglibProxy() { <add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); <add> context.register(CglibConfiguration.class); <add> RuntimeHints runtimeHints = new RuntimeHints(); <add> context.refreshForAotProcessing(runtimeHints); <add> TypeReference cglibType = TypeReference.of(CglibConfiguration.class.getName() + "$$SpringCGLIB$$0"); <add> assertThat(RuntimeHintsPredicates.reflection().onType(cglibType) <add> .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, <add> MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS)) <add> .accepts(runtimeHints); <add> } <add> <add> @Test <add> void refreshForAotRegisterHintsForTargetOfCglibProxy() { <add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); <add> context.register(CglibConfiguration.class); <add> RuntimeHints runtimeHints = new RuntimeHints(); <add> context.refreshForAotProcessing(runtimeHints); <add> assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of(CglibConfiguration.class)) <add> .withMemberCategories(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS, <add> MemberCategory.INVOKE_DECLARED_METHODS)) <add> .accepts(runtimeHints); <add> } <add> <add> @Test <add> void refreshForAotRegisterDoesNotConsiderLambdaBeanAsCglibProxy() { <add> AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); <add> context.register(LambdaBeanConfiguration.class); <add> RuntimeHints runtimeHints = new RuntimeHints(); <add> context.refreshForAotProcessing(runtimeHints); <add> assertThat(runtimeHints.reflection().typeHints()).isEmpty(); <add> } <add> <ide> <ide> @Configuration <ide> static class Config { <ide><path>spring-context/src/test/java/org/springframework/context/aot/ApplicationContextAotGeneratorTests.java <ide> void processAheadOfTimeWhenHasCglibProxyWriteProxyAndGenerateReflectionHints() t <ide> GenericApplicationContext applicationContext = new AnnotationConfigApplicationContext(); <ide> applicationContext.registerBean(CglibConfiguration.class); <ide> TestGenerationContext context = processAheadOfTime(applicationContext); <del> String proxyClassName = CglibConfiguration.class.getName() + "$$SpringCGLIB$$0"; <add> isRegisteredCglibClass(context, CglibConfiguration.class.getName() + "$$SpringCGLIB$$0"); <add> isRegisteredCglibClass(context, CglibConfiguration.class.getName() + "$$SpringCGLIB$$1"); <add> isRegisteredCglibClass(context, CglibConfiguration.class.getName() + "$$SpringCGLIB$$2"); <add> } <add> <add> private void isRegisteredCglibClass(TestGenerationContext context, String cglibClassName) throws IOException { <ide> assertThat(context.getGeneratedFiles() <del> .getGeneratedFileContent(Kind.CLASS, proxyClassName.replace('.', '/') + ".class")).isNotNull(); <del> assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of(proxyClassName)) <add> .getGeneratedFileContent(Kind.CLASS, cglibClassName.replace('.', '/') + ".class")).isNotNull(); <add> assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of(cglibClassName)) <ide> .withMemberCategory(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)).accepts(context.getRuntimeHints()); <ide> } <ide> <add><path>spring-context/src/test/java/org/springframework/context/aot/CglibClassHandlerTests.java <del><path>spring-context/src/test/java/org/springframework/context/aot/GeneratedClassHandlerTests.java <ide> import org.springframework.core.io.InputStreamSource; <ide> <ide> import static org.assertj.core.api.Assertions.assertThat; <del>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; <ide> <ide> /** <del> * Tests for {@link GeneratedClassHandler}. <add> * Tests for {@link CglibClassHandler}. <ide> * <ide> * @author Stephane Nicoll <ide> */ <del>class GeneratedClassHandlerTests { <add>class CglibClassHandlerTests { <ide> <ide> private static final byte[] TEST_CONTENT = new byte[] { 'a' }; <ide> <ide> private final TestGenerationContext generationContext; <ide> <del> private final GeneratedClassHandler handler; <add> private final CglibClassHandler handler; <ide> <del> public GeneratedClassHandlerTests() { <add> public CglibClassHandlerTests() { <ide> this.generationContext = new TestGenerationContext(); <del> this.handler = new GeneratedClassHandler(this.generationContext); <add> this.handler = new CglibClassHandler(this.generationContext); <ide> } <ide> <ide> @Test <del> void handlerGenerateRuntimeHintsForProxy() { <add> void handlerGeneratedClassCreatesRuntimeHintsForProxy() { <ide> String className = "com.example.Test$$SpringCGLIB$$0"; <del> this.handler.accept(className, TEST_CONTENT); <add> this.handler.handleGeneratedClass(className, TEST_CONTENT); <ide> assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of(className)) <del> .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, <del> MemberCategory.INVOKE_DECLARED_METHODS, MemberCategory.DECLARED_FIELDS)) <add> .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)) <ide> .accepts(this.generationContext.getRuntimeHints()); <ide> } <ide> <ide> @Test <del> void handlerGenerateRuntimeHintsForTargetType() { <del> String className = "com.example.Test$$SpringCGLIB$$0"; <del> this.handler.accept(className, TEST_CONTENT); <del> assertThat(RuntimeHintsPredicates.reflection().onType(TypeReference.of("com.example.Test")) <del> .withMemberCategories(MemberCategory.INTROSPECT_DECLARED_CONSTRUCTORS, <del> MemberCategory.INVOKE_DECLARED_METHODS)) <add> void handlerLoadedClassCreatesRuntimeHintsForProxy() { <add> this.handler.handleLoadedClass(CglibClassHandler.class); <add> assertThat(RuntimeHintsPredicates.reflection().onType(CglibClassHandler.class) <add> .withMemberCategories(MemberCategory.INVOKE_DECLARED_CONSTRUCTORS)) <ide> .accepts(this.generationContext.getRuntimeHints()); <ide> } <ide> <del> @Test <del> void handlerFailsWithInvalidProxyClassName() { <del> String className = "com.example.Test$$AnotherProxy$$0"; <del> assertThatIllegalArgumentException().isThrownBy(() -> this.handler.accept(className, TEST_CONTENT)) <del> .withMessageContaining("Failed to extract target type"); <del> } <del> <ide> @Test <ide> void handlerRegisterGeneratedClass() throws IOException { <ide> String className = "com.example.Test$$SpringCGLIB$$0"; <del> this.handler.accept(className, TEST_CONTENT); <add> this.handler.handleGeneratedClass(className, TEST_CONTENT); <ide> InMemoryGeneratedFiles generatedFiles = this.generationContext.getGeneratedFiles(); <ide> assertThat(generatedFiles.getGeneratedFiles(Kind.SOURCE)).isEmpty(); <ide> assertThat(generatedFiles.getGeneratedFiles(Kind.RESOURCE)).isEmpty(); <ide><path>spring-context/src/testFixtures/java/org/springframework/context/testfixture/context/annotation/LambdaBeanConfiguration.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.context.testfixture.context.annotation; <add> <add>import org.springframework.beans.factory.config.BeanFactoryPostProcessor; <add>import org.springframework.context.annotation.Bean; <add>import org.springframework.context.annotation.Configuration; <add> <add>@Configuration(proxyBeanMethods = false) <add>public class LambdaBeanConfiguration { <add> <add> @Bean <add> public static BeanFactoryPostProcessor lambaBean() { <add> return beanFactory -> {}; <add> } <add> <add>}
7
Go
Go
avoid cancellation with forked pull context
d8d71ad5b94d44a2778f2d8989424259cac94e9b
<ide><path>daemon/cluster/executor/container/controller.go <ide> type controller struct { <ide> adapter *containerAdapter <ide> closed chan struct{} <ide> err error <add> <add> pulled chan struct{} // closed after pull <add> cancelPull func() // cancels pull context if not nil <add> pullErr error // pull error, only read after pulled closed <ide> } <ide> <ide> var _ exec.Controller = &controller{} <ide> func (r *controller) Prepare(ctx context.Context) error { <ide> } <ide> <ide> if os.Getenv("DOCKER_SERVICE_PREFER_OFFLINE_IMAGE") != "1" { <del> if err := r.adapter.pullImage(ctx); err != nil { <del> cause := errors.Cause(err) <del> if cause == context.Canceled || cause == context.DeadlineExceeded { <del> return err <del> } <add> if r.pulled == nil { <add> // Fork the pull to a different context to allow pull to continue <add> // on re-entrant calls to Prepare. This ensures that Prepare can be <add> // idempotent and not incur the extra cost of pulling when <add> // cancelled on updates. <add> var pctx context.Context <add> <add> r.pulled = make(chan struct{}) <add> pctx, r.cancelPull = context.WithCancel(context.Background()) // TODO(stevvooe): Bind a context to the entire controller. <add> <add> go func() { <add> defer close(r.pulled) <add> r.pullErr = r.adapter.pullImage(pctx) // protected by closing r.pulled <add> }() <add> } <ide> <del> // NOTE(stevvooe): We always try to pull the image to make sure we have <del> // the most up to date version. This will return an error, but we only <del> // log it. If the image truly doesn't exist, the create below will <del> // error out. <del> // <del> // This gives us some nice behavior where we use up to date versions of <del> // mutable tags, but will still run if the old image is available but a <del> // registry is down. <del> // <del> // If you don't want this behavior, lock down your image to an <del> // immutable tag or digest. <del> log.G(ctx).WithError(err).Error("pulling image failed") <add> select { <add> case <-ctx.Done(): <add> return ctx.Err() <add> case <-r.pulled: <add> if r.pullErr != nil { <add> // NOTE(stevvooe): We always try to pull the image to make sure we have <add> // the most up to date version. This will return an error, but we only <add> // log it. If the image truly doesn't exist, the create below will <add> // error out. <add> // <add> // This gives us some nice behavior where we use up to date versions of <add> // mutable tags, but will still run if the old image is available but a <add> // registry is down. <add> // <add> // If you don't want this behavior, lock down your image to an <add> // immutable tag or digest. <add> log.G(ctx).WithError(r.pullErr).Error("pulling image failed") <add> } <ide> } <ide> } <ide> <ide> func (r *controller) Shutdown(ctx context.Context) error { <ide> return err <ide> } <ide> <add> if r.cancelPull != nil { <add> r.cancelPull() <add> } <add> <ide> if err := r.adapter.shutdown(ctx); err != nil { <ide> if isUnknownContainer(err) || isStoppedContainer(err) { <ide> return nil <ide> func (r *controller) Terminate(ctx context.Context) error { <ide> return err <ide> } <ide> <add> if r.cancelPull != nil { <add> r.cancelPull() <add> } <add> <ide> if err := r.adapter.terminate(ctx); err != nil { <ide> if isUnknownContainer(err) { <ide> return nil <ide> func (r *controller) Remove(ctx context.Context) error { <ide> return err <ide> } <ide> <add> if r.cancelPull != nil { <add> r.cancelPull() <add> } <add> <ide> // It may be necessary to shut down the task before removing it. <ide> if err := r.Shutdown(ctx); err != nil { <ide> if isUnknownContainer(err) { <ide> func (r *controller) Close() error { <ide> case <-r.closed: <ide> return r.err <ide> default: <add> if r.cancelPull != nil { <add> r.cancelPull() <add> } <add> <ide> r.err = exec.ErrControllerClosed <ide> close(r.closed) <ide> }
1
Javascript
Javascript
use containslocation() for url handler processing
2a2ef17d85f9336799c3e39249f960f75cac7cf6
<ide><path>src/core-uri-handlers.js <add>const fs = require('fs-plus') <add> <ide> // Converts a query string parameter for a line or column number <ide> // to a zero-based line or column number for the Atom API. <ide> function getLineColNumber (numStr) { <ide> function openFile (atom, {query}) { <ide> <ide> function windowShouldOpenFile ({query}) { <ide> const {filename} = query <del> return (win) => win.containsPath(filename) <add> const stat = fs.statSyncNoException(filename) <add> <add> return win => win.containsLocation({ <add> pathToOpen: filename, <add> exists: Boolean(stat), <add> isFile: stat.isFile(), <add> isDirectory: stat.isDirectory() <add> }) <ide> } <ide> <ide> const ROUTER = { <ide> module.exports = { <ide> if (config && config.getWindowPredicate) { <ide> return config.getWindowPredicate(parsed) <ide> } else { <del> return (win) => true <add> return () => true <ide> } <ide> } <ide> }
1
Javascript
Javascript
remove unused properties from reactmount
b8ad5a23c68743052084f32cb639a66a809f012d
<ide><path>src/browser/ui/ReactMount.js <ide> function findDeepestCachedAncestor(targetID) { <ide> * Inside of `container`, the first element rendered is the "reactRoot". <ide> */ <ide> var ReactMount = { <del> /** Time spent generating markup. */ <del> totalInstantiationTime: 0, <del> <del> /** Time spent inserting markup into the DOM. */ <del> totalInjectionTime: 0, <del> <del> /** Whether support for touch events should be initialized. */ <del> useTouchEvents: false, <del> <ide> /** Exposed for debugging purposes **/ <ide> _instancesByReactRootID: instancesByReactRootID, <ide>
1
Python
Python
fix momentum and epsilon values
4dd784c32f76fb8285f205b94e2a6ebde731a1cd
<ide><path>src/transformers/models/data2vec/modeling_tf_data2vec_vision.py <ide> def __init__( <ide> dilation_rate=dilation, <ide> name="conv", <ide> ) <del> self.bn = tf.keras.layers.BatchNormalization(name="bn") <add> self.bn = tf.keras.layers.BatchNormalization(name="bn", momentum=0.9, epsilon=1e-5) <ide> self.activation = tf.nn.relu <ide> <ide> def call(self, input: tf.Tensor) -> tf.Tensor: <ide> def __init__(self, config: Data2VecVisionConfig, *inputs, **kwargs) -> None: <ide> # FPNs <ide> self.fpn1 = [ <ide> tf.keras.layers.Conv2DTranspose(config.hidden_size, kernel_size=2, strides=2, name="fpn1.0"), <del> tf.keras.layers.BatchNormalization(name="fpn1.1"), <add> tf.keras.layers.BatchNormalization(name="fpn1.1", momentum=0.9, epsilon=1e-5), <ide> tf.keras.layers.Activation("gelu"), <ide> tf.keras.layers.Conv2DTranspose(config.hidden_size, kernel_size=2, strides=2, name="fpn1.3"), <ide> ] <ide><path>src/transformers/models/groupvit/modeling_tf_groupvit.py <ide> def __init__(self, config: GroupViTConfig, **kwargs): <ide> <ide> self.visual_projection = [ <ide> tf.keras.layers.Dense(self.projection_intermediate_dim, name="visual_projection.0"), <del> tf.keras.layers.BatchNormalization(name="visual_projection.1", momentum=0.1, epsilon=1e-5), <add> tf.keras.layers.BatchNormalization(name="visual_projection.1", momentum=0.9, epsilon=1e-5), <ide> tf.keras.layers.ReLU(name="visual_projection.2"), <ide> tf.keras.layers.Dense(self.projection_dim, name="visual_projection.3"), <ide> ] <ide> self.text_projection = [ <ide> tf.keras.layers.Dense(self.projection_intermediate_dim, name="text_projection.0"), <del> tf.keras.layers.BatchNormalization(name="text_projection.1", momentum=0.1, epsilon=1e-5), <add> tf.keras.layers.BatchNormalization(name="text_projection.1", momentum=0.9, epsilon=1e-5), <ide> tf.keras.layers.ReLU(name="text_projection.2"), <ide> tf.keras.layers.Dense(self.projection_dim, name="text_projection.3"), <ide> ] <ide><path>src/transformers/models/regnet/modeling_tf_regnet.py <ide> def __init__( <ide> use_bias=False, <ide> name="convolution", <ide> ) <del> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.1, name="normalization") <add> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="normalization") <ide> self.activation = ACT2FN[activation] if activation is not None else tf.identity <ide> <ide> def call(self, hidden_state): <ide> def __init__(self, out_channels: int, stride: int = 2, **kwargs): <ide> self.convolution = tf.keras.layers.Conv2D( <ide> filters=out_channels, kernel_size=1, strides=stride, use_bias=False, name="convolution" <ide> ) <del> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.1, name="normalization") <add> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="normalization") <ide> <ide> def call(self, inputs: tf.Tensor, training: bool = False) -> tf.Tensor: <ide> return self.normalization(self.convolution(inputs), training=training) <ide><path>src/transformers/models/resnet/modeling_tf_resnet.py <ide> def __init__( <ide> out_channels, kernel_size=kernel_size, strides=stride, padding="valid", use_bias=False, name="convolution" <ide> ) <ide> # Use same default momentum and epsilon as PyTorch equivalent <del> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.1, name="normalization") <add> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="normalization") <ide> self.activation = ACT2FN[activation] if activation is not None else tf.keras.layers.Activation("linear") <ide> <ide> def convolution(self, hidden_state: tf.Tensor) -> tf.Tensor: <ide> def __init__(self, out_channels: int, stride: int = 2, **kwargs) -> None: <ide> out_channels, kernel_size=1, strides=stride, use_bias=False, name="convolution" <ide> ) <ide> # Use same default momentum and epsilon as PyTorch equivalent <del> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.1, name="normalization") <add> self.normalization = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="normalization") <ide> <ide> def call(self, x: tf.Tensor, training: bool = False) -> tf.Tensor: <ide> hidden_state = x <ide><path>src/transformers/models/segformer/modeling_tf_segformer.py <ide> def __init__(self, config: SegformerConfig, **kwargs): <ide> self.linear_fuse = tf.keras.layers.Conv2D( <ide> filters=config.decoder_hidden_size, kernel_size=1, use_bias=False, name="linear_fuse" <ide> ) <del> self.batch_norm = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.1, name="batch_norm") <add> self.batch_norm = tf.keras.layers.BatchNormalization(epsilon=1e-5, momentum=0.9, name="batch_norm") <ide> self.activation = tf.keras.layers.Activation("relu") <ide> <ide> self.dropout = tf.keras.layers.Dropout(config.classifier_dropout_prob)
5
Ruby
Ruby
display invalid value in error
efae65d005ee298207d720fb4f61c28a38973e8e
<ide><path>activerecord/lib/active_record/core.rb <ide> def strict_loading? <ide> # => #<ActiveRecord::Associations::CollectionProxy> <ide> def strict_loading!(value = true, mode: :all) <ide> unless [:all, :n_plus_one_only].include?(mode) <del> raise ArgumentError, "The :mode option must be one of [:all, :n_plus_one_only]." <add> raise ArgumentError, "The :mode option must be one of [:all, :n_plus_one_only] but #{mode.inspect} was provided." <ide> end <ide> <ide> @strict_loading_mode = mode
1
Java
Java
implement equality for redablenativearray
a8703fe10bfeefcf07f44733986a602a3bc6ad4d
<ide><path>ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java <ide> public int getInt(int index) { <ide> return DynamicFromArray.create(this, index); <ide> } <ide> <add> @Override <add> public int hashCode() { <add> return getLocalArray().hashCode(); <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> if (!(obj instanceof ReadableNativeArray)) { <add> return false; <add> } <add> ReadableNativeArray other = (ReadableNativeArray) obj; <add> return Arrays.deepEquals(getLocalArray(), other.getLocalArray()); <add> } <add> <ide> @Override <ide> public @Nonnull ArrayList<Object> toArrayList() { <ide> ArrayList<Object> arrayList = new ArrayList<>();
1
Text
Text
add the way to specify number of decimal places
be96a8808fa7d8a550448bd96bcbe73583dc6c2b
<ide><path>guide/chinese/c/format-specifiers/index.md <ide> int main() { float a = 0.0; scanf(“%f”,&a); //输入是45.65 p <ide> <ide> 字符串输入:%s <ide> <add>可以设定要放多少个小数点: <add>%.2f 代表只会显示两个小数点。 <add>但只可以放在 printf()里,不能在scanf()里。 <add> <ide> # 包括 <ide> <ide> int main() { char str \[20\]; scanf(“%s”,str); //输入是nitesh printf(“%s \\ n”,str); 返回0; } <ide> int main() { char ch; scanf(“%c”,&ch); //输入是A. printf( <ide> <ide> 您可以在ANSI C中使用的%说明符是: <ide> <del>|说明符|用于| |:-------------:|:-------------:| | %c |单个字符| | %s |一个字符串| |成喜|短(签字)| |胡锦涛%|短(无符号)| | %的Lf |长双| | %n |什么都不打印| | %d |十进制整数| | %o |八进制(基数为8)整数| | %x |十六进制(基数为16)的整数| | %p |地址(或指针)| | %f |浮点数的浮点数 | %u | int无符号小数| | %e |科学记数法中的浮点数| | %E |科学记数法中的浮点数| | %% | %符号! | <ide>\ No newline at end of file <add>|说明符|用于| |:-------------:|:-------------:| | %c |单个字符| | %s |一个字符串| |成喜|短(签字)| |胡锦涛%|短(无符号)| | %的Lf |长双| | %n |什么都不打印| | %d |十进制整数| | %o |八进制(基数为8)整数| | %x |十六进制(基数为16)的整数| | %p |地址(或指针)| | %f |浮点数的浮点数 | %u | int无符号小数| | %e |科学记数法中的浮点数| | %E |科学记数法中的浮点数| | %% | %符号! |
1
Ruby
Ruby
put lib back on the autoload path
02a5842cd09bd75de4c2fdb6b474c6c0ff163ebf
<ide><path>railties/lib/rails/engine/configuration.rb <ide> def paths <ide> paths.app.models "app/models", :eager_load => true <ide> paths.app.mailers "app/mailers", :eager_load => true <ide> paths.app.views "app/views" <del> paths.lib "lib", :load_path => true <add> paths.lib "lib", :eager_load => true <ide> paths.lib.tasks "lib/tasks", :glob => "**/*.rake" <ide> paths.config "config" <ide> paths.config.initializers "config/initializers", :glob => "**/*.rb"
1
Javascript
Javascript
update imports in ember-debug package tests
d0cdb8030024f27453b598963350481bb7fe79a2
<ide><path>packages/ember-debug/tests/handlers-test.js <ide> import { <ide> HANDLERS, <ide> registerHandler, <ide> invoke <del>} from 'ember-debug/handlers'; <add>} from '../handlers'; <ide> <ide> QUnit.module('ember-debug/handlers', { <ide> teardown() { <ide><path>packages/ember-debug/tests/main_test.js <ide> import { ENV } from 'ember-environment'; <del>import EmberObject from 'ember-runtime/system/object'; <del>import { HANDLERS } from 'ember-debug/handlers'; <add>import { Object as EmberObject } from 'ember-runtime'; <add>import { HANDLERS } from '../handlers'; <ide> import { <ide> registerHandler, <ide> missingOptionsDeprecation, <ide> missingOptionsIdDeprecation, <ide> missingOptionsUntilDeprecation <del>} from 'ember-debug/deprecate'; <add>} from '../deprecate'; <ide> <ide> import { <ide> missingOptionsIdDeprecation as missingWarnOptionsIdDeprecation, <ide> missingOptionsDeprecation as missingWarnOptionsDeprecation, <ide> registerHandler as registerWarnHandler <del>} from 'ember-debug/warn'; <add>} from '../warn'; <ide> <ide> import { <ide> deprecate, <ide> warn, <ide> assert as emberAssert <del>} from 'ember-metal/debug'; <add>} from 'ember-metal'; <ide> <ide> let originalEnvValue; <ide> let originalDeprecateHandler; <ide><path>packages/ember-debug/tests/warn_if_using_stripped_feature_flags_test.js <ide> import { ENV } from 'ember-environment'; <del>import { getDebugFunction, setDebugFunction } from 'ember-metal/debug'; <del>import { _warnIfUsingStrippedFeatureFlags } from 'ember-debug'; <add>import { getDebugFunction, setDebugFunction } from 'ember-metal'; <add>import { _warnIfUsingStrippedFeatureFlags } from '../index'; <ide> <ide> let oldWarn, oldRunInDebug, origEnvFeatures, origEnableOptional, features, knownFeatures; <ide>
3
Python
Python
fix some relative imports for extension modules
35523ead5c998abc1c9d64baab860d555d22e6c1
<ide><path>tools/py3tool.py <ide> def getenv(): <ide> # Run nosetests <ide> subprocess.call(['nosetests3', '-v', d], cwd=TEMP) <ide> <add>def custom_mangling(filename): <add> import_mangling = [ <add> os.path.join('core', '__init__.py'), <add> os.path.join('core', 'numeric.py'), <add> os.path.join('core', '_internal.py'), <add> os.path.join('core', 'arrayprint.py'), <add> os.path.join('core', 'fromnumeric.py'), <add> os.path.join('numpy', '__init__.py'), <add> os.path.join('lib', 'io.py'), <add> os.path.join('lib', 'function_base.py'), <add> os.path.join('fft', 'fftpack.py'), <add> os.path.join('random', '__init__.py'), <add> ] <add> <add> if any(filename.endswith(x) for x in import_mangling): <add> f = open(filename, 'r') <add> text = f.read() <add> f.close() <add> for mod in ['multiarray', 'scalarmath', 'umath', '_sort', <add> '_compiled_base', 'core', 'lib', 'testing', 'fft', <add> 'polynomial', 'random', 'ma', 'linalg', 'compat', <add> 'mtrand']: <add> text = re.sub(r'^(\s*)import %s' % mod, <add> r'\1from . import %s' % mod, <add> text, flags=re.M) <add> text = re.sub(r'^(\s*)from %s import' % mod, <add> r'\1from .%s import' % mod, <add> text, flags=re.M) <add> text = text.replace('from matrixlib', 'from .matrixlib') <add> f = open(filename, 'w') <add> f.write(text) <add> f.close() <add> <add> if filename.endswith(os.path.join('lib', 'io.py')): <add> f = open(filename, 'r') <add> text = f.read() <add> f.close() <add> text = text.replace('from . import io', 'import io') <add> f = open(filename, 'w') <add> f.write(text) <add> f.close() <add> <ide> def walk_sync(dir1, dir2, _seen=None): <ide> if _seen is None: <ide> seen = {} <ide> def sync_2to3(src, dst, patchfile=None, clean=False): <ide> subprocess.call(['2to3', '-w'] + to_convert, stdout=p) <ide> if scripts: <ide> subprocess.call(['2to3', '-w', '-x', 'import'] + scripts, stdout=p) <add> <add> for fn in to_convert + scripts: <add> # perform custom mangling <add> custom_mangling(fn) <add> <ide> p.close() <ide> <ide> if __name__ == "__main__":
1
PHP
PHP
fix a long line
29031cb70a60932e40b317ad4c9e693b82564afc
<ide><path>src/Illuminate/Auth/Console/MakeAuthCommand.php <ide> public function fire() <ide> if (! $this->option('views')) { <ide> $this->info('Installed HomeController.'); <ide> <del> copy(__DIR__.'/stubs/make/controllers/HomeController.stub', app_path('Http/Controllers/HomeController.php')); <add> copy( <add> __DIR__.'/stubs/make/controllers/HomeController.stub', <add> app_path('Http/Controllers/HomeController.php') <add> ); <ide> <ide> $this->info('Updated Routes File.'); <ide>
1
PHP
PHP
move session assertions
fb644538937e91b922135161355d7466600f7a03
<ide><path>src/Illuminate/Foundation/Testing/InteractsWithSession.php <ide> public function flushSession() <ide> <ide> $this->app['session']->flush(); <ide> } <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 seeInSession($key, $value = null) <add> { <add> $this->assertSessionHas($key, $value); <add> <add> return $this; <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)) { <add> return $this->assertSessionHasAll($key); <add> } <add> <add> if (is_null($value)) { <add> PHPUnit::assertTrue($this->app['session.store']->has($key), "Session missing key: $key"); <add> } else { <add> PHPUnit::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> if (is_int($key)) { <add> $this->assertSessionHas($value); <add> } else { <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 = [], $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> if (is_int($key)) { <add> PHPUnit::assertTrue($errors->has($value), "Session missing error: $value"); <add> } else { <add> PHPUnit::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><path>src/Illuminate/Foundation/Testing/MakesHttpRequests.php <ide> public function assertRedirectedToAction($name, $parameters = [], $with = []) <ide> $this->assertRedirectedTo($this->app['url']->action($name, $parameters), $with); <ide> } <ide> <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 seeInSession($key, $value = null) <del> { <del> $this->assertSessionHas($key, $value); <del> <del> return $this; <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)) { <del> return $this->assertSessionHasAll($key); <del> } <del> <del> if (is_null($value)) { <del> PHPUnit::assertTrue($this->app['session.store']->has($key), "Session missing key: $key"); <del> } else { <del> PHPUnit::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> if (is_int($key)) { <del> $this->assertSessionHas($value); <del> } else { <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 = [], $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> if (is_int($key)) { <del> PHPUnit::assertTrue($errors->has($value), "Session missing error: $value"); <del> } else { <del> PHPUnit::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> } <del> <ide> /** <ide> * Dump the content from the last response. <ide> *
2
Python
Python
define the `urlpatterns` as a list of `url()...
bfd7219352213c47299dd560b302c88f87825769
<ide><path>tests/browsable_api/auth_urls.py <ide> <ide> <ide> urlpatterns = [ <del> (r'^$', MockView.as_view()), <add> url(r'^$', MockView.as_view()), <ide> url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), <ide> ] <ide><path>tests/browsable_api/no_auth_urls.py <ide> from __future__ import unicode_literals <ide> <add>from django.conf.urls import url <ide> from .views import MockView <ide> <ide> urlpatterns = [ <del> (r'^$', MockView.as_view()), <add> url(r'^$', MockView.as_view()), <ide> ] <ide><path>tests/test_authentication.py <ide> def put(self, request): <ide> <ide> <ide> urlpatterns = [ <del> (r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])), <del> (r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])), <del> (r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])), <del> (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'), <del> url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')) <add> url(r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])), <add> url(r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])), <add> url(r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])), <add> url(r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'), <add> url(r'^auth/', include('rest_framework.urls', namespace='rest_framework')), <ide> ] <ide> <ide> <ide><path>tests/test_request.py <ide> Tests for content parsing, and form-overloaded content parsing. <ide> """ <ide> from __future__ import unicode_literals <add>from django.conf.urls import url <ide> from django.contrib.auth.models import User <ide> from django.contrib.auth import authenticate, login, logout <ide> from django.contrib.sessions.middleware import SessionMiddleware <ide> def post(self, request): <ide> return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR) <ide> <ide> urlpatterns = [ <del> (r'^$', MockView.as_view()), <add> url(r'^$', MockView.as_view()), <ide> ] <ide> <ide>
4
Go
Go
add more error details on plugin get
b1a3fe49341bec714c1017067bd17d9052e5a2d6
<ide><path>pkg/plugins/plugins.go <ide> package plugins // import "github.com/docker/docker/pkg/plugins" <ide> <ide> import ( <ide> "errors" <add> "fmt" <ide> "sync" <ide> "time" <ide> <ide> func Get(name, imp string) (*Plugin, error) { <ide> logrus.Debugf("%s implements: %s", name, imp) <ide> return pl, nil <ide> } <del> return nil, ErrNotImplements <add> return nil, fmt.Errorf("%w: plugin=%q, requested implementation=%q", ErrNotImplements, name, imp) <ide> } <ide> <ide> // Handle adds the specified function to the extpointHandlers.
1
Javascript
Javascript
replace bluebird with promise
fccea2f365983bbd05bc24c7960dbbb31bf26775
<ide><path>packager/react-packager/__mocks__/bluebird.js <del>'use strict'; <del> <del>jest.autoMockOff(); <del>module.exports = require.requireActual('bluebird'); <del>jest.autoMockOn(); <ide><path>packager/react-packager/src/AssetServer/__tests__/AssetServer-test.js <ide> jest <ide> .mock('crypto') <ide> .mock('fs'); <ide> <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> <ide> describe('AssetServer', function() { <ide> var AssetServer; <ide><path>packager/react-packager/src/AssetServer/index.js <ide> var declareOpts = require('../lib/declareOpts'); <ide> var getAssetDataFromName = require('../lib/getAssetDataFromName'); <ide> var path = require('path'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> var fs = require('fs'); <ide> var crypto = require('crypto'); <ide> <del>var stat = Promise.promisify(fs.stat); <del>var readDir = Promise.promisify(fs.readdir); <del>var readFile = Promise.promisify(fs.readFile); <add>var stat = Promise.denodeify(fs.stat); <add>var readDir = Promise.denodeify(fs.readdir); <add>var readFile = Promise.denodeify(fs.readFile); <ide> <ide> module.exports = AssetServer; <ide> <ide> AssetServer.prototype._getAssetRecord = function(assetPath) { <ide> this._roots, <ide> path.dirname(assetPath) <ide> ).then(function(dir) { <del> return [ <add> return Promise.all([ <ide> dir, <ide> readDir(dir), <del> ]; <del> }).spread(function(dir, files) { <add> ]); <add> }).then(function(res) { <add> var dir = res[0]; <add> var files = res[1]; <ide> var assetData = getAssetDataFromName(filename); <add> <ide> var map = buildAssetMap(dir, files); <ide> var record = map[assetData.assetName]; <ide> <ide> AssetServer.prototype.getAssetData = function(assetPath) { <ide> }; <ide> <ide> function findRoot(roots, dir) { <del> return Promise.some( <add> return Promise.all( <ide> roots.map(function(root) { <ide> var absPath = path.join(root, dir); <ide> return stat(absPath).then(function(fstat) { <del> if (!fstat.isDirectory()) { <del> throw new Error('Looking for dirs'); <del> } <del> fstat._path = absPath; <del> return fstat; <add> return {path: absPath, isDirectory: fstat.isDirectory()}; <add> }, function (err) { <add> return {path: absPath, isDirectory: false}; <ide> }); <del> }), <del> 1 <del> ).spread( <del> function(fstat) { <del> return fstat._path; <add> }) <add> ).then( <add> function(stats) { <add> for (var i = 0; i < stats.length; i++) { <add> if (stats[i].isDirectory) { <add> return stats[i].path; <add> } <add> } <add> throw new Error('Could not find any directories'); <ide> } <ide> ); <ide> } <ide><path>packager/react-packager/src/DependencyResolver/AssetModule.js <ide> 'use strict'; <ide> <ide> const Module = require('./Module'); <del>const Promise = require('bluebird'); <add>const Promise = require('promise'); <ide> const getAssetDataFromName = require('../lib/getAssetDataFromName'); <ide> <ide> class AssetModule extends Module { <ide><path>packager/react-packager/src/DependencyResolver/AssetModule_DEPRECATED.js <ide> 'use strict'; <ide> <ide> const Module = require('./Module'); <del>const Promise = require('bluebird'); <add>const Promise = require('promise'); <ide> const getAssetDataFromName = require('../lib/getAssetDataFromName'); <ide> <ide> class AssetModule_DEPRECATED extends Module { <ide><path>packager/react-packager/src/DependencyResolver/DependencyGraph/index.js <ide> const isAbsolutePath = require('absolute-path'); <ide> const debug = require('debug')('DependencyGraph'); <ide> const getAssetDataFromName = require('../../lib/getAssetDataFromName'); <ide> const util = require('util'); <del>const Promise = require('bluebird'); <add>const Promise = require('promise'); <ide> const _ = require('underscore'); <ide> <ide> const validateOpts = declareOpts({ <ide><path>packager/react-packager/src/DependencyResolver/Module.js <ide> 'use strict'; <ide> <del>const Promise = require('bluebird'); <add>const Promise = require('promise'); <ide> const docblock = require('./DependencyGraph/docblock'); <ide> const isAbsolutePath = require('absolute-path'); <ide> const path = require('path'); <ide><path>packager/react-packager/src/DependencyResolver/__tests__/HasteDependencyResolver-test.js <ide> jest.dontMock('../') <ide> <ide> jest.mock('path'); <ide> <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> <ide> describe('HasteDependencyResolver', function() { <ide> var HasteDependencyResolver; <ide><path>packager/react-packager/src/DependencyResolver/fastfs.js <ide> 'use strict'; <ide> <del>const Promise = require('bluebird'); <add>const Promise = require('promise'); <ide> const {EventEmitter} = require('events'); <ide> <ide> const _ = require('underscore'); <ide> const debug = require('debug')('DependencyGraph'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> <del>const readDir = Promise.promisify(fs.readdir); <del>const readFile = Promise.promisify(fs.readFile); <del>const stat = Promise.promisify(fs.stat); <add>const readDir = Promise.denodeify(fs.readdir); <add>const readFile = Promise.denodeify(fs.readFile); <add>const stat = Promise.denodeify(fs.stat); <ide> const hasOwn = Object.prototype.hasOwnProperty; <ide> <ide> class Fastfs extends EventEmitter { <ide><path>packager/react-packager/src/DependencyResolver/index.js <ide> var path = require('path'); <ide> var DependencyGraph = require('./DependencyGraph'); <ide> var replacePatterns = require('./replacePatterns'); <ide> var declareOpts = require('../lib/declareOpts'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> <ide> var validateOpts = declareOpts({ <ide> projectRoots: { <ide><path>packager/react-packager/src/FileWatcher/index.js <ide> <ide> var EventEmitter = require('events').EventEmitter; <ide> var sane = require('sane'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> var util = require('util'); <ide> var exec = require('child_process').exec; <ide> <ide> util.inherits(FileWatcher, EventEmitter); <ide> FileWatcher.prototype.end = function() { <ide> return this._loading.then(function(watchers) { <ide> watchers.forEach(function(watcher) { <del> return Promise.promisify(watcher.close, watcher)(); <add> return Promise.denodeify(watcher.close).call(watcher); <ide> }); <ide> }); <ide> }; <ide><path>packager/react-packager/src/JSTransformer/Cache.js <ide> var declareOpts = require('../lib/declareOpts'); <ide> var fs = require('fs'); <ide> var isAbsolutePath = require('absolute-path'); <ide> var path = require('path'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> var tmpdir = require('os').tmpDir(); <ide> var version = require('../../../../package.json').version; <ide> <ide> Cache.prototype.get = function(filepath, loaderCb) { <ide> <ide> Cache.prototype._set = function(filepath, loaderPromise) { <ide> this._data[filepath] = loaderPromise.then(function(data) { <del> return [ <add> return Promise.all([ <ide> data, <del> Promise.promisify(fs.stat)(filepath) <del> ]; <del> }).spread(function(data, stat) { <add> Promise.denodeify(fs.stat)(filepath) <add> ]); <add> }).then(function(ref) { <add> var data = ref[0]; <add> var stat = ref[1]; <ide> this._persistEventually(); <ide> return { <ide> data: data, <ide> Cache.prototype._persistCache = function() { <ide> Object.keys(data).forEach(function(key, i) { <ide> json[key] = values[i]; <ide> }); <del> return Promise.promisify(fs.writeFile)(cacheFilepath, JSON.stringify(json)); <add> return Promise.denodeify(fs.writeFile)(cacheFilepath, JSON.stringify(json)); <ide> }) <ide> .then(function() { <ide> this._persisting = null; <ide><path>packager/react-packager/src/JSTransformer/__tests__/Cache-test.js <ide> jest <ide> .mock('os') <ide> .mock('fs'); <ide> <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> <ide> describe('JSTransformer Cache', function() { <ide> var Cache; <ide><path>packager/react-packager/src/JSTransformer/index.js <ide> 'use strict'; <ide> <ide> var fs = require('fs'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> var Cache = require('./Cache'); <ide> var workerFarm = require('worker-farm'); <ide> var declareOpts = require('../lib/declareOpts'); <ide> var util = require('util'); <ide> var ModuleTransport = require('../lib/ModuleTransport'); <ide> <del>var readFile = Promise.promisify(fs.readFile); <add>var readFile = Promise.denodeify(fs.readFile); <ide> <ide> module.exports = Transformer; <ide> Transformer.TransformError = TransformError; <ide> function Transformer(options) { <ide> options.transformModulePath <ide> ); <ide> <del> this._transform = Promise.promisify(this._workers); <add> this._transform = Promise.denodeify(this._workers); <ide> } <ide> } <ide> <ide><path>packager/react-packager/src/Packager/__tests__/Packager-test.js <ide> jest <ide> <ide> jest.mock('fs'); <ide> <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> <ide> describe('Packager', function() { <ide> var getDependencies; <ide><path>packager/react-packager/src/Packager/index.js <ide> var assert = require('assert'); <ide> var fs = require('fs'); <ide> var path = require('path'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> var Transformer = require('../JSTransformer'); <ide> var DependencyResolver = require('../DependencyResolver'); <ide> var Package = require('./Package'); <ide> var ModuleTransport = require('../lib/ModuleTransport'); <ide> var declareOpts = require('../lib/declareOpts'); <ide> var imageSize = require('image-size'); <ide> <del>var sizeOf = Promise.promisify(imageSize); <del>var readFile = Promise.promisify(fs.readFile); <add>var sizeOf = Promise.denodeify(imageSize); <add>var readFile = Promise.denodeify(fs.readFile); <ide> <ide> var validateOpts = declareOpts({ <ide> projectRoots: { <ide> Packager.prototype.generateAssetModule = function(ppackage, module) { <ide> return Promise.all([ <ide> sizeOf(module.path), <ide> this._assetServer.getAssetData(relPath), <del> ]).spread(function(dimensions, assetData) { <add> ]).then(function(res) { <add> var dimensions = res[0]; <add> var assetData = res[1]; <ide> var img = { <ide> __packager_asset: true, <ide> fileSystemLocation: path.dirname(module.path), <ide><path>packager/react-packager/src/Server/__tests__/Server-test.js <ide> jest.setMock('worker-farm', function() { return function() {}; }) <ide> .setMock('uglify-js') <ide> .dontMock('../'); <ide> <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> <ide> describe('processRequest', function() { <ide> var server; <ide><path>packager/react-packager/src/Server/index.js <ide> var FileWatcher = require('../FileWatcher'); <ide> var Packager = require('../Packager'); <ide> var Activity = require('../Activity'); <ide> var AssetServer = require('../AssetServer'); <del>var Promise = require('bluebird'); <add>var Promise = require('promise'); <ide> var _ = require('underscore'); <ide> var exec = require('child_process').exec; <ide> var fs = require('fs');
18
Text
Text
fix mdn links to avoid redirections
259f62a8e8d4eac2f067b205abc9264b946d6738
<ide><path>doc/api/assert.md <ide> second argument. This might lead to difficult-to-spot errors. <ide> <ide> [`Error.captureStackTrace`]: errors.html#errors_error_capturestacktrace_targetobject_constructoropt <ide> [`Error`]: errors.html#errors_class_error <del>[`Map`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map <add>[`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map <ide> [`Object.is()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is <ide> [`RegExp`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions <del>[`Set`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set <del>[`Symbol`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Symbol <add>[`Set`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set <add>[`Symbol`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol <ide> [`TypeError`]: errors.html#errors_class_typeerror <del>[`WeakMap`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/WeakMap <del>[`WeakSet`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/WeakSet <add>[`WeakMap`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap <add>[`WeakSet`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet <ide> [`assert.deepEqual()`]: #assert_assert_deepequal_actual_expected_message <ide> [`assert.deepStrictEqual()`]: #assert_assert_deepstrictequal_actual_expected_message <ide> [`assert.notDeepStrictEqual()`]: #assert_assert_notdeepstrictequal_actual_expected_message <ide><path>doc/api/fs.md <ide> The following constants are meant for use with the [`fs.Stats`][] object's <ide> [Caveats]: #fs_caveats <ide> [Common System Errors]: errors.html#errors_common_system_errors <ide> [FS Constants]: #fs_fs_constants_1 <del>[MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date <add>[MDN-Date]: https://developer.mozilla.org/en-US/JavaScript/Reference/Global_Objects/Date <ide> [MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type <ide> [MSDN-Rel-Path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#fully_qualified_vs._relative_paths <ide> [Readable Streams]: stream.html#stream_class_stream_readable <ide><path>doc/api/intl.md <ide> to be helpful: <ide> <ide> ["ICU Data"]: http://userguide.icu-project.org/icudata <ide> [`--icu-data-dir`]: cli.html#cli_icu_data_dir_file <del>[`Date.prototype.toLocaleString()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString <del>[`Intl`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Intl <add>[`Date.prototype.toLocaleString()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString <add>[`Intl`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl <ide> [`Intl.DateTimeFormat`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat <ide> [`NODE_ICU_DATA`]: cli.html#cli_node_icu_data_file <del>[`Number.prototype.toLocaleString()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString <add>[`Number.prototype.toLocaleString()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString <ide> [`require('buffer').transcode()`]: buffer.html#buffer_buffer_transcode_source_fromenc_toenc <ide> [`require('util').TextDecoder`]: util.html#util_class_util_textdecoder <del>[`String.prototype.localeCompare()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare <del>[`String.prototype.normalize()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/normalize <del>[`String.prototype.toLowerCase()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase <del>[`String.prototype.toUpperCase()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase <add>[`String.prototype.localeCompare()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare <add>[`String.prototype.normalize()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize <add>[`String.prototype.toLowerCase()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase <add>[`String.prototype.toUpperCase()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase <ide> [BUILDING.md]: https://github.com/nodejs/node/blob/master/BUILDING.md <ide> [BUILDING.md#full-icu]: https://github.com/nodejs/node/blob/master/BUILDING.md#build-with-full-icu-support-all-locales-supported-by-icu <ide> [ECMA-262]: https://tc39.github.io/ecma262/ <ide><path>doc/api/url.md <ide> console.log(myURL.origin); <ide> ``` <ide> <ide> [`Error`]: errors.html#errors_class_error <del>[`JSON.stringify()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify <add>[`JSON.stringify()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify <ide> [`Map`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map <ide> [`TypeError`]: errors.html#errors_class_typeerror <ide> [`URLSearchParams`]: #url_class_urlsearchparams <ide><path>doc/api/util.md <ide> Deprecated predecessor of `console.log`. <ide> [`Array.isArray`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray <ide> [`Buffer.isBuffer()`]: buffer.html#buffer_class_method_buffer_isbuffer_obj <ide> [`Error`]: errors.html#errors_class_error <del>[`Object.assign()`]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign <add>[`Object.assign()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign <ide> [`assert.deepStrictEqual()`]: assert.html#assert_assert_deepstrictequal_actual_expected_message <ide> [`console.error()`]: console.html#console_console_error_data_args <ide> [`console.log()`]: console.html#console_console_log_data_args <ide> Deprecated predecessor of `console.log`. <ide> [Internationalization]: intl.html <ide> [WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/ <ide> [Common System Errors]: errors.html#errors_common_system_errors <del>[constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor <add>[constructor]: https://developer.mozilla.org/en-US/JavaScript/Reference/Global_Objects/Object/constructor <ide> [list of deprecated APIS]: deprecations.html#deprecations_list_of_deprecated_apis <ide> [semantically incompatible]: https://github.com/nodejs/node/issues/4179
5
Javascript
Javascript
add yeti smart home to the list of showcase apps
81193eba07bbaf438fd508e24a7a893ebbdecc30
<ide><path>website/src/react-native/showcase.js <ide> var featured = [ <ide> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.deliverycom&hl=en', <ide> infoLink: 'https://medium.com/delivery-com-engineering/react-native-in-an-existing-ios-app-delivered-874ba95a3c52#.37qruw6ck', <ide> infoTitle: 'React Native in an Existing iOS App: Getting Started' <del> }, <add> }, <add> { <add> name: 'Yeti Smart Home', <add> icon: 'https://res.cloudinary.com/netbeast/image/upload/v1484303676/Android_192_loykto.png', <add> linkPlayStore: 'https://play.google.com/store/apps/details?id=com.netbeast.yeti', <add> infoLink: 'https://medium.com/@jesusdario/developing-beyond-the-screen-9af812b96724#.ozx0xy4lv', <add> infoTitle: 'How react native is helping us to reinvent the wheel, smart homes and release Yeti.', <add> }, <ide> ]; <ide> <ide> /*
1
Text
Text
add new solution version that directly returns
271b2c34342618485d674fa9cb041e145ddc6586
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/basic-data-structures/check-for-the-presence-of-an-element-with-indexof/index.md <ide> return arr.indexOf(elem) >= 0 ? true : false; <ide> } <ide> console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms')); <ide> ``` <add>- `Solution-3` demonstrates how the problem can be solved by directly returning result of the comparison. <add> <add>## Solution-3: <add>```javascript <add>function quickCheck(arr, elem) { <add> return arr.indexOf(elem) != -1; <add>} <add>console.log(quickCheck(['squash', 'onions', 'shallots'], 'mushrooms')); <add>```
1
Javascript
Javascript
restore getchar in jpegstream
825f9249b23d247b78ab8eb6fa685c373362e4fa
<ide><path>pdf.js <ide> var JpegStream = (function() { <ide> constructor.prototype = { <ide> getImage: function() { <ide> return this.domImage; <add> }, <add> getChar: function() { <add> error("internal error: getChar is not valid on JpegStream"); <ide> } <ide> }; <ide>
1
Javascript
Javascript
replace var with let/const
0271f1b067be019f67e274802a2c951b29f18ab8
<ide><path>lib/internal/http2/util.js <ide> const IDX_OPTIONS_MAX_SESSION_MEMORY = 8; <ide> const IDX_OPTIONS_FLAGS = 9; <ide> <ide> function updateOptionsBuffer(options) { <del> var flags = 0; <add> let flags = 0; <ide> if (typeof options.maxDeflateDynamicTableSize === 'number') { <ide> flags |= (1 << IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE); <ide> optionsBuffer[IDX_OPTIONS_MAX_DEFLATE_DYNAMIC_TABLE_SIZE] = <ide> function getSettings(session, remote) { <ide> } <ide> <ide> function updateSettingsBuffer(settings) { <del> var flags = 0; <add> let flags = 0; <ide> if (typeof settings.headerTableSize === 'number') { <ide> flags |= (1 << IDX_SETTINGS_HEADER_TABLE_SIZE); <ide> settingsBuffer[IDX_SETTINGS_HEADER_TABLE_SIZE] = <ide> const assertWithinRange = hideStackFrames( <ide> function toHeaderObject(headers) { <ide> const obj = Object.create(null); <ide> for (var n = 0; n < headers.length; n = n + 2) { <del> var name = headers[n]; <del> var value = headers[n + 1]; <add> const name = headers[n]; <add> let value = headers[n + 1]; <ide> if (name === HTTP2_HEADER_STATUS) <ide> value |= 0; <del> var existing = obj[name]; <add> const existing = obj[name]; <ide> if (existing === undefined) { <ide> obj[name] = name === HTTP2_HEADER_SET_COOKIE ? [value] : value; <ide> } else if (!kSingleValueHeaders.has(name)) {
1
Javascript
Javascript
fix typo in template.js
c66289f1fc47a918c08bad8ad5b78d187ea27de5
<ide><path>src/core/xfa/template.js <ide> class Image extends StringObject { <ide> <ide> [$toHTML]() { <ide> if (this.href || !this[$content]) { <del> // TODO: href can be a Name refering to an internal stream <add> // TODO: href can be a Name referring to an internal stream <ide> // containing a picture. <ide> // In general, we don't get remote data and use what we have <ide> // in the pdf itself, so no picture for non null href.
1
Text
Text
update example copyright dates
3ec6c0e42442aaaa2fa68e93fb68bec082dfae95
<ide><path>CONTRIBUTING.md <ide> present in the framework. <ide> <ide> ```java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2017 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> package ...; <ide> ### Update Apache license header in modified files as necessary <ide> <ide> Always check the date range in the license header. For example, if you've <del>modified a file in 2015 whose header still reads: <add>modified a file in 2017 whose header still reads: <ide> <ide> ```java <ide> /* <ide> * Copyright 2002-2011 the original author or authors. <ide> ``` <ide> <del>Then be sure to update it to 2016 accordingly: <add>Then be sure to update it to 2017 accordingly: <ide> <ide> ```java <ide> /* <del> * Copyright 2002-2016 the original author or authors. <add> * Copyright 2002-2017 the original author or authors. <ide> ``` <ide> <ide> ### Use @since tags for newly-added public API types and methods <ide> For example: <ide> * ... <ide> * <ide> * @author First Last <del> * @since 4.2.3 <add> * @since 5.0 <ide> * @see ... <ide> */ <ide> ```
1
Python
Python
fix loading of tagger
45a6f9b9c7ea97cda09bfda33e60e2cab1df7487
<ide><path>spacy/language.py <ide> def create_tokenizer(cls, nlp=None): <ide> def create_tagger(cls, nlp=None): <ide> if nlp is None: <ide> return Tagger(cls.create_vocab(), features=cls.tagger_features) <del> elif nlp.path is None or not (nlp.path / 'ner').exists(): <add> elif nlp.path is None or not (nlp.path / 'pos').exists(): <ide> return Tagger(nlp.vocab, features=cls.tagger_features) <ide> else: <del> return Tagger.load(nlp.path / 'ner', nlp.vocab) <add> return Tagger.load(nlp.path / 'pos', nlp.vocab) <ide> <ide> @classmethod <ide> def create_parser(cls, nlp=None):
1
Python
Python
solve the port conflict
1c76a51615ccd5c8e60570771b29ef16a9c3bc17
<ide><path>tests/deepspeed/test_deepspeed.py <ide> def load_json(path): <ide> return json.load(f) <ide> <ide> <add>def get_master_port(real_launcher=False): <add> """ <add> When using a single gpu launcher emulation (i.e. not deepspeed or python -m torch.distributed) <add> the issue is that once the port is tied it can't be used anywhere else outside of this process, <add> since torch.dist doesn't free the port until the process exits. Therefore for the sake of being <add> able to run both emulated launcher and normal launcher tests we need 2 distinct ports. <add> <add> This function will give the right port in the right context. For real launcher it'll give the <add> base port, for emulated launcher it'll give the base port + 1. In both cases a string is <add> returned. <add> <add> Args: <add> `real_launcher`: whether a real launcher is going to be used, or the emulated one <add> <add> """ <add> <add> master_port_base = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT) <add> if not real_launcher: <add> master_port_base = str(int(master_port_base) + 1) <add> return master_port_base <add> <add> <ide> def require_deepspeed_aio(test_case): <ide> """ <ide> Decorator marking a test that requires deepspeed aio (nvme) <ide> def get_launcher(distributed=False): <ide> # 2. for now testing with just 2 gpus max (since some quality tests may give different <ide> # results with mode gpus because we use very little data) <ide> num_gpus = min(2, get_gpu_count()) if distributed else 1 <del> master_port = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT) <add> master_port = get_master_port(real_launcher=True) <ide> return f"deepspeed --num_nodes 1 --num_gpus {num_gpus} --master_port {master_port}".split() <ide> <ide> <ide> class CoreIntegrationDeepSpeed(TestCasePlus, TrainerIntegrationCommon): <ide> def setUp(self): <ide> super().setUp() <ide> <del> master_port = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT) <add> master_port = get_master_port(real_launcher=False) <ide> self.dist_env_1_gpu = dict( <ide> MASTER_ADDR="localhost", MASTER_PORT=master_port, RANK="0", LOCAL_RANK="0", WORLD_SIZE="1" <ide> ) <ide> def setUp(self): <ide> self.n_epochs = args.num_train_epochs <ide> self.batch_size = args.train_batch_size <ide> <del> master_port = os.environ.get("DS_TEST_PORT", DEFAULT_MASTER_PORT) <add> master_port = get_master_port(real_launcher=False) <ide> self.dist_env_1_gpu = dict( <ide> MASTER_ADDR="localhost", MASTER_PORT=master_port, RANK="0", LOCAL_RANK="0", WORLD_SIZE="1" <ide> )
1
Ruby
Ruby
move header injection back into integration tests
d63b42da362d696398fd371815734cb0caed48df
<ide><path>actionpack/lib/action_controller/testing/integration.rb <ide> def process(method, path, parameters = nil, headers = nil) <ide> opts = { <ide> :method => method.to_s.upcase, <ide> :params => parameters, <del> :headers => headers, <ide> <ide> "SERVER_NAME" => host, <ide> "SERVER_PORT" => (https? ? "443" : "80"), <ide> def process(method, path, parameters = nil, headers = nil) <ide> } <ide> env = ActionDispatch::Test::MockRequest.env_for(@path, opts) <ide> <add> (headers || {}).each do |key, value| <add> key = key.to_s.upcase.gsub(/-/, "_") <add> key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/ <add> env[key] = value <add> end <add> <ide> app = Rack::Lint.new(@app) <ide> status, headers, body = app.call(env) <ide> response = ::Rack::MockResponse.new(status, headers, body) <ide><path>actionpack/lib/action_dispatch/test/mock.rb <ide> class MockRequest < Rack::MockRequest <ide> <ide> class << self <ide> def env_for(path, opts) <del> headers = opts.delete(:headers) <del> <ide> method = (opts[:method] || opts["REQUEST_METHOD"]).to_s.upcase <ide> opts[:method] = opts["REQUEST_METHOD"] = method <ide> <ide> def env_for(path, opts) <ide> uri.query = requestify(params) <ide> end <ide> <del> env = ::Rack::MockRequest.env_for(uri.to_s, opts) <del> <del> (headers || {}).each do |key, value| <del> key = key.to_s.upcase.gsub(/-/, "_") <del> key = "HTTP_#{key}" unless env.has_key?(key) || key =~ /^HTTP_/ <del> env[key] = value <del> end <del> <del> env <add> ::Rack::MockRequest.env_for(uri.to_s, opts) <ide> end <ide> <ide> private
2
Javascript
Javascript
fix typo in internal message event name
c8108aad832b4734a4bc14ab6e2e052218be3990
<ide><path>lib/cluster.js <ide> function Worker(customEnv) { <ide> } <ide> <ide> // Internal message: handle message <del> this.process.on('inernalMessage', function(message, handle) { <add> this.process.on('internalMessage', function(message, handle) { <ide> debug('recived: ', message); <ide> <ide> // relay to handleMessage <ide><path>test/simple/test-child-process-internal.js <ide> if (process.argv[2] === 'child') { <ide> }); <ide> <ide> var gotInternal; <del> child.once('inernalMessage', function(data) { <add> child.once('internalMessage', function(data) { <ide> gotInternal = data; <ide> }); <ide>
2
Python
Python
specify kb_id and kb_url for url visualisation
f4b5c4209d6cb3748534ad072784a3f9c4fa194c
<ide><path>spacy/displacy/render.py <ide> def render_ents( <ide> """Render entities in text. <ide> <ide> text (str): Original text. <del> spans (list): Individual entity spans and their start, end and label. <add> spans (list): Individual entity spans and their start, end, label, kb_id and kb_url. <ide> title (str / None): Document title set in Doc.user_data['title']. <ide> """ <ide> markup = "" <ide> def render_ents( <ide> label = span["label"] <ide> start = span["start"] <ide> end = span["end"] <add> kb_id = str(span.get("kb_id") or "") <add> kb_url = str(span.get("kb_url") or "") <ide> additional_params = span.get("params", {}) <ide> entity = escape_html(text[start:end]) <ide> fragments = text[offset:start].split("\n") <ide> def render_ents( <ide> markup += "</br>" <ide> if self.ents is None or label.upper() in self.ents: <ide> color = self.colors.get(label.upper(), self.default_color) <del> ent_settings = {"label": label, "text": entity, "bg": color} <add> ent_settings = {"label": label, "text": entity, "bg": color, "kb_id": kb_id, "kb_url": kb_url} <ide> ent_settings.update(additional_params) <ide> markup += self.ent_template.format(**ent_settings) <ide> else:
1
Ruby
Ruby
unroll validation loop
8575034f192d0c85bb97c2ad70533c9ed93a60c5
<ide><path>Library/Homebrew/formula.rb <ide> def initialize(name, path, spec) <ide> set_spec :head <ide> <ide> @active_spec = determine_active_spec(spec) <del> validate_attributes :url, :name, :version <add> validate_attributes! <ide> @pkg_version = PkgVersion.new(version, revision) <ide> @build = active_spec.build <ide> @pin = FormulaPin.new(self) <ide> def determine_active_spec(requested) <ide> spec or raise FormulaSpecificationError, "formulae require at least a URL" <ide> end <ide> <del> def validate_attributes(*attrs) <del> attrs.each do |attr| <del> if (value = send(attr).to_s).empty? || value =~ /\s/ <del> raise FormulaValidationError.new(attr, value) <del> end <add> def validate_attributes! <add> if name.nil? || name.empty? || name =~ /\s/ <add> raise FormulaValidationError.new(:name, name) <add> end <add> <add> if url.nil? || url.empty? || url =~ /\s/ <add> raise FormulaValidationError.new(:url, url) <add> end <add> <add> val = version.respond_to?(:to_str) ? version.to_str : version <add> if val.nil? || val.empty? || val =~ /\s/ <add> raise FormulaValidationError.new(:version, val) <ide> end <ide> end <ide> <ide><path>Library/Homebrew/test/test_formula_validation.rb <ide> def test_validates_version <ide> version "" <ide> end <ide> end <add> <add> assert_invalid :version do <add> formula do <add> url "foo" <add> version nil <add> end <add> end <ide> end <ide> <ide> def test_devel_only_valid
2
Javascript
Javascript
increase coverage for fs/dir read
a9c0077493e86b6e2c6ef51a74bdb0b7eb2e87f7
<ide><path>test/parallel/test-fs-opendir.js <ide> async function doConcurrentAsyncAndSyncOps() { <ide> } <ide> doConcurrentAsyncAndSyncOps().then(common.mustCall()); <ide> <add>// Check read throw exceptions on invalid callback <add>{ <add> const dir = fs.opendirSync(testDir); <add> assert.throws(() => dir.read('INVALID_CALLBACK'), /ERR_INVALID_CALLBACK/); <add>} <add> <ide> // Check that concurrent read() operations don't do weird things. <ide> async function doConcurrentAsyncOps() { <ide> const dir = await fs.promises.opendir(testDir);
1
Ruby
Ruby
handle more non-executable curl edge-cases
924865ec7f18078650be87ca31b6c0a434b0a78d
<ide><path>Library/Homebrew/utils/curl.rb <ide> require "open3" <ide> <ide> def curl_executable <del> curl = Pathname.new ENV["HOMEBREW_CURL"] <del> curl = which("curl") unless curl.exist? <del> return curl if curl.executable? <del> raise "#{curl} is not executable" <add> @curl ||= [ <add> ENV["HOMEBREW_CURL"], <add> which("curl"), <add> "/usr/bin/curl", <add> ].map { |c| Pathname(c) }.find(&:executable?) <add> raise "curl is not executable" unless @curl <add> @curl <ide> end <ide> <ide> def curl_args(*extra_args, show_output: false, user_agent: :default)
1
PHP
PHP
update basics to match code standards
d861a733273bf10d6aa2e16477a3d06afa6ab218
<ide><path>lib/Cake/basics.php <ide> <?php <add> <ide> /** <ide> * Basic Cake functionality. <ide> * <ide> * @return boolean Success <ide> * @link http://book.cakephp.org/view/1125/config <ide> */ <del> function config() { <del> $args = func_get_args(); <del> foreach ($args as $arg) { <del> if ($arg === 'database' && file_exists(CONFIGS . 'database.php')) { <del> include_once(CONFIGS . $arg . '.php'); <del> } elseif (file_exists(CONFIGS . $arg . '.php')) { <del> include_once(CONFIGS . $arg . '.php'); <del> <del> if (count($args) == 1) { <del> return true; <del> } <del> } else { <del> if (count($args) == 1) { <del> return false; <del> } <add>function config() { <add> $args = func_get_args(); <add> foreach ($args as $arg) { <add> if ($arg === 'database' && file_exists(CONFIGS . 'database.php')) { <add> include_once(CONFIGS . $arg . '.php'); <add> } elseif (file_exists(CONFIGS . $arg . '.php')) { <add> include_once(CONFIGS . $arg . '.php'); <add> <add> if (count($args) == 1) { <add> return true; <add> } <add> } else { <add> if (count($args) == 1) { <add> return false; <ide> } <ide> } <del> return true; <ide> } <add> return true; <add>} <ide> <ide> /** <ide> * Prints out debug information about given variable. <ide> function config() { <ide> * @link http://book.cakephp.org/view/1190/Basic-Debugging <ide> * @link http://book.cakephp.org/view/1128/debug <ide> */ <del> function debug($var = false, $showHtml = null, $showFrom = true) { <del> if (Configure::read('debug') > 0) { <del> $file = ''; <del> $line = ''; <del> if ($showFrom) { <del> $calledFrom = debug_backtrace(); <del> $file = substr(str_replace(ROOT, '', $calledFrom[0]['file']), 1); <del> $line = $calledFrom[0]['line']; <del> } <del> $html = <<<HTML <add>function debug($var = false, $showHtml = null, $showFrom = true) { <add> if (Configure::read('debug') > 0) { <add> $file = ''; <add> $line = ''; <add> if ($showFrom) { <add> $calledFrom = debug_backtrace(); <add> $file = substr(str_replace(ROOT, '', $calledFrom[0]['file']), 1); <add> $line = $calledFrom[0]['line']; <add> } <add> $html = <<<HTML <ide> <strong>%s</strong> (line <strong>%s</strong>) <ide> <pre class="cake-debug"> <ide> %s <ide> function debug($var = false, $showHtml = null, $showFrom = true) { <ide> ########################### <ide> <ide> TEXT; <del> $template = $html; <del> if (php_sapi_name() == 'cli') { <del> $template = $text; <del> } <del> if ($showHtml === null && $template !== $text) { <del> $showHtml = true; <del> } <del> $var = print_r($var, true); <del> if ($showHtml) { <del> $var = str_replace(array('<', '>'), array('&lt;', '&gt;'), $var); <del> } <del> printf($template, $file, $line, $var); <add> $template = $html; <add> if (php_sapi_name() == 'cli') { <add> $template = $text; <ide> } <add> if ($showHtml === null && $template !== $text) { <add> $showHtml = true; <add> } <add> $var = print_r($var, true); <add> if ($showHtml) { <add> $var = str_replace(array('<', '>'), array('&lt;', '&gt;'), $var); <add> } <add> printf($template, $file, $line, $var); <ide> } <add>} <ide> <ide> if (!function_exists('sortByKey')) { <ide> <del>/** <del> * Sorts given $array by key $sortby. <del> * <del> * @param array $array Array to sort <del> * @param string $sortby Sort by this key <del> * @param string $order Sort order asc/desc (ascending or descending). <del> * @param integer $type Type of sorting to perform <del> * @return mixed Sorted array <del> */ <add> /** <add> * Sorts given $array by key $sortby. <add> * <add> * @param array $array Array to sort <add> * @param string $sortby Sort by this key <add> * @param string $order Sort order asc/desc (ascending or descending). <add> * @param integer $type Type of sorting to perform <add> * @return mixed Sorted array <add> */ <ide> function sortByKey(&$array, $sortby, $order = 'asc', $type = SORT_NUMERIC) { <ide> if (!is_array($array)) { <ide> return null; <ide> function sortByKey(&$array, $sortby, $order = 'asc', $type = SORT_NUMERIC) { <ide> * @return string Wrapped text <ide> * @link http://book.cakephp.org/view/1132/h <ide> */ <del> function h($text, $double = true, $charset = null) { <del> if (is_array($text)) { <del> $texts = array(); <del> foreach ($text as $k => $t) { <del> $texts[$k] = h($t, $double, $charset); <del> } <del> return $texts; <add>function h($text, $double = true, $charset = null) { <add> if (is_array($text)) { <add> $texts = array(); <add> foreach ($text as $k => $t) { <add> $texts[$k] = h($t, $double, $charset); <ide> } <add> return $texts; <add> } <ide> <del> static $defaultCharset = false; <del> if ($defaultCharset === false) { <del> $defaultCharset = Configure::read('App.encoding'); <del> if ($defaultCharset === null) { <del> $defaultCharset = 'UTF-8'; <del> } <del> } <del> if (is_string($double)) { <del> $charset = $double; <add> static $defaultCharset = false; <add> if ($defaultCharset === false) { <add> $defaultCharset = Configure::read('App.encoding'); <add> if ($defaultCharset === null) { <add> $defaultCharset = 'UTF-8'; <ide> } <del> return htmlspecialchars($text, ENT_QUOTES, ($charset) ? $charset : $defaultCharset, $double); <ide> } <add> if (is_string($double)) { <add> $charset = $double; <add> } <add> return htmlspecialchars($text, ENT_QUOTES, ($charset) ? $charset : $defaultCharset, $double); <add>} <ide> <ide> /** <ide> * Splits a dot syntax plugin name into its plugin and classname. <ide> function h($text, $double = true, $charset = null) { <ide> * @param string $plugin Optional default plugin to use if no plugin is found. Defaults to null. <ide> * @return array Array with 2 indexes. 0 => plugin name, 1 => classname <ide> */ <del> function pluginSplit($name, $dotAppend = false, $plugin = null) { <del> if (strpos($name, '.') !== false) { <del> $parts = explode('.', $name, 2); <del> if ($dotAppend) { <del> $parts[0] .= '.'; <del> } <del> return $parts; <add>function pluginSplit($name, $dotAppend = false, $plugin = null) { <add> if (strpos($name, '.') !== false) { <add> $parts = explode('.', $name, 2); <add> if ($dotAppend) { <add> $parts[0] .= '.'; <ide> } <del> return array($plugin, $name); <add> return $parts; <ide> } <add> return array($plugin, $name); <add>} <ide> <ide> /** <ide> * Print_r convenience function, which prints out <PRE> tags around <ide> function pluginSplit($name, $dotAppend = false, $plugin = null) { <ide> * @param array $var Variable to print out <ide> * @link http://book.cakephp.org/view/1136/pr <ide> */ <del> function pr($var) { <del> if (Configure::read('debug') > 0) { <del> echo '<pre>'; <del> print_r($var); <del> echo '</pre>'; <del> } <add>function pr($var) { <add> if (Configure::read('debug') > 0) { <add> echo '<pre>'; <add> print_r($var); <add> echo '</pre>'; <ide> } <add>} <ide> <ide> /** <ide> * Merge a group of arrays <ide> function pr($var) { <ide> * @return array All array parameters merged into one <ide> * @link http://book.cakephp.org/view/1124/am <ide> */ <del> function am() { <del> $r = array(); <del> $args = func_get_args(); <del> foreach ($args as $a) { <del> if (!is_array($a)) { <del> $a = array($a); <del> } <del> $r = array_merge($r, $a); <del> } <del> return $r; <add>function am() { <add> $r = array(); <add> $args = func_get_args(); <add> foreach ($args as $a) { <add> if (!is_array($a)) { <add> $a = array($a); <add> } <add> $r = array_merge($r, $a); <ide> } <add> return $r; <add>} <ide> <ide> /** <ide> * Gets an environment variable from available sources, and provides emulation <ide> function am() { <ide> * @return string Environment variable setting. <ide> * @link http://book.cakephp.org/view/1130/env <ide> */ <del> function env($key) { <del> if ($key === 'HTTPS') { <del> if (isset($_SERVER['HTTPS'])) { <del> return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'); <del> } <del> return (strpos(env('SCRIPT_URI'), 'https://') === 0); <add>function env($key) { <add> if ($key === 'HTTPS') { <add> if (isset($_SERVER['HTTPS'])) { <add> return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off'); <ide> } <add> return (strpos(env('SCRIPT_URI'), 'https://') === 0); <add> } <ide> <del> if ($key === 'SCRIPT_NAME') { <del> if (env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) { <del> $key = 'SCRIPT_URL'; <del> } <add> if ($key === 'SCRIPT_NAME') { <add> if (env('CGI_MODE') && isset($_ENV['SCRIPT_URL'])) { <add> $key = 'SCRIPT_URL'; <ide> } <add> } <ide> <del> $val = null; <del> if (isset($_SERVER[$key])) { <del> $val = $_SERVER[$key]; <del> } elseif (isset($_ENV[$key])) { <del> $val = $_ENV[$key]; <del> } elseif (getenv($key) !== false) { <del> $val = getenv($key); <del> } <add> $val = null; <add> if (isset($_SERVER[$key])) { <add> $val = $_SERVER[$key]; <add> } elseif (isset($_ENV[$key])) { <add> $val = $_ENV[$key]; <add> } elseif (getenv($key) !== false) { <add> $val = getenv($key); <add> } <ide> <del> if ($key === 'REMOTE_ADDR' && $val === env('SERVER_ADDR')) { <del> $addr = env('HTTP_PC_REMOTE_ADDR'); <del> if ($addr !== null) { <del> $val = $addr; <del> } <add> if ($key === 'REMOTE_ADDR' && $val === env('SERVER_ADDR')) { <add> $addr = env('HTTP_PC_REMOTE_ADDR'); <add> if ($addr !== null) { <add> $val = $addr; <ide> } <add> } <ide> <del> if ($val !== null) { <del> return $val; <del> } <add> if ($val !== null) { <add> return $val; <add> } <ide> <del> switch ($key) { <del> case 'SCRIPT_FILENAME': <del> if (defined('SERVER_IIS') && SERVER_IIS === true) { <del> return str_replace('\\\\', '\\', env('PATH_TRANSLATED')); <del> } <del> break; <del> case 'DOCUMENT_ROOT': <del> $name = env('SCRIPT_NAME'); <del> $filename = env('SCRIPT_FILENAME'); <del> $offset = 0; <del> if (!strpos($name, '.php')) { <del> $offset = 4; <del> } <del> return substr($filename, 0, strlen($filename) - (strlen($name) + $offset)); <del> break; <del> case 'PHP_SELF': <del> return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME')); <del> break; <del> case 'CGI_MODE': <del> return (PHP_SAPI === 'cgi'); <del> break; <del> case 'HTTP_BASE': <del> $host = env('HTTP_HOST'); <del> $parts = explode('.', $host); <del> $count = count($parts); <del> <del> if ($count === 1) { <del> return '.' . $host; <del> } elseif ($count === 2) { <add> switch ($key) { <add> case 'SCRIPT_FILENAME': <add> if (defined('SERVER_IIS') && SERVER_IIS === true) { <add> return str_replace('\\\\', '\\', env('PATH_TRANSLATED')); <add> } <add> break; <add> case 'DOCUMENT_ROOT': <add> $name = env('SCRIPT_NAME'); <add> $filename = env('SCRIPT_FILENAME'); <add> $offset = 0; <add> if (!strpos($name, '.php')) { <add> $offset = 4; <add> } <add> return substr($filename, 0, strlen($filename) - (strlen($name) + $offset)); <add> break; <add> case 'PHP_SELF': <add> return str_replace(env('DOCUMENT_ROOT'), '', env('SCRIPT_FILENAME')); <add> break; <add> case 'CGI_MODE': <add> return (PHP_SAPI === 'cgi'); <add> break; <add> case 'HTTP_BASE': <add> $host = env('HTTP_HOST'); <add> $parts = explode('.', $host); <add> $count = count($parts); <add> <add> if ($count === 1) { <add> return '.' . $host; <add> } elseif ($count === 2) { <add> return '.' . $host; <add> } elseif ($count === 3) { <add> $gTLD = array( <add> 'aero', <add> 'asia', <add> 'biz', <add> 'cat', <add> 'com', <add> 'coop', <add> 'edu', <add> 'gov', <add> 'info', <add> 'int', <add> 'jobs', <add> 'mil', <add> 'mobi', <add> 'museum', <add> 'name', <add> 'net', <add> 'org', <add> 'pro', <add> 'tel', <add> 'travel', <add> 'xxx' <add> ); <add> if (in_array($parts[1], $gTLD)) { <ide> return '.' . $host; <del> } elseif ($count === 3) { <del> $gTLD = array('aero', 'asia', 'biz', 'cat', 'com', 'coop', 'edu', 'gov', 'info', 'int', 'jobs', 'mil', 'mobi', 'museum', 'name', 'net', 'org', 'pro', 'tel', 'travel', 'xxx'); <del> if (in_array($parts[1], $gTLD)) { <del> return '.' . $host; <del> } <ide> } <del> array_shift($parts); <del> return '.' . implode('.', $parts); <del> break; <del> } <del> return null; <add> } <add> array_shift($parts); <add> return '.' . implode('.', $parts); <add> break; <ide> } <add> return null; <add>} <ide> <ide> /** <ide> * Reads/writes temporary data to cache files or session. <ide> function env($key) { <ide> * @return mixed The contents of the temporary file. <ide> * @deprecated Please use Cache::write() instead <ide> */ <del> function cache($path, $data = null, $expires = '+1 day', $target = 'cache') { <del> if (Configure::read('Cache.disable')) { <del> return null; <del> } <del> $now = time(); <add>function cache($path, $data = null, $expires = '+1 day', $target = 'cache') { <add> if (Configure::read('Cache.disable')) { <add> return null; <add> } <add> $now = time(); <ide> <del> if (!is_numeric($expires)) { <del> $expires = strtotime($expires, $now); <del> } <add> if (!is_numeric($expires)) { <add> $expires = strtotime($expires, $now); <add> } <ide> <del> switch (strtolower($target)) { <del> case 'cache': <del> $filename = CACHE . $path; <del> break; <del> case 'public': <del> $filename = WWW_ROOT . $path; <del> break; <del> case 'tmp': <del> $filename = TMP . $path; <del> break; <del> } <del> $timediff = $expires - $now; <del> $filetime = false; <add> switch (strtolower($target)) { <add> case 'cache': <add> $filename = CACHE . $path; <add> break; <add> case 'public': <add> $filename = WWW_ROOT . $path; <add> break; <add> case 'tmp': <add> $filename = TMP . $path; <add> break; <add> } <add> $timediff = $expires - $now; <add> $filetime = false; <ide> <del> if (file_exists($filename)) { <del> $filetime = @filemtime($filename); <del> } <add> if (file_exists($filename)) { <add> $filetime = @filemtime($filename); <add> } <ide> <del> if ($data === null) { <del> if (file_exists($filename) && $filetime !== false) { <del> if ($filetime + $timediff < $now) { <del> @unlink($filename); <del> } else { <del> $data = @file_get_contents($filename); <del> } <add> if ($data === null) { <add> if (file_exists($filename) && $filetime !== false) { <add> if ($filetime + $timediff < $now) { <add> @unlink($filename); <add> } else { <add> $data = @file_get_contents($filename); <ide> } <del> } elseif (is_writable(dirname($filename))) { <del> @file_put_contents($filename, $data); <ide> } <del> return $data; <add> } elseif (is_writable(dirname($filename))) { <add> @file_put_contents($filename, $data); <ide> } <add> return $data; <add>} <ide> <ide> /** <ide> * Used to delete files in the cache directories, or clear contents of cache directories <ide> function cache($path, $data = null, $expires = '+1 day', $target = 'cache') { <ide> * @param string $ext The file extension you are deleting <ide> * @return true if files found and deleted false otherwise <ide> */ <del> function clearCache($params = null, $type = 'views', $ext = '.php') { <del> if (is_string($params) || $params === null) { <del> $params = preg_replace('/\/\//', '/', $params); <del> $cache = CACHE . $type . DS . $params; <add>function clearCache($params = null, $type = 'views', $ext = '.php') { <add> if (is_string($params) || $params === null) { <add> $params = preg_replace('/\/\//', '/', $params); <add> $cache = CACHE . $type . DS . $params; <ide> <del> if (is_file($cache . $ext)) { <del> @unlink($cache . $ext); <del> return true; <del> } elseif (is_dir($cache)) { <del> $files = glob($cache . '*'); <add> if (is_file($cache . $ext)) { <add> @unlink($cache . $ext); <add> return true; <add> } elseif (is_dir($cache)) { <add> $files = glob($cache . '*'); <ide> <del> if ($files === false) { <del> return false; <del> } <add> if ($files === false) { <add> return false; <add> } <ide> <del> foreach ($files as $file) { <del> if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) { <del> @unlink($file); <del> } <del> } <del> return true; <del> } else { <del> $cache = array( <del> CACHE . $type . DS . '*' . $params . $ext, <del> CACHE . $type . DS . '*' . $params . '_*' . $ext <del> ); <del> $files = array(); <del> while ($search = array_shift($cache)) { <del> $results = glob($search); <del> if ($results !== false) { <del> $files = array_merge($files, $results); <del> } <add> foreach ($files as $file) { <add> if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) { <add> @unlink($file); <ide> } <del> if (empty($files)) { <del> return false; <del> } <del> foreach ($files as $file) { <del> if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) { <del> @unlink($file); <del> } <add> } <add> return true; <add> } else { <add> $cache = array( <add> CACHE . $type . DS . '*' . $params . $ext, <add> CACHE . $type . DS . '*' . $params . '_*' . $ext <add> ); <add> $files = array(); <add> while ($search = array_shift($cache)) { <add> $results = glob($search); <add> if ($results !== false) { <add> $files = array_merge($files, $results); <ide> } <del> return true; <ide> } <del> } elseif (is_array($params)) { <del> foreach ($params as $file) { <del> clearCache($file, $type, $ext); <add> if (empty($files)) { <add> return false; <add> } <add> foreach ($files as $file) { <add> if (is_file($file) && strrpos($file, DS . 'empty') !== strlen($file) - 6) { <add> @unlink($file); <add> } <ide> } <ide> return true; <ide> } <del> return false; <add> } elseif (is_array($params)) { <add> foreach ($params as $file) { <add> clearCache($file, $type, $ext); <add> } <add> return true; <ide> } <add> return false; <add>} <ide> <ide> /** <ide> * Recursively strips slashes from all values in an array <ide> function clearCache($params = null, $type = 'views', $ext = '.php') { <ide> * @return mixed What is returned from calling stripslashes <ide> * @link http://book.cakephp.org/view/1138/stripslashes_deep <ide> */ <del> function stripslashes_deep($values) { <del> if (is_array($values)) { <del> foreach ($values as $key => $value) { <del> $values[$key] = stripslashes_deep($value); <del> } <del> } else { <del> $values = stripslashes($values); <add>function stripslashes_deep($values) { <add> if (is_array($values)) { <add> foreach ($values as $key => $value) { <add> $values[$key] = stripslashes_deep($value); <ide> } <del> return $values; <add> } else { <add> $values = stripslashes($values); <ide> } <add> return $values; <add>} <ide> <ide> /** <ide> * Returns a translated string if one is found; Otherwise, the submitted message. <ide> function stripslashes_deep($values) { <ide> * @return mixed translated string <ide> * @link http://book.cakephp.org/view/1121/__ <ide> */ <del> function __($singular, $args = null) { <del> if (!$singular) { <del> return; <del> } <add>function __($singular, $args = null) { <add> if (!$singular) { <add> return; <add> } <ide> <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($singular); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 1); <del> } <del> return vsprintf($translated, $args); <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($singular); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 1); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * Returns correct plural form of message identified by $singular and $plural for count $count. <ide> function __($singular, $args = null) { <ide> * @param mixed $args Array with arguments or multiple arguments in function <ide> * @return mixed plural form of translated string <ide> */ <del> function __n($singular, $plural, $count, $args = null) { <del> if (!$singular) { <del> return; <del> } <add>function __n($singular, $plural, $count, $args = null) { <add> if (!$singular) { <add> return; <add> } <ide> <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($singular, $plural, null, 6, $count); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 3); <del> } <del> return vsprintf($translated, $args); <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($singular, $plural, null, 6, $count); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 3); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * Allows you to override the current domain for a single message lookup. <ide> function __n($singular, $plural, $count, $args = null) { <ide> * @param mixed $args Array with arguments or multiple arguments in function <ide> * @return translated string <ide> */ <del> function __d($domain, $msg, $args = null) { <del> if (!$msg) { <del> return; <del> } <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($msg, null, $domain); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 2); <del> } <del> return vsprintf($translated, $args); <add>function __d($domain, $msg, $args = null) { <add> if (!$msg) { <add> return; <add> } <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($msg, null, $domain); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 2); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * Allows you to override the current domain for a single plural message lookup. <ide> function __d($domain, $msg, $args = null) { <ide> * @param mixed $args Array with arguments or multiple arguments in function <ide> * @return plural form of translated string <ide> */ <del> function __dn($domain, $singular, $plural, $count, $args = null) { <del> if (!$singular) { <del> return; <del> } <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($singular, $plural, $domain, 6, $count); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 4); <del> } <del> return vsprintf($translated, $args); <add>function __dn($domain, $singular, $plural, $count, $args = null) { <add> if (!$singular) { <add> return; <add> } <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($singular, $plural, $domain, 6, $count); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 4); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * Allows you to override the current domain for a single message lookup. <ide> function __dn($domain, $singular, $plural, $count, $args = null) { <ide> * @param mixed $args Array with arguments or multiple arguments in function <ide> * @return translated string <ide> */ <del> function __dc($domain, $msg, $category, $args = null) { <del> if (!$msg) { <del> return; <del> } <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($msg, null, $domain, $category); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 3); <del> } <del> return vsprintf($translated, $args); <add>function __dc($domain, $msg, $category, $args = null) { <add> if (!$msg) { <add> return; <add> } <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($msg, null, $domain, $category); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 3); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * Allows you to override the current domain for a single plural message lookup. <ide> function __dc($domain, $msg, $category, $args = null) { <ide> * @param mixed $args Array with arguments or multiple arguments in function <ide> * @return plural form of translated string <ide> */ <del> function __dcn($domain, $singular, $plural, $count, $category, $args = null) { <del> if (!$singular) { <del> return; <del> } <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($singular, $plural, $domain, $category, $count); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 5); <del> } <del> return vsprintf($translated, $args); <add>function __dcn($domain, $singular, $plural, $count, $category, $args = null) { <add> if (!$singular) { <add> return; <add> } <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($singular, $plural, $domain, $category, $count); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 5); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * The category argument allows a specific category of the locale settings to be used for fetching a message. <ide> function __dcn($domain, $singular, $plural, $count, $category, $args = null) { <ide> * @param mixed $args Array with arguments or multiple arguments in function <ide> * @return translated string <ide> */ <del> function __c($msg, $category, $args = null) { <del> if (!$msg) { <del> return; <del> } <del> App::uses('I18n', 'I18n'); <del> $translated = I18n::translate($msg, null, null, $category); <del> if ($args === null) { <del> return $translated; <del> } elseif (!is_array($args)) { <del> $args = array_slice(func_get_args(), 2); <del> } <del> return vsprintf($translated, $args); <add>function __c($msg, $category, $args = null) { <add> if (!$msg) { <add> return; <add> } <add> App::uses('I18n', 'I18n'); <add> $translated = I18n::translate($msg, null, null, $category); <add> if ($args === null) { <add> return $translated; <add> } elseif (!is_array($args)) { <add> $args = array_slice(func_get_args(), 2); <ide> } <add> return vsprintf($translated, $args); <add>} <ide> <ide> /** <ide> * Shortcut to Log::write. <ide> * <ide> * @param string $message Message to write to log <ide> */ <del> function LogError($message) { <del> App::uses('CakeLog', 'Log'); <del> $bad = array("\n", "\r", "\t"); <del> $good = ' '; <del> CakeLog::write('error', str_replace($bad, $good, $message)); <del> } <add>function LogError($message) { <add> App::uses('CakeLog', 'Log'); <add> $bad = array("\n", "\r", "\t"); <add> $good = ' '; <add> CakeLog::write('error', str_replace($bad, $good, $message)); <add>} <ide> <ide> /** <ide> * Searches include path for files. <ide> function LogError($message) { <ide> * @return Full path to file if exists, otherwise false <ide> * @link http://book.cakephp.org/view/1131/fileExistsInPath <ide> */ <del> function fileExistsInPath($file) { <del> $paths = explode(PATH_SEPARATOR, ini_get('include_path')); <del> foreach ($paths as $path) { <del> $fullPath = $path . DS . $file; <del> <del> if (file_exists($fullPath)) { <del> return $fullPath; <del> } elseif (file_exists($file)) { <del> return $file; <del> } <add>function fileExistsInPath($file) { <add> $paths = explode(PATH_SEPARATOR, ini_get('include_path')); <add> foreach ($paths as $path) { <add> $fullPath = $path . DS . $file; <add> <add> if (file_exists($fullPath)) { <add> return $fullPath; <add> } elseif (file_exists($file)) { <add> return $file; <ide> } <del> return false; <ide> } <add> return false; <add>} <ide> <ide> /** <ide> * Convert forward slashes to underscores and removes first and last underscores in a string <ide> function fileExistsInPath($file) { <ide> * @return string with underscore remove from start and end of string <ide> * @link http://book.cakephp.org/view/1126/convertSlash <ide> */ <del> function convertSlash($string) { <del> $string = trim($string, '/'); <del> $string = preg_replace('/\/\//', '/', $string); <del> $string = str_replace('/', '_', $string); <del> return $string; <del> } <add>function convertSlash($string) { <add> $string = trim($string, '/'); <add> $string = preg_replace('/\/\//', '/', $string); <add> $string = str_replace('/', '_', $string); <add> return $string; <add>}
1
Javascript
Javascript
fix whitespace issues
fb8811d95ec3d644f60db24f4a816f8c05cd9ad5
<ide><path>lib/_debugger.js <ide> Client.prototype.fullTrace = function(cb) { <ide> }; <ide> <ide> <del> <del> <del> <del> <ide> const commands = [ <ide> [ <ide> 'run (r)', <ide><path>lib/_http_server.js <ide> ServerResponse.prototype._finish = function() { <ide> }; <ide> <ide> <del> <ide> exports.ServerResponse = ServerResponse; <ide> <ide> ServerResponse.prototype.statusCode = 200; <ide><path>lib/_stream_readable.js <ide> function readableAddChunk(stream, state, chunk, encoding, addToFront) { <ide> } <ide> <ide> <del> <ide> // if it's past the high water mark, we can push in some more. <ide> // Also, if we have no data yet, we can stand some <ide> // more bytes. This is to work around cases where hwm=0, <ide> Readable.prototype.pipe = function(dest, pipeOpts) { <ide> dest._events.error = [onerror, dest._events.error]; <ide> <ide> <del> <ide> // Both close and finish should trigger unpipe, but only once. <ide> function onclose() { <ide> dest.removeListener('finish', onfinish); <ide> Readable.prototype.wrap = function(stream) { <ide> }; <ide> <ide> <del> <ide> // exposed for testing purposes only. <ide> Readable._fromList = fromList; <ide> <ide><path>lib/crypto.js <ide> Decipheriv.prototype.setAuthTag = Cipher.prototype.setAuthTag; <ide> Decipheriv.prototype.setAAD = Cipher.prototype.setAAD; <ide> <ide> <del> <ide> exports.createSign = exports.Sign = Sign; <ide> function Sign(algorithm, options) { <ide> if (!(this instanceof Sign)) <ide> Sign.prototype.sign = function(options, encoding) { <ide> }; <ide> <ide> <del> <ide> exports.createVerify = exports.Verify = Verify; <ide> function Verify(algorithm, options) { <ide> if (!(this instanceof Verify)) <ide> ECDH.prototype.getPublicKey = function getPublicKey(encoding, format) { <ide> }; <ide> <ide> <del> <ide> exports.pbkdf2 = function(password, <ide> salt, <ide> iterations, <ide><path>lib/fs.js <ide> fs.realpath = function realpath(p, cache, cb) { <ide> }; <ide> <ide> <del> <ide> var pool; <ide> <ide> function allocNewPool(poolSize) { <ide> function allocNewPool(poolSize) { <ide> } <ide> <ide> <del> <ide> fs.createReadStream = function(path, options) { <ide> return new ReadStream(path, options); <ide> }; <ide> ReadStream.prototype.close = function(cb) { <ide> }; <ide> <ide> <del> <del> <ide> fs.createWriteStream = function(path, options) { <ide> return new WriteStream(path, options); <ide> }; <ide><path>lib/net.js <ide> Socket.prototype.unref = function() { <ide> }; <ide> <ide> <del> <ide> function afterConnect(status, handle, req, readable, writable) { <ide> var self = handle.owner; <ide> <ide><path>lib/readline.js <ide> Interface.prototype._ttyWrite = function(s, key) { <ide> exports.Interface = Interface; <ide> <ide> <del> <ide> /** <ide> * accepts a readable Stream instance and makes it emit "keypress" events <ide> */ <ide><path>lib/stream.js <ide> Stream.PassThrough = require('_stream_passthrough'); <ide> Stream.Stream = Stream; <ide> <ide> <del> <ide> // old-style streams. Note that the pipe method (the only relevant <ide> // part of this class) is overridden in the Readable class. <ide> <ide><path>lib/tty.js <ide> ReadStream.prototype.setRawMode = function(flag) { <ide> }; <ide> <ide> <del> <ide> function WriteStream(fd) { <ide> if (!(this instanceof WriteStream)) return new WriteStream(fd); <ide> net.Socket.call(this, { <ide><path>lib/zlib.js <ide> function Inflate(opts) { <ide> } <ide> <ide> <del> <ide> // gzip - bigger header, same deflate compression <ide> function Gzip(opts) { <ide> if (!(this instanceof Gzip)) return new Gzip(opts); <ide> function Gunzip(opts) { <ide> } <ide> <ide> <del> <ide> // raw - no header <ide> function DeflateRaw(opts) { <ide> if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); <ide><path>test/internet/test-net-connect-timeout.js <ide> socket1.on('connect', function() { <ide> }); <ide> <ide> <del> <del> <del> <ide> process.on('exit', function() { <ide> assert.ok(gotTimeout0); <ide> assert.ok(!gotConnect0); <ide><path>test/parallel/test-buffer-inspect.js <ide> buffer.INSPECT_MAX_BYTES = Infinity; <ide> assert.doesNotThrow(function() { <ide> assert.strictEqual(util.inspect(b), expected); <ide> assert.strictEqual(util.inspect(s), expected); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/parallel/test-buffer.js <ide> assert.equal(b, c.parent); <ide> assert.equal(b, d.parent); <ide> <ide> <del> <ide> // Bug regression test <ide> var testValue = '\u00F6\u65E5\u672C\u8A9E'; // ö日本語 <ide> var buffer = new Buffer(32); <ide><path>test/parallel/test-child-process-double-pipe.js <ide> if (is_windows) { <ide> */ <ide> <ide> <del> <ide> // pipe echo | grep <ide> echo.stdout.on('data', function(data) { <ide> console.error('grep stdin write ' + data.length); <ide> sed.on('exit', function() { <ide> }); <ide> <ide> <del> <ide> // pipe grep | sed <ide> grep.stdout.on('data', function(data) { <ide> console.error('grep stdout ' + data.length); <ide> grep.stdout.on('end', function(code) { <ide> }); <ide> <ide> <del> <ide> var result = ''; <ide> <ide> // print sed's output <ide><path>test/parallel/test-child-process-exit-code.js <ide> exitChild.on('exit', function(code, signal) { <ide> }); <ide> <ide> <del> <ide> var errorScript = path.join(common.fixturesDir, <ide> 'child_process_should_emit_error.js'); <ide> var errorChild = spawn(process.argv[0], [errorScript]); <ide><path>test/parallel/test-domain.js <ide> d.on('error', function(er) { <ide> }); <ide> <ide> <del> <ide> process.on('exit', function() { <ide> console.error('exit', caught, expectCaught); <ide> assert.equal(caught, expectCaught, 'caught the expected number of errors'); <ide> console.log('ok'); <ide> }); <ide> <ide> <del> <ide> // revert to using the domain when a callback is passed to nextTick in <ide> // the middle of a tickCallback loop <ide> d.run(function() { <ide> d.run(function() { <ide> expectCaught++; <ide> <ide> <del> <ide> // catch thrown errors no matter how many times we enter the event loop <ide> // this only uses implicit binding, except for the first function <ide> // passed to d.run(). The rest are implicitly bound by virtue of being <ide> d.run(function() { <ide> expectCaught++; <ide> <ide> <del> <ide> // implicit addition of a timer created within a domain-bound context. <ide> d.run(function() { <ide> setTimeout(function() { <ide> d.run(function() { <ide> expectCaught++; <ide> <ide> <del> <ide> // Event emitters added to the domain have their errors routed. <ide> d.add(e); <ide> e.emit('error', new Error('emitted')); <ide> expectCaught++; <ide> <ide> <del> <ide> // get rid of the `if (er) return cb(er)` malarky, by intercepting <ide> // the cb functions to the domain, and using the intercepted function <ide> // as a callback instead. <ide> bound(new Error('bound')); <ide> expectCaught++; <ide> <ide> <del> <ide> // intercepted should never pass first argument to callback <ide> function fn2(data) { <ide> assert.equal(data, 'data', 'should not be null err argument'); <ide> setTimeout(d.bind(thrower), 100); <ide> expectCaught++; <ide> <ide> <del> <ide> // Pass an intercepted function to an fs operation that fails. <ide> fs.open('this file does not exist', 'r', d.intercept(function(er) { <ide> console.error('should not get here!', er); <ide> fs.open('this file does not exist', 'r', d.intercept(function(er) { <ide> expectCaught++; <ide> <ide> <del> <ide> // implicit addition by being created within a domain-bound context. <ide> var implicit; <ide> <ide><path>test/parallel/test-event-emitter-num-args.js <ide> e.emit('numArgs', null, null, null, null, null); <ide> process.on('exit', function() { <ide> assert.deepEqual([0, 1, 2, 3, 4, 5], num_args_emited); <ide> }); <del> <del> <ide><path>test/parallel/test-fs-read-stream-resume.js <ide> stream.on('data', function(chunk) { <ide> stream.resume(); <ide> } <ide> }); <del> <add> <ide> process.nextTick(function() { <ide> stream.pause(); <ide> setTimeout(function() { <ide><path>test/parallel/test-http-expect-continue.js <ide> server.on('checkContinue', function(req, res) { <ide> server.listen(common.PORT); <ide> <ide> <del> <ide> server.on('listening', function() { <ide> var req = http.request({ <ide> port: common.PORT, <ide><path>test/parallel/test-https-strict.js <ide> var responseCount = 0; <ide> var pending = 0; <ide> <ide> <del> <ide> function server(options, port) { <ide> var s = https.createServer(options, handler); <ide> s.requests = []; <ide><path>test/parallel/test-module-nodemodulepaths.js <ide> if (isWindows) { <ide> paths = module._nodeModulePaths(file); <ide> <ide> assert.ok(paths.indexOf(file + delimiter + 'node_modules') !== -1); <del>assert.ok(Array.isArray(paths)); <ide>\ No newline at end of file <add>assert.ok(Array.isArray(paths)); <ide><path>test/parallel/test-require-dot.js <ide> module._initPaths(); <ide> <ide> var c = require('.'); <ide> <del>assert.equal(c.value, 42, 'require(".") should honor NODE_PATH'); <ide>\ No newline at end of file <add>assert.equal(c.value, 42, 'require(".") should honor NODE_PATH'); <ide><path>test/parallel/test-require-extensions-main.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> <del>require(common.fixturesDir + '/require-bin/bin/req.js'); <ide>\ No newline at end of file <add>require(common.fixturesDir + '/require-bin/bin/req.js'); <ide><path>test/parallel/test-smalloc.js <ide> assert.equal(b[0], 0xff); <ide> assert.equal(b[1], 0xff); <ide> <ide> <del> <ide> // verify checking external if has external memory <ide> <ide> // check objects <ide><path>test/parallel/test-stream-unshift-empty-chunk.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> <del>// This test verifies that stream.unshift(Buffer(0)) or <add>// This test verifies that stream.unshift(Buffer(0)) or <ide> // stream.unshift('') does not set state.reading=false. <ide> var Readable = require('stream').Readable; <ide> <ide><path>test/parallel/test-stream2-readable-from-list.js <ide> process.on('exit', function() { <ide> process.nextTick(run); <ide> <ide> <del> <ide> test('buffers', function(t) { <ide> // have a length <ide> var len = 16; <ide><path>test/parallel/test-stringbytes-external.js <ide> assert.equal(c_bin.toString('binary'), ucs2_control); <ide> assert.equal(c_ucs.toString('binary'), ucs2_control); <ide> <ide> <del> <ide> // now let's test BASE64 and HEX ecoding/decoding <ide> var RADIOS = 2; <ide> var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; <ide><path>test/parallel/test-url.js <ide> relativeTests2.forEach(function(relativeTest) { <ide> }); <ide> <ide> <del> <ide> // https://github.com/nodejs/io.js/pull/1036 <ide> var throws = [ <ide> undefined, <ide><path>test/parallel/test-vm-new-script-new-context.js <ide> assert.throws(function() { <ide> }, /test/); <ide> <ide> <del> <ide> console.error('undefined reference'); <ide> var error; <ide> script = new Script('foo.bar = 5;'); <ide> console.error('invalid this'); <ide> assert.throws(function() { <ide> script.runInNewContext.call('\'hello\';'); <ide> }, TypeError); <del> <del> <ide><path>test/parallel/test-zlib-random-byte-pipes.js <ide> var util = require('util'); <ide> var zlib = require('zlib'); <ide> <ide> <del> <ide> // emit random bytes, and keep a shasum <ide> function RandomReadStream(opt) { <ide> Stream.call(this); <ide> HashStream.prototype.end = function(c) { <ide> }; <ide> <ide> <del> <del> <ide> var inp = new RandomReadStream({ total: 1024, block: 256, jitter: 16 }); <ide> var out = new HashStream(); <ide> var gzip = zlib.createGzip(); <ide><path>test/parallel/test-zlib.js <ide> SlowStream.prototype.end = function(chunk) { <ide> }; <ide> <ide> <del> <ide> // for each of the files, make sure that compressing and <ide> // decompressing results in the same data, for every combination <ide> // of the options set above. <ide><path>test/pummel/test-exec.js <ide> exec('thisisnotavalidcommand', function(err, stdout, stderr) { <ide> }); <ide> <ide> <del> <ide> var sleeperStart = new Date(); <ide> exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { <ide> var diff = (new Date()) - sleeperStart; <ide> exec(SLEEP3_COMMAND, { timeout: 50 }, function(err, stdout, stderr) { <ide> }); <ide> <ide> <del> <del> <ide> var startSleep3 = new Date(); <ide> var killMeTwice = exec(SLEEP3_COMMAND, {timeout: 1000}, killMeTwiceCallback); <ide> <ide><path>test/pummel/test-net-throttle.js <ide> server.listen(common.PORT, function() { <ide> }); <ide> <ide> <del> <ide> process.on('exit', function() { <ide> assert.equal(N, chars_recved); <ide> assert.equal(true, npauses > 2); <ide><path>test/pummel/test-regress-GH-814.js <ide> var testFileFD = fs.openSync(testFileName, 'w'); <ide> console.log(testFileName); <ide> <ide> <del> <ide> var kBufSize = 128 * 1024; <ide> var PASS = true; <ide> var neverWrittenBuffer = newBuffer(kBufSize, 0x2e); //0x2e === '.' <ide> var bufPool = []; <ide> <ide> <del> <ide> var tail = require('child_process').spawn('tail', ['-f', testFileName]); <ide> tail.stdout.on('data', tailCB); <ide> <ide> function tailCB(data) { <ide> } <ide> <ide> <del> <ide> var timeToQuit = Date.now() + 8e3; //Test during no more than this seconds. <ide> (function main() { <ide> <ide> function cb(err, written) { <ide> throw err; <ide> } <ide> } <del> <del> <ide><path>test/pummel/test-regress-GH-814_2.js <ide> function writerCB(err, written) { <ide> } <ide> <ide> <del> <del> <ide> // ******************* UTILITIES <ide> <ide> <ide><path>test/pummel/test-stream2-basic.js <ide> test('pipe', function(t) { <ide> }); <ide> <ide> <del> <ide> [1, 2, 3, 4, 5, 6, 7, 8, 9].forEach(function(SPLIT) { <ide> test('unpipe', function(t) { <ide> var r = new TestReader(5); <ide><path>test/sequential/test-pipe.js <ide> var web = http.Server(function(req, res) { <ide> web.listen(webPort, startClient); <ide> <ide> <del> <ide> var tcp = net.Server(function(s) { <ide> tcp.close(); <ide> <ide><path>test/sequential/test-regress-GH-3542.js <ide> test(process.env.windir); <ide> <ide> process.on('exit', function() { <ide> assert.strictEqual(succeeded, 7); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/sequential/test-regress-GH-4948.js <ide> sock.connect(common.PORT, 'localhost'); <ide> sock.on('connect', function() { <ide> sock.write('GET / HTTP/1.1\r\n\r\n'); <ide> sock.end(); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/sequential/test-regress-GH-784.js <ide> function ping() { <ide> } <ide> <ide> <del> <ide> function pingping() { <ide> ping(); <ide> ping(); <ide> } <ide> <del> <ide> pingping(); <ide> <del> <del> <del> <ide> process.on('exit', function() { <ide> console.error("process.on('exit')"); <ide> console.error(responses);
40
Javascript
Javascript
fix permanent deoptimizations
b6da225799cd754e6696586e759218d7514fdd85
<ide><path>test/common.js <ide> exports.allowGlobals = allowGlobals; <ide> function leakedGlobals() { <ide> const leaked = []; <ide> <del> for (const val in global) <add> // eslint-disable-next-line no-var <add> for (var val in global) <ide> if (!knownGlobals.includes(global[val])) <ide> leaked.push(val); <ide>
1
Mixed
Javascript
add readme to app template, lint
ab81db65c51bfb28b35b0154b5e16a13271afd64
<ide><path>local-cli/templates/HelloNavigation/README.md <add># App template for new React Native apps <add> <add>This is a simple React Native app template which demonstrates a few basics concepts such as navigation between a few screens, ListViews, and handling text input. <add> <add><img src="https://cloud.githubusercontent.com/assets/346214/22697898/ced66f52-ed4a-11e6-9b90-df6daef43199.gif" alt="Android Example" height="800" style="float: left"/> <add> <add><img src="https://cloud.githubusercontent.com/assets/346214/22697901/cfeab3e4-ed4a-11e6-8552-d76585317ac2.gif" alt="iOS Example" height="800"/> <add> <add>## Purpose <add> <add>The idea is to make it easier for people to get started with React Native. Currently `react-native init` creates a very simple app that contains one screen with static text. Everyone new to React Native then needs to figure out how to do very basic things such as: <add>- Rendering a list of items fetched from a server <add>- Navigating between screens <add>- Handling text input and the software keyboard <add> <add>This app serves as a template used by `react-native init` so it is easier for anyone to get up and running quickly by having an app with a few screens and a ListView ready to go. <add> <add>### Best practices <add> <add>Another purpose of this app is to define best practices such as the folder structure of a standalone React Native app and naming conventions. <add> <add>## Not using Redux <add> <add>This template intentionally doesn't use Redux. After discussing with a few people who have experience using Redux we concluded that adding Redux to this app targeted at beginners would make the code more confusing, and wouldn't clearly show the benefits of Redux (because the app is too small). There are already a few concepts to grasp - the React component lifecycle, rendeing lists, using async / await, handling the software keyboard. We thought that's the maximum amount of things to learn at once. It's better for everyone to see patterns in their codebase as the app grows and decide for themselves whether and when they need Redux. See also the post [You Might Not Need Redux](https://medium.com/@dan_abramov/you-might-not-need-redux-be46360cf367#.f3q7kq4b3) by [Dan Abramov](https://twitter.com/dan_abramov). <add> <add>## Not using Flow (for now) <add> <add>Many people are new to React Native, some are new to ES6 and most people will be new to Flow. Therefore we didn't want to introduce all these concepts all at once in a single codebase. However, it might make sense to later introduce a separate version of this template that uses Flow annotations. <add> <add>## Provide feedback <add> <add>We need your feedback. Do you have a lot of experience building React Native apps? If so, please carefully read the code of the template and if you think something should be done differently, use issues in the repo [mkonicek/AppTemplateFeedback](https://github.com/mkonicek/AppTemplateFeedback) to discuss what should be done differently. <add> <add>## How to use the template <add> <add>``` <add>$ react-native init MyApp --version 0.42.0-rc.2 --template navigation <add>$ cd MyApp <add>$ react-native run-android <add>$ react-native run-ios <add>``` <ide><path>local-cli/templates/HelloNavigation/components/KeyboardSpacer.js <add>'use strict'; <add> <ide> /* @flow */ <ide> <ide> import React, { PropTypes, Component } from 'react'; <ide> import { <ide> } from 'react-native'; <ide> <ide> type Props = { <del> offset?: number; <add> offset?: number, <ide> } <ide> <ide> type State = { <ide> type State = { <ide> */ <ide> const KeyboardSpacer = () => ( <ide> Platform.OS === 'ios' ? <KeyboardSpacerIOS /> : null <del>) <add>); <ide> <ide> class KeyboardSpacerIOS extends Component<Props, Props, State> { <ide> static propTypes = { <ide><path>local-cli/templates/HelloNavigation/components/ListItem.js <add>'use strict'; <add> <ide> import React, { Component } from 'react'; <ide> import { <ide> Platform, <ide> const Touchable = ({onPress, children}) => { <ide> ); <ide> } else { <ide> return ( <del> <TouchableHighlight onPress={onPress} underlayColor='#ddd'> <add> <TouchableHighlight onPress={onPress} underlayColor="#ddd"> <ide> {child} <ide> </TouchableHighlight> <ide> ); <ide><path>local-cli/templates/HelloNavigation/lib/Backend.js <add>'use strict'; <ide> <ide> // This file just a dummy example of a HTTP API to talk to the backend. <ide> // The state of the "database" that would normally live on the server <ide> function _makeSimulatedNetworkRequest(getValue) { <ide> */ <ide> async function fetchChatList() { <ide> return _makeSimulatedNetworkRequest((resolve, reject) => { <del> resolve(backendStateForLoggedInPerson.chats.map(chat => chat.name)) <add> resolve(backendStateForLoggedInPerson.chats.map(chat => chat.name)); <ide> }); <ide> } <ide> <ide> async function fetchChat(name) { <ide> backendStateForLoggedInPerson.chats.find( <ide> chat => chat.name === name <ide> ) <del> ) <add> ); <ide> }); <ide> } <ide> <ide> async function fetchChat(name) { <ide> */ <ide> async function sendMessage({name, message}) { <ide> return _makeSimulatedNetworkRequest((resolve, reject) => { <del> const chat = backendStateForLoggedInPerson.chats.find( <add> const chatForName = backendStateForLoggedInPerson.chats.find( <ide> chat => chat.name === name <ide> ); <del> if (chat) { <del> chat.messages.push({ <add> if (chatForName) { <add> chatForName.messages.push({ <ide> name: 'Me', <ide> text: message, <ide> }); <ide><path>local-cli/templates/HelloNavigation/views/HomeScreenTabNavigator.js <del>import React, { Component } from 'react'; <add>'use strict'; <add> <ide> import { TabNavigator } from 'react-navigation'; <ide> <ide> import ChatListScreen from './chat/ChatListScreen'; <ide><path>local-cli/templates/HelloNavigation/views/MainNavigator.js <add>'use strict'; <add> <ide> /** <ide> * This is an example React Native app demonstrates ListViews, text input and <ide> * navigation between a few screens. <ide><path>local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js <add>'use strict'; <add> <ide> import React, { Component } from 'react'; <ide> import { <ide> ActivityIndicator, <ide> export default class ChatListScreen extends Component { <ide> <ide> async componentDidMount() { <ide> const chatList = await Backend.fetchChatList(); <del> const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); <ide> this.setState((prevState) => ({ <ide> dataSource: prevState.dataSource.cloneWithRows(chatList), <ide> isLoading: false, <ide> export default class ChatListScreen extends Component { <ide> }); <ide> }} <ide> /> <del> ) <add> ); <ide> } <ide> <ide> render() { <ide><path>local-cli/templates/HelloNavigation/views/chat/ChatScreen.js <add>'use strict'; <add> <ide> import React, { Component } from 'react'; <ide> import { <ide> ActivityIndicator, <ide> export default class ChatScreen extends Component { <ide> }); <ide> return; <ide> } <del> const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); <ide> this.setState((prevState) => ({ <ide> messages: chat.messages, <ide> dataSource: prevState.dataSource.cloneWithRows(chat.messages), <ide> export default class ChatScreen extends Component { <ide> myMessage: '', <ide> } <ide> }); <del> this.refs.textInput.clear(); <add> this.textInput.clear(); <ide> } <ide> <ide> onMyMessageChange = (event) => { <ide> export default class ChatScreen extends Component { <ide> return ( <ide> <View style={styles.container}> <ide> <ListView <del> ref="listView" <ide> dataSource={this.state.dataSource} <ide> renderRow={this.renderRow} <ide> style={styles.listView} <ide> onLayout={this.scrollToBottom} <ide> /> <ide> <View style={styles.composer}> <ide> <TextInput <del> ref='textInput' <add> ref={(textInput) => { this.textInput = textInput; }} <ide> style={styles.textInput} <del> placeholder='Type a message...' <add> placeholder="Type a message..." <ide> text={this.state.myMessage} <ide> onSubmitEditing={this.onAddMessage} <ide> onChange={this.onMyMessageChange} <ide><path>local-cli/templates/HelloNavigation/views/welcome/WelcomeScreen.js <add>'use strict'; <add> <ide> import React, { Component } from 'react'; <ide> import { <ide> Image, <ide> Platform, <ide> StyleSheet, <del> Text, <ide> } from 'react-native'; <ide> <ide> import ListItem from '../../components/ListItem'; <ide> export default class WelcomeScreen extends Component { <ide> } <ide> <ide> const styles = StyleSheet.create({ <del> container: { <del> backgroundColor: 'white', <del> flex: 1, <del> padding: 16, <del> }, <ide> icon: { <ide> width: 30, <ide> height: 26, <ide><path>local-cli/templates/HelloNavigation/views/welcome/WelcomeText.android.js <add>'use strict'; <add> <ide> import React, { Component } from 'react'; <ide> import { <ide> StyleSheet, <ide><path>local-cli/templates/HelloNavigation/views/welcome/WelcomeText.ios.js <add>'use strict'; <add> <ide> import React, { Component } from 'react'; <ide> import { <ide> StyleSheet,
11
Javascript
Javascript
add lti annotations to xplat/js
037e346197a3c7f99fa93dab68b5a1a94011f1ee
<ide><path>Libraries/Animated/SpringConfig.js <ide> type SpringConfigType = { <ide> ... <ide> }; <ide> <del>function stiffnessFromOrigamiValue(oValue) { <add>function stiffnessFromOrigamiValue(oValue: number) { <ide> return (oValue - 30) * 3.62 + 194; <ide> } <ide> <del>function dampingFromOrigamiValue(oValue) { <add>function dampingFromOrigamiValue(oValue: number) { <ide> return (oValue - 8) * 3 + 25; <ide> } <ide> <ide> function fromBouncinessAndSpeed( <ide> bounciness: number, <ide> speed: number, <ide> ): SpringConfigType { <del> function normalize(value, startValue, endValue) { <add> function normalize(value: number, startValue: number, endValue: number) { <ide> return (value - startValue) / (endValue - startValue); <ide> } <ide> <del> function projectNormal(n, start, end) { <add> function projectNormal(n: number, start: number, end: number) { <ide> return start + n * (end - start); <ide> } <ide> <del> function linearInterpolation(t, start, end) { <add> function linearInterpolation(t: number, start: number, end: number) { <ide> return t * end + (1 - t) * start; <ide> } <ide> <del> function quadraticOutInterpolation(t, start, end) { <add> function quadraticOutInterpolation(t: number, start: number, end: number) { <ide> return linearInterpolation(2 * t - t * t, start, end); <ide> } <ide> <del> function b3Friction1(x) { <add> function b3Friction1(x: number) { <ide> return 0.0007 * Math.pow(x, 3) - 0.031 * Math.pow(x, 2) + 0.64 * x + 1.28; <ide> } <ide> <del> function b3Friction2(x) { <add> function b3Friction2(x: number) { <ide> return 0.000044 * Math.pow(x, 3) - 0.006 * Math.pow(x, 2) + 0.36 * x + 2; <ide> } <ide> <del> function b3Friction3(x) { <add> function b3Friction3(x: number) { <ide> return ( <ide> 0.00000045 * Math.pow(x, 3) - <ide> 0.000332 * Math.pow(x, 2) + <ide> function fromBouncinessAndSpeed( <ide> ); <ide> } <ide> <del> function b3Nobounce(tension) { <add> function b3Nobounce(tension: number) { <ide> if (tension <= 18) { <ide> return b3Friction1(tension); <ide> } else if (tension > 18 && tension <= 44) { <ide><path>Libraries/Animated/bezier.js <ide> const kSampleStepSize = 1.0 / (kSplineTableSize - 1.0); <ide> <ide> const float32ArraySupported = typeof Float32Array === 'function'; <ide> <del>function A(aA1, aA2) { <add>function A(aA1: number, aA2: number) { <ide> return 1.0 - 3.0 * aA2 + 3.0 * aA1; <ide> } <del>function B(aA1, aA2) { <add>function B(aA1: number, aA2: number) { <ide> return 3.0 * aA2 - 6.0 * aA1; <ide> } <del>function C(aA1) { <add>function C(aA1: number) { <ide> return 3.0 * aA1; <ide> } <ide> <ide> // Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2. <del>function calcBezier(aT, aA1, aA2) { <add>function calcBezier(aT: number, aA1: number, aA2: number) { <ide> return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT; <ide> } <ide> <ide> // Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2. <del>function getSlope(aT, aA1, aA2) { <add>function getSlope(aT: number, aA1: number, aA2: number) { <ide> return 3.0 * A(aA1, aA2) * aT * aT + 2.0 * B(aA1, aA2) * aT + C(aA1); <ide> } <ide> <del>function binarySubdivide(aX, _aA, _aB, mX1, mX2) { <add>function binarySubdivide( <add> aX: number, <add> _aA: number, <add> _aB: number, <add> mX1: number, <add> mX2: number, <add>) { <ide> let currentX, <ide> currentT, <ide> i = 0, <ide> function binarySubdivide(aX, _aA, _aB, mX1, mX2) { <ide> return currentT; <ide> } <ide> <del>function newtonRaphsonIterate(aX, _aGuessT, mX1, mX2) { <add>function newtonRaphsonIterate( <add> aX: number, <add> _aGuessT: number, <add> mX1: number, <add> mX2: number, <add>) { <ide> let aGuessT = _aGuessT; <ide> for (let i = 0; i < NEWTON_ITERATIONS; ++i) { <ide> const currentSlope = getSlope(aGuessT, mX1, mX2); <ide> module.exports = function bezier( <ide> } <ide> } <ide> <del> function getTForX(aX) { <add> function getTForX(aX: number) { <ide> let intervalStart = 0.0; <ide> let currentSample = 1; <ide> const lastSample = kSplineTableSize - 1; <ide><path>Libraries/Animated/createAnimatedComponent.js <ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>( <ide> } <ide> }; <ide> <del> _attachProps(nextProps) { <add> _attachProps(nextProps: any) { <ide> const oldPropsAnimated = this._propsAnimated; <ide> <ide> this._propsAnimated = new AnimatedProps( <ide> function createAnimatedComponent<Props: {+[string]: mixed, ...}, Instance>( <ide> this._markUpdateComplete(); <ide> } <ide> <del> UNSAFE_componentWillReceiveProps(newProps) { <add> UNSAFE_componentWillReceiveProps(newProps: any) { <ide> this._waitForUpdate(); <ide> this._attachProps(newProps); <ide> } <ide> <del> componentDidUpdate(prevProps) { <add> componentDidUpdate(prevProps: any) { <ide> if (this._component !== this._prevComponent) { <ide> this._propsAnimated.setNativeView(this._component); <ide> } <ide><path>Libraries/Animated/nodes/AnimatedInterpolation.js <ide> export type InterpolationConfigType = { <ide> extrapolateRight?: ExtrapolateType, <ide> }; <ide> <del>const linear = t => t; <add>const linear = (t: number) => t; <ide> <ide> /** <ide> * Very handy helper to map input ranges to output ranges with an easing <ide> function createInterpolationFromStringOutputRange( <ide> }; <ide> } <ide> <del>function isRgbOrRgba(range) { <add>function isRgbOrRgba(range: string) { <ide> return typeof range === 'string' && range.startsWith('rgb'); <ide> } <ide> <ide><path>Libraries/Animated/nodes/AnimatedStyle.js <ide> class AnimatedStyle extends AnimatedWithChildren { <ide> } <ide> <ide> // Recursively get values for nested styles (like iOS's shadowOffset) <del> _walkStyleAndGetValues(style) { <add> _walkStyleAndGetValues(style: any) { <ide> const updatedStyle = {}; <ide> for (const key in style) { <ide> const value = style[key]; <ide> class AnimatedStyle extends AnimatedWithChildren { <ide> } <ide> <ide> // Recursively get animated values for nested styles (like iOS's shadowOffset) <del> _walkStyleAndGetAnimatedValues(style) { <add> _walkStyleAndGetAnimatedValues(style: any) { <ide> const updatedStyle = {}; <ide> for (const key in style) { <ide> const value = style[key]; <ide><path>Libraries/BugReporting/getReactData.js <ide> function getData(element: Object): Object { <ide> }; <ide> } <ide> <del>function setInProps(internalInst, path: Array<string | number>, value: any) { <add>function setInProps( <add> internalInst: any, <add> path: Array<string | number>, <add> value: any, <add>) { <ide> const element = internalInst._currentElement; <ide> internalInst._currentElement = { <ide> ...element, <ide> function setInProps(internalInst, path: Array<string | number>, value: any) { <ide> internalInst._instance.forceUpdate(); <ide> } <ide> <del>function setInState(inst, path: Array<string | number>, value: any) { <add>function setInState(inst: any, path: Array<string | number>, value: any) { <ide> setIn(inst.state, path, value); <ide> inst.forceUpdate(); <ide> } <ide> <del>function setInContext(inst, path: Array<string | number>, value: any) { <add>function setInContext(inst: any, path: Array<string | number>, value: any) { <ide> setIn(inst.context, path, value); <ide> inst.forceUpdate(); <ide> } <ide> function setIn(obj: Object, path: Array<string | number>, value: any) { <ide> } <ide> } <ide> <del>function childrenList(children) { <add>function childrenList(children: any) { <ide> const res = []; <ide> for (const name in children) { <ide> res.push(children[name]); <ide> } <ide> return res; <ide> } <ide> <del>function copyWithSetImpl(obj, path, idx, value) { <add>function copyWithSetImpl( <add> obj: any | Array<any>, <add> path: Array<string | number>, <add> idx: number, <add> value: any, <add>) { <ide> if (idx >= path.length) { <ide> return value; <ide> } <ide><path>Libraries/Components/DatePicker/DatePickerIOS.ios.js <ide> const styles = StyleSheet.create({ <ide> }, <ide> }); <ide> <del>function getHeight(pickerStyle, mode) { <add>function getHeight( <add> pickerStyle: ?( <add> | 'compact' <add> | 'inline' <add> | 'spinner' <add> | $TEMPORARY$string<'compact'> <add> | $TEMPORARY$string<'inline'> <add> | $TEMPORARY$string<'spinner'> <add> ), <add> mode: <add> | 'date' <add> | 'datetime' <add> | 'time' <add> | $TEMPORARY$string<'date'> <add> | $TEMPORARY$string<'datetime'> <add> | $TEMPORARY$string<'time'>, <add>) { <ide> if (pickerStyle === 'compact') { <ide> return styles.datePickerIOSCompact; <ide> } <ide><path>Libraries/Components/Keyboard/KeyboardAvoidingView.js <ide> import type { <ide> ViewLayout, <ide> ViewLayoutEvent, <ide> } from '../View/ViewPropTypes'; <del>import type {KeyboardEvent} from './Keyboard'; <add>import type {KeyboardEvent, KeyboardEventCoordinates} from './Keyboard'; <ide> <ide> type Props = $ReadOnly<{| <ide> ...ViewProps, <ide> class KeyboardAvoidingView extends React.Component<Props, State> { <ide> this.viewRef = React.createRef(); <ide> } <ide> <del> _relativeKeyboardHeight(keyboardFrame): number { <add> _relativeKeyboardHeight(keyboardFrame: KeyboardEventCoordinates): number { <ide> const frame = this._frame; <ide> if (!frame || !keyboardFrame) { <ide> return 0; <ide><path>Libraries/Components/Keyboard/__tests__/Keyboard-test.js <ide> describe('Keyboard', () => { <ide> }); <ide> <ide> describe('scheduling layout animation', () => { <del> const scheduleLayoutAnimation = (duration, easing): void => <add> const scheduleLayoutAnimation = ( <add> duration: null | number, <add> easing: <add> | null <add> | $TEMPORARY$string<'linear'> <add> | $TEMPORARY$string<'some-unknown-animation-type'> <add> | $TEMPORARY$string<'spring'>, <add> ): void => <ide> // $FlowFixMe[incompatible-call] <ide> Keyboard.scheduleLayoutAnimation({duration, easing}); <ide> <ide> describe('Keyboard', () => { <ide> }); <ide> <ide> describe('animation update type', () => { <del> const assertAnimationUpdateType = type => <add> const assertAnimationUpdateType = ( <add> type: $TEMPORARY$string<'keyboard'> | $TEMPORARY$string<'linear'>, <add> ) => <ide> expect(LayoutAnimation.configureNext).toHaveBeenCalledWith( <ide> expect.objectContaining({ <ide> duration: expect.anything(), <ide><path>Libraries/Components/ScrollView/ScrollViewStickyHeader.js <ide> class ScrollViewStickyHeader extends React.Component<Props, State> { <ide> ); <ide> } <ide> <del> _onLayout = event => { <add> _onLayout = (event: any) => { <ide> const layoutY = event.nativeEvent.layout.y; <ide> const layoutHeight = event.nativeEvent.layout.height; <ide> const measured = true; <ide><path>Libraries/Core/ReactNativeVersionCheck.js <ide> exports.checkVersions = function checkVersions(): void { <ide> } <ide> }; <ide> <del>function _formatVersion(version): string { <add>function _formatVersion( <add> version: <add> | {major: number, minor: number, patch: number, prerelease: ?number} <add> | $TEMPORARY$object<{ <add> major: number, <add> minor: number, <add> patch: number, <add> prerelease: null, <add> }>, <add>): string { <ide> return ( <ide> `${version.major}.${version.minor}.${version.patch}` + <ide> // eslint-disable-next-line eqeqeq <ide><path>Libraries/Core/setUpBatchedBridge.js <ide> if (global.RN$Bridgeless === true && global.RN$registerCallableModule) { <ide> registerModule = global.RN$registerCallableModule; <ide> } else { <ide> const BatchedBridge = require('../BatchedBridge/BatchedBridge'); <del> registerModule = (moduleName, factory) => <del> BatchedBridge.registerLazyCallableModule(moduleName, factory); <add> registerModule = ( <add> moduleName: <add> | $TEMPORARY$string<'GlobalPerformanceLogger'> <add> | $TEMPORARY$string<'HMRClient'> <add> | $TEMPORARY$string<'HeapCapture'> <add> | $TEMPORARY$string<'JSDevSupportModule'> <add> | $TEMPORARY$string<'JSTimers'> <add> | $TEMPORARY$string<'RCTDeviceEventEmitter'> <add> | $TEMPORARY$string<'RCTLog'> <add> | $TEMPORARY$string<'RCTNativeAppEventEmitter'> <add> | $TEMPORARY$string<'SamplingProfiler'> <add> | $TEMPORARY$string<'Systrace'>, <add> factory, <add> ) => BatchedBridge.registerLazyCallableModule(moduleName, factory); <ide> } <ide> <ide> registerModule('Systrace', () => require('../Performance/Systrace')); <ide><path>Libraries/Core/setUpErrorHandling.js <ide> ExceptionsManager.installConsoleErrorReporter(); <ide> <ide> // Set up error handler <ide> if (!global.__fbDisableExceptionsManager) { <del> const handleError = (e, isFatal) => { <add> const handleError = (e: mixed, isFatal: boolean) => { <ide> try { <ide> ExceptionsManager.handleException(e, isFatal); <ide> } catch (ee) { <ide><path>Libraries/Core/setUpTimers.js <ide> if (global.RN$Bridgeless !== true) { <ide> * Set up timers. <ide> * You can use this module directly, or just require InitializeCore. <ide> */ <del> const defineLazyTimer = name => { <add> const defineLazyTimer = ( <add> name: <add> | $TEMPORARY$string<'cancelAnimationFrame'> <add> | $TEMPORARY$string<'cancelIdleCallback'> <add> | $TEMPORARY$string<'clearInterval'> <add> | $TEMPORARY$string<'clearTimeout'> <add> | $TEMPORARY$string<'requestAnimationFrame'> <add> | $TEMPORARY$string<'requestIdleCallback'> <add> | $TEMPORARY$string<'setInterval'> <add> | $TEMPORARY$string<'setTimeout'>, <add> ) => { <ide> polyfillGlobal(name, () => require('./Timers/JSTimers')[name]); <ide> }; <ide> defineLazyTimer('setTimeout'); <ide><path>Libraries/Inspector/Inspector.js <ide> class Inspector extends React.Component< <ide> }, 100); <ide> }; <ide> <del> _onAgentShowNativeHighlight = node => { <add> _onAgentShowNativeHighlight = (node: any) => { <ide> clearTimeout(this._hideTimeoutID); <ide> <ide> // Shape of `node` is different in Fabric. <ide><path>Libraries/Lists/__tests__/VirtualizedSectionList-test.js <ide> describe('VirtualizedSectionList', () => { <ide> describe('scrollToLocation', () => { <ide> const ITEM_HEIGHT = 100; <ide> <del> const createVirtualizedSectionList = props => { <add> const createVirtualizedSectionList = ( <add> props: void | $TEMPORARY$object<{stickySectionHeadersEnabled: boolean}>, <add> ) => { <ide> const component = ReactTestRenderer.create( <ide> <VirtualizedSectionList <ide> sections={[ <ide><path>Libraries/LogBox/LogBox.js <ide> if (__DEV__) { <ide> }, <ide> }; <ide> <del> const isRCTLogAdviceWarning = (...args) => { <add> const isRCTLogAdviceWarning = (...args: Array<mixed>) => { <ide> // RCTLogAdvice is a native logging function designed to show users <ide> // a message in the console, but not show it to them in Logbox. <ide> return typeof args[0] === 'string' && args[0].startsWith('(ADVICE)'); <ide> }; <ide> <del> const isWarningModuleWarning = (...args) => { <add> const isWarningModuleWarning = (...args: any) => { <ide> return typeof args[0] === 'string' && args[0].startsWith('Warning: '); <ide> }; <ide> <del> const registerWarning = (...args): void => { <add> const registerWarning = (...args: Array<mixed>): void => { <ide> // Let warnings within LogBox itself fall through. <ide> if (LogBoxData.isLogBoxErrorMessage(String(args[0]))) { <ide> originalConsoleError(...args); <ide><path>Libraries/LogBox/UI/LogBoxInspector.js <ide> const headerTitleMap = { <ide> component: 'Render Error', <ide> }; <ide> <del>function LogBoxInspectorBody(props) { <add>function LogBoxInspectorBody( <add> props: $TEMPORARY$object<{log: LogBoxLog, onRetry: () => void}>, <add>) { <ide> const [collapsed, setCollapsed] = React.useState(true); <ide> <ide> React.useEffect(() => { <ide><path>Libraries/LogBox/UI/LogBoxInspectorReactFrames.js <ide> type Props = $ReadOnly<{| <ide> const BEFORE_SLASH_RE = /^(.*)[\\/]/; <ide> <ide> // Taken from React https://github.com/facebook/react/blob/206d61f72214e8ae5b935f0bf8628491cb7f0797/packages/react-devtools-shared/src/backend/describeComponentFrame.js#L27-L41 <del>function getPrettyFileName(path) { <add>function getPrettyFileName(path: string) { <ide> let fileName = path.replace(BEFORE_SLASH_RE, ''); <ide> <ide> // In DEV, include code for a common special case: <ide><path>Libraries/LogBox/UI/LogBoxInspectorStackFrame.js <ide> function LogBoxInspectorStackFrame(props: Props): React.Node { <ide> ); <ide> } <ide> <del>function getFileName(file) { <add>function getFileName(file: ?string) { <ide> if (file == null) { <ide> return '<unknown>'; <ide> } <ide><path>Libraries/LogBox/UI/LogBoxInspectorStackFrames.js <ide> function StackFrameList(props) { <ide> ); <ide> } <ide> <del>function StackFrameFooter(props) { <add>function StackFrameFooter( <add> props: $TEMPORARY$object<{message: string, onPress: () => void}>, <add>) { <ide> return ( <ide> <View style={stackStyles.collapseContainer}> <ide> <LogBoxButton <ide><path>Libraries/LogBox/UI/LogBoxMessage.js <ide> type Props = { <ide> ... <ide> }; <ide> <del>const cleanContent = content => <add>const cleanContent = (content: string) => <ide> content.replace(/^(TransformError |Warning: (Warning: )?|Error: )/g, ''); <ide> <ide> function LogBoxMessage(props: Props): React.Node { <ide> function LogBoxMessage(props: Props): React.Node { <ide> const substitutionStyle: TextStyleProp = props.style; <ide> const elements = []; <ide> let length = 0; <del> const createUnderLength = (key, message, style) => { <add> const createUnderLength = ( <add> key: string | $TEMPORARY$string<'-1'>, <add> message: string, <add> style: void | TextStyleProp, <add> ) => { <ide> let cleanMessage = cleanContent(message); <ide> <ide> if (props.maxLength != null) { <ide><path>Libraries/Performance/Systrace.js <ide> const userTimingPolyfill = __DEV__ <ide> } <ide> : null; <ide> <del>function installPerformanceHooks(polyfill) { <add>function installPerformanceHooks( <add> polyfill: null | $TEMPORARY$object<{ <add> clearMarks(markName: string): void, <add> clearMeasures(): void, <add> mark(markName: string): void, <add> measure(measureName: string, startMark: ?string, endMark: ?string): void, <add> }>, <add>) { <ide> if (polyfill) { <ide> if (global.performance === undefined) { <ide> global.performance = {}; <ide><path>Libraries/ReactNative/getCachedComponentWithDebugName.js <ide> export default function getCachedComponentWithDisplayName( <ide> let ComponentWithDisplayName = cache.get(displayName); <ide> <ide> if (!ComponentWithDisplayName) { <del> ComponentWithDisplayName = ({children}) => children; <add> ComponentWithDisplayName = ({ <add> children, <add> }: $TEMPORARY$object<{children: Node}>) => children; <ide> ComponentWithDisplayName.displayName = displayName; <ide> cache.set(displayName, ComponentWithDisplayName); <ide> } <ide><path>Libraries/StyleSheet/processTransform.js <ide> function _validateTransforms(transform: Array<Object>): void { <ide> }); <ide> } <ide> <del>function _validateTransform(key, value, transformation) { <add>function _validateTransform( <add> key: <add> | string <add> | $TEMPORARY$string<'matrix'> <add> | $TEMPORARY$string<'perspective'> <add> | $TEMPORARY$string<'rotate'> <add> | $TEMPORARY$string<'rotateX'> <add> | $TEMPORARY$string<'rotateY'> <add> | $TEMPORARY$string<'rotateZ'> <add> | $TEMPORARY$string<'scale'> <add> | $TEMPORARY$string<'scaleX'> <add> | $TEMPORARY$string<'scaleY'> <add> | $TEMPORARY$string<'skewX'> <add> | $TEMPORARY$string<'skewY'> <add> | $TEMPORARY$string<'translate'> <add> | $TEMPORARY$string<'translateX'> <add> | $TEMPORARY$string<'translateY'>, <add> value: any | number | string, <add> transformation: any, <add>) { <ide> invariant( <ide> !value.getValue, <ide> 'You passed an Animated.Value to a normal component. ' + <ide><path>Libraries/Utilities/__tests__/useRefEffect-test.js <ide> import {act, create} from 'react-test-renderer'; <ide> /** <ide> * TestView provide a component execution environment to test hooks. <ide> */ <del>function TestView({childKey = null, effect}) { <add>function TestView({ <add> childKey = null, <add> effect, <add>}: <add> | $FlowFixMe <add> | $TEMPORARY$object<{ <add> childKey: $TEMPORARY$string<'bar'>, <add> effect: () => () => void, <add> }> <add> | $TEMPORARY$object<{childKey: $TEMPORARY$string<'foo'>, effect: () => void}> <add> | $TEMPORARY$object<{ <add> childKey: $TEMPORARY$string<'foo'>, <add> effect: () => () => void, <add> }>) { <ide> const ref = useRefEffect(effect); <ide> return <View key={childKey} ref={ref} testID={childKey} />; <ide> } <ide><path>Libraries/Utilities/deepFreezeAndThrowOnMutationInDev.js <ide> function deepFreezeAndThrowOnMutationInDev<T: {...} | Array<mixed>>( <ide> return object; <ide> } <ide> <del>function throwOnImmutableMutation(key, value) { <add>function throwOnImmutableMutation(key: empty, value) { <ide> throw Error( <ide> 'You attempted to set the key `' + <ide> key + <ide> function throwOnImmutableMutation(key, value) { <ide> ); <ide> } <ide> <del>function identity(value) { <add>function identity(value: mixed) { <ide> return value; <ide> } <ide> <ide><path>Libraries/Utilities/useWindowDimensions.js <ide> export default function useWindowDimensions(): <ide> | DisplayMetricsAndroid { <ide> const [dimensions, setDimensions] = useState(() => Dimensions.get('window')); <ide> useEffect(() => { <del> function handleChange({window}) { <add> function handleChange({ <add> window, <add> }: <add> | $FlowFixMe <add> | $TEMPORARY$object<{window: DisplayMetrics | DisplayMetricsAndroid}>) { <ide> if ( <ide> dimensions.width !== window.width || <ide> dimensions.height !== window.height || <ide><path>Libraries/Utilities/verifyComponentAttributeEquivalence.js <ide> export default function verifyComponentAttributeEquivalence( <ide> export function lefthandObjectDiff(leftObj: Object, rightObj: Object): Object { <ide> const differentKeys = {}; <ide> <del> function compare(leftItem, rightItem, key) { <add> function compare(leftItem: any, rightItem: any, key: string) { <ide> if (typeof leftItem !== typeof rightItem && leftItem != null) { <ide> differentKeys[key] = rightItem; <ide> return; <ide><path>packages/react-native-codegen/src/cli/combine/combine-js-to-schema-cli.js <ide> const path = require('path'); <ide> <ide> const [outfile, ...fileList] = process.argv.slice(2); <ide> <del>function filterJSFile(file) { <add>function filterJSFile(file: string) { <ide> return ( <ide> /^(Native.+|.+NativeComponent)/.test(path.basename(file)) && <ide> // NativeUIManager will be deprecated by Fabric UIManager. <ide><path>packages/react-native-codegen/src/generators/components/JavaHelpers.js <ide> function getImports( <ide> } <ide> }); <ide> <del> function addImportsForNativeName(name) { <add> function addImportsForNativeName( <add> name: <add> | 'ColorPrimitive' <add> | 'EdgeInsetsPrimitive' <add> | 'ImageSourcePrimitive' <add> | 'PointPrimitive' <add> | $TEMPORARY$string<'ColorPrimitive'> <add> | $TEMPORARY$string<'EdgeInsetsPrimitive'> <add> | $TEMPORARY$string<'ImageSourcePrimitive'> <add> | $TEMPORARY$string<'PointPrimitive'>, <add> ) { <ide> switch (name) { <ide> case 'ColorPrimitive': <ide> if (type === 'delegate') { <ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/header/serializeConstantsStruct.js <ide> function toObjCValue( <ide> depth + 1, <ide> ); <ide> <del> const RCTConvertVecToArray = transformer => { <add> const RCTConvertVecToArray = (transformer: string) => { <ide> return `RCTConvert${ <ide> !isRequired ? 'Optional' : '' <ide> }VecToArray(${value}, ${transformer})`; <ide><path>packages/react-native-codegen/src/generators/modules/GenerateModuleObjCpp/index.js <ide> */ <ide> <ide> 'use strict'; <add>import type {NativeModulePropertyShape} from '../../../CodegenSchema'; <ide> <ide> import type {SchemaType} from '../../../CodegenSchema'; <ide> import type {MethodSerializationOutput} from './serializeMethod'; <ide> module.exports = { <ide> const structCollector = new StructCollector(); <ide> <ide> const methodSerializations: Array<MethodSerializationOutput> = []; <del> const serializeProperty = property => { <add> const serializeProperty = (property: NativeModulePropertyShape) => { <ide> methodSerializations.push( <ide> ...serializeMethod( <ide> hasteModuleName, <ide><path>packages/react-native-codegen/src/parsers/flow/components/commands.js <ide> const {getValueFromTypes} = require('../utils.js'); <ide> <ide> type EventTypeAST = Object; <ide> <del>function buildCommandSchema(property, types: TypeDeclarationMap) { <add>function buildCommandSchema(property: EventTypeAST, types: TypeDeclarationMap) { <ide> const name = property.key.name; <ide> const optional = property.optional; <ide> const value = getValueFromTypes(property.value, types); <ide><path>packages/react-native-codegen/src/parsers/flow/components/index.js <ide> */ <ide> <ide> 'use strict'; <add>import type {CommandOptions} from './options'; <add>import type {TypeDeclarationMap} from '../utils'; <ide> <ide> import type {ComponentSchemaBuilderConfig} from './schema.js'; <ide> const {getCommands} = require('./commands'); <ide> function findComponentConfig(ast) { <ide> }; <ide> } <ide> <del>function getCommandProperties(commandTypeName, types, commandOptions) { <add>function getCommandProperties( <add> commandTypeName, <add> types: TypeDeclarationMap, <add> commandOptions: ?CommandOptions, <add>) { <ide> if (commandTypeName == null) { <ide> return []; <ide> } <ide><path>packages/react-native-codegen/src/parsers/flow/components/props.js <ide> function getPropProperties( <ide> } <ide> } <ide> <del>function getTypeAnnotationForArray(name, typeAnnotation, defaultValue, types) { <add>function getTypeAnnotationForArray( <add> name: string, <add> typeAnnotation: $FlowFixMe, <add> defaultValue: $FlowFixMe | null, <add> types: TypeDeclarationMap, <add>) { <ide> const extractedTypeAnnotation = getValueFromTypes(typeAnnotation, types); <ide> if (extractedTypeAnnotation.type === 'NullableTypeAnnotation') { <ide> throw new Error( <ide> function getTypeAnnotationForArray(name, typeAnnotation, defaultValue, types) { <ide> } <ide> <ide> function getTypeAnnotation( <del> name, <add> name: string, <ide> annotation, <del> defaultValue, <del> withNullDefault, <del> types, <add> defaultValue: $FlowFixMe | null, <add> withNullDefault: boolean, <add> types: TypeDeclarationMap, <ide> ) { <ide> const typeAnnotation = getValueFromTypes(annotation, types); <ide> <ide> function getTypeAnnotation( <ide> } <ide> <ide> function buildPropSchema( <del> property, <add> property: PropAST, <ide> types: TypeDeclarationMap, <ide> ): ?NamedShape<PropTypeAnnotation> { <ide> const name = property.key.name; <ide><path>packages/react-native-codegen/src/parsers/flow/modules/errors.js <ide> class MoreThanOneModuleFlowInterfaceParserError extends ParserError { <ide> ) { <ide> const finalName = names[names.length - 1]; <ide> const allButLastName = names.slice(0, -1); <del> const quote = x => `'${x}'`; <add> const quote = (x: string) => `'${x}'`; <ide> <ide> const nameStr = <ide> allButLastName.map(quote).join(', ') + ', and ' + quote(finalName); <ide><path>packages/rn-tester/js/components/RNTesterExampleFilter.js <ide> class RNTesterExampleFilter<T> extends React.Component<Props<T>, State> { <ide> ); <ide> } <ide> <del> const filter = example => { <add> const filter = (example: T) => { <ide> const category = this.state.category; <ide> return ( <ide> this.props.disableSearch || <ide> class RNTesterExampleFilter<T> extends React.Component<Props<T>, State> { <ide> ); <ide> } <ide> <del> _renderFilteredSections(filteredSections): ?React.Element<any> { <add> _renderFilteredSections( <add> filteredSections: Array< <add> $TEMPORARY$object<{data: Array<T>, key: string, title: string}>, <add> >, <add> ): ?React.Element<any> { <ide> if (this.props.page === 'examples_page') { <ide> return ( <ide> <ScrollView <ide><path>packages/rn-tester/js/components/RNTesterModuleContainer.js <ide> type Props = { <ide> onExampleCardPress?: ?(exampleName: string) => mixed, <ide> }; <ide> <del>function getExampleTitle(title, platform) { <add>function getExampleTitle(title: $FlowFixMe, platform: $FlowFixMe) { <ide> return platform != null ? `${title} (${platform} only)` : title; <ide> } <ide> <ide> export default function RNTesterModuleContainer(props: Props): React.Node { <ide> const {module, example, onExampleCardPress} = props; <ide> const theme = React.useContext(RNTesterThemeContext); <del> const renderExample = (e, i) => { <add> const renderExample = (e: $FlowFixMe, i: $FlowFixMe) => { <ide> // Filter platform-specific es <ide> const {title, description, platform, render: ExampleComponent} = e; <ide> if (platform != null && Platform.OS !== platform) { <ide> export default function RNTesterModuleContainer(props: Props): React.Node { <ide> ); <ide> } <ide> <del> const filter = ({example: e, filterRegex}) => filterRegex.test(e.title); <add> const filter = ({example: e, filterRegex}: $FlowFixMe) => <add> filterRegex.test(e.title); <ide> <ide> const sections = [ <ide> { <ide><path>packages/rn-tester/js/components/RNTesterModuleList.js <ide> const ExampleModuleRow = ({ <ide> ); <ide> }; <ide> <del>const renderSectionHeader = ({section}) => ( <add>const renderSectionHeader = ({section}: {section: any, ...}) => ( <ide> <RNTesterThemeContext.Consumer> <ide> {theme => { <ide> return ( <ide> const renderSectionHeader = ({section}) => ( <ide> <ide> const RNTesterModuleList: React$AbstractComponent<any, void> = React.memo( <ide> ({sections, toggleBookmark, handleModuleCardPress}) => { <del> const filter = ({example, filterRegex, category}) => <add> const filter = ({example, filterRegex, category}: any) => <ide> filterRegex.test(example.module.title) && <ide> (!category || example.category === category) && <ide> (!Platform.isTV || example.supportsTVOS); <ide><path>packages/rn-tester/js/components/RNTesterNavbar.js <ide> * @flow <ide> */ <ide> <add>import type {RNTesterTheme} from './RNTesterTheme'; <add> <ide> import * as React from 'react'; <ide> import {Text, View, StyleSheet, Image, Pressable} from 'react-native'; <ide> <ide> import {RNTesterThemeContext} from './RNTesterTheme'; <ide> <del>const BookmarkTab = ({handleNavBarPress, isBookmarkActive, theme}) => ( <add>const BookmarkTab = ({ <add> handleNavBarPress, <add> isBookmarkActive, <add> theme, <add>}: $TEMPORARY$object<{ <add> handleNavBarPress: (data: {screen: string}) => void, <add> isBookmarkActive: boolean, <add> theme: RNTesterTheme, <add>}>) => ( <ide> <View style={styles.centerBox}> <ide> <View <ide> style={[ <ide> const NavbarButton = ({ <ide> </Pressable> <ide> ); <ide> <del>const ComponentTab = ({isComponentActive, handleNavBarPress, theme}) => ( <add>const ComponentTab = ({ <add> isComponentActive, <add> handleNavBarPress, <add> theme, <add>}: $TEMPORARY$object<{ <add> handleNavBarPress: (data: {screen: string}) => void, <add> isComponentActive: boolean, <add> theme: RNTesterTheme, <add>}>) => ( <ide> <NavbarButton <ide> testID="components-tab" <ide> label="Components" <ide> const ComponentTab = ({isComponentActive, handleNavBarPress, theme}) => ( <ide> /> <ide> ); <ide> <del>const APITab = ({isAPIActive, handleNavBarPress, theme}) => ( <add>const APITab = ({ <add> isAPIActive, <add> handleNavBarPress, <add> theme, <add>}: $TEMPORARY$object<{ <add> handleNavBarPress: (data: {screen: string}) => void, <add> isAPIActive: boolean, <add> theme: RNTesterTheme, <add>}>) => ( <ide> <NavbarButton <ide> testID="apis-tab" <ide> label="APIs" <ide><path>packages/rn-tester/js/examples/Accessibility/AccessibilityExample.js <ide> <ide> 'use strict'; <ide> <add>import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes'; <add> <ide> const React = require('react'); <ide> const { <ide> AccessibilityInfo, <ide> class EnabledExample extends React.Component< <ide> this._subscription?.remove(); <ide> } <ide> <del> _handleToggled = isEnabled => { <add> _handleToggled = (isEnabled: void | PressEvent | boolean) => { <ide> if (!this.state.isEnabled) { <ide> this.setState({isEnabled: true}); <ide> } else { <ide><path>packages/rn-tester/js/examples/Alert/AlertIOSExample.js <ide> type State = {|promptValue: ?string|}; <ide> class PromptOptions extends React.Component<Props, State> { <ide> customButtons: Array<Object>; <ide> <del> constructor(props) { <add> constructor(props: void | Props) { <ide> super(props); <ide> <ide> /* $FlowFixMe[cannot-write] this seems to be a Flow bug, `saveResponse` is <ide> class PromptOptions extends React.Component<Props, State> { <ide> ); <ide> } <ide> <del> saveResponse(promptValue) { <add> saveResponse(promptValue: any) { <ide> this.setState({promptValue: JSON.stringify(promptValue)}); <ide> } <ide> } <ide><path>packages/rn-tester/js/examples/Animated/ComposingExample.js <ide> <ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; <ide> import type {CompositeAnimation} from 'react-native/Libraries/Animated/AnimatedMock'; <add>import type AnimatedValue from 'react-native/Libraries/Animated/nodes/AnimatedValue'; <ide> import * as React from 'react'; <ide> import RNTesterButton from '../../components/RNTesterButton'; <ide> import ToggleNativeDriver from './utils/ToggleNativeDriver'; <ide> const items = [ <ide> { <ide> title: 'Parallel', <ide> description: 'Starts a number of animations at the same time', <del> compositeAnimation: (values, useNativeDriver) => <add> compositeAnimation: ( <add> values: Array<AnimatedValue>, <add> useNativeDriver: boolean, <add> ) => <ide> Animated.sequence([ <ide> Animated.parallel( <ide> values.map(value => <ide> const items = [ <ide> title: 'Sequence', <ide> description: <ide> 'Starts the animations in order, waiting for each to complete before starting the next', <del> compositeAnimation: (values, useNativeDriver) => <add> compositeAnimation: ( <add> values: Array<AnimatedValue>, <add> useNativeDriver: boolean, <add> ) => <ide> Animated.sequence([ <ide> Animated.sequence( <ide> values.map(value => <ide> const items = [ <ide> title: 'Stagger', <ide> description: <ide> 'Starts animations in order and in parallel, but with successive delays', <del> compositeAnimation: (values, useNativeDriver) => <add> compositeAnimation: ( <add> values: Array<AnimatedValue>, <add> useNativeDriver: boolean, <add> ) => <ide> Animated.sequence([ <ide> Animated.stagger( <ide> 150, <ide> const items = [ <ide> { <ide> title: 'Delay', <ide> description: 'Starts an animation after a given delay', <del> compositeAnimation: (values, useNativeDriver) => <add> compositeAnimation: ( <add> values: Array<AnimatedValue>, <add> useNativeDriver: boolean, <add> ) => <ide> Animated.sequence([ <ide> Animated.delay(2000), <ide> Animated.parallel( <ide><path>packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExBobble.js <ide> class AnExBobble extends React.Component<Object, any> { <ide> return new Animated.ValueXY(); <ide> }); <ide> this.state.selectedBobble = null; <del> const bobblePanListener = (e, gestureState) => { <add> const bobblePanListener = (e: any, gestureState: any) => { <ide> // async events => change selection <ide> const newSelected = computeNewSelected(gestureState); <ide> if (this.state.selectedBobble !== newSelected) { <ide><path>packages/rn-tester/js/examples/AnimatedGratuitousApp/AnExChained.js <ide> <ide> 'use strict'; <ide> <add>import type {PressEvent} from 'react-native/Libraries/Types/CoreEventTypes'; <add>import type {GestureState} from 'react-native/Libraries/Interaction/PanResponder'; <add> <ide> const React = require('react'); <ide> <ide> const {Animated, PanResponder, StyleSheet, View} = require('react-native'); <ide> class AnExChained extends React.Component<Object, any> { <ide> }).start(); <ide> this.state.stickers.push(sticker); // push on the followers <ide> } <del> const releaseChain = (e, gestureState) => { <add> const releaseChain = (e: PressEvent, gestureState: GestureState) => { <ide> this.state.stickers[0].flattenOffset(); // merges offset into value and resets <ide> Animated.sequence([ <ide> // spring to start after decay finishes <ide><path>packages/rn-tester/js/examples/AppState/AppStateExample.js <ide> <ide> 'use strict'; <ide> <add>import type {AppStateValues} from 'react-native/Libraries/AppState/AppState'; <add> <ide> const React = require('react'); <ide> <ide> import {type EventSubscription} from 'react-native/Libraries/vendor/emitter/EventEmitter'; <ide> class AppStateSubscription extends React.Component< <ide> this.setState({eventsDetected}); <ide> }; <ide> <del> _handleAppStateChange = appState => { <add> _handleAppStateChange = (appState: AppStateValues) => { <ide> const previousAppStates = this.state.previousAppStates.slice(); <ide> previousAppStates.push(this.state.appState); <ide> this.setState({ <ide><path>packages/rn-tester/js/examples/FlatList/BaseFlatListExample.js <ide> * @format <ide> */ <ide> <add>import type {RenderItemProps} from 'react-native/Libraries/Lists/VirtualizedList'; <ide> import { <ide> Pressable, <ide> Button, <ide> const DATA = [ <ide> 'Ice Cream', <ide> ]; <ide> <del>const Item = ({item, separators}) => { <add>const Item = ({item, separators}: RenderItemProps<string>) => { <ide> return ( <ide> <Pressable <ide> onPressIn={() => { <ide><path>packages/rn-tester/js/examples/FlatList/FlatList-basic.js <ide> <ide> 'use strict'; <ide> <add>import type {AnimatedComponentType} from 'react-native/Libraries/Animated/createAnimatedComponent'; <add>import typeof FlatListType from 'react-native/Libraries/Lists/FlatList'; <add> <ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; <ide> import * as React from 'react'; <ide> import { <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> this.setState({filterText}); <ide> }; <ide> <del> _onChangeScrollToIndex = text => { <add> _onChangeScrollToIndex = (text: mixed) => { <ide> this._listRef.scrollToIndex({viewPosition: 0.5, index: Number(text)}); <ide> }; <ide> <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> <ide> render(): React.Node { <ide> const filterRegex = new RegExp(String(this.state.filterText), 'i'); <del> const filter = item => <add> const filter = (item: Item) => <ide> filterRegex.test(item.text) || filterRegex.test(item.title); <ide> const filteredData = this.state.data.filter(filter); <ide> const flatListItemRendererProps = this._renderItemComponent(); <ide> class FlatListExample extends React.PureComponent<Props, State> { <ide> </RNTesterPage> <ide> ); <ide> } <del> _captureRef = ref => { <add> _captureRef = ( <add> ref: React.ElementRef< <add> AnimatedComponentType< <add> React.ElementConfig<FlatListType>, <add> React.ElementRef<FlatListType>, <add> >, <add> >, <add> ) => { <ide> this._listRef = ref; <ide> }; <ide> _getItemLayout = (data: any, index: number) => { <ide><path>packages/rn-tester/js/examples/FlatList/FlatList-multiColumn.js <ide> */ <ide> <ide> 'use strict'; <add> <add>import type {RenderItemProps} from 'react-native/Libraries/Lists/VirtualizedList'; <ide> import type {RNTesterModuleExample} from '../../types/RNTesterTypes'; <ide> const RNTesterPage = require('../../components/RNTesterPage'); <ide> const React = require('react'); <ide> class MultiColumnExample extends React.PureComponent< <ide> _onChangeFilterText = filterText => { <ide> this.setState(() => ({filterText})); <ide> }; <del> _onChangeNumColumns = numColumns => { <add> _onChangeNumColumns = (numColumns: mixed) => { <ide> this.setState(() => ({numColumns: Number(numColumns)})); <ide> }; <ide> <ide> class MultiColumnExample extends React.PureComponent< <ide> <ide> render(): React.Node { <ide> const filterRegex = new RegExp(String(this.state.filterText), 'i'); <del> const filter = item => <add> const filter = (item: any | Item) => <ide> filterRegex.test(item.text) || filterRegex.test(item.title); <ide> const filteredData = this.state.data.filter(filter); <ide> return ( <ide> class MultiColumnExample extends React.PureComponent< <ide> getItemLayout(data, index).length + 2 * (CARD_MARGIN + BORDER_WIDTH); <ide> return {length, offset: length * index, index}; <ide> } <del> _renderItemComponent = ({item}) => { <add> _renderItemComponent = ({item}: RenderItemProps<any | Item>) => { <ide> return ( <ide> <View style={styles.card}> <ide> <ItemComponent <ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewPressableStickyHeaderExample.js <ide> function StickyHeader() { <ide> ); <ide> } <ide> <del>function renderComponent1(i) { <add>function renderComponent1(i: number) { <ide> return ( <ide> <View <ide> key={i} <ide><path>packages/rn-tester/js/examples/XHR/XHRExampleAbortController.js <ide> const {Alert, Button, View} = require('react-native'); <ide> class XHRExampleAbortController extends React.Component<{...}, {...}> { <ide> _timeout: any; <ide> <del> _submit(abortDelay) { <add> _submit(abortDelay: number) { <ide> clearTimeout(this._timeout); <ide> const abortController = new global.AbortController(); <ide> fetch('https://reactnative.dev/', { <ide><path>packages/rn-tester/js/examples/XHR/XHRExampleDownload.js <ide> class XHRExampleDownload extends React.Component<{...}, Object> { <ide> }); <ide> } <ide> }; <del> const onprogress = event => { <add> const onprogress = (event: ProgressEvent) => { <ide> this.setState({ <ide> progressTotal: event.total, <ide> progressLoaded: event.loaded,
53
PHP
PHP
convert schemacache shell into commands
f29ff30974c4d6324d1ad7ac1a017093d610f75b
<ide><path>src/Command/SchemacacheBuildCommand.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.6.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Command; <add> <add>use Cake\Console\Arguments; <add>use Cake\Console\Command; <add>use Cake\Console\ConsoleIo; <add>use Cake\Console\ConsoleOptionParser; <add>use Cake\Database\SchemaCache; <add>use Cake\Datasource\ConnectionManager; <add>use RuntimeException; <add> <add>/** <add> * Provides CLI tool for updating schema cache. <add> */ <add>class SchemacacheBuildCommand extends Command <add>{ <add> /** <add> * Display all routes in an application <add> * <add> * @param \Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return null|int The exit code or null for success <add> */ <add> public function execute(Arguments $args, ConsoleIo $io): ?int <add> { <add> try { <add> /** @var \Cake\Database\Connection $connection */ <add> $connection = ConnectionManager::get($args->getOption('connection')); <add> <add> $cache = new SchemaCache($connection); <add> } catch (RuntimeException $e) { <add> $io->error($e->getMessage()); <add> $this->abort(); <add> } <add> $tables = $cache->build($args->getArgument('name')); <add> <add> foreach ($tables as $table) { <add> $io->verbose(sprintf('Cached "%s"', $table)); <add> } <add> <add> $io->out('<success>Cache build complete</success>'); <add> <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the option parser. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The option parser to update <add> * @return \Cake\Console\ConsoleOptionParser <add> */ <add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser <add> { <add> $parser->setDescription( <add> 'Build all metadata caches for the connection. If a ' . <add> 'table name is provided, only that table will be cached.' <add> )->addOption('connection', [ <add> 'help' => 'The connection to build/clear metadata cache data for.', <add> 'short' => 'c', <add> 'default' => 'default', <add> ])->addArgument('name', [ <add> 'help' => 'A specific table you want to refresh cached data for.', <add> 'optional' => true, <add> ]); <add> <add> return $parser; <add> } <add>} <ide><path>src/Command/SchemacacheClearCommand.php <add><?php <add>declare(strict_types=1); <add> <add>/** <add> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <add> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * <add> * Licensed under The MIT License <add> * For full copyright and license information, please see the LICENSE.txt <add> * Redistributions of files must retain the above copyright notice. <add> * <add> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <add> * @link https://cakephp.org CakePHP(tm) Project <add> * @since 3.6.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Command; <add> <add>use Cake\Console\Arguments; <add>use Cake\Console\Command; <add>use Cake\Console\ConsoleIo; <add>use Cake\Console\ConsoleOptionParser; <add>use Cake\Database\SchemaCache; <add>use Cake\Datasource\ConnectionManager; <add>use RuntimeException; <add> <add>/** <add> * Provides CLI tool for clearing schema cache. <add> */ <add>class SchemacacheClearCommand extends Command <add>{ <add> /** <add> * Display all routes in an application <add> * <add> * @param \Cake\Console\Arguments $args The command arguments. <add> * @param \Cake\Console\ConsoleIo $io The console io <add> * @return null|int The exit code or null for success <add> */ <add> public function execute(Arguments $args, ConsoleIo $io): ?int <add> { <add> try { <add> /** @var \Cake\Database\Connection $connection */ <add> $connection = ConnectionManager::get($args->getOption('connection')); <add> <add> $cache = new SchemaCache($connection); <add> } catch (RuntimeException $e) { <add> $io->error($e->getMessage()); <add> $this->abort(); <add> } <add> $tables = $cache->clear($args->getArgument('name')); <add> <add> foreach ($tables as $table) { <add> $io->verbose(sprintf('Cleared "%s"', $table)); <add> } <add> <add> $io->out('<success>Cache clear complete</success>'); <add> <add> return static::CODE_SUCCESS; <add> } <add> <add> /** <add> * Get the option parser. <add> * <add> * @param \Cake\Console\ConsoleOptionParser $parser The option parser to update <add> * @return \Cake\Console\ConsoleOptionParser <add> */ <add> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser <add> { <add> $parser->setDescription( <add> 'Clear all metadata caches for the connection. If a ' . <add> 'table name is provided, only that table will be removed.' <add> )->addOption('connection', [ <add> 'help' => 'The connection to build/clear metadata cache data for.', <add> 'short' => 'c', <add> 'default' => 'default', <add> ])->addArgument('name', [ <add> 'help' => 'A specific table you want to clear cached data for.', <add> 'optional' => true, <add> ]); <add> <add> return $parser; <add> } <add>} <ide><path>src/Console/CommandScanner.php <ide> protected function inflectCommandNames(array $commands): array <ide> $command['name'] = str_replace('_', ' ', $command['name']); <ide> $command['fullName'] = str_replace('_', ' ', $command['fullName']); <ide> $commands[$i] = $command; <add> <add> // Maintain backwards compatibility for schema_cache as it is likely <add> // hooked up to people's deploy tooling <add> if (strpos($command['name'], 'schemacache') === 0) { <add> $compat = [ <add> 'name' => str_replace('schemacache', 'schema_cache', $command['name']), <add> 'fullName' => str_replace('schemacache', 'schema_cache', $command['fullName']), <add> ]; <add> $commands[] = $compat + $command; <add> } <ide> } <ide> <ide> return $commands; <ide><path>src/Shell/SchemaCacheShell.php <del><?php <del>declare(strict_types=1); <del> <del>/** <del> * CakePHP(tm) : Rapid Development Framework (https://cakephp.org) <del> * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * <del> * Licensed under The MIT License <del> * For full copyright and license information, please see the LICENSE.txt <del> * Redistributions of files must retain the above copyright notice. <del> * <del> * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org) <del> * @link https://cakephp.org CakePHP(tm) Project <del> * @since 3.6.0 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace Cake\Shell; <del> <del>use Cake\Console\ConsoleOptionParser; <del>use Cake\Console\Shell; <del>use Cake\Database\SchemaCache; <del>use Cake\Datasource\ConnectionManager; <del>use RuntimeException; <del> <del>/** <del> * Schema Cache Shell. <del> * <del> * Provides a CLI interface to the schema metadata caching features. <del> * This tool is intended to be used by deployment scripts so that you <del> * can prevent "thundering herd" effect on the metadata cache when new <del> * versions of your application is deployed, or when migrations <del> * requiring updated metadata are required. <del> */ <del>class SchemaCacheShell extends Shell <del>{ <del> /** <del> * Build metadata. <del> * <del> * @param string|null $name The name of the table to build cache data for. <del> * @return bool <del> */ <del> public function build(?string $name = null): bool <del> { <del> $cache = $this->_getSchemaCache(); <del> $tables = $cache->build($name); <del> <del> foreach ($tables as $table) { <del> $this->verbose(sprintf('Cached "%s"', $table)); <del> } <del> <del> $this->out('<success>Cache build complete</success>'); <del> <del> return true; <del> } <del> <del> /** <del> * Clear metadata. <del> * <del> * @param string|null $name The name of the table to clear cache data for. <del> * @return void <del> */ <del> public function clear(?string $name = null): void <del> { <del> $cache = $this->_getSchemaCache(); <del> $tables = $cache->clear($name); <del> <del> foreach ($tables as $table) { <del> $this->verbose(sprintf('Cleared "%s"', $table)); <del> } <del> <del> $this->out('<success>Cache clear complete</success>'); <del> } <del> <del> /** <del> * Gets the Schema Cache instance <del> * <del> * @return \Cake\Database\SchemaCache <del> */ <del> protected function _getSchemaCache(): SchemaCache <del> { <del> try { <del> /** @var \Cake\Database\Connection $connection */ <del> $connection = ConnectionManager::get($this->params['connection']); <del> <del> return new SchemaCache($connection); <del> } catch (RuntimeException $e) { <del> $this->abort($e->getMessage()); <del> } <del> } <del> <del> /** <del> * Get the option parser for this shell. <del> * <del> * @return \Cake\Console\ConsoleOptionParser <del> */ <del> public function getOptionParser(): ConsoleOptionParser <del> { <del> $parser = parent::getOptionParser(); <del> $parser->addSubcommand('clear', [ <del> 'help' => 'Clear all metadata caches for the connection. If a ' . <del> 'table name is provided, only that table will be removed.', <del> ])->addSubcommand('build', [ <del> 'help' => 'Build all metadata caches for the connection. If a ' . <del> 'table name is provided, only that table will be cached.', <del> ])->addOption('connection', [ <del> 'help' => 'The connection to build/clear metadata cache data for.', <del> 'short' => 'c', <del> 'default' => 'default', <del> ])->addArgument('name', [ <del> 'help' => 'A specific table you want to clear/refresh cached data for.', <del> 'optional' => true, <del> ]); <del> <del> return $parser; <del> } <del>} <add><path>tests/TestCase/Command/SchemacacheCommandsTest.php <del><path>tests/TestCase/Shell/SchemaCacheShellTest.php <ide> * @since 3.6.0 <ide> * @license https://opensource.org/licenses/mit-license.php MIT License <ide> */ <del>namespace Cake\Test\TestCase\Shell; <add>namespace Cake\Test\TestCase\Command; <ide> <ide> use Cake\Cache\Cache; <ide> use Cake\Datasource\ConnectionManager; <ide> use Cake\TestSuite\ConsoleIntegrationTestTrait; <ide> use Cake\TestSuite\TestCase; <ide> <ide> /** <del> * SchemaCacheShell test. <add> * SchemacacheCommands test. <ide> */ <del>class SchemaCacheShellTest extends TestCase <add>class SchemacacheCommandsTest extends TestCase <ide> { <ide> use ConsoleIntegrationTestTrait; <ide>
5
PHP
PHP
set property to null instead of unsetting
3c3d86dcdc142e610b98100f8f7a0a59c5991388
<ide><path>src/View/ViewVarsTrait.php <ide> public function createView($viewClass = null) <ide> $builder = $this->viewBuilder(); <ide> if ($viewClass === null && $builder->getClassName() === null) { <ide> $builder->setClassName($this->viewClass); <del> unset($this->viewClass); <add> $this->viewClass = null; <ide> } <ide> if ($viewClass) { <ide> $builder->setClassName($viewClass);
1
Javascript
Javascript
fix some output
3be4f097a3dc1228e99b48e9beca9120c9c70a5f
<ide><path>lib/_debugger.js <ide> Client.prototype._onResponse = function(res) { <ide> <ide> if (res.headers.Type == 'connect') { <ide> // do nothing <del> console.log(res); <ide> this.emit('ready'); <ide> } else if (res.body && res.body.event == 'break') { <ide> this.emit('break', res.body); <ide> function startInterface() { <ide> }); <ide> <ide> c.on('break', function (res) { <del> var result = ''; <add> var result = '\r\n'; <ide> if (res.body.breakpoints) { <ide> result += 'breakpoint'; <ide> if (res.body.breakpoints.length > 1) {
1
Text
Text
move stray sentences in zlib doc
944ff77cabb5cd1d9cd973474b0525e63f9508a8
<ide><path>doc/api/zlib.md <ide> Only applicable to deflate algorithm. <ide> added: v0.7.0 <ide> --> <ide> <add>Reset the compressor/decompressor to factory defaults. Only applicable to <add>the inflate and deflate algorithms. <add> <ide> ## zlib.constants <ide> <ide> Provides an object enumerating Zlib-related constants. <ide> <del>Reset the compressor/decompressor to factory defaults. Only applicable to <del>the inflate and deflate algorithms. <del> <ide> ## zlib.createDeflate([options]) <ide> <!-- YAML <ide> added: v0.5.8
1
Ruby
Ruby
use proper hook for loading fixtures extension
2035138115035ffb94e19bad8a941f8da0c60560
<ide><path>activerecord/lib/active_record/railtie.rb <ide> class Railtie < Rails::Railtie # :nodoc: <ide> **config.active_record.encryption <ide> <ide> ActiveSupport.on_load(:active_record) do <del> # Encrypt active record fixtures <del> if ActiveRecord::Encryption.config.encrypt_fixtures <del> ActiveRecord::Fixture.prepend ActiveRecord::Encryption::EncryptedFixtures <del> end <del> <ide> # Support extended queries for deterministic attributes and validations <ide> if ActiveRecord::Encryption.config.extend_queries <ide> ActiveRecord::Encryption::ExtendedDeterministicQueries.install_support <ide> ActiveRecord::Encryption::ExtendedDeterministicUniquenessValidator.install_support <ide> end <ide> end <ide> <add> ActiveSupport.on_load(:active_record_fixture_set) do <add> # Encrypt active record fixtures <add> if ActiveRecord::Encryption.config.encrypt_fixtures <add> ActiveRecord::Fixture.prepend ActiveRecord::Encryption::EncryptedFixtures <add> end <add> end <add> <ide> # Filtered params <ide> ActiveSupport.on_load(:action_controller) do <ide> if ActiveRecord::Encryption.config.add_to_filter_parameters
1
Go
Go
add integration test for volumes-from as file
28015f8e579e7bbe396f65b3343188ca03b06cbd
<ide><path>integration-cli/docker_cli_run_test.go <ide> func TestDockerRunWithoutNetworking(t *testing.T) { <ide> logDone("run - disable networking with --networking=false") <ide> logDone("run - disable networking with -n=false") <ide> } <add> <add>// Regression test for #4741 <add>func TestDockerRunWithVolumesAsFiles(t *testing.T) { <add> runCmd := exec.Command(dockerBinary, "run", "--name", "test-data", "--volume", "/etc/hosts:/target-file", "busybox", "true") <add> out, stderr, exitCode, err := runCommandWithStdoutStderr(runCmd) <add> if err != nil && exitCode != 0 { <add> t.Fatal("1", out, stderr, err) <add> } <add> <add> runCmd = exec.Command(dockerBinary, "run", "--volumes-from", "test-data", "busybox", "cat", "/target-file") <add> out, stderr, exitCode, err = runCommandWithStdoutStderr(runCmd) <add> if err != nil && exitCode != 0 { <add> t.Fatal("2", out, stderr, err) <add> } <add> deleteAllContainers() <add> <add> logDone("run - regression test for #4741 - volumes from as files") <add>}
1
PHP
PHP
remove remote provider
4204337382b2ac2a45ff4839b268a2e967718a55
<ide><path>config/app.php <ide> 'Illuminate\Pagination\PaginationServiceProvider', <ide> 'Illuminate\Queue\QueueServiceProvider', <ide> 'Illuminate\Redis\RedisServiceProvider', <del> 'Illuminate\Remote\RemoteServiceProvider', <ide> 'Illuminate\Auth\Reminders\ReminderServiceProvider', <ide> 'Illuminate\Database\SeedServiceProvider', <ide> 'Illuminate\Session\SessionServiceProvider',
1
Ruby
Ruby
show formula version in failed build output
b24ef38bc1990707133fb24788fcabe0be81c9a1
<ide><path>Library/Homebrew/exceptions.rb <ide> def dump <ide> ohai "ENV" <ide> Homebrew.dump_build_env(env) <ide> puts <del> onoe "#{formula.name} did not build" <add> onoe "#{formula.name} #{formula.version} did not build" <ide> unless (logs = Dir["#{HOMEBREW_LOGS}/#{formula}/*"]).empty? <ide> puts "Logs:" <ide> puts logs.map{|fn| " #{fn}"}.join("\n")
1
Javascript
Javascript
fix two failing assert.throws
36c59cd2338ff29bbe18383fa58cef2fe859718b
<ide><path>test/selection/data-test.js <ide> suite.addBatch({ <ide> assert.deepEqual(body.data(), [data]); <ide> assert.strictEqual(body.data()[0], data); <ide> }, <del> // TODO not sure why Node is not catching this error: <del> "throws an error if data is null or undefined": function(body) { <del> assert.throws(function() { body.data(null); }, Error); <del> assert.throws(function() { body.data(function() {}); }, Error); <add> "throws an error if data is null": function(body) { <add> var errored; <add> try { body.data(null); } catch (e) { errored = true; } <add> assert.isTrue(errored); <add> }, <add> "throws an error if data is a function that returns null": function(body) { <add> var errored; <add> try { body.data(function() {}); } catch (e) { errored = true; } <add> assert.isTrue(errored); <ide> } <ide> } <ide> } <ide> suite.addBatch({ <ide> "returns a new selection": function(div) { <ide> assert.isFalse(div.data([0, 1]) === div); <ide> }, <del> // TODO not sure why Node is not catching this error: <del> "throws an error if data is null or undefined": function(div) { <del> assert.throws(function() { div.data(null); }, Error); <del> assert.throws(function() { div.data(function() {}); }, Error); <add> "throws an error if data is null": function(div) { <add> var errored; <add> try { div.data(null); } catch (e) { errored = true; } <add> assert.isTrue(errored); <add> }, <add> "throws an error if data is a function that returns null": function(div) { <add> var errored; <add> try { div.data(function() {}); } catch (e) { errored = true; } <add> assert.isTrue(errored); <ide> }, <ide> "with no arguments, returns an array of data": function(div) { <ide> var a = new Object(), b = new Object(), actual = [];
1
Go
Go
move some kill integration cli to api tests
2227c8ad5ee2bd2f636651efd4ef70e56c082f85
<ide><path>integration-cli/docker_cli_kill_test.go <ide> import ( <ide> <ide> "github.com/docker/docker/integration-cli/checker" <ide> "github.com/docker/docker/integration-cli/cli" <del> "github.com/docker/docker/integration-cli/request" <ide> "github.com/go-check/check" <del> "github.com/gotestyourself/gotestyourself/icmd" <del> "golang.org/x/net/context" <ide> ) <ide> <del>func (s *DockerSuite) TestKillContainer(c *check.C) { <del> out := runSleepingContainer(c, "-d") <del> cleanedContainerID := strings.TrimSpace(out) <del> cli.WaitRun(c, cleanedContainerID) <del> <del> cli.DockerCmd(c, "kill", cleanedContainerID) <del> cli.WaitExited(c, cleanedContainerID, 10*time.Second) <del> <del> out = cli.DockerCmd(c, "ps", "-q").Combined() <del> c.Assert(out, checker.Not(checker.Contains), cleanedContainerID, check.Commentf("killed container is still running")) <del> <del>} <del> <del>func (s *DockerSuite) TestKillOffStoppedContainer(c *check.C) { <del> out := runSleepingContainer(c, "-d") <del> cleanedContainerID := strings.TrimSpace(out) <del> <del> cli.DockerCmd(c, "stop", cleanedContainerID) <del> cli.WaitExited(c, cleanedContainerID, 10*time.Second) <del> <del> cli.Docker(cli.Args("kill", "-s", "30", cleanedContainerID)).Assert(c, icmd.Expected{ <del> ExitCode: 1, <del> }) <del>} <del> <ide> func (s *DockerSuite) TestKillDifferentUserContainer(c *check.C) { <ide> // TODO Windows: Windows does not yet support -u (Feb 2016). <ide> testRequires(c, DaemonIsLinux) <ide> func (s *DockerSuite) TestKillDifferentUserContainer(c *check.C) { <ide> c.Assert(out, checker.Not(checker.Contains), cleanedContainerID, check.Commentf("killed container is still running")) <ide> <ide> } <del> <del>// regression test about correct signal parsing see #13665 <del>func (s *DockerSuite) TestKillWithSignal(c *check.C) { <del> // Cannot port to Windows - does not support signals in the same way Linux does <del> testRequires(c, DaemonIsLinux) <del> out, _ := dockerCmd(c, "run", "-d", "busybox", "top") <del> cid := strings.TrimSpace(out) <del> c.Assert(waitRun(cid), check.IsNil) <del> <del> dockerCmd(c, "kill", "-s", "SIGWINCH", cid) <del> time.Sleep(250 * time.Millisecond) <del> <del> running := inspectField(c, cid, "State.Running") <del> <del> c.Assert(running, checker.Equals, "true", check.Commentf("Container should be in running state after SIGWINCH")) <del>} <del> <del>func (s *DockerSuite) TestKillWithStopSignalWithSameSignalShouldDisableRestartPolicy(c *check.C) { <del> // Cannot port to Windows - does not support signals int the same way as Linux does <del> testRequires(c, DaemonIsLinux) <del> out := cli.DockerCmd(c, "run", "-d", "--stop-signal=TERM", "--restart=always", "busybox", "top").Combined() <del> cid := strings.TrimSpace(out) <del> cli.WaitRun(c, cid) <del> <del> // Let docker send a TERM signal to the container <del> // It will kill the process and disable the restart policy <del> cli.DockerCmd(c, "kill", "-s", "TERM", cid) <del> cli.WaitExited(c, cid, 10*time.Second) <del> <del> out = cli.DockerCmd(c, "ps", "-q").Combined() <del> c.Assert(out, checker.Not(checker.Contains), cid, check.Commentf("killed container is still running")) <del>} <del> <del>func (s *DockerSuite) TestKillWithStopSignalWithDifferentSignalShouldKeepRestartPolicy(c *check.C) { <del> // Cannot port to Windows - does not support signals int the same way as Linux does <del> testRequires(c, DaemonIsLinux) <del> out := cli.DockerCmd(c, "run", "-d", "--stop-signal=CONT", "--restart=always", "busybox", "top").Combined() <del> cid := strings.TrimSpace(out) <del> cli.WaitRun(c, cid) <del> <del> // Let docker send a TERM signal to the container <del> // It will kill the process, but not disable the restart policy <del> cli.DockerCmd(c, "kill", "-s", "TERM", cid) <del> cli.WaitRestart(c, cid, 10*time.Second) <del> <del> // Restart policy should still be in place, so it should be still running <del> cli.WaitRun(c, cid) <del>} <del> <del>// FIXME(vdemeester) should be a unit test <del>func (s *DockerSuite) TestKillWithInvalidSignal(c *check.C) { <del> out := runSleepingContainer(c, "-d") <del> cid := strings.TrimSpace(out) <del> c.Assert(waitRun(cid), check.IsNil) <del> <del> out, _, err := dockerCmdWithError("kill", "-s", "0", cid) <del> c.Assert(err, check.NotNil) <del> c.Assert(out, checker.Contains, "Invalid signal: 0", check.Commentf("Kill with an invalid signal didn't error out correctly")) <del> <del> running := inspectField(c, cid, "State.Running") <del> c.Assert(running, checker.Equals, "true", check.Commentf("Container should be in running state after an invalid signal")) <del> <del> out = runSleepingContainer(c, "-d") <del> cid = strings.TrimSpace(out) <del> c.Assert(waitRun(cid), check.IsNil) <del> <del> out, _, err = dockerCmdWithError("kill", "-s", "SIG42", cid) <del> c.Assert(err, check.NotNil) <del> c.Assert(out, checker.Contains, "Invalid signal: SIG42", check.Commentf("Kill with an invalid signal error out correctly")) <del> <del> running = inspectField(c, cid, "State.Running") <del> c.Assert(running, checker.Equals, "true", check.Commentf("Container should be in running state after an invalid signal")) <del> <del>} <del> <del>func (s *DockerSuite) TestKillStoppedContainerAPIPre120(c *check.C) { <del> testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later <del> runSleepingContainer(c, "--name", "docker-kill-test-api", "-d") <del> dockerCmd(c, "stop", "docker-kill-test-api") <del> cli, err := request.NewEnvClientWithVersion("v1.19") <del> c.Assert(err, check.IsNil) <del> defer cli.Close() <del> err = cli.ContainerKill(context.Background(), "docker-kill-test-api", "SIGKILL") <del> c.Assert(err, check.IsNil) <del>} <ide><path>integration/container/kill_test.go <add>package container <add> <add>import ( <add> "context" <add> "testing" <add> "time" <add> <add> "github.com/docker/docker/api/types" <add> "github.com/docker/docker/api/types/container" <add> "github.com/docker/docker/api/types/network" <add> "github.com/docker/docker/api/types/strslice" <add> "github.com/docker/docker/client" <add> "github.com/docker/docker/integration/util/request" <add> "github.com/gotestyourself/gotestyourself/poll" <add> "github.com/gotestyourself/gotestyourself/skip" <add> "github.com/stretchr/testify/require" <add>) <add> <add>func TestKillContainerInvalidSignal(t *testing.T) { <add> defer setupTest(t)() <add> client := request.NewAPIClient(t) <add> t.Parallel() <add> ctx := context.Background() <add> c, err := client.ContainerCreate(ctx, <add> &container.Config{ <add> Image: "busybox", <add> Cmd: strslice.StrSlice([]string{"top"}), <add> }, <add> &container.HostConfig{}, <add> &network.NetworkingConfig{}, <add> "") <add> require.NoError(t, err) <add> err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{}) <add> require.NoError(t, err) <add> <add> err = client.ContainerKill(ctx, c.ID, "0") <add> require.EqualError(t, err, "Error response from daemon: Invalid signal: 0") <add> poll.WaitOn(t, containerIsInState(ctx, client, c.ID, "running"), poll.WithDelay(100*time.Millisecond)) <add> <add> err = client.ContainerKill(ctx, c.ID, "SIG42") <add> require.EqualError(t, err, "Error response from daemon: Invalid signal: SIG42") <add> poll.WaitOn(t, containerIsInState(ctx, client, c.ID, "running"), poll.WithDelay(100*time.Millisecond)) <add>} <add> <add>func TestKillContainer(t *testing.T) { <add> defer setupTest(t)() <add> client := request.NewAPIClient(t) <add> <add> testCases := []struct { <add> doc string <add> signal string <add> status string <add> }{ <add> { <add> doc: "no signal", <add> signal: "", <add> status: "exited", <add> }, <add> { <add> doc: "non killing signal", <add> signal: "SIGWINCH", <add> status: "running", <add> }, <add> { <add> doc: "killing signal", <add> signal: "SIGTERM", <add> status: "exited", <add> }, <add> } <add> <add> for _, tc := range testCases { <add> tc := tc <add> t.Run(tc.doc, func(t *testing.T) { <add> t.Parallel() <add> ctx := context.Background() <add> c, err := client.ContainerCreate(ctx, <add> &container.Config{ <add> Image: "busybox", <add> Cmd: strslice.StrSlice([]string{"top"}), <add> }, <add> &container.HostConfig{}, <add> &network.NetworkingConfig{}, <add> "") <add> require.NoError(t, err) <add> err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{}) <add> require.NoError(t, err) <add> err = client.ContainerKill(ctx, c.ID, tc.signal) <add> require.NoError(t, err) <add> <add> poll.WaitOn(t, containerIsInState(ctx, client, c.ID, tc.status), poll.WithDelay(100*time.Millisecond)) <add> }) <add> } <add>} <add> <add>func TestKillWithStopSignalAndRestartPolicies(t *testing.T) { <add> skip.If(t, testEnv.OSType != "linux", "Windows only supports 1.25 or later") <add> defer setupTest(t)() <add> client := request.NewAPIClient(t) <add> <add> testCases := []struct { <add> doc string <add> stopsignal string <add> status string <add> }{ <add> { <add> doc: "same-signal-disables-restart-policy", <add> stopsignal: "TERM", <add> status: "exited", <add> }, <add> { <add> doc: "different-signal-keep-restart-policy", <add> stopsignal: "CONT", <add> status: "running", <add> }, <add> } <add> <add> for _, tc := range testCases { <add> tc := tc <add> t.Run(tc.doc, func(t *testing.T) { <add> t.Parallel() <add> ctx := context.Background() <add> c, err := client.ContainerCreate(ctx, <add> &container.Config{ <add> Image: "busybox", <add> Cmd: strslice.StrSlice([]string{"top"}), <add> StopSignal: tc.stopsignal, <add> }, <add> &container.HostConfig{ <add> RestartPolicy: container.RestartPolicy{ <add> Name: "always", <add> }}, <add> &network.NetworkingConfig{}, <add> "") <add> require.NoError(t, err) <add> err = client.ContainerStart(ctx, c.ID, types.ContainerStartOptions{}) <add> require.NoError(t, err) <add> err = client.ContainerKill(ctx, c.ID, "TERM") <add> require.NoError(t, err) <add> <add> poll.WaitOn(t, containerIsInState(ctx, client, c.ID, tc.status), poll.WithDelay(100*time.Millisecond)) <add> }) <add> } <add>} <add> <add>func TestKillStoppedContainer(t *testing.T) { <add> skip.If(t, testEnv.OSType != "linux") // Windows only supports 1.25 or later <add> defer setupTest(t)() <add> t.Parallel() <add> ctx := context.Background() <add> client := request.NewAPIClient(t) <add> c, err := client.ContainerCreate(ctx, <add> &container.Config{ <add> Image: "busybox", <add> Cmd: strslice.StrSlice([]string{"top"}), <add> }, <add> &container.HostConfig{}, <add> &network.NetworkingConfig{}, <add> "") <add> require.NoError(t, err) <add> err = client.ContainerKill(ctx, c.ID, "SIGKILL") <add> require.Error(t, err) <add> require.Contains(t, err.Error(), "is not running") <add>} <add> <add>func TestKillStoppedContainerAPIPre120(t *testing.T) { <add> skip.If(t, testEnv.OSType != "linux") // Windows only supports 1.25 or later <add> defer setupTest(t)() <add> t.Parallel() <add> ctx := context.Background() <add> client := request.NewAPIClient(t, client.WithVersion("1.19")) <add> c, err := client.ContainerCreate(ctx, <add> &container.Config{ <add> Image: "busybox", <add> Cmd: strslice.StrSlice([]string{"top"}), <add> }, <add> &container.HostConfig{}, <add> &network.NetworkingConfig{}, <add> "") <add> require.NoError(t, err) <add> err = client.ContainerKill(ctx, c.ID, "SIGKILL") <add> require.NoError(t, err) <add>} <ide><path>integration/util/request/client.go <ide> import ( <ide> "testing" <ide> "time" <ide> <del> "github.com/docker/docker/api" <ide> "github.com/docker/docker/client" <ide> "github.com/docker/go-connections/sockets" <ide> "github.com/docker/go-connections/tlsconfig" <ide> "github.com/stretchr/testify/require" <ide> ) <ide> <ide> // NewAPIClient returns a docker API client configured from environment variables <del>func NewAPIClient(t *testing.T) client.APIClient { <del> clt, err := client.NewEnvClient() <add>func NewAPIClient(t *testing.T, ops ...func(*client.Client) error) client.APIClient { <add> ops = append([]func(*client.Client) error{client.FromEnv}, ops...) <add> clt, err := client.NewClientWithOpts(ops...) <ide> require.NoError(t, err) <ide> return clt <ide> } <ide> func NewTLSAPIClient(t *testing.T, host, cacertPath, certPath, keyPath string) ( <ide> Transport: tr, <ide> CheckRedirect: client.CheckRedirect, <ide> } <del> verStr := api.DefaultVersion <del> customHeaders := map[string]string{} <del> return client.NewClient(host, verStr, httpClient, customHeaders) <add> return client.NewClientWithOpts(client.WithHost(host), client.WithHTTPClient(httpClient)) <ide> }
3
Ruby
Ruby
add support for a not predicate
0e6888232a19c8c59416490d3da6079e590fab77
<ide><path>lib/arel/algebra/attributes/attribute.rb <ide> def eq(other) <ide> Predicates::Equality.new(self, other) <ide> end <ide> <add> def not(other) <add> Predicates::Not.new(self, other) <add> end <add> <ide> def lt(other) <ide> Predicates::LessThan.new(self, other) <ide> end <ide><path>lib/arel/algebra/predicates.rb <ide> def ==(other) <ide> end <ide> end <ide> <add> class Not < Binary; end <ide> class GreaterThanOrEqualTo < Binary; end <ide> class GreaterThan < Binary; end <ide> class LessThanOrEqualTo < Binary; end <ide><path>lib/arel/engines/memory/predicates.rb <ide> class Equality < Binary <ide> def operator; :== end <ide> end <ide> <add> class Not < Binary <add> def eval(row) <add> operand1.eval(row) != operand2.eval(row) <add> end <add> end <add> <ide> class GreaterThanOrEqualTo < Binary <ide> def operator; :>= end <ide> end <ide><path>lib/arel/engines/sql/predicates.rb <ide> def predicate_sql <ide> end <ide> end <ide> <add> class Not < Binary <add> def predicate_sql; '!=' end <add> end <add> <ide> class GreaterThanOrEqualTo < Binary <ide> def predicate_sql; '>=' end <ide> end <ide><path>spec/algebra/integration/basic_spec.rb <ide> def have_rows(expected) <ide> expected = @expected.select { |r| r[@relation[:age]] == @pivot[@relation[:age]] } <ide> @relation.where(@relation[:age].eq(@pivot[@relation[:age]])).should have_rows(expected) <ide> end <add> <add> it "finds rows with a not predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] != @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].not(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a less than predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] < @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].lt(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a less than or equal to predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] <= @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].lteq(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a greater than predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] > @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].gt(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a greater than or equal to predicate" do <add> expected = @expected.select { |r| r[@relation[:age]] >= @pivot[@relation[:age]] } <add> @relation.where(@relation[:age].gteq(@pivot[@relation[:age]])).should have_rows(expected) <add> end <add> <add> it "finds rows with a matches predicate" <add> <add> it "finds rows with an in predicate" do <add> pending <add> set = @expected[1..(@expected.length/2+1)] <add> @relation.all(:id.in => set.map { |r| r.id }).should have_resources(set) <add> end <ide> end <ide> end <ide>
5
Ruby
Ruby
pass strings to the underscore method
59ec4562a2e70df455b2e44a67c340fa5254e26e
<ide><path>railties/lib/rails/engine.rb <ide> def endpoint(endpoint = nil) <ide> end <ide> <ide> def isolate_namespace(mod) <del> engine_name(generate_railtie_name(mod)) <add> engine_name(generate_railtie_name(mod.name)) <ide> <ide> self.routes.default_scope = { module: ActiveSupport::Inflector.underscore(mod.name) } <ide> self.isolated = true <ide><path>railties/lib/rails/railtie.rb <ide> def configure(&block) <ide> end <ide> <ide> protected <del> def generate_railtie_name(class_or_module) <del> ActiveSupport::Inflector.underscore(class_or_module).tr("/", "_") <add> def generate_railtie_name(string) <add> ActiveSupport::Inflector.underscore(string).tr("/", "_") <ide> end <ide> <ide> # If the class method does not have a method, then send the method call
2
Javascript
Javascript
create flow props for image
8bac869f5d1f2ef42e707d0ec817afc6ac98b3b2
<ide><path>Libraries/Image/ImageProps.js <ide> * <ide> * @providesModule ImageProps <ide> * @flow <add> * @format <ide> */ <ide> <ide> 'use strict'; <ide> const ImageStylePropTypes = require('ImageStylePropTypes'); <ide> const PropTypes = require('prop-types'); <ide> const StyleSheetPropType = require('StyleSheetPropType'); <ide> <add>import type {ImageSource} from 'ImageSource'; <add>import type {EdgeInsetsProp} from 'EdgeInsetsPropType'; <add>import type {LayoutEvent} from 'CoreEventTypes'; <add>import type {SyntheticEvent} from 'CoreEventTypes'; <add> <add>export type ImageProps = { <add> accessible?: boolean, <add> accessibilityLabel?: ?(string | Array<any> | any), <add> blurRadius?: number, <add> capInsets?: ?EdgeInsetsProp, <add> <add> onError?: ?(event: SyntheticEvent<$ReadOnly<{||}>>) => void, <add> onLayout?: ?(event: LayoutEvent) => void, <add> onLoad?: ?() => void, <add> onLoadEnd?: ?() => void, <add> onLoadStart?: ?() => void, <add> resizeMethod?: ?('auto' | 'resize' | 'scale'), <add> resizeMode?: ?('cover' | 'contain' | 'stretch' | 'repeat' | 'center'), <add> source?: ?ImageSource, <add> style?: typeof ImageStylePropTypes, <add> testID?: ?string, <add> <add> // ios <add> defaultSource?: ?ImageSource, <add> onPartialLoad?: ?() => void, <add> onProgress?: ?( <add> event: SyntheticEvent<$ReadOnly<{|loaded: number, total: number|}>>, <add> ) => void, <add>}; <add> <ide> module.exports = { <ide> /** <ide> * See https://facebook.github.io/react-native/docs/image.html#style
1
Text
Text
improve changelog entry [ci skip]
4efb0f373047c44249bc6542fdf9969e4c63dd88
<ide><path>activerecord/CHANGELOG.md <del>* Revert the behaviour of AR::Relation#join changed through 4.0 => 4.1 to 4.0 <add>* Revert the behaviour of `ActiveRecord::Relation#join` changed through 4.0 => 4.1 to 4.0. <ide> <del> In 4.1.0 Relation#join is delegated to Arel#SelectManager. <del> In 4.0 series it is delegated to Array#join <add> In 4.1.0 `Relation#join` is delegated to `Arel#SelectManager`. <add> In 4.0 series it is delegated to `Array#join`. <ide> <ide> *Bogdan Gusiev* <ide>
1
Python
Python
fix bad import with pytorch <= 1.4.1
d1ad4bff445d86fcf2700b9317bf6c029f86788a
<ide><path>src/transformers/trainer_pt_utils.py <ide> <ide> import numpy as np <ide> import torch <del>from torch.optim.lr_scheduler import SAVE_STATE_WARNING <add>from packaging import version <ide> from torch.utils.data.distributed import DistributedSampler <ide> from torch.utils.data.sampler import RandomSampler, Sampler <ide> <ide> if is_torch_tpu_available(): <ide> import torch_xla.core.xla_model as xm <ide> <add>if version.parse(torch.__version__) <= version.parse("1.4.1"): <add> SAVE_STATE_WARNING = "" <add>else: <add> from torch.optim.lr_scheduler import SAVE_STATE_WARNING <add> <ide> logger = logging.get_logger(__name__) <ide> <ide>
1
Javascript
Javascript
move generatestructname to cpphelpers
e6c1e81c60638b052edbe373d110ccc321fcefec
<ide><path>packages/react-native-codegen/src/generators/components/CppHelpers.js <ide> function getImports(component: ComponentShape): Set<string> { <ide> return imports; <ide> } <ide> <add>function generateStructName( <add> componentName: string, <add> parts: $ReadOnlyArray<string> = [], <add>) { <add> const additional = parts.map(toSafeCppString).join(''); <add> return `${componentName}${additional}Struct`; <add>} <add> <ide> module.exports = { <ide> getCppTypeForAnnotation, <ide> getImports, <ide> toSafeCppString, <add> generateStructName, <ide> }; <ide><path>packages/react-native-codegen/src/generators/components/EventEmitterHelpers.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> * @flow strict <del> * @format <del> */ <del> <del>'use strict'; <del> <del>const {toSafeCppString} = require('./CppHelpers.js'); <del> <del>// import type {EventTypeShape} from './CodegenSchema'; <del> <del>function generateStructName( <del> componentName: string, <del> parts: $ReadOnlyArray<string> = [], <del>): string { <del> const additional = parts.map(toSafeCppString).join(''); <del> return `${componentName}${additional}Struct`; <del>} <del> <del>module.exports = { <del> generateStructName, <del>}; <ide><path>packages/react-native-codegen/src/generators/components/GenerateEventEmitterCpp.js <ide> <ide> 'use strict'; <ide> <del>const {generateStructName} = require('./EventEmitterHelpers.js'); <add>const {generateStructName} = require('./CppHelpers.js'); <ide> <ide> import type { <ide> ComponentShape, <del> EventTypeShape, <ide> ObjectPropertyType, <ide> SchemaType, <ide> } from '../../CodegenSchema'; <ide> type ComponentCollection = $ReadOnly<{ <ide> [component: string]: ComponentShape, <ide> }>; <ide> <del>type SettersSet = Set<string>; <del> <ide> const template = ` <ide> /** <ide> * Copyright (c) Facebook, Inc. and its affiliates. <ide><path>packages/react-native-codegen/src/generators/components/GenerateEventEmitterH.js <ide> <ide> const nullthrows = require('nullthrows'); <ide> <del>const {getCppTypeForAnnotation, toSafeCppString} = require('./CppHelpers.js'); <del>const {generateStructName} = require('./EventEmitterHelpers.js'); <add>const { <add> getCppTypeForAnnotation, <add> toSafeCppString, <add> generateStructName, <add>} = require('./CppHelpers.js'); <ide> <ide> import type { <ide> ComponentShape,
4
Python
Python
replace remaining uses of "bail"
0d8bc95ad643924ebcad4da0d9ea36416e05d5e3
<ide><path>airflow/cli/commands/dag_command.py <ide> def dag_delete(args): <ide> except OSError as err: <ide> raise AirflowException(err) <ide> else: <del> print("Bail.") <add> print("Cancelled") <ide> <ide> <ide> @cli_utils.action_logging <ide><path>airflow/cli/commands/db_command.py <ide> def resetdb(args): <ide> "(y/n)").upper() == "Y": <ide> db.resetdb() <ide> else: <del> print("Bail.") <add> print("Cancelled") <ide> <ide> <ide> @cli_utils.action_logging <ide><path>airflow/models/dag.py <ide> def topological_sort(self, include_subdag_tasks: bool = False): <ide> # graph as we move through it. We also keep a flag for <ide> # checking that that graph is acyclic, which is true if any <ide> # nodes are resolved during each pass through the graph. If <del> # not, we need to bail out as the graph therefore can't be <add> # not, we need to exit as the graph therefore can't be <ide> # sorted. <ide> acyclic = False <ide> for node in list(graph_unsorted.values()): <ide> def clear( <ide> ) <ide> else: <ide> count = 0 <del> print("Bail. Nothing was cleared.") <add> print("Cancelled, nothing was cleared.") <ide> <ide> session.commit() <ide> return count <ide> def clear_dags( <ide> ) <ide> else: <ide> count = 0 <del> print("Bail. Nothing was cleared.") <add> print("Cancelled, nothing was cleared.") <ide> return count <ide> <ide> def __deepcopy__(self, memo):
3
Text
Text
fix some typos at formula cookbook
3d9bc57feacf32d9050569b3645c29d2a0ddd749
<ide><path>share/doc/homebrew/Formula-Cookbook.md <ide> so you can override this with `brew create <url> --set-name <name>`. <ide> <ide> ## Fill in the [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method) <ide> <del>**We don’t accept formulae without [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method)s!** <add>**We don’t accept formulae without a [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method)!** <ide> <ide> A SSL/TLS (https) [`homepage`](http://www.rubydoc.info/github/Homebrew/homebrew/master/Formula#homepage%3D-class_method) is preferred, if one is available. <ide>
1
Python
Python
set version to v3.0.2
b31471b5b8c1d16dd0960f4e121b32c5f1e7fefa
<ide><path>spacy/about.py <ide> # fmt: off <ide> __title__ = "spacy" <del>__version__ = "3.0.1" <add>__version__ = "3.0.2" <ide> __download_url__ = "https://github.com/explosion/spacy-models/releases/download" <ide> __compatibility__ = "https://raw.githubusercontent.com/explosion/spacy-models/master/compatibility.json" <ide> __projects__ = "https://github.com/explosion/projects"
1
Javascript
Javascript
remove unused local var from link_to test
cf2cd8310084155379dd74b4278b7df472e59bae
<ide><path>packages/ember/tests/helpers/link_to_test.js <ide> test("The {{link-to}} helper moves into the named route with context", function( <ide> <ide> Ember.TEMPLATES.about = Ember.Handlebars.compile("<h3>List</h3><ul>{{#each controller}}<li>{{#link-to 'item' this}}{{name}}{{/link-to}}<li>{{/each}}</ul>{{#link-to 'index' id='home-link'}}Home{{/link-to}}"); <ide> <del> var people = { <del> yehuda: "Yehuda Katz", <del> tom: "Tom Dale", <del> erik: "Erik Brynroflsson" <del> }; <del> <ide> App.AboutRoute = Ember.Route.extend({ <ide> model: function() { <ide> return Ember.A([
1
Javascript
Javascript
add test to validate changelogs for releases
cf523c659fa27956c7fe8670e9509ced9899f8b7
<ide><path>test/parallel/test-release-changelog.js <add>'use strict'; <add> <add>// This test checks that the changelogs contain an entry for releases. <add> <add>const common = require('../common'); <add>const assert = require('assert'); <add>const fs = require('fs'); <add>const path = require('path'); <add> <add>const getDefine = (text, name) => { <add> const regexp = new RegExp(`#define\\s+${name}\\s+(.*)`); <add> const match = regexp.exec(text); <add> assert.notStrictEqual(match, null); <add> return match[1]; <add>}; <add> <add>const srcRoot = path.join(__dirname, '..', '..'); <add>const mainChangelogFile = path.join(srcRoot, 'CHANGELOG.md'); <add>const versionFile = path.join(srcRoot, 'src', 'node_version.h'); <add>const versionText = fs.readFileSync(versionFile, { encoding: 'utf8' }); <add>const release = getDefine(versionText, 'NODE_VERSION_IS_RELEASE') !== '0'; <add> <add>if (!release) { <add> common.skip('release bit is not set'); <add>} <add> <add>const major = getDefine(versionText, 'NODE_MAJOR_VERSION'); <add>const minor = getDefine(versionText, 'NODE_MINOR_VERSION'); <add>const patch = getDefine(versionText, 'NODE_PATCH_VERSION'); <add>const versionForRegex = `${major}\\.${minor}\\.${patch}`; <add> <add>const lts = getDefine(versionText, 'NODE_VERSION_IS_LTS') !== '0'; <add>const codename = getDefine(versionText, 'NODE_VERSION_LTS_CODENAME').slice(1, -1); <add>// If the LTS bit is set there should be a codename. <add>if (lts) { <add> assert.notStrictEqual(codename, ''); <add>} <add> <add>const changelogPath = `doc/changelogs/CHANGELOG_V${major}.md`; <add>// Check CHANGELOG_V*.md <add>{ <add> const changelog = fs.readFileSync(path.join(srcRoot, changelogPath), { encoding: 'utf8' }); <add> // Check title matches major version. <add> assert.match(changelog, new RegExp(`# Node\\.js ${major} ChangeLog`)); <add> // Check table header <add> let tableHeader; <add> if (lts) { <add> tableHeader = new RegExp(`<th>LTS '${codename}'</th>`); <add> } else { <add> tableHeader = /<th>Current<\/th>/; <add> } <add> assert.match(changelog, tableHeader); <add> // Check table contains link to this release. <add> assert.match(changelog, new RegExp(`<a href="#${versionForRegex}">${versionForRegex}</a>`)); <add> // Check anchor for this release. <add> assert.match(changelog, new RegExp(`<a id="${versionForRegex}"></a>`)); <add> // Check title for changelog entry. <add> let title; <add> if (lts) { <add> title = new RegExp(`## \\d{4}-\\d{2}-\\d{2}, Version ${versionForRegex} '${codename}' \\(LTS\\), @\\S+`); <add> } else { <add> title = new RegExp(`## \\d{4}-\\d{2}-\\d{2}, Version ${versionForRegex} \\(Current\\), @\\S+`); <add> } <add> assert.match(changelog, title); <add>} <add> <add>// Main CHANGELOG.md checks <add>{ <add> const mainChangelog = fs.readFileSync(mainChangelogFile, { encoding: 'utf8' }); <add> // Check for the link to the appropriate CHANGELOG_V*.md file. <add> let linkToChangelog; <add> if (lts) { <add> linkToChangelog = new RegExp(`\\[Node\\.js ${major}\\]\\(${changelogPath}\\) \\*\\*Long Term Support\\*\\*`); <add> } else { <add> linkToChangelog = new RegExp(`\\[Node\\.js ${major}\\]\\(${changelogPath}\\) \\*\\*Current\\*\\*`); <add> } <add> assert.match(mainChangelog, linkToChangelog); <add> // Check table header. <add> let tableHeader; <add> if (lts) { <add> tableHeader = new RegExp(`<th title="LTS Until \\d{4}-\\d{2}"><a href="${changelogPath}">${major}</a> \\(LTS\\)</th>`); <add> } else { <add> tableHeader = new RegExp(`<th title="Current"><a href="${changelogPath}">${major}</a> \\(Current\\)</th>`); <add> } <add> assert.match(mainChangelog, tableHeader); <add> // Check the table contains a link to the release in the appropriate CHANGELOG_V*.md file. <add> const linkToVersion = new RegExp(`<b><a href="${changelogPath}#${versionForRegex}">${versionForRegex}</a></b><br/>`); <add> assert.match(mainChangelog, linkToVersion); <add>}
1
Javascript
Javascript
report more errors to workers
3e9f2e61db371f8208ccb04824fdfb186de72f36
<ide><path>lib/cluster.js <ide> if (cluster.isMaster) { <ide> <ide> if (serverHandlers.hasOwnProperty(key)) { <ide> handler = serverHandlers[key]; <del> } else if (message.addressType === 'udp4' || <del> message.addressType === 'udp6') { <del> var dgram = require('dgram'); <del> handler = dgram._createSocketHandle.apply(net, args); <del> serverHandlers[key] = handler; <ide> } else { <del> handler = net._createServerHandle.apply(net, args); <add> if (message.addressType === 'udp4' || <add> message.addressType === 'udp6') { <add> var dgram = require('dgram'); <add> handler = dgram._createSocketHandle.apply(net, args); <add> } else { <add> handler = net._createServerHandle.apply(net, args); <add> } <add> if (!handler) { <add> send({ content: { error: process._errno } }, null); <add> return; <add> } <ide> serverHandlers[key] = handler; <ide> } <ide> <ide> cluster._getServer = function(tcpSelf, address, port, addressType, fd, cb) { <ide> <ide> // The callback will be stored until the master has responded <ide> sendInternalMessage(cluster.worker, message, function(msg, handle) { <del> cb(handle); <add> cb(handle, msg && msg.error); <ide> }); <ide> <ide> }; <ide><path>lib/dgram.js <ide> Socket.prototype.bind = function(/*port, address, callback*/) { <ide> cluster = require('cluster'); <ide> <ide> if (cluster.isWorker) { <del> cluster._getServer(self, ip, port, self.type, -1, function(handle) { <add> cluster._getServer(self, ip, port, self.type, -1, function(handle, err) { <add> if (err) <add> return self.emit('error', errnoException(err, 'bind')); <add> <ide> if (!self._handle) <ide> // handle has been closed in the mean time. <ide> return handle.close(); <ide><path>lib/net.js <ide> function listen(self, address, port, addressType, backlog, fd) { <ide> return; <ide> } <ide> <del> cluster._getServer(self, address, port, addressType, fd, function(handle) { <add> cluster._getServer(self, address, port, addressType, fd, function(handle, <add> err) { <add> // EACCESS and friends <add> if (err) { <add> self.emit('error', errnoException(err, 'bind')); <add> return; <add> } <add> <ide> // Some operating systems (notably OS X and Solaris) don't report EADDRINUSE <ide> // errors right away. libuv mimics that behavior for the sake of platform <ide> // consistency but that means we have have a socket on our hands that is <ide><path>test/simple/test-cluster-eaccess.js <add>// Copyright Joyent, Inc. and other Node contributors. <add>// <add>// Permission is hereby granted, free of charge, to any person obtaining a <add>// copy of this software and associated documentation files (the <add>// "Software"), to deal in the Software without restriction, including <add>// without limitation the rights to use, copy, modify, merge, publish, <add>// distribute, sublicense, and/or sell copies of the Software, and to permit <add>// persons to whom the Software is furnished to do so, subject to the <add>// following conditions: <add>// <add>// The above copyright notice and this permission notice shall be included <add>// in all copies or substantial portions of the Software. <add>// <add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS <add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF <add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN <add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, <add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR <add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE <add>// USE OR OTHER DEALINGS IN THE SOFTWARE. <add> <add> <add>var common = require('../common'); <add>var assert = require('assert'); <add>var cluster = require('cluster'); <add>var path = require('path'); <add>var fs = require('fs'); <add>var net = require('net'); <add> <add>// No win32 support so far <add>if (process.platform === 'win32') <add> return; <add> <add>var socketPath = path.join(common.fixturesDir, 'socket-path'); <add> <add>if (cluster.isMaster) { <add> cluster.fork(); <add>} else { <add> fs.writeFileSync(socketPath, 'some contents'); <add> <add> var server = net.createServer().listen(socketPath, function() { <add> console.log('here'); <add> }); <add> <add> var gotError = 0; <add> server.on('error', function(err) { <add> gotError++; <add> assert(/EADDRINUSE/.test(err.message)); <add> process.exit(); <add> }); <add> <add> process.on('exit', function() { <add> try { <add> fs.unlinkSync(socketPath); <add> } catch (e) { <add> } <add> assert.equal(gotError, 1); <add> }); <add>}
4
Javascript
Javascript
move __styleprop to stylesheet
cf89a2cbfd4fb66580a0ed2b195a6daf680ca79c
<ide><path>Libraries/StyleSheet/StyleSheet.js <ide> import type { <ide> StyleSheetStyle as _StyleSheetStyle, <ide> Styles as _Styles, <ide> ____StyleObj_Internal, <add> ____ViewStyleProp_Internal, <add> ____TextStyleProp_Internal, <add> ____ImageStyleProp_Internal, <ide> LayoutStyle <ide> } from 'StyleSheetTypes'; <ide> <ide> export type DangerouslyImpreciseStyleProp = ____StyleObj_Internal; <add>export type ViewStyleProp = ____ViewStyleProp_Internal; <add>export type TextStyleProp = ____TextStyleProp_Internal; <add>export type ImageStyleProp = ____ImageStyleProp_Internal; <add> <ide> export type Styles = _Styles; <ide> export type StyleSheetStyle = _StyleSheetStyle; <ide> type StyleSheet<+S: Styles> = $ObjMap<S, (Object) => StyleSheetStyle>; <ide><path>Libraries/StyleSheet/StyleSheetTypes.js <ide> type GenericStyleProp<+T> = <ide> | $ReadOnlyArray<GenericStyleProp<T>>; <ide> <ide> export type ____StyleObj_Internal = GenericStyleProp<$Shape<Style>>; <del> <del>export type ViewStyleProp = GenericStyleProp<$ReadOnly<$Shape<ViewStyle>>>; <del>export type TextStyleProp = GenericStyleProp<$ReadOnly<$Shape<TextStyle>>>; <del>export type ImageStyleProp = GenericStyleProp<$ReadOnly<$Shape<ImageStyle>>>; <add>export type ____ViewStyleProp_Internal = GenericStyleProp< <add> $ReadOnly<$Shape<ViewStyle>>, <add>>; <add>export type ____TextStyleProp_Internal = GenericStyleProp< <add> $ReadOnly<$Shape<TextStyle>>, <add>>; <add>export type ____ImageStyleProp_Internal = GenericStyleProp< <add> $ReadOnly<$Shape<ImageStyle>>, <add>>; <ide> <ide> export type Styles = { <ide> +[key: string]: $Shape<Style>, <ide><path>Libraries/Text/TextProps.js <ide> import type {Node} from 'react'; <ide> <ide> import type {LayoutEvent} from 'CoreEventTypes'; <del>import type {TextStyleProp} from 'StyleSheetTypes'; <add>import type {TextStyleProp} from 'StyleSheet'; <ide> <ide> type PressRetentionOffset = { <ide> top: number,
3
Ruby
Ruby
use env shebang when installing gems
81f262ece3ba6215579c1a0147bc281590ea7d3d
<ide><path>Library/Homebrew/utils/gems.rb <ide> def install_gem!(name, version: nil, setup_gem_environment: true) <ide> ohai_if_defined "Installing '#{name}' gem" <ide> # `document: []` is equivalent to --no-document <ide> # `build_args: []` stops ARGV being used as a default <del> specs = Gem.install name, version, document: [], build_args: [] <add> # `env_shebang: true` makes shebangs generic to allow switching between system and Portable Ruby <add> specs = Gem.install name, version, document: [], build_args: [], env_shebang: true <ide> end <ide> <ide> specs += specs.flat_map(&:runtime_dependencies)
1
Javascript
Javascript
squeeze support module. close gh-1165
22a4e5bd0a7c0a92b54b9965984b582fd42099f2
<ide><path>src/support.js <ide> jQuery.support = (function( support ) { <del> <del> var a, select, opt, input, fragment, <del> div = document.createElement("div"); <del> <del> // Finish early in limited (non-browser) environments <del> div.innerHTML = "<a>a</a><input type='checkbox'/>"; <del> a = div.getElementsByTagName("a")[ 0 ]; <del> if ( !a ) { <add> var input = document.createElement("input"), <add> fragment = document.createDocumentFragment(), <add> div = document.createElement("div"), <add> select = document.createElement("select"), <add> opt = select.appendChild( document.createElement("option") ); <add> <add> // Finish early in limited environments <add> if ( !input.type ) { <ide> return support; <ide> } <ide> <del> // First batch of tests <del> select = document.createElement("select"); <del> opt = select.appendChild( document.createElement("option") ); <del> input = div.getElementsByTagName("input")[ 0 ]; <add> input.type = "checkbox"; <ide> <del> a.style.cssText = "float:left;opacity:.5"; <del> <del> // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) <del> support.checkOn = !!input.value; <add> // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) <add> support.checkOn = input.value === ""; <ide> <ide> // Must access the parent to make an option select properly <ide> // Support: IE9, IE10 <ide> jQuery.support = (function( support ) { <ide> support.pixelPosition = false; <ide> <ide> // Make sure checked status is properly cloned <add> // Support: IE9, IE10 <ide> input.checked = true; <ide> support.noCloneChecked = input.cloneNode( true ).checked; <ide> <ide> jQuery.support = (function( support ) { <ide> support.optDisabled = !opt.disabled; <ide> <ide> // Check if an input maintains its value after becoming a radio <add> // Support: IE9, IE10, Opera <ide> input = document.createElement("input"); <ide> input.value = "t"; <del> input.setAttribute( "type", "radio" ); <add> input.type = "radio"; <ide> support.radioValue = input.value === "t"; <ide> <ide> // #11217 - WebKit loses check when the name is after the checked attribute <ide> input.setAttribute( "checked", "t" ); <ide> input.setAttribute( "name", "t" ); <ide> <del> fragment = document.createDocumentFragment(); <ide> fragment.appendChild( input ); <ide> <del> // WebKit doesn't clone checked state correctly in fragments <add> // old WebKit doesn't clone checked state correctly in fragments <ide> support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; <ide> <ide> // Support: Firefox 17+ <ide> // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) <del> div.setAttribute( "onfocusin", "t" ); <del> support.focusinBubbles = "onfocusin" in window || div.attributes.onfocusin.expando === false; <add> support.focusinBubbles = "onfocusin" in window; <ide> <ide> div.style.backgroundClip = "content-box"; <ide> div.cloneNode( true ).style.backgroundClip = ""; <ide> support.clearCloneStyle = div.style.backgroundClip === "content-box"; <ide> <ide> // Run tests that need a body at doc ready <ide> jQuery(function() { <del> var container, marginDiv, tds, <add> var container, marginDiv, <ide> divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", <del> body = document.getElementsByTagName("body")[0]; <add> body = document.getElementsByTagName("body")[ 0 ]; <ide> <ide> if ( !body ) { <ide> // Return for frameset docs that don't have a body <ide> jQuery.support = (function( support ) { <ide> body.appendChild( container ).appendChild( div ); <ide> div.innerHTML = ""; <ide> div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; <del> support.boxSizing = ( div.offsetWidth === 4 ); <del> support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); <add> <add> support.boxSizing = div.offsetWidth === 4; <add> support.doesNotIncludeMarginInBodyOffset = body.offsetTop !== 1; <ide> <ide> // Use window.getComputedStyle because jsdom on node.js will break without it. <ide> if ( window.getComputedStyle ) { <ide> jQuery.support = (function( support ) { <ide> } <ide> <ide> body.removeChild( container ); <del> <del> // Null elements to avoid leaks in IE <del> container = div = tds = marginDiv = null; <ide> }); <ide> <del> // Null elements to avoid leaks in IE <del> select = fragment = opt = a = input = null; <del> <ide> return support; <del>})({}); <add>})( {} ); <ide>
1
Go
Go
update volumepath regex to allow returning earlier
55ceb5047c304d3ac8ecd15801a4b0472832158e
<ide><path>pkg/system/filesys_windows.go <ide> import ( <ide> const SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" <ide> <ide> // volumePath is a regular expression to check if a path is a Windows <del>// volume path (e.g., "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}". <del>var volumePath = regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`) <add>// volume path (e.g., "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}" <add>// or "\\?\Volume{4c1b02c1-d990-11dc-99ae-806e6f6e6963}\"). <add>var volumePath = regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}\\?$`) <ide> <ide> // MkdirAllWithACL is a custom version of os.MkdirAll modified for use on Windows <ide> // so that it is both volume path aware, and can create a directory with
1
Python
Python
use 2 spaces for indent
01dfbda369d9a3e85e18a9af7e51bcba66866cb5
<ide><path>keras/engine/data_adapter_test.py <ide> def __init__(self, batch_size, feature_shape, epochs=2): <ide> self.on_epoch_end() <ide> <ide> def __len__(self): <del> """Number of batches in the Sequence. <add> """Number of batches in the Sequence. <ide> <del> Returns: int <del> The number of batches in the Sequence. <del> """ <del> # data was rebalanced, so need to recalculate number of examples <del> num_examples = 20 <del> batch_size = self._current_batch_size <del> return num_examples // batch_size + int(num_examples % batch_size > 0) # = math.ceil(num_examples / batch_size ) <add> Returns: int <add> The number of batches in the Sequence. <add> """ <add> # data was rebalanced, so need to recalculate number of examples <add> num_examples = 20 <add> batch_size = self._current_batch_size <add> return num_examples // batch_size + int(num_examples % batch_size > 0) # = math.ceil(num_examples / batch_size ) <ide> <ide> def __getitem__(self, index): <del> """Gets batch at position `index`. <add> """Gets batch at position `index`. <ide> <del> Arguments: <del> index (int): position of the batch in the Sequence. <add> Arguments: <add> index (int): position of the batch in the Sequence. <ide> <del> Returns: Tuple[Any, Any] <del> A batch (tuple of input data and target data). <del> """ <del> # return input and target data, as our target data is inside the input <del> # data return None for the target data <del> return (np.zeros((self._current_batch_size, self.feature_shape)), <del> np.ones((self._current_batch_size,))) <add> Returns: Tuple[Any, Any] <add> A batch (tuple of input data and target data). <add> """ <add> # return input and target data, as our target data is inside the input <add> # data return None for the target data <add> return (np.zeros((self._current_batch_size, self.feature_shape)), <add> np.ones((self._current_batch_size,))) <ide> <ide> def on_epoch_end(self): <ide> """Update the data after every epoch.""" <ide> def on_epoch_end(self): <ide> self._current_batch_size = self._linearly_increasing_batch_size() <ide> <ide> def _linearly_increasing_batch_size(self): <del> """Linearly increase batch size with every epoch. <del> <del> The idea comes from https://arxiv.org/abs/1711.00489. <add> """Linearly increase batch size with every epoch. <ide> <del> Returns: int <del> The batch size to use in this epoch. <del> """ <del> if not isinstance(self.batch_size, list): <del> return int(self.batch_size) <add> The idea comes from https://arxiv.org/abs/1711.00489. <ide> <del> if self._epochs > 1: <del> return int( <del> self.batch_size[0] <del> + self._current_epoch <del> * (self.batch_size[1] - self.batch_size[0]) <del> / (self._epochs - 1) <del> ) <del> else: <del> return int(self.batch_size[0]) <add> Returns: int <add> The batch size to use in this epoch. <add> """ <add> if not isinstance(self.batch_size, list): <add> return int(self.batch_size) <add> <add> if self._epochs > 1: <add> return int( <add> self.batch_size[0] <add> + self._current_epoch <add> * (self.batch_size[1] - self.batch_size[0]) <add> / (self._epochs - 1) <add> ) <add> else: <add> return int(self.batch_size[0]) <ide> <ide> <ide> class DummyArrayLike: <ide> def test_training_increasing_batch_size_fit_internals(self): <ide> for epoch, iterator in data_handler.enumerate_epochs(): <ide> self.model.reset_metrics() <ide> with data_handler.catch_stop_iteration(): <del> for step in data_handler.steps(): <del> cur_bs = self.sequence_input_increasing_batch_size._current_batch_size <del> with tf.profiler.experimental.Trace( <del> "train", <del> epoch_num=epoch, <del> step_num=step, <del> batch_size=cur_bs, <del> _r=1, <del> ): <del> if data_handler.should_sync: <del> context.async_wait() <del> if self.model.stop_training: <del> break <add> for step in data_handler.steps(): <add> cur_bs = self.sequence_input_increasing_batch_size._current_batch_size <add> with tf.profiler.experimental.Trace( <add> "train", <add> epoch_num=epoch, <add> step_num=step, <add> batch_size=cur_bs, <add> _r=1, <add> ): <add> if data_handler.should_sync: <add> context.async_wait() <add> if self.model.stop_training: <add> break <ide> self.assertEqual(data_handler.inferred_steps, 2) # 20 samples / 10 bs = 2 <ide> <ide> @test_combinations.run_all_keras_modes(always_skip_v1=True)
1
Java
Java
fix typo in javadoc for mergedannotations
ee2041388b6adcf3a6727415be78a90774ed4113
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/MergedAnnotations.java <ide> * mergedAnnotations.get(ExampleAnnotation.class).getString("value"); <ide> * <ide> * // get all meta-annotations but no directly present annotations <del> * mergedAnnotations.stream().anyMatch(MergedAnnotation::isMetaPresent); <add> * mergedAnnotations.stream().filter(MergedAnnotation::isMetaPresent); <ide> * <ide> * // get all ExampleAnnotation declarations (including any meta-annotations) and <ide> * // print the merged "value" attributes
1