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
Javascript
Javascript
expand client testing for espanol
92dfb3065cfc62febb49e5a269c01b8e961ae712
<ide><path>client/src/components/Header/Header.test.js <ide> const hasProfileAndSettingsNavItems = (component, username) => { <ide> <ide> const hasForumNavItem = component => { <ide> const { children, to } = navigationLinks(component, 'forum'); <add> const localizedForums = { <add> chinese: 'https://chinese.freecodecamp.org/forum', <add> espanol: 'https://forum.freecodecamp.org/c/espanol/', <add> english: 'https://forum.freecodecamp.org/' <add> }; <ide> return ( <ide> children[0].props.children === 'buttons.forum' && <del> (clientLocale === 'chinese' <del> ? to === 'https://chinese.freecodecamp.org/forum' <del> : to === 'https://forum.freecodecamp.org/') <add> to === localizedForums[clientLocale] <ide> ); <ide> }; <ide> <ide> const hasNewsNavItem = component => { <ide> const { children, to } = navigationLinks(component, 'news'); <add> const localizedNews = { <add> chinese: 'https://chinese.freecodecamp.org/news', <add> espanol: 'https://www.freecodecamp.org/espanol/news', <add> english: 'https://www.freecodecamp.org/news' <add> }; <ide> return ( <ide> children[0].props.children === 'buttons.news' && <del> (clientLocale === 'chinese' <del> ? to === 'https://chinese.freecodecamp.org/news' <del> : to === 'https://www.freecodecamp.org/news') <add> to === localizedNews[clientLocale] <ide> ); <ide> }; <ide>
1
PHP
PHP
add phpdoc hints for request class
66eb5d01609f1021baed99a3f5d9d16bec6dcfcb
<ide><path>src/Illuminate/Http/Request.php <ide> use Symfony\Component\HttpFoundation\ParameterBag; <ide> use Symfony\Component\HttpFoundation\Request as SymfonyRequest; <ide> <add>/** <add> * @method array validate(array $rules, ...$params) <add> * @method array validateWithBag(array $rules, ...$params) <add> * @method string hasValidSignature(\Illuminate\Http\Request $request, bool $absolute = true) <add> */ <ide> class Request extends SymfonyRequest implements Arrayable, ArrayAccess <ide> { <ide> use Concerns\InteractsWithContentTypes,
1
Java
Java
avoid unnecessary generics on emptymap/set/list
fb7ae010c867ae48ab51f48cce97fe2c07f44115
<ide><path>spring-context/src/main/java/org/springframework/cache/interceptor/CacheAspectSupport.java <ide> public CacheOperationContexts(Collection<? extends CacheOperation> operations, M <ide> <ide> public Collection<CacheOperationContext> get(Class<? extends CacheOperation> operationClass) { <ide> Collection<CacheOperationContext> result = this.contexts.get(operationClass); <del> return (result != null ? result : Collections.<CacheOperationContext>emptyList()); <add> return (result != null ? result : Collections.emptyList()); <ide> } <ide> <ide> public boolean isSynchronized() { <ide><path>spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskRegistrar.java <ide> public void setTriggerTasksList(List<TriggerTask> triggerTasks) { <ide> */ <ide> public List<TriggerTask> getTriggerTaskList() { <ide> return (this.triggerTasks != null? Collections.unmodifiableList(this.triggerTasks) : <del> Collections.<TriggerTask>emptyList()); <add> Collections.emptyList()); <ide> } <ide> <ide> /** <ide> public void setCronTasksList(List<CronTask> cronTasks) { <ide> */ <ide> public List<CronTask> getCronTaskList() { <ide> return (this.cronTasks != null ? Collections.unmodifiableList(this.cronTasks) : <del> Collections.<CronTask>emptyList()); <add> Collections.emptyList()); <ide> } <ide> <ide> /** <ide> public void setFixedRateTasksList(List<IntervalTask> fixedRateTasks) { <ide> */ <ide> public List<IntervalTask> getFixedRateTaskList() { <ide> return (this.fixedRateTasks != null ? Collections.unmodifiableList(this.fixedRateTasks) : <del> Collections.<IntervalTask>emptyList()); <add> Collections.emptyList()); <ide> } <ide> <ide> /** <ide> public void setFixedDelayTasksList(List<IntervalTask> fixedDelayTasks) { <ide> */ <ide> public List<IntervalTask> getFixedDelayTaskList() { <ide> return (this.fixedDelayTasks != null ? Collections.unmodifiableList(this.fixedDelayTasks) : <del> Collections.<IntervalTask>emptyList()); <add> Collections.emptyList()); <ide> } <ide> <ide> <ide><path>spring-core/src/main/java/org/springframework/core/Conventions.java <ide> public abstract class Conventions { <ide> * when searching for the 'primary' interface of a proxy. <ide> */ <ide> private static final Set<Class<?>> IGNORED_INTERFACES; <add> <ide> static { <del> IGNORED_INTERFACES = Collections.unmodifiableSet( <del> new HashSet<>(Arrays.<Class<?>>asList( <del> Serializable.class, <del> Externalizable.class, <del> Cloneable.class, <del> Comparable.class))); <add> IGNORED_INTERFACES = Collections.unmodifiableSet(new HashSet<>( <add> Arrays.asList(Serializable.class, Externalizable.class, Cloneable.class, Comparable.class))); <ide> } <ide> <ide> <ide><path>spring-core/src/main/java/org/springframework/core/env/JOptCommandLinePropertySource.java <ide> public List<String> getOptionValues(String name) { <ide> stringArgValues.add(argValue instanceof String ? (String) argValue : argValue.toString()); <ide> } <ide> if (stringArgValues.isEmpty()) { <del> return (this.source.has(name) ? Collections.<String>emptyList() : null); <add> return (this.source.has(name) ? Collections.emptyList() : null); <ide> } <ide> return Collections.unmodifiableList(stringArgValues); <ide> } <ide> protected List<String> getNonOptionArgs() { <ide> Assert.isInstanceOf(String.class, argValue, "Argument values must be of type String"); <ide> stringArgValues.add((String) argValue); <ide> } <del> return (stringArgValues.isEmpty() ? Collections.<String>emptyList() : <add> return (stringArgValues.isEmpty() ? Collections.emptyList() : <ide> Collections.unmodifiableList(stringArgValues)); <ide> } <ide> <ide><path>spring-core/src/main/java/org/springframework/util/InstanceFilter.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 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 InstanceFilter(Collection<? extends T> includes, <ide> Collection<? extends T> excludes, boolean matchIfEmpty) { <ide> <del> this.includes = includes != null ? includes : Collections.<T>emptyList(); <del> this.excludes = excludes != null ? excludes : Collections.<T>emptyList(); <add> this.includes = (includes != null ? includes : Collections.emptyList()); <add> this.excludes = (excludes != null ? excludes : Collections.emptyList()); <ide> this.matchIfEmpty = matchIfEmpty; <ide> } <ide> <ide> public InstanceFilter(Collection<? extends T> includes, <ide> * Determine if the specified {code instance} matches this filter. <ide> */ <ide> public boolean match(T instance) { <del> Assert.notNull(instance, "The instance to match is mandatory"); <add> Assert.notNull(instance, "Instance to match must not be null"); <ide> <ide> boolean includesSet = !this.includes.isEmpty(); <ide> boolean excludesSet = !this.excludes.isEmpty(); <ide> public boolean match(T instance) { <ide> <ide> boolean matchIncludes = match(instance, this.includes); <ide> boolean matchExcludes = match(instance, this.excludes); <del> <ide> if (!includesSet) { <ide> return !matchExcludes; <ide> } <del> <ide> if (!excludesSet) { <ide> return matchIncludes; <ide> } <ide><path>spring-core/src/main/java/org/springframework/util/MimeType.java <ide> public MimeType(String type) { <ide> * @throws IllegalArgumentException if any of the parameters contains illegal characters <ide> */ <ide> public MimeType(String type, String subtype) { <del> this(type, subtype, Collections.<String, String>emptyMap()); <add> this(type, subtype, Collections.emptyMap()); <ide> } <ide> <ide> /** <ide><path>spring-core/src/main/java/org/springframework/util/xml/SimpleNamespaceContext.java <ide> else if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespaceUri)) { <ide> } <ide> else { <ide> Set<String> prefixes = this.namespaceUriToPrefixes.get(namespaceUri); <del> return (prefixes != null ? Collections.unmodifiableSet(prefixes) : Collections.<String>emptySet()); <add> return (prefixes != null ? Collections.unmodifiableSet(prefixes) : Collections.emptySet()); <ide> } <ide> } <ide> <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ExpressionState.java <ide> public void enterScope(Map<String, Object> argMap) { <ide> <ide> public void enterScope() { <ide> ensureVariableScopesInitialized(); <del> this.variableScopes.push(new VariableScope(Collections.<String,Object>emptyMap())); <add> this.variableScopes.push(new VariableScope(Collections.emptyMap())); <ide> this.scopeRootObjects.push(getActiveContextObject()); <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/DestinationPatternsMessageCondition.java <ide> private DestinationPatternsMessageCondition(Collection<String> patterns, PathMat <ide> <ide> <ide> private static List<String> asList(String... patterns) { <del> return (patterns != null ? Arrays.asList(patterns) : Collections.<String>emptyList()); <add> return (patterns != null ? Arrays.asList(patterns) : Collections.emptyList()); <ide> } <ide> <ide> private static Set<String> prependLeadingSlash(Collection<String> patterns, PathMatcher pathMatcher) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/broker/AbstractBrokerMessageHandler.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 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 AbstractBrokerMessageHandler(SubscribableChannel inboundChannel, MessageChannel outboundChannel, <ide> SubscribableChannel brokerChannel) { <ide> <del> this(inboundChannel, outboundChannel, brokerChannel, Collections.<String>emptyList()); <add> this(inboundChannel, outboundChannel, brokerChannel, Collections.emptyList()); <ide> } <ide> <ide> /** <ide> public AbstractBrokerMessageHandler(SubscribableChannel inboundChannel, MessageC <ide> this.clientOutboundChannel = outboundChannel; <ide> this.brokerChannel = brokerChannel; <ide> <del> destinationPrefixes = (destinationPrefixes != null) ? destinationPrefixes : Collections.<String>emptyList(); <add> destinationPrefixes = (destinationPrefixes != null) ? destinationPrefixes : Collections.emptyList(); <ide> this.destinationPrefixes = Collections.unmodifiableCollection(destinationPrefixes); <ide> } <ide> <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/config/AbstractBrokerRegistration.java <ide> /* <del> * Copyright 2002-2013 the original author or authors. <add> * Copyright 2002-2016 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 AbstractBrokerRegistration(SubscribableChannel clientInboundChannel, <ide> this.clientInboundChannel = clientInboundChannel; <ide> this.clientOutboundChannel = clientOutboundChannel; <ide> <del> this.destinationPrefixes = (destinationPrefixes != null) <del> ? Arrays.<String>asList(destinationPrefixes) : Collections.<String>emptyList(); <add> this.destinationPrefixes = (destinationPrefixes != null ? <add> Arrays.asList(destinationPrefixes) : Collections.emptyList()); <ide> } <ide> <ide> <ide> protected Collection<String> getDestinationPrefixes() { <ide> return this.destinationPrefixes; <ide> } <ide> <add> <ide> protected abstract AbstractBrokerMessageHandler getMessageHandler(SubscribableChannel brokerChannel); <ide> <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompHeaderAccessor.java <ide> protected MessageHeaderAccessor createAccessor(Message<?> message) { <ide> Map<String, List<String>> getNativeHeaders() { <ide> @SuppressWarnings("unchecked") <ide> Map<String, List<String>> map = (Map<String, List<String>>) getHeader(NATIVE_HEADERS); <del> return (map != null ? map : Collections.<String, List<String>>emptyMap()); <add> return (map != null ? map : Collections.emptyMap()); <ide> } <ide> <ide> public StompCommand updateStompCommandAsClientMessage() { <ide> public void setAcceptVersion(String acceptVersion) { <ide> <ide> public Set<String> getAcceptVersion() { <ide> String rawValue = getFirstNativeHeader(STOMP_ACCEPT_VERSION_HEADER); <del> return (rawValue != null ? StringUtils.commaDelimitedListToSet(rawValue) : Collections.<String>emptySet()); <add> return (rawValue != null ? StringUtils.commaDelimitedListToSet(rawValue) : Collections.emptySet()); <ide> } <ide> <ide> public void setHost(String host) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/user/DefaultUserDestinationResolver.java <ide> else if (SimpMessageType.MESSAGE.equals(messageType)) { <ide> } <ide> } <ide> else { <del> sessionIds = Collections.<String>emptySet(); <add> sessionIds = Collections.emptySet(); <ide> } <ide> } <ide> if (!this.keepLeadingSlash) { <ide><path>spring-messaging/src/main/java/org/springframework/messaging/support/NativeMessageHeaderAccessor.java <ide> private Map<String, List<String>> getNativeHeaders() { <ide> */ <ide> public Map<String, List<String>> toNativeHeaderMap() { <ide> Map<String, List<String>> map = getNativeHeaders(); <del> return (map != null ? new LinkedMultiValueMap<>(map) : Collections.<String, List<String>>emptyMap()); <add> return (map != null ? new LinkedMultiValueMap<>(map) : Collections.emptyMap()); <ide> } <ide> <ide> @Override <ide><path>spring-messaging/src/main/java/org/springframework/messaging/tcp/reactor/Reactor2TcpClient.java <ide> private static class SynchronousDispatcherConfigReader implements ConfigurationR <ide> <ide> @Override <ide> public ReactorConfiguration read() { <del> return new ReactorConfiguration( <del> Collections.<DispatcherConfiguration>emptyList(), "sync", new Properties()); <add> return new ReactorConfiguration(Collections.emptyList(), "sync", new Properties()); <ide> } <ide> } <ide> <ide><path>spring-test/src/main/java/org/springframework/mock/web/MockServletContext.java <ide> public Servlet getServlet(String name) { <ide> @Override <ide> @Deprecated <ide> public Enumeration<Servlet> getServlets() { <del> return Collections.enumeration(Collections.<Servlet>emptySet()); <add> return Collections.enumeration(Collections.emptySet()); <ide> } <ide> <ide> @Override <ide> @Deprecated <ide> public Enumeration<String> getServletNames() { <del> return Collections.enumeration(Collections.<String>emptySet()); <add> return Collections.enumeration(Collections.emptySet()); <ide> } <ide> <ide> @Override <ide><path>spring-test/src/main/java/org/springframework/test/context/support/TestPropertySourceUtils.java <ide> private static String[] mergeProperties(List<TestPropertySourceAttributes> attri <ide> if (logger.isTraceEnabled()) { <ide> logger.trace(String.format("Processing inlined properties for TestPropertySource attributes %s", attrs)); <ide> } <del> properties.addAll(0, Arrays.<String>asList(attrs.getProperties())); <add> properties.addAll(0, Arrays.asList(attrs.getProperties())); <ide> if (!attrs.isInheritProperties()) { <ide> break; <ide> } <ide><path>spring-web/src/main/java/org/springframework/http/MediaType.java <ide> public MediaType(String type) { <ide> * @throws IllegalArgumentException if any of the parameters contain illegal characters <ide> */ <ide> public MediaType(String type, String subtype) { <del> super(type, subtype, Collections.<String, String>emptyMap()); <add> super(type, subtype, Collections.emptyMap()); <ide> } <ide> <ide> /** <ide> public static List<MediaType> parseMediaTypes(String mediaTypes) { <ide> */ <ide> public static List<MediaType> parseMediaTypes(List<String> mediaTypes) { <ide> if (CollectionUtils.isEmpty(mediaTypes)) { <del> return Collections.<MediaType>emptyList(); <add> return Collections.emptyList(); <ide> } <ide> else if (mediaTypes.size() == 1) { <ide> return parseMediaTypes(mediaTypes.get(0)); <ide><path>spring-web/src/main/java/org/springframework/http/client/InterceptingAsyncClientHttpRequestFactory.java <ide> public InterceptingAsyncClientHttpRequestFactory(AsyncClientHttpRequestFactory d <ide> List<AsyncClientHttpRequestInterceptor> interceptors) { <ide> <ide> this.delegate = delegate; <del> this.interceptors = (interceptors != null ? interceptors : Collections.<AsyncClientHttpRequestInterceptor>emptyList()); <add> this.interceptors = (interceptors != null ? interceptors : Collections.emptyList()); <ide> } <ide> <ide> <ide><path>spring-web/src/main/java/org/springframework/http/client/InterceptingClientHttpRequestFactory.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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 InterceptingClientHttpRequestFactory(ClientHttpRequestFactory requestFact <ide> List<ClientHttpRequestInterceptor> interceptors) { <ide> <ide> super(requestFactory); <del> this.interceptors = (interceptors != null ? interceptors : Collections.<ClientHttpRequestInterceptor>emptyList()); <add> this.interceptors = (interceptors != null ? interceptors : Collections.emptyList()); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/web/accept/HeaderContentNegotiationStrategy.java <ide> public List<MediaType> resolveMediaTypes(NativeWebRequest request) <ide> <ide> String[] headerValueArray = request.getHeaderValues(HttpHeaders.ACCEPT); <ide> if (headerValueArray == null) { <del> return Collections.<MediaType>emptyList(); <add> return Collections.emptyList(); <ide> } <ide> <ide> List<String> headerValues = Arrays.asList(headerValueArray); <ide><path>spring-web/src/main/java/org/springframework/web/accept/MappingMediaTypeFileExtensionResolver.java <ide> protected void addMapping(String extension, MediaType mediaType) { <ide> @Override <ide> public List<String> resolveFileExtensions(MediaType mediaType) { <ide> List<String> fileExtensions = this.fileExtensions.get(mediaType); <del> return (fileExtensions != null) ? fileExtensions : Collections.<String>emptyList(); <add> return (fileExtensions != null) ? fileExtensions : Collections.emptyList(); <ide> } <ide> <ide> @Override <ide><path>spring-web/src/main/java/org/springframework/web/filter/ForwardedHeaderFilter.java <ide> public String getHeader(String name) { <ide> @Override <ide> public Enumeration<String> getHeaders(String name) { <ide> List<String> value = this.headers.get(name); <del> return (Collections.enumeration(value != null ? value : Collections.<String>emptySet())); <add> return (Collections.enumeration(value != null ? value : Collections.emptySet())); <ide> } <ide> <ide> @Override <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerMethodMapping.java <ide> private List<String> getDirectUrls(T mapping) { <ide> private void addMappingName(String name, HandlerMethod handlerMethod) { <ide> List<HandlerMethod> oldList = this.nameLookup.get(name); <ide> if (oldList == null) { <del> oldList = Collections.<HandlerMethod>emptyList(); <add> oldList = Collections.emptyList(); <ide> } <ide> <ide> for (HandlerMethod current : oldList) { <ide> public MappingRegistration(T mapping, HandlerMethod handlerMethod, List<String> <ide> Assert.notNull(handlerMethod); <ide> this.mapping = mapping; <ide> this.handlerMethod = handlerMethod; <del> this.directUrls = (directUrls != null ? directUrls : Collections.<String>emptyList()); <add> this.directUrls = (directUrls != null ? directUrls : Collections.emptyList()); <ide> this.mappingName = mappingName; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/handler/SimpleServletPostProcessor.java <ide> public String getInitParameter(String paramName) { <ide> <ide> @Override <ide> public Enumeration<String> getInitParameterNames() { <del> return Collections.enumeration(Collections.<String>emptySet()); <add> return Collections.enumeration(Collections.emptySet()); <ide> } <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/PatternsRequestCondition.java <ide> private PatternsRequestCondition(Collection<String> patterns, UrlPathHelper urlP <ide> <ide> <ide> private static List<String> asList(String... patterns) { <del> return (patterns != null ? Arrays.asList(patterns) : Collections.<String>emptyList()); <add> return (patterns != null ? Arrays.asList(patterns) : Collections.emptyList()); <ide> } <ide> <ide> private static Set<String> prependLeadingSlash(Collection<String> patterns) { <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/RequestMethodsRequestCondition.java <ide> private RequestMethodsRequestCondition(Collection<RequestMethod> requestMethods) <ide> <ide> <ide> private static List<RequestMethod> asList(RequestMethod... requestMethods) { <del> return (requestMethods != null ? Arrays.asList(requestMethods) : Collections.<RequestMethod>emptyList()); <add> return (requestMethods != null ? Arrays.asList(requestMethods) : Collections.emptyList()); <ide> } <ide> <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ServletModelAttributeMethodProcessor.java <ide> /* <del> * Copyright 2002-2015 the original author or authors. <add> * Copyright 2002-2016 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> else if (StringUtils.hasText(request.getParameter(attributeName))) { <ide> protected final Map<String, String> getUriTemplateVariables(NativeWebRequest request) { <ide> Map<String, String> variables = (Map<String, String>) request.getAttribute( <ide> HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); <del> return (variables != null ? variables : Collections.<String, String>emptyMap()); <add> return (variables != null ? variables : Collections.emptyMap()); <ide> } <ide> <ide> /** <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java <ide> SseEventBuilderImpl append(String text) { <ide> @Override <ide> public Set<DataWithMediaType> build() { <ide> if ((this.sb == null || this.sb.length() == 0) && this.dataToSend.isEmpty()) { <del> return Collections.<DataWithMediaType>emptySet(); <add> return Collections.emptySet(); <ide> } <ide> append("\n"); <ide> saveAppendedText(); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/freemarker/FreeMarkerView.java <ide> public String getInitParameter(String paramName) { <ide> <ide> @Override <ide> public Enumeration<String> getInitParameterNames() { <del> return Collections.enumeration(Collections.<String>emptySet()); <add> return Collections.enumeration(Collections.emptySet()); <ide> } <ide> } <ide> <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/client/AbstractWebSocketClient.java <ide> */ <ide> public abstract class AbstractWebSocketClient implements WebSocketClient { <ide> <del> protected final Log logger = LogFactory.getLog(getClass()); <del> <ide> private static final Set<String> specialHeaders = new HashSet<>(); <ide> <ide> static { <ide> public abstract class AbstractWebSocketClient implements WebSocketClient { <ide> } <ide> <ide> <add> protected final Log logger = LogFactory.getLog(getClass()); <add> <add> <ide> @Override <ide> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <ide> String uriTemplate, Object... uriVars) { <ide> <del> Assert.notNull(uriTemplate, "uriTemplate must not be null"); <add> Assert.notNull(uriTemplate, "'uriTemplate' must not be null"); <ide> URI uri = UriComponentsBuilder.fromUriString(uriTemplate).buildAndExpand(uriVars).encode().toUri(); <ide> return doHandshake(webSocketHandler, null, uri); <ide> } <ide> public ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocket <ide> public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler webSocketHandler, <ide> WebSocketHttpHeaders headers, URI uri) { <ide> <del> Assert.notNull(webSocketHandler, "webSocketHandler must not be null"); <add> Assert.notNull(webSocketHandler, "WebSocketHandler must not be null"); <ide> assertUri(uri); <ide> <ide> if (logger.isDebugEnabled()) { <ide> public final ListenableFuture<WebSocketSession> doHandshake(WebSocketHandler web <ide> } <ide> } <ide> <del> List<String> subProtocols = ((headers != null) && (headers.getSecWebSocketProtocol() != null)) ? <del> headers.getSecWebSocketProtocol() : Collections.<String>emptyList(); <add> List<String> subProtocols = (headers != null && headers.getSecWebSocketProtocol() != null ? <add> headers.getSecWebSocketProtocol() : Collections.emptyList()); <ide> <del> List<WebSocketExtension> extensions = ((headers != null) && (headers.getSecWebSocketExtensions() != null)) ? <del> headers.getSecWebSocketExtensions() : Collections.<WebSocketExtension>emptyList(); <add> List<WebSocketExtension> extensions = (headers != null && headers.getSecWebSocketExtensions() != null ? <add> headers.getSecWebSocketExtensions() : Collections.emptyList()); <ide> <ide> return doHandshakeInternal(webSocketHandler, headersToUse, uri, subProtocols, extensions, <del> Collections.<String, Object>emptyMap()); <add> Collections.emptyMap()); <ide> } <ide> <ide> protected void assertUri(URI uri) { <del> Assert.notNull(uri, "uri must not be null"); <add> Assert.notNull(uri, "URI must not be null"); <ide> String scheme = uri.getScheme(); <del> Assert.isTrue(scheme != null && ("ws".equals(scheme) || "wss".equals(scheme)), "Invalid scheme: " + scheme); <add> if (!"ws".equals(scheme) && !"wss".equals(scheme)) { <add> throw new IllegalArgumentException("Invalid scheme: " + scheme); <add> } <ide> } <ide> <ide> /** <ide> * Perform the actual handshake to establish a connection to the server. <del> * <ide> * @param webSocketHandler the client-side handler for WebSocket messages <ide> * @param headers HTTP headers to use for the handshake, with unwanted (forbidden) <ide> * headers filtered out, never {@code null} <ide> protected void assertUri(URI uri) { <ide> * @param extensions requested WebSocket extensions, or an empty list <ide> * @param attributes attributes to associate with the WebSocketSession, i.e. via <ide> * {@link WebSocketSession#getAttributes()}; currently always an empty map. <del> * <ide> * @return the established WebSocket session wrapped in a ListenableFuture. <ide> */ <ide> protected abstract ListenableFuture<WebSocketSession> doHandshakeInternal(WebSocketHandler webSocketHandler, <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/WebSocketStompClient.java <ide> public StompWebSocketMessageCodec(int messageSizeLimit) { <ide> } <ide> <ide> public List<Message<byte[]>> decode(WebSocketMessage<?> webSocketMessage) { <del> List<Message<byte[]>> result = Collections.<Message<byte[]>>emptyList(); <add> List<Message<byte[]>> result = Collections.emptyList(); <ide> ByteBuffer byteBuffer; <ide> if (webSocketMessage instanceof TextMessage) { <ide> byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes()); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/standard/UndertowRequestUpgradeStrategy.java <ide> protected void upgradeInternal(ServerHttpRequest request, ServerHttpResponse res <ide> <ide> StringBuffer requestUrl = servletRequest.getRequestURL(); <ide> String path = servletRequest.getRequestURI(); // shouldn't matter <del> Map<String, String> pathParams = Collections.<String, String>emptyMap(); <add> Map<String, String> pathParams = Collections.emptyMap(); <ide> <ide> ServerEndpointRegistration endpointConfig = new ServerEndpointRegistration(path, endpoint); <ide> endpointConfig.setSubprotocols(Collections.singletonList(selectedProtocol)); <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java <ide> protected final List<String> determineHandlerSupportedProtocols(WebSocketHandler <ide> if (handlerToCheck instanceof SubProtocolCapable) { <ide> subProtocols = ((SubProtocolCapable) handlerToCheck).getSubProtocols(); <ide> } <del> return (subProtocols != null ? subProtocols : Collections.<String>emptyList()); <add> return (subProtocols != null ? subProtocols : Collections.emptyList()); <ide> } <ide> <ide> /** <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/HandshakeInterceptorChain.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2016 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 HandshakeInterceptorChain { <ide> <ide> <ide> public HandshakeInterceptorChain(List<HandshakeInterceptor> interceptors, WebSocketHandler wsHandler) { <del> this.interceptors = (interceptors != null ? interceptors : Collections.<HandshakeInterceptor>emptyList()); <add> this.interceptors = (interceptors != null ? interceptors : Collections.emptyList()); <ide> this.wsHandler = wsHandler; <ide> } <ide>
35
PHP
PHP
remove locale routing stuff
5f78e404c665c5f70d845b7514d87bc751d44fd5
<ide><path>src/Illuminate/Foundation/Application.php <ide> public function __construct(Request $request = null) <ide> */ <ide> protected function createRequest(Request $request = null) <ide> { <del> $request = $request ?: Request::createFromGlobals(); <del> <del> $this->registerLocaleHandler($request); <del> <del> return $request; <del> } <del> <del> /** <del> * Register the URI locale boot handler. <del> * <del> * @param Illuminate\Http\Request $request <del> * @return void <del> */ <del> protected function registerLocaleHandler(Request $request) <del> { <del> $this->booting(function($app) use ($request) <del> { <del> $locales = $app['config']->get('app.locales', array()); <del> <del> // Here, we will check to see if the incoming request begins with any of the <del> // supported locales. If it does, we will set that locale as this default <del> // for an application and remove it from the current request path info. <del> $locale = $request->handleUriLocales($locales); <del> <del> if ($locale) <del> { <del> $app->setLocale($locale); <del> <del> $app['url']->setPrefix($locale); <del> } <del> }); <add> return $request ?: Request::createFromGlobals(); <ide> } <ide> <ide> /** <ide><path>src/Illuminate/Routing/UrlGenerator.php <ide> class UrlGenerator { <ide> */ <ide> protected $generator; <ide> <del> /** <del> * The global prefix for the generator. <del> * <del> * @var string <del> */ <del> protected $prefix; <del> <ide> /** <ide> * Create a new URL Generator instance. <ide> * <ide> public function to($path, $parameters = array(), $secure = null) <ide> <ide> $root = $this->getRootUrl($scheme); <ide> <del> return trim($root.$this->getPrefix().'/'.trim($path.'/'.$tail, '/'), '/'); <add> return trim($root.'/'.trim($path.'/'.$tail, '/'), '/'); <ide> } <ide> <ide> /** <ide> public function route($name, $parameters = array()) <ide> $parameters = $this->buildParameterList($route, $parameters); <ide> } <ide> <del> return $this->getPrefix().$this->generator->generate($name, $parameters, true); <add> return $this->generator->generate($name, $parameters, true); <ide> } <ide> <ide> /** <ide> public function isValidUrl($path) <ide> return filter_var($path, FILTER_VALIDATE_URL) !== false; <ide> } <ide> <del> /** <del> * Set a global prefix on the generator. <del> * <del> * @return string <del> */ <del> public function getPrefix() <del> { <del> return isset($this->prefix) ? '/'.$this->prefix : ''; <del> } <del> <del> /** <del> * Set the global prefix on the generator. <del> * <del> * @param string $prefix <del> * @return void <del> */ <del> public function setPrefix($prefix) <del> { <del> $this->prefix = $prefix; <del> } <del> <ide> /** <ide> * Get the request instance. <ide> * <ide><path>tests/Foundation/FoundationApplicationTest.php <ide> public function testServiceProvidersAreCorrectlyRegistered() <ide> $this->assertTrue(in_array($class, $app->getLoadedProviders())); <ide> } <ide> <del> <del> public function testLocaleDetectionOnBoot() <del> { <del> $request = Illuminate\Http\Request::create('/en/foo/bar', 'GET'); <del> $application = $this->getMock('Illuminate\Foundation\Application', array('setLocale'), array($request)); <del> $application->instance('config', $config = m::mock('StdClass')); <del> $config->shouldReceive('get')->once()->with('app.locales', array())->andReturn(array('en')); <del> $application->instance('url', $url = m::mock('StdClass')); <del> $url->shouldReceive('setPrefix')->once()->with('en'); <del> $application->expects($this->once())->method('setLocale')->with($this->equalTo('en')); <del> <del> $application->boot(); <del> } <del> <ide> } <ide> <ide> class ApplicationCustomExceptionHandlerStub extends Illuminate\Foundation\Application { <ide><path>tests/Routing/RoutingUrlGeneratorTest.php <ide> public function testUrlGenerationUsesCurrentProtocol() <ide> } <ide> <ide> <del> public function testGeneratorGlobalPrefixes() <del> { <del> $gen = $this->getGenerator(); <del> $gen->setRequest(Request::create('http://foobar.com/foo/bar', 'GET')); <del> $gen->setPrefix('en'); <del> <del> $this->assertEquals('http://foobar.com/en/dayle', $gen->to('dayle')); <del> } <del> <del> <ide> public function testAssetUrlGeneration() <ide> { <ide> $gen = $this->getGenerator(); <ide> public function testRouteUrlGeneration() <ide> { <ide> $gen = $this->getGenerator(); <ide> $symfonyGen = m::mock('Symfony\Component\Routing\Generator\UrlGenerator'); <del> $symfonyGen->shouldReceive('generate')->once()->with('foo.bar', array('name' => 'taylor')); <add> $symfonyGen->shouldReceive('generate')->once()->with('foo.bar', array('name' => 'taylor'), true); <ide> $gen->setRequest(Request::create('http://foobar.com', 'GET')); <ide> $gen->setGenerator($symfonyGen); <ide> <ide> $gen->route('foo.bar', array('name' => 'taylor')); <ide> } <ide> <ide> <del> public function testRouteUrlGenerationWithPrefixes() <del> { <del> $gen = $this->getGenerator(); <del> $symfonyGen = m::mock('Symfony\Component\Routing\Generator\UrlGenerator'); <del> $symfonyGen->shouldReceive('generate')->once()->with('foo.bar', array('name' => 'taylor'))->andReturn('boom/breeze'); <del> $gen->setRequest(Request::create('http://foobar.com', 'GET')); <del> $gen->setGenerator($symfonyGen); <del> $gen->setPrefix('en'); <del> <del> $result = $gen->route('foo.bar', array('name' => 'taylor')); <del> <del> $this->assertEquals('http://foobar.com/en/boom/breeze', $result); <del> } <del> <del> <ide> public function testRouteUrlGenerationWithOptional() <ide> { <ide> $gen = $this->getGenerator(); <ide> $symfonyGen = m::mock('Symfony\Component\Routing\Generator\UrlGenerator'); <del> $symfonyGen->shouldReceive('generate')->once()->with('foo.boom', array()); <add> $symfonyGen->shouldReceive('generate')->once()->with('foo.boom', array(), true); <ide> $gen->setRequest(Request::create('http://foobar.com', 'GET')); <ide> $gen->setGenerator($symfonyGen); <ide> <ide> public function testRouteParametersCanBeShortCircuited() <ide> { <ide> $gen = $this->getGenerator(); <ide> $symfonyGen = m::mock('Symfony\Component\Routing\Generator\UrlGenerator'); <del> $symfonyGen->shouldReceive('generate')->once()->with('foo.baz', array('name' => 'taylor', 'age' => 25)); <add> $symfonyGen->shouldReceive('generate')->once()->with('foo.baz', array('name' => 'taylor', 'age' => 25), true); <ide> $gen->setRequest(Request::create('http://foobar.com', 'GET')); <ide> $gen->setGenerator($symfonyGen); <ide> <ide> public function testRouteParametersCanBeShortCircuitedWithOptionals() <ide> { <ide> $gen = $this->getGenerator(); <ide> $symfonyGen = m::mock('Symfony\Component\Routing\Generator\UrlGenerator'); <del> $symfonyGen->shouldReceive('generate')->once()->with('foo.breeze', array('boom' => 'bar', 'breeze' => null)); <add> $symfonyGen->shouldReceive('generate')->once()->with('foo.breeze', array('boom' => 'bar', 'breeze' => null), true); <ide> $gen->setRequest(Request::create('http://foobar.com', 'GET')); <ide> $gen->setGenerator($symfonyGen); <ide>
4
PHP
PHP
update typehints for event/
744065a75a635bdebe61199ae5a884856a31d27e
<ide><path>src/Event/EventDispatcherInterface.php <ide> interface EventDispatcherInterface <ide> * <ide> * @return \Cake\Event\EventInterface <ide> */ <del> public function dispatchEvent(string $name, $data = null, $subject = null): EventInterface; <add> public function dispatchEvent(string $name, ?array $data = null, ?object $subject = null): EventInterface; <ide> <ide> /** <ide> * Sets the Cake\Event\EventManager manager instance for this object. <ide><path>src/Event/EventDispatcherTrait.php <ide> public function setEventManager(EventManagerInterface $eventManager) <ide> * <ide> * @return \Cake\Event\EventInterface <ide> */ <del> public function dispatchEvent(string $name, $data = null, $subject = null): EventInterface <add> public function dispatchEvent(string $name, ?array $data = null, ?object $subject = null): EventInterface <ide> { <ide> if ($subject === null) { <ide> $subject = $this; <ide><path>src/Event/EventList.php <ide> class EventList implements ArrayAccess, Countable <ide> * <ide> * @return void <ide> */ <del> public function flush() <add> public function flush(): void <ide> { <ide> $this->_events = []; <ide> } <ide> public function count(): int <ide> * @param string $name Event name. <ide> * @return bool <ide> */ <del> public function hasEvent($name): bool <add> public function hasEvent(string $name): bool <ide> { <ide> foreach ($this->_events as $event) { <ide> if ($event->getName() === $name) { <ide><path>src/Event/EventManager.php <ide> public function listeners(string $eventKey): array <ide> * @param string $eventKey Event key. <ide> * @return array <ide> */ <del> public function prioritisedListeners($eventKey) <add> public function prioritisedListeners(string $eventKey): array <ide> { <ide> if (empty($this->_listeners[$eventKey])) { <ide> return []; <ide> public function prioritisedListeners($eventKey) <ide> * @param string $eventKeyPattern Pattern to match. <ide> * @return array <ide> */ <del> public function matchingListeners($eventKeyPattern) <add> public function matchingListeners(string $eventKeyPattern): array <ide> { <ide> $matchPattern = '/' . preg_quote($eventKeyPattern, '/') . '/'; <ide> $matches = array_intersect_key( <ide> public function addEventToList(EventInterface $event) <ide> * @param bool $enabled True or false to enable / disable it. <ide> * @return $this <ide> */ <del> public function trackEvents($enabled) <add> public function trackEvents(bool $enabled) <ide> { <ide> $this->_trackEvents = (bool)$enabled; <ide> <ide> public function trackEvents($enabled) <ide> * <ide> * @return bool <ide> */ <del> public function isTrackingEvents() <add> public function isTrackingEvents(): bool <ide> { <ide> return $this->_trackEvents && $this->_eventList; <ide> } <ide> public function unsetEventList() <ide> * <ide> * @return array <ide> */ <del> public function __debugInfo() <add> public function __debugInfo(): array <ide> { <ide> $properties = get_object_vars($this); <ide> $properties['_generalManager'] = '(object) EventManager';
4
Go
Go
fix issue with multiple volume refs with same name
0fe31306d1c1c93c4ef33654f7a37932296cf8a6
<ide><path>volume/store/store.go <ide> func (s *VolumeStore) Dereference(v volume.Volume, ref string) { <ide> <ide> s.globalLock.Lock() <ide> defer s.globalLock.Unlock() <del> refs, exists := s.refs[v.Name()] <del> if !exists { <del> return <del> } <add> var refs []string <ide> <del> for i, r := range refs { <del> if r == ref { <del> s.refs[v.Name()] = append(s.refs[v.Name()][:i], s.refs[v.Name()][i+1:]...) <add> for _, r := range s.refs[v.Name()] { <add> if r != ref { <add> refs = append(refs, r) <ide> } <ide> } <add> s.refs[v.Name()] = refs <ide> } <ide> <ide> // Refs gets the current list of refs for the given volume <ide><path>volume/store/store_test.go <ide> func TestFilterByUsed(t *testing.T) { <ide> t.Fatalf("expected used volume fake1, got %s", used[0].Name()) <ide> } <ide> } <add> <add>func TestDerefMultipleOfSameRef(t *testing.T) { <add> volumedrivers.Register(vt.NewFakeDriver("fake"), "fake") <add> <add> s := New() <add> v, err := s.CreateWithRef("fake1", "fake", "volReference", nil) <add> if err != nil { <add> t.Fatal(err) <add> } <add> <add> if _, err := s.GetWithRef("fake1", "fake", "volReference"); err != nil { <add> t.Fatal(err) <add> } <add> <add> s.Dereference(v, "volReference") <add> if err := s.Remove(v); err != nil { <add> t.Fatal(err) <add> } <add>}
2
Text
Text
add railties info to 5.1 release notes
ee9f97de94fef19550da3006f36e5090d138cdbc
<ide><path>guides/source/5_1_release_notes.md <ide> Please refer to the [Changelog][railties] for detailed changes. <ide> <ide> ### Removals <ide> <add>* Remove deprecated `config.static_cache_control`. <add> ([commit](https://github.com/rails/rails/commit/c861decd44198f8d7d774ee6a74194d1ac1a5a13) <add> <add>* Remove deprecated `config.serve_static_files`. <add> ([commit](https://github.com/rails/rails/commit/0129ca2eeb6d5b2ea8c6e6be38eeb770fe45f1fa)) <add> <add>* Remove deprecated file `rails/rack/debugger`. <add> ([commit](https://github.com/rails/rails/commit/7563bf7b46e6f04e160d664e284a33052f9804b8)) <add> <add>* Remove deprecated tasks: `rails:update`, `rails:template`, `rails:template:copy`, <add> `rails:update:configs` and `rails:update:bin`. <add> ([commit](https://github.com/rails/rails/commit/f7782812f7e727178e4a743aa2874c078b722eef)) <add> <add>* Remove deprecated `CONTROLLER` environment variable for `routes` task. <add> ([commit](https://github.com/rails/rails/commit/f9ed83321ac1d1902578a0aacdfe55d3db754219)) <add> <add>* Remove -j (--javascript) option from `rails new` command. <add> ([Pull Request](https://github.com/rails/rails/pull/28546)) <add> <ide> ### Deprecations <ide> <ide> ### Notable changes <ide> <add>* The config file `secrets.yml` is now loaded in with all keys as symbols. <add> ([Pull Request](https://github.com/rails/rails/pull/26929)) <add> <add>* Removed jquery-rails from default stack. rails-ujs, which is shipped <add> with Action View, is included as default UJS adapter. <add> ([Pull Request](https://github.com/rails/rails/pull/27113)) <add> <add>* Add Yarn support in new apps with a yarn binstub and package.json. <add> ([Pull Request](https://github.com/rails/rails/pull/26836)) <add> <add>* Add Webpack support in new apps via the --webpack option, which will delegate <add> to the rails/webpacker gem. <add> ([Pull Request](https://github.com/rails/rails/pull/27288)) <add> <add>* Add encrypted secrets in `config/secrets.yml.enc`. <add> ([Pull Request](https://github.com/rails/rails/pull/28038)) <add> <ide> Action Cable <ide> ----------- <ide>
1
Python
Python
crerate ti context with data interval compat layer
1159133040b3513bcc88921823fa001e9773276d
<ide><path>airflow/models/taskinstance.py <ide> def get_template_context(self, session: Session = None, ignore_param_exceptions: <ide> integrate_macros_plugins() <ide> <ide> dag_run = self.get_dagrun(session) <add> data_interval = dag.get_run_data_interval(dag_run) <ide> <ide> params = ParamsDict(suppress_exception=ignore_param_exceptions) <ide> <ide> def get_prev_ds_nodash() -> Optional[str]: <ide> 'conf': conf, <ide> 'dag': dag, <ide> 'dag_run': dag_run, <del> 'data_interval_end': timezone.coerce_datetime(dag_run.data_interval_end), <del> 'data_interval_start': timezone.coerce_datetime(dag_run.data_interval_start), <add> 'data_interval_end': timezone.coerce_datetime(data_interval.end), <add> 'data_interval_start': timezone.coerce_datetime(data_interval.start), <ide> 'ds': ds, <ide> 'ds_nodash': ds_nodash, <ide> 'execution_date': deprecated_proxy(
1
Text
Text
update ruby version to 2.3.1p112
913542f79432ba85aed25ebe1699e585554ba150
<ide><path>guides/source/getting_started.md <ide> current version of Ruby installed: <ide> <ide> ```bash <ide> $ ruby -v <del>ruby 2.3.0p0 <add>ruby 2.3.1p112 <ide> ``` <ide> <ide> TIP: A number of tools exist to help you quickly install Ruby and Ruby
1
Javascript
Javascript
use regex to hide hikes
c736a5c00ff6a4db3cb98b290cd03b68f020b69a
<ide><path>seed/index.js <ide> destroy() <ide> challenge.order = order; <ide> challenge.suborder = index + 1; <ide> challenge.block = block; <del> challenge.superBlock = superBlock; <ide> challenge.isBeta = challenge.isBeta || isBeta; <ide> challenge.time = challengeSpec.time; <add> challenge.superBlock = superBlock <add> .split('-') <add> .map(function(word) { <add> return _.capitalize(word); <add> }) <add> .join(' '); <ide> <ide> return challenge; <ide> }); <ide><path>server/boot/challenge.js <ide> module.exports = function(app) { <ide> challenges: blockArray, <ide> superBlock: blockArray[0].superBlock <ide> })) <del> .filter(({ name })=> { <del> return name !== 'Hikes'; <add> .filter(({ superBlock }) => { <add> console.log('sup', superBlock); <add> return challengesRegex.test(superBlock); <ide> }) <ide> .groupBy(block => block.superBlock) <ide> .flatMap(superBlocks$ => superBlocks$.toArray()) <ide> module.exports = function(app) { <ide> // find challenge <ide> return challenge$ <ide> .map(challenge => challenge.toJSON()) <del> .filter(({ superBlock }) => superBlock !== 'hikes') <add> .filter(({ superBlock }) => challengesRegex.test(superBlock)) <ide> .filter(({ id }) => id === challengeId) <ide> // now lets find the block it belongs to <ide> .flatMap(challenge => { <ide> module.exports = function(app) { <ide> time: blockArray[0] && blockArray[0].time || '???' <ide> }; <ide> }) <del> .filter(({ superBlock }) => superBlock !== 'hikes') <add> .filter(({ superBlock }) => { <add> return !(/hikes/i).test(superBlock); <add> }) <ide> // turn stream of blocks into a stream of an array <ide> .toArray() <ide> .doOnNext(blocks => {
2
Javascript
Javascript
fix event replaying
9e7f334c7159b10900a8d197c3df226d32efdc96
<ide><path>packages/react-dom/src/events/DOMModernPluginEventSystem.js <ide> export function dispatchEventForPluginEventSystem( <ide> ) { <ide> return; <ide> } <del> // The below logic attempts to work out if we need to change <del> // the target fiber to a different ancestor. We had similar logic <del> // in the legacy event system, except the big difference between <del> // systems is that the modern event system now has an event listener <del> // attached to each React Root and React Portal Root. Together, <del> // the DOM nodes representing these roots are the "rootContainer". <del> // To figure out which ancestor instance we should use, we traverse <del> // up the fiber tree from the target instance and attempt to find <del> // root boundaries that match that of our current "rootContainer". <del> // If we find that "rootContainer", we find the parent fiber <del> // sub-tree for that root and make that our ancestor instance. <del> let node = targetInst; <add> if (targetInst !== null) { <add> // The below logic attempts to work out if we need to change <add> // the target fiber to a different ancestor. We had similar logic <add> // in the legacy event system, except the big difference between <add> // systems is that the modern event system now has an event listener <add> // attached to each React Root and React Portal Root. Together, <add> // the DOM nodes representing these roots are the "rootContainer". <add> // To figure out which ancestor instance we should use, we traverse <add> // up the fiber tree from the target instance and attempt to find <add> // root boundaries that match that of our current "rootContainer". <add> // If we find that "rootContainer", we find the parent fiber <add> // sub-tree for that root and make that our ancestor instance. <add> let node = targetInst; <ide> <del> while (true) { <del> if (node === null) { <del> return; <del> } <del> if (node.tag === HostRoot || node.tag === HostPortal) { <del> const container = node.stateNode.containerInfo; <del> if (isMatchingRootContainer(container, possibleTargetContainerNode)) { <del> break; <add> while (true) { <add> if (node === null) { <add> return; <ide> } <del> if (node.tag === HostPortal) { <del> // The target is a portal, but it's not the rootContainer we're looking for. <del> // Normally portals handle their own events all the way down to the root. <del> // So we should be able to stop now. However, we don't know if this portal <del> // was part of *our* root. <del> let grandNode = node.return; <del> while (grandNode !== null) { <del> if (grandNode.tag === HostRoot || grandNode.tag === HostPortal) { <del> const grandContainer = grandNode.stateNode.containerInfo; <del> if ( <del> isMatchingRootContainer( <del> grandContainer, <del> possibleTargetContainerNode, <del> ) <del> ) { <del> // This is the rootContainer we're looking for and we found it as <del> // a parent of the Portal. That means we can ignore it because the <del> // Portal will bubble through to us. <del> return; <add> if (node.tag === HostRoot || node.tag === HostPortal) { <add> const container = node.stateNode.containerInfo; <add> if (isMatchingRootContainer(container, possibleTargetContainerNode)) { <add> break; <add> } <add> if (node.tag === HostPortal) { <add> // The target is a portal, but it's not the rootContainer we're looking for. <add> // Normally portals handle their own events all the way down to the root. <add> // So we should be able to stop now. However, we don't know if this portal <add> // was part of *our* root. <add> let grandNode = node.return; <add> while (grandNode !== null) { <add> if (grandNode.tag === HostRoot || grandNode.tag === HostPortal) { <add> const grandContainer = grandNode.stateNode.containerInfo; <add> if ( <add> isMatchingRootContainer( <add> grandContainer, <add> possibleTargetContainerNode, <add> ) <add> ) { <add> // This is the rootContainer we're looking for and we found it as <add> // a parent of the Portal. That means we can ignore it because the <add> // Portal will bubble through to us. <add> return; <add> } <ide> } <add> grandNode = grandNode.return; <ide> } <del> grandNode = grandNode.return; <ide> } <add> const parentSubtreeInst = getClosestInstanceFromNode(container); <add> if (parentSubtreeInst === null) { <add> return; <add> } <add> node = ancestorInst = parentSubtreeInst; <add> continue; <ide> } <del> const parentSubtreeInst = getClosestInstanceFromNode(container); <del> if (parentSubtreeInst === null) { <del> return; <del> } <del> node = ancestorInst = parentSubtreeInst; <del> continue; <add> node = node.return; <ide> } <del> node = node.return; <ide> } <ide> } <ide> <ide><path>packages/react-dom/src/events/ReactDOMEventReplaying.js <ide> type QueuedReplayableEvent = {| <ide> topLevelType: DOMTopLevelEventType, <ide> eventSystemFlags: EventSystemFlags, <ide> nativeEvent: AnyNativeEvent, <del> targetContainer: EventTarget | null, <add> targetContainers: Array<EventTarget>, <ide> |}; <ide> <ide> let hasScheduledReplayAttempt = false; <ide> function createQueuedReplayableEvent( <ide> topLevelType, <ide> eventSystemFlags: eventSystemFlags | IS_REPLAYED, <ide> nativeEvent, <del> targetContainer, <add> targetContainers: targetContainer !== null ? [targetContainer] : [], <ide> }; <ide> } <ide> <ide> function accumulateOrCreateContinuousQueuedReplayableEvent( <ide> } <ide> // If we have already queued this exact event, then it's because <ide> // the different event systems have different DOM event listeners. <del> // We can accumulate the flags and store a single event to be <del> // replayed. <add> // We can accumulate the flags, and the targetContainers, and <add> // store a single event to be replayed. <ide> existingQueuedEvent.eventSystemFlags |= eventSystemFlags; <add> const targetContainers = existingQueuedEvent.targetContainers; <add> if ( <add> targetContainer !== null && <add> targetContainers.indexOf(targetContainer) === -1 <add> ) { <add> targetContainers.push(targetContainer); <add> } <ide> return existingQueuedEvent; <ide> } <ide> <ide> function attemptReplayContinuousQueuedEvent( <ide> if (queuedEvent.blockedOn !== null) { <ide> return false; <ide> } <del> let nextBlockedOn = attemptToDispatchEvent( <del> queuedEvent.topLevelType, <del> queuedEvent.eventSystemFlags, <del> queuedEvent.targetContainer, <del> queuedEvent.nativeEvent, <del> ); <del> if (nextBlockedOn !== null) { <del> // We're still blocked. Try again later. <del> let fiber = getInstanceFromNode(nextBlockedOn); <del> if (fiber !== null) { <del> attemptContinuousHydration(fiber); <add> let targetContainers = queuedEvent.targetContainers; <add> while (targetContainers.length > 0) { <add> let targetContainer = targetContainers[0]; <add> let nextBlockedOn = attemptToDispatchEvent( <add> queuedEvent.topLevelType, <add> queuedEvent.eventSystemFlags, <add> targetContainer, <add> queuedEvent.nativeEvent, <add> ); <add> if (nextBlockedOn !== null) { <add> // We're still blocked. Try again later. <add> let fiber = getInstanceFromNode(nextBlockedOn); <add> if (fiber !== null) { <add> attemptContinuousHydration(fiber); <add> } <add> queuedEvent.blockedOn = nextBlockedOn; <add> return false; <ide> } <del> queuedEvent.blockedOn = nextBlockedOn; <del> return false; <add> // This target container was successfully dispatched. Try the next. <add> targetContainers.shift(); <ide> } <ide> return true; <ide> } <ide> function replayUnblockedEvents() { <ide> } <ide> break; <ide> } <del> let nextBlockedOn = attemptToDispatchEvent( <del> nextDiscreteEvent.topLevelType, <del> nextDiscreteEvent.eventSystemFlags, <del> nextDiscreteEvent.targetContainer, <del> nextDiscreteEvent.nativeEvent, <del> ); <del> if (nextBlockedOn !== null) { <del> // We're still blocked. Try again later. <del> nextDiscreteEvent.blockedOn = nextBlockedOn; <del> } else { <add> let targetContainers = nextDiscreteEvent.targetContainers; <add> while (targetContainers.length > 0) { <add> let targetContainer = targetContainers[0]; <add> let nextBlockedOn = attemptToDispatchEvent( <add> nextDiscreteEvent.topLevelType, <add> nextDiscreteEvent.eventSystemFlags, <add> targetContainer, <add> nextDiscreteEvent.nativeEvent, <add> ); <add> if (nextBlockedOn !== null) { <add> // We're still blocked. Try again later. <add> nextDiscreteEvent.blockedOn = nextBlockedOn; <add> break; <add> } <add> // This target container was successfully dispatched. Try the next. <add> targetContainers.shift(); <add> } <add> if (nextDiscreteEvent.blockedOn === null) { <ide> // We've successfully replayed the first event. Let's try the next one. <ide> queuedDiscreteEvents.shift(); <ide> }
2
Python
Python
add npz support and make zipping optional
0b393d4049afd187ed7d24ea70177a72cf4a3ce2
<ide><path>keras/saving/experimental/saving_lib.py <ide> import warnings <ide> import zipfile <ide> <add>import numpy as np <ide> import tensorflow.compat.v2 as tf <ide> <ide> import keras <ide> <ide> # isort: off <ide> <del>_SELF_DIRNAME = "self" <ide> _CONFIG_FILENAME = "config.json" <ide> _METADATA_FILENAME = "metadata.json" <del>_VARS_FNAME = "variables.h5" <add>_VARS_FNAME = "variables" <ide> _ASSETS_DIRNAME = "assets" <ide> <ide> # A temporary flag to enable the new idempotent saving framework. <ide> ) <ide> <ide> <del>def save_model(model, filepath): <del> """Save a zip-archive representing a Keras model to the given filepath. <add>def save_model(model, filepath, weights_format="h5", use_zip=True): <add> """Save an archive representing a Keras model to the given filepath. <ide> <ide> The zip-based archive contains the following structure: <ide> <del> - JSON-based configuration file (config.json): Records of model, layer, and <del> other trackables' configuration. <del> - NPZ-based trackable state files, found in respective directories, such as <del> model/states.npz, model/dense_layer/states.npz, etc. <del> - Metadata file (this is a TODO). <add> - JSON configuration file (`config.json`): Records of model, layer, and <add> other object configurations. <add> - Npz or h5 model variables file (`variables.npz` or `variables.h5`). <add> - Assets files (if any) found in the `assets/` directory structure, <add> which mirrors the model's inner structure. <add> - JSON metadata file (`metdata.json`). <ide> <ide> The states of Keras trackables (layers, optimizers, loss, and metrics) are <ide> automatically saved as long as they can be discovered through the attributes <del> returned by `dir(Model)`. Typically, the state includes the variables <add> returned by `dir(model)`. Typically, the state includes the variables <ide> associated with the trackable, but some specially purposed layers may <ide> contain more such as the vocabularies stored in the hashmaps. The trackables <del> define how their states are saved by exposing `save_state()` and <del> `load_state()` APIs. <add> define how their asset state is saved by exposing `save_assets()` and <add> `load_assets()` APIs. <ide> <ide> For the case of layer states, the variables will be visited as long as <ide> they are either 1) referenced via layer attributes, or 2) referenced via a <ide> def save_model(model, filepath): <ide> "Invalid filename: expected a `.keras` extension. " <ide> f"Received: filepath={filepath}" <ide> ) <del> if h5py is None: <del> raise ImportError("h5py must be installed in order to save a model.") <add> if weights_format == "h5" and h5py is None: <add> raise ImportError( <add> "h5py must be installed in order to save a model in hdf5 format." <add> ) <add> <ide> if not model.built: <ide> warnings.warn( <ide> "You are saving a model that has not yet been built. " <ide> def save_model(model, filepath): <ide> "date_saved": datetime.datetime.now().strftime("%Y-%m-%d@%H:%M:%S"), <ide> } <ide> ) <del> <del> # Use a temporary directory for the storing files prior to zipping. <del> temp_path = _get_temp_dir() <add> if use_zip: <add> # Use a temporary directory for the storing files prior to zipping. <add> write_path = _get_temp_dir() <add> else: <add> tf.io.gfile.makedirs(filepath) <add> write_path = filepath <ide> try: <ide> # Write files locally before zipping. <del> with open(tf.io.gfile.join(temp_path, _METADATA_FILENAME), "w") as f: <add> with open(tf.io.gfile.join(write_path, _METADATA_FILENAME), "w") as f: <ide> f.write(metadata_json) <del> with open(tf.io.gfile.join(temp_path, _CONFIG_FILENAME), "w") as f: <add> with open(tf.io.gfile.join(write_path, _CONFIG_FILENAME), "w") as f: <ide> f.write(config_json) <ide> <del> h5_file = h5py.File(tf.io.gfile.join(temp_path, _VARS_FNAME), "w") <del> assets_dir = tf.io.gfile.join(temp_path, _ASSETS_DIRNAME) <add> weights_path = tf.io.gfile.join(write_path, _VARS_FNAME) <add> assets_path = tf.io.gfile.join(write_path, _ASSETS_DIRNAME) <add> <add> if weights_format == "h5": <add> weights_store = H5IOStore(weights_path, mode="w") <add> elif weights_format == "npz": <add> weights_store = NpzIOStore(weights_path, mode="w") <add> else: <add> raise ValueError( <add> "Unknown `weights_format`. Expected 'h5' or 'npz'. " <add> f"Received: {weights_format}" <add> ) <ide> _save_state( <ide> model, <del> weights_handler=H5IOHandler(h5_file), <del> assets_handler=DiskIOHandler(assets_dir), <add> weights_handler=weights_store, <add> assets_handler=DiskIOStore(assets_path), <ide> inner_path="", <ide> visited_trackables=set(), <ide> ) <del> _print_h5_file(h5_file, action="saving") <del> h5_file.close() <add> weights_store.close() <ide> <del> # Zip local files into an archive. <del> with zipfile.ZipFile(filepath, "w") as zipfile_to_save: <del> _write_recursively(zipfile_to_save, temp_path, "") <del> _print_zip_file(zipfile_to_save, "saving") <add> if use_zip: <add> # Zip local files into an archive. <add> with zipfile.ZipFile(filepath, "w") as zipfile_to_save: <add> _write_to_zip_recursively(zipfile_to_save, write_path, "") <ide> except Exception as e: <ide> raise e <ide> finally: <ide> _SAVING_V3_ENABLED.value = saving_v3_enabled_value <del> # Remove the directory temporarily used. <del> tf.io.gfile.rmtree(temp_path) <add> if use_zip and tf.io.gfile.exists(write_path): <add> # Remove the directory temporarily used. <add> tf.io.gfile.rmtree(write_path) <ide> <ide> <ide> def load_model(filepath, custom_objects=None): <del> """Load a zip archive representing a Keras model.""" <add> """Load an archive representing a Keras model.""" <ide> if not filepath.endswith(".keras"): <ide> raise ValueError( <ide> "Invalid filename: expected a `.keras` extension. " <ide> f"Received: filepath={filepath}" <ide> ) <del> if h5py is None: <del> raise ImportError("h5py must be installed in order to load a model.") <add> use_zip = not tf.io.gfile.isdir(filepath) <add> <ide> saving_v3_enabled_value = getattr(_SAVING_V3_ENABLED, "value", False) <ide> _SAVING_V3_ENABLED.value = True <del> temp_path = _get_temp_dir() <add> <add> if use_zip: <add> read_path = _get_temp_dir() <add> else: <add> read_path = filepath <ide> try: <del> with zipfile.ZipFile(filepath, "r") as zipfile_to_load: <del> _print_zip_file(zipfile_to_load, "loading") <del> zipfile_to_load.extractall(temp_path) <add> if use_zip: <add> with zipfile.ZipFile(filepath, "r") as zipfile_to_load: <add> zipfile_to_load.extractall(read_path) <ide> <del> with open(tf.io.gfile.join(temp_path, _CONFIG_FILENAME), "r") as f: <add> with open(tf.io.gfile.join(read_path, _CONFIG_FILENAME), "r") as f: <ide> config_json = f.read() <ide> # Note: we should NOT use a custom JSON decoder. Anything that <ide> # needs custom decoding must be handled in deserialize_keras_object. <ide> config_dict = json.loads(config_json) <ide> # Construct the model from the configuration file in the archive. <ide> model = deserialize_keras_object(config_dict, custom_objects) <del> h5_file = h5py.File(tf.io.gfile.join(temp_path, _VARS_FNAME), "r") <del> _print_h5_file(h5_file, action="loading") <del> assets_dir = tf.io.gfile.join(temp_path, _ASSETS_DIRNAME) <add> <add> weights_path = tf.io.gfile.join(read_path, _VARS_FNAME) <add> if tf.io.gfile.exists(weights_path + ".h5"): <add> weights_format = "h5" <add> if h5py is None: <add> raise ImportError( <add> "h5py must be installed in order to save " <add> "a model in hdf5 format." <add> ) <add> elif tf.io.gfile.exists(weights_path + ".npz"): <add> weights_format = "npz" <add> <add> if weights_format == "h5": <add> weights_store = H5IOStore(weights_path, mode="r") <add> elif weights_format == "npz": <add> weights_store = NpzIOStore(weights_path, mode="r") <add> else: <add> raise ValueError( <add> f"Expected a {weights_path}.h5 or {weights_path}.npz file." <add> ) <add> <add> assets_path = tf.io.gfile.join(read_path, _ASSETS_DIRNAME) <ide> _load_state( <ide> model, <del> weights_handler=H5IOHandler(h5_file), <del> assets_handler=DiskIOHandler(assets_dir), <add> weights_handler=weights_store, <add> assets_handler=DiskIOStore(assets_path), <ide> inner_path="", <ide> visited_trackables=set(), <ide> ) <del> h5_file.close() <add> weights_store.close() <ide> except Exception as e: <ide> raise e <ide> else: <ide> return model <ide> finally: <ide> _SAVING_V3_ENABLED.value = saving_v3_enabled_value <del> if tf.io.gfile.exists(temp_path): <del> tf.io.gfile.rmtree(temp_path) <add> if use_zip and tf.io.gfile.exists(read_path): <add> tf.io.gfile.rmtree(read_path) <ide> <ide> <del>def _write_recursively(zipfile_to_save, system_path, zip_path): <add>def _write_to_zip_recursively(zipfile_to_save, system_path, zip_path): <ide> if not tf.io.gfile.isdir(system_path): <ide> zipfile_to_save.write(system_path, zip_path) <ide> else: <ide> for file_name in tf.io.gfile.listdir(system_path): <ide> system_file_path = tf.io.gfile.join(system_path, file_name) <ide> zip_file_path = tf.io.gfile.join(zip_path, file_name) <del> _write_recursively(zipfile_to_save, system_file_path, zip_file_path) <add> _write_to_zip_recursively( <add> zipfile_to_save, system_file_path, zip_file_path <add> ) <ide> <ide> <ide> def _save_state( <ide> def _load_container_state( <ide> ) <ide> <ide> <del>class DiskIOHandler: <del> def __init__(self, base_directory): <del> self.base_directory = base_directory <add>class DiskIOStore: <add> def __init__(self, root_path, mode=None): <add> self.base_directory = root_path <ide> <ide> def make(self, path): <ide> if not path: <ide> def get(self, path): <ide> return path <ide> return None <ide> <add> def close(self): <add> pass <ide> <del>class H5IOHandler: <del> def __init__(self, h5_file): <del> self.h5_file = h5_file <add> <add>class H5IOStore: <add> def __init__(self, root_path, mode="r"): <add> self.h5_file = h5py.File(root_path + ".h5", mode=mode) <ide> <ide> def make(self, path): <ide> if not path: <ide> def make(self, path): <ide> def get(self, path): <ide> if not path: <ide> return self.h5_file["vars"] <del> if path in self.h5_file: <add> if path in self.h5_file and "vars" in self.h5_file[path]: <ide> return self.h5_file[path]["vars"] <del> print(f"Warning: asset missing from file: {path}") <ide> return {} <ide> <add> def close(self): <add> self.h5_file.close() <add> <add> <add>class NpzIOStore: <add> def __init__(self, root_path, mode="r"): <add> self.root_path = root_path <add> self.mode = mode <add> if mode == "w": <add> self.contents = {} <add> else: <add> f = open(root_path + ".npz", mode="rb") <add> self.contents = np.load(f) <add> f.close() <add> <add> def make(self, path): <add> if not path: <add> self.contents["vars"] = {} <add> return self.contents["vars"] <add> self.contents[path] = {"vars": {}} <add> return self.contents[path]["vars"] <add> <add> def get(self, path): <add> if not path: <add> if "vars" in self.contents: <add> return self.contents["vars"] <add> return {} <add> if path in self.contents and "vars" in self.contents[path]: <add> return self.contents[path]["vars"] <add> return {} <add> <add> def close(self): <add> if self.mode == "w": <add> f = open(self.root_path + ".npz", mode="wb") <add> np.savez(f, **self.contents) <add> f.close() <add> <ide> <ide> def _get_temp_dir(): <ide> temp_dir = tempfile.mkdtemp()
1
Python
Python
register sentencesegmenter in language.factories
38109a0e4a65f815eacc1a84ee5a3faad391e483
<ide><path>spacy/language.py <ide> from .vocab import Vocab <ide> from .lemmatizer import Lemmatizer <ide> from .pipeline import DependencyParser, Tensorizer, Tagger, EntityRecognizer <del>from .pipeline import SimilarityHook, TextCategorizer <add>from .pipeline import SimilarityHook, TextCategorizer, SentenceSegmenter <ide> from .compat import json_dumps, izip <ide> from .scorer import Scorer <ide> from ._ml import link_vectors_to_models <ide> class Language(object): <ide> 'parser': lambda nlp, **cfg: DependencyParser(nlp.vocab, **cfg), <ide> 'ner': lambda nlp, **cfg: EntityRecognizer(nlp.vocab, **cfg), <ide> 'similarity': lambda nlp, **cfg: SimilarityHook(nlp.vocab, **cfg), <del> 'textcat': lambda nlp, **cfg: TextCategorizer(nlp.vocab, **cfg) <add> 'textcat': lambda nlp, **cfg: TextCategorizer(nlp.vocab, **cfg), <add> 'sbd': lambda nlp, **cfg: SentenceSegmenter(nlp.vocab, **cfg), <add> 'sentencizer': lambda nlp, **cfg: SentenceSegmenter(nlp.vocab, **cfg) <ide> } <ide> <ide> def __init__(self, vocab=True, make_doc=True, meta={}, **kwargs):
1
Text
Text
correct information about milestones
2daaf3ea19149f471850d8c3aa3d0989f0a0d23b
<ide><path>TRIAGING.md <ide> This process based on the idea of minimizing user pain <ide> 1. Label `origin: google` for issues from Google <ide> <ide> 1. Assign a milestone: <del> * Current 1.x.y milestone - regressions and urgent bugs only <del> * Backlog - fixes; changes that should go into a patch release <del> * Ice Box - new features; changes that belong inß a major/minor release <add> * Backlog - triaged fixes and features, should be the default choice <add> * Current 1.x.y milestone (e.g. 1.3.0-beta-2) - regressions and urgent bugs only <add> <ide> <ide> 1. Unassign yourself from the issue <ide>
1
Go
Go
handle kernel and os info error in /info api
b0fb0f19934287f428d14d1267183fe9194a4fdf
<ide><path>daemon/info.go <ide> import ( <ide> // SystemInfo returns information about the host server the daemon is running on. <ide> func (daemon *Daemon) SystemInfo() (*types.Info, error) { <ide> kernelVersion := "<unknown>" <del> if kv, err := kernel.GetKernelVersion(); err == nil { <add> if kv, err := kernel.GetKernelVersion(); err != nil { <add> logrus.Warnf("Could not get kernel version: %v", err) <add> } else { <ide> kernelVersion = kv.String() <ide> } <ide> <ide> operatingSystem := "<unknown>" <del> if s, err := operatingsystem.GetOperatingSystem(); err == nil { <add> if s, err := operatingsystem.GetOperatingSystem(); err != nil { <add> logrus.Warnf("Could not get operating system name: %v", err) <add> } else { <ide> operatingSystem = s <ide> } <ide>
1
Mixed
Javascript
add example for polyfilling domparser in node
20f2b0b3b2decc6544a29ddd90c19e2fdbe8b009
<ide><path>examples/with-react-intl/README.md <ide> $ npm start <ide> <ide> You can then switch your browser's language preferences to French and refresh the page to see the UI update accordingly. <ide> <add>### FormattedHTMLMessage support (react-intl pre-v4) <add> <add>Out of the box, this example does not support the use of the `FormattedHTMLMessage` component on the server due to `DOMParser` not being present in a Node environment. <add>This functionality is deprecated and has been removed as of react-intl 4.0 <add>If you still want to enable this feature, you should install a `DOMParser` implementation (e.g. `xmldom` or `jsdom`) and enable the polyfill in `server.js`: <add> <add>```js <add>// Polyfill Node with `DOMParser` required by formatjs. <add>// See: https://github.com/zeit/next.js/issues/10533 <add>const { DOMParser } = require('xmldom') <add>global.DOMParser = DOMParser <add>``` <add> <ide> [react intl]: https://github.com/yahoo/react-intl <ide><path>examples/with-react-intl/server.js <ide> const IntlPolyfill = require('intl') <ide> Intl.NumberFormat = IntlPolyfill.NumberFormat <ide> Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat <ide> <add>// Polyfill DOMParser for **pre-v4** react-intl used by formatjs. <add>// Only needed when using FormattedHTMLMessage. Make sure to install `xmldom`. <add>// See: https://github.com/zeit/next.js/issues/10533 <add>// const { DOMParser } = require('xmldom') <add>// global.DOMParser = DOMParser <add> <ide> const { readFileSync } = require('fs') <ide> const { basename } = require('path') <ide> const { createServer } = require('http')
2
Python
Python
drop defunct tests
c8764de7881f419c9269913ec3654fc1d904ab2e
<ide><path>tests/test_files.py <del># from __future__ import unicode_literals <del># from django.test import TestCase <del># from django.utils import six <del># from rest_framework import serializers <del># from rest_framework.compat import BytesIO <del># import datetime <del> <del> <del># class UploadedFile(object): <del># def __init__(self, file=None, created=None): <del># self.file = file <del># self.created = created or datetime.datetime.now() <del> <del> <del># class UploadedFileSerializer(serializers.Serializer): <del># file = serializers.FileField(required=False) <del># created = serializers.DateTimeField() <del> <del># def restore_object(self, attrs, instance=None): <del># if instance: <del># instance.file = attrs['file'] <del># instance.created = attrs['created'] <del># return instance <del># return UploadedFile(**attrs) <del> <del> <del># class FileSerializerTests(TestCase): <del># def test_create(self): <del># now = datetime.datetime.now() <del># file = BytesIO(six.b('stuff')) <del># file.name = 'stuff.txt' <del># file.size = len(file.getvalue()) <del># serializer = UploadedFileSerializer(data={'created': now}, files={'file': file}) <del># uploaded_file = UploadedFile(file=file, created=now) <del># self.assertTrue(serializer.is_valid()) <del># self.assertEqual(serializer.object.created, uploaded_file.created) <del># self.assertEqual(serializer.object.file, uploaded_file.file) <del># self.assertFalse(serializer.object is uploaded_file) <del> <del># def test_creation_failure(self): <del># """ <del># Passing files=None should result in an ValidationError <del> <del># Regression test for: <del># https://github.com/tomchristie/django-rest-framework/issues/542 <del># """ <del># now = datetime.datetime.now() <del> <del># serializer = UploadedFileSerializer(data={'created': now}) <del># self.assertTrue(serializer.is_valid()) <del># self.assertEqual(serializer.object.created, now) <del># self.assertIsNone(serializer.object.file) <del> <del># def test_remove_with_empty_string(self): <del># """ <del># Passing empty string as data should cause file to be removed <del> <del># Test for: <del># https://github.com/tomchristie/django-rest-framework/issues/937 <del># """ <del># now = datetime.datetime.now() <del># file = BytesIO(six.b('stuff')) <del># file.name = 'stuff.txt' <del># file.size = len(file.getvalue()) <del> <del># uploaded_file = UploadedFile(file=file, created=now) <del> <del># serializer = UploadedFileSerializer(instance=uploaded_file, data={'created': now, 'file': ''}) <del># self.assertTrue(serializer.is_valid()) <del># self.assertEqual(serializer.object.created, uploaded_file.created) <del># self.assertIsNone(serializer.object.file) <del> <del># def test_validation_error_with_non_file(self): <del># """ <del># Passing non-files should raise a validation error. <del># """ <del># now = datetime.datetime.now() <del># errmsg = 'No file was submitted. Check the encoding type on the form.' <del> <del># serializer = UploadedFileSerializer(data={'created': now, 'file': 'abc'}) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'file': [errmsg]}) <del> <del># def test_validation_with_no_data(self): <del># """ <del># Validation should still function when no data dictionary is provided. <del># """ <del># uploaded_file = BytesIO(six.b('stuff')) <del># uploaded_file.name = 'stuff.txt' <del># uploaded_file.size = len(uploaded_file.getvalue()) <del># serializer = UploadedFileSerializer(files={'file': uploaded_file}) <del># self.assertFalse(serializer.is_valid()) <ide><path>tests/test_hyperlinkedserializers.py <del># from __future__ import unicode_literals <del># import json <del># from django.test import TestCase <del># from rest_framework import generics, status, serializers <del># from django.conf.urls import patterns, url <del># from rest_framework.settings import api_settings <del># from rest_framework.test import APIRequestFactory <del># from tests.models import ( <del># Anchor, BasicModel, ManyToManyModel, BlogPost, BlogPostComment, <del># Album, Photo, OptionalRelationModel <del># ) <del> <del># factory = APIRequestFactory() <del> <del> <del># class BlogPostCommentSerializer(serializers.ModelSerializer): <del># url = serializers.HyperlinkedIdentityField(view_name='blogpostcomment-detail') <del># text = serializers.CharField() <del># blog_post_url = serializers.HyperlinkedRelatedField(source='blog_post', view_name='blogpost-detail') <del> <del># class Meta: <del># model = BlogPostComment <del># fields = ('text', 'blog_post_url', 'url') <del> <del> <del># class PhotoSerializer(serializers.Serializer): <del># description = serializers.CharField() <del># album_url = serializers.HyperlinkedRelatedField(source='album', view_name='album-detail', queryset=Album.objects.all(), lookup_field='title') <del> <del># def restore_object(self, attrs, instance=None): <del># return Photo(**attrs) <del> <del> <del># class AlbumSerializer(serializers.ModelSerializer): <del># url = serializers.HyperlinkedIdentityField(view_name='album-detail', lookup_field='title') <del> <del># class Meta: <del># model = Album <del># fields = ('title', 'url') <del> <del> <del># class BasicSerializer(serializers.HyperlinkedModelSerializer): <del># class Meta: <del># model = BasicModel <del> <del> <del># class AnchorSerializer(serializers.HyperlinkedModelSerializer): <del># class Meta: <del># model = Anchor <del> <del> <del># class ManyToManySerializer(serializers.HyperlinkedModelSerializer): <del># class Meta: <del># model = ManyToManyModel <del> <del> <del># class BlogPostSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BlogPost <del> <del> <del># class OptionalRelationSerializer(serializers.HyperlinkedModelSerializer): <del># class Meta: <del># model = OptionalRelationModel <del> <del> <del># class BasicList(generics.ListCreateAPIView): <del># queryset = BasicModel.objects.all() <del># serializer_class = BasicSerializer <del> <del> <del># class BasicDetail(generics.RetrieveUpdateDestroyAPIView): <del># queryset = BasicModel.objects.all() <del># serializer_class = BasicSerializer <del> <del> <del># class AnchorDetail(generics.RetrieveAPIView): <del># queryset = Anchor.objects.all() <del># serializer_class = AnchorSerializer <del> <del> <del># class ManyToManyList(generics.ListAPIView): <del># queryset = ManyToManyModel.objects.all() <del># serializer_class = ManyToManySerializer <del> <del> <del># class ManyToManyDetail(generics.RetrieveAPIView): <del># queryset = ManyToManyModel.objects.all() <del># serializer_class = ManyToManySerializer <del> <del> <del># class BlogPostCommentListCreate(generics.ListCreateAPIView): <del># queryset = BlogPostComment.objects.all() <del># serializer_class = BlogPostCommentSerializer <del> <del> <del># class BlogPostCommentDetail(generics.RetrieveAPIView): <del># queryset = BlogPostComment.objects.all() <del># serializer_class = BlogPostCommentSerializer <del> <del> <del># class BlogPostDetail(generics.RetrieveAPIView): <del># queryset = BlogPost.objects.all() <del># serializer_class = BlogPostSerializer <del> <del> <del># class PhotoListCreate(generics.ListCreateAPIView): <del># queryset = Photo.objects.all() <del># serializer_class = PhotoSerializer <del> <del> <del># class AlbumDetail(generics.RetrieveAPIView): <del># queryset = Album.objects.all() <del># serializer_class = AlbumSerializer <del># lookup_field = 'title' <del> <del> <del># class OptionalRelationDetail(generics.RetrieveUpdateDestroyAPIView): <del># queryset = OptionalRelationModel.objects.all() <del># serializer_class = OptionalRelationSerializer <del> <del> <del># urlpatterns = patterns( <del># '', <del># url(r'^basic/$', BasicList.as_view(), name='basicmodel-list'), <del># url(r'^basic/(?P<pk>\d+)/$', BasicDetail.as_view(), name='basicmodel-detail'), <del># url(r'^anchor/(?P<pk>\d+)/$', AnchorDetail.as_view(), name='anchor-detail'), <del># url(r'^manytomany/$', ManyToManyList.as_view(), name='manytomanymodel-list'), <del># url(r'^manytomany/(?P<pk>\d+)/$', ManyToManyDetail.as_view(), name='manytomanymodel-detail'), <del># url(r'^posts/(?P<pk>\d+)/$', BlogPostDetail.as_view(), name='blogpost-detail'), <del># url(r'^comments/$', BlogPostCommentListCreate.as_view(), name='blogpostcomment-list'), <del># url(r'^comments/(?P<pk>\d+)/$', BlogPostCommentDetail.as_view(), name='blogpostcomment-detail'), <del># url(r'^albums/(?P<title>\w[\w-]*)/$', AlbumDetail.as_view(), name='album-detail'), <del># url(r'^photos/$', PhotoListCreate.as_view(), name='photo-list'), <del># url(r'^optionalrelation/(?P<pk>\d+)/$', OptionalRelationDetail.as_view(), name='optionalrelationmodel-detail'), <del># ) <del> <del> <del># class TestBasicHyperlinkedView(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># """ <del># Create 3 BasicModel instances. <del># """ <del># items = ['foo', 'bar', 'baz'] <del># for item in items: <del># BasicModel(text=item).save() <del># self.objects = BasicModel.objects <del># self.data = [ <del># {'url': 'http://testserver/basic/%d/' % obj.id, 'text': obj.text} <del># for obj in self.objects.all() <del># ] <del># self.list_view = BasicList.as_view() <del># self.detail_view = BasicDetail.as_view() <del> <del># def test_get_list_view(self): <del># """ <del># GET requests to ListCreateAPIView should return list of objects. <del># """ <del># request = factory.get('/basic/') <del># response = self.list_view(request).render() <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(response.data, self.data) <del> <del># def test_get_detail_view(self): <del># """ <del># GET requests to ListCreateAPIView should return list of objects. <del># """ <del># request = factory.get('/basic/1') <del># response = self.detail_view(request, pk=1).render() <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(response.data, self.data[0]) <del> <del> <del># class TestManyToManyHyperlinkedView(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># """ <del># Create 3 BasicModel instances. <del># """ <del># items = ['foo', 'bar', 'baz'] <del># anchors = [] <del># for item in items: <del># anchor = Anchor(text=item) <del># anchor.save() <del># anchors.append(anchor) <del> <del># manytomany = ManyToManyModel() <del># manytomany.save() <del># manytomany.rel.add(*anchors) <del> <del># self.data = [{ <del># 'url': 'http://testserver/manytomany/1/', <del># 'rel': [ <del># 'http://testserver/anchor/1/', <del># 'http://testserver/anchor/2/', <del># 'http://testserver/anchor/3/', <del># ] <del># }] <del># self.list_view = ManyToManyList.as_view() <del># self.detail_view = ManyToManyDetail.as_view() <del> <del># def test_get_list_view(self): <del># """ <del># GET requests to ListCreateAPIView should return list of objects. <del># """ <del># request = factory.get('/manytomany/') <del># response = self.list_view(request) <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(response.data, self.data) <del> <del># def test_get_detail_view(self): <del># """ <del># GET requests to ListCreateAPIView should return list of objects. <del># """ <del># request = factory.get('/manytomany/1/') <del># response = self.detail_view(request, pk=1) <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(response.data, self.data[0]) <del> <del> <del># class TestHyperlinkedIdentityFieldLookup(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># """ <del># Create 3 Album instances. <del># """ <del># titles = ['foo', 'bar', 'baz'] <del># for title in titles: <del># album = Album(title=title) <del># album.save() <del># self.detail_view = AlbumDetail.as_view() <del># self.data = { <del># 'foo': {'title': 'foo', 'url': 'http://testserver/albums/foo/'}, <del># 'bar': {'title': 'bar', 'url': 'http://testserver/albums/bar/'}, <del># 'baz': {'title': 'baz', 'url': 'http://testserver/albums/baz/'} <del># } <del> <del># def test_lookup_field(self): <del># """ <del># GET requests to AlbumDetail view should return serialized Albums <del># with a url field keyed by `title`. <del># """ <del># for album in Album.objects.all(): <del># request = factory.get('/albums/{0}/'.format(album.title)) <del># response = self.detail_view(request, title=album.title) <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(response.data, self.data[album.title]) <del> <del> <del># class TestCreateWithForeignKeys(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># """ <del># Create a blog post <del># """ <del># self.post = BlogPost.objects.create(title="Test post") <del># self.create_view = BlogPostCommentListCreate.as_view() <del> <del># def test_create_comment(self): <del> <del># data = { <del># 'text': 'A test comment', <del># 'blog_post_url': 'http://testserver/posts/1/' <del># } <del> <del># request = factory.post('/comments/', data=data) <del># response = self.create_view(request) <del># self.assertEqual(response.status_code, status.HTTP_201_CREATED) <del># self.assertEqual(response['Location'], 'http://testserver/comments/1/') <del># self.assertEqual(self.post.blogpostcomment_set.count(), 1) <del># self.assertEqual(self.post.blogpostcomment_set.all()[0].text, 'A test comment') <del> <del> <del># class TestCreateWithForeignKeysAndCustomSlug(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># """ <del># Create an Album <del># """ <del># self.post = Album.objects.create(title='test-album') <del># self.list_create_view = PhotoListCreate.as_view() <del> <del># def test_create_photo(self): <del> <del># data = { <del># 'description': 'A test photo', <del># 'album_url': 'http://testserver/albums/test-album/' <del># } <del> <del># request = factory.post('/photos/', data=data) <del># response = self.list_create_view(request) <del># self.assertEqual(response.status_code, status.HTTP_201_CREATED) <del># self.assertNotIn('Location', response, msg='Location should only be included if there is a "url" field on the serializer') <del># self.assertEqual(self.post.photo_set.count(), 1) <del># self.assertEqual(self.post.photo_set.all()[0].description, 'A test photo') <del> <del> <del># class TestOptionalRelationHyperlinkedView(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># """ <del># Create 1 OptionalRelationModel instances. <del># """ <del># OptionalRelationModel().save() <del># self.objects = OptionalRelationModel.objects <del># self.detail_view = OptionalRelationDetail.as_view() <del># self.data = {"url": "http://testserver/optionalrelation/1/", "other": None} <del> <del># def test_get_detail_view(self): <del># """ <del># GET requests to RetrieveAPIView with optional relations should return None <del># for non existing relations. <del># """ <del># request = factory.get('/optionalrelationmodel-detail/1') <del># response = self.detail_view(request, pk=1) <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del># self.assertEqual(response.data, self.data) <del> <del># def test_put_detail_view(self): <del># """ <del># PUT requests to RetrieveUpdateDestroyAPIView with optional relations <del># should accept None for non existing relations. <del># """ <del># response = self.client.put('/optionalrelation/1/', <del># data=json.dumps(self.data), <del># content_type='application/json') <del># self.assertEqual(response.status_code, status.HTTP_200_OK) <del> <del> <del># class TestOverriddenURLField(TestCase): <del># def setUp(self): <del># class OverriddenURLSerializer(serializers.HyperlinkedModelSerializer): <del># url = serializers.SerializerMethodField('get_url') <del> <del># class Meta: <del># model = BlogPost <del># fields = ('title', 'url') <del> <del># def get_url(self, obj): <del># return 'foo bar' <del> <del># self.Serializer = OverriddenURLSerializer <del># self.obj = BlogPost.objects.create(title='New blog post') <del> <del># def test_overridden_url_field(self): <del># """ <del># The 'url' field should respect overriding. <del># Regression test for #936. <del># """ <del># serializer = self.Serializer(self.obj) <del># self.assertEqual( <del># serializer.data, <del># {'title': 'New blog post', 'url': 'foo bar'} <del># ) <del> <del> <del># class TestURLFieldNameBySettings(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># self.saved_url_field_name = api_settings.URL_FIELD_NAME <del># api_settings.URL_FIELD_NAME = 'global_url_field' <del> <del># class Serializer(serializers.HyperlinkedModelSerializer): <del> <del># class Meta: <del># model = BlogPost <del># fields = ('title', api_settings.URL_FIELD_NAME) <del> <del># self.Serializer = Serializer <del># self.obj = BlogPost.objects.create(title="New blog post") <del> <del># def tearDown(self): <del># api_settings.URL_FIELD_NAME = self.saved_url_field_name <del> <del># def test_overridden_url_field_name(self): <del># request = factory.get('/posts/') <del># serializer = self.Serializer(self.obj, context={'request': request}) <del># self.assertIn(api_settings.URL_FIELD_NAME, serializer.data) <del> <del> <del># class TestURLFieldNameByOptions(TestCase): <del># urls = 'tests.test_hyperlinkedserializers' <del> <del># def setUp(self): <del># class Serializer(serializers.HyperlinkedModelSerializer): <del> <del># class Meta: <del># model = BlogPost <del># fields = ('title', 'serializer_url_field') <del># url_field_name = 'serializer_url_field' <del> <del># self.Serializer = Serializer <del># self.obj = BlogPost.objects.create(title="New blog post") <del> <del># def test_overridden_url_field_name(self): <del># request = factory.get('/posts/') <del># serializer = self.Serializer(self.obj, context={'request': request}) <del># self.assertIn(self.Serializer.Meta.url_field_name, serializer.data) <ide><path>tests/test_nullable_fields.py <del># from django.core.urlresolvers import reverse <del> <del># from django.conf.urls import patterns, url <del># from rest_framework import serializers, generics <del># from rest_framework.test import APITestCase <del># from tests.models import NullableForeignKeySource <del> <del> <del># class NullableFKSourceSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = NullableForeignKeySource <del> <del> <del># class NullableFKSourceDetail(generics.RetrieveUpdateDestroyAPIView): <del># queryset = NullableForeignKeySource.objects.all() <del># serializer_class = NullableFKSourceSerializer <del> <del> <del># urlpatterns = patterns( <del># '', <del># url(r'^objects/(?P<pk>\d+)/$', NullableFKSourceDetail.as_view(), name='object-detail'), <del># ) <del> <del> <del># class NullableForeignKeyTests(APITestCase): <del># """ <del># DRF should be able to handle nullable foreign keys when a test <del># Client POST/PUT request is made with its own serialized object. <del># """ <del># urls = 'tests.test_nullable_fields' <del> <del># def test_updating_object_with_null_fk(self): <del># obj = NullableForeignKeySource(name='example', target=None) <del># obj.save() <del># serialized_data = NullableFKSourceSerializer(obj).data <del> <del># response = self.client.put(reverse('object-detail', args=[obj.pk]), serialized_data) <del> <del># self.assertEqual(response.data, serialized_data) <ide><path>tests/test_relations.py <ide> def test_slug_related_lookup_invalid_type(self): <ide> def test_representation(self): <ide> representation = self.field.to_representation(self.instance) <ide> assert representation == self.instance.name <del> <del># Older tests, for review... <del> <del># """ <del># General tests for relational fields. <del># """ <del># from __future__ import unicode_literals <del># from django import get_version <del># from django.db import models <del># from django.test import TestCase <del># from django.utils import unittest <del># from rest_framework import serializers <del># from tests.models import BlogPost <del> <del> <del># class NullModel(models.Model): <del># pass <del> <del> <del># class FieldTests(TestCase): <del># def test_pk_related_field_with_empty_string(self): <del># """ <del># Regression test for #446 <del> <del># https://github.com/tomchristie/django-rest-framework/issues/446 <del># """ <del># field = serializers.PrimaryKeyRelatedField(queryset=NullModel.objects.all()) <del># self.assertRaises(serializers.ValidationError, field.to_primitive, '') <del># self.assertRaises(serializers.ValidationError, field.to_primitive, []) <del> <del># def test_hyperlinked_related_field_with_empty_string(self): <del># field = serializers.HyperlinkedRelatedField(queryset=NullModel.objects.all(), view_name='') <del># self.assertRaises(serializers.ValidationError, field.to_primitive, '') <del># self.assertRaises(serializers.ValidationError, field.to_primitive, []) <del> <del># def test_slug_related_field_with_empty_string(self): <del># field = serializers.SlugRelatedField(queryset=NullModel.objects.all(), slug_field='pk') <del># self.assertRaises(serializers.ValidationError, field.to_primitive, '') <del># self.assertRaises(serializers.ValidationError, field.to_primitive, []) <del> <del> <del># class TestManyRelatedMixin(TestCase): <del># def test_missing_many_to_many_related_field(self): <del># ''' <del># Regression test for #632 <del> <del># https://github.com/tomchristie/django-rest-framework/pull/632 <del># ''' <del># field = serializers.RelatedField(many=True, read_only=False) <del> <del># into = {} <del># field.field_from_native({}, None, 'field_name', into) <del># self.assertEqual(into['field_name'], []) <del> <del> <del># # Regression tests for #694 (`source` attribute on related fields) <del> <del># class RelatedFieldSourceTests(TestCase): <del># def test_related_manager_source(self): <del># """ <del># Relational fields should be able to use manager-returning methods as their source. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.RelatedField(many=True, source='get_blogposts_manager') <del> <del># class ClassWithManagerMethod(object): <del># def get_blogposts_manager(self): <del># return BlogPost.objects <del> <del># obj = ClassWithManagerMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, ['BlogPost object']) <del> <del># def test_related_queryset_source(self): <del># """ <del># Relational fields should be able to use queryset-returning methods as their source. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.RelatedField(many=True, source='get_blogposts_queryset') <del> <del># class ClassWithQuerysetMethod(object): <del># def get_blogposts_queryset(self): <del># return BlogPost.objects.all() <del> <del># obj = ClassWithQuerysetMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, ['BlogPost object']) <del> <del># def test_dotted_source(self): <del># """ <del># Source argument should support dotted.source notation. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.RelatedField(many=True, source='a.b.c') <del> <del># class ClassWithQuerysetMethod(object): <del># a = { <del># 'b': { <del># 'c': BlogPost.objects.all() <del># } <del># } <del> <del># obj = ClassWithQuerysetMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, ['BlogPost object']) <del> <del># # Regression for #1129 <del># def test_exception_for_incorect_fk(self): <del># """ <del># Check that the exception message are correct if the source field <del># doesn't exist. <del># """ <del># from tests.models import ManyToManySource <del> <del># class Meta: <del># model = ManyToManySource <del> <del># attrs = { <del># 'name': serializers.SlugRelatedField( <del># slug_field='name', source='banzai'), <del># 'Meta': Meta, <del># } <del> <del># TestSerializer = type( <del># str('TestSerializer'), <del># (serializers.ModelSerializer,), <del># attrs <del># ) <del># with self.assertRaises(AttributeError): <del># TestSerializer(data={'name': 'foo'}) <del> <del> <del># @unittest.skipIf(get_version() < '1.6.0', 'Upstream behaviour changed in v1.6') <del># class RelatedFieldChoicesTests(TestCase): <del># """ <del># Tests for #1408 "Web browseable API doesn't have blank option on drop down list box" <del># https://github.com/tomchristie/django-rest-framework/issues/1408 <del># """ <del># def test_blank_option_is_added_to_choice_if_required_equals_false(self): <del># """ <del> <del># """ <del># post = BlogPost(title="Checking blank option is added") <del># post.save() <del> <del># queryset = BlogPost.objects.all() <del># field = serializers.RelatedField(required=False, queryset=queryset) <del> <del># choice_count = BlogPost.objects.count() <del># widget_count = len(field.widget.choices) <del> <del># self.assertEqual(widget_count, choice_count + 1, 'BLANK_CHOICE_DASH option should have been added') <ide><path>tests/test_relations_hyperlink.py <ide> def test_foreign_key_update_with_valid_emptystring(self): <ide> ] <ide> self.assertEqual(serializer.data, expected) <ide> <del># # reverse foreign keys MUST be read_only <del># # In the general case they do not provide .remove() or .clear() <del># # and cannot be arbitrarily set. <del> <del> # def test_reverse_foreign_key_update(self): <del> # data = {'id': 1, 'name': 'target-1', 'sources': [1]} <del> # instance = ForeignKeyTarget.objects.get(pk=1) <del> # serializer = ForeignKeyTargetSerializer(instance, data=data) <del> # print serializer.is_valid() <del> # print serializer.errors <del> # print serializer <del> # self.assertTrue(serializer.is_valid()) <del> # serializer.save() <del> # self.assertEqual(serializer.data, data) <del> <del> # # Ensure target 1 is updated, and everything else is as expected <del> # queryset = ForeignKeyTarget.objects.all() <del> # serializer = ForeignKeyTargetSerializer(queryset, many=True) <del> # expected = [ <del> # {'id': 1, 'name': 'target-1', 'sources': [1]}, <del> # {'id': 2, 'name': 'target-2', 'sources': []}, <del> # ] <del> # self.assertEqual(serializer.data, expected) <del> <ide> <ide> class HyperlinkedNullableOneToOneTests(TestCase): <ide> urls = 'tests.test_relations_hyperlink' <ide> def test_reverse_foreign_key_retrieve_with_null(self): <ide> {'url': 'http://testserver/onetoonetarget/2/', 'name': 'target-2', 'nullable_source': None}, <ide> ] <ide> self.assertEqual(serializer.data, expected) <del> <del> <del># # Regression tests for #694 (`source` attribute on related fields) <del> <del># class HyperlinkedRelatedFieldSourceTests(TestCase): <del># urls = 'tests.test_relations_hyperlink' <del> <del># def test_related_manager_source(self): <del># """ <del># Relational fields should be able to use manager-returning methods as their source. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.HyperlinkedRelatedField( <del># many=True, <del># source='get_blogposts_manager', <del># view_name='dummy-url', <del># ) <del># field.context = {'request': request} <del> <del># class ClassWithManagerMethod(object): <del># def get_blogposts_manager(self): <del># return BlogPost.objects <del> <del># obj = ClassWithManagerMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, ['http://testserver/dummyurl/1/']) <del> <del># def test_related_queryset_source(self): <del># """ <del># Relational fields should be able to use queryset-returning methods as their source. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.HyperlinkedRelatedField( <del># many=True, <del># source='get_blogposts_queryset', <del># view_name='dummy-url', <del># ) <del># field.context = {'request': request} <del> <del># class ClassWithQuerysetMethod(object): <del># def get_blogposts_queryset(self): <del># return BlogPost.objects.all() <del> <del># obj = ClassWithQuerysetMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, ['http://testserver/dummyurl/1/']) <del> <del># def test_dotted_source(self): <del># """ <del># Source argument should support dotted.source notation. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.HyperlinkedRelatedField( <del># many=True, <del># source='a.b.c', <del># view_name='dummy-url', <del># ) <del># field.context = {'request': request} <del> <del># class ClassWithQuerysetMethod(object): <del># a = { <del># 'b': { <del># 'c': BlogPost.objects.all() <del># } <del># } <del> <del># obj = ClassWithQuerysetMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, ['http://testserver/dummyurl/1/']) <ide><path>tests/test_relations_nested.py <del># from __future__ import unicode_literals <del># from django.db import models <del># from django.test import TestCase <del># from rest_framework import serializers <del> <del># from .models import OneToOneTarget <del> <del> <del># class OneToOneSource(models.Model): <del># name = models.CharField(max_length=100) <del># target = models.OneToOneField(OneToOneTarget, related_name='source', <del># null=True, blank=True) <del> <del> <del># class OneToManyTarget(models.Model): <del># name = models.CharField(max_length=100) <del> <del> <del># class OneToManySource(models.Model): <del># name = models.CharField(max_length=100) <del># target = models.ForeignKey(OneToManyTarget, related_name='sources') <del> <del> <del># class ReverseNestedOneToOneTests(TestCase): <del># def setUp(self): <del># class OneToOneSourceSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = OneToOneSource <del># fields = ('id', 'name') <del> <del># class OneToOneTargetSerializer(serializers.ModelSerializer): <del># source = OneToOneSourceSerializer() <del> <del># class Meta: <del># model = OneToOneTarget <del># fields = ('id', 'name', 'source') <del> <del># self.Serializer = OneToOneTargetSerializer <del> <del># for idx in range(1, 4): <del># target = OneToOneTarget(name='target-%d' % idx) <del># target.save() <del># source = OneToOneSource(name='source-%d' % idx, target=target) <del># source.save() <del> <del># def test_one_to_one_retrieve(self): <del># queryset = OneToOneTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <del># {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <del># {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_one_create(self): <del># data = {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}} <del># serializer = self.Serializer(data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'target-4') <del> <del># # Ensure (target 4, target_source 4, source 4) are added, and <del># # everything else is as expected. <del># queryset = OneToOneTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <del># {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <del># {'id': 3, 'name': 'target-3', 'source': {'id': 3, 'name': 'source-3'}}, <del># {'id': 4, 'name': 'target-4', 'source': {'id': 4, 'name': 'source-4'}} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_one_create_with_invalid_data(self): <del># data = {'id': 4, 'name': 'target-4', 'source': {'id': 4}} <del># serializer = self.Serializer(data=data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'source': [{'name': ['This field is required.']}]}) <del> <del># def test_one_to_one_update(self): <del># data = {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}} <del># instance = OneToOneTarget.objects.get(pk=3) <del># serializer = self.Serializer(instance, data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'target-3-updated') <del> <del># # Ensure (target 3, target_source 3, source 3) are updated, <del># # and everything else is as expected. <del># queryset = OneToOneTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <del># {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <del># {'id': 3, 'name': 'target-3-updated', 'source': {'id': 3, 'name': 'source-3-updated'}} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del> <del># class ForwardNestedOneToOneTests(TestCase): <del># def setUp(self): <del># class OneToOneTargetSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = OneToOneTarget <del># fields = ('id', 'name') <del> <del># class OneToOneSourceSerializer(serializers.ModelSerializer): <del># target = OneToOneTargetSerializer() <del> <del># class Meta: <del># model = OneToOneSource <del># fields = ('id', 'name', 'target') <del> <del># self.Serializer = OneToOneSourceSerializer <del> <del># for idx in range(1, 4): <del># target = OneToOneTarget(name='target-%d' % idx) <del># target.save() <del># source = OneToOneSource(name='source-%d' % idx, target=target) <del># source.save() <del> <del># def test_one_to_one_retrieve(self): <del># queryset = OneToOneSource.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <del># {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <del># {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_one_create(self): <del># data = {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}} <del># serializer = self.Serializer(data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'source-4') <del> <del># # Ensure (target 4, target_source 4, source 4) are added, and <del># # everything else is as expected. <del># queryset = OneToOneSource.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <del># {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <del># {'id': 3, 'name': 'source-3', 'target': {'id': 3, 'name': 'target-3'}}, <del># {'id': 4, 'name': 'source-4', 'target': {'id': 4, 'name': 'target-4'}} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_one_create_with_invalid_data(self): <del># data = {'id': 4, 'name': 'source-4', 'target': {'id': 4}} <del># serializer = self.Serializer(data=data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'target': [{'name': ['This field is required.']}]}) <del> <del># def test_one_to_one_update(self): <del># data = {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}} <del># instance = OneToOneSource.objects.get(pk=3) <del># serializer = self.Serializer(instance, data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'source-3-updated') <del> <del># # Ensure (target 3, target_source 3, source 3) are updated, <del># # and everything else is as expected. <del># queryset = OneToOneSource.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <del># {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <del># {'id': 3, 'name': 'source-3-updated', 'target': {'id': 3, 'name': 'target-3-updated'}} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_one_update_to_null(self): <del># data = {'id': 3, 'name': 'source-3-updated', 'target': None} <del># instance = OneToOneSource.objects.get(pk=3) <del># serializer = self.Serializer(instance, data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del> <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'source-3-updated') <del># self.assertEqual(obj.target, None) <del> <del># queryset = OneToOneSource.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'source-1', 'target': {'id': 1, 'name': 'target-1'}}, <del># {'id': 2, 'name': 'source-2', 'target': {'id': 2, 'name': 'target-2'}}, <del># {'id': 3, 'name': 'source-3-updated', 'target': None} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># # TODO: Nullable 1-1 tests <del># # def test_one_to_one_delete(self): <del># # data = {'id': 3, 'name': 'target-3', 'target_source': None} <del># # instance = OneToOneTarget.objects.get(pk=3) <del># # serializer = self.Serializer(instance, data=data) <del># # self.assertTrue(serializer.is_valid()) <del># # serializer.save() <del> <del># # # Ensure (target_source 3, source 3) are deleted, <del># # # and everything else is as expected. <del># # queryset = OneToOneTarget.objects.all() <del># # serializer = self.Serializer(queryset) <del># # expected = [ <del># # {'id': 1, 'name': 'target-1', 'source': {'id': 1, 'name': 'source-1'}}, <del># # {'id': 2, 'name': 'target-2', 'source': {'id': 2, 'name': 'source-2'}}, <del># # {'id': 3, 'name': 'target-3', 'source': None} <del># # ] <del># # self.assertEqual(serializer.data, expected) <del> <del> <del># class ReverseNestedOneToManyTests(TestCase): <del># def setUp(self): <del># class OneToManySourceSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = OneToManySource <del># fields = ('id', 'name') <del> <del># class OneToManyTargetSerializer(serializers.ModelSerializer): <del># sources = OneToManySourceSerializer(many=True, allow_add_remove=True) <del> <del># class Meta: <del># model = OneToManyTarget <del># fields = ('id', 'name', 'sources') <del> <del># self.Serializer = OneToManyTargetSerializer <del> <del># target = OneToManyTarget(name='target-1') <del># target.save() <del># for idx in range(1, 4): <del># source = OneToManySource(name='source-%d' % idx, target=target) <del># source.save() <del> <del># def test_one_to_many_retrieve(self): <del># queryset = OneToManyTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <del># {'id': 2, 'name': 'source-2'}, <del># {'id': 3, 'name': 'source-3'}]}, <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_many_create(self): <del># data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <del># {'id': 2, 'name': 'source-2'}, <del># {'id': 3, 'name': 'source-3'}, <del># {'id': 4, 'name': 'source-4'}]} <del># instance = OneToManyTarget.objects.get(pk=1) <del># serializer = self.Serializer(instance, data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'target-1') <del> <del># # Ensure source 4 is added, and everything else is as <del># # expected. <del># queryset = OneToManyTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <del># {'id': 2, 'name': 'source-2'}, <del># {'id': 3, 'name': 'source-3'}, <del># {'id': 4, 'name': 'source-4'}]} <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_many_create_with_invalid_data(self): <del># data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <del># {'id': 2, 'name': 'source-2'}, <del># {'id': 3, 'name': 'source-3'}, <del># {'id': 4}]} <del># serializer = self.Serializer(data=data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'sources': [{}, {}, {}, {'name': ['This field is required.']}]}) <del> <del># def test_one_to_many_update(self): <del># data = {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, <del># {'id': 2, 'name': 'source-2'}, <del># {'id': 3, 'name': 'source-3'}]} <del># instance = OneToManyTarget.objects.get(pk=1) <del># serializer = self.Serializer(instance, data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(serializer.data, data) <del># self.assertEqual(obj.name, 'target-1-updated') <del> <del># # Ensure (target 1, source 1) are updated, <del># # and everything else is as expected. <del># queryset = OneToManyTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1-updated', 'sources': [{'id': 1, 'name': 'source-1-updated'}, <del># {'id': 2, 'name': 'source-2'}, <del># {'id': 3, 'name': 'source-3'}]} <del> <del># ] <del># self.assertEqual(serializer.data, expected) <del> <del># def test_one_to_many_delete(self): <del># data = {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <del># {'id': 3, 'name': 'source-3'}]} <del># instance = OneToManyTarget.objects.get(pk=1) <del># serializer = self.Serializer(instance, data=data) <del># self.assertTrue(serializer.is_valid()) <del># serializer.save() <del> <del># # Ensure source 2 is deleted, and everything else is as <del># # expected. <del># queryset = OneToManyTarget.objects.all() <del># serializer = self.Serializer(queryset, many=True) <del># expected = [ <del># {'id': 1, 'name': 'target-1', 'sources': [{'id': 1, 'name': 'source-1'}, <del># {'id': 3, 'name': 'source-3'}]} <del> <del># ] <del># self.assertEqual(serializer.data, expected) <ide><path>tests/test_relations_pk.py <ide> def test_foreign_key_update_with_valid_emptystring(self): <ide> ] <ide> self.assertEqual(serializer.data, expected) <ide> <del> # reverse foreign keys MUST be read_only <del> # In the general case they do not provide .remove() or .clear() <del> # and cannot be arbitrarily set. <del> <del> # def test_reverse_foreign_key_update(self): <del> # data = {'id': 1, 'name': 'target-1', 'sources': [1]} <del> # instance = ForeignKeyTarget.objects.get(pk=1) <del> # serializer = ForeignKeyTargetSerializer(instance, data=data) <del> # self.assertTrue(serializer.is_valid()) <del> # self.assertEqual(serializer.data, data) <del> # serializer.save() <del> <del> # # Ensure target 1 is updated, and everything else is as expected <del> # queryset = ForeignKeyTarget.objects.all() <del> # serializer = ForeignKeyTargetSerializer(queryset, many=True) <del> # expected = [ <del> # {'id': 1, 'name': 'target-1', 'sources': [1]}, <del> # {'id': 2, 'name': 'target-2', 'sources': []}, <del> # ] <del> # self.assertEqual(serializer.data, expected) <del> <ide> <ide> class PKNullableOneToOneTests(TestCase): <ide> def setUp(self): <ide> def test_reverse_foreign_key_retrieve_with_null(self): <ide> {'id': 2, 'name': 'target-2', 'nullable_source': 1}, <ide> ] <ide> self.assertEqual(serializer.data, expected) <del> <del> <del># The below models and tests ensure that serializer fields corresponding <del># to a ManyToManyField field with a user-specified ``through`` model are <del># set to read only <del> <del> <del># class ManyToManyThroughTarget(models.Model): <del># name = models.CharField(max_length=100) <del> <del> <del># class ManyToManyThrough(models.Model): <del># source = models.ForeignKey('ManyToManyThroughSource') <del># target = models.ForeignKey(ManyToManyThroughTarget) <del> <del> <del># class ManyToManyThroughSource(models.Model): <del># name = models.CharField(max_length=100) <del># targets = models.ManyToManyField(ManyToManyThroughTarget, <del># related_name='sources', <del># through='ManyToManyThrough') <del> <del> <del># class ManyToManyThroughTargetSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = ManyToManyThroughTarget <del># fields = ('id', 'name', 'sources') <del> <del> <del># class ManyToManyThroughSourceSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = ManyToManyThroughSource <del># fields = ('id', 'name', 'targets') <del> <del> <del># class PKManyToManyThroughTests(TestCase): <del># def setUp(self): <del># self.source = ManyToManyThroughSource.objects.create( <del># name='through-source-1') <del># self.target = ManyToManyThroughTarget.objects.create( <del># name='through-target-1') <del> <del># def test_many_to_many_create(self): <del># data = {'id': 2, 'name': 'source-2', 'targets': [self.target.pk]} <del># serializer = ManyToManyThroughSourceSerializer(data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(obj.name, 'source-2') <del># self.assertEqual(obj.targets.count(), 0) <del> <del># def test_many_to_many_reverse_create(self): <del># data = {'id': 2, 'name': 'target-2', 'sources': [self.source.pk]} <del># serializer = ManyToManyThroughTargetSerializer(data=data) <del># self.assertTrue(serializer.is_valid()) <del># obj = serializer.save() <del># self.assertEqual(obj.name, 'target-2') <del># self.assertEqual(obj.sources.count(), 0) <del> <del> <del># # Regression tests for #694 (`source` attribute on related fields) <del> <del> <del># class PrimaryKeyRelatedFieldSourceTests(TestCase): <del># def test_related_manager_source(self): <del># """ <del># Relational fields should be able to use manager-returning methods as their source. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_manager') <del> <del># class ClassWithManagerMethod(object): <del># def get_blogposts_manager(self): <del># return BlogPost.objects <del> <del># obj = ClassWithManagerMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, [1]) <del> <del># def test_related_queryset_source(self): <del># """ <del># Relational fields should be able to use queryset-returning methods as their source. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.PrimaryKeyRelatedField(many=True, source='get_blogposts_queryset') <del> <del># class ClassWithQuerysetMethod(object): <del># def get_blogposts_queryset(self): <del># return BlogPost.objects.all() <del> <del># obj = ClassWithQuerysetMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, [1]) <del> <del># def test_dotted_source(self): <del># """ <del># Source argument should support dotted.source notation. <del># """ <del># BlogPost.objects.create(title='blah') <del># field = serializers.PrimaryKeyRelatedField(many=True, source='a.b.c') <del> <del># class ClassWithQuerysetMethod(object): <del># a = { <del># 'b': { <del># 'c': BlogPost.objects.all() <del># } <del># } <del> <del># obj = ClassWithQuerysetMethod() <del># value = field.field_to_native(obj, 'field_name') <del># self.assertEqual(value, [1]) <ide><path>tests/test_request.py <ide> def test_form_POST_unicode(self): <ide> self.assertEqual(request._data, Empty) <ide> self.assertEqual(request._files, Empty) <ide> <del> # def test_accessing_post_after_data_form(self): <del> # """ <del> # Ensures request.POST can be accessed after request.DATA in <del> # form request. <del> # """ <del> # data = {'qwerty': 'uiop'} <del> # request = factory.post('/', data=data) <del> # self.assertEqual(request.DATA.items(), data.items()) <del> # self.assertEqual(request.POST.items(), data.items()) <del> <del> # def test_accessing_post_after_data_for_json(self): <del> # """ <del> # Ensures request.POST can be accessed after request.DATA in <del> # json request. <del> # """ <del> # data = {'qwerty': 'uiop'} <del> # content = json.dumps(data) <del> # content_type = 'application/json' <del> # parsers = (JSONParser, ) <del> <del> # request = factory.post('/', content, content_type=content_type, <del> # parsers=parsers) <del> # self.assertEqual(request.DATA.items(), data.items()) <del> # self.assertEqual(request.POST.items(), []) <del> <del> # def test_accessing_post_after_data_for_overloaded_json(self): <del> # """ <del> # Ensures request.POST can be accessed after request.DATA in overloaded <del> # json request. <del> # """ <del> # data = {'qwerty': 'uiop'} <del> # content = json.dumps(data) <del> # content_type = 'application/json' <del> # parsers = (JSONParser, ) <del> # form_data = {Request._CONTENT_PARAM: content, <del> # Request._CONTENTTYPE_PARAM: content_type} <del> <del> # request = factory.post('/', form_data, parsers=parsers) <del> # self.assertEqual(request.DATA.items(), data.items()) <del> # self.assertEqual(request.POST.items(), form_data.items()) <del> <del> # def test_accessing_data_after_post_form(self): <del> # """ <del> # Ensures request.DATA can be accessed after request.POST in <del> # form request. <del> # """ <del> # data = {'qwerty': 'uiop'} <del> # parsers = (FormParser, MultiPartParser) <del> # request = factory.post('/', data, parsers=parsers) <del> <del> # self.assertEqual(request.POST.items(), data.items()) <del> # self.assertEqual(request.DATA.items(), data.items()) <del> <del> # def test_accessing_data_after_post_for_json(self): <del> # """ <del> # Ensures request.DATA can be accessed after request.POST in <del> # json request. <del> # """ <del> # data = {'qwerty': 'uiop'} <del> # content = json.dumps(data) <del> # content_type = 'application/json' <del> # parsers = (JSONParser, ) <del> # request = factory.post('/', content, content_type=content_type, <del> # parsers=parsers) <del> # self.assertEqual(request.POST.items(), []) <del> # self.assertEqual(request.DATA.items(), data.items()) <del> <del> # def test_accessing_data_after_post_for_overloaded_json(self): <del> # """ <del> # Ensures request.DATA can be accessed after request.POST in overloaded <del> # json request <del> # """ <del> # data = {'qwerty': 'uiop'} <del> # content = json.dumps(data) <del> # content_type = 'application/json' <del> # parsers = (JSONParser, ) <del> # form_data = {Request._CONTENT_PARAM: content, <del> # Request._CONTENTTYPE_PARAM: content_type} <del> <del> # request = factory.post('/', form_data, parsers=parsers) <del> # self.assertEqual(request.POST.items(), form_data.items()) <del> # self.assertEqual(request.DATA.items(), data.items()) <del> <ide> <ide> class MockView(APIView): <ide> authentication_classes = (SessionAuthentication,) <ide> def test_user_logged_in_authentication_has_POST_when_not_logged_in(self): <ide> response = self.csrf_client.post('/', content) <ide> self.assertEqual(status.HTTP_200_OK, response.status_code) <ide> <del> # def test_user_logged_in_authentication_has_post_when_logged_in(self): <del> # """Ensures request.POST exists after UserLoggedInAuthentication when user does log in""" <del> # self.client.login(username='john', password='password') <del> # self.csrf_client.login(username='john', password='password') <del> # content = {'example': 'example'} <del> <del> # response = self.client.post('/', content) <del> # self.assertEqual(status.OK, response.status_code, "POST data is malformed") <del> <del> # response = self.csrf_client.post('/', content) <del> # self.assertEqual(status.OK, response.status_code, "POST data is malformed") <del> <ide> <ide> class TestUserSetter(TestCase): <ide> <ide><path>tests/test_serializer.py <ide> def test_nested_serialize(self): <ide> instance = {'a': 1, 'b': 2, 'c': 3, 'd': 4} <ide> serializer = self.Serializer(instance) <ide> assert serializer.data == self.data <del> <del># # -*- coding: utf-8 -*- <del># from __future__ import unicode_literals <del># from django.db import models <del># from django.db.models.fields import BLANK_CHOICE_DASH <del># from django.test import TestCase <del># from django.utils import unittest <del># from django.utils.datastructures import MultiValueDict <del># from django.utils.translation import ugettext_lazy as _ <del># from rest_framework import serializers, fields, relations <del># from tests.models import ( <del># HasPositiveIntegerAsChoice, Album, ActionItem, Anchor, BasicModel, <del># BlankFieldModel, BlogPost, BlogPostComment, Book, CallableDefaultValueModel, <del># DefaultValueModel, ManyToManyModel, Person, ReadOnlyManyToManyModel, Photo, <del># RESTFrameworkModel, ForeignKeySource <del># ) <del># from tests.models import BasicModelSerializer <del># import datetime <del># import pickle <del># try: <del># import PIL <del># except: <del># PIL = None <del> <del> <del># if PIL is not None: <del># class AMOAFModel(RESTFrameworkModel): <del># char_field = models.CharField(max_length=1024, blank=True) <del># comma_separated_integer_field = models.CommaSeparatedIntegerField(max_length=1024, blank=True) <del># decimal_field = models.DecimalField(max_digits=64, decimal_places=32, blank=True) <del># email_field = models.EmailField(max_length=1024, blank=True) <del># file_field = models.FileField(upload_to='test', max_length=1024, blank=True) <del># image_field = models.ImageField(upload_to='test', max_length=1024, blank=True) <del># slug_field = models.SlugField(max_length=1024, blank=True) <del># url_field = models.URLField(max_length=1024, blank=True) <del># nullable_char_field = models.CharField(max_length=1024, blank=True, null=True) <del> <del># class DVOAFModel(RESTFrameworkModel): <del># positive_integer_field = models.PositiveIntegerField(blank=True) <del># positive_small_integer_field = models.PositiveSmallIntegerField(blank=True) <del># email_field = models.EmailField(blank=True) <del># file_field = models.FileField(upload_to='test', blank=True) <del># image_field = models.ImageField(upload_to='test', blank=True) <del># slug_field = models.SlugField(blank=True) <del># url_field = models.URLField(blank=True) <del> <del> <del># class SubComment(object): <del># def __init__(self, sub_comment): <del># self.sub_comment = sub_comment <del> <del> <del># class Comment(object): <del># def __init__(self, email, content, created): <del># self.email = email <del># self.content = content <del># self.created = created or datetime.datetime.now() <del> <del># def __eq__(self, other): <del># return all([getattr(self, attr) == getattr(other, attr) <del># for attr in ('email', 'content', 'created')]) <del> <del># def get_sub_comment(self): <del># sub_comment = SubComment('And Merry Christmas!') <del># return sub_comment <del> <del> <del># class CommentSerializer(serializers.Serializer): <del># email = serializers.EmailField() <del># content = serializers.CharField(max_length=1000) <del># created = serializers.DateTimeField() <del># sub_comment = serializers.Field(source='get_sub_comment.sub_comment') <del> <del># def restore_object(self, data, instance=None): <del># if instance is None: <del># return Comment(**data) <del># for key, val in data.items(): <del># setattr(instance, key, val) <del># return instance <del> <del> <del># class NamesSerializer(serializers.Serializer): <del># first = serializers.CharField() <del># last = serializers.CharField(required=False, default='') <del># initials = serializers.CharField(required=False, default='') <del> <del> <del># class PersonIdentifierSerializer(serializers.Serializer): <del># ssn = serializers.CharField() <del># names = NamesSerializer(source='names', required=False) <del> <del> <del># class BookSerializer(serializers.ModelSerializer): <del># isbn = serializers.RegexField(regex=r'^[0-9]{13}$', error_messages={'invalid': 'isbn has to be exact 13 numbers'}) <del> <del># class Meta: <del># model = Book <del> <del> <del># class ActionItemSerializer(serializers.ModelSerializer): <del> <del># class Meta: <del># model = ActionItem <del> <del> <del># class ActionItemSerializerOptionalFields(serializers.ModelSerializer): <del># """ <del># Intended to test that fields with `required=False` are excluded from validation. <del># """ <del># title = serializers.CharField(required=False) <del> <del># class Meta: <del># model = ActionItem <del># fields = ('title',) <del> <del> <del># class ActionItemSerializerCustomRestore(serializers.ModelSerializer): <del> <del># class Meta: <del># model = ActionItem <del> <del># def restore_object(self, data, instance=None): <del># if instance is None: <del># return ActionItem(**data) <del># for key, val in data.items(): <del># setattr(instance, key, val) <del># return instance <del> <del> <del># class PersonSerializer(serializers.ModelSerializer): <del># info = serializers.Field(source='info') <del> <del># class Meta: <del># model = Person <del># fields = ('name', 'age', 'info') <del># read_only_fields = ('age',) <del> <del> <del># class NestedSerializer(serializers.Serializer): <del># info = serializers.Field() <del> <del> <del># class ModelSerializerWithNestedSerializer(serializers.ModelSerializer): <del># nested = NestedSerializer(source='*') <del> <del># class Meta: <del># model = Person <del> <del> <del># class NestedSerializerWithRenamedField(serializers.Serializer): <del># renamed_info = serializers.Field(source='info') <del> <del> <del># class ModelSerializerWithNestedSerializerWithRenamedField(serializers.ModelSerializer): <del># nested = NestedSerializerWithRenamedField(source='*') <del> <del># class Meta: <del># model = Person <del> <del> <del># class PersonSerializerInvalidReadOnly(serializers.ModelSerializer): <del># """ <del># Testing for #652. <del># """ <del># info = serializers.Field(source='info') <del> <del># class Meta: <del># model = Person <del># fields = ('name', 'age', 'info') <del># read_only_fields = ('age', 'info') <del> <del> <del># class AlbumsSerializer(serializers.ModelSerializer): <del> <del># class Meta: <del># model = Album <del># fields = ['title', 'ref'] # lists are also valid options <del> <del> <del># class PositiveIntegerAsChoiceSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = HasPositiveIntegerAsChoice <del># fields = ['some_integer'] <del> <del> <del># class ForeignKeySourceSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = ForeignKeySource <del> <del> <del># class HyperlinkedForeignKeySourceSerializer(serializers.HyperlinkedModelSerializer): <del># class Meta: <del># model = ForeignKeySource <del> <del> <del># class BasicTests(TestCase): <del># def setUp(self): <del># self.comment = Comment( <del># 'tom@example.com', <del># 'Happy new year!', <del># datetime.datetime(2012, 1, 1) <del># ) <del># self.actionitem = ActionItem(title='Some to do item',) <del># self.data = { <del># 'email': 'tom@example.com', <del># 'content': 'Happy new year!', <del># 'created': datetime.datetime(2012, 1, 1), <del># 'sub_comment': 'This wont change' <del># } <del># self.expected = { <del># 'email': 'tom@example.com', <del># 'content': 'Happy new year!', <del># 'created': datetime.datetime(2012, 1, 1), <del># 'sub_comment': 'And Merry Christmas!' <del># } <del># self.person_data = {'name': 'dwight', 'age': 35} <del># self.person = Person(**self.person_data) <del># self.person.save() <del> <del># def test_empty(self): <del># serializer = CommentSerializer() <del># expected = { <del># 'email': '', <del># 'content': '', <del># 'created': None <del># } <del># self.assertEqual(serializer.data, expected) <del> <del># def test_retrieve(self): <del># serializer = CommentSerializer(self.comment) <del># self.assertEqual(serializer.data, self.expected) <del> <del># def test_create(self): <del># serializer = CommentSerializer(data=self.data) <del># expected = self.comment <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected) <del># self.assertFalse(serializer.object is expected) <del># self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!') <del> <del># def test_create_nested(self): <del># """Test a serializer with nested data.""" <del># names = {'first': 'John', 'last': 'Doe', 'initials': 'jd'} <del># data = {'ssn': '1234567890', 'names': names} <del># serializer = PersonIdentifierSerializer(data=data) <del> <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, data) <del># self.assertFalse(serializer.object is data) <del># self.assertEqual(serializer.data['names'], names) <del> <del># def test_create_partial_nested(self): <del># """Test a serializer with nested data which has missing fields.""" <del># names = {'first': 'John'} <del># data = {'ssn': '1234567890', 'names': names} <del># serializer = PersonIdentifierSerializer(data=data) <del> <del># expected_names = {'first': 'John', 'last': '', 'initials': ''} <del># data['names'] = expected_names <del> <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, data) <del># self.assertFalse(serializer.object is expected_names) <del># self.assertEqual(serializer.data['names'], expected_names) <del> <del># def test_null_nested(self): <del># """Test a serializer with a nonexistent nested field""" <del># data = {'ssn': '1234567890'} <del># serializer = PersonIdentifierSerializer(data=data) <del> <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, data) <del># self.assertFalse(serializer.object is data) <del># expected = {'ssn': '1234567890', 'names': None} <del># self.assertEqual(serializer.data, expected) <del> <del># def test_update(self): <del># serializer = CommentSerializer(self.comment, data=self.data) <del># expected = self.comment <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected) <del># self.assertTrue(serializer.object is expected) <del># self.assertEqual(serializer.data['sub_comment'], 'And Merry Christmas!') <del> <del># def test_partial_update(self): <del># msg = 'Merry New Year!' <del># partial_data = {'content': msg} <del># serializer = CommentSerializer(self.comment, data=partial_data) <del># self.assertEqual(serializer.is_valid(), False) <del># serializer = CommentSerializer(self.comment, data=partial_data, partial=True) <del># expected = self.comment <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected) <del># self.assertTrue(serializer.object is expected) <del># self.assertEqual(serializer.data['content'], msg) <del> <del># def test_model_fields_as_expected(self): <del># """ <del># Make sure that the fields returned are the same as defined <del># in the Meta data <del># """ <del># serializer = PersonSerializer(self.person) <del># self.assertEqual( <del># set(serializer.data.keys()), <del># set(['name', 'age', 'info']) <del># ) <del> <del># def test_field_with_dictionary(self): <del># """ <del># Make sure that dictionaries from fields are left intact <del># """ <del># serializer = PersonSerializer(self.person) <del># expected = self.person_data <del># self.assertEqual(serializer.data['info'], expected) <del> <del># def test_read_only_fields(self): <del># """ <del># Attempting to update fields set as read_only should have no effect. <del># """ <del># serializer = PersonSerializer(self.person, data={'name': 'dwight', 'age': 99}) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(serializer.errors, {}) <del># # Assert age is unchanged (35) <del># self.assertEqual(instance.age, self.person_data['age']) <del> <del># def test_invalid_read_only_fields(self): <del># """ <del># Regression test for #652. <del># """ <del># self.assertRaises(AssertionError, PersonSerializerInvalidReadOnly, []) <del> <del># def test_serializer_data_is_cleared_on_save(self): <del># """ <del># Check _data attribute is cleared on `save()` <del> <del># Regression test for #1116 <del># """ <del># serializer = ActionItemSerializer(self.actionitem) <del># self.assertIsNone(serializer.data.get('id', None), 'New instance. `id` should not be set.') <del># serializer.save() <del># self.assertIsNotNone(serializer.data.get('id', None), 'Model is saved. `id` should be set.') <del> <del># def test_fields_marked_as_not_required_are_excluded_from_validation(self): <del># """ <del># Check that fields with `required=False` are included in list of exclusions. <del># """ <del># serializer = ActionItemSerializerOptionalFields(self.actionitem) <del># exclusions = serializer.get_validation_exclusions() <del># self.assertTrue('title' in exclusions, '`title` field was marked `required=False` and should be excluded') <del> <del> <del># class DictStyleSerializer(serializers.Serializer): <del># """ <del># Note that we don't have any `restore_object` method, so the default <del># case of simply returning a dict will apply. <del># """ <del># email = serializers.EmailField() <del> <del> <del># class DictStyleSerializerTests(TestCase): <del># def test_dict_style_deserialize(self): <del># """ <del># Ensure serializers can deserialize into a dict. <del># """ <del># data = {'email': 'foo@example.com'} <del># serializer = DictStyleSerializer(data=data) <del># self.assertTrue(serializer.is_valid()) <del># self.assertEqual(serializer.data, data) <del> <del># def test_dict_style_serialize(self): <del># """ <del># Ensure serializers can serialize dict objects. <del># """ <del># data = {'email': 'foo@example.com'} <del># serializer = DictStyleSerializer(data) <del># self.assertEqual(serializer.data, data) <del> <del> <del># class ValidationTests(TestCase): <del># def setUp(self): <del># self.comment = Comment( <del># 'tom@example.com', <del># 'Happy new year!', <del># datetime.datetime(2012, 1, 1) <del># ) <del># self.data = { <del># 'email': 'tom@example.com', <del># 'content': 'x' * 1001, <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del># self.actionitem = ActionItem(title='Some to do item',) <del> <del># def test_create(self): <del># serializer = CommentSerializer(data=self.data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']}) <del> <del># def test_update(self): <del># serializer = CommentSerializer(self.comment, data=self.data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, {'content': ['Ensure this value has at most 1000 characters (it has 1001).']}) <del> <del># def test_update_missing_field(self): <del># data = { <del># 'content': 'xxx', <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del># serializer = CommentSerializer(self.comment, data=data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, {'email': ['This field is required.']}) <del> <del># def test_missing_bool_with_default(self): <del># """Make sure that a boolean value with a 'False' value is not <del># mistaken for not having a default.""" <del># data = { <del># 'title': 'Some action item', <del># # No 'done' value. <del># } <del># serializer = ActionItemSerializer(self.actionitem, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.errors, {}) <del> <del># def test_cross_field_validation(self): <del> <del># class CommentSerializerWithCrossFieldValidator(CommentSerializer): <del> <del># def validate(self, attrs): <del># if attrs["email"] not in attrs["content"]: <del># raise serializers.ValidationError("Email address not in content") <del># return attrs <del> <del># data = { <del># 'email': 'tom@example.com', <del># 'content': 'A comment from tom@example.com', <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del> <del># serializer = CommentSerializerWithCrossFieldValidator(data=data) <del># self.assertTrue(serializer.is_valid()) <del> <del># data['content'] = 'A comment from foo@bar.com' <del> <del># serializer = CommentSerializerWithCrossFieldValidator(data=data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'non_field_errors': ['Email address not in content']}) <del> <del># def test_null_is_true_fields(self): <del># """ <del># Omitting a value for null-field should validate. <del># """ <del># serializer = PersonSerializer(data={'name': 'marko'}) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.errors, {}) <del> <del># def test_modelserializer_max_length_exceeded(self): <del># data = { <del># 'title': 'x' * 201, <del># } <del># serializer = ActionItemSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']}) <del> <del># def test_modelserializer_max_length_exceeded_with_custom_restore(self): <del># """ <del># When overriding ModelSerializer.restore_object, validation tests should still apply. <del># Regression test for #623. <del> <del># https://github.com/tomchristie/django-rest-framework/pull/623 <del># """ <del># data = { <del># 'title': 'x' * 201, <del># } <del># serializer = ActionItemSerializerCustomRestore(data=data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, {'title': ['Ensure this value has at most 200 characters (it has 201).']}) <del> <del># def test_default_modelfield_max_length_exceeded(self): <del># data = { <del># 'title': 'Testing "info" field...', <del># 'info': 'x' * 13, <del># } <del># serializer = ActionItemSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, {'info': ['Ensure this value has at most 12 characters (it has 13).']}) <del> <del># def test_datetime_validation_failure(self): <del># """ <del># Test DateTimeField validation errors on non-str values. <del># Regression test for #669. <del> <del># https://github.com/tomchristie/django-rest-framework/issues/669 <del># """ <del># data = self.data <del># data['created'] = 0 <del> <del># serializer = CommentSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), False) <del> <del># self.assertIn('created', serializer.errors) <del> <del># def test_missing_model_field_exception_msg(self): <del># """ <del># Assert that a meaningful exception message is outputted when the model <del># field is missing (e.g. when mistyping ``model``). <del># """ <del># class BrokenModelSerializer(serializers.ModelSerializer): <del># class Meta: <del># fields = ['some_field'] <del> <del># try: <del># BrokenModelSerializer() <del># except AssertionError as e: <del># self.assertEqual(e.args[0], "Serializer class 'BrokenModelSerializer' is missing 'model' Meta option") <del># except: <del># self.fail('Wrong exception type thrown.') <del> <del># def test_writable_star_source_on_nested_serializer(self): <del># """ <del># Assert that a nested serializer instantiated with source='*' correctly <del># expands the data into the outer serializer. <del># """ <del># serializer = ModelSerializerWithNestedSerializer(data={ <del># 'name': 'marko', <del># 'nested': {'info': 'hi'}}, <del># ) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># def test_writable_star_source_on_nested_serializer_with_parent_object(self): <del># class TitleSerializer(serializers.Serializer): <del># title = serializers.WritableField(source='title') <del> <del># class AlbumSerializer(serializers.ModelSerializer): <del># nested = TitleSerializer(source='*') <del> <del># class Meta: <del># model = Album <del># fields = ('nested',) <del> <del># class PhotoSerializer(serializers.ModelSerializer): <del># album = AlbumSerializer(source='album') <del> <del># class Meta: <del># model = Photo <del># fields = ('album', ) <del> <del># photo = Photo(album=Album()) <del> <del># data = {'album': {'nested': {'title': 'test'}}} <del> <del># serializer = PhotoSerializer(photo, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.data, data) <del> <del># def test_writable_star_source_with_inner_source_fields(self): <del># """ <del># Tests that a serializer with source="*" correctly expands the <del># it's fields into the outer serializer even if they have their <del># own 'source' parameters. <del># """ <del> <del># serializer = ModelSerializerWithNestedSerializerWithRenamedField(data={ <del># 'name': 'marko', <del># 'nested': {'renamed_info': 'hi'}}, <del># ) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.errors, {}) <del> <del> <del># class CustomValidationTests(TestCase): <del># class CommentSerializerWithFieldValidator(CommentSerializer): <del> <del># def validate_email(self, attrs, source): <del># attrs[source] <del># return attrs <del> <del># def validate_content(self, attrs, source): <del># value = attrs[source] <del># if "test" not in value: <del># raise serializers.ValidationError("Test not in value") <del># return attrs <del> <del># def test_field_validation(self): <del># data = { <del># 'email': 'tom@example.com', <del># 'content': 'A test comment', <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del> <del># serializer = self.CommentSerializerWithFieldValidator(data=data) <del># self.assertTrue(serializer.is_valid()) <del> <del># data['content'] = 'This should not validate' <del> <del># serializer = self.CommentSerializerWithFieldValidator(data=data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'content': ['Test not in value']}) <del> <del># def test_missing_data(self): <del># """ <del># Make sure that validate_content isn't called if the field is missing <del># """ <del># incomplete_data = { <del># 'email': 'tom@example.com', <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del># serializer = self.CommentSerializerWithFieldValidator(data=incomplete_data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'content': ['This field is required.']}) <del> <del># def test_wrong_data(self): <del># """ <del># Make sure that validate_content isn't called if the field input is wrong <del># """ <del># wrong_data = { <del># 'email': 'not an email', <del># 'content': 'A test comment', <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del># serializer = self.CommentSerializerWithFieldValidator(data=wrong_data) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'email': ['Enter a valid email address.']}) <del> <del># def test_partial_update(self): <del># """ <del># Make sure that validate_email isn't called when partial=True and email <del># isn't found in data. <del># """ <del># initial_data = { <del># 'email': 'tom@example.com', <del># 'content': 'A test comment', <del># 'created': datetime.datetime(2012, 1, 1) <del># } <del> <del># serializer = self.CommentSerializerWithFieldValidator(data=initial_data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.object <del> <del># new_content = 'An *updated* test comment' <del># partial_data = { <del># 'content': new_content <del># } <del> <del># serializer = self.CommentSerializerWithFieldValidator(instance=instance, <del># data=partial_data, <del># partial=True) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.object <del># self.assertEqual(instance.content, new_content) <del> <del> <del># class PositiveIntegerAsChoiceTests(TestCase): <del># def test_positive_integer_in_json_is_correctly_parsed(self): <del># data = {'some_integer': 1} <del># serializer = PositiveIntegerAsChoiceSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del> <del> <del># class ModelValidationTests(TestCase): <del># def test_validate_unique(self): <del># """ <del># Just check if serializers.ModelSerializer handles unique checks via .full_clean() <del># """ <del># serializer = AlbumsSerializer(data={'title': 'a', 'ref': '1'}) <del># serializer.is_valid() <del># serializer.save() <del># second_serializer = AlbumsSerializer(data={'title': 'a'}) <del># self.assertFalse(second_serializer.is_valid()) <del># self.assertEqual(second_serializer.errors, {'title': ['Album with this Title already exists.']}) <del># third_serializer = AlbumsSerializer(data=[{'title': 'b', 'ref': '1'}, {'title': 'c'}], many=True) <del># self.assertFalse(third_serializer.is_valid()) <del># self.assertEqual(third_serializer.errors, [{'ref': ['Album with this Ref already exists.']}, {}]) <del> <del># def test_foreign_key_is_null_with_partial(self): <del># """ <del># Test ModelSerializer validation with partial=True <del> <del># Specifically test that a null foreign key does not pass validation <del># """ <del># album = Album(title='test') <del># album.save() <del> <del># class PhotoSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Photo <del> <del># photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk}) <del># self.assertTrue(photo_serializer.is_valid()) <del># photo = photo_serializer.save() <del> <del># # Updating only the album (foreign key) <del># photo_serializer = PhotoSerializer(instance=photo, data={'album': ''}, partial=True) <del># self.assertFalse(photo_serializer.is_valid()) <del># self.assertTrue('album' in photo_serializer.errors) <del># self.assertEqual(photo_serializer.errors['album'], [photo_serializer.error_messages['required']]) <del> <del># def test_foreign_key_with_partial(self): <del># """ <del># Test ModelSerializer validation with partial=True <del> <del># Specifically test foreign key validation. <del># """ <del> <del># album = Album(title='test') <del># album.save() <del> <del># class PhotoSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Photo <del> <del># photo_serializer = PhotoSerializer(data={'description': 'test', 'album': album.pk}) <del># self.assertTrue(photo_serializer.is_valid()) <del># photo = photo_serializer.save() <del> <del># # Updating only the album (foreign key) <del># photo_serializer = PhotoSerializer(instance=photo, data={'album': album.pk}, partial=True) <del># self.assertTrue(photo_serializer.is_valid()) <del># self.assertTrue(photo_serializer.save()) <del> <del># # Updating only the description <del># photo_serializer = PhotoSerializer(instance=photo, <del># data={'description': 'new'}, <del># partial=True) <del> <del># self.assertTrue(photo_serializer.is_valid()) <del># self.assertTrue(photo_serializer.save()) <del> <del> <del># class RegexValidationTest(TestCase): <del># def test_create_failed(self): <del># serializer = BookSerializer(data={'isbn': '1234567890'}) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) <del> <del># serializer = BookSerializer(data={'isbn': '12345678901234'}) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) <del> <del># serializer = BookSerializer(data={'isbn': 'abcdefghijklm'}) <del># self.assertFalse(serializer.is_valid()) <del># self.assertEqual(serializer.errors, {'isbn': ['isbn has to be exact 13 numbers']}) <del> <del># def test_create_success(self): <del># serializer = BookSerializer(data={'isbn': '1234567890123'}) <del># self.assertTrue(serializer.is_valid()) <del> <del> <del># class MetadataTests(TestCase): <del># def test_empty(self): <del># serializer = CommentSerializer() <del># expected = { <del># 'email': serializers.CharField, <del># 'content': serializers.CharField, <del># 'created': serializers.DateTimeField <del># } <del># for field_name, field in expected.items(): <del># self.assertTrue(isinstance(serializer.data.fields[field_name], field)) <del> <del> <del># class ManyToManyTests(TestCase): <del># def setUp(self): <del># class ManyToManySerializer(serializers.ModelSerializer): <del># class Meta: <del># model = ManyToManyModel <del> <del># self.serializer_class = ManyToManySerializer <del> <del># # An anchor instance to use for the relationship <del># self.anchor = Anchor() <del># self.anchor.save() <del> <del># # A model instance with a many to many relationship to the anchor <del># self.instance = ManyToManyModel() <del># self.instance.save() <del># self.instance.rel.add(self.anchor) <del> <del># # A serialized representation of the model instance <del># self.data = {'id': 1, 'rel': [self.anchor.id]} <del> <del># def test_retrieve(self): <del># """ <del># Serialize an instance of a model with a ManyToMany relationship. <del># """ <del># serializer = self.serializer_class(instance=self.instance) <del># expected = self.data <del># self.assertEqual(serializer.data, expected) <del> <del># def test_create(self): <del># """ <del># Create an instance of a model with a ManyToMany relationship. <del># """ <del># data = {'rel': [self.anchor.id]} <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ManyToManyModel.objects.all()), 2) <del># self.assertEqual(instance.pk, 2) <del># self.assertEqual(list(instance.rel.all()), [self.anchor]) <del> <del># def test_update(self): <del># """ <del># Update an instance of a model with a ManyToMany relationship. <del># """ <del># new_anchor = Anchor() <del># new_anchor.save() <del># data = {'rel': [self.anchor.id, new_anchor.id]} <del># serializer = self.serializer_class(self.instance, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ManyToManyModel.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># self.assertEqual(list(instance.rel.all()), [self.anchor, new_anchor]) <del> <del># def test_create_empty_relationship(self): <del># """ <del># Create an instance of a model with a ManyToMany relationship, <del># containing no items. <del># """ <del># data = {'rel': []} <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ManyToManyModel.objects.all()), 2) <del># self.assertEqual(instance.pk, 2) <del># self.assertEqual(list(instance.rel.all()), []) <del> <del># def test_update_empty_relationship(self): <del># """ <del># Update an instance of a model with a ManyToMany relationship, <del># containing no items. <del># """ <del># new_anchor = Anchor() <del># new_anchor.save() <del># data = {'rel': []} <del># serializer = self.serializer_class(self.instance, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ManyToManyModel.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># self.assertEqual(list(instance.rel.all()), []) <del> <del># def test_create_empty_relationship_flat_data(self): <del># """ <del># Create an instance of a model with a ManyToMany relationship, <del># containing no items, using a representation that does not support <del># lists (eg form data). <del># """ <del># data = MultiValueDict() <del># data.setlist('rel', ['']) <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ManyToManyModel.objects.all()), 2) <del># self.assertEqual(instance.pk, 2) <del># self.assertEqual(list(instance.rel.all()), []) <del> <del> <del># class ReadOnlyManyToManyTests(TestCase): <del># def setUp(self): <del># class ReadOnlyManyToManySerializer(serializers.ModelSerializer): <del># rel = serializers.RelatedField(many=True, read_only=True) <del> <del># class Meta: <del># model = ReadOnlyManyToManyModel <del> <del># self.serializer_class = ReadOnlyManyToManySerializer <del> <del># # An anchor instance to use for the relationship <del># self.anchor = Anchor() <del># self.anchor.save() <del> <del># # A model instance with a many to many relationship to the anchor <del># self.instance = ReadOnlyManyToManyModel() <del># self.instance.save() <del># self.instance.rel.add(self.anchor) <del> <del># # A serialized representation of the model instance <del># self.data = {'rel': [self.anchor.id], 'id': 1, 'text': 'anchor'} <del> <del># def test_update(self): <del># """ <del># Attempt to update an instance of a model with a ManyToMany <del># relationship. Not updated due to read_only=True <del># """ <del># new_anchor = Anchor() <del># new_anchor.save() <del># data = {'rel': [self.anchor.id, new_anchor.id]} <del># serializer = self.serializer_class(self.instance, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># # rel is still as original (1 entry) <del># self.assertEqual(list(instance.rel.all()), [self.anchor]) <del> <del># def test_update_without_relationship(self): <del># """ <del># Attempt to update an instance of a model where many to ManyToMany <del># relationship is not supplied. Not updated due to read_only=True <del># """ <del># new_anchor = Anchor() <del># new_anchor.save() <del># data = {} <del># serializer = self.serializer_class(self.instance, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(ReadOnlyManyToManyModel.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># # rel is still as original (1 entry) <del># self.assertEqual(list(instance.rel.all()), [self.anchor]) <del> <del> <del># class DefaultValueTests(TestCase): <del># def setUp(self): <del># class DefaultValueSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = DefaultValueModel <del> <del># self.serializer_class = DefaultValueSerializer <del># self.objects = DefaultValueModel.objects <del> <del># def test_create_using_default(self): <del># data = {} <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(self.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># self.assertEqual(instance.text, 'foobar') <del> <del># def test_create_overriding_default(self): <del># data = {'text': 'overridden'} <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(self.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># self.assertEqual(instance.text, 'overridden') <del> <del># def test_partial_update_default(self): <del># """ Regression test for issue #532 """ <del># data = {'text': 'overridden'} <del># serializer = self.serializer_class(data=data, partial=True) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del> <del># data = {'extra': 'extra_value'} <del># serializer = self.serializer_class(instance=instance, data=data, partial=True) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del> <del># self.assertEqual(instance.extra, 'extra_value') <del># self.assertEqual(instance.text, 'overridden') <del> <del> <del># class WritableFieldDefaultValueTests(TestCase): <del> <del># def setUp(self): <del># self.expected = {'default': 'value'} <del># self.create_field = fields.WritableField <del> <del># def test_get_default_value_with_noncallable(self): <del># field = self.create_field(default=self.expected) <del># got = field.get_default_value() <del># self.assertEqual(got, self.expected) <del> <del># def test_get_default_value_with_callable(self): <del># field = self.create_field(default=lambda: self.expected) <del># got = field.get_default_value() <del># self.assertEqual(got, self.expected) <del> <del># def test_get_default_value_when_not_required(self): <del># field = self.create_field(default=self.expected, required=False) <del># got = field.get_default_value() <del># self.assertEqual(got, self.expected) <del> <del># def test_get_default_value_returns_None(self): <del># field = self.create_field() <del># got = field.get_default_value() <del># self.assertIsNone(got) <del> <del># def test_get_default_value_returns_non_True_values(self): <del># values = [None, '', False, 0, [], (), {}] # values that assumed as 'False' in the 'if' clause <del># for expected in values: <del># field = self.create_field(default=expected) <del># got = field.get_default_value() <del># self.assertEqual(got, expected) <del> <del> <del># class RelatedFieldDefaultValueTests(WritableFieldDefaultValueTests): <del> <del># def setUp(self): <del># self.expected = {'foo': 'bar'} <del># self.create_field = relations.RelatedField <del> <del># def test_get_default_value_returns_empty_list(self): <del># field = self.create_field(many=True) <del># got = field.get_default_value() <del># self.assertListEqual(got, []) <del> <del># def test_get_default_value_returns_expected(self): <del># expected = [1, 2, 3] <del># field = self.create_field(many=True, default=expected) <del># got = field.get_default_value() <del># self.assertListEqual(got, expected) <del> <del> <del># class CallableDefaultValueTests(TestCase): <del># def setUp(self): <del># class CallableDefaultValueSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = CallableDefaultValueModel <del> <del># self.serializer_class = CallableDefaultValueSerializer <del># self.objects = CallableDefaultValueModel.objects <del> <del># def test_create_using_default(self): <del># data = {} <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(self.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># self.assertEqual(instance.text, 'foobar') <del> <del># def test_create_overriding_default(self): <del># data = {'text': 'overridden'} <del># serializer = self.serializer_class(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># instance = serializer.save() <del># self.assertEqual(len(self.objects.all()), 1) <del># self.assertEqual(instance.pk, 1) <del># self.assertEqual(instance.text, 'overridden') <del> <del> <del># class ManyRelatedTests(TestCase): <del># def test_reverse_relations(self): <del># post = BlogPost.objects.create(title="Test blog post") <del># post.blogpostcomment_set.create(text="I hate this blog post") <del># post.blogpostcomment_set.create(text="I love this blog post") <del> <del># class BlogPostCommentSerializer(serializers.Serializer): <del># text = serializers.CharField() <del> <del># class BlogPostSerializer(serializers.Serializer): <del># title = serializers.CharField() <del># comments = BlogPostCommentSerializer(source='blogpostcomment_set') <del> <del># serializer = BlogPostSerializer(instance=post) <del># expected = { <del># 'title': 'Test blog post', <del># 'comments': [ <del># {'text': 'I hate this blog post'}, <del># {'text': 'I love this blog post'} <del># ] <del># } <del> <del># self.assertEqual(serializer.data, expected) <del> <del># def test_include_reverse_relations(self): <del># post = BlogPost.objects.create(title="Test blog post") <del># post.blogpostcomment_set.create(text="I hate this blog post") <del># post.blogpostcomment_set.create(text="I love this blog post") <del> <del># class BlogPostSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BlogPost <del># fields = ('id', 'title', 'blogpostcomment_set') <del> <del># serializer = BlogPostSerializer(instance=post) <del># expected = { <del># 'id': 1, 'title': 'Test blog post', 'blogpostcomment_set': [1, 2] <del># } <del># self.assertEqual(serializer.data, expected) <del> <del># def test_depth_include_reverse_relations(self): <del># post = BlogPost.objects.create(title="Test blog post") <del># post.blogpostcomment_set.create(text="I hate this blog post") <del># post.blogpostcomment_set.create(text="I love this blog post") <del> <del># class BlogPostSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BlogPost <del># fields = ('id', 'title', 'blogpostcomment_set') <del># depth = 1 <del> <del># serializer = BlogPostSerializer(instance=post) <del># expected = { <del># 'id': 1, 'title': 'Test blog post', <del># 'blogpostcomment_set': [ <del># {'id': 1, 'text': 'I hate this blog post', 'blog_post': 1}, <del># {'id': 2, 'text': 'I love this blog post', 'blog_post': 1} <del># ] <del># } <del># self.assertEqual(serializer.data, expected) <del> <del># def test_callable_source(self): <del># post = BlogPost.objects.create(title="Test blog post") <del># post.blogpostcomment_set.create(text="I love this blog post") <del> <del># class BlogPostCommentSerializer(serializers.Serializer): <del># text = serializers.CharField() <del> <del># class BlogPostSerializer(serializers.Serializer): <del># title = serializers.CharField() <del># first_comment = BlogPostCommentSerializer(source='get_first_comment') <del> <del># serializer = BlogPostSerializer(post) <del> <del># expected = { <del># 'title': 'Test blog post', <del># 'first_comment': {'text': 'I love this blog post'} <del># } <del># self.assertEqual(serializer.data, expected) <del> <del> <del># class RelatedTraversalTest(TestCase): <del># def test_nested_traversal(self): <del># """ <del># Source argument should support dotted.source notation. <del># """ <del># user = Person.objects.create(name="django") <del># post = BlogPost.objects.create(title="Test blog post", writer=user) <del># post.blogpostcomment_set.create(text="I love this blog post") <del> <del># class PersonSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Person <del># fields = ("name", "age") <del> <del># class BlogPostCommentSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BlogPostComment <del># fields = ("text", "post_owner") <del> <del># text = serializers.CharField() <del># post_owner = PersonSerializer(source='blog_post.writer') <del> <del># class BlogPostSerializer(serializers.Serializer): <del># title = serializers.CharField() <del># comments = BlogPostCommentSerializer(source='blogpostcomment_set') <del> <del># serializer = BlogPostSerializer(instance=post) <del> <del># expected = { <del># 'title': 'Test blog post', <del># 'comments': [{ <del># 'text': 'I love this blog post', <del># 'post_owner': { <del># "name": "django", <del># "age": None <del># } <del># }] <del># } <del> <del># self.assertEqual(serializer.data, expected) <del> <del># def test_nested_traversal_with_none(self): <del># """ <del># If a component of the dotted.source is None, return None for the field. <del># """ <del># from tests.models import NullableForeignKeySource <del># instance = NullableForeignKeySource.objects.create(name='Source with null FK') <del> <del># class NullableSourceSerializer(serializers.Serializer): <del># target_name = serializers.Field(source='target.name') <del> <del># serializer = NullableSourceSerializer(instance=instance) <del> <del># expected = { <del># 'target_name': None, <del># } <del> <del># self.assertEqual(serializer.data, expected) <del> <del> <del># class SerializerMethodFieldTests(TestCase): <del># def setUp(self): <del> <del># class BoopSerializer(serializers.Serializer): <del># beep = serializers.SerializerMethodField('get_beep') <del># boop = serializers.Field() <del># boop_count = serializers.SerializerMethodField('get_boop_count') <del> <del># def get_beep(self, obj): <del># return 'hello!' <del> <del># def get_boop_count(self, obj): <del># return len(obj.boop) <del> <del># self.serializer_class = BoopSerializer <del> <del># def test_serializer_method_field(self): <del> <del># class MyModel(object): <del># boop = ['a', 'b', 'c'] <del> <del># source_data = MyModel() <del> <del># serializer = self.serializer_class(source_data) <del> <del># expected = { <del># 'beep': 'hello!', <del># 'boop': ['a', 'b', 'c'], <del># 'boop_count': 3, <del># } <del> <del># self.assertEqual(serializer.data, expected) <del> <del> <del># # Test for issue #324 <del># class BlankFieldTests(TestCase): <del># def setUp(self): <del> <del># class BlankFieldModelSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BlankFieldModel <del> <del># class BlankFieldSerializer(serializers.Serializer): <del># title = serializers.CharField(required=False) <del> <del># class NotBlankFieldModelSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BasicModel <del> <del># class NotBlankFieldSerializer(serializers.Serializer): <del># title = serializers.CharField() <del> <del># self.model_serializer_class = BlankFieldModelSerializer <del># self.serializer_class = BlankFieldSerializer <del># self.not_blank_model_serializer_class = NotBlankFieldModelSerializer <del># self.not_blank_serializer_class = NotBlankFieldSerializer <del># self.data = {'title': ''} <del> <del># def test_create_blank_field(self): <del># serializer = self.serializer_class(data=self.data) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># def test_create_model_blank_field(self): <del># serializer = self.model_serializer_class(data=self.data) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># def test_create_model_null_field(self): <del># serializer = self.model_serializer_class(data={'title': None}) <del># self.assertEqual(serializer.is_valid(), True) <del># serializer.save() <del># self.assertIsNot(serializer.object.pk, None) <del># self.assertEqual(serializer.object.title, '') <del> <del># def test_create_not_blank_field(self): <del># """ <del># Test to ensure blank data in a field not marked as blank=True <del># is considered invalid in a non-model serializer <del># """ <del># serializer = self.not_blank_serializer_class(data=self.data) <del># self.assertEqual(serializer.is_valid(), False) <del> <del># def test_create_model_not_blank_field(self): <del># """ <del># Test to ensure blank data in a field not marked as blank=True <del># is considered invalid in a model serializer <del># """ <del># serializer = self.not_blank_model_serializer_class(data=self.data) <del># self.assertEqual(serializer.is_valid(), False) <del> <del># def test_create_model_empty_field(self): <del># serializer = self.model_serializer_class(data={}) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># def test_create_model_null_field_save(self): <del># """ <del># Regression test for #1330. <del> <del># https://github.com/tomchristie/django-rest-framework/pull/1330 <del># """ <del># serializer = self.model_serializer_class(data={'title': None}) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># try: <del># serializer.save() <del># except Exception: <del># self.fail('Exception raised on save() after validation passes') <del> <del> <del># # Test for issue #460 <del># class SerializerPickleTests(TestCase): <del># """ <del># Test pickleability of the output of Serializers <del># """ <del># def test_pickle_simple_model_serializer_data(self): <del># """ <del># Test simple serializer <del># """ <del># pickle.dumps(PersonSerializer(Person(name="Methusela", age=969)).data) <del> <del># def test_pickle_inner_serializer(self): <del># """ <del># Test pickling a serializer whose resulting .data (a SortedDictWithMetadata) will <del># have unpickleable meta data--in order to make sure metadata doesn't get pulled into the pickle. <del># See DictWithMetadata.__getstate__ <del># """ <del># class InnerPersonSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Person <del># fields = ('name', 'age') <del># pickle.dumps(InnerPersonSerializer(Person(name="Noah", age=950)).data, 0) <del> <del># def test_getstate_method_should_not_return_none(self): <del># """ <del># Regression test for #645. <del># """ <del># data = serializers.DictWithMetadata({1: 1}) <del># self.assertEqual(data.__getstate__(), serializers.SortedDict({1: 1})) <del> <del># def test_serializer_data_is_pickleable(self): <del># """ <del># Another regression test for #645. <del># """ <del># data = serializers.SortedDictWithMetadata({1: 1}) <del># repr(pickle.loads(pickle.dumps(data, 0))) <del> <del> <del># # test for issue #725 <del># class SeveralChoicesModel(models.Model): <del># color = models.CharField( <del># max_length=10, <del># choices=[('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')], <del># blank=False <del># ) <del># drink = models.CharField( <del># max_length=10, <del># choices=[('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')], <del># blank=False, <del># default='beer' <del># ) <del># os = models.CharField( <del># max_length=10, <del># choices=[('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')], <del># blank=True <del># ) <del># music_genre = models.CharField( <del># max_length=10, <del># choices=[('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')], <del># blank=True, <del># default='metal' <del># ) <del> <del> <del># class SerializerChoiceFields(TestCase): <del> <del># def setUp(self): <del># super(SerializerChoiceFields, self).setUp() <del> <del># class SeveralChoicesSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = SeveralChoicesModel <del># fields = ('color', 'drink', 'os', 'music_genre') <del> <del># self.several_choices_serializer = SeveralChoicesSerializer <del> <del># def test_choices_blank_false_not_default(self): <del># serializer = self.several_choices_serializer() <del># self.assertEqual( <del># serializer.fields['color'].choices, <del># [('red', 'Red'), ('green', 'Green'), ('blue', 'Blue')] <del># ) <del> <del># def test_choices_blank_false_with_default(self): <del># serializer = self.several_choices_serializer() <del># self.assertEqual( <del># serializer.fields['drink'].choices, <del># [('beer', 'Beer'), ('wine', 'Wine'), ('cider', 'Cider')] <del># ) <del> <del># def test_choices_blank_true_not_default(self): <del># serializer = self.several_choices_serializer() <del># self.assertEqual( <del># serializer.fields['os'].choices, <del># BLANK_CHOICE_DASH + [('linux', 'Linux'), ('osx', 'OSX'), ('windows', 'Windows')] <del># ) <del> <del># def test_choices_blank_true_with_default(self): <del># serializer = self.several_choices_serializer() <del># self.assertEqual( <del># serializer.fields['music_genre'].choices, <del># BLANK_CHOICE_DASH + [('rock', 'Rock'), ('metal', 'Metal'), ('grunge', 'Grunge')] <del># ) <del> <del> <del># # Regression tests for #675 <del># class Ticket(models.Model): <del># assigned = models.ForeignKey( <del># Person, related_name='assigned_tickets') <del># reviewer = models.ForeignKey( <del># Person, blank=True, null=True, related_name='reviewed_tickets') <del> <del> <del># class SerializerRelatedChoicesTest(TestCase): <del> <del># def setUp(self): <del># super(SerializerRelatedChoicesTest, self).setUp() <del> <del># class RelatedChoicesSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Ticket <del># fields = ('assigned', 'reviewer') <del> <del># self.related_fields_serializer = RelatedChoicesSerializer <del> <del># def test_empty_queryset_required(self): <del># serializer = self.related_fields_serializer() <del># self.assertEqual(serializer.fields['assigned'].queryset.count(), 0) <del># self.assertEqual( <del># [x for x in serializer.fields['assigned'].widget.choices], <del># [] <del># ) <del> <del># def test_empty_queryset_not_required(self): <del># serializer = self.related_fields_serializer() <del># self.assertEqual(serializer.fields['reviewer'].queryset.count(), 0) <del># self.assertEqual( <del># [x for x in serializer.fields['reviewer'].widget.choices], <del># [('', '---------')] <del># ) <del> <del># def test_with_some_persons_required(self): <del># Person.objects.create(name="Lionel Messi") <del># Person.objects.create(name="Xavi Hernandez") <del># serializer = self.related_fields_serializer() <del># self.assertEqual(serializer.fields['assigned'].queryset.count(), 2) <del># self.assertEqual( <del># [x for x in serializer.fields['assigned'].widget.choices], <del># [(1, 'Person object - 1'), (2, 'Person object - 2')] <del># ) <del> <del># def test_with_some_persons_not_required(self): <del># Person.objects.create(name="Lionel Messi") <del># Person.objects.create(name="Xavi Hernandez") <del># serializer = self.related_fields_serializer() <del># self.assertEqual(serializer.fields['reviewer'].queryset.count(), 2) <del># self.assertEqual( <del># [x for x in serializer.fields['reviewer'].widget.choices], <del># [('', '---------'), (1, 'Person object - 1'), (2, 'Person object - 2')] <del># ) <del> <del> <del># class DepthTest(TestCase): <del># def test_implicit_nesting(self): <del> <del># writer = Person.objects.create(name="django", age=1) <del># post = BlogPost.objects.create(title="Test blog post", writer=writer) <del># comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post) <del> <del># class BlogPostCommentSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = BlogPostComment <del># depth = 2 <del> <del># serializer = BlogPostCommentSerializer(instance=comment) <del># expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post', <del># 'writer': {'id': 1, 'name': 'django', 'age': 1}}} <del> <del># self.assertEqual(serializer.data, expected) <del> <del># def test_explicit_nesting(self): <del># writer = Person.objects.create(name="django", age=1) <del># post = BlogPost.objects.create(title="Test blog post", writer=writer) <del># comment = BlogPostComment.objects.create(text="Test blog post comment", blog_post=post) <del> <del># class PersonSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Person <del> <del># class BlogPostSerializer(serializers.ModelSerializer): <del># writer = PersonSerializer() <del> <del># class Meta: <del># model = BlogPost <del> <del># class BlogPostCommentSerializer(serializers.ModelSerializer): <del># blog_post = BlogPostSerializer() <del> <del># class Meta: <del># model = BlogPostComment <del> <del># serializer = BlogPostCommentSerializer(instance=comment) <del># expected = {'id': 1, 'text': 'Test blog post comment', 'blog_post': {'id': 1, 'title': 'Test blog post', <del># 'writer': {'id': 1, 'name': 'django', 'age': 1}}} <del> <del># self.assertEqual(serializer.data, expected) <del> <del> <del># class NestedSerializerContextTests(TestCase): <del> <del># def test_nested_serializer_context(self): <del># """ <del># Regression for #497 <del> <del># https://github.com/tomchristie/django-rest-framework/issues/497 <del># """ <del># class PhotoSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Photo <del># fields = ("description", "callable") <del> <del># callable = serializers.SerializerMethodField('_callable') <del> <del># def _callable(self, instance): <del># if 'context_item' not in self.context: <del># raise RuntimeError("context isn't getting passed into 2nd level nested serializer") <del># return "success" <del> <del># class AlbumSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = Album <del># fields = ("photo_set", "callable") <del> <del># photo_set = PhotoSerializer(source="photo_set", many=True) <del># callable = serializers.SerializerMethodField("_callable") <del> <del># def _callable(self, instance): <del># if 'context_item' not in self.context: <del># raise RuntimeError("context isn't getting passed into 1st level nested serializer") <del># return "success" <del> <del># class AlbumCollection(object): <del># albums = None <del> <del># class AlbumCollectionSerializer(serializers.Serializer): <del># albums = AlbumSerializer(source="albums", many=True) <del> <del># album1 = Album.objects.create(title="album 1") <del># album2 = Album.objects.create(title="album 2") <del># Photo.objects.create(description="Bigfoot", album=album1) <del># Photo.objects.create(description="Unicorn", album=album1) <del># Photo.objects.create(description="Yeti", album=album2) <del># Photo.objects.create(description="Sasquatch", album=album2) <del># album_collection = AlbumCollection() <del># album_collection.albums = [album1, album2] <del> <del># # This will raise RuntimeError if context doesn't get passed correctly to the nested Serializers <del># AlbumCollectionSerializer(album_collection, context={'context_item': 'album context'}).data <del> <del> <del># class DeserializeListTestCase(TestCase): <del> <del># def setUp(self): <del># self.data = { <del># 'email': 'nobody@nowhere.com', <del># 'content': 'This is some test content', <del># 'created': datetime.datetime(2013, 3, 7), <del># } <del> <del># def test_no_errors(self): <del># data = [self.data.copy() for x in range(0, 3)] <del># serializer = CommentSerializer(data=data, many=True) <del># self.assertTrue(serializer.is_valid()) <del># self.assertTrue(isinstance(serializer.object, list)) <del># self.assertTrue( <del># all((isinstance(item, Comment) for item in serializer.object)) <del># ) <del> <del># def test_errors_return_as_list(self): <del># invalid_item = self.data.copy() <del># invalid_item['email'] = '' <del># data = [self.data.copy(), invalid_item, self.data.copy()] <del> <del># serializer = CommentSerializer(data=data, many=True) <del># self.assertFalse(serializer.is_valid()) <del># expected = [{}, {'email': ['This field is required.']}, {}] <del># self.assertEqual(serializer.errors, expected) <del> <del> <del># # Test for issue 747 <del> <del># class LazyStringModel(object): <del># def __init__(self, lazystring): <del># self.lazystring = lazystring <del> <del> <del># class LazyStringSerializer(serializers.Serializer): <del># lazystring = serializers.Field() <del> <del># def restore_object(self, attrs, instance=None): <del># if instance is not None: <del># instance.lazystring = attrs.get('lazystring', instance.lazystring) <del># return instance <del># return LazyStringModel(**attrs) <del> <del> <del># class LazyStringsTestCase(TestCase): <del># def setUp(self): <del># self.model = LazyStringModel(lazystring=_('lazystring')) <del> <del># def test_lazy_strings_are_translated(self): <del># serializer = LazyStringSerializer(self.model) <del># self.assertEqual(type(serializer.data['lazystring']), <del># type('lazystring')) <del> <del> <del># # Test for issue #467 <del> <del># class FieldLabelTest(TestCase): <del># def setUp(self): <del># self.serializer_class = BasicModelSerializer <del> <del># def test_label_from_model(self): <del># """ <del># Validates that label and help_text are correctly copied from the model class. <del># """ <del># serializer = self.serializer_class() <del># text_field = serializer.fields['text'] <del> <del># self.assertEqual('Text comes here', text_field.label) <del># self.assertEqual('Text description.', text_field.help_text) <del> <del># def test_field_ctor(self): <del># """ <del># This is check that ctor supports both label and help_text. <del># """ <del># self.assertEqual('Label', fields.Field(label='Label', help_text='Help').label) <del># self.assertEqual('Help', fields.CharField(label='Label', help_text='Help').help_text) <del># self.assertEqual('Label', relations.HyperlinkedRelatedField(view_name='fake', label='Label', help_text='Help', many=True).label) <del> <del> <del># # Test for issue #961 <del> <del># class ManyFieldHelpTextTest(TestCase): <del># def test_help_text_no_hold_down_control_msg(self): <del># """ <del># Validate that help_text doesn't contain the 'Hold down "Control" ...' <del># message that Django appends to choice fields. <del># """ <del># rel_field = fields.Field(help_text=ManyToManyModel._meta.get_field('rel').help_text) <del># self.assertEqual('Some help text.', rel_field.help_text) <del> <del> <del># class AttributeMappingOnAutogeneratedRelatedFields(TestCase): <del> <del># def test_primary_key_related_field(self): <del># serializer = ForeignKeySourceSerializer() <del># self.assertEqual(serializer.fields['target'].help_text, 'Target') <del># self.assertEqual(serializer.fields['target'].label, 'Target') <del> <del># def test_hyperlinked_related_field(self): <del># serializer = HyperlinkedForeignKeySourceSerializer() <del># self.assertEqual(serializer.fields['target'].help_text, 'Target') <del># self.assertEqual(serializer.fields['target'].label, 'Target') <del> <del> <del># @unittest.skipUnless(PIL is not None, 'PIL is not installed') <del># class AttributeMappingOnAutogeneratedFieldsTests(TestCase): <del> <del># def setUp(self): <del> <del># class AMOAFSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = AMOAFModel <del> <del># self.serializer_class = AMOAFSerializer <del># self.fields_attributes = { <del># 'char_field': [ <del># ('max_length', 1024), <del># ], <del># 'comma_separated_integer_field': [ <del># ('max_length', 1024), <del># ], <del># 'decimal_field': [ <del># ('max_digits', 64), <del># ('decimal_places', 32), <del># ], <del># 'email_field': [ <del># ('max_length', 1024), <del># ], <del># 'file_field': [ <del># ('max_length', 1024), <del># ], <del># 'image_field': [ <del># ('max_length', 1024), <del># ], <del># 'slug_field': [ <del># ('max_length', 1024), <del># ], <del># 'url_field': [ <del># ('max_length', 1024), <del># ], <del># 'nullable_char_field': [ <del># ('max_length', 1024), <del># ('allow_none', True), <del># ], <del># } <del> <del># def field_test(self, field): <del># serializer = self.serializer_class(data={}) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># for attribute in self.fields_attributes[field]: <del># self.assertEqual( <del># getattr(serializer.fields[field], attribute[0]), <del># attribute[1] <del># ) <del> <del># def test_char_field(self): <del># self.field_test('char_field') <del> <del># def test_comma_separated_integer_field(self): <del># self.field_test('comma_separated_integer_field') <del> <del># def test_decimal_field(self): <del># self.field_test('decimal_field') <del> <del># def test_email_field(self): <del># self.field_test('email_field') <del> <del># def test_file_field(self): <del># self.field_test('file_field') <del> <del># def test_image_field(self): <del># self.field_test('image_field') <del> <del># def test_slug_field(self): <del># self.field_test('slug_field') <del> <del># def test_url_field(self): <del># self.field_test('url_field') <del> <del># def test_nullable_char_field(self): <del># self.field_test('nullable_char_field') <del> <del> <del># @unittest.skipUnless(PIL is not None, 'PIL is not installed') <del># class DefaultValuesOnAutogeneratedFieldsTests(TestCase): <del> <del># def setUp(self): <del> <del># class DVOAFSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = DVOAFModel <del> <del># self.serializer_class = DVOAFSerializer <del># self.fields_attributes = { <del># 'positive_integer_field': [ <del># ('min_value', 0), <del># ], <del># 'positive_small_integer_field': [ <del># ('min_value', 0), <del># ], <del># 'email_field': [ <del># ('max_length', 75), <del># ], <del># 'file_field': [ <del># ('max_length', 100), <del># ], <del># 'image_field': [ <del># ('max_length', 100), <del># ], <del># 'slug_field': [ <del># ('max_length', 50), <del># ], <del># 'url_field': [ <del># ('max_length', 200), <del># ], <del># } <del> <del># def field_test(self, field): <del># serializer = self.serializer_class(data={}) <del># self.assertEqual(serializer.is_valid(), True) <del> <del># for attribute in self.fields_attributes[field]: <del># self.assertEqual( <del># getattr(serializer.fields[field], attribute[0]), <del># attribute[1] <del># ) <del> <del># def test_positive_integer_field(self): <del># self.field_test('positive_integer_field') <del> <del># def test_positive_small_integer_field(self): <del># self.field_test('positive_small_integer_field') <del> <del># def test_email_field(self): <del># self.field_test('email_field') <del> <del># def test_file_field(self): <del># self.field_test('file_field') <del> <del># def test_image_field(self): <del># self.field_test('image_field') <del> <del># def test_slug_field(self): <del># self.field_test('slug_field') <del> <del># def test_url_field(self): <del># self.field_test('url_field') <del> <del> <del># class MetadataSerializer(serializers.Serializer): <del># field1 = serializers.CharField(max_length=3, required=True) <del># field2 = serializers.CharField(max_length=10, required=False) <del> <del> <del># class MetadataSerializerTestCase(TestCase): <del># def setUp(self): <del># self.serializer = MetadataSerializer() <del> <del># def test_serializer_metadata(self): <del># metadata = self.serializer.metadata() <del># expected = { <del># 'field1': { <del># 'required': True, <del># 'max_length': 3, <del># 'type': 'string', <del># 'read_only': False <del># }, <del># 'field2': { <del># 'required': False, <del># 'max_length': 10, <del># 'type': 'string', <del># 'read_only': False <del># } <del># } <del># self.assertEqual(expected, metadata) <del> <del> <del># # Regression test for #840 <del> <del># class SimpleModel(models.Model): <del># text = models.CharField(max_length=100) <del> <del> <del># class SimpleModelSerializer(serializers.ModelSerializer): <del># text = serializers.CharField() <del># other = serializers.CharField() <del> <del># class Meta: <del># model = SimpleModel <del> <del># def validate_other(self, attrs, source): <del># del attrs['other'] <del># return attrs <del> <del> <del># class FieldValidationRemovingAttr(TestCase): <del># def test_removing_non_model_field_in_validation(self): <del># """ <del># Removing an attr during field valiation should ensure that it is not <del># passed through when restoring the object. <del> <del># This allows additional non-model fields to be supported. <del> <del># Regression test for #840. <del># """ <del># serializer = SimpleModelSerializer(data={'text': 'foo', 'other': 'bar'}) <del># self.assertTrue(serializer.is_valid()) <del># serializer.save() <del># self.assertEqual(serializer.object.text, 'foo') <del> <del> <del># # Regression test for #878 <del> <del># class SimpleTargetModel(models.Model): <del># text = models.CharField(max_length=100) <del> <del> <del># class SimplePKSourceModelSerializer(serializers.Serializer): <del># targets = serializers.PrimaryKeyRelatedField(queryset=SimpleTargetModel.objects.all(), many=True) <del># text = serializers.CharField() <del> <del> <del># class SimpleSlugSourceModelSerializer(serializers.Serializer): <del># targets = serializers.SlugRelatedField(queryset=SimpleTargetModel.objects.all(), many=True, slug_field='pk') <del># text = serializers.CharField() <del> <del> <del># class SerializerSupportsManyRelationships(TestCase): <del># def setUp(self): <del># SimpleTargetModel.objects.create(text='foo') <del># SimpleTargetModel.objects.create(text='bar') <del> <del># def test_serializer_supports_pk_many_relationships(self): <del># """ <del># Regression test for #878. <del> <del># Note that pk behavior has a different code path to usual cases, <del># for performance reasons. <del># """ <del># serializer = SimplePKSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) <del># self.assertTrue(serializer.is_valid()) <del># self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) <del> <del># def test_serializer_supports_slug_many_relationships(self): <del># """ <del># Regression test for #878. <del># """ <del># serializer = SimpleSlugSourceModelSerializer(data={'text': 'foo', 'targets': [1, 2]}) <del># self.assertTrue(serializer.is_valid()) <del># self.assertEqual(serializer.data, {'text': 'foo', 'targets': [1, 2]}) <del> <del> <del># class TransformMethodsSerializer(serializers.Serializer): <del># a = serializers.CharField() <del># b_renamed = serializers.CharField(source='b') <del> <del># def transform_a(self, obj, value): <del># return value.lower() <del> <del># def transform_b_renamed(self, obj, value): <del># if value is not None: <del># return 'and ' + value <del> <del> <del># class TestSerializerTransformMethods(TestCase): <del># def setUp(self): <del># self.s = TransformMethodsSerializer() <del> <del># def test_transform_methods(self): <del># self.assertEqual( <del># self.s.to_native({'a': 'GREEN EGGS', 'b': 'HAM'}), <del># { <del># 'a': 'green eggs', <del># 'b_renamed': 'and HAM', <del># } <del># ) <del> <del># def test_missing_fields(self): <del># self.assertEqual( <del># self.s.to_native({'a': 'GREEN EGGS'}), <del># { <del># 'a': 'green eggs', <del># 'b_renamed': None, <del># } <del># ) <del> <del> <del># class DefaultTrueBooleanModel(models.Model): <del># cat = models.BooleanField(default=True) <del># dog = models.BooleanField(default=False) <del> <del> <del># class SerializerDefaultTrueBoolean(TestCase): <del> <del># def setUp(self): <del># super(SerializerDefaultTrueBoolean, self).setUp() <del> <del># class DefaultTrueBooleanSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = DefaultTrueBooleanModel <del># fields = ('cat', 'dog') <del> <del># self.default_true_boolean_serializer = DefaultTrueBooleanSerializer <del> <del># def test_enabled_as_false(self): <del># serializer = self.default_true_boolean_serializer(data={'cat': False, <del># 'dog': False}) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.data['cat'], False) <del># self.assertEqual(serializer.data['dog'], False) <del> <del># def test_enabled_as_true(self): <del># serializer = self.default_true_boolean_serializer(data={'cat': True, <del># 'dog': True}) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.data['cat'], True) <del># self.assertEqual(serializer.data['dog'], True) <del> <del># def test_enabled_partial(self): <del># serializer = self.default_true_boolean_serializer(data={'cat': False}, <del># partial=True) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.data['cat'], False) <del># self.assertEqual(serializer.data['dog'], False) <del> <del> <del># class BoolenFieldTypeTest(TestCase): <del># ''' <del># Ensure the various Boolean based model fields are rendered as the proper <del># field type <del> <del># ''' <del> <del># def setUp(self): <del># ''' <del># Setup an ActionItemSerializer for BooleanTesting <del># ''' <del># data = { <del># 'title': 'b' * 201, <del># } <del># self.serializer = ActionItemSerializer(data=data) <del> <del># def test_booleanfield_type(self): <del># ''' <del># Test that BooleanField is infered from models.BooleanField <del># ''' <del># bfield = self.serializer.get_fields()['done'] <del># self.assertEqual(type(bfield), fields.BooleanField) <del> <del># def test_nullbooleanfield_type(self): <del># ''' <del># Test that BooleanField is infered from models.NullBooleanField <del> <del># https://groups.google.com/forum/#!topic/django-rest-framework/D9mXEftpuQ8 <del># ''' <del># bfield = self.serializer.get_fields()['started'] <del># self.assertEqual(type(bfield), fields.BooleanField) <ide><path>tests/test_serializer_bulk_update.py <ide> def test_invalid_single_object(self): <ide> expected_errors = {'non_field_errors': ['Expected a list of items but got type `dict`.']} <ide> <ide> self.assertEqual(serializer.errors, expected_errors) <del> <del> <del># class BulkUpdateSerializerTests(TestCase): <del># """ <del># Updating multiple instances using serializers. <del># """ <del> <del># def setUp(self): <del># class Book(object): <del># """ <del># A data type that can be persisted to a mock storage backend <del># with `.save()` and `.delete()`. <del># """ <del># object_map = {} <del> <del># def __init__(self, id, title, author): <del># self.id = id <del># self.title = title <del># self.author = author <del> <del># def save(self): <del># Book.object_map[self.id] = self <del> <del># def delete(self): <del># del Book.object_map[self.id] <del> <del># class BookSerializer(serializers.Serializer): <del># id = serializers.IntegerField() <del># title = serializers.CharField(max_length=100) <del># author = serializers.CharField(max_length=100) <del> <del># def restore_object(self, attrs, instance=None): <del># if instance: <del># instance.id = attrs['id'] <del># instance.title = attrs['title'] <del># instance.author = attrs['author'] <del># return instance <del># return Book(**attrs) <del> <del># self.Book = Book <del># self.BookSerializer = BookSerializer <del> <del># data = [ <del># { <del># 'id': 0, <del># 'title': 'The electric kool-aid acid test', <del># 'author': 'Tom Wolfe' <del># }, { <del># 'id': 1, <del># 'title': 'If this is a man', <del># 'author': 'Primo Levi' <del># }, { <del># 'id': 2, <del># 'title': 'The wind-up bird chronicle', <del># 'author': 'Haruki Murakami' <del># } <del># ] <del> <del># for item in data: <del># book = Book(item['id'], item['title'], item['author']) <del># book.save() <del> <del># def books(self): <del># """ <del># Return all the objects in the mock storage backend. <del># """ <del># return self.Book.object_map.values() <del> <del># def test_bulk_update_success(self): <del># """ <del># Correct bulk update serialization should return the input data. <del># """ <del># data = [ <del># { <del># 'id': 0, <del># 'title': 'The electric kool-aid acid test', <del># 'author': 'Tom Wolfe' <del># }, { <del># 'id': 2, <del># 'title': 'Kafka on the shore', <del># 'author': 'Haruki Murakami' <del># } <del># ] <del># serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.data, data) <del># serializer.save() <del># new_data = self.BookSerializer(self.books(), many=True).data <del> <del># self.assertEqual(data, new_data) <del> <del># def test_bulk_update_and_create(self): <del># """ <del># Bulk update serialization may also include created items. <del># """ <del># data = [ <del># { <del># 'id': 0, <del># 'title': 'The electric kool-aid acid test', <del># 'author': 'Tom Wolfe' <del># }, { <del># 'id': 3, <del># 'title': 'Kafka on the shore', <del># 'author': 'Haruki Murakami' <del># } <del># ] <del># serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.data, data) <del># serializer.save() <del># new_data = self.BookSerializer(self.books(), many=True).data <del># self.assertEqual(data, new_data) <del> <del># def test_bulk_update_invalid_create(self): <del># """ <del># Bulk update serialization without allow_add_remove may not create items. <del># """ <del># data = [ <del># { <del># 'id': 0, <del># 'title': 'The electric kool-aid acid test', <del># 'author': 'Tom Wolfe' <del># }, { <del># 'id': 3, <del># 'title': 'Kafka on the shore', <del># 'author': 'Haruki Murakami' <del># } <del># ] <del># expected_errors = [ <del># {}, <del># {'non_field_errors': ['Cannot create a new item, only existing items may be updated.']} <del># ] <del># serializer = self.BookSerializer(self.books(), data=data, many=True) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, expected_errors) <del> <del># def test_bulk_update_error(self): <del># """ <del># Incorrect bulk update serialization should return error data. <del># """ <del># data = [ <del># { <del># 'id': 0, <del># 'title': 'The electric kool-aid acid test', <del># 'author': 'Tom Wolfe' <del># }, { <del># 'id': 'foo', <del># 'title': 'Kafka on the shore', <del># 'author': 'Haruki Murakami' <del># } <del># ] <del># expected_errors = [ <del># {}, <del># {'id': ['Enter a whole number.']} <del># ] <del># serializer = self.BookSerializer(self.books(), data=data, many=True, allow_add_remove=True) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, expected_errors) <ide><path>tests/test_serializer_empty.py <del># from django.test import TestCase <del># from rest_framework import serializers <del> <del> <del># class EmptySerializerTestCase(TestCase): <del># def test_empty_serializer(self): <del># class FooBarSerializer(serializers.Serializer): <del># foo = serializers.IntegerField() <del># bar = serializers.SerializerMethodField() <del> <del># def get_bar(self, obj): <del># return 'bar' <del> <del># serializer = FooBarSerializer() <del># self.assertEquals(serializer.data, {'foo': 0}) <ide><path>tests/test_serializer_nested.py <ide> def test_nested_serialize_empty(self): <ide> } <ide> serializer = self.Serializer() <ide> assert serializer.data == expected_data <del> <del># """ <del># Tests to cover nested serializers. <del> <del># Doesn't cover model serializers. <del># """ <del># from __future__ import unicode_literals <del># from django.test import TestCase <del># from rest_framework import serializers <del># from . import models <del> <del> <del># class WritableNestedSerializerBasicTests(TestCase): <del># """ <del># Tests for deserializing nested entities. <del># Basic tests that use serializers that simply restore to dicts. <del># """ <del> <del># def setUp(self): <del># class TrackSerializer(serializers.Serializer): <del># order = serializers.IntegerField() <del># title = serializers.CharField(max_length=100) <del># duration = serializers.IntegerField() <del> <del># class AlbumSerializer(serializers.Serializer): <del># album_name = serializers.CharField(max_length=100) <del># artist = serializers.CharField(max_length=100) <del># tracks = TrackSerializer(many=True) <del> <del># self.AlbumSerializer = AlbumSerializer <del> <del># def test_nested_validation_success(self): <del># """ <del># Correct nested serialization should return the input data. <del># """ <del> <del># data = { <del># 'album_name': 'Discovery', <del># 'artist': 'Daft Punk', <del># 'tracks': [ <del># {'order': 1, 'title': 'One More Time', 'duration': 235}, <del># {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, <del># {'order': 3, 'title': 'Digital Love', 'duration': 239} <del># ] <del># } <del> <del># serializer = self.AlbumSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, data) <del> <del># def test_nested_validation_error(self): <del># """ <del># Incorrect nested serialization should return appropriate error data. <del># """ <del> <del># data = { <del># 'album_name': 'Discovery', <del># 'artist': 'Daft Punk', <del># 'tracks': [ <del># {'order': 1, 'title': 'One More Time', 'duration': 235}, <del># {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, <del># {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'} <del># ] <del># } <del># expected_errors = { <del># 'tracks': [ <del># {}, <del># {}, <del># {'duration': ['Enter a whole number.']} <del># ] <del># } <del> <del># serializer = self.AlbumSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, expected_errors) <del> <del># def test_many_nested_validation_error(self): <del># """ <del># Incorrect nested serialization should return appropriate error data <del># when multiple entities are being deserialized. <del># """ <del> <del># data = [ <del># { <del># 'album_name': 'Russian Red', <del># 'artist': 'I Love Your Glasses', <del># 'tracks': [ <del># {'order': 1, 'title': 'Cigarettes', 'duration': 121}, <del># {'order': 2, 'title': 'No Past Land', 'duration': 198}, <del># {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191} <del># ] <del># }, <del># { <del># 'album_name': 'Discovery', <del># 'artist': 'Daft Punk', <del># 'tracks': [ <del># {'order': 1, 'title': 'One More Time', 'duration': 235}, <del># {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, <del># {'order': 3, 'title': 'Digital Love', 'duration': 'foobar'} <del># ] <del># } <del># ] <del># expected_errors = [ <del># {}, <del># { <del># 'tracks': [ <del># {}, <del># {}, <del># {'duration': ['Enter a whole number.']} <del># ] <del># } <del># ] <del> <del># serializer = self.AlbumSerializer(data=data, many=True) <del># self.assertEqual(serializer.is_valid(), False) <del># self.assertEqual(serializer.errors, expected_errors) <del> <del> <del># class WritableNestedSerializerObjectTests(TestCase): <del># """ <del># Tests for deserializing nested entities. <del># These tests use serializers that restore to concrete objects. <del># """ <del> <del># def setUp(self): <del># # Couple of concrete objects that we're going to deserialize into <del># class Track(object): <del># def __init__(self, order, title, duration): <del># self.order, self.title, self.duration = order, title, duration <del> <del># def __eq__(self, other): <del># return ( <del># self.order == other.order and <del># self.title == other.title and <del># self.duration == other.duration <del># ) <del> <del># class Album(object): <del># def __init__(self, album_name, artist, tracks): <del># self.album_name, self.artist, self.tracks = album_name, artist, tracks <del> <del># def __eq__(self, other): <del># return ( <del># self.album_name == other.album_name and <del># self.artist == other.artist and <del># self.tracks == other.tracks <del># ) <del> <del># # And their corresponding serializers <del># class TrackSerializer(serializers.Serializer): <del># order = serializers.IntegerField() <del># title = serializers.CharField(max_length=100) <del># duration = serializers.IntegerField() <del> <del># def restore_object(self, attrs, instance=None): <del># return Track(attrs['order'], attrs['title'], attrs['duration']) <del> <del># class AlbumSerializer(serializers.Serializer): <del># album_name = serializers.CharField(max_length=100) <del># artist = serializers.CharField(max_length=100) <del># tracks = TrackSerializer(many=True) <del> <del># def restore_object(self, attrs, instance=None): <del># return Album(attrs['album_name'], attrs['artist'], attrs['tracks']) <del> <del># self.Album, self.Track = Album, Track <del># self.AlbumSerializer = AlbumSerializer <del> <del># def test_nested_validation_success(self): <del># """ <del># Correct nested serialization should return a restored object <del># that corresponds to the input data. <del># """ <del> <del># data = { <del># 'album_name': 'Discovery', <del># 'artist': 'Daft Punk', <del># 'tracks': [ <del># {'order': 1, 'title': 'One More Time', 'duration': 235}, <del># {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, <del># {'order': 3, 'title': 'Digital Love', 'duration': 239} <del># ] <del># } <del># expected_object = self.Album( <del># album_name='Discovery', <del># artist='Daft Punk', <del># tracks=[ <del># self.Track(order=1, title='One More Time', duration=235), <del># self.Track(order=2, title='Aerodynamic', duration=184), <del># self.Track(order=3, title='Digital Love', duration=239), <del># ] <del># ) <del> <del># serializer = self.AlbumSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected_object) <del> <del># def test_many_nested_validation_success(self): <del># """ <del># Correct nested serialization should return multiple restored objects <del># that corresponds to the input data when multiple objects are <del># being deserialized. <del># """ <del> <del># data = [ <del># { <del># 'album_name': 'Russian Red', <del># 'artist': 'I Love Your Glasses', <del># 'tracks': [ <del># {'order': 1, 'title': 'Cigarettes', 'duration': 121}, <del># {'order': 2, 'title': 'No Past Land', 'duration': 198}, <del># {'order': 3, 'title': 'They Don\'t Believe', 'duration': 191} <del># ] <del># }, <del># { <del># 'album_name': 'Discovery', <del># 'artist': 'Daft Punk', <del># 'tracks': [ <del># {'order': 1, 'title': 'One More Time', 'duration': 235}, <del># {'order': 2, 'title': 'Aerodynamic', 'duration': 184}, <del># {'order': 3, 'title': 'Digital Love', 'duration': 239} <del># ] <del># } <del># ] <del># expected_object = [ <del># self.Album( <del># album_name='Russian Red', <del># artist='I Love Your Glasses', <del># tracks=[ <del># self.Track(order=1, title='Cigarettes', duration=121), <del># self.Track(order=2, title='No Past Land', duration=198), <del># self.Track(order=3, title='They Don\'t Believe', duration=191), <del># ] <del># ), <del># self.Album( <del># album_name='Discovery', <del># artist='Daft Punk', <del># tracks=[ <del># self.Track(order=1, title='One More Time', duration=235), <del># self.Track(order=2, title='Aerodynamic', duration=184), <del># self.Track(order=3, title='Digital Love', duration=239), <del># ] <del># ) <del># ] <del> <del># serializer = self.AlbumSerializer(data=data, many=True) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected_object) <del> <del> <del># class ForeignKeyNestedSerializerUpdateTests(TestCase): <del># def setUp(self): <del># class Artist(object): <del># def __init__(self, name): <del># self.name = name <del> <del># def __eq__(self, other): <del># return self.name == other.name <del> <del># class Album(object): <del># def __init__(self, name, artist): <del># self.name, self.artist = name, artist <del> <del># def __eq__(self, other): <del># return self.name == other.name and self.artist == other.artist <del> <del># class ArtistSerializer(serializers.Serializer): <del># name = serializers.CharField() <del> <del># def restore_object(self, attrs, instance=None): <del># if instance: <del># instance.name = attrs['name'] <del># else: <del># instance = Artist(attrs['name']) <del># return instance <del> <del># class AlbumSerializer(serializers.Serializer): <del># name = serializers.CharField() <del># by = ArtistSerializer(source='artist') <del> <del># def restore_object(self, attrs, instance=None): <del># if instance: <del># instance.name = attrs['name'] <del># instance.artist = attrs['artist'] <del># else: <del># instance = Album(attrs['name'], attrs['artist']) <del># return instance <del> <del># self.Artist = Artist <del># self.Album = Album <del># self.AlbumSerializer = AlbumSerializer <del> <del># def test_create_via_foreign_key_with_source(self): <del># """ <del># Check that we can both *create* and *update* into objects across <del># ForeignKeys that have a `source` specified. <del># Regression test for #1170 <del># """ <del># data = { <del># 'name': 'Discovery', <del># 'by': {'name': 'Daft Punk'}, <del># } <del> <del># expected = self.Album(artist=self.Artist('Daft Punk'), name='Discovery') <del> <del># # create <del># serializer = self.AlbumSerializer(data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected) <del> <del># # update <del># original = self.Album(artist=self.Artist('The Bats'), name='Free All the Monsters') <del># serializer = self.AlbumSerializer(instance=original, data=data) <del># self.assertEqual(serializer.is_valid(), True) <del># self.assertEqual(serializer.object, expected) <del> <del> <del># class NestedModelSerializerUpdateTests(TestCase): <del># def test_second_nested_level(self): <del># john = models.Person.objects.create(name="john") <del> <del># post = john.blogpost_set.create(title="Test blog post") <del># post.blogpostcomment_set.create(text="I hate this blog post") <del># post.blogpostcomment_set.create(text="I love this blog post") <del> <del># class BlogPostCommentSerializer(serializers.ModelSerializer): <del># class Meta: <del># model = models.BlogPostComment <del> <del># class BlogPostSerializer(serializers.ModelSerializer): <del># comments = BlogPostCommentSerializer(many=True, source='blogpostcomment_set') <del> <del># class Meta: <del># model = models.BlogPost <del># fields = ('id', 'title', 'comments') <del> <del># class PersonSerializer(serializers.ModelSerializer): <del># posts = BlogPostSerializer(many=True, source='blogpost_set') <del> <del># class Meta: <del># model = models.Person <del># fields = ('id', 'name', 'age', 'posts') <del> <del># serialize = PersonSerializer(instance=john) <del># deserialize = PersonSerializer(data=serialize.data, instance=john) <del># self.assertTrue(deserialize.is_valid()) <del> <del># result = deserialize.object <del># result.save() <del># self.assertEqual(result.id, john.id) <ide><path>tests/test_validation.py <ide> def test_choices(self): <ide> except serializers.ValidationError: <ide> self.fail("Value %s does not validate" % str(value)) <ide> <del> # def test_nested_choices(self): <del> # """ <del> # Make sure a nested value for choices works as expected. <del> # """ <del> # f = serializers.ChoiceField(choices=self.CHOICES_NESTED) <del> # value = self.CHOICES_NESTED[0][1][0][0] <del> # try: <del> # f.to_native(value) <del> # except ValidationError: <del> # self.fail("Value %s does not validate" % str(value)) <del> <ide> <ide> class RegexSerializer(serializers.Serializer): <ide> pin = serializers.CharField(
13
PHP
PHP
remove extra spaces
7ccba640d4fbb1bc9e3d7335c3e8405fc435b0d5
<ide><path>src/Illuminate/Pagination/Paginator.php <ide> class Paginator implements ArrayAccess, Countable, IteratorAggregate { <ide> */ <ide> public function __construct(Environment $env, array $items, $total, $perPage) <ide> { <del> $this->env = $env; <del> $this->total = $total; <del> $this->items = $items; <add> $this->env = $env; <add> $this->total = $total; <add> $this->items = $items; <ide> $this->perPage = $perPage; <ide> } <ide>
1
PHP
PHP
add multiple_of custom replacer
11d747064030963c906412012ac8f6581711022e
<ide><path>src/Illuminate/Validation/Concerns/ReplacesAttributes.php <ide> protected function replaceMax($message, $attribute, $rule, $parameters) <ide> return str_replace(':max', $parameters[0], $message); <ide> } <ide> <add> /** <add> * Replace all place-holders for the multiple_of rule. <add> * <add> * @param string $message <add> * @param string $attribute <add> * @param string $rule <add> * @param array $parameters <add> * @return string <add> */ <add> protected function replaceMultipleOf($message, $attribute, $rule, $parameters) <add> { <add> return str_replace(':value', $parameters[0], $message); <add> } <add> <ide> /** <ide> * Replace all place-holders for the in rule. <ide> * <ide><path>tests/Validation/ValidationValidatorTest.php <ide> public function testValidateMax() <ide> public function testValidateMutlpleOf($input, $allowed, $passes) <ide> { <ide> $trans = $this->getIlluminateArrayTranslator(); <add> $trans->addLines(['validation.multiple_of' => 'The :attribute must be a multiple of :value'], 'en'); <ide> <ide> $v = new Validator($trans, ['foo' => $input], ['foo' => "multiple_of:{$allowed}"]); <add> <ide> $this->assertSame($passes, $v->passes()); <add> if ($v->fails()) { <add> $this->assertSame("The foo must be a multiple of {$allowed}", $v->messages()->first('foo')); <add> } else { <add> $this->assertSame('', $v->messages()->first('foo')); <add> } <ide> } <ide> <ide> public function multipleOfDataProvider() <ide> public function multipleOfDataProvider() <ide> ['foo', 1, false], // invalid values <ide> [1, 'foo', false], <ide> ['foo', 'foo', false], <add> [1, '', false], <add> [1, null, false], <ide> ]; <ide> } <ide>
2
Ruby
Ruby
reverse tag/digest for new bottles
fc1c142ebd0e7d0c1ab308c11c52ab33ce204054
<ide><path>Library/Homebrew/software_spec.rb <ide> def tag?(tag) <ide> # a Hash, which indicates the platform the checksum applies on. <ide> # Example bottle block syntax: <ide> # bottle do <del> # sha256 "69489ae397e4645..." => :big_sur, :cellar => :any_skip_relocation <del> # sha256 "449de5ea35d0e94..." => :catalina, :cellar => :any <add> # sha256 cellar: :any_skip_relocation, big_sur: "69489ae397e4645..." <add> # sha256 cellar: :any, catalina: "449de5ea35d0e94..." <ide> # end <del> # Example args: <del> # {"69489ae397e4645..."=> :big_sur, :cellar=>:any_skip_relocation} <ide> def sha256(hash) <ide> sha256_regex = /^[a-f0-9]{64}$/i <del> digest, tag = hash.find do |key, value| <del> key.is_a?(String) && value.is_a?(Symbol) && key.match?(sha256_regex) <add> <add> # find new `sha256 big_sur: "69489ae397e4645..."` format <add> tag, digest = hash.find do |key, value| <add> key.is_a?(Symbol) && value.is_a?(String) && value.match?(sha256_regex) <add> end <add> <add> if digest && tag <add> # the cellar hash key only exists on the new format <add> cellar = hash[:cellar] <add> else <add> # otherwise, find old `sha256 "69489ae397e4645..." => :big_sur` format <add> digest, tag = hash.find do |key, value| <add> key.is_a?(String) && value.is_a?(Symbol) && key.match?(sha256_regex) <add> end <ide> end <del> cellar = hash[:cellar] || all_tags_cellar <add> <add> cellar ||= all_tags_cellar <ide> collector[tag] = { checksum: Checksum.new(digest), cellar: cellar } <ide> end <ide> <ide><path>Library/Homebrew/test/software_spec_spec.rb <ide> <ide> it "works with cellar" do <ide> checksums = [ <del> { digest: "deadbeef" * 8, tag: :snow_leopard_32, cellar: :any_skip_relocation }, <del> { digest: "faceb00c" * 8, tag: :snow_leopard, cellar: :any }, <del> { digest: "baadf00d" * 8, tag: :lion, cellar: "/usr/local/Cellar" }, <del> { digest: "8badf00d" * 8, tag: :mountain_lion, cellar: Homebrew::DEFAULT_CELLAR }, <add> { cellar: :any_skip_relocation, tag: :snow_leopard_32, digest: "deadbeef" * 8 }, <add> { cellar: :any, tag: :snow_leopard, digest: "faceb00c" * 8 }, <add> { cellar: "/usr/local/Cellar", tag: :lion, digest: "baadf00d" * 8 }, <add> { cellar: Homebrew::DEFAULT_CELLAR, tag: :mountain_lion, digest: "8badf00d" * 8 }, <ide> ] <ide> <ide> checksums.each do |checksum| <del> subject.sha256(checksum[:digest] => checksum[:tag], cellar: checksum[:cellar]) <add> subject.sha256(checksum[:tag] => checksum[:digest], cellar: checksum[:cellar]) <ide> digest, tag, cellar = subject.checksum_for(checksum[:tag]) <ide> expect(Checksum.new(checksum[:digest])).to eq(digest) <ide> expect(checksum[:tag]).to eq(tag) <ide><path>Library/Homebrew/test/support/fixtures/testball_bottle_cellar.rb <ide> def initialize(name = "testball_bottle", path = Pathname.new(__FILE__).expand_pa <ide> hexdigest = "8f9aecd233463da6a4ea55f5f88fc5841718c013f3e2a7941350d6130f1dc149" <ide> stable.bottle do <ide> root_url "file://#{TEST_FIXTURE_DIR}/bottles" <del> sha256 hexdigest => Utils::Bottles.tag, :cellar => :any_skip_relocation <add> sha256 cellar: :any_skip_relocation, Utils::Bottles.tag => hexdigest <ide> end <ide> cxxstdlib_check :skip <ide> end
3
Text
Text
add a pointer to a colab for the embeddings
60d6808b4cf1c728ad8ec10d7a2793c62d94c120
<ide><path>research/audioset/README.md <ide> the postprocessor can be run after inference. <ide> If you don't need to use the released embeddings or YouTube-8M, then you could <ide> skip postprocessing and use raw embeddings. <ide> <add>A [Colab](https://colab.research.google.com/) <add>showing how to download the model and calculate the embeddings on your <add>own sound data is available here: <add>[AudioSet Embedding Colab](https://colab.research.google.com/drive/1TbX92UL9sYWbdwdGE0rJ9owmezB-Rl1C). <add> <ide> ### Future Work <ide> <ide> Below are some of the things we would like to add to this repository. We
1
Javascript
Javascript
export the hmr plugin directly
cf1569c556d28779edbba92edb658a881a68516c
<ide><path>babel-preset/configs/hmr.js <ide> module.exports = function(options, filename) { <ide> return { <ide> plugins: [ <ide> [ <del> require('metro-babel7-plugin-react-transform').default, <add> require('metro-babel7-plugin-react-transform'), <ide> { <ide> transforms: [{ <ide> transform: transform,
1
PHP
PHP
make migration opt-in with shortcut
cfba00f2dee92bbba9343004d3d1e8aa0a3e269e
<ide><path>src/Illuminate/Foundation/Console/ModelMakeCommand.php <ide> public function fire() <ide> { <ide> parent::fire(); <ide> <del> if ( ! $this->option('no-migration')) <add> if ($this->option('migration')) <ide> { <ide> $table = str_plural(snake_case(class_basename($this->argument('name')))); <ide> <ide> protected function getDefaultNamespace($rootNamespace) <ide> protected function getOptions() <ide> { <ide> return array( <del> array('no-migration', null, InputOption::VALUE_NONE, 'Do not create a new migration file.'), <add> array('migration', 'm', InputOption::VALUE_NONE, 'Create a new migration file for the model.'), <ide> ); <ide> } <ide>
1
Javascript
Javascript
remove remaining obsolete jquery.cache references
d96111e18b42ae1bc7def72a8a0d156ea39e4d0e
<ide><path>test/data/testrunner.js <ide> <ide> "use strict"; <ide> <del>// Store the old counts so that we only assert on tests that have actually leaked, <add>// Store the old count so that we only assert on tests that have actually leaked, <ide> // instead of asserting every time a test has leaked sometime in the past <del>var oldCacheLength = 0, <del> oldActive = 0, <add>var oldActive = 0, <ide> <del> expectedDataKeys = {}, <ide> splice = [].splice, <ide> ajaxSettings = jQuery.ajaxSettings; <ide> <ide> QUnit.config.requireExpects = true; <ide> * teardown function on all modules' lifecycle object. <ide> */ <ide> window.moduleTeardown = function( assert ) { <del> var i, expectedKeys, actualKeys, <del> cacheLength = 0; <del> <del> // Reset data register <del> expectedDataKeys = {}; <ide> <ide> // Check for (and clean up, if possible) incomplete animations/requests/etc. <ide> if ( jQuery.timers && jQuery.timers.length !== 0 ) { <ide> window.moduleTeardown = function( assert ) { <ide> } <ide> <ide> Globals.cleanup(); <del> <del> for ( i in jQuery.cache ) { <del> ++cacheLength; <del> } <del> <del> // Because QUnit doesn't have a mechanism for retrieving <del> // the number of expected assertions for a test, <del> // if we unconditionally assert any of these, <del> // the test will fail with too many assertions :| <del> if ( cacheLength !== oldCacheLength ) { <del> assert.equal( cacheLength, oldCacheLength, "No unit tests leak memory in jQuery.cache" ); <del> oldCacheLength = cacheLength; <del> } <ide> }; <ide> <ide> QUnit.done( function() { <ide><path>test/unit/wrap.js <ide> function manipulationFunctionReturningObj( value ) { <ide> <ide> function testWrap( val, assert ) { <ide> <del> assert.expect( 19 ); <add> assert.expect( 18 ); <ide> <ide> var defaultText, result, j, i, cacheLength; <ide> <ide> function testWrap( val, assert ) { <ide> "Check node,textnode,comment wraps doesn't hurt text" <ide> ); <ide> <del> // Try wrapping a disconnected node <del> cacheLength = 0; <del> for ( i in jQuery.cache ) { <del> cacheLength++; <del> } <del> <ide> j = jQuery( "<label></label>" ).wrap( val( "<li></li>" ) ); <ide> assert.equal( <ide> j[ 0 ] .nodeName.toUpperCase(), "LABEL", "Element is a label" <ide> function testWrap( val, assert ) { <ide> j[ 0 ].parentNode.nodeName.toUpperCase(), "LI", "Element has been wrapped" <ide> ); <ide> <del> for ( i in jQuery.cache ) { <del> cacheLength--; <del> } <del> assert.equal( <del> cacheLength, 0, "No memory leak in jQuery.cache (bug #7165)" <del> ); <del> <ide> // Wrap an element containing a text node <ide> j = jQuery( "<span></span>" ).wrap( "<div>test</div>" ); <ide> assert.equal(
2
Ruby
Ruby
move option comparison into buildoptions
f3d3bc436829b5e9212e052cec50cded80cea2df
<ide><path>Library/Homebrew/bottles.rb <ide> def install_bottle? f <ide> and f.downloader.local_bottle_path <ide> not ARGV.build_from_source? \ <ide> and MacOS.bottles_supported? \ <del> and ARGV.used_options(f).empty? \ <add> and f.build.used_options.empty? \ <ide> and bottle_current?(f) <ide> end <ide> <ide><path>Library/Homebrew/extend/ARGV.rb <ide> def options_only <ide> select {|arg| arg[0..0] == '-'} <ide> end <ide> <del> def used_options f <del> f.build.as_flags & options_only <del> end <del> <del> def unused_options f <del> f.build.as_flags - options_only <del> end <del> <ide> def formulae <ide> require 'formula' <ide> @formulae ||= downcased_unique_named.map{ |name| Formula.factory name } <ide><path>Library/Homebrew/formula_support.rb <ide> def hash <ide> # This class holds the build-time options defined for a Formula, <ide> # and provides named access to those options during install. <ide> class BuildOptions <add> attr_writer :args <ide> include Enumerable <ide> <ide> def initialize args <ide> def universal? <ide> def build_32_bit? <ide> @args.include? '--32-bit' <ide> end <add> <add> def used_options <add> as_flags & @args.options_only <add> end <add> <add> def unused_options <add> as_flags - @args.options_only <add> end <ide> end <ide><path>Library/Homebrew/tab.rb <ide> class Tab < OpenStruct <ide> FILENAME = 'INSTALL_RECEIPT.json' <ide> <ide> def self.create f, args <add> f.build.args = args <add> <ide> sha = HOMEBREW_REPOSITORY.cd do <ide> `git rev-parse --verify -q HEAD 2>/dev/null`.chuzzle <ide> end <ide> <del> Tab.new :used_options => args.used_options(f), <del> :unused_options => args.unused_options(f), <add> Tab.new :used_options => f.build.used_options, <add> :unused_options => f.build.unused_options, <ide> :tabfile => f.prefix.join(FILENAME), <del> :built_as_bottle => !!args.build_bottle?, <add> :built_as_bottle => !!ARGV.build_bottle?, <ide> :tapped_from => f.tap, <ide> :time => Time.now.to_i, # to_s would be better but Ruby has no from_s function :P <ide> :HEAD => sha
4
PHP
PHP
fix parameter typehints in testapp
acc6cef75357191b17307407fae9ab593a9b72db
<ide><path>tests/TestCase/Auth/FormAuthenticateTest.php <ide> public function testAuthenticateRehash(): void <ide> /** <ide> * Tests that password hasher function is called exactly once in all cases. <ide> * <del> * @param string $username <del> * @param string|null $password <ide> * @return void <ide> * @dataProvider userList <ide> */ <ide><path>tests/TestCase/Controller/Component/PaginatorComponentTest.php <ide> protected function _getMockPosts(array $methods = []) <ide> /** <ide> * Helper method for mocking queries. <ide> * <del> * @param RepositoryInterface|null $table <ide> * @return \Cake\ORM\Query|\PHPUnit\Framework\MockObject\MockObject <ide> */ <ide> protected function _getMockFindQuery(?RepositoryInterface $table = null) <ide><path>tests/TestCase/DatabaseSuite.php <ide> public function count($preferCache = false): int <ide> /** <ide> * Runs the tests and collects their result in a TestResult. <ide> * <del> * @param \PHPUnit\Framework\TestResult $result <ide> * @return \PHPUnit\Framework\TestResult <ide> */ <ide> public function run(?TestResult $result = null): TestResult <ide><path>tests/TestCase/Event/EventManagerTest.php <ide> public function testDispatchGlobalBeforeLocal() <ide> <ide> /** <ide> * test callback <del> * <del> * @param \Cake\Event\EventInterface $event <ide> */ <ide> public function onMyEvent(EventInterface $event) <ide> { <ide><path>tests/TestCase/Routing/RouterTest.php <ide> public function invalidRoutePathProvider() <ide> /** <ide> * Test parseRoutePath() with invalid strings <ide> * <del> * @param string $value <ide> * @return void <ide> * @dataProvider invalidRoutePathProvider <ide> */ <ide><path>tests/test_app/TestApp/Application.php <ide> public function bootstrap(): void <ide> } <ide> <ide> /** <del> * @param \Cake\Console\CommandCollection $commands <ide> * @return \Cake\Console\CommandCollection <ide> */ <ide> public function console(CommandCollection $commands): CommandCollection <ide> public function console(CommandCollection $commands): CommandCollection <ide> } <ide> <ide> /** <del> * @param \Cake\Http\MiddlewareQueue $middlewareQueue <ide> * @return \Cake\Http\MiddlewareQueue <ide> */ <ide> public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue <ide> public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue <ide> /** <ide> * Routes hook, used for testing with RoutingMiddleware. <ide> * <del> * @param \Cake\Routing\RouteBuilder $routes <ide> * @return void <ide> */ <ide> public function routes(RouteBuilder $routes): void <ide><path>tests/test_app/TestApp/ApplicationWithDefaultRoutes.php <ide> public function bootstrap(): void <ide> } <ide> <ide> /** <del> * @param \Cake\Http\MiddlewareQueue $middlewareQueueQueue <ide> * @return \Cake\Http\MiddlewareQueue <ide> */ <ide> public function middleware(MiddlewareQueue $middlewareQueueQueue): MiddlewareQueue <ide><path>tests/test_app/TestApp/ApplicationWithPluginRoutes.php <ide> public function bootstrap(): void <ide> } <ide> <ide> /** <del> * @param \Cake\Http\MiddlewareQueue $middlewareQueue <ide> * @return \Cake\Http\MiddlewareQueue <ide> */ <ide> public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue <ide> public function middleware(MiddlewareQueue $middlewareQueue): MiddlewareQueue <ide> /** <ide> * Routes hook, used for testing with RoutingMiddleware. <ide> * <del> * @param \Cake\Routing\RouteBuilder $routes <ide> * @return void <ide> */ <ide> public function routes(RouteBuilder $routes): void <ide><path>tests/test_app/TestApp/Auth/TestAuthenticate.php <ide> public function implementedEvents(): array <ide> } <ide> <ide> /** <del> * @param \Cake\Http\ServerRequest $request <del> * @param \Cake\Http\Response $response <ide> * @return array <ide> */ <ide> public function authenticate(ServerRequest $request, Response $response) <ide> public function authenticate(ServerRequest $request, Response $response) <ide> } <ide> <ide> /** <del> * @param \Cake\Event\EventInterface $event <ide> * @param array $user <ide> * @return array <ide> */ <ide> public function afterIdentify(EventInterface $event, array $user) <ide> } <ide> <ide> /** <del> * @param \Cake\Event\EventInterface $event <ide> * @param array $user <ide> */ <ide> public function logout(EventInterface $event, array $user) <ide><path>tests/test_app/TestApp/Cache/Engine/TestAppCacheEngine.php <ide> <ide> class TestAppCacheEngine extends CacheEngine <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function set($key, $value, $ttl = null): bool <ide> { <ide> if ($key === 'fail') { <ide> public function set($key, $value, $ttl = null): bool <ide> return true; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function get($key, $default = null) <ide> { <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function increment(string $key, int $offset = 1) <ide> { <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function decrement(string $key, int $offset = 1) <ide> { <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function delete($key): bool <ide> { <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function clear(): bool <ide> { <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function clearGroup(string $group): bool <ide> { <ide> } <ide><path>tests/test_app/TestApp/Collection/CountableIterator.php <ide> <ide> class CountableIterator extends \IteratorIterator implements \Countable <ide> { <add> /** <add> * @param mixed $items <add> */ <ide> public function __construct($items) <ide> { <ide> $f = function () use ($items) { <ide><path>tests/test_app/TestApp/Collection/TestIterator.php <ide> class TestIterator extends ArrayIterator <ide> <ide> public $data = []; <ide> <add> /** <add> * @param mixed $data <add> */ <ide> public function __construct($data) <ide> { <ide> $this->data = $data; <ide><path>tests/test_app/TestApp/Controller/AuthTestController.php <ide> public function camelCase() <ide> * redirect method <ide> * <ide> * @param array|string $url <del> * @param int $status <ide> * @return \Cake\Http\Response|null <ide> */ <ide> public function redirect($url, int $status = 302): ?Response <ide><path>tests/test_app/TestApp/Controller/Component/AppleComponent.php <ide> class AppleComponent extends Component <ide> /** <ide> * startup method <ide> * <del> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <ide> public function startup(EventInterface $event) <ide><path>tests/test_app/TestApp/Controller/Component/OrangeComponent.php <ide> public function initialize(array $config): void <ide> /** <ide> * startup method <ide> * <del> * @param \Cake\Event\EventInterface $event <ide> * @return void <ide> */ <ide> public function startup(EventInterface $event): void <ide><path>tests/test_app/TestApp/Controller/Component/RequestHandlerExtComponent.php <ide> public function getExt() <ide> return $this->ext; <ide> } <ide> <del> public function setExt($ext) <add> public function setExt(?string $ext) <ide> { <ide> $this->ext = $ext; <ide> } <ide><path>tests/test_app/TestApp/Controller/Component/TestAuthComponent.php <ide> class TestAuthComponent extends AuthComponent <ide> public $authCheckCalledFrom; <ide> <ide> /** <del> * @param \Cake\Event\EventInterface $event <ide> * @return \Cake\Http\Response|null <ide> */ <ide> public function authCheck(EventInterface $event): ?Response <ide><path>tests/test_app/TestApp/Controller/Component/TestSecurityComponent.php <ide> class TestSecurityComponent extends SecurityComponent <ide> /** <ide> * validatePost method <ide> * <del> * @param Controller $controller <ide> * @return void <ide> */ <ide> public function validatePost(Controller $controller): void <ide><path>tests/test_app/TestApp/Controller/DependenciesController.php <ide> public function optionalString(string $str = 'default val') <ide> return $this->response->withStringBody(json_encode(compact('str'))); <ide> } <ide> <add> /** <add> * @param mixed $any <add> */ <ide> public function optionalDep($any = null, ?string $str = null, ?stdClass $dep = null) <ide> { <ide> return $this->response->withStringBody(json_encode(compact('dep', 'any', 'str'))); <ide> } <ide> <add> /** <add> * @param mixed $any <add> */ <ide> public function requiredDep(stdClass $dep, $any = null, ?string $str = null) <ide> { <ide> return $this->response->withStringBody(json_encode(compact('dep', 'any', 'str'))); <ide> public function spread(string ...$args) <ide> return $this->response->withStringBody(json_encode(['args' => $args])); <ide> } <ide> <add> /** <add> * @param mixed $one <add> */ <ide> public function requiredParam($one) <ide> { <ide> return $this->response->withStringBody(json_encode(compact('one'))); <ide><path>tests/test_app/TestApp/Controller/PostsController.php <ide> public function initialize(): void <ide> } <ide> <ide> /** <del> * @param \Cake\Event\EventInterface $event <ide> * @return \Cake\Http\Response|null|void <ide> */ <ide> public function beforeFilter(EventInterface $event) <ide><path>tests/test_app/TestApp/Controller/SecurityTestController.php <ide> public function fail(): void <ide> } <ide> <ide> /** <del> * redirect method <del> * <del> * @param array|string $url <del> * @param int $status <del> * @return \Cake\Http\Response|null <add> * @inheritDoc <ide> */ <ide> public function redirect($url, ?int $status = null): ?Response <ide> { <ide> public function redirect($url, ?int $status = null): ?Response <ide> /** <ide> * Convenience method for header() <ide> * <del> * @param string $status <ide> * @return void <ide> */ <ide> public function header(string $status): void <ide><path>tests/test_app/TestApp/Controller/TestController.php <ide> class TestController extends ControllerTestAppController <ide> /** <ide> * beforeFilter handler <ide> * <del> * @param \Cake\Event\EventInterface $event <ide> * @return \Cake\Http\Response|null|void <ide> */ <ide> public function beforeFilter(EventInterface $event) <ide> public function view($testId, $testTwoId): void <ide> ]); <ide> } <ide> <add> /** <add> * @param mixed $passed <add> */ <ide> public function reflection($passed, Table $table) <ide> { <ide> } <ide><path>tests/test_app/TestApp/Database/Type/ColumnSchemaAwareType.php <ide> <ide> class ColumnSchemaAwareType extends BaseType implements ExpressionTypeInterface, ColumnSchemaAwareInterface <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function toPHP($value, DriverInterface $driver) <ide> { <ide> return $value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function marshal($value) <ide> { <ide> return $value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function toDatabase($value, DriverInterface $driver) <ide> { <ide> return $value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function toExpression($value): ExpressionInterface <ide> { <ide> if ($value instanceof ColumnSchemaAwareTypeValueObject) { <ide> public function toExpression($value): ExpressionInterface <ide> )); <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function getColumnSql(TableSchemaInterface $schema, string $column, DriverInterface $driver): ?string <ide> { <ide> $data = $schema->getColumn($column); <ide> public function getColumnSql(TableSchemaInterface $schema, string $column, Drive <ide> return $sql; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function convertColumnDefinition(array $definition, DriverInterface $driver): ?array <ide> { <ide> return [ <ide><path>tests/test_app/TestApp/Database/Type/OrderedUuidType.php <ide> */ <ide> class OrderedUuidType extends BaseType implements ExpressionTypeInterface <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function toPHP($value, DriverInterface $d) <ide> { <ide> return new UuidValue($value); <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function toExpression($value): ExpressionInterface <ide> { <ide> if ($value instanceof UuidValue) { <ide> public function toExpression($value): ExpressionInterface <ide> ); <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function marshal($value) <ide> { <ide> return $value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function toDatabase($value, DriverInterface $d) <ide> { <ide> return $value; <ide><path>tests/test_app/TestApp/Database/Type/TestType.php <ide> <ide> class TestType extends StringType implements ExpressionTypeInterface <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function toExpression($value): ExpressionInterface <ide> { <ide> return new FunctionExpression('CONCAT', [$value, ' - foo']); <ide><path>tests/test_app/TestApp/Database/Type/UuidValue.php <ide> class UuidValue <ide> { <ide> public $value; <ide> <add> /** <add> * @param mixed $value <add> */ <ide> public function __construct($value) <ide> { <ide> $this->value = $value; <ide><path>tests/test_app/TestApp/Http/Client/Adapter/CakeStreamWrapper.php <ide> class CakeStreamWrapper implements \ArrayAccess <ide> ], <ide> ]; <ide> <del> public function stream_open($path, $mode, $options, &$openedPath) <add> public function stream_open(string $path, string $mode, int $options, ?string &$openedPath) <ide> { <ide> if ($path === 'http://throw_exception/') { <ide> throw new \Exception(); <ide> public function stream_close() <ide> return fclose($this->_stream); <ide> } <ide> <del> public function stream_read($count) <add> public function stream_read(int $count) <ide> { <ide> if (isset($this->_query['sleep'])) { <ide> sleep(1); <ide> public function stream_eof() <ide> return feof($this->_stream); <ide> } <ide> <del> public function stream_set_option($option, $arg1, $arg2) <add> public function stream_set_option(int $option, int $arg1, int $arg2) <ide> { <ide> return false; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function offsetExists($offset) <ide> { <ide> return isset($this->_data[$offset]); <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function offsetGet($offset) <ide> { <ide> return $this->_data[$offset]; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function offsetSet($offset, $value) <ide> { <ide> $this->_data[$offset] = $value; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function offsetUnset($offset) <ide> { <ide> unset($this->_data[$offset]); <ide><path>tests/test_app/TestApp/Http/Session/TestAppLibSession.php <ide> class TestAppLibSession implements SessionHandlerInterface <ide> { <ide> public $options = []; <ide> <del> public function __construct($options = []) <add> public function __construct(array $options = []) <ide> { <ide> $this->options = $options; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function open($path, $name): bool <ide> { <ide> return true; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function close(): bool <ide> { <ide> return true; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> #[ReturnTypeWillChange] <ide> public function read($id) <ide> { <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function write($id, $data): bool <ide> { <ide> return true; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function destroy($id): bool <ide> { <ide> return true; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> #[ReturnTypeWillChange] <ide> public function gc($maxlifetime) <ide> { <ide><path>tests/test_app/TestApp/Log/Formatter/ValidFormatter.php <ide> <ide> class ValidFormatter extends AbstractFormatter <ide> { <add> /** <add> * @inheritDoc <add> */ <ide> public function format($level, string $message, array $context = []): string <ide> { <ide> return $message; <ide><path>tests/test_app/TestApp/Mailer/TestMessage.php <ide> class TestMessage extends Message <ide> * <ide> * @return array <ide> */ <del> public function fmtAddress($address) <add> public function fmtAddress(array $address) <ide> { <ide> return parent::formatAddress($address); <ide> } <ide> public function getBoundary() <ide> * <ide> * @return string <ide> */ <del> public function encode($text) <add> public function encode(string $text) <ide> { <ide> return parent::encodeForHeader($text); <ide> } <ide> public function encode($text) <ide> * <ide> * @return string <ide> */ <del> public function decode($text) <add> public function decode(string $text) <ide> { <ide> return parent::decodeForHeader($text); <ide> } <ide> <ide> /** <ide> * Wrap to protected method <ide> * <del> * @param string $text <del> * @param int $length <ide> * @return array <ide> */ <del> public function doWrap($text, $length = Message::LINE_LENGTH_MUST) <add> public function doWrap(string $text, int $length = Message::LINE_LENGTH_MUST) <ide> { <ide> return $this->wrap($text, $length); <ide> } <ide><path>tests/test_app/TestApp/Mailer/TestUserMailer.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.3.3 <del> * @license https://opensource.org/licenses/mit-license.php MIT License <del> */ <del>namespace TestApp\Mailer; <del> <del>/** <del> * Test Suite Test App Mailer class. <del> */ <del>class TestUserMailer extends TestMailer <del>{ <del> public function invite($email) <del> { <del> $this->_email <del> ->setSubject('CakePHP') <del> ->setFrom('jadb@cakephp.org') <del> ->setTo($email) <del> ->setCc('markstory@cakephp.org') <del> ->addCc('admad@cakephp.org', 'Adnan') <del> ->setBcc('dereuromark@cakephp.org', 'Mark') <del> ->addBcc('antograssiot@cakephp.org') <del> ->setAttachments([ <del> dirname(__FILE__) . DS . 'TestMailer.php', <del> dirname(__FILE__) . DS . 'TestUserMailer.php', <del> ]) <del> ->send('Hello ' . $email); <del> } <del>} <ide><path>tests/test_app/TestApp/Mailer/Transport/SmtpTestTransport.php <ide> class SmtpTestTransport extends SmtpTransport <ide> /** <ide> * Helper to change the socket <ide> * <del> * @param Socket $socket <ide> * @return void <ide> */ <ide> public function setSocket(Socket $socket) <ide><path>tests/test_app/TestApp/Middleware/DumbMiddleware.php <ide> */ <ide> namespace TestApp\Middleware; <ide> <add>use Psr\Http\Message\ResponseInterface; <add>use Psr\Http\Message\ServerRequestInterface; <add> <ide> /** <ide> * Testing stub for middleware tests. <ide> */ <ide> class DumbMiddleware <ide> { <del> public function __invoke($request, $response, $next) <add> public function __invoke(ServerRequestInterface $req, ResponseInterface $res, callable $next) <ide> { <del> return $next($request, $response); <add> return $next($req, $res); <ide> } <ide> } <ide><path>tests/test_app/TestApp/Middleware/SampleMiddleware.php <ide> */ <ide> class SampleMiddleware <ide> { <del> public function __invoke($req, $res, $next) <add> public function __invoke(ServerRequestInterface $req, ResponseInterface $res, callable $next) <ide> { <ide> } <ide> } <ide><path>tests/test_app/TestApp/Middleware/ThrowsExceptionMiddleware.php <ide> namespace TestApp\Middleware; <ide> <ide> use Cake\Http\Exception\ForbiddenException; <add>use Psr\Http\Message\ResponseInterface; <add>use Psr\Http\Message\ServerRequestInterface; <ide> <ide> /** <ide> * Testing stub for middleware tests. <ide> */ <ide> class ThrowsExceptionMiddleware <ide> { <del> public function __invoke($req, $res, $next) <add> public function __invoke(ServerRequestInterface $req, ResponseInterface $res, callable $next) <ide> { <ide> throw new ForbiddenException('Sample Message'); <ide> } <ide><path>tests/test_app/TestApp/Model/Behavior/SluggableBehavior.php <ide> <ide> class SluggableBehavior extends Behavior <ide> { <del> public function beforeFind(EventInterface $event, Query $query, $options = []) <add> public function beforeFind(EventInterface $event, Query $query, array $options = []) <ide> { <ide> $query->where(['slug' => 'test']); <ide> <ide> return $query; <ide> } <ide> <del> public function findNoSlug(Query $query, $options = []) <add> public function findNoSlug(Query $query, array $options = []) <ide> { <ide> $query->where(['slug IS' => null]); <ide> <ide> return $query; <ide> } <ide> <del> public function slugify($value) <add> public function slugify(string $value) <ide> { <ide> return Text::slug($value); <ide> } <ide><path>tests/test_app/TestApp/Model/Table/PaginatorPostsTable.php <ide> public function findPublished(Query $query, array $options) <ide> /** <ide> * Custom finder, used with fixture data to ensure Paginator is sending options <ide> * <del> * @param \Cake\ORM\Query $query <del> * @param array $options <ide> * @return \Cake\ORM\Query <ide> */ <ide> public function findAuthor(Query $query, array $options = []) <ide><path>tests/test_app/TestApp/Model/Table/PublishedPostsTable.php <ide> class PublishedPostsTable extends Table <ide> { <ide> /** <del> * @param \Cake\Database\Query $query <del> * @param array $options <ide> * @return \Cake\Database\Query <ide> */ <ide> public function findPublished(Query $query, array $options) <ide><path>tests/test_app/TestApp/Model/Table/TestTable.php <ide> public function initialize(array $config): void <ide> } <ide> <ide> /** <del> * @param \Cake\Datasource\QueryInterface $query <ide> * @return \Cake\Datasource\QueryInterface <ide> */ <ide> public function findPublished(QueryInterface $query) <ide><path>tests/test_app/TestApp/Shell/ShellTestShell.php <ide> class ShellTestShell extends Shell <ide> public $testMessage = 'all your base are belong to us'; <ide> <ide> /** <del> * stop method <del> * <del> * @param int $status <del> * @return void <add> * @inheritDoc <ide> */ <ide> protected function _stop(int $status = Shell::CODE_SUCCESS): void <ide> { <ide><path>tests/test_app/TestApp/Shell/TestingDispatchShell.php <ide> protected function _welcome(): void <ide> $this->out('<info>Welcome to CakePHP Console</info>'); <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function out($message = null, int $newlines = 1, int $level = Shell::NORMAL): ?int <ide> { <ide> echo $message . "\n"; <ide><path>tests/test_app/TestApp/Stub/Stub.php <ide> class Stub <ide> use ModelAwareTrait; <ide> <ide> /** <del> * @param string $name <ide> * @return void <ide> */ <ide> public function setProps(string $name): void <ide><path>tests/test_app/TestApp/Utility/Base.php <ide> class Base <ide> <ide> public $assocProperty = ['Red']; <ide> <add> /** <add> * @param string[] $properties An array of properties and the merge strategy for them. <add> * @param array $options The options to use when merging properties. <add> * @return void <add> */ <ide> public function mergeVars($properties, $options = []) <ide> { <ide> return $this->_mergeVars($properties, $options); <ide><path>tests/test_app/TestApp/View/Cell/ArticlesCell.php <ide> public function customTemplatePath() <ide> /** <ide> * Simple echo. <ide> * <del> * @param string $msg1 <del> * @param string $msg2 <ide> * @return void <ide> */ <del> public function doEcho($msg1, $msg2) <add> public function doEcho(string $msg1, string $msg2) <ide> { <ide> $this->set('msg', $msg1 . $msg2); <ide> } <ide><path>tests/test_app/TestApp/View/Helper/EventListenerTestHelper.php <ide> class EventListenerTestHelper extends Helper <ide> * @param string $viewFile The view file being rendered. <ide> * @return void <ide> */ <del> public function beforeRender(EventInterface $event, $viewFile) <add> public function beforeRender(EventInterface $event, string $viewFile) <ide> { <ide> $this->config('options.foo', 'bar'); <ide> } <ide><path>tests/test_app/TestApp/View/Helper/HtmlAliasHelper.php <ide> <ide> namespace TestApp\View\Helper; <ide> <add>use Cake\Event\EventInterface; <ide> use Cake\View\Helper; <ide> <ide> /** <ide> class HtmlAliasHelper extends Helper <ide> { <ide> /** <del> * @param string $viewFile <ide> * @return void <ide> */ <del> public function afterRender($viewFile) <add> public function afterRender(EventInterface $event, string $viewFile) <ide> { <ide> } <ide> } <ide><path>tests/test_app/TestApp/View/Helper/TestBeforeAfterHelper.php <ide> <ide> namespace TestApp\View\Helper; <ide> <add>use Cake\Event\EventInterface; <ide> use Cake\View\Helper; <ide> <ide> class TestBeforeAfterHelper extends Helper <ide> class TestBeforeAfterHelper extends Helper <ide> * @param string $viewFile View file name. <ide> * @return void <ide> */ <del> public function beforeLayout($viewFile) <add> public function beforeLayout(EventInterface $event, string $viewFile) <ide> { <ide> $this->property = 'Valuation'; <ide> } <ide> public function beforeLayout($viewFile) <ide> * @param string $layoutFile Layout file name. <ide> * @return void <ide> */ <del> public function afterLayout($layoutFile) <add> public function afterLayout(EventInterface $event, string $layoutFile) <ide> { <ide> $this->_View->append('content', 'modified in the afterlife'); <ide> } <ide><path>tests/test_app/TestApp/View/TestView.php <ide> public function paths(?string $plugin = null, bool $cached = true): array <ide> * @param string $ext The extension <ide> * @return void <ide> */ <del> public function ext($ext) <add> public function ext(string $ext) <ide> { <ide> $this->_ext = $ext; <ide> } <ide><path>tests/test_app/TestApp/View/Widget/TestUsingViewWidget.php <ide> public function getView(): View <ide> return $this->_view; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function render(array $data, ContextInterface $context): string <ide> { <ide> return '<success></success>'; <ide> } <ide> <add> /** <add> * @inheritDoc <add> */ <ide> public function secureFields(array $data): array <ide> { <ide> if (!isset($data['name']) || $data['name'] === '') {
49
Javascript
Javascript
extract applicationinstance to separate file
9c2b8d4166d67774d5565834cd2622dd6d2b0b95
<ide><path>packages/ember-application/lib/system/application-instance.js <add>/** <add>@module ember <add>@submodule ember-application <add>*/ <add> <add>import EmberObject from "ember-runtime/system/object"; <add>import run from "ember-metal/run_loop"; <add> <add>export default EmberObject.extend({ <add> container: null, <add> customEvents: null, <add> rootElement: null, <add> <add> startRouting: function(isModuleBasedResolver) { <add> var router = this.container.lookup('router:main'); <add> if (!router) { return; } <add> <add> router.startRouting(isModuleBasedResolver); <add> }, <add> <add> handleURL: function(url) { <add> var router = this.container.lookup('router:main'); <add> <add> return router.handleURL(url); <add> }, <add> <add> setupEventDispatcher: function() { <add> var dispatcher = this.container.lookup('event_dispatcher:main'); <add> <add> dispatcher.setup(this.customEvents, this.rootElement); <add> <add> return dispatcher; <add> }, <add> <add> willDestroy: function() { <add> run(this.container, 'destroy'); <add> } <add>}); <ide><path>packages/ember-application/lib/system/application.js <ide> import HistoryLocation from "ember-routing/location/history_location"; <ide> import AutoLocation from "ember-routing/location/auto_location"; <ide> import NoneLocation from "ember-routing/location/none_location"; <ide> import BucketCache from "ember-routing/system/cache"; <add>import ApplicationInstance from "ember-application/system/application-instance"; <ide> <ide> import ContainerDebugAdapter from "ember-extension-support/container_debug_adapter"; <ide> <ide> function logLibraryVersions() { <ide> } <ide> } <ide> <del>var ApplicationInstance = Ember.Object.extend({ <del> container: null, <del> customEvents: null, <del> rootElement: null, <del> <del> startRouting: function(isModuleBasedResolver) { <del> var router = this.container.lookup('router:main'); <del> if (!router) { return; } <del> <del> router.startRouting(isModuleBasedResolver); <del> }, <del> <del> handleURL: function(url) { <del> var router = this.container.lookup('router:main'); <del> <del> return router.handleURL(url); <del> }, <del> <del> setupEventDispatcher: function() { <del> var dispatcher = this.container.lookup('event_dispatcher:main'); <del> <del> dispatcher.setup(this.customEvents, this.rootElement); <del> <del> return dispatcher; <del> }, <del> <del> willDestroy: function() { <del> run(this.container, 'destroy'); <del> } <del>}); <del> <ide> export default Application;
2
Python
Python
make test less flakey
711278b66785498f155785d430bce0295ba364dc
<ide><path>spacy/tests/parser/test_preset_sbd.py <ide> def test_sents_1_2(parser): <ide> doc[1].sent_start = True <ide> doc[2].sent_start = True <ide> doc = parser(doc) <del> assert len(list(doc.sents)) == 3 <add> assert len(list(doc.sents)) >= 3 <ide> <ide> <ide> def test_sents_1_3(parser):
1
Javascript
Javascript
create utilities for module generators
c3001938537b7f5590d71e536653ebfd083ffa52
<ide><path>packages/react-native-codegen/src/generators/modules/Utils.js <ide> <ide> 'use strict'; <ide> <del>import type {ObjectTypeAliasTypeShape} from '../../CodegenSchema'; <add>import type { <add> SchemaType, <add> NativeModuleAliasMap, <add> Required, <add> NativeModuleObjectTypeAnnotation, <add> NativeModuleSchema, <add>} from '../../CodegenSchema'; <ide> <del>function getTypeAliasTypeAnnotation( <del> name: string, <del> aliases: $ReadOnly<{[aliasName: string]: ObjectTypeAliasTypeShape, ...}>, <del>): $ReadOnly<ObjectTypeAliasTypeShape> { <del> const typeAnnotation = aliases[name]; <del> if (!typeAnnotation) { <del> throw Error(`No type annotation found for "${name}" in schema`); <del> } <del> if (typeAnnotation.type === 'ObjectTypeAnnotation') { <del> if (typeAnnotation.properties) { <del> return typeAnnotation; <del> } <add>const invariant = require('invariant'); <ide> <del> throw new Error( <del> `Unsupported type for "${name}". Please provide properties.`, <del> ); <del> } <del> // $FlowFixMe[incompatible-type] <del> if (typeAnnotation.type === 'TypeAliasTypeAnnotation') { <del> return getTypeAliasTypeAnnotation(typeAnnotation.name, aliases); <del> } <add>export type AliasResolver = ( <add> aliasName: string, <add>) => Required<NativeModuleObjectTypeAnnotation>; <add> <add>function createAliasResolver(aliasMap: NativeModuleAliasMap): AliasResolver { <add> return (aliasName: string) => { <add> const alias = aliasMap[aliasName]; <add> invariant(alias != null, `Unable to resolve type alias '${aliasName}'.`); <add> return alias; <add> }; <add>} <ide> <del> throw Error( <del> `Unsupported type annotation in alias "${name}", found: ${typeAnnotation.type}`, <del> ); <add>function getModules( <add> schema: SchemaType, <add>): $ReadOnly<{|[moduleName: string]: NativeModuleSchema|}> { <add> return Object.keys(schema.modules) <add> .map<?{+[string]: NativeModuleSchema}>( <add> moduleName => schema.modules[moduleName].nativeModules, <add> ) <add> .filter(Boolean) <add> .reduce<{+[string]: NativeModuleSchema}>( <add> (acc, modules) => ({...acc, ...modules}), <add> {}, <add> ); <ide> } <ide> <ide> module.exports = { <del> getTypeAliasTypeAnnotation, <add> createAliasResolver, <add> getModules, <ide> };
1
Ruby
Ruby
remove dependency on pathname in new routes
5ced4023931e2749aea1c64a4491bbd9efa5a524
<ide><path>actionpack/lib/action_controller/routing.rb <ide> require 'cgi' <del>require 'pathname' <ide> <ide> class Object <ide> def to_param <ide> def possible_controllers <ide> @possible_controllers = [] <ide> <ide> paths = $LOAD_PATH.select { |path| File.directory? path } <del> paths.collect! { |path| Pathname.new(path).realpath.to_s } <ide> paths = paths.sort_by { |path| - path.length } <ide> <ide> seen_paths = Hash.new {|h, k| h[k] = true; false}
1
Javascript
Javascript
remove unused https imports
71776f90572fcc3c3c79089189bae3661a679b81
<ide><path>test/parallel/test-http-url.parse-post.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <del>var https = require('https'); <ide> var url = require('url'); <ide> <ide> var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv'); <ide><path>test/parallel/test-http-url.parse-search.js <ide> var common = require('../common'); <ide> var assert = require('assert'); <ide> var http = require('http'); <del>var https = require('https'); <ide> var url = require('url'); <ide> <ide> var testURL = url.parse('http://localhost:' + common.PORT + '/asdf?qwer=zxcv');
2
Ruby
Ruby
do a hash lookup for collision detection
3e9158bb95de1770c5a529a903fe15b19a473439
<ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <ide> def name_for_action(as, action) #:nodoc: <ide> # and return nil in case it isn't. Otherwise, we pass the invalid name <ide> # forward so the underlying router engine treats it and raises an exception. <ide> if as.nil? <del> candidate unless @set.routes.find { |r| r.name == candidate } || candidate !~ /\A[_a-z]/i <add> candidate unless @set.named_routes.key?(candidate) || candidate !~ /\A[_a-z]/i <ide> else <ide> candidate <ide> end <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def get(name) <ide> routes[name.to_sym] <ide> end <ide> <add> def key?(name) <add> routes.key? name.to_sym <add> end <add> <ide> alias []= add <ide> alias [] get <ide> alias clear clear!
2
Text
Text
fix typo in repl.md
a413df40b67e1005b6c0c6d9e280bd7dcb53ee11
<ide><path>doc/api/repl.md <ide> changes: <ide> * `output` {Writable} The Writable stream to which REPL output will be <ide> written. Defaults to `process.stdout`. <ide> * `terminal` {boolean} If `true`, specifies that the `output` should be <del> treated as a a TTY terminal, and have ANSI/VT100 escape codes written to it. <add> treated as a TTY terminal, and have ANSI/VT100 escape codes written to it. <ide> Defaults to checking the value of the `isTTY` property on the `output` <ide> stream upon instantiation. <ide> * `eval` {Function} The function to be used when evaluating each given line
1
Java
Java
make jscconfig non-nullable
e54ff3d03f488d9d7e2b236c3f9d5914987d2b67
<ide><path>ReactAndroid/src/main/java/com/facebook/react/JSCConfig.java <ide> * Interface for the configuration object that is passed to JSC. <ide> */ <ide> public interface JSCConfig { <del> public WritableNativeMap getConfigMap(); <add> JSCConfig EMPTY = new JSCConfig() { <add> @Override <add> public WritableNativeMap getConfigMap() { <add> return new WritableNativeMap(); <add> } <add> }; <add> <add> WritableNativeMap getConfigMap(); <ide> } <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManager.java <ide> public static class Builder { <ide> protected @Nullable LifecycleState mInitialLifecycleState; <ide> protected @Nullable UIImplementationProvider mUIImplementationProvider; <ide> protected @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler; <del> protected @Nullable JSCConfig mJSCConfig; <add> protected JSCConfig mJSCConfig = JSCConfig.EMPTY; <ide> protected @Nullable Activity mCurrentActivity; <ide> protected @Nullable DefaultHardwareBackBtnHandler mDefaultHardwareBackBtnHandler; <ide> protected @Nullable RedBoxHandler mRedBoxHandler; <ide><path>ReactAndroid/src/main/java/com/facebook/react/XReactInstanceManagerImpl.java <ide> private final UIImplementationProvider mUIImplementationProvider; <ide> private final MemoryPressureRouter mMemoryPressureRouter; <ide> private final @Nullable NativeModuleCallExceptionHandler mNativeModuleCallExceptionHandler; <del> private final @Nullable JSCConfig mJSCConfig; <add> private final JSCConfig mJSCConfig; <ide> private @Nullable RedBoxHandler mRedBoxHandler; <ide> <ide> private final ReactInstanceDevCommandsHandler mDevInterface = <ide> public T get() throws Exception { <ide> LifecycleState initialLifecycleState, <ide> UIImplementationProvider uiImplementationProvider, <ide> NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler, <del> @Nullable JSCConfig jscConfig) { <add> JSCConfig jscConfig) { <ide> <ide> this(applicationContext, <ide> currentActivity, <ide> public T get() throws Exception { <ide> LifecycleState initialLifecycleState, <ide> UIImplementationProvider uiImplementationProvider, <ide> NativeModuleCallExceptionHandler nativeModuleCallExceptionHandler, <del> @Nullable JSCConfig jscConfig, <add> JSCConfig jscConfig, <ide> @Nullable RedBoxHandler redBoxHandler) { <ide> <ide> initializeSoLoaderIfNecessary(applicationContext); <ide> public void run() { <ide> <ide> private void recreateReactContextInBackgroundFromBundleFile() { <ide> recreateReactContextInBackground( <del> new JSCJavaScriptExecutor.Factory( <del> mJSCConfig == null ? new WritableNativeMap() : mJSCConfig.getConfigMap()), <add> new JSCJavaScriptExecutor.Factory(mJSCConfig.getConfigMap()), <ide> JSBundleLoader.createFileLoader(mApplicationContext, mJSBundleFile)); <ide> } <ide> <ide> private void onReloadWithJSDebugger(JavaJSExecutor.Factory jsExecutorFactory) { <ide> <ide> private void onJSBundleLoadedFromServer() { <ide> recreateReactContextInBackground( <del> new JSCJavaScriptExecutor.Factory( <del> mJSCConfig == null ? new WritableNativeMap() : mJSCConfig.getConfigMap()), <add> new JSCJavaScriptExecutor.Factory(mJSCConfig.getConfigMap()), <ide> JSBundleLoader.createCachedBundleFromNetworkLoader( <ide> mDevSupportManager.getSourceUrl(), <ide> mDevSupportManager.getDownloadedJSBundleFile()));
3
Ruby
Ruby
remove public `prevent_writes` writer
e4213e7c682f2b4bf19383ea1af1681c81c96ac5
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> class AbstractAdapter <ide> attr_writer :visitor <ide> deprecate :visitor= <ide> <del> attr_accessor :pool, :prevent_writes <del> attr_reader :schema_cache, :visitor, :owner, :logger, :prepared_statements, :lock <add> attr_accessor :pool <add> attr_reader :schema_cache, :visitor, :owner, :logger, :lock, :prepared_statements, :prevent_writes <ide> alias :in_use? :owner <ide> <ide> set_callback :checkin, :after, :enable_lazy_transactions! <ide> def initialize(connection, logger = nil, config = {}) # :nodoc: <ide> @idle_since = Concurrent.monotonic_time <ide> @schema_cache = SchemaCache.new self <ide> @quoted_column_names, @quoted_table_names = {}, {} <add> @prevent_writes = false <ide> @visitor = arel_visitor <ide> @lock = ActiveSupport::Concurrency::LoadInterlockAwareMonitor.new <ide> <ide> def preventing_writes? <ide> # even if you are on a database that can write. `while_preventing_writes` <ide> # will prevent writes to the database for the duration of the block. <ide> def while_preventing_writes <del> original = self.prevent_writes <del> self.prevent_writes = true <add> original, @prevent_writes = @prevent_writes, true <ide> yield <ide> ensure <del> self.prevent_writes = original <add> @prevent_writes = original <ide> end <ide> <ide> def migrations_paths # :nodoc:
1
Javascript
Javascript
move externals into chunk with entry
1b459d91f56215a3c617373d456ad53f9a63fea3
<ide><path>lib/Chunk.js <ide> Chunk.prototype.integratedSize = function(other, options) { <ide> return modulesSize * (this.initial || other.initial ? ENTRY_CHUNK_MULTIPLICATOR : 1) + CHUNK_OVERHEAD; <ide> }; <ide> <add>Chunk.prototype.hasEntryModule = function() { <add> return this.modules.some(function(module) { <add> return module.entry; <add> }); <add>} <add> <ide> Chunk.prototype.getChunkMaps = function(includeEntries, realHash) { <ide> var chunksProcessed = []; <ide> var chunkHashMap = {}; <ide><path>lib/ChunkTemplate.js <ide> ChunkTemplate.prototype.render = function(chunk, moduleTemplate, dependencyTempl <ide> var modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates); <ide> var core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates); <ide> var source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates); <del> if(chunk.modules.some(function(module) { <del> return module.entry; <del> })) { <add> if(chunk.hasEntryModule()) { <ide> source = this.applyPluginsWaterfall("render-with-entry", source, chunk); <ide> } <ide> chunk.rendered = true; <ide><path>lib/ExternalModule.js <ide> var WebpackMissingModule = require("./dependencies/WebpackMissingModule"); <ide> <ide> function ExternalModule(request, type) { <ide> Module.call(this); <add> this.chunkCondition = function(chunk) { <add> return chunk.hasEntryModule(); <add> }; <ide> this.request = request; <ide> this.type = type; <ide> this.built = false; <ide><path>lib/MainTemplate.js <ide> MainTemplate.prototype.render = function(hash, chunk, moduleTemplate, dependency <ide> buf.push(""); <ide> buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash))); <ide> var source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates); <del> if(chunk.modules.some(function(module) { <del> return module.entry; <del> })) { <add> if(chunk.hasEntryModule()) { <ide> source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash); <ide> } <ide> if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something"); <ide><path>lib/WebpackOptionsApply.js <ide> var RequireContextPlugin = require("./dependencies/RequireContextPlugin"); <ide> var RequireEnsurePlugin = require("./dependencies/RequireEnsurePlugin"); <ide> var RequireIncludePlugin = require("./dependencies/RequireIncludePlugin"); <ide> <add>var EnsureChunkConditionsPlugin = require("./optimize/EnsureChunkConditionsPlugin"); <ide> var RemoveParentModulesPlugin = require("./optimize/RemoveParentModulesPlugin"); <ide> var RemoveEmptyChunksPlugin = require("./optimize/RemoveEmptyChunksPlugin"); <ide> var MergeDuplicateChunksPlugin = require("./optimize/MergeDuplicateChunksPlugin"); <ide> WebpackOptionsApply.prototype.process = function(options, compiler) { <ide> ); <ide> <ide> compiler.apply( <add> new EnsureChunkConditionsPlugin(), <ide> new RemoveParentModulesPlugin(), <ide> new RemoveEmptyChunksPlugin(), <ide> new MergeDuplicateChunksPlugin(), <ide><path>lib/optimize/EnsureChunkConditionsPlugin.js <add>/* <add> MIT License http://www.opensource.org/licenses/mit-license.php <add> Author Tobias Koppers @sokra <add>*/ <add>function EnsureChunkConditionsPlugin() {} <add>module.exports = EnsureChunkConditionsPlugin; <add> <add>EnsureChunkConditionsPlugin.prototype.apply = function(compiler) { <add> compiler.plugin("compilation", function(compilation) { <add> compilation.plugin(["optimize-chunks-basic", "optimize-extracted-chunks-basic"], function(chunks) { <add> var changed = false; <add> chunks.forEach(function(chunk) { <add> chunk.modules.slice().forEach(function(module) { <add> if(!module.chunkCondition) return; <add> if(!module.chunkCondition(chunk)) { <add> chunk.parents.forEach(function(parent) { <add> parent.addModule(module); <add> }); <add> module.rewriteChunkInReasons(chunk, chunk.parents); <add> chunk.removeModule(module); <add> changed = true; <add> } <add> }); <add> }); <add> if(changed) return true; <add> }); <add> }); <add>}; <ide><path>test/configCases/externals/externals-in-chunk/chunk.js <add>exports.a = require("external"); <add>exports.b = System.import("./chunk2"); <ide>\ No newline at end of file <ide><path>test/configCases/externals/externals-in-chunk/chunk2.js <add>module.exports = require("external2"); <ide>\ No newline at end of file <ide><path>test/configCases/externals/externals-in-chunk/index.js <add>it("should move externals in chunks into entry chunk", function(done) { <add> var fs = require("fs"); <add> var source = fs.readFileSync(__filename, "utf-8"); <add> source.should.containEql("1+" + (1+1)); <add> source.should.containEql("3+" + (2+2)); <add> source.should.containEql("5+" + (3+3)); <add> <add> System.import("./chunk").then(function(chunk) { <add> chunk.a.should.be.eql(3); <add> chunk.b.then(function(chunk2) { <add> chunk2.should.be.eql(7); <add> System.import("external3").then(function(ex) { <add> ex.should.be.eql(11); <add> done(); <add> }); <add> }); <add> }); <add>}); <ide><path>test/configCases/externals/externals-in-chunk/webpack.config.js <add>module.exports = { <add> externals: { <add> external: "1+2", <add> external2: "3+4", <add> external3: "5+6" <add> }, <add> node: { <add> __dirname: false, <add> __filename: false <add> } <add>}; <ide>\ No newline at end of file
10
Ruby
Ruby
use jenkins pr plugin provided url
358fd0ca19ea65e82577a1ff58f51793a9e9b56f
<ide><path>Library/Homebrew/cmd/test-bot.rb <ide> def single_commit? start_revision, end_revision <ide> <ide> # Use Jenkins environment variables if present. <ide> if no_args? and ENV['GIT_PREVIOUS_COMMIT'] and ENV['GIT_COMMIT'] \ <del> and not ENV['ghprbPullId'] <add> and not ENV['ghprbPullLink'] <ide> diff_start_sha1 = shorten_revision ENV['GIT_PREVIOUS_COMMIT'] <ide> diff_end_sha1 = shorten_revision ENV['GIT_COMMIT'] <ide> test "brew", "update" if current_branch == "master" <ide> def single_commit? start_revision, end_revision <ide> end <ide> <ide> # Handle Jenkins pull request builder plugin. <del> if ENV['ghprbPullId'] and ENV['GIT_URL'] <del> git_url = ENV['GIT_URL'] <del> git_match = git_url.match %r{.*github.com[:/](\w+/\w+).*} <del> if git_match <del> github_repo = git_match[1] <del> pull_id = ENV['ghprbPullId'] <del> @url = "https://github.com/#{github_repo}/pull/#{pull_id}" <del> @hash = nil <del> else <del> puts "Invalid 'ghprbPullId' environment variable value!" <del> end <del> end <add> @url = ENV['ghprbPullLink'] if ENV['ghprbPullLink'] <ide> <ide> if no_args? <ide> if diff_start_sha1 == diff_end_sha1 or \
1
Python
Python
fix issue #879 and add a test for it
280d8659601a5e3b8dab77231d9f9fc16f5cd1ce
<ide><path>flask/app.py <ide> def try_trigger_before_first_request_functions(self): <ide> with self._before_request_lock: <ide> if self._got_first_request: <ide> return <del> self._got_first_request = True <ide> for func in self.before_first_request_funcs: <ide> func() <add> self._got_first_request = True <ide> <ide> def make_default_options_response(self): <ide> """This method is called to create the default `OPTIONS` response. <ide><path>flask/testsuite/basic.py <ide> import unittest <ide> from datetime import datetime <ide> from threading import Thread <add>from time import sleep <ide> from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning <ide> from flask._compat import text_type <ide> from werkzeug.exceptions import BadRequest, NotFound <ide> def foo(): <ide> self.assert_equal(got, [42]) <ide> self.assert_true(app.got_first_request) <ide> <add> def test_before_first_request_functions_concurrent(self): <add> got = [] <add> app = flask.Flask(__name__) <add> @app.before_first_request <add> def foo(): <add> sleep(1) <add> got.append(42) <add> c = app.test_client() <add> def get_and_assert(): <add> c.get("/") <add> self.assert_equal(got, [42]) <add> t = Thread(target=get_and_assert) <add> t.start() <add> get_and_assert() <add> t.join() <add> self.assert_true(app.got_first_request) <add> <ide> def test_routing_redirect_debugging(self): <ide> app = flask.Flask(__name__) <ide> app.debug = True
2
PHP
PHP
fix variable typo
f2d4bef8c0bf301bcad398f1e15ce8d0dfe9e48a
<ide><path>src/Illuminate/Database/Eloquent/Model.php <ide> public static function getGlobalScope($scope) <ide> { <ide> return array_first(static::$globalScopes[get_called_class()], function($key, $value) use ($scope) <ide> { <del> return $scope instanceof $registered; <add> return $scope instanceof $value; <ide> }); <ide> } <ide>
1
Javascript
Javascript
remove unused code
336e31740cb5697d67653fe00f1c4b214f49d398
<ide><path>test/math/random-test.js <ide> var vows = require("vows"), <ide> <ide> var suite = vows.describe("d3.random"); <ide> <del>var STDDEV = 5; <del>var MEAN = 38; <del> <del> <ide> /** <ide> * Testing a random number generator is a bit more complicated than testing <del> * deterministic code, so we use a different methodology. <add> * deterministic code, so we use different techniques. <ide> * <del> * If the RNG is correct, each test in this suite will pass with probability <del> * at least P. The tests have been designed so that P is 98%+. If the tests <del> * fail consistently, the RNG is broken. The value of P is given above each <del> * test case. <add> * If the RNG is correct, each test in this suite will pass with probability at <add> * least P. The tests have been designed so that P ≥ 98%. If the tests fail <add> * consistently, d3's RNG is broken. Specific values of P are given above each <add> * case. <ide> * <ide> * More on RNG testing here: <del> * http://www.johndcook.com/Beautiful_Testing_ch10.pdf <add> * @see http://www.johndcook.com/Beautiful_Testing_ch10.pdf <ide> * <ide> * @author Daniel Goldbach <ide> */ <add> <add>// Arbitrarily chosen parameters for the normal RNG <add>var STDDEV = 38.8; <add>var MEAN = 23428; <add> <ide> suite.addBatch({ <ide> "random": { <ide> topic: load("math/random").expression("d3.random"), <ide> "normal": { <del> "topic": function(random) { <del> return random.normal(MEAN, STDDEV); <del> }, <del> <del> // Mean of n normals is within µ ± 3σ/√n with P=99.7%. <del> "has expected mean" : function(normalRNG) { <del> var normals = []; <del> for (var i=0 ; i<2500 ; i++) { <del> normals.push(normalRNG()); <del> } <del> assert.inDelta(d3_test_math_random_mean(normals), MEAN, 3 * STDDEV/50); <del> }, <del> <del> // Variance of n normals is within σ² ± 3*σ²√(2/(n-1)) with P=99.7%. <del> "has expected variance" : function(normalRNG) { <del> var normals = []; <del> for (var i=0 ; i<2500 ; i++) { <del> normals.push(normalRNG()); <del> } <del> var sampleVar = d3_test_math_random_variance(normals); <del> var radiusAroundMean = 3 * Math.pow(STDDEV, 2) * Math.sqrt(2 / 2499); <del> assert.inDelta(sampleVar, Math.pow(STDDEV, 2), radiusAroundMean); <del> }, <add> "topic": function(random) { return random.normal(MEAN, STDDEV); }, <ide> <add> // P = 98% <ide> "has normal distribution" : KSTest(normalCDF(MEAN, STDDEV)) <ide> }, <ide> "logNormal": { <del> "topic": function(random) { <del> return random.logNormal(MEAN, STDDEV); <del> }, <add> "topic": function(random) { return random.logNormal(MEAN, STDDEV); }, <add> <add> // P = 98% <ide> "has log-normal distribution" : KSTest(logNormalCDF(MEAN, STDDEV)) <ide> }, <ide> "irwinHall": { <del> "topic": function(random) { <del> return random.irwinHall(10); <del> }, <add> "topic": function(random) { return random.irwinHall(10); }, <add> <add> // P = 98% <ide> "has Irwin-Hall distribution" : KSTest(irwinHallCDF(10)) <ide> } <ide> } <ide> }); <ide> <add> <ide> /** <del> * A macro that that takes a RNG and asserts that the values generated by the <del> * RNG could be generated by a random variable with cumulative distribution <del> * function `cdf'. `n' is the number of sample points to use. Higher n = better <del> * evaluation, slower test. <add> * A macro that that takes a RNG and performs a Kolmogorov-Smirnov test: asserts <add> * that the values generated by the RNG could be generated by the distribution <add> * with cumulative distribution function `cdf'. <ide> * <ide> * Passes with P≈98%. <add> * <add> * @param cdf function(x) { returns CDF of the distribution evaluated at x } <add> * @param n number of sample points. Higher n = better evaluation, slower test. <add> * @return function(rng) { <add> * // asserts that rng produces values fitting the distribution <add> * } <ide> */ <ide> function KSTest(cdf, n) { <ide> return function(rng) { <ide> function binom(n, k) { <ide> return factorial(n) / (factorial(k) * factorial(n - k)); <ide> } <ide> <del>function d3_test_math_random_mean(arr) { <del> if (arr.length === 0) { <del> return 0; <del> } <del> <del> var mean = 0; <del> for (var i = 0; i < arr.length; i++) { <del> mean += arr[i]; <del> } <del> return mean / arr.length; <del>} <del> <del>/** <del> * Sample variance implementation borrowed from science.js. <del> */ <del>function d3_test_math_random_variance(x) { <del> var n = x.length; <del> if (n < 1) return NaN; <del> if (n === 1) return 0; <del> var mean = d3_test_math_random_mean(x), <del> i = -1, <del> s = 0; <del> while (++i < n) { <del> var v = x[i] - mean; <del> s += v * v; <del> } <del> return s / (n - 1); <del>}; <ide> suite.export(module);
1
Javascript
Javascript
serialize userdata in gltfexporter
9614c891972632ec8bbd33667e8024a144fe64d7
<ide><path>examples/js/exporters/GLTFExporter.js <ide> THREE.GLTFExporter.prototype = { <ide> <ide> } <ide> <add> if ( scene.userData && Object.keys( scene.userData ).length > 0 ) { <add> <add> gltfScene.extras = serializeUserData( scene ); <add> <add> } <add> <ide> outputJSON.scenes.push( gltfScene ); <ide> <ide> var nodes = [];
1
Ruby
Ruby
convert zap test to spec
c431758f2dff931b69b16ab412dabacbe77380c0
<add><path>Library/Homebrew/cask/spec/cask/artifact/zap_spec.rb <del><path>Library/Homebrew/cask/test/cask/artifact/zap_test.rb <del>require "test_helper" <add>require "spec_helper" <ide> <ide> # TODO: test that zap removes an alternate version of the same Cask <ide> describe Hbc::Artifact::Zap do <ide> Hbc::Artifact::Zap.new(cask, command: Hbc::FakeSystemCommand) <ide> } <ide> <del> before do <add> before(:each) do <ide> shutup do <del> TestHelper.install_without_artifacts(cask) <add> InstallHelper.install_without_artifacts(cask) <ide> end <ide> end <ide> <ide> end <ide> } <ide> <del> describe "when using launchctl" do <add> context "when using launchctl" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-launchctl.rb") } <ide> let(:launchctl_list_cmd) { %w[/bin/launchctl list my.fancy.package.service] } <ide> let(:launchctl_remove_cmd) { %w[/bin/launchctl remove my.fancy.package.service] } <ide> EOS <ide> } <ide> <del> describe "when launchctl job is owned by user" do <add> context "when launchctl job is owned by user" do <ide> it "can zap" do <ide> Hbc::FakeSystemCommand.stubs_command( <ide> launchctl_list_cmd, <ide> end <ide> end <ide> <del> describe "when using pkgutil" do <add> context "when using pkgutil" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-pkgutil.rb") } <ide> let(:main_pkg_id) { "my.fancy.package.main" } <ide> let(:agent_pkg_id) { "my.fancy.package.agent" } <ide> end <ide> end <ide> <del> describe "when using kext" do <add> context "when using kext" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-kext.rb") } <ide> let(:kext_id) { "my.fancy.package.kernelextension" } <ide> <ide> end <ide> end <ide> <del> describe "when using quit" do <add> context "when using quit" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-quit.rb") } <ide> let(:bundle_id) { "my.fancy.package.app" } <ide> let(:quit_application_script) { <ide> end <ide> end <ide> <del> describe "when using signal" do <add> context "when using signal" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-signal.rb") } <ide> let(:bundle_id) { "my.fancy.package.app" } <ide> let(:signals) { %w[TERM KILL] } <ide> ) <ide> <ide> signals.each do |signal| <del> Process.expects(:kill).with(signal, *unix_pids) <add> expect(Process).to receive(:kill).with(signal, *unix_pids) <ide> end <ide> <ide> subject <ide> end <ide> end <ide> <del> describe "when using delete" do <add> context "when using delete" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-delete.rb") } <ide> <ide> it "can zap" do <ide> end <ide> end <ide> <del> describe "when using trash" do <add> context "when using trash" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-trash.rb") } <ide> <ide> it "can zap" do <ide> end <ide> end <ide> <del> describe "when using rmdir" do <add> context "when using rmdir" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-rmdir.rb") } <ide> let(:dir_pathname) { Pathname.new("#{TEST_FIXTURE_DIR}/cask/empty_directory") } <ide> <ide> end <ide> end <ide> <del> describe "when using script" do <add> context "when using script" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-script.rb") } <ide> let(:script_pathname) { cask.staged_path.join("MyFancyPkg", "FancyUninstaller.tool") } <ide> <ide> end <ide> end <ide> <del> describe "when using early_script" do <add> context "when using early_script" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-early-script.rb") } <ide> let(:script_pathname) { cask.staged_path.join("MyFancyPkg", "FancyUninstaller.tool") } <ide> <ide> end <ide> end <ide> <del> describe "when using login_item" do <add> context "when using login_item" do <ide> let(:cask) { Hbc::CaskLoader.load_from_file(TEST_FIXTURE_DIR/"cask/Casks/with-zap-login-item.rb") } <ide> <ide> it "can zap" do <ide><path>Library/Homebrew/cask/spec/support/fake_system_command.rb <add>def sudo(*args) <add> %w[/usr/bin/sudo -E --] + args.flatten <add>end <add> <add>module Hbc <add> class FakeSystemCommand <add> def self.responses <add> @responses ||= {} <add> end <add> <add> def self.expectations <add> @expectations ||= {} <add> end <add> <add> def self.system_calls <add> @system_calls ||= Hash.new(0) <add> end <add> <add> def self.clear <add> @responses = nil <add> @expectations = nil <add> @system_calls = nil <add> end <add> <add> def self.stubs_command(command, response = "") <add> responses[command] = response <add> end <add> <add> def self.expects_command(command, response = "", times = 1) <add> stubs_command(command, response) <add> expectations[command] = times <add> end <add> <add> def self.expect_and_pass_through(command, times = 1) <add> pass_through = ->(cmd, opts) { Hbc::SystemCommand.run(cmd, opts) } <add> expects_command(command, pass_through, times) <add> end <add> <add> def self.verify_expectations! <add> expectations.each do |command, times| <add> unless system_calls[command] == times <add> raise("expected #{command.inspect} to be run #{times} times, but got #{system_calls[command]}") <add> end <add> end <add> end <add> <add> def self.run(command_string, options = {}) <add> command = Hbc::SystemCommand.new(command_string, options).command <add> puts command <add> unless responses.key?(command) <add> raise("no response faked for #{command.inspect}, faked responses are: #{responses.inspect}") <add> end <add> system_calls[command] += 1 <add> <add> response = responses[command] <add> if response.respond_to?(:call) <add> response.call(command_string, options) <add> else <add> Hbc::SystemCommand::Result.new(command, response, "", 0) <add> end <add> end <add> <add> def self.run!(command, options = {}) <add> run(command, options.merge(must_succeed: true)) <add> end <add> end <add>end <add> <add>RSpec.configure do |config| <add> config.after(:each) do <add> begin <add> Hbc::FakeSystemCommand.verify_expectations! <add> ensure <add> Hbc::FakeSystemCommand.clear <add> end <add> end <add>end
2
Python
Python
correct a bug with docker module and server mode
aa9845d985f7b1e3a21ad1a7b441c7712f6bca7b
<ide><path>glances/plugins/glances_docker.py <ide> def update(self): <ide> self.reset() <ide> <ide> # The Docker-py lib is mandatory <del> if not docker_tag or self.args.disable_docker: <add> if not docker_tag or (self.args is not None and self.args.disable_docker): <ide> return self.stats <ide> <ide> if self.get_input() == 'local':
1
Javascript
Javascript
fix parsing of ssh urls
a1e54d6fb72ef0e0d3aab9ed2bf88d60a4a419d9
<ide><path>lib/url.js <ide> var protocolPattern = /^([a-z0-9.+-]+:)/i, <ide> nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), <ide> hostEndingChars = ['/', '?', '#'], <ide> hostnameMaxLen = 255, <del> hostnamePatternString = '[^' + nonHostChars.join('') + ']{0,63}', <del> hostnamePartPattern = new RegExp('^' + hostnamePatternString + '$'), <del> hostnamePartStart = new RegExp('^(' + hostnamePatternString + ')(.*)$'), <add> hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, <add> hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, <ide> // protocols that can allow "unsafe" and "unwise" chars. <ide> unsafeProtocol = { <ide> 'javascript': true, <ide><path>test/parallel/test-url.js <ide> var parseTests = { <ide> pathname: '%0D%0Ad/e', <ide> path: '%0D%0Ad/e?f', <ide> href: 'http://a%0D%22%20%09%0A%3C\'b:b@c/%0D%0Ad/e?f' <add> }, <add> <add> // git urls used by npm <add> 'git+ssh://git@github.com:npm/npm': { <add> protocol: 'git+ssh:', <add> slashes: true, <add> auth: 'git', <add> host: 'github.com', <add> port: null, <add> hostname: 'github.com', <add> hash: null, <add> search: null, <add> query: null, <add> pathname: '/:npm/npm', <add> path: '/:npm/npm', <add> href: 'git+ssh://git@github.com/:npm/npm' <ide> } <ide> <ide> };
2
Python
Python
fix docstrings for broadcastable inputs in ufunc
4e532b858e5ccdcbc32051df18e9b8467d755bc0
<ide><path>numpy/core/code_generators/ufunc_docstrings.py <ide> def get(name): <ide> For other keyword-only arguments, see the <ide> :ref:`ufunc docs <ufuncs.kwargs>`. <ide> """).strip(), <add> 'BROADCASTABLE_2': ("If ``x1.shape != x2.shape``, they must be " <add> "broadcastable to a common shape (which becomes the " <add> "shape of the output)."), <ide> 'OUT_SCALAR_1': "This is a scalar if `x` is a scalar.", <ide> 'OUT_SCALAR_2': "This is a scalar if both `x1` and `x2` are scalars.", <ide> } <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> The arrays to be added. If ``x1.shape != x2.shape``, they must be <del> broadcastable to a common shape (which may be the shape of one or <del> the other). <add> The arrays to be added. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like, real-valued <ide> `y`-coordinates. <ide> x2 : array_like, real-valued <del> `x`-coordinates. `x2` must be broadcastable to match the shape of <del> `x1` or vice versa. <add> `x`-coordinates. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Only integer and boolean types are handled. <add> Only integer and boolean types are handled. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Only integer and boolean types are handled. <add> Only integer and boolean types are handled. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Only integer and boolean types are handled. <add> Only integer and boolean types are handled. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Input values. <ide> x2 : array_like <del> The value of the function when x1 is 0. <add> The value of the function when x1 is 0. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Dividend array. <ide> x2 : array_like <del> Divisor array. <add> Divisor array. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays of the same shape. <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Numerator. <ide> x2 : array_like <del> Denominator. <add> Denominator. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Dividend. <ide> x2 : array_like <del> Divisor. <add> Divisor. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays. If ``x1.shape != x2.shape``, they must be <del> broadcastable to a common shape (which may be the shape of one or <del> the other). <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays. If ``x1.shape != x2.shape``, they must be <del> broadcastable to a common shape (which may be the shape of one or <del> the other). <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Leg of the triangle(s). <add> Leg of the triangle(s). $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Input values. <ide> x2 : array_like of integer type <ide> Number of zeros to append to `x1`. Has to be non-negative. <add> $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays. If ``x1.shape != x2.shape``, they must be <del> broadcastable to a common shape (which may be the shape of one or <del> the other). <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays. If ``x1.shape != x2.shape``, they must be <del> broadcastable to a common shape (which may be the shape of one or <del> the other). <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input values. <add> Input values. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input values. <add> Input values. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays. `x1` and `x2` must be of the same shape. <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> ------- <ide> y : ndarray or bool <del> Boolean result with the same shape as `x1` and `x2` of the logical <del> AND operation on corresponding elements of `x1` and `x2`. <add> Boolean result of the logical OR operation applied to the elements <add> of `x1` and `x2`; the shape is determined by broadcasting. <ide> $OUT_SCALAR_2 <ide> <ide> See Also <ide> def add_newdoc(place, name, doc): <ide> ---------- <ide> x1, x2 : array_like <ide> Logical OR is applied to the elements of `x1` and `x2`. <del> They have to be of the same shape. <add> $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> ------- <ide> y : ndarray or bool <del> Boolean result with the same shape as `x1` and `x2` of the logical <del> OR operation on elements of `x1` and `x2`. <add> Boolean result of the logical OR operation applied to the elements <add> of `x1` and `x2`; the shape is determined by broadcasting. <ide> $OUT_SCALAR_2 <ide> <ide> See Also <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Logical XOR is applied to the elements of `x1` and `x2`. They must <del> be broadcastable to the same shape. <add> Logical XOR is applied to the elements of `x1` and `x2`. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> ------- <ide> y : bool or ndarray of bool <ide> Boolean result of the logical XOR operation applied to the elements <del> of `x1` and `x2`; the shape is determined by whether or not <del> broadcasting of one or both arrays was required. <add> of `x1` and `x2`; the shape is determined by broadcasting. <ide> $OUT_SCALAR_2 <ide> <ide> See Also <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> The arrays holding the elements to be compared. They must have <del> the same shape, or shapes that can be broadcast to a single shape. <add> The arrays holding the elements to be compared. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> The arrays holding the elements to be compared. They must have <del> the same shape, or shapes that can be broadcast to a single shape. <add> The arrays holding the elements to be compared. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> The arrays holding the elements to be compared. They must have <del> the same shape. <add> The arrays holding the elements to be compared. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> The arrays holding the elements to be compared. They must have <del> the same shape. <add> The arrays holding the elements to be compared. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays to be multiplied. <add> Input arrays to be multiplied. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> Input arrays. <add> Input arrays. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> The bases. <ide> x2 : array_like <del> The exponents. <add> The exponents. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> The bases. <ide> x2 : array_like <del> The exponents. <add> The exponents. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Dividend array. <ide> x2 : array_like <del> Divisor array. <add> Divisor array. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Dividend array. <ide> x2 : array_like <del> Divisor array. <add> Divisor array. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like, int <ide> Input values. <ide> x2 : array_like, int <del> Number of bits to remove at the right of `x1`. <add> Number of bits to remove at the right of `x1`. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> """ <ide> Change the sign of x1 to that of x2, element-wise. <ide> <del> If both arguments are arrays or sequences, they have to be of the same <del> length. If `x2` is a scalar, its sign will be copied to all elements of <del> `x1`. <add> If `x2` is a scalar, its sign will be copied to all elements of `x1`. <ide> <ide> Parameters <ide> ---------- <ide> x1 : array_like <ide> Values to change the sign of. <ide> x2 : array_like <del> The sign of `x2` is copied to `x1`. <add> The sign of `x2` is copied to `x1`. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Values to find the next representable value of. <ide> x2 : array_like <ide> The direction where to look for the next representable value of `x1`. <add> $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like <del> The arrays to be subtracted from each other. <add> The arrays to be subtracted from each other. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Dividend array. <ide> x2 : array_like <del> Divisor array. <add> Divisor array. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> x1 : array_like <ide> Array of multipliers. <ide> x2 : array_like, int <del> Array of twos exponents. <add> Array of twos exponents. $BROADCASTABLE_2 <ide> $PARAMS <ide> <ide> Returns <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like, int <del> Arrays of values <add> Arrays of values. $BROADCASTABLE_2 <ide> <ide> Returns <ide> ------- <ide> def add_newdoc(place, name, doc): <ide> Parameters <ide> ---------- <ide> x1, x2 : array_like, int <del> Arrays of values <add> Arrays of values. $BROADCASTABLE_2 <ide> <ide> Returns <ide> -------
1
Javascript
Javascript
update radial linear tests
73bc52f196062f1998b7b5461f76eeb9a0fb4432
<ide><path>gulpfile.js <ide> var testFiles = [ <ide> '!./test/controller.line.tests.js', <ide> '!./test/core.layoutService.tests.js', <ide> '!./test/defaultConfig.tests.js', <del> '!./test/scale.radialLinear.tests.js', <del> //'!./test/scale.time.tests.js' <ide> ]; <ide> <ide> gulp.task('build', buildTask); <ide><path>test/scale.radialLinear.tests.js <ide> // Tests for the radial linear scale used by the polar area and radar charts <ide> describe('Test the radial linear scale', function() { <add> var chartInstance; <add> <add> beforeEach(function() { <add> window.addDefaultMatchers(jasmine); <add> }); <add> <add> afterEach(function() { <add> if (chartInstance) { <add> releaseChart(chartInstance); <add> } <add> }); <add> <ide> it('Should register the constructor with the scale service', function() { <ide> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <ide> expect(Constructor).not.toBe(undefined); <ide> describe('Test the radial linear scale', function() { <ide> }); <ide> <ide> it('Should correctly determine the max & min data values', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, -5, 78, -100] <del> }, { <del> yAxisID: scaleID, <del> data: [150] <del> }], <del> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: Chart.scaleService.getScaleDefaults('radialLinear'), // use default config for scale <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, -5, 78, -100] <add> }, { <add> data: [150] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <ide> }, <del> id: scaleID, <add> options: { <add> scales: { <add> <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> expect(scale.min).toBe(-100); <del> expect(scale.max).toBe(200); <add> expect(chartInstance.scale.min).toBe(-100); <add> expect(chartInstance.scale.max).toBe(150); <ide> }); <ide> <ide> it('Should correctly determine the max & min of string data values', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: ['10', '5', '0', '-5', '78', '-100'] <del> }, { <del> yAxisID: scaleID, <del> data: ['150'] <del> }], <del> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: Chart.scaleService.getScaleDefaults('radialLinear'), // use default config for scale <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: ['10', '5', '0', '-5', '78', '-100'] <add> }, { <add> data: ['150'] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <ide> }, <del> id: scaleID, <add> options: { <add> scales: { <add> <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> expect(scale.min).toBe(-100); <del> expect(scale.max).toBe(200); <add> expect(chartInstance.scale.min).toBe(-100); <add> expect(chartInstance.scale.max).toBe(150); <ide> }); <ide> <ide> it('Should correctly determine the max & min data values when there are hidden datasets', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, -5, 78, -100] <del> }, { <del> yAxisID: scaleID, <del> data: [150] <del> }, { <del> yAxisID: scaleID, <del> data: [1000], <del> hidden: true <del> }], <del> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: Chart.scaleService.getScaleDefaults('radialLinear'), // use default config for scale <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: ['10', '5', '0', '-5', '78', '-100'] <add> }, { <add> data: ['150'] <add> }, { <add> data: [1000], <add> hidden: true <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <ide> }, <del> id: scaleID, <add> options: { <add> scales: { <add> <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> expect(scale.min).toBe(-100); <del> expect(scale.max).toBe(200); <add> expect(chartInstance.scale.min).toBe(-100); <add> expect(chartInstance.scale.max).toBe(150); <ide> }); <ide> <ide> it('Should correctly determine the max & min data values when there is NaN data', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [50, 60, NaN, 70, null, undefined] <del> }], <del> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: Chart.scaleService.getScaleDefaults('radialLinear'), // use default config for scale <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [50, 60, NaN, 70, null, undefined] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <ide> }, <del> id: scaleID, <add> options: { <add> scales: { <add> <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> expect(scale.min).toBe(50); <del> expect(scale.max).toBe(70); <add> expect(chartInstance.scale.min).toBe(50); <add> expect(chartInstance.scale.max).toBe(70); <ide> }); <ide> <ide> it('Should ensure that the scale has a max and min that are not equal', function() { <ide> describe('Test the radial linear scale', function() { <ide> }); <ide> <ide> it('Should use the suggestedMin and suggestedMax options', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [1, 1, 1, 2, 1, 0] <del> }], <del> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <del> }; <del> <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> config.ticks.suggestedMin = -10; <del> config.ticks.suggestedMax = 10; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [1, 1, 1, 2, 1, 0] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <ide> }, <del> id: scaleID <add> options: { <add> scale: { <add> ticks: { <add> suggestedMin: -10, <add> suggestedMax: 10 <add> } <add> } <add> } <ide> }); <ide> <del> // Set arbitrary width and height for now <del> scale.update(200, 300); <del> expect(scale.min).toBe(-10); <del> expect(scale.max).toBe(10); <add> expect(chartInstance.scale.min).toBe(-10); <add> expect(chartInstance.scale.max).toBe(10); <ide> }); <ide> <ide> it('Should use the min and max options', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [1, 1, 1, 2, 1, 0] <del> }], <del> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <del> }; <del> <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> config.ticks.min = -1010; <del> config.ticks.max = 1010; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [1, 1, 1, 2, 1, 0] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5', 'label6'] <ide> }, <del> id: scaleID <add> options: { <add> scale: { <add> ticks: { <add> min: -1010, <add> max: 1010 <add> } <add> } <add> } <ide> }); <ide> <del> // Set arbitrary width and height for now <del> scale.update(200, 300); <del> expect(scale.min).toBe(-1010); <del> expect(scale.max).toBe(1010); <del> expect(scale.ticks[0]).toBe('-1010'); <del> expect(scale.ticks[scale.ticks.length - 1]).toBe('1010'); <del> expect(scale.ticks).toEqual(['-1010', '-1000', '0', '1000', '1010']); <add> expect(chartInstance.scale.min).toBe(-1010); <add> expect(chartInstance.scale.max).toBe(1010); <add> expect(chartInstance.scale.ticks).toEqual(['-1010', '-1000', '-500', '0', '500', '1000', '1010']); <ide> }); <ide> <ide> it('should forcibly include 0 in the range if the beginAtZero option is used', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [20, 30, 40, 50] <del> }], <del> labels: [], <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [20, 30, 40, 50] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> ticks: { <add> beginAtZero: false <add> } <add> } <add> } <ide> }); <ide> <del> config.ticks.beginAtZero = false; <del> scale.update(400, 400); <del> expect(scale.ticks).toEqual(['20', '25', '30', '35', '40', '45', '50']); <add> expect(chartInstance.scale.ticks).toEqual(['20', '25', '30', '35', '40', '45', '50']); <ide> <del> config.ticks.beginAtZero = true; <del> scale.update(400, 400); <del> expect(scale.ticks).toEqual(['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50']); <add> chartInstance.scale.options.ticks.beginAtZero = true; <add> chartInstance.update(); <ide> <del> mockData.datasets[0].data = [-20, -30, -40, -50]; <del> scale.update(400, 400); <del> expect(scale.ticks).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20', '-15', '-10', '-5', '0']); <add> expect(chartInstance.scale.ticks).toEqual(['0', '5', '10', '15', '20', '25', '30', '35', '40', '45', '50']); <ide> <del> config.ticks.beginAtZero = false; <del> scale.update(400, 400); <del> expect(scale.ticks).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20']); <del> }); <add> chartInstance.data.datasets[0].data = [-20, -30, -40, -50]; <add> chartInstance.update(); <ide> <del> it('Should generate tick marks in the correct order in reversed mode', function() { <del> var scaleID = 'myScale'; <add> expect(chartInstance.scale.ticks).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20', '-15', '-10', '-5', '0']); <ide> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }], <del> labels: [] <del> }; <add> chartInstance.scale.options.ticks.beginAtZero = false; <add> chartInstance.update(); <ide> <del> var mockContext = window.createMockContext(); <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> config.ticks.reverse = true; <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> expect(chartInstance.scale.ticks).toEqual(['-50', '-45', '-40', '-35', '-30', '-25', '-20']); <add> }); <add> <add> it('Should generate tick marks in the correct order in reversed mode', function() { <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78] <add> }], <add> labels: ['lablel1', 'label2', 'label3', 'label4', 'label5'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> ticks: { <add> reverse: true <add> } <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> <del> // Reverse mode makes this count up <del> expect(scale.ticks).toEqual(['80', '60', '40', '20', '0']); <del> expect(scale.start).toBe(80); <del> expect(scale.end).toBe(0); <add> expect(chartInstance.scale.ticks).toEqual(['80', '70', '60', '50', '40', '30', '20', '10', '0']); <add> expect(chartInstance.scale.start).toBe(80); <add> expect(chartInstance.scale.end).toBe(0); <ide> }); <ide> <ide> it('Should build labels using the user supplied callback', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }], <del> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <del> }; <del> <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> config.ticks.userCallback = function(value, index) { <del> return index.toString(); <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78] <add> }], <add> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> ticks: { <add> callback: function(value, index) { <add> return index.toString(); <add> } <add> } <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> <del> // Just the index <del> expect(scale.ticks).toEqual(['0', '1', '2', '3', '4']); <del> expect(scale.pointLabels).toEqual(['label1', 'label2', 'label3', 'label4', 'label5']); <add> expect(chartInstance.scale.ticks).toEqual(['0', '1', '2', '3', '4', '5', '6', '7', '8']); <add> expect(chartInstance.scale.pointLabels).toEqual(['label1', 'label2', 'label3', 'label4', 'label5']); <ide> }); <ide> <ide> it('Should build point labels using the user supplied callback', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }], <del> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <del> }; <del> <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> config.pointLabels.callback = function(value, index) { <del> return index.toString(); <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78] <add> }], <add> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> pointLabels: { <add> callback: function(value, index) { <add> return index.toString(); <add> } <add> } <add> } <add> } <ide> }); <ide> <del> scale.update(200, 300); <del> <del> // Just the index <del> expect(scale.pointLabels).toEqual(['0', '1', '2', '3', '4']); <add> expect(chartInstance.scale.pointLabels).toEqual(['0', '1', '2', '3', '4']); <ide> }); <ide> <ide> it('should correctly set the center point', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }], <del> labels: ['point1', 'point2', 'point3', 'point4', 'point5'] // used in radar charts which use the same scales <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78] <add> }], <add> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> pointLabels: { <add> callback: function(value, index) { <add> return index.toString(); <add> } <add> } <add> } <add> } <ide> }); <ide> <del> scale.left = 10; <del> scale.right = 210; <del> scale.top = 5; <del> scale.bottom = 305; <del> scale.update(200, 300); <del> <del> expect(scale.drawingArea).toBe(37); <del> expect(scale.xCenter).toBe(110); <del> expect(scale.yCenter).toBe(155); <add> expect(chartInstance.scale.drawingArea).toBe(225); <add> expect(chartInstance.scale.xCenter).toBe(256); <add> expect(chartInstance.scale.yCenter).toBe(272); <ide> }); <ide> <ide> it('should correctly get the label for a given data index', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }], <del> labels: ['point1', 'point2', 'point3', 'point4', 'point5'] // used in radar charts which use the same scales <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78] <add> }], <add> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> pointLabels: { <add> callback: function(value, index) { <add> return index.toString(); <add> } <add> } <add> } <add> } <ide> }); <del> <del> scale.left = 10; <del> scale.right = 210; <del> scale.top = 5; <del> scale.bottom = 305; <del> scale.update(200, 300); <del> <del> expect(scale.getLabelForIndex(1, 0)).toBe(5); <add> expect(chartInstance.scale.getLabelForIndex(1, 0)).toBe(5); <ide> }); <ide> <ide> it('should get the correct distance from the center point', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }], <del> labels: ['point1', 'point2', 'point3', 'point4', 'point5'] // used in radar charts which use the same scales <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <add> chartInstance = window.acquireChart({ <add> type: 'radar', <add> data: { <add> datasets: [{ <add> data: [10, 5, 0, 25, 78] <add> }], <add> labels: ['label1', 'label2', 'label3', 'label4', 'label5'] <ide> }, <del> id: scaleID, <add> options: { <add> scale: { <add> pointLabels: { <add> callback: function(value, index) { <add> return index.toString(); <add> } <add> } <add> } <add> } <ide> }); <ide> <del> scale.left = 0; <del> scale.right = 200; <del> scale.top = 0; <del> scale.bottom = 300; <del> scale.update(200, 300); <del> <del> expect(scale.getDistanceFromCenterForValue(scale.min)).toBe(0); <del> expect(scale.getDistanceFromCenterForValue(scale.max)).toBe(37); <del> expect(scale.getPointPositionForValue(1, 5)).toEqual({ <del> x: 102, <del> y: 149, <add> expect(chartInstance.scale.getDistanceFromCenterForValue(chartInstance.scale.min)).toBe(0); <add> expect(chartInstance.scale.getDistanceFromCenterForValue(chartInstance.scale.max)).toBe(225); <add> expect(chartInstance.scale.getPointPositionForValue(1, 5)).toEqual({ <add> x: 269, <add> y: 268, <ide> }); <ide> <del> config.reverse = true; <del> <del> scale.update(200, 300); <del> <del> expect(scale.getDistanceFromCenterForValue(scale.min)).toBe(37); <del> expect(scale.getDistanceFromCenterForValue(scale.max)).toBe(0); <del> }); <del> <del> it('should draw correctly when there are no point labels', function() { <del> var scaleID = 'myScale'; <del> <del> var mockData = { <del> datasets: [{ <del> yAxisID: scaleID, <del> data: [10, 5, 0, 25, 78] <del> }, ], <del> labels: ['point1', 'point2', 'point3', 'point4', 'point5'] // used in radar charts which use the same scales <del> }; <del> <del> var mockContext = window.createMockContext(); <del> var config = Chart.helpers.clone(Chart.scaleService.getScaleDefaults('radialLinear')); <del> config.lineArc = true; <del> var Constructor = Chart.scaleService.getScaleConstructor('radialLinear'); <del> var scale = new Constructor({ <del> ctx: mockContext, <del> options: config, <del> chart: { <del> data: mockData <del> }, <del> id: scaleID, <del> }); <del> <del> scale.left = 0; <del> scale.right = 200; <del> scale.top = 0; <del> scale.bottom = 300; <del> scale.update(200, 300); <add> chartInstance.scale.options.reverse = true; <add> chartInstance.update(); <ide> <del> scale.draw(); <del> <del> var expected = [{ <del> "name": "measureText", <del> "args": ["0"] <del> }, { <del> "name": "measureText", <del> "args": ["80"] <del> }, { <del> "name": "measureText", <del> "args": ["point1"] <del> }, { <del> "name": "measureText", <del> "args": ["point2"] <del> }, { <del> "name": "measureText", <del> "args": ["point3"] <del> }, { <del> "name": "measureText", <del> "args": ["point4"] <del> }, { <del> "name": "measureText", <del> "args": ["point5"] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "arc", <del> "args": [100, 150, 9.25, 0, 6.283185307179586] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["20"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 132.75, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["20", 100, 140.75] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "arc", <del> "args": [100, 150, 18.5, 0, 6.283185307179586] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["40"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 123.5, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["40", 100, 131.5] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "arc", <del> "args": [100, 150, 27.75, 0, 6.283185307179586] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["60"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 114.25, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["60", 100, 122.25] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "arc", <del> "args": [100, 150, 37, 0, 6.283185307179586] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["80"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 105, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["80", 100, 113] <del> }]; <del> expect(mockContext.getCalls()).toEqual(expected); <del> <del> mockContext.resetCalls(); <del> config.lineArc = false; <del> scale.draw(); <del> <del> expect(mockContext.getCalls()).toEqual([{ <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 141] <del> }, { <del> "name": "lineTo", <del> "args": [109, 147] <del> }, { <del> "name": "lineTo", <del> "args": [105, 157] <del> }, { <del> "name": "lineTo", <del> "args": [95, 157] <del> }, { <del> "name": "lineTo", <del> "args": [91, 147] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["20"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 132.75, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["20", 100, 140.75] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 132] <del> }, { <del> "name": "lineTo", <del> "args": [118, 144] <del> }, { <del> "name": "lineTo", <del> "args": [111, 165] <del> }, { <del> "name": "lineTo", <del> "args": [89, 165] <del> }, { <del> "name": "lineTo", <del> "args": [82, 144] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["40"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 123.5, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["40", 100, 131.5] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 122] <del> }, { <del> "name": "lineTo", <del> "args": [126, 141] <del> }, { <del> "name": "lineTo", <del> "args": [116, 172] <del> }, { <del> "name": "lineTo", <del> "args": [84, 172] <del> }, { <del> "name": "lineTo", <del> "args": [74, 141] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["60"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 114.25, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["60", 100, 122.25] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 113] <del> }, { <del> "name": "lineTo", <del> "args": [135, 139] <del> }, { <del> "name": "lineTo", <del> "args": [122, 180] <del> }, { <del> "name": "lineTo", <del> "args": [78, 180] <del> }, { <del> "name": "lineTo", <del> "args": [65, 139] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "measureText", <del> "args": ["80"] <del> }, { <del> "name": "setFillStyle", <del> "args": ["rgba(255,255,255,0.75)"] <del> }, { <del> "name": "fillRect", <del> "args": [88, 105, 24, 16] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["80", 100, 113] <del> }, { <del> "name": "setLineWidth", <del> "args": [1] <del> }, { <del> "name": "setStrokeStyle", <del> "args": ["rgba(0, 0, 0, 0.1)"] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 150] <del> }, { <del> "name": "lineTo", <del> "args": [65, 139] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["point5", 60, 137] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 150] <del> }, { <del> "name": "lineTo", <del> "args": [78, 180] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["point4", 75, 184] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 150] <del> }, { <del> "name": "lineTo", <del> "args": [122, 180] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["point3", 125, 184] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 150] <del> }, { <del> "name": "lineTo", <del> "args": [135, 139] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["point2", 140, 137] <del> }, { <del> "name": "beginPath", <del> "args": [] <del> }, { <del> "name": "moveTo", <del> "args": [100, 150] <del> }, { <del> "name": "lineTo", <del> "args": [100, 113] <del> }, { <del> "name": "stroke", <del> "args": [] <del> }, { <del> "name": "closePath", <del> "args": [] <del> }, { <del> "name": "setFillStyle", <del> "args": ["#666"] <del> }, { <del> "name": "fillText", <del> "args": ["point1", 100, 108] <del> }]); <add> expect(chartInstance.scale.getDistanceFromCenterForValue(chartInstance.scale.min)).toBe(225); <add> expect(chartInstance.scale.getDistanceFromCenterForValue(chartInstance.scale.max)).toBe(0); <ide> }); <ide> });
2
Python
Python
handle more exception types inside one clause
fb35eaf746cbf15a4642bbd04c8cad3f51b571af
<ide><path>libcloud/base.py <ide> def deploy_node(self, **kwargs): <ide> try: <ide> client.connect() <ide> break <del> except IOError, e: <del> laste = e <del> except socket.error, e: <add> except (IOError, socket.gaierror, socket.error), e: <ide> laste = e <ide> time.sleep(WAIT_PERIOD) <ide> if laste is not None:
1
Javascript
Javascript
fix uiexplorer search
c780a717e5e146e1b0c16893d70c3bbb87ef5907
<ide><path>Libraries/NavigationExperimental/Reducer/NavigationScenesReducer.js <ide> 'use strict'; <ide> <ide> const invariant = require('fbjs/lib/invariant'); <add>const shallowEqual = require('fbjs/lib/shallowEqual'); <ide> <ide> import type { <ide> NavigationRoute, <ide> function compareScenes( <ide> ); <ide> } <ide> <add>/** <add> * Whether two routes are the same. <add> */ <ide> function areScenesShallowEqual( <ide> one: NavigationScene, <ide> two: NavigationScene, <ide> function areScenesShallowEqual( <ide> one.key === two.key && <ide> one.index === two.index && <ide> one.isStale === two.isStale && <del> one.route.key === two.route.key <add> areRoutesShallowEqual(one.route, two.route) <ide> ); <ide> } <ide> <add>/** <add> * Whether two routes are the same. <add> */ <add>function areRoutesShallowEqual( <add> one: ?NavigationRoute, <add> two: ?NavigationRoute, <add>): boolean { <add> if (!one || !two) { <add> return one === two; <add> } <add> <add> if (one.key !== two.key) { <add> return false; <add> } <add> <add> return shallowEqual(one, two); <add>} <add> <ide> function NavigationScenesReducer( <ide> scenes: Array<NavigationScene>, <ide> nextState: NavigationState, <ide><path>Libraries/NavigationExperimental/Reducer/__tests__/NavigationScenesReducer-test.js <ide> describe('NavigationScenesReducer', () => { <ide> expect(scenes1).toBe(scenes2); <ide> }); <ide> <del> it('gets different scenes', () => { <add> it('gets different scenes when keys are different', () => { <ide> const state1 = { <ide> index: 0, <ide> routes: [{key: '1'}, {key: '2'}], <ide> describe('NavigationScenesReducer', () => { <ide> expect(scenes1).not.toBe(scenes2); <ide> }); <ide> <add> it('gets different scenes when routes are different', () => { <add> const state1 = { <add> index: 0, <add> routes: [{key: '1', x: 1}, {key: '2', x: 2}], <add> }; <add> <add> const state2 = { <add> index: 0, <add> routes: [{key: '1', x: 3}, {key: '2', x: 4}], <add> }; <add> <add> const scenes1 = NavigationScenesReducer([], state1, null); <add> const scenes2 = NavigationScenesReducer(scenes1, state2, state1); <add> expect(scenes1).not.toBe(scenes2); <add> }); <add> <add> <ide> it('pops scenes', () => { <ide> // Transition from ['1', '2', '3'] to ['1', '2']. <ide> const scenes = testTransition([
2
Text
Text
update doc docker_remote_api_v1.20.md
47e3ea7dd1a08abc86d1ef0e32b71248a0eac95e
<ide><path>docs/reference/api/docker_remote_api_v1.20.md <ide> Status Codes: <ide> <ide> ### Inspect a container <ide> <del>`GET /containers/(id)/json` <add>`GET /containers/(id or name)/json` <ide> <ide> Return low-level information on the container `id` <ide> <ide> Status Codes: <ide> <ide> ### List processes running inside a container <ide> <del>`GET /containers/(id)/top` <add>`GET /containers/(id or name)/top` <ide> <ide> List processes running inside the container `id`. On Unix systems this <ide> is done by running the `ps` command. This endpoint is not <ide> Status Codes: <ide> <ide> ### Get container logs <ide> <del>`GET /containers/(id)/logs` <add>`GET /containers/(id or name)/logs` <ide> <ide> Get `stdout` and `stderr` logs from the container ``id`` <ide> <ide> Status Codes: <ide> <ide> ### Inspect changes on a container's filesystem <ide> <del>`GET /containers/(id)/changes` <add>`GET /containers/(id or name)/changes` <ide> <ide> Inspect changes on container `id`'s filesystem <ide> <ide> Status Codes: <ide> <ide> ### Export a container <ide> <del>`GET /containers/(id)/export` <add>`GET /containers/(id or name)/export` <ide> <ide> Export the contents of container `id` <ide> <ide> Status Codes: <ide> <ide> ### Get container stats based on resource usage <ide> <del>`GET /containers/(id)/stats` <add>`GET /containers/(id or name)/stats` <ide> <ide> This endpoint returns a live stream of a container's resource usage statistics. <ide> <ide> Status Codes: <ide> <ide> ### Resize a container TTY <ide> <del>`POST /containers/(id)/resize?h=<height>&w=<width>` <add>`POST /containers/(id or name)/resize?h=<height>&w=<width>` <ide> <ide> Resize the TTY for container with `id`. You must restart the container for the resize to take effect. <ide> <ide> Status Codes: <ide> <ide> ### Start a container <ide> <del>`POST /containers/(id)/start` <add>`POST /containers/(id or name)/start` <ide> <ide> Start the container `id` <ide> <ide> Start the container `id` <ide> <ide> **Example request**: <ide> <del> POST /containers/(id)/start HTTP/1.1 <add> POST /containers/(id or name)/start HTTP/1.1 <ide> <ide> **Example response**: <ide> <ide> Status Codes: <ide> <ide> ### Stop a container <ide> <del>`POST /containers/(id)/stop` <add>`POST /containers/(id or name)/stop` <ide> <ide> Stop the container `id` <ide> <ide> Status Codes: <ide> <ide> ### Restart a container <ide> <del>`POST /containers/(id)/restart` <add>`POST /containers/(id or name)/restart` <ide> <ide> Restart the container `id` <ide> <ide> Status Codes: <ide> <ide> ### Kill a container <ide> <del>`POST /containers/(id)/kill` <add>`POST /containers/(id or name)/kill` <ide> <ide> Kill the container `id` <ide> <ide> Status Codes: <ide> <ide> ### Rename a container <ide> <del>`POST /containers/(id)/rename` <add>`POST /containers/(id or name)/rename` <ide> <ide> Rename the container `id` to a `new_name` <ide> <ide> Status Codes: <ide> <ide> ### Pause a container <ide> <del>`POST /containers/(id)/pause` <add>`POST /containers/(id or name)/pause` <ide> <ide> Pause the container `id` <ide> <ide> Status Codes: <ide> <ide> ### Unpause a container <ide> <del>`POST /containers/(id)/unpause` <add>`POST /containers/(id or name)/unpause` <ide> <ide> Unpause the container `id` <ide> <ide> Status Codes: <ide> <ide> ### Attach to a container <ide> <del>`POST /containers/(id)/attach` <add>`POST /containers/(id or name)/attach` <ide> <ide> Attach to the container `id` <ide> <ide> Status Codes: <ide> <ide> ### Attach to a container (websocket) <ide> <del>`GET /containers/(id)/attach/ws` <add>`GET /containers/(id or name)/attach/ws` <ide> <ide> Attach to the container `id` via websocket <ide> <ide> Status Codes: <ide> <ide> ### Wait a container <ide> <del>`POST /containers/(id)/wait` <add>`POST /containers/(id or name)/wait` <ide> <ide> Block until container `id` stops, then returns the exit code <ide> <ide> Status Codes: <ide> <ide> ### Remove a container <ide> <del>`DELETE /containers/(id)` <add>`DELETE /containers/(id or name)` <ide> <ide> Remove the container `id` from the filesystem <ide> <ide> Status Codes: <ide> <ide> ### Copy files or folders from a container <ide> <del>`POST /containers/(id)/copy` <add>`POST /containers/(id or name)/copy` <ide> <ide> Copy files or folders of container `id` <ide> <ide> Status Codes: <ide> <ide> ### Retrieving information about files and folders in a container <ide> <del>`HEAD /containers/(id)/archive` <add>`HEAD /containers/(id or name)/archive` <ide> <ide> See the description of the `X-Docker-Container-Path-Stat` header in the <ide> following section. <ide> <ide> ### Get an archive of a filesystem resource in a container <ide> <del>`GET /containers/(id)/archive` <add>`GET /containers/(id or name)/archive` <ide> <ide> Get an tar archive of a resource in the filesystem of container `id`. <ide> <ide> Status Codes: <ide> <ide> ### Extract an archive of files or folders to a directory in a container <ide> <del>`PUT /containers/(id)/archive` <add>`PUT /containers/(id or name)/archive` <ide> <ide> Upload a tar archive to be extracted to a path in the filesystem of container <ide> `id`. <ide> the root that contains a list of repository and tag names mapped to layer IDs. <ide> <ide> ### Exec Create <ide> <del>`POST /containers/(id)/exec` <add>`POST /containers/(id or name)/exec` <ide> <ide> Sets up an exec instance in a running container `id` <ide>
1
Mixed
Ruby
inspect time attributes with subsec
a3f4202cd8b6675f0727593a45bcb970373557da
<ide><path>activerecord/CHANGELOG.md <add>* Inspect time attributes with subsec. <add> <add> ```ruby <add> p Knot.create <add> => #<Knot id: 1, created_at: "2016-05-05 01:29:47.116928000"> <add> ``` <add> <add> *akinomaeni* <add> <ide> * Deprecate passing a column to `type_cast`. <ide> <ide> *Ryuta Kamizono* <ide><path>activerecord/lib/active_record/attribute_methods.rb <ide> def attributes_for_create(attribute_names) <ide> def format_for_inspect(value) <ide> if value.is_a?(String) && value.length > 50 <ide> "#{value[0, 50]}...".inspect <del> elsif value.is_a?(Date) || value.is_a?(Time) <add> elsif value.is_a?(Time) <add> %("#{value.strftime(Time::DATE_FORMATS[:db] + '.%9N')}") <add> elsif value.is_a?(Date) <ide> %("#{value.to_s(:db)}") <ide> else <ide> value.inspect <ide><path>activerecord/test/cases/attribute_methods_test.rb <ide> def setup <ide> test "attribute_for_inspect with a date" do <ide> t = topics(:first) <ide> <del> assert_equal %("#{t.written_on.to_s(:db)}"), t.attribute_for_inspect(:written_on) <add> assert_equal %("#{t.written_on.to_s(:db)}.#{t.written_on.strftime('%9N')}"), t.attribute_for_inspect(:written_on) <ide> end <ide> <ide> test "attribute_for_inspect with an array" do <ide><path>activerecord/test/cases/core_test.rb <ide> def test_inspect_class <ide> <ide> def test_inspect_instance <ide> topic = topics(:first) <del> assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}", bonus_time: "#{topic.bonus_time.to_s(:db)}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", important: nil, approved: false, replies_count: 1, unique_replies_count: 0, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}", updated_at: "#{topic.updated_at.to_s(:db)}">), topic.inspect <add> assert_equal %(#<Topic id: 1, title: "The First Topic", author_name: "David", author_email_address: "david@loudthinking.com", written_on: "#{topic.written_on.to_s(:db)}.#{topic.written_on.strftime('%9N')}", bonus_time: "#{topic.bonus_time.to_s(:db)}.#{topic.bonus_time.strftime('%9N')}", last_read: "#{topic.last_read.to_s(:db)}", content: "Have a nice day", important: nil, approved: false, replies_count: 1, unique_replies_count: 0, parent_id: nil, parent_title: nil, type: nil, group: nil, created_at: "#{topic.created_at.to_s(:db)}.#{topic.created_at.strftime('%9N')}", updated_at: "#{topic.updated_at.to_s(:db)}.#{topic.updated_at.strftime('%9N')}">), topic.inspect <ide> end <ide> <ide> def test_inspect_new_instance
4
PHP
PHP
add final test for fifo
b72bfa502b0993dbe2ca74ab656ba75b3406b96a
<ide><path>tests/Queue/QueueSqsQueueTest.php <ide> public function testGetQueueProperlyResolvesUrlWithoutPrefix() <ide> $this->assertEquals($queueUrl, $queue->getQueue($queueUrl)); <ide> } <ide> <add> public function testGetQueueProperlyResolvesFifoUrlWithoutPrefix() <add> { <add> $this->queueName = 'emails.fifo'; <add> $this->queueUrl = $this->prefix . $this->queueName; <add> $queue = new SqsQueue($this->sqs, $this->queueUrl); <add> $this->assertEquals($this->queueUrl, $queue->getQueue(null)); <add> $fifoQueueUrl = $this->baseUrl . '/' . $this->account . '/test.fifo'; <add> $this->assertEquals($fifoQueueUrl, $queue->getQueue($fifoQueueUrl)); <add> } <add> <ide> public function testGetQueueProperlyResolvesUrlWithSuffix() <ide> { <ide> $queue = new SqsQueue($this->sqs, $this->queueName, $this->prefix, $suffix = '-staging');
1
Text
Text
register django urls
3bf611787a6ca8fedcf69dde3776a308da1c7f30
<ide><path>docs/tutorial/quickstart.md <ide> Okay, now let's wire up the API URLs. On to `tutorial/urls.py`... <ide> path('', include(router.urls)), <ide> path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) <ide> ] <add> <add> urlpatterns += router.urls <ide> <ide> Because we're using viewsets instead of views, we can automatically generate the URL conf for our API, by simply registering the viewsets with a router class. <ide>
1
Ruby
Ruby
remove view_assigns from av
977c60eeeaaeec694d71d2b3baadd372f19f0b2f
<ide><path>actionview/lib/action_view/rendering.rb <ide> def default_protected_instance_vars <ide> super + [:@_view_context_class, :@_view_renderer, :@_lookup_context] <ide> end <ide> <del> # This method should return a hash with assigns. <del> # You can overwrite this configuration per controller. <del> # :api: public <del> def view_assigns <del> super <del> end <del> <ide> private <ide> <ide> # Normalize args and options.
1
Mixed
Go
add support for cpuset.mems
8077b2fb805c78cee642d8350df88227c6414960
<ide><path>daemon/container.go <ide> func populateCommand(c *Container, env []string) error { <ide> MemorySwap: c.hostConfig.MemorySwap, <ide> CpuShares: c.hostConfig.CpuShares, <ide> CpusetCpus: c.hostConfig.CpusetCpus, <add> CpusetMems: c.hostConfig.CpusetMems, <ide> Rlimits: rlimits, <ide> } <ide> <ide><path>daemon/execdriver/driver.go <ide> type Resources struct { <ide> MemorySwap int64 `json:"memory_swap"` <ide> CpuShares int64 `json:"cpu_shares"` <ide> CpusetCpus string `json:"cpuset_cpus"` <add> CpusetMems string `json:"cpuset_mems"` <ide> Rlimits []*ulimit.Rlimit `json:"rlimits"` <ide> } <ide> <ide> func SetupCgroups(container *configs.Config, c *Command) error { <ide> container.Cgroups.MemoryReservation = c.Resources.Memory <ide> container.Cgroups.MemorySwap = c.Resources.MemorySwap <ide> container.Cgroups.CpusetCpus = c.Resources.CpusetCpus <add> container.Cgroups.CpusetMems = c.Resources.CpusetMems <ide> } <ide> <ide> return nil <ide><path>daemon/execdriver/lxc/lxc_template.go <ide> lxc.cgroup.cpu.shares = {{.Resources.CpuShares}} <ide> {{if .Resources.CpusetCpus}} <ide> lxc.cgroup.cpuset.cpus = {{.Resources.CpusetCpus}} <ide> {{end}} <add>{{if .Resources.CpusetMems}} <add>lxc.cgroup.cpuset.mems = {{.Resources.CpusetMems}} <add>{{end}} <ide> {{end}} <ide> <ide> {{if .LxcConfig}} <ide><path>docs/man/docker-create.1.md <ide> docker-create - Create a new container <ide> [**--cap-drop**[=*[]*]] <ide> [**--cidfile**[=*CIDFILE*]] <ide> [**--cpuset-cpus**[=*CPUSET-CPUS*]] <add>[**--cpuset-mems**[=*CPUSET-MEMS*]] <ide> [**--device**[=*[]*]] <ide> [**--dns-search**[=*[]*]] <ide> [**--dns**[=*[]*]] <ide> IMAGE [COMMAND] [ARG...] <ide> **--cpuset-cpus**="" <ide> CPUs in which to allow execution (0-3, 0,1) <ide> <add>**--cpuset-mems**="" <add> Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. <add> <add> If you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1` <add>then processes in your Docker container will only use memory from the first <add>two memory nodes. <add> <ide> **--device**=[] <ide> Add a host device to the container (e.g. --device=/dev/sdc:/dev/xvdc:rwm) <ide> <ide><path>docs/man/docker-run.1.md <ide> docker-run - Run a command in a new container <ide> [**--cap-drop**[=*[]*]] <ide> [**--cidfile**[=*CIDFILE*]] <ide> [**--cpuset-cpus**[=*CPUSET-CPUS*]] <add>[**--cpuset-mems**[=*CPUSET-MEMS*]] <ide> [**-d**|**--detach**[=*false*]] <ide> [**--device**[=*[]*]] <ide> [**--dns-search**[=*[]*]] <ide> division of CPU shares: <ide> **--cpuset-cpus**="" <ide> CPUs in which to allow execution (0-3, 0,1) <ide> <add>**--cpuset-mems**="" <add> Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. <add> <add> If you have four memory nodes on your system (0-3), use `--cpuset-mems=0,1` <add>then processes in your Docker container will only use memory from the first <add>two memory nodes. <add> <ide> **-d**, **--detach**=*true*|*false* <ide> Detached mode: run the container in the background and print the new container ID. The default is *false*. <ide> <ide><path>docs/sources/reference/api/docker_remote_api_v1.19.md <ide> Create a container <ide> "MemorySwap": 0, <ide> "CpuShares": 512, <ide> "CpusetCpus": "0,1", <add> "CpusetMems": "0,1", <ide> "PortBindings": { "22/tcp": [{ "HostPort": "11022" }] }, <ide> "PublishAllPorts": false, <ide> "Privileged": false, <ide> Json Parameters: <ide> (ie. the relative weight vs other containers). <ide> - **Cpuset** - The same as CpusetCpus, but deprecated, please don't use. <ide> - **CpusetCpus** - String value containing the cgroups CpusetCpus to use. <add>- **CpusetMems** - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. <ide> - **AttachStdin** - Boolean value, attaches to stdin. <ide> - **AttachStdout** - Boolean value, attaches to stdout. <ide> - **AttachStderr** - Boolean value, attaches to stderr. <ide> Return low-level information on the container `id` <ide> "CapDrop": null, <ide> "ContainerIDFile": "", <ide> "CpusetCpus": "", <add> "CpusetMems": "", <ide> "CpuShares": 0, <ide> "Devices": [], <ide> "Dns": null, <ide><path>docs/sources/reference/commandline/cli.md <ide> Creates a new container. <ide> --cgroup-parent="" Optional parent cgroup for the container <ide> --cidfile="" Write the container ID to the file <ide> --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1) <add> --cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1) <ide> --device=[] Add a host device to the container <ide> --dns=[] Set custom DNS servers <ide> --dns-search=[] Set custom DNS search domains <ide> To remove an image using its digest: <ide> --cap-drop=[] Drop Linux capabilities <ide> --cidfile="" Write the container ID to the file <ide> --cpuset-cpus="" CPUs in which to allow execution (0-3, 0,1) <add> --cpuset-mems="" Memory nodes (MEMs) in which to allow execution (0-3, 0,1) <ide> -d, --detach=false Run container in background and print container ID <ide> --device=[] Add a host device to the container <ide> --dns=[] Set custom DNS servers <ide><path>docs/sources/reference/run.md <ide> container: <ide> -memory-swap="": Total memory limit (memory + swap, format: <number><optional unit>, where unit = b, k, m or g) <ide> -c, --cpu-shares=0: CPU shares (relative weight) <ide> --cpuset-cpus="": CPUs in which to allow execution (0-3, 0,1) <add> --cpuset-mems="": Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. <ide> <ide> ### Memory constraints <ide> <ide> This means processes in container can be executed on cpu 1 and cpu 3. <ide> <ide> This means processes in container can be executed on cpu 0, cpu 1 and cpu 2. <ide> <add>We can set mems in which to allow execution for containers. Only effective <add>on NUMA systems. <add> <add>Examples: <add> <add> $ docker run -ti --cpuset-mems="1,3" ubuntu:14.04 /bin/bash <add> <add>This example restricts the processes in the container to only use memory from <add>memory nodes 1 and 3. <add> <add> $ docker run -ti --cpuset-mems="0-2" ubuntu:14.04 /bin/bash <add> <add>This example restricts the processes in the container to only use memory from <add>memory nodes 0, 1 and 2. <add> <ide> ## Runtime privilege, Linux capabilities, and LXC configuration <ide> <ide> --cap-add: Add Linux capabilities <ide><path>integration-cli/docker_cli_run_test.go <ide> func TestRunWithCpuset(t *testing.T) { <ide> <ide> cmd := exec.Command(dockerBinary, "run", "--cpuset", "0", "busybox", "true") <ide> if code, err := runCommand(cmd); err != nil || code != 0 { <del> t.Fatalf("container should run successfuly with cpuset of 0: %s", err) <add> t.Fatalf("container should run successfully with cpuset of 0: %s", err) <ide> } <ide> <ide> logDone("run - cpuset 0") <ide> func TestRunWithCpusetCpus(t *testing.T) { <ide> <ide> cmd := exec.Command(dockerBinary, "run", "--cpuset-cpus", "0", "busybox", "true") <ide> if code, err := runCommand(cmd); err != nil || code != 0 { <del> t.Fatalf("container should run successfuly with cpuset-cpus of 0: %s", err) <add> t.Fatalf("container should run successfully with cpuset-cpus of 0: %s", err) <ide> } <ide> <ide> logDone("run - cpuset-cpus 0") <ide> } <ide> <add>func TestRunWithCpusetMems(t *testing.T) { <add> defer deleteAllContainers() <add> <add> cmd := exec.Command(dockerBinary, "run", "--cpuset-mems", "0", "busybox", "true") <add> if code, err := runCommand(cmd); err != nil || code != 0 { <add> t.Fatalf("container should run successfully with cpuset-mems of 0: %s", err) <add> } <add> <add> logDone("run - cpuset-mems 0") <add>} <add> <ide> func TestRunDeviceNumbers(t *testing.T) { <ide> defer deleteAllContainers() <ide> <ide><path>runconfig/hostconfig.go <ide> type HostConfig struct { <ide> MemorySwap int64 // Total memory usage (memory + swap); set `-1` to disable swap <ide> CpuShares int64 // CPU shares (relative weight vs. other containers) <ide> CpusetCpus string // CpusetCpus 0-2, 0,1 <add> CpusetMems string // CpusetMems 0-2, 0,1 <ide> Privileged bool <ide> PortBindings nat.PortMap <ide> Links []string <ide><path>runconfig/parse.go <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> flWorkingDir = cmd.String([]string{"w", "-workdir"}, "", "Working directory inside the container") <ide> flCpuShares = cmd.Int64([]string{"c", "-cpu-shares"}, 0, "CPU shares (relative weight)") <ide> flCpusetCpus = cmd.String([]string{"#-cpuset", "-cpuset-cpus"}, "", "CPUs in which to allow execution (0-3, 0,1)") <add> flCpusetMems = cmd.String([]string{"-cpuset-mems"}, "", "MEMs in which to allow execution (0-3, 0,1)") <ide> flNetMode = cmd.String([]string{"-net"}, "bridge", "Set the Network mode for the container") <ide> flMacAddress = cmd.String([]string{"-mac-address"}, "", "Container MAC address (e.g. 92:d0:c6:0a:29:33)") <ide> flIpcMode = cmd.String([]string{"-ipc"}, "", "IPC namespace to use") <ide> func Parse(cmd *flag.FlagSet, args []string) (*Config, *HostConfig, *flag.FlagSe <ide> MemorySwap: MemorySwap, <ide> CpuShares: *flCpuShares, <ide> CpusetCpus: *flCpusetCpus, <add> CpusetMems: *flCpusetMems, <ide> Privileged: *flPrivileged, <ide> PortBindings: portBindings, <ide> Links: flLinks.GetAll(),
11
Text
Text
add missing word to data fetching docs
334ce64cd7419e3be53ff1b60f886e40060da8e9
<ide><path>docs/basic-features/data-fetching.md <ide> In the [Pages documentation](/docs/basic-features/pages.md), we’ve explained t <ide> We’ll talk about the three unique Next.js functions you can use to fetch data for pre-rendering: <ide> <ide> - [`getStaticProps`](#getstaticprops-static-generation) (Static Generation): Fetch data at **build time**. <del>- [`getStaticPaths`](#getstaticpaths-static-generation) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render based on data. <add>- [`getStaticPaths`](#getstaticpaths-static-generation) (Static Generation): Specify [dynamic routes](/docs/routing/dynamic-routes.md) to pre-render pages based on data. <ide> - [`getServerSideProps`](#getserversideprops-server-side-rendering) (Server-side Rendering): Fetch data on **each request**. <ide> <ide> In addition, we’ll talk briefly about how to fetch data on the client side.
1
Ruby
Ruby
build fix for observing_test.rb
7f248076a3f0aee773bc4148009a30623efcf173
<ide><path>activemodel/test/cases/observing_test.rb <ide> def teardown <ide> <ide> test "tracks implicit observable models" do <ide> instance = FooObserver.new <del> assert_equal [Foo], old_instance.observed_classes <add> assert_equal [Foo], instance.observed_classes <ide> end <ide> <ide> test "tracks explicit observed model class" do
1
Go
Go
fix builder cache bug
4f3889e4be9fe518e9be73306a8716c3a5f4b1c6
<ide><path>builder/tarsum.go <ide> func (c *tarSumContext) Stat(path string) (string, FileInfo, error) { <ide> sum := path <ide> // Use the checksum of the followed path(not the possible symlink) because <ide> // this is the file that is actually copied. <del> if tsInfo := c.sums.GetFile(rel); tsInfo != nil { <add> if tsInfo := c.sums.GetFile(filepath.ToSlash(rel)); tsInfo != nil { <ide> sum = tsInfo.Sum() <ide> } <ide> fi := &HashedFileInfo{PathFileInfo{st, fullpath, filepath.Base(cleanpath)}, sum} <ide><path>integration-cli/docker_cli_build_test.go <ide> ADD %s/file /` <ide> <ide> } <ide> <add>// Regression for https://github.com/docker/docker/pull/27805 <add>// Makes sure that we don't use the cache if the contents of <add>// a file in a subfolder of the context is modified and we re-build. <add>func (s *DockerSuite) TestBuildModifyFileInFolder(c *check.C) { <add> name := "testbuildmodifyfileinfolder" <add> <add> ctx, err := fakeContext(`FROM busybox <add>RUN ["mkdir", "/test"] <add>ADD folder/file /test/changetarget`, <add> map[string]string{}) <add> if err != nil { <add> c.Fatal(err) <add> } <add> defer ctx.Close() <add> if err := ctx.Add("folder/file", "first"); err != nil { <add> c.Fatal(err) <add> } <add> id1, err := buildImageFromContext(name, ctx, true) <add> if err != nil { <add> c.Fatal(err) <add> } <add> if err := ctx.Add("folder/file", "second"); err != nil { <add> c.Fatal(err) <add> } <add> id2, err := buildImageFromContext(name, ctx, true) <add> if err != nil { <add> c.Fatal(err) <add> } <add> if id1 == id2 { <add> c.Fatal("cache was used even though file contents in folder was changed") <add> } <add>} <add> <ide> func (s *DockerSuite) TestBuildAddSingleFileToRoot(c *check.C) { <ide> testRequires(c, DaemonIsLinux) // Linux specific test <ide> name := "testaddimg" <ide><path>integration-cli/docker_utils.go <ide> func (f *FakeContext) Add(file, content string) error { <ide> } <ide> <ide> func (f *FakeContext) addFile(file string, content []byte) error { <del> filepath := path.Join(f.Dir, file) <del> dirpath := path.Dir(filepath) <add> fp := filepath.Join(f.Dir, filepath.FromSlash(file)) <add> dirpath := filepath.Dir(fp) <ide> if dirpath != "." { <ide> if err := os.MkdirAll(dirpath, 0755); err != nil { <ide> return err <ide> } <ide> } <del> return ioutil.WriteFile(filepath, content, 0644) <add> return ioutil.WriteFile(fp, content, 0644) <ide> <ide> } <ide> <ide> // Delete a file at a path <ide> func (f *FakeContext) Delete(file string) error { <del> filepath := path.Join(f.Dir, file) <del> return os.RemoveAll(filepath) <add> fp := filepath.Join(f.Dir, filepath.FromSlash(file)) <add> return os.RemoveAll(fp) <ide> } <ide> <ide> // Close deletes the context
3
Java
Java
use more modern java api for empty collections
6163f2d32f3f1541a7032f8888bd79395e927140
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/ContextAnnotationAutowireCandidateResolver.java <ide> public Object getTarget() { <ide> if (target == null) { <ide> Class<?> type = getTargetClass(); <ide> if (Map.class == type) { <del> return Collections.EMPTY_MAP; <add> return Collections.emptyMap(); <ide> } <ide> else if (List.class == type) { <del> return Collections.EMPTY_LIST; <add> return Collections.emptyList(); <ide> } <ide> else if (Set.class == type || Collection.class == type) { <del> return Collections.EMPTY_SET; <add> return Collections.emptySet(); <ide> } <ide> throw new NoSuchBeanDefinitionException(descriptor.getResolvableType(), <ide> "Optional dependency not present for lazy injection point");
1
Text
Text
update documentation for data download script.
335dd532b7c6c3bfce18680ed4c0e7ffd12a9a9b
<ide><path>official/recommendation/README.md <ide> In both datasets, the timestamp is represented in seconds since midnight Coordin <ide> ### Download and preprocess dataset <ide> To download the dataset, please install Pandas package first. Then issue the following command: <ide> ``` <del>python data_download.py <add>python movielens_dataset.py <ide> ``` <ide> Arguments: <ide> * `--data_dir`: Directory where to download and save the preprocessed data. By default, it is `/tmp/movielens-data/`.
1
PHP
PHP
add unit test for debugsecurity param
2c0cebf5833216d84653606073b25acfff3e4a32
<ide><path>src/View/Helper/FormHelper.php <ide> public function secure(array $fields = [], array $secureAttributes = []) <ide> if (empty($this->request['_Token'])) { <ide> return null; <ide> } <del> $debugSecurity = Hash::get($secureAttributes, 'debugSecurity') ?: Configure::read('debug'); <del> unset($secureAttributes['debugSecurity']); <add> $debugSecurity = Configure::read('debug'); <add> if (isset($secureAttributes['debugSecurity'])) { <add> $debugSecurity = $secureAttributes['debugSecurity']; <add> unset($secureAttributes['debugSecurity']); <add> } <ide> <ide> $tokenData = $this->_buildFieldToken( <ide> $this->_lastAction, <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testFormSecurityInputUnlockedFields() <ide> $this->assertHtml($expected, $result); <ide> } <ide> <add> /** <add> * testFormSecurityInputUnlockedFieldsDebugSecurityTrue method <add> * <add> * Test single record form with debugSecurity param. <add> * <add> * @return void <add> */ <add> public function testFormSecurityInputUnlockedFieldsDebugSecurityTrue() <add> { <add> $this->Form->request['_Token'] = [ <add> 'unlockedFields' => ['first_name', 'address'] <add> ]; <add> $this->Form->create(); <add> $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField()); <add> <add> $this->Form->hidden('Addresses.id', ['value' => '123456']); <add> $this->Form->text('Addresses.title'); <add> $this->Form->text('Addresses.first_name'); <add> $this->Form->text('Addresses.last_name'); <add> $this->Form->text('Addresses.address'); <add> $this->Form->text('Addresses.city'); <add> $this->Form->text('Addresses.phone'); <add> <add> $result = $this->Form->fields; <add> $expected = [ <add> 'Addresses.id' => '123456', 'Addresses.title', 'Addresses.last_name', <add> 'Addresses.city', 'Addresses.phone' <add> ]; <add> $this->assertEquals($expected, $result); <add> $debug = Configure::read('debug'); <add> Configure::write('debug', false); <add> $result = $this->Form->secure($expected, ['data-foo' => 'bar', 'debugSecurity' => true]); <add> Configure::write('debug', $debug); <add> <add> $hash = 'a303becbdd99cb42ca14a1cf7e63dfd48696a3c5%3AAddresses.id'; <add> $tokenDebug = urlencode(json_encode([ <add> '/articles/add', <add> [ <add> 'Addresses.id' => '123456', <add> 'Addresses.title', <add> 'Addresses.last_name', <add> 'Addresses.city', <add> 'Addresses.phone' <add> ], <add> [ <add> 'first_name', <add> 'address' <add> ] <add> ])); <add> <add> $expected = [ <add> 'div' => ['style' => 'display:none;'], <add> ['input' => [ <add> 'type' => 'hidden', <add> 'name' => '_Token[fields]', <add> 'value' => $hash, <add> 'data-foo' => 'bar', <add> ]], <add> ['input' => [ <add> 'type' => 'hidden', <add> 'name' => '_Token[unlocked]', <add> 'value' => 'address%7Cfirst_name', <add> 'data-foo' => 'bar', <add> ]], <add> ['input' => [ <add> 'type' => 'hidden', 'name' => '_Token[debug]', <add> 'value' => $tokenDebug, <add> 'data-foo' => 'bar' <add> ]], <add> '/div' <add> ]; <add> $this->assertHtml($expected, $result); <add> } <add> <add> /** <add> * testFormSecurityInputUnlockedFieldsDebugSecurityFalse method <add> * <add> * Test single record form with debugSecurity param. <add> * <add> * @return void <add> */ <add> public function testFormSecurityInputUnlockedFieldsDebugSecurityFalse() <add> { <add> $this->Form->request['_Token'] = [ <add> 'unlockedFields' => ['first_name', 'address'] <add> ]; <add> $this->Form->create(); <add> $this->assertEquals($this->Form->request['_Token']['unlockedFields'], $this->Form->unlockField()); <add> <add> $this->Form->hidden('Addresses.id', ['value' => '123456']); <add> $this->Form->text('Addresses.title'); <add> $this->Form->text('Addresses.first_name'); <add> $this->Form->text('Addresses.last_name'); <add> $this->Form->text('Addresses.address'); <add> $this->Form->text('Addresses.city'); <add> $this->Form->text('Addresses.phone'); <add> <add> $result = $this->Form->fields; <add> $expected = [ <add> 'Addresses.id' => '123456', 'Addresses.title', 'Addresses.last_name', <add> 'Addresses.city', 'Addresses.phone' <add> ]; <add> $this->assertEquals($expected, $result); <add> <add> $debug = Configure::read('debug'); <add> Configure::write('debug', true); <add> $result = $this->Form->secure($expected, ['data-foo' => 'bar', 'debugSecurity' => false]); <add> Configure::write('debug', $debug); <add> <add> $hash = 'a303becbdd99cb42ca14a1cf7e63dfd48696a3c5%3AAddresses.id'; <add> <add> $expected = [ <add> 'div' => ['style' => 'display:none;'], <add> ['input' => [ <add> 'type' => 'hidden', <add> 'name' => '_Token[fields]', <add> 'value' => $hash, <add> 'data-foo' => 'bar', <add> ]], <add> ['input' => [ <add> 'type' => 'hidden', <add> 'name' => '_Token[unlocked]', <add> 'value' => 'address%7Cfirst_name', <add> 'data-foo' => 'bar', <add> ]], <add> '/div' <add> ]; <add> <add> $this->assertHtml($expected, $result); <add> } <add> <ide> /** <ide> * test securing inputs with custom name attributes. <ide> *
2
PHP
PHP
add exceptions for http client as per psr 18
da53acca8b65ee6de8e7d6315ee77fb50d1d1c59
<ide><path>src/Http/Client/Adapter/Curl.php <ide> namespace Cake\Http\Client\Adapter; <ide> <ide> use Cake\Http\Client\AdapterInterface; <add>use Cake\Http\Client\Exception\RequestException; <add>use Cake\Http\Client\Exception\NetworkException; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <del>use Cake\Http\Exception\HttpException; <ide> use Composer\CaBundle\CaBundle; <ide> use Psr\Http\Message\RequestInterface; <ide> <ide> public function send(RequestInterface $request, array $options): array <ide> $error = curl_error($ch); <ide> curl_close($ch); <ide> <del> $status = 500; <del> if ($errorCode === CURLE_OPERATION_TIMEOUTED) { <del> $status = 504; <add> $message = "cURL Error ({$errorCode}) {$error}"; <add> $errorNumbers = [ <add> CURLE_FAILED_INIT, <add> CURLE_URL_MALFORMAT, <add> CURLE_URL_MALFORMAT_USER, <add> ]; <add> if (in_array($errorCode, $errorNumbers, true)) { <add> throw new RequestException($message, $request); <ide> } <del> throw new HttpException("cURL Error ({$errorCode}) {$error}", $status); <add> throw new NetworkException($message, $request); <ide> } <ide> <ide> $responses = $this->createResponse($ch, $body); <ide><path>src/Http/Client/Adapter/Stream.php <ide> namespace Cake\Http\Client\Adapter; <ide> <ide> use Cake\Core\Exception\Exception; <add>use Cake\Http\Client\Exception\RequestException; <add>use Cake\Http\Client\Exception\NetworkException; <ide> use Cake\Http\Client\AdapterInterface; <ide> use Cake\Http\Client\Response; <del>use Cake\Http\Exception\HttpException; <ide> use Composer\CaBundle\CaBundle; <ide> use Psr\Http\Message\RequestInterface; <ide> <ide> protected function _buildSslContext(RequestInterface $request, array $options): <ide> * <ide> * @param \Psr\Http\Message\RequestInterface $request The request object. <ide> * @return array Array of populated Response objects <del> * @throws \Cake\Http\Exception\HttpException <add> * @throws \Psr\Http\Client\NetworkExceptionInterface <ide> */ <ide> protected function _send(RequestInterface $request): array <ide> { <ide> protected function _send(RequestInterface $request): array <ide> } <ide> <ide> $url = $request->getUri(); <del> $this->_open((string)$url); <add> $this->_open((string)$url, $request); <ide> $content = ''; <ide> $timedOut = false; <ide> <ide> protected function _send(RequestInterface $request): array <ide> fclose($this->_stream); <ide> <ide> if ($timedOut) { <del> throw new HttpException('Connection timed out ' . $url, 504); <add> throw new NetworkException('Connection timed out ' . $url, $request); <ide> } <ide> <ide> $headers = $meta['wrapper_data']; <ide> protected function _buildResponse(array $headers, string $body): Response <ide> * Open the socket and handle any connection errors. <ide> * <ide> * @param string $url The url to connect to. <add> * @param \Psr\Http\Message\RequestInterface $request The request object. <ide> * @return void <del> * @throws \Cake\Core\Exception\Exception <add> * @throws \Psr\Http\Client\RequestExceptionInterface <ide> */ <del> protected function _open(string $url): void <add> protected function _open(string $url, RequestInterface $request): void <ide> { <ide> set_error_handler(function ($code, $message) { <ide> $this->_connectionErrors[] = $message; <ide> protected function _open(string $url): void <ide> } <ide> <ide> if (!$this->_stream || !empty($this->_connectionErrors)) { <del> throw new Exception(implode("\n", $this->_connectionErrors)); <add> throw new RequestException(implode("\n", $this->_connectionErrors), $request); <ide> } <ide> } <ide> <ide><path>src/Http/Client/Exception/NetworkException.php <add><?php <add>declare(strict_types=1); <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> * 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 4.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Http\Client\Exception; <add> <add>use Psr\Http\Client\NetworkExceptionInterface; <add> <add>/** <add> * Thrown when the request cannot be completed because of network issues. <add> * <add> * There is no response object as this exception is thrown when no response has been received. <add> * <add> * Example: the target host name can not be resolved or the connection failed. <add> */ <add>class NetworkException extends RequestException implements NetworkExceptionInterface <add>{ <add>} <ide><path>src/Http/Client/Exception/RequestException.php <add><?php <add>declare(strict_types=1); <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> * 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 4.0.0 <add> * @license https://opensource.org/licenses/mit-license.php MIT License <add> */ <add>namespace Cake\Http\Client\Exception; <add> <add>use Exception; <add>use Psr\Http\Client\RequestExceptionInterface; <add>use Psr\Http\Message\RequestInterface; <add>use RuntimeException; <add> <add>/** <add> * Exception for when a request failed. <add> * <add> * Examples: <add> * - Request is invalid (e.g. method is missing) <add> * - Runtime request errors (e.g. the body stream is not seekable) <add> */ <add>class RequestException extends RuntimeException implements RequestExceptionInterface <add>{ <add> /** <add> * @var \Psr\Http\Message\RequestInterface <add> */ <add> protected $request; <add> <add> /** <add> * @param string $message <add> * @param \Psr\Http\Message\RequestInterface $request <add> * <add> * @param \Exception|null $previous <add> */ <add> public function __construct($message, RequestInterface $request, Exception $previous = null) <add> { <add> $this->request = $request; <add> parent::__construct($message, 0, $previous); <add> } <add> <add> /** <add> * Returns the request. <add> * <add> * The request object MAY be a different object from the one passed to ClientInterface::sendRequest() <add> * <add> * @return \Psr\Http\Message\RequestInterface <add> */ <add> public function getRequest(): RequestInterface <add> { <add> return $this->request; <add> } <add>} <ide><path>tests/TestCase/Http/Client/Adapter/CurlTest.php <ide> namespace Cake\Test\TestCase\Http\Client\Adapter; <ide> <ide> use Cake\Http\Client\Adapter\Curl; <add>use Cake\Http\Client\Exception\NetworkException; <ide> use Cake\Http\Client\Request; <ide> use Cake\Http\Client\Response; <ide> use Cake\TestSuite\TestCase; <ide> public function testBuildOptionsCurlOptions() <ide> ]; <ide> $this->assertSame($expected, $result); <ide> } <add> <add> /** <add> * Test that an exception is raised when timed out. <add> * <add> * @return void <add> */ <add> public function testNetworkException() <add> { <add> $this->expectException(NetworkException::class); <add> $this->expectExceptionMessage('cURL Error (6) Could not resolve host: dummy'); <add> $request = new Request('http://dummy/?sleep'); <add> $options = [ <add> 'timeout' => 2, <add> ]; <add> <add> $this->curl->send($request, $options); <add> } <ide> } <ide><path>tests/TestCase/Http/Client/Adapter/StreamTest.php <ide> public function testKeepDeadline() <ide> */ <ide> public function testMissDeadline() <ide> { <del> $this->expectException(\Cake\Http\Exception\HttpException::class); <add> $this->expectException(\Cake\Http\Client\Exception\NetworkException::class); <ide> $this->expectExceptionMessage('Connection timed out http://dummy/?sleep'); <ide> $request = new Request('http://dummy/?sleep'); <ide> $options = [
6
Java
Java
add doondiscard hook for streaming mode
77a562dfee04cfb4a76a84257cf33fd73ab6b696
<ide><path>spring-web/src/main/java/org/springframework/http/codec/EncoderHttpMessageWriter.java <ide> public Mono<Void> write(Publisher<? extends T> inputStream, ResolvableType eleme <ide> } <ide> <ide> if (isStreamingMediaType(contentType)) { <del> return message.writeAndFlushWith(body.map(buffer -> { <del> Hints.touchDataBuffer(buffer, hints, logger); <del> return Mono.just(buffer).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); <del> })); <add> return message <add> .writeAndFlushWith(body.map(buffer -> { <add> Hints.touchDataBuffer(buffer, hints, logger); <add> return Mono.just(buffer).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); <add> })) <add> .doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); <ide> } <ide> <ide> if (logger.isDebugEnabled()) { <ide> body = body.doOnNext(buffer -> Hints.touchDataBuffer(buffer, hints, logger)); <ide> } <del> return message.writeWith(body); <add> return message.writeWith(body).doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release); <ide> } <ide> <ide> @Nullable
1
Javascript
Javascript
remove jslint comments
553dd90528f38e281c24829c8bd351a8b94f4a68
<ide><path>src/browser/__tests__/ReactDOM-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var React = require('React'); <ide><path>src/browser/__tests__/ReactDOMSVG-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var React; <ide><path>src/browser/__tests__/ReactWebWorker-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> describe('ReactWebWorker', function() { <ide><path>src/browser/eventPlugins/__tests__/EnterLeaveEventPlugin-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var EnterLeaveEventPlugin; <ide><path>src/browser/server/__tests__/ReactServerRendering-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> require('mock-modules') <ide><path>src/browser/ui/ReactComponentBrowserEnvironment.js <ide> * @providesModule ReactComponentBrowserEnvironment <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var ReactDOMIDOperations = require('ReactDOMIDOperations'); <ide><path>src/browser/ui/ReactDOMIDOperations.js <ide> * @typechecks static-only <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var CSSPropertyOperations = require('CSSPropertyOperations'); <ide><path>src/browser/ui/__tests__/ReactDOMComponent-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var assign = require('Object.assign'); <ide><path>src/browser/ui/__tests__/ReactDOMIDOperations-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> describe('ReactDOMIDOperations', function() { <ide><path>src/browser/ui/__tests__/ReactRenderDocument-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var React; <ide><path>src/browser/ui/dom/DOMProperty.js <ide> * @typechecks static-only <ide> */ <ide> <del>/*jslint bitwise: true */ <del> <ide> 'use strict'; <ide> <ide> var invariant = require('invariant'); <ide><path>src/browser/ui/dom/Danger.js <ide> * @typechecks static-only <ide> */ <ide> <del>/*jslint evil: true, sub: true */ <del> <ide> 'use strict'; <ide> <ide> var ExecutionEnvironment = require('ExecutionEnvironment'); <ide><path>src/browser/ui/dom/HTMLDOMPropertyConfig.js <ide> * @providesModule HTMLDOMPropertyConfig <ide> */ <ide> <del>/*jslint bitwise: true*/ <del> <ide> 'use strict'; <ide> <ide> var DOMProperty = require('DOMProperty'); <ide><path>src/browser/ui/dom/SVGDOMPropertyConfig.js <ide> * @providesModule SVGDOMPropertyConfig <ide> */ <ide> <del>/*jslint bitwise: true*/ <del> <ide> 'use strict'; <ide> <ide> var DOMProperty = require('DOMProperty'); <ide><path>src/browser/ui/dom/__tests__/CSSProperty-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> describe('CSSProperty', function() { <ide><path>src/browser/ui/dom/__tests__/CSSPropertyOperations-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var React = require('React'); <ide><path>src/browser/ui/dom/__tests__/Danger-test.js <ide> * <ide> * @emails react-core <ide> */ <del>/*jslint evil: true */ <ide> <ide> 'use strict'; <ide> <ide><path>src/browser/ui/dom/__tests__/getNodeForCharacterOffset-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> var getTestDocument = require('getTestDocument'); <ide><path>src/core/__tests__/ReactMultiChildText-test.js <ide> * @emails react-core <ide> */ <ide> <del>/*jslint evil: true */ <del> <ide> 'use strict'; <ide> <ide> require('mock-modules'); <ide><path>src/utils/adler32.js <ide> * @providesModule adler32 <ide> */ <ide> <del>/* jslint bitwise:true */ <del> <ide> 'use strict'; <ide> <ide> var MOD = 65521;
20
Python
Python
test no reuse of non-existing buffers in nditer
1e6d6e6272a1ca83c8e45d33c50268cfa4b32511
<ide><path>numpy/core/tests/test_nditer.py <ide> def test_iter_buffered_reduce_reuse(): <ide> a = np.arange(2*3**5)[3**5:3**5+1] <ide> flags = ['buffered', 'delay_bufalloc', 'multi_index', 'reduce_ok', 'refs_ok'] <ide> op_flags = [('readonly',), ('readwrite','allocate')] <del> op_axes = [(0,1,2), (0,1,-1)] <add> op_axes_list = [[(0,1,2), (0,1,-1)], [(0,1,2), (0,-1,-1)]] <ide> # wrong dtype to force buffering <ide> op_dtypes = [np.float, a.dtype] <ide> <ide> def get_params(): <ide> for xs in xrange(-3**2, 3**2 + 1): <ide> for ys in xrange(xs, 3**2 + 1): <del> # last stride is reduced and because of that not <del> # important for this test, as it is the inner stride. <del> strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize) <del> arr = np.lib.stride_tricks.as_strided(a, (3,3,3), strides) <del> <del> for bufsize in xrange(0, 3**3): <add> for op_axes in op_axes_list: <add> # last stride is reduced and because of that not <add> # important for this test, as it is the inner stride. <add> strides = (xs * a.itemsize, ys * a.itemsize, a.itemsize) <add> arr = np.lib.stride_tricks.as_strided(a, (3,3,3), strides) <add> <ide> for skip in [0, 1]: <del> yield arr, bufsize, skip <add> yield arr, op_axes, skip <ide> <del> for arr, bufsize, skip in get_params(): <del> nditer1 = np.nditer([arr, None], <del> op_axes=op_axes, flags=flags, op_flags=op_flags, <del> buffersize=bufsize, op_dtypes=op_dtypes) <del> nditer1.operands[-1][...] = 0 <del> nditer1.reset() <del> nditer1.iterindex = skip <del> <del> for (a1_in, b1_in) in nditer1: <del> b1_in += a1_in.astype(np.int_) <del> <add> for arr, op_axes, skip in get_params(): <ide> nditer2 = np.nditer([arr.copy(), None], <ide> op_axes=op_axes, flags=flags, op_flags=op_flags, <ide> op_dtypes=op_dtypes) <ide> def get_params(): <ide> for (a2_in, b2_in) in nditer2: <ide> b2_in += a2_in.astype(np.int_) <ide> <del> res = nditer1.operands[-1] <ide> comp_res = nditer2.operands[-1] <ide> <del> assert_array_equal(res, comp_res) <add> for bufsize in xrange(0, 3**3): <add> nditer1 = np.nditer([arr, None], <add> op_axes=op_axes, flags=flags, op_flags=op_flags, <add> buffersize=bufsize, op_dtypes=op_dtypes) <add> nditer1.operands[-1][...] = 0 <add> nditer1.reset() <add> nditer1.iterindex = skip <add> <add> for (a1_in, b1_in) in nditer1: <add> b1_in += a1_in.astype(np.int_) <add> <add> res = nditer1.operands[-1] <add> assert_array_equal(res, comp_res) <ide> <ide> <ide> def test_iter_no_broadcast():
1
Python
Python
fix an undefined name in a test
c758839239626a2acc1884f58e9e3eb7c9177cb6
<ide><path>numpy/core/tests/test_numeric.py <ide> def test_clip_scalar_nan_propagation(self, arr, amin, amax): <ide> def test_NaT_propagation(self, arr, amin, amax): <ide> # NOTE: the expected function spec doesn't <ide> # propagate NaT, but clip() now does <del> expected = np.minimum(np.maximum(a, amin), amax) <add> expected = np.minimum(np.maximum(arr, amin), amax) <ide> actual = np.clip(arr, amin, amax) <ide> assert_equal(actual, expected) <ide>
1
Python
Python
correct a bug on batinfo __init__ function
ca2b55ff6f6f3df616d9170a8f9269730a83548d
<ide><path>glances/glances.py <ide> def __init__(self): <ide> if batinfo_lib_tag: <ide> try: <ide> self.bat = batinfo.batteries() <add> self.initok = True <add> self.__update__() <ide> except: <ide> self.initok = False <ide> else: <del> self.initok = True <del> self.__update__() <add> self.initok = False <ide> <ide> def __update__(self): <ide> """
1
Ruby
Ruby
improve formula name guessing
99bb068ca734c7096bf82c72730f1babc7f72431
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb <ide> def bump_formula_pr <ide> <ide> new_url = ARGV.value("url") <ide> if new_url && !formula <del> is_devel = ARGV.include?("--devel") <del> base_url = new_url.split("/")[0..4].join("/") <add> # Split the new URL on / and find any formulae that have the same URL <add> # except for the last component, but don't try to match any more than the <add> # first five components since sometimes the last component isn't the only <add> # one to change. <add> new_url_split = new_url.split("/") <add> maximum_url_components_to_match = 5 <add> components_to_match = [new_url_split.count - 1, maximum_url_components_to_match].min <add> base_url = new_url_split.first(components_to_match).join("/") <ide> base_url = /#{Regexp.escape(base_url)}/ <add> is_devel = ARGV.include?("--devel") <ide> guesses = [] <ide> Formula.each do |f| <ide> if is_devel && f.devel && f.devel.url && f.devel.url.match(base_url)
1
Javascript
Javascript
add test of cleartextstream.getcipher() in tls
8727e5f2becfa538d0f2f5f48172fd0d1c902546
<ide><path>test/simple/test-tls-getcipher.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>var common = require('../common'); <add>var assert = require('assert'); <add>var tls = require('tls'); <add>var fs = require('fs'); <add>var cipher_list = ['RC4-SHA', 'AES256-SHA']; <add>var cipher_version_pattern = /TLS|SSL/; <add>var options = { <add> key: fs.readFileSync(common.fixturesDir + '/keys/agent2-key.pem'), <add> cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem'), <add> ciphers: cipher_list.join(':'), <add> honorCipherOrder: true <add>}; <add> <add>var nconns = 0; <add> <add>process.on('exit', function() { <add> assert.equal(nconns, 1); <add>}); <add> <add>var server = tls.createServer(options, function(cleartextStream) { <add> nconns++; <add>}); <add> <add>server.listen(common.PORT, '127.0.0.1', function() { <add> var client = tls.connect(common.PORT, '127.0.0.1', function() { <add> var cipher = client.getCipher(); <add> assert.equal(cipher.name, cipher_list[0]); <add> assert(cipher_version_pattern.test(cipher.version)); <add> client.end(); <add> server.close(); <add> }); <add>});
1
Python
Python
update albert with tf decorator
37793259bb0201622b87c1a630cd16806d99897d
<ide><path>src/transformers/models/albert/modeling_tf_albert.py <ide> TFSequenceClassificationLoss, <ide> TFTokenClassificationLoss, <ide> get_initializer, <del> input_processing, <ide> keras_serializable, <add> unpack_inputs, <ide> ) <ide> from ...tf_utils import shape_list <ide> from ...utils import logging <ide> class PreTrainedModel <ide> """ <ide> raise NotImplementedError <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> input_ids: Optional[TFModelInputType] = None, <ide> def call( <ide> training: bool = False, <ide> **kwargs, <ide> ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]: <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <del> attention_mask=attention_mask, <del> token_type_ids=token_type_ids, <del> position_ids=position_ids, <del> head_mask=head_mask, <del> inputs_embeds=inputs_embeds, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if inputs["input_ids"] is not None and inputs["inputs_embeds"] is not None: <add> if input_ids is not None and inputs_embeds is not None: <ide> raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") <del> elif inputs["input_ids"] is not None: <del> input_shape = shape_list(inputs["input_ids"]) <del> elif inputs["inputs_embeds"] is not None: <del> input_shape = shape_list(inputs["inputs_embeds"])[:-1] <add> elif input_ids is not None: <add> input_shape = shape_list(input_ids) <add> elif inputs_embeds is not None: <add> input_shape = shape_list(inputs_embeds)[:-1] <ide> else: <ide> raise ValueError("You have to specify either input_ids or inputs_embeds") <ide> <del> if inputs["attention_mask"] is None: <del> inputs["attention_mask"] = tf.fill(dims=input_shape, value=1) <add> if attention_mask is None: <add> attention_mask = tf.fill(dims=input_shape, value=1) <ide> <del> if inputs["token_type_ids"] is None: <del> inputs["token_type_ids"] = tf.fill(dims=input_shape, value=0) <add> if token_type_ids is None: <add> token_type_ids = tf.fill(dims=input_shape, value=0) <ide> <ide> embedding_output = self.embeddings( <del> input_ids=inputs["input_ids"], <del> position_ids=inputs["position_ids"], <del> token_type_ids=inputs["token_type_ids"], <del> inputs_embeds=inputs["inputs_embeds"], <del> training=inputs["training"], <add> input_ids=input_ids, <add> position_ids=position_ids, <add> token_type_ids=token_type_ids, <add> inputs_embeds=inputs_embeds, <add> training=training, <ide> ) <ide> <ide> # We create a 3D attention mask from a 2D tensor mask. <ide> # Sizes are [batch_size, 1, 1, to_seq_length] <ide> # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length] <ide> # this attention mask is more simple than the triangular masking of causal attention <ide> # used in OpenAI GPT, we just need to prepare the broadcast dimension here. <del> extended_attention_mask = tf.reshape(inputs["attention_mask"], (input_shape[0], 1, 1, input_shape[1])) <add> extended_attention_mask = tf.reshape(attention_mask, (input_shape[0], 1, 1, input_shape[1])) <ide> <ide> # Since attention_mask is 1.0 for positions we want to attend and 0.0 for <ide> # masked positions, this operation will create a tensor which is 0.0 for <ide> def call( <ide> # attention_probs has shape bsz x n_heads x N x N <ide> # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] <ide> # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] <del> if inputs["head_mask"] is not None: <add> if head_mask is not None: <ide> raise NotImplementedError <ide> else: <del> inputs["head_mask"] = [None] * self.config.num_hidden_layers <add> head_mask = [None] * self.config.num_hidden_layers <ide> <ide> encoder_outputs = self.encoder( <ide> hidden_states=embedding_output, <ide> attention_mask=extended_attention_mask, <del> head_mask=inputs["head_mask"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> head_mask=head_mask, <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> <ide> sequence_output = encoder_outputs[0] <ide> pooled_output = self.pooler(inputs=sequence_output[:, 0]) if self.pooler is not None else None <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> return ( <ide> sequence_output, <ide> pooled_output, <ide> def __init__(self, config: AlbertConfig, *inputs, **kwargs): <ide> <ide> self.albert = TFAlbertMainLayer(config, name="albert") <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> training: Optional[bool] = False, <ide> **kwargs, <ide> ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor]]: <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> outputs = self.albert( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> token_type_ids=token_type_ids, <ide> def call( <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.albert( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> token_type_ids=inputs["token_type_ids"], <del> position_ids=inputs["position_ids"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> return outputs <ide> def __init__(self, config: AlbertConfig, *inputs, **kwargs): <ide> def get_lm_head(self) -> tf.keras.layers.Layer: <ide> return self.predictions <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @replace_return_docstrings(output_type=TFAlbertForPreTrainingOutput, config_class=_CONFIG_FOR_DOC) <ide> def call( <ide> def call( <ide> >>> sop_logits = outputs.sop_logits <ide> ```""" <ide> <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> outputs = self.albert( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> token_type_ids=token_type_ids, <ide> def call( <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> labels=labels, <del> sentence_order_label=sentence_order_label, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.albert( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> token_type_ids=inputs["token_type_ids"], <del> position_ids=inputs["position_ids"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> sequence_output, pooled_output = outputs[:2] <ide> prediction_scores = self.predictions(hidden_states=sequence_output) <del> sop_scores = self.sop_classifier(pooled_output=pooled_output, training=inputs["training"]) <add> sop_scores = self.sop_classifier(pooled_output=pooled_output, training=training) <ide> total_loss = None <ide> <del> if inputs["labels"] is not None and inputs["sentence_order_label"] is not None: <del> d_labels = {"labels": inputs["labels"]} <del> d_labels["sentence_order_label"] = inputs["sentence_order_label"] <add> if labels is not None and sentence_order_label is not None: <add> d_labels = {"labels": labels} <add> d_labels["sentence_order_label"] = sentence_order_label <ide> total_loss = self.hf_compute_loss(labels=d_labels, logits=(prediction_scores, sop_scores)) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (prediction_scores, sop_scores) + outputs[2:] <ide> return ((total_loss,) + output) if total_loss is not None else output <ide> <ide> def __init__(self, config: AlbertConfig, *inputs, **kwargs): <ide> def get_lm_head(self) -> tf.keras.layers.Layer: <ide> return self.predictions <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the <ide> loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> outputs = self.albert( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> token_type_ids=token_type_ids, <ide> def call( <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> labels=labels, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.albert( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> token_type_ids=inputs["token_type_ids"], <del> position_ids=inputs["position_ids"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> sequence_output = outputs[0] <del> prediction_scores = self.predictions(hidden_states=sequence_output, training=inputs["training"]) <del> loss = ( <del> None <del> if inputs["labels"] is None <del> else self.hf_compute_loss(labels=inputs["labels"], logits=prediction_scores) <del> ) <add> prediction_scores = self.predictions(hidden_states=sequence_output, training=training) <add> loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=prediction_scores) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (prediction_scores,) + outputs[2:] <ide> <ide> return ((loss,) + output) if loss is not None else output <ide> def __init__(self, config: AlbertConfig, *inputs, **kwargs): <ide> units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier" <ide> ) <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If <ide> `config.num_labels > 1` a classification loss is computed (Cross-Entropy). <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> outputs = self.albert( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> token_type_ids=token_type_ids, <ide> def call( <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> labels=labels, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.albert( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> token_type_ids=inputs["token_type_ids"], <del> position_ids=inputs["position_ids"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> pooled_output = outputs[1] <del> pooled_output = self.dropout(inputs=pooled_output, training=inputs["training"]) <add> pooled_output = self.dropout(inputs=pooled_output, training=training) <ide> logits = self.classifier(inputs=pooled_output) <del> loss = None if inputs["labels"] is None else self.hf_compute_loss(labels=inputs["labels"], logits=logits) <add> loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (logits,) + outputs[2:] <ide> <ide> return ((loss,) + output) if loss is not None else output <ide> def __init__(self, config: AlbertConfig, *inputs, **kwargs): <ide> units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="classifier" <ide> ) <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> labels (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*): <ide> Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> outputs = self.albert( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> token_type_ids=token_type_ids, <ide> def call( <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> labels=labels, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.albert( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> token_type_ids=inputs["token_type_ids"], <del> position_ids=inputs["position_ids"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=return_dict, <del> training=inputs["training"], <ide> ) <ide> sequence_output = outputs[0] <del> sequence_output = self.dropout(inputs=sequence_output, training=inputs["training"]) <add> sequence_output = self.dropout(inputs=sequence_output, training=training) <ide> logits = self.classifier(inputs=sequence_output) <del> loss = None if inputs["labels"] is None else self.hf_compute_loss(labels=inputs["labels"], logits=logits) <add> loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=logits) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (logits,) + outputs[2:] <ide> <ide> return ((loss,) + output) if loss is not None else output <ide> def __init__(self, config: AlbertConfig, *inputs, **kwargs): <ide> units=config.num_labels, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs" <ide> ) <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence <ide> are not taken into account for computing the loss. <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> outputs = self.albert( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> token_type_ids=token_type_ids, <ide> def call( <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> start_positions=start_positions, <del> end_positions=end_positions, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> outputs = self.albert( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> token_type_ids=inputs["token_type_ids"], <del> position_ids=inputs["position_ids"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> sequence_output = outputs[0] <ide> logits = self.qa_outputs(inputs=sequence_output) <ide> def call( <ide> end_logits = tf.squeeze(input=end_logits, axis=-1) <ide> loss = None <ide> <del> if inputs["start_positions"] is not None and inputs["end_positions"] is not None: <del> labels = {"start_position": inputs["start_positions"]} <del> labels["end_position"] = inputs["end_positions"] <add> if start_positions is not None and end_positions is not None: <add> labels = {"start_position": start_positions} <add> labels["end_position"] = end_positions <ide> loss = self.hf_compute_loss(labels=labels, logits=(start_logits, end_logits)) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (start_logits, end_logits) + outputs[2:] <ide> <ide> return ((loss,) + output) if loss is not None else output <ide> def dummy_inputs(self): <ide> """ <ide> return {"input_ids": tf.constant(MULTIPLE_CHOICE_DUMMY_INPUTS)} <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(ALBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., num_choices]` <ide> where `num_choices` is the size of the second dimension of the input tensors. (See `input_ids` above) <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <del> attention_mask=attention_mask, <del> token_type_ids=token_type_ids, <del> position_ids=position_ids, <del> head_mask=head_mask, <del> inputs_embeds=inputs_embeds, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> labels=labels, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if inputs["input_ids"] is not None: <del> num_choices = shape_list(inputs["input_ids"])[1] <del> seq_length = shape_list(inputs["input_ids"])[2] <add> if input_ids is not None: <add> num_choices = shape_list(input_ids)[1] <add> seq_length = shape_list(input_ids)[2] <ide> else: <del> num_choices = shape_list(inputs["inputs_embeds"])[1] <del> seq_length = shape_list(inputs["inputs_embeds"])[2] <add> num_choices = shape_list(inputs_embeds)[1] <add> seq_length = shape_list(inputs_embeds)[2] <ide> <del> flat_input_ids = tf.reshape(inputs["input_ids"], (-1, seq_length)) if inputs["input_ids"] is not None else None <add> flat_input_ids = tf.reshape(input_ids, (-1, seq_length)) if input_ids is not None else None <ide> flat_attention_mask = ( <del> tf.reshape(tensor=inputs["attention_mask"], shape=(-1, seq_length)) <del> if inputs["attention_mask"] is not None <del> else None <add> tf.reshape(tensor=attention_mask, shape=(-1, seq_length)) if attention_mask is not None else None <ide> ) <ide> flat_token_type_ids = ( <del> tf.reshape(tensor=inputs["token_type_ids"], shape=(-1, seq_length)) <del> if inputs["token_type_ids"] is not None <del> else None <add> tf.reshape(tensor=token_type_ids, shape=(-1, seq_length)) if token_type_ids is not None else None <ide> ) <ide> flat_position_ids = ( <ide> tf.reshape(tensor=position_ids, shape=(-1, seq_length)) if position_ids is not None else None <ide> ) <ide> flat_inputs_embeds = ( <del> tf.reshape(tensor=inputs["inputs_embeds"], shape=(-1, seq_length, shape_list(inputs["inputs_embeds"])[3])) <del> if inputs["inputs_embeds"] is not None <add> tf.reshape(tensor=inputs_embeds, shape=(-1, seq_length, shape_list(inputs_embeds)[3])) <add> if inputs_embeds is not None <ide> else None <ide> ) <ide> outputs = self.albert( <ide> input_ids=flat_input_ids, <ide> attention_mask=flat_attention_mask, <ide> token_type_ids=flat_token_type_ids, <ide> position_ids=flat_position_ids, <del> head_mask=inputs["head_mask"], <add> head_mask=head_mask, <ide> inputs_embeds=flat_inputs_embeds, <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> pooled_output = outputs[1] <del> pooled_output = self.dropout(inputs=pooled_output, training=inputs["training"]) <add> pooled_output = self.dropout(inputs=pooled_output, training=training) <ide> logits = self.classifier(inputs=pooled_output) <ide> reshaped_logits = tf.reshape(tensor=logits, shape=(-1, num_choices)) <del> loss = ( <del> None if inputs["labels"] is None else self.hf_compute_loss(labels=inputs["labels"], logits=reshaped_logits) <del> ) <add> loss = None if labels is None else self.hf_compute_loss(labels=labels, logits=reshaped_logits) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (reshaped_logits,) + outputs[2:] <ide> return ((loss,) + output) if loss is not None else output <ide>
1
Ruby
Ruby
add tests for named methods
74c101025616c98bc5774a9a84a7c34311c886d1
<ide><path>Library/Homebrew/cli/parser.rb <ide> def check_constraint_violations <ide> def check_named_args(args) <ide> exception = if @min_named_args && args.size < @min_named_args <ide> if @named_args_type.present? <del> types = @named_args_type.is_a?(Array) ? @named_args_type : [@named_args_type] <add> types = Array(@named_args_type) <ide> if types.any? { |arg| arg.is_a? String } <ide> MinNamedArgumentsError.new(@min_named_args) <ide> else <ide><path>Library/Homebrew/test/cli/parser_spec.rb <ide> expect(args.named).to be_empty <ide> end <ide> end <add> <add> describe "named_args" do <add> let(:parser_none) { <add> described_class.new do <add> named_args :none <add> end <add> } <add> let(:parser_number) { <add> described_class.new do <add> named_args number: 1 <add> end <add> } <add> <add> it "doesn't allow :none passed with a number" do <add> expect do <add> described_class.new do <add> named_args :none, number: 1 <add> end <add> end.to raise_error(ArgumentError, /Do not specify both `number`, `min` or `max` with `named_args :none`/) <add> end <add> <add> it "doesn't allow number and min" do <add> expect do <add> described_class.new do <add> named_args number: 1, min: 1 <add> end <add> end.to raise_error(ArgumentError, /Do not specify both `number` and `min` or `max`/) <add> end <add> <add> it "doesn't accept fewer than the passed number of arguments" do <add> expect { parser_number.parse([]) }.to raise_error(Homebrew::CLI::MinNamedArgumentsError) <add> end <add> <add> it "doesn't accept more than the passed number of arguments" do <add> expect { parser_number.parse(["foo", "bar"]) }.to raise_error(Homebrew::CLI::MaxNamedArgumentsError) <add> end <add> <add> it "accepts the passed number of arguments" do <add> expect { parser_number.parse(["foo"]) }.not_to raise_error <add> end <add> <add> it "doesn't accept any arguments with :none" do <add> expect { parser_none.parse(["foo"]) } <add> .to raise_error(Homebrew::CLI::MaxNamedArgumentsError, /This command does not take named arguments/) <add> end <add> <add> it "accepts no arguments with :none" do <add> expect { parser_none.parse([]) }.not_to raise_error <add> end <add> <add> it "displays the correct error message with an array of strings" do <add> parser = described_class.new do <add> named_args %w[on off], min: 1 <add> end <add> expect { parser.parse([]) }.to raise_error(Homebrew::CLI::MinNamedArgumentsError) <add> end <add> <add> it "displays the correct error message with an array of symbols" do <add> parser = described_class.new do <add> named_args [:formula, :cask], min: 1 <add> end <add> expect { parser.parse([]) }.to raise_error(UsageError, /this command requires a formula or cask argument/) <add> end <add> end <add> <add> describe "named" do <add> subject(:parser) { <add> described_class.new do <add> named 1 <add> end <add> } <add> <add> it "allows the specified number of arguments" do <add> expect { parser.parse(["foo"]) }.not_to raise_error <add> end <add> <add> it "doesn't allow less than the specified number of arguments" do <add> expect { parser.parse([]) }.to raise_error(Homebrew::CLI::MinNamedArgumentsError) <add> end <add> <add> it "doesn't allow more than the specified number of arguments" do <add> expect { parser.parse(["foo", "bar"]) }.to raise_error(Homebrew::CLI::MaxNamedArgumentsError) <add> end <add> end <add> <add> describe "min_named" do <add> subject(:parser) { <add> described_class.new do <add> min_named 1 <add> end <add> } <add> <add> it "doesn't allow less than the minimum number of arguments" do <add> expect { parser.parse([]) }.to raise_error(Homebrew::CLI::MinNamedArgumentsError) <add> end <add> <add> it "allows the minimum number of arguments" do <add> expect { parser.parse(["foo"]) }.not_to raise_error <add> end <add> <add> it "allows more than the specified number of arguments" do <add> expect { parser.parse(["foo", "bar"]) }.not_to raise_error <add> end <add> end <add> <add> describe "max_named" do <add> subject(:parser) { <add> described_class.new do <add> max_named 1 <add> end <add> } <add> <add> it "doesn't allow more than the minimum number of arguments" do <add> expect { parser.parse(["foo", "bar"]) }.to raise_error(Homebrew::CLI::MaxNamedArgumentsError) <add> end <add> <add> it "allows the minimum number of arguments" do <add> expect { parser.parse(["foo"]) }.not_to raise_error <add> end <add> <add> it "allows less than the specified number of arguments" do <add> expect { parser.parse([]) }.not_to raise_error <add> end <add> end <ide> end
2
Python
Python
fix slack connections created in the ui
7b183071a398cbe340853f357bc6c029d551b4d1
<ide><path>airflow/providers/slack/hooks/slack.py <ide> def get_connection_form_widgets(cls) -> dict[str, Any]: <ide> from flask_appbuilder.fieldwidgets import BS3TextFieldWidget <ide> from flask_babel import lazy_gettext <ide> from wtforms import IntegerField, StringField <add> from wtforms.validators import NumberRange, Optional <ide> <ide> return { <ide> prefixed_extra_field("timeout", cls.conn_type): IntegerField( <ide> lazy_gettext("Timeout"), <ide> widget=BS3TextFieldWidget(), <add> validators=[Optional(strip_whitespace=True), NumberRange(min=1)], <ide> description="Optional. The maximum number of seconds the client will wait to connect " <ide> "and receive a response from Slack API.", <ide> ), <ide><path>airflow/providers/slack/hooks/slack_webhook.py <ide> def get_connection_form_widgets(cls) -> dict[str, Any]: <ide> from flask_appbuilder.fieldwidgets import BS3TextFieldWidget <ide> from flask_babel import lazy_gettext <ide> from wtforms import IntegerField, StringField <add> from wtforms.validators import NumberRange, Optional <ide> <ide> return { <ide> prefixed_extra_field("timeout", cls.conn_type): IntegerField( <ide> lazy_gettext("Timeout"), <ide> widget=BS3TextFieldWidget(), <add> validators=[Optional(), NumberRange(min=1)], <ide> description="Optional. The maximum number of seconds the client will wait to connect " <ide> "and receive a response from Slack Incoming Webhook.", <ide> ), <ide><path>airflow/providers/slack/utils/__init__.py <ide> def get(self, field, default: Any = NOTSET): <ide> :param default: If specified then use as default value if field not present in Connection Extra. <ide> """ <ide> prefixed_field = prefixed_extra_field(field, self.conn_type) <del> if prefixed_field in self.extra: <add> if prefixed_field in self.extra and self.extra[prefixed_field] not in (None, ""): <add> # Addition validation with non-empty required for connection which created in the UI <add> # in Airflow 2.2. In these connections always present key-value pair for all prefixed extras <add> # even if user do not fill this fields. <add> # In additional fields from `wtforms.IntegerField` might contain None value. <add> # E.g.: `{'extra__slackwebhook__proxy': '', 'extra__slackwebhook__timeout': None}` <ide> return self.extra[prefixed_field] <ide> elif field in self.extra: <ide> return self.extra[field] <ide><path>tests/providers/slack/utils/test_utils.py <ide> def test_both_prefixed_and_not_in_extra_field(self, conn_type): <ide> ) <ide> assert extra_config.get("arg1") == "bar" <ide> <add> @pytest.mark.parametrize("conn_type", ["slack", "slack_incoming_webhook"]) <add> @pytest.mark.parametrize("empty_value", [None, ""]) <add> def test_prefixed_extra_created_in_ui_connections(self, conn_type, empty_value): <add> """Test that empty strings or None values in UI ignored.""" <add> extra_config = ConnectionExtraConfig( <add> conn_type=conn_type, <add> conn_id="test-conn-id", <add> extra={ <add> f"extra__{conn_type}__arg_missing": empty_value, <add> "arg_extra": "bar", <add> f"extra__{conn_type}__arg_extra": empty_value, <add> }, <add> ) <add> error_message = ( <add> r"Couldn't find '.*' or '.*' in Connection \('.*'\) Extra and no default value specified\." <add> ) <add> with pytest.raises(KeyError, match=error_message): <add> # No fallback should raise an error <add> extra_config.get("arg_missing") <add> <add> assert extra_config.get("arg_missing", default="foo") == "foo" <add> assert extra_config.get("arg_extra") == "bar" <add> <ide> def test_get_parse_int(self): <ide> extra_config = ConnectionExtraConfig( <ide> conn_type="slack",
4
Ruby
Ruby
initialize instance variable to remove warning
b4ac65aa3855b806442934f6287d681e8bb0ef70
<ide><path>railties/lib/rails/generators/actions.rb <ide> module Rails <ide> module Generators <ide> module Actions <add> def initialize(*) # :nodoc: <add> super <add> @in_group = nil <add> end <ide> <ide> # Adds an entry into Gemfile for the supplied gem. <ide> #
1
Javascript
Javascript
fix lint errors
5a6f93d1c34f369dffae4f7aa94ab4b86128308d
<ide><path>spec/grammar-registry-spec.js <ide> describe('GrammarRegistry', () => { <ide> describe('text-mate grammars with content regexes', () => { <ide> it('favors grammars that match the content regex', () => { <ide> const grammar1 = { <del> name: "foo", <del> fileTypes: ["foo"] <add> name: 'foo', <add> fileTypes: ['foo'] <ide> } <ide> grammarRegistry.addGrammar(grammar1) <ide> const grammar2 = { <del> name: "foo++", <del> contentRegex: new OnigRegExp(".*bar"), <del> fileTypes: ["foo"] <add> name: 'foo++', <add> contentRegex: new OnigRegExp('.*bar'), <add> fileTypes: ['foo'] <ide> } <ide> grammarRegistry.addGrammar(grammar2) <ide>
1
Ruby
Ruby
prefix keys in active storage service test
e44b3419d44b5fa6e66305fe703f34bb63932593
<ide><path>activestorage/test/service/shared_service_tests.rb <ide> module ActiveStorage::Service::SharedServiceTests <ide> end <ide> <ide> test "deleting by prefix" do <del> @service.upload("a/a/a", StringIO.new(FIXTURE_DATA)) <del> @service.upload("a/a/b", StringIO.new(FIXTURE_DATA)) <del> @service.upload("a/b/a", StringIO.new(FIXTURE_DATA)) <del> <del> @service.delete_prefixed("a/a/") <del> assert_not @service.exist?("a/a/a") <del> assert_not @service.exist?("a/a/b") <del> assert @service.exist?("a/b/a") <add> key = SecureRandom.base58(24) <add> <add> @service.upload("#{key}/a/a/a", StringIO.new(FIXTURE_DATA)) <add> @service.upload("#{key}/a/a/b", StringIO.new(FIXTURE_DATA)) <add> @service.upload("#{key}/a/b/a", StringIO.new(FIXTURE_DATA)) <add> <add> @service.delete_prefixed("#{key}/a/a/") <add> assert_not @service.exist?("#{key}/a/a/a") <add> assert_not @service.exist?("#{key}/a/a/b") <add> assert @service.exist?("#{key}/a/b/a") <ide> ensure <del> @service.delete("a/a/a") <del> @service.delete("a/a/b") <del> @service.delete("a/b/a") <add> @service.delete("#{key}/a/a/a") <add> @service.delete("#{key}/a/a/b") <add> @service.delete("#{key}/a/b/a") <ide> end <ide> end <ide> end
1
Javascript
Javascript
ensure consistent use of ember.create
1647fdd3ccdce1502ab7e9041c77b2136beba32e
<ide><path>packages/ember-application/lib/system/application.js <ide> var Application = Namespace.extend(DeferredMixin, { <ide> }); <ide> <ide> Application.reopenClass({ <del> initializers: Object.create(null), <add> initializers: create(null), <ide> <ide> /** <ide> Initializer receives an object which has the following attributes: <ide><path>packages/ember-metal-views/tests/test_helpers.js <add>import { create } from "ember-metal/platform"; <ide> import { Renderer } from "ember-metal-views"; <ide> <ide> var renderer; <ide> function MetalRenderer () { <ide> MetalRenderer._super.call(this); <ide> } <ide> MetalRenderer._super = Renderer; <del>MetalRenderer.prototype = Object.create(Renderer.prototype, { <add>MetalRenderer.prototype = create(Renderer.prototype, { <ide> constructor: { <ide> value: MetalRenderer, <ide> enumerable: false, <ide><path>packages/ember-metal/lib/dictionary.js <add>import { create } from "ember-metal/platform"; <add> <ide> // the delete is meant to hint at runtimes that this object should remain in <ide> // dictionary mode. This is clearly a runtime specific hack, but currently it <ide> // appears worthwile in some usecases. Please note, these deletes do increase <ide> // the cost of creation dramatically over a plain Object.create. And as this <ide> // only makes sense for long-lived dictionaries that aren't instantiated often. <ide> export default function makeDictionary(parent) { <del> var dict = Object.create(parent); <add> var dict = create(parent); <ide> dict['_dict'] = null; <ide> delete dict['_dict']; <ide> return dict; <ide><path>packages/ember-metal/lib/map.js <ide> function missingNew(name) { <ide> } <ide> <ide> function copyNull(obj) { <del> var output = Object.create(null); <add> var output = create(null); <ide> <ide> for (var prop in obj) { <ide> // hasOwnPropery is not needed because obj is Object.create(null); <ide> OrderedSet.prototype = { <ide> @method clear <ide> */ <ide> clear: function() { <del> this.presenceSet = Object.create(null); <add> this.presenceSet = create(null); <ide> this.list = []; <ide> this.size = 0; <ide> }, <ide> function Map() { <ide> if (this instanceof this.constructor) { <ide> this.keys = OrderedSet.create(); <ide> this.keys._silenceRemoveDeprecation = true; <del> this.values = Object.create(null); <add> this.values = create(null); <ide> this.size = 0; <ide> } else { <ide> missingNew("OrderedSet"); <ide> Map.prototype = { <ide> */ <ide> clear: function() { <ide> this.keys.clear(); <del> this.values = Object.create(null); <add> this.values = create(null); <ide> this.size = 0; <ide> }, <ide> <ide><path>packages/ember-metal/lib/mixin.js <ide> function connectStreamBinding(obj, key, stream) { <ide> stream.subscribe(onNotify); <ide> <ide> if (obj._streamBindingSubscriptions === undefined) { <del> obj._streamBindingSubscriptions = Object.create(null); <add> obj._streamBindingSubscriptions = o_create(null); <ide> } <ide> <ide> obj._streamBindingSubscriptions[key] = onNotify; <ide><path>packages/ember-metal/lib/streams/stream.js <add>import { create } from "ember-metal/platform"; <ide> import { <ide> getFirstKey, <ide> getTailPath <ide> Stream.prototype = { <ide> var tailPath = getTailPath(path); <ide> <ide> if (this.children === undefined) { <del> this.children = Object.create(null); <add> this.children = create(null); <ide> } <ide> <ide> var keyStream = this.children[firstKey]; <ide><path>packages/ember-routing/lib/system/router.js <ide> import { <ide> getActiveTargetName, <ide> stashParamNames <ide> } from "ember-routing/utils"; <add>import { create } from "ember-metal/platform"; <ide> <ide> /** <ide> @module ember <ide> var EmberRouter = EmberObject.extend(Evented, { <ide> }, <ide> <ide> _getHandlerFunction: function() { <del> var seen = Object.create(null); <add> var seen = create(null); <ide> var container = this.container; <ide> var DefaultRoute = container.lookupFactory('route:basic'); <ide> var self = this; <ide><path>packages/ember-runtime/tests/core/copy_test.js <add>import { create } from "ember-metal/platform"; <ide> import copy from "ember-runtime/copy"; <ide> <ide> QUnit.module("Ember Copy Method"); <ide> test("Ember.copy date", function() { <ide> }); <ide> <ide> test("Ember.copy null prototype object", function() { <del> var obj = Object.create(null); <add> var obj = create(null); <ide> <ide> obj.foo = 'bar'; <ide> <ide><path>packages/ember-views/lib/system/render_buffer.js <ide> import jQuery from "ember-views/system/jquery"; <ide> import { DOMHelper } from "morph"; <ide> import Ember from "ember-metal/core"; <add>import { create } from "ember-metal/platform"; <ide> <ide> // The HTML spec allows for "omitted start tags". These tags are optional <ide> // when their intended child is the first thing in the parent tag. For <ide> function detectOmittedStartTag(string, contextualElement){ <ide> } <ide> <ide> function ClassSet() { <del> this.seen = Object.create(null); <add> this.seen = create(null); <ide> this.list = []; <ide> } <ide> <ide><path>packages/ember-views/lib/views/view.js <ide> // Ember.ContainerView circular dependency <ide> // Ember.ENV <ide> import Ember from 'ember-metal/core'; <add>import { create } from 'ember-metal/platform'; <ide> <ide> import Evented from "ember-runtime/mixins/evented"; <ide> import EmberObject from "ember-runtime/system/object"; <ide> var View = CoreView.extend({ <ide> this._streamBindings = undefined; <ide> <ide> if (!this._keywords) { <del> this._keywords = Object.create(null); <add> this._keywords = create(null); <ide> } <ide> this._keywords.view = new SimpleStream(); <ide> this._keywords._view = this; <ide> var View = CoreView.extend({ <ide> <ide> _getBindingForStream: function(path) { <ide> if (this._streamBindings === undefined) { <del> this._streamBindings = Object.create(null); <add> this._streamBindings = create(null); <ide> this.one('willDestroyElement', this, this._destroyStreamBindings); <ide> } <ide>
10
Python
Python
add missing cats to gold annot_tuples in scorer
29e3da64930434c178fba30cfbbc2f0b7a29e3c7
<ide><path>spacy/scorer.py <ide> def score(self, doc, gold, verbose=False, punct_labels=("p", "punct")): <ide> DOCS: https://spacy.io/api/scorer#score <ide> """ <ide> if len(doc) != len(gold): <del> gold = GoldParse.from_annot_tuples(doc, zip(*gold.orig_annot)) <add> gold = GoldParse.from_annot_tuples(doc, tuple(zip(*gold.orig_annot)) + (gold.cats,)) <ide> gold_deps = set() <ide> gold_tags = set() <ide> gold_ents = set(tags_to_entities([annot[-1] for annot in gold.orig_annot]))
1
PHP
PHP
translate error messsages
9d8452da5511c72592d14a1d59abda34506d104b
<ide><path>src/Illuminate/Foundation/Exceptions/views/403.blade.php <ide> @extends('errors::illustrated-layout') <ide> <ide> @section('code', '403') <del>@section('title', 'Unauthorized') <add>@section('title', __('Unauthorized')) <ide> <ide> @section('image') <ide> <div style="background-image: url('/svg/403.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> <ide> </div> <ide> @endsection <ide> <del>@section('message', 'Sorry, you are not authorized to access this page.') <add>@section('message', __('Sorry, you are not authorized to access this page.')) <ide><path>src/Illuminate/Foundation/Exceptions/views/404.blade.php <ide> @extends('errors::illustrated-layout') <ide> <ide> @section('code', '404') <del>@section('title', 'Page Not Found') <add>@section('title', __('Page Not Found')) <ide> <ide> @section('image') <ide> <div style="background-image: url('/svg/404.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> <ide> </div> <ide> @endsection <ide> <del>@section('message', 'Sorry, the page you are looking for could not be found.') <add>@section('message', __('Sorry, the page you are looking for could not be found.')) <ide><path>src/Illuminate/Foundation/Exceptions/views/419.blade.php <ide> @extends('errors::illustrated-layout') <ide> <ide> @section('code', '419') <del>@section('title', 'Page Expired') <add>@section('title', __('Page Expired')) <ide> <ide> @section('image') <ide> <div style="background-image: url('/svg/403.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> <ide> </div> <ide> @endsection <ide> <del>@section('message', 'Sorry, your session has expired. Please refresh and try again.') <add>@section('message', __('Sorry, your session has expired. Please refresh and try again.')) <ide><path>src/Illuminate/Foundation/Exceptions/views/429.blade.php <ide> @extends('errors::illustrated-layout') <ide> <ide> @section('code', '429') <del>@section('title', 'Too Many Requests') <add>@section('title', __('Too Many Requests')) <ide> <ide> @section('image') <ide> <div style="background-image: url('/svg/403.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> <ide> </div> <ide> @endsection <ide> <del>@section('message', 'Sorry, you are making too many requests to our servers.') <add>@section('message', __('Sorry, you are making too many requests to our servers.')) <ide><path>src/Illuminate/Foundation/Exceptions/views/500.blade.php <ide> @extends('errors::illustrated-layout') <ide> <ide> @section('code', '500') <del>@section('title', 'Error') <add>@section('title', __('Error')) <ide> <ide> @section('image') <ide> <div style="background-image: url('/svg/500.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> <ide> </div> <ide> @endsection <ide> <del>@section('message', 'Whoops, something went wrong on our servers.') <add>@section('message', __('Whoops, something went wrong on our servers.')) <ide><path>src/Illuminate/Foundation/Exceptions/views/503.blade.php <ide> @extends('errors::illustrated-layout') <ide> <ide> @section('code', '503') <del>@section('title', 'Service Unavailable') <add>@section('title', __('Service Unavailable')) <ide> <ide> @section('image') <ide> <div style="background-image: url('/svg/503.svg');" class="absolute pin bg-cover bg-no-repeat md:bg-left lg:bg-center"> <ide> </div> <ide> @endsection <ide> <del>@section('message', 'Sorry, we are doing some maintenance. Please check back soon.') <add>@section('message', __('Sorry, we are doing some maintenance. Please check back soon.')) <ide><path>src/Illuminate/Foundation/Exceptions/views/illustrated-layout.blade.php <ide> <div class="w-full md:w-1/2 bg-white flex items-center justify-center"> <ide> <div class="max-w-sm m-8"> <ide> <div class="text-black text-5xl md:text-15xl font-black"> <del> @yield('code', 'Oh no') <add> @yield('code', __('Oh no')) <ide> </div> <ide> <ide> <div class="w-16 h-1 bg-purple-light my-3 md:my-6"></div> <ide> <ide> <a href="/"> <ide> <button class="bg-transparent text-grey-darkest font-bold uppercase tracking-wide py-3 px-6 border-2 border-grey-light hover:border-grey rounded-lg"> <del> Go Home <add> {{ __('Go Home') }} <ide> </button> <ide> </a> <ide> </div>
7
Ruby
Ruby
remove some globals from configuration tests
5fc5665066110031ad4c76c9bc843713470824d0
<ide><path>railties/test/application/configuration_test.rb <ide> def index <ide> end <ide> <ide> test "rake_tasks block works at instance level" do <del> $ran_block = false <del> <ide> app_file "config/environments/development.rb", <<-RUBY <ide> Rails.application.configure do <add> config.ran_block = false <add> <ide> rake_tasks do <del> $ran_block = true <add> config.ran_block = true <ide> end <ide> end <ide> RUBY <ide> <ide> require "#{app_path}/config/environment" <add> assert_not Rails.configuration.ran_block <ide> <del> assert !$ran_block <ide> require 'rake' <ide> require 'rake/testtask' <ide> require 'rdoc/task' <ide> <ide> Rails.application.load_tasks <del> assert $ran_block <add> assert Rails.configuration.ran_block <ide> end <ide> <ide> test "generators block works at instance level" do <del> $ran_block = false <del> <ide> app_file "config/environments/development.rb", <<-RUBY <ide> Rails.application.configure do <add> config.ran_block = false <add> <ide> generators do <del> $ran_block = true <add> config.ran_block = true <ide> end <ide> end <ide> RUBY <ide> <ide> require "#{app_path}/config/environment" <add> assert_not Rails.configuration.ran_block <ide> <del> assert !$ran_block <ide> Rails.application.load_generators <del> assert $ran_block <add> assert Rails.configuration.ran_block <ide> end <ide> <ide> test "console block works at instance level" do <del> $ran_block = false <del> <ide> app_file "config/environments/development.rb", <<-RUBY <ide> Rails.application.configure do <add> config.ran_block = false <add> <ide> console do <del> $ran_block = true <add> config.ran_block = true <ide> end <ide> end <ide> RUBY <ide> <ide> require "#{app_path}/config/environment" <add> assert_not Rails.configuration.ran_block <ide> <del> assert !$ran_block <ide> Rails.application.load_console <del> assert $ran_block <add> assert Rails.configuration.ran_block <ide> end <ide> <ide> test "runner block works at instance level" do <del> $ran_block = false <del> <ide> app_file "config/environments/development.rb", <<-RUBY <ide> Rails.application.configure do <add> config.ran_block = false <add> <ide> runner do <del> $ran_block = true <add> config.ran_block = true <ide> end <ide> end <ide> RUBY <ide> <ide> require "#{app_path}/config/environment" <add> assert_not Rails.configuration.ran_block <ide> <del> assert !$ran_block <ide> Rails.application.load_runner <del> assert $ran_block <add> assert Rails.configuration.ran_block <ide> end <ide> <ide> test "loading the first existing database configuration available" do
1
Ruby
Ruby
remove outdated comment
ba2e9e0911a8ee91ce736578c03c8a7e1137d80a
<ide><path>activesupport/lib/active_support/callbacks.rb <ide> def invoke_after(arg) <ide> end <ide> end <ide> <del> # An Array with a compile method. <ide> class CallbackChain #:nodoc:# <ide> include Enumerable <ide>
1
Ruby
Ruby
remove unused branches from options.coerce
0a2be32d802073ef46596792a46f7139bb862a8c
<ide><path>Library/Homebrew/options.rb <ide> def inspect <ide> <ide> def self.coerce(arg) <ide> case arg <del> when self then arg <del> when Option then new << arg <ide> when Array <ide> opts = new <ide> arg.each do |a| <ide><path>Library/Homebrew/test/test_options.rb <ide> def test_set_union <ide> assert_equal [foo, bar, baz].sort, (@options | options).to_a.sort <ide> end <ide> <del> def test_coerce_with_options <del> assert_same @options, Options.coerce(@options) <del> end <del> <del> def test_coerce_with_option <del> option = Option.new("foo") <del> assert_equal option, Options.coerce(option).to_a.first <del> end <del> <ide> def test_coerce_with_array <ide> array = %w{--foo --bar} <ide> option1 = Option.new("foo")
2
Javascript
Javascript
add e2e tests for /learn
206c5994b72c353d118e3828b2c83905fdf5e6b5
<ide><path>cypress/integration/learn/index.js <ide> const locations = { <ide> }; <ide> <ide> const superBlockNames = [ <del> 'Responsive Web Design', <del> 'JavaScript Algorithms and Data Structures', <del> 'Front End Libraries', <del> 'Data Visualization', <del> 'APIs and Microservices', <del> 'Quality Assurance', <del> 'Scientific Computing with Python', <del> 'Data Analysis with Python', <del> 'Information Security', <del> 'Machine Learning with Python', <del> 'Coding Interview Prep' <add> 'Responsive Web Design Certification', <add> 'JavaScript Algorithms and Data Structures Certification', <add> 'Front End Libraries Certification', <add> 'Data Visualization Certification', <add> 'APIs and Microservices Certification', <add> 'Quality Assurance Certification', <add> 'Scientific Computing with Python Certification', <add> 'Data Analysis with Python Certification', <add> 'Information Security Certification', <add> 'Machine Learning with Python Certification', <add> 'Coding Interview Prep (Thousands of hours of challenges)' <ide> ]; <ide> <del>describe('Learn Landing page', function() { <del> it('renders', () => { <add>describe('Learn Landing page (not logged in)', () => { <add> it('Should render', () => { <ide> cy.visit(locations.index); <ide> <ide> cy.title().should('eq', 'Learn to code at home | freeCodeCamp.org'); <ide> describe('Learn Landing page', function() { <ide> cy.contains('h1', "Welcome to freeCodeCamp's curriculum."); <ide> }); <ide> <del> it('renders a curriuculum map', () => { <add> it('Should render a curriculum map', () => { <ide> cy.document().then(document => { <ide> const superBlocks = document.querySelectorAll( <ide> `${selectors.challengeMap} > ul > li` <ide> describe('Learn Landing page', function() { <ide> }); <ide> }); <ide> }); <add> <add>describe('Quotes', () => { <add> beforeEach(() => { <add> cy.visit('/'); <add> cy.contains("Get started (it's free)").click({ force: true }); <add> }); <add> <add> it('Should show a quote', () => { <add> cy.get('blockquote').within(() => { <add> cy.get('q').should('be.visible'); <add> }); <add> }); <add> <add> it('Should show quote author', () => { <add> cy.get('blockquote').within(() => { <add> cy.get('cite').should('be.visible'); <add> }); <add> }); <add>}); <add> <add>describe('Superblocks and Blocks', () => { <add> beforeEach(() => { <add> cy.visit('/'); <add> cy.contains("Get started (it's free)").click({ force: true }); <add> }); <add> <add> it('Has first superblock and block collapsed by default', () => { <add> cy.contains(superBlockNames[0]) <add> .should('be.visible') <add> .and('have.attr', 'aria-expanded', 'true'); <add> <add> cy.contains('Basic HTML and HTML5') <add> .should('be.visible') <add> .and('have.attr', 'aria-expanded', 'true'); <add> }); <add> <add> it('Has all supeblocks visible but folded (excluding the first one)', () => { <add> cy.wrap(superBlockNames.slice(1)).each(name => { <add> cy.contains(name) <add> .should('be.visible') <add> .and('have.attr', 'aria-expanded', 'false'); <add> }); <add> }); <add> it('Superblocks should be collapsable and foldable', () => { <add> cy.contains(superBlockNames[0]) <add> .click({ <add> force: true <add> }) <add> .should('have.attr', 'aria-expanded', 'false'); <add> cy.contains('Basic HTML and HTML5').should('not.be.visible'); <add> <add> cy.contains(superBlockNames[0]) <add> .click({ <add> force: true <add> }) <add> .should('have.attr', 'aria-expanded', 'true'); <add> cy.contains('Basic HTML and HTML5').should('be.visible'); <add> }); <add> <add> it('Blocks should be collapsable and foldable', () => { <add> cy.contains('Basic HTML and HTML5') <add> .click({ force: true }) <add> .should('have.attr', 'aria-expanded', 'false'); <add> cy.contains('Introduction to Basic HTML and HTML5').should( <add> 'not.be.visible' <add> ); <add> <add> cy.contains('Basic HTML and HTML5') <add> .click({ force: true }) <add> .should('have.attr', 'aria-expanded', 'true'); <add> cy.contains('Introduction to Basic HTML and HTML5').should('be.visible'); <add> }); <add>});
1
Javascript
Javascript
improve wasi test coverage
bcd5491219bfd34630d331bdca3c92538a7b0e5e
<ide><path>test/wasi/test-wasi-options-validation.js <add>'use strict'; <add> <add>// Flags: --experimental-wasi-unstable-preview0 <add> <add>require('../common'); <add>const assert = require('assert'); <add>const { WASI } = require('wasi'); <add> <add>// If args is undefined, it should default to [] and should not throw. <add>new WASI({}); <add> <add>// If args is not an Array and not undefined, it should throw. <add>assert.throws(() => { new WASI({ args: 'fhqwhgads' }); }, <add> { code: 'ERR_INVALID_ARG_TYPE' }); <add> <add>// If env is not an Object and not undefined, it should throw. <add>assert.throws(() => { new WASI({ env: 'fhqwhgads' }); }, <add> { code: 'ERR_INVALID_ARG_TYPE' }); <add> <add>// If preopens is not an Object and not undefined, it should throw. <add>assert.throws(() => { new WASI({ preopens: 'fhqwhgads' }); }, <add> { code: 'ERR_INVALID_ARG_TYPE' });
1
Javascript
Javascript
fix required descriptor
64ef59005be9902815005846e641a5253ff58c59
<ide><path>packages/ember-metal/lib/mixin.js <ide> function mergeMixins(mixins, m, descs, values, base) { <ide> value = baseValue ? baseValue.concat(value) : Ember.makeArray(value); <ide> } <ide> <add> descs[key] = undefined; <ide> values[key] = value; <ide> } <ide> }
1
Go
Go
move writejson() together with readjson()
ff5f70e55f8cd303efbaee3eafda9dfe86a3da36
<ide><path>api/server/httputils/httputils.go <ide> func ReadJSON(r *http.Request, out interface{}) error { <ide> return nil <ide> } <ide> <add>// WriteJSON writes the value v to the http response stream as json with standard json encoding. <add>func WriteJSON(w http.ResponseWriter, code int, v interface{}) error { <add> w.Header().Set("Content-Type", "application/json") <add> w.WriteHeader(code) <add> enc := json.NewEncoder(w) <add> enc.SetEscapeHTML(false) <add> return enc.Encode(v) <add>} <add> <ide> // ParseForm ensures the request form is parsed even with invalid content types. <ide> // If we don't do this, POST method without Content-type (even with empty body) will fail. <ide> func ParseForm(r *http.Request) error { <ide><path>api/server/httputils/httputils_write_json.go <del>package httputils // import "github.com/docker/docker/api/server/httputils" <del> <del>import ( <del> "encoding/json" <del> "net/http" <del>) <del> <del>// WriteJSON writes the value v to the http response stream as json with standard json encoding. <del>func WriteJSON(w http.ResponseWriter, code int, v interface{}) error { <del> w.Header().Set("Content-Type", "application/json") <del> w.WriteHeader(code) <del> enc := json.NewEncoder(w) <del> enc.SetEscapeHTML(false) <del> return enc.Encode(v) <del>}
2
Go
Go
add nilvalue for structured-data in rfc5424 logs
b7d802bbccdf7ec6e4cc1ead733663cdce9768c0
<ide><path>daemon/logger/syslog/syslog.go <ide> func init() { <ide> func rfc5424formatterWithAppNameAsTag(p syslog.Priority, hostname, tag, content string) string { <ide> timestamp := time.Now().Format(time.RFC3339) <ide> pid := os.Getpid() <del> msg := fmt.Sprintf("<%d>%d %s %s %s %d %s %s", <add> msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s", <ide> p, 1, timestamp, hostname, tag, pid, tag, content) <ide> return msg <ide> } <ide> func rfc5424formatterWithAppNameAsTag(p syslog.Priority, hostname, tag, content <ide> func rfc5424microformatterWithAppNameAsTag(p syslog.Priority, hostname, tag, content string) string { <ide> timestamp := time.Now().Format("2006-01-02T15:04:05.999999Z07:00") <ide> pid := os.Getpid() <del> msg := fmt.Sprintf("<%d>%d %s %s %s %d %s %s", <add> msg := fmt.Sprintf("<%d>%d %s %s %s %d %s - %s", <ide> p, 1, timestamp, hostname, tag, pid, tag, content) <ide> return msg <ide> }
1
Python
Python
remove lrn2d layer
82353da4dc66bc702a74c6c233f3e16b7682f9e6
<ide><path>keras/layers/normalization.py <ide> def get_config(self): <ide> "momentum": self.momentum} <ide> base_config = super(BatchNormalization, self).get_config() <ide> return dict(list(base_config.items()) + list(config.items())) <del> <del> <del>class LRN2D(Layer): <del> """ <del> This code is adapted from pylearn2. <del> License at: https://github.com/lisa-lab/pylearn2/blob/master/LICENSE.txt <del> """ <del> <del> def __init__(self, alpha=1e-4, k=2, beta=0.75, n=5, **kwargs): <del> if n % 2 == 0: <del> raise NotImplementedError("LRN2D only works with odd n. n provided: " + str(n)) <del> super(LRN2D, self).__init__(**kwargs) <del> self.alpha = alpha <del> self.k = k <del> self.beta = beta <del> self.n = n <del> <del> def get_output(self, train): <del> X = self.get_input(train) <del> b, ch, r, c = K.shape(X) <del> half_n = self.n // 2 <del> input_sqr = K.square(X) <del> extra_channels = K.zeros((b, ch + 2 * half_n, r, c)) <del> input_sqr = K.concatenate([extra_channels[:, :half_n, :, :], <del> input_sqr, <del> extra_channels[:, half_n + ch:, :, :]], <del> axis=1) <del> scale = self.k <del> for i in range(self.n): <del> scale += self.alpha * input_sqr[:, i:i + ch, :, :] <del> scale = scale ** self.beta <del> return X / scale <del> <del> def get_config(self): <del> config = {"name": self.__class__.__name__, <del> "alpha": self.alpha, <del> "k": self.k, <del> "beta": self.beta, <del> "n": self.n} <del> base_config = super(LRN2D, self).get_config() <del> return dict(list(base_config.items()) + list(config.items()))
1
PHP
PHP
add additional assertions for saving joindata
f942e6ec9c474d2a1e11dbbffa5dd838ed3b5af3
<ide><path>tests/TestCase/ORM/QueryRegressionTest.php <ide> public function testBelongsToManyDeepSave($strategy) <ide> 'Highlights.Authors' <ide> ] <ide> ]); <del> $this->assertEquals('mariano', end($entity->special_tags)->author->name); <ide> $this->assertEquals('mark', end($entity->highlights)->author->name); <add> <add> $lastTag = end($entity->special_tags); <add> $this->assertTrue($lastTag->highlighted); <add> $this->assertEquals('2014-06-01 10:10:00', $lastTag->highlighted_time->format('Y-m-d H:i:s')); <add> $this->assertEquals('mariano', $lastTag->author->name); <ide> } <ide> <ide> /**
1
PHP
PHP
add tests to dispatcher
dae0cb962dbf6f48f9b5bd7dccd932b7833f41bc
<ide><path>tests/Events/EventsDispatcherTest.php <ide> public function testBasicEventExecution() <ide> <ide> $this->assertEquals([null], $response); <ide> $this->assertSame('bar', $_SERVER['__event.test']); <add> <add> // we can still add listeners after the event has fired <add> $d->listen('foo', function ($foo) { <add> $_SERVER['__event.test'] .= $foo; <add> }); <add> <add> $d->dispatch('foo', ['bar']); <add> $this->assertSame('barbar', $_SERVER['__event.test']); <ide> } <ide> <ide> public function testHaltingEventExecution() <ide> public function testBothClassesAndInterfacesWork() <ide> unset($_SERVER['__event.test1']); <ide> unset($_SERVER['__event.test2']); <ide> } <add> <add> public function testNestedEvent() <add> { <add> $_SERVER['__event.test'] = []; <add> $d = new Dispatcher; <add> <add> $d->listen('event', function () use ($d) { <add> $d->listen('event', function () { <add> $_SERVER['__event.test'][] = 'fired 1'; <add> }); <add> $d->listen('event', function () { <add> $_SERVER['__event.test'][] = 'fired 2'; <add> }); <add> }); <add> <add> $d->dispatch('event'); <add> $this->assertSame([], $_SERVER['__event.test']); <add> $d->dispatch('event'); <add> $this->assertEquals(['fired 1', 'fired 2'], $_SERVER['__event.test']); <add> } <ide> } <ide> <ide> class ExampleEvent
1
Ruby
Ruby
prepare ap and ar to be frozen string friendly
b3f3d49fd6b91c6573b3e10e3d00f65306638927
<ide><path>actionpack/lib/action_dispatch/http/request.rb <add># frozen_string_literal: true <ide> require "stringio" <ide> <ide> require "active_support/inflector" <ide><path>actionpack/lib/action_dispatch/http/url.rb <add># frozen_string_literal: true <ide> require "active_support/core_ext/module/attribute_accessors" <ide> <ide> module ActionDispatch <ide> def normalize_host(_host, options) <ide> subdomain = options.fetch :subdomain, true <ide> domain = options[:domain] <ide> <del> host = "" <add> host = "".dup <ide> if subdomain == true <ide> return _host if domain.nil? <ide> <ide><path>actionpack/lib/action_dispatch/journey/formatter.rb <add># frozen_string_literal: true <ide> require "action_controller/metal/exceptions" <ide> <ide> module ActionDispatch <ide> def generate(name, options, path_parameters, parameterize = nil) <ide> unmatched_keys = (missing_keys || []) & constraints.keys <ide> missing_keys = (missing_keys || []) - unmatched_keys <ide> <del> message = "No route matches #{Hash[constraints.sort_by { |k, v| k.to_s }].inspect}" <add> message = "No route matches #{Hash[constraints.sort_by { |k, v| k.to_s }].inspect}".dup <ide> message << ", missing required keys: #{missing_keys.sort.inspect}" if missing_keys && !missing_keys.empty? <ide> message << ", possible unmatched constraints: #{unmatched_keys.sort.inspect}" if unmatched_keys && !unmatched_keys.empty? <ide> <ide><path>actionpack/lib/action_dispatch/journey/visitors.rb <add># frozen_string_literal: true <ide> module ActionDispatch <ide> # :stopdoc: <ide> module Journey <ide> def nary(node, seed) <ide> last_child = node.children.last <ide> node.children.inject(seed) { |s, c| <ide> string = visit(c, s) <del> string << "|".freeze unless last_child == c <add> string << "|" unless last_child == c <ide> string <ide> } <ide> end <ide> def terminal(node, seed) <ide> end <ide> <ide> def visit_GROUP(node, seed) <del> visit(node.left, seed << "(".freeze) << ")".freeze <add> visit(node.left, seed.dup << "(") << ")" <ide> end <ide> <ide> INSTANCE = new <ide><path>actionpack/lib/action_dispatch/middleware/debug_exceptions.rb <add># frozen_string_literal: true <ide> require_relative "../http/request" <ide> require_relative "exception_wrapper" <ide> require_relative "../routing/inspector" <ide> def debug_params(params) <ide> if clean_params.empty? <ide> "None" <ide> else <del> PP.pp(clean_params, "", 200) <add> PP.pp(clean_params, "".dup, 200) <ide> end <ide> end <ide> <ide><path>actionpack/lib/action_dispatch/middleware/ssl.rb <add># frozen_string_literal: true <ide> module ActionDispatch <ide> # This middleware is added to the stack when `config.force_ssl = true`, and is passed <ide> # the options set in `config.ssl_options`. It does three jobs to enforce secure HTTP <ide> def normalize_hsts_options(options) <ide> <ide> # http://tools.ietf.org/html/rfc6797#section-6.1 <ide> def build_hsts_header(hsts) <del> value = "max-age=#{hsts[:expires].to_i}" <add> value = "max-age=#{hsts[:expires].to_i}".dup <ide> value << "; includeSubDomains" if hsts[:subdomains] <ide> value << "; preload" if hsts[:preload] <ide> value <ide> def https_location_for(request) <ide> host = @redirect[:host] || request.host <ide> port = @redirect[:port] || request.port <ide> <del> location = "https://#{host}" <add> location = "https://#{host}".dup <ide> location << ":#{port}" if port != 80 && port != 443 <ide> location << request.fullpath <ide> location <ide><path>actionpack/lib/action_dispatch/middleware/static.rb <add># frozen_string_literal: true <ide> require "rack/utils" <ide> require "active_support/core_ext/uri" <ide> <ide> def match?(path) <ide> paths = [path, "#{path}#{ext}", "#{path}/#{@index}#{ext}"] <ide> <ide> if match = paths.detect { |p| <del> path = File.join(@root, p.force_encoding(Encoding::UTF_8)) <add> path = File.join(@root, p.dup.force_encoding(Encoding::UTF_8)) <ide> begin <ide> File.file?(path) && File.readable?(path) <ide> rescue SystemCallError <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb <add># frozen_string_literal: true <ide> require "active_support/core_ext/hash/slice" <ide> require "active_support/core_ext/enumerable" <ide> require "active_support/core_ext/array/extract_options" <ide> def app(blocks) <ide> def check_controller_and_action(path_params, controller, action) <ide> hash = check_part(:controller, controller, path_params, {}) do |part| <ide> translate_controller(part) { <del> message = "'#{part}' is not a supported controller name. This can lead to potential routing problems." <add> message = "'#{part}' is not a supported controller name. This can lead to potential routing problems.".dup <ide> message << " See http://guides.rubyonrails.org/routing.html#specifying-a-controller-to-use" <ide> <ide> raise ArgumentError, message <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <add># frozen_string_literal: true <ide> require_relative "../journey" <ide> require "active_support/core_ext/object/to_query" <ide> require "active_support/core_ext/hash/slice" <ide> def raise_generation_error(args) <ide> missing_keys << missing_key <ide> } <ide> constraints = Hash[@route.requirements.merge(params).sort_by { |k, v| k.to_s }] <del> message = "No route matches #{constraints.inspect}" <add> message = "No route matches #{constraints.inspect}".dup <ide> message << ", missing required keys: #{missing_keys.sort.inspect}" <ide> <ide> raise ActionController::UrlGenerationError, message <ide><path>actionpack/test/abstract_unit.rb <add># frozen_string_literal: true <ide> $:.unshift File.expand_path("lib", __dir__) <ide> $:.unshift File.expand_path("fixtures/helpers", __dir__) <ide> $:.unshift File.expand_path("fixtures/alternate_helpers", __dir__) <ide> def with_autoload_path(path) <ide> class Rack::TestCase < ActionDispatch::IntegrationTest <ide> def self.testing(klass = nil) <ide> if klass <del> @testing = "/#{klass.name.underscore}".sub!(/_controller$/, "") <add> @testing = "/#{klass.name.underscore}".sub(/_controller$/, "") <ide> else <ide> @testing <ide> end <ide><path>actionpack/test/controller/routing_test.rb <add># frozen_string_literal: true <ide> require "abstract_unit" <ide> require "controller/fake_controllers" <ide> require "active_support/core_ext/object/with_options" <ide> def test_route_with_text_default <ide> assert_equal "/page/foo", url_for(rs, controller: "content", action: "show_page", id: "foo") <ide> assert_equal({ controller: "content", action: "show_page", id: "foo" }, rs.recognize_path("/page/foo")) <ide> <del> token = "\321\202\320\265\320\272\321\201\321\202" # 'text' in Russian <add> token = "\321\202\320\265\320\272\321\201\321\202".dup # 'text' in Russian <ide> token.force_encoding(Encoding::BINARY) <ide> escaped_token = CGI::escape(token) <ide> <ide><path>actionpack/test/dispatch/debug_exceptions_test.rb <add># frozen_string_literal: true <ide> require "abstract_unit" <ide> <ide> class DebugExceptionsTest < ActionDispatch::IntegrationTest <ide> def call(env) <ide> }) <ide> assert_response 500 <ide> <del> assert_includes(body, CGI.escapeHTML(PP.pp(params, "", 200))) <add> assert_includes(body, CGI.escapeHTML(PP.pp(params, "".dup, 200))) <ide> end <ide> <ide> test "sets the HTTP charset parameter" do <ide><path>actionpack/test/dispatch/prefix_generation_test.rb <add># frozen_string_literal: true <ide> require "abstract_unit" <ide> require "rack/test" <ide> require "rails/engine" <ide> def to_param <ide> end <ide> <ide> def self.model_name <del> klass = "Post" <add> klass = "Post".dup <ide> def klass.name; self end <ide> <ide> ActiveModel::Name.new(klass) <ide><path>actionpack/test/dispatch/static_test.rb <add># frozen_string_literal: true <ide> require "abstract_unit" <ide> require "zlib" <ide> <ide> def test_handles_urls_with_bad_encoding <ide> end <ide> <ide> def test_handles_urls_with_ascii_8bit <del> assert_equal "Hello, World!", get("/doorkeeper%E3E4".force_encoding("ASCII-8BIT")).body <add> assert_equal "Hello, World!", get("/doorkeeper%E3E4".dup.force_encoding("ASCII-8BIT")).body <ide> end <ide> <ide> def test_handles_urls_with_ascii_8bit_on_win_31j <ide> silence_warnings do <ide> Encoding.default_internal = "Windows-31J" <ide> Encoding.default_external = "Windows-31J" <ide> end <del> assert_equal "Hello, World!", get("/doorkeeper%E3E4".force_encoding("ASCII-8BIT")).body <add> assert_equal "Hello, World!", get("/doorkeeper%E3E4".dup.force_encoding("ASCII-8BIT")).body <ide> end <ide> <ide> def test_handles_urls_with_null_byte <ide><path>actionpack/test/journey/router/utils_test.rb <add># frozen_string_literal: true <ide> require "abstract_unit" <ide> <ide> module ActionDispatch <ide> def test_uri_unescape <ide> end <ide> <ide> def test_uri_unescape_with_utf8_string <del> assert_equal "Šašinková", Utils.unescape_uri("%C5%A0a%C5%A1inkov%C3%A1".force_encoding(Encoding::US_ASCII)) <add> assert_equal "Šašinková", Utils.unescape_uri("%C5%A0a%C5%A1inkov%C3%A1".dup.force_encoding(Encoding::US_ASCII)) <ide> end <ide> <ide> def test_normalize_path_not_greedy <ide><path>actionview/lib/action_view/log_subscriber.rb <add># frozen_string_literal: true <ide> require "active_support/log_subscriber" <ide> <ide> module ActionView <ide> def cache_message(payload) # :doc: <ide> <ide> def log_rendering_start(payload) <ide> info do <del> message = " Rendering #{from_rails_root(payload[:identifier])}" <add> message = " Rendering #{from_rails_root(payload[:identifier])}".dup <ide> message << " within #{from_rails_root(payload[:layout])}" if payload[:layout] <ide> message <ide> end <ide><path>actionview/lib/action_view/template.rb <add># frozen_string_literal: true <ide> require "active_support/core_ext/object/try" <ide> require "active_support/core_ext/kernel/singleton_class" <ide> require "thread" <ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/money.rb <add># frozen_string_literal: true <ide> module ActiveRecord <ide> module ConnectionAdapters <ide> module PostgreSQL <ide> def cast_value(value) <ide> # (3) -$2.55 <ide> # (4) ($2.55) <ide> <del> value.sub!(/^\((.+)\)$/, '-\1') # (4) <add> value = value.sub(/^\((.+)\)$/, '-\1') # (4) <ide> case value <ide> when /^-?\D+[\d,]+\.\d{2}$/ # (1) <ide> value.gsub!(/[^-\d.]/, "")
18
Javascript
Javascript
avoid gc tracking of asyncresource in als
014feecc445c7dfc754378f2626cd43ee30a448d
<ide><path>lib/async_hooks.js <ide> const storageHook = createHook({ <ide> } <ide> }); <ide> <add>const defaultAlsResourceOpts = { requireManualDestroy: true }; <ide> class AsyncLocalStorage { <ide> constructor() { <ide> this.kResourceStore = Symbol('kResourceStore'); <ide> class AsyncLocalStorage { <ide> if (ObjectIs(store, this.getStore())) { <ide> return callback(...args); <ide> } <del> const resource = new AsyncResource('AsyncLocalStorage'); <del> return resource.runInAsyncScope(() => { <add> const resource = new AsyncResource('AsyncLocalStorage', <add> defaultAlsResourceOpts); <add> // Calling emitDestroy before runInAsyncScope avoids a try/finally <add> // It is ok because emitDestroy only schedules calling the hook <add> return resource.emitDestroy().runInAsyncScope(() => { <ide> this.enterWith(store); <ide> return callback(...args); <ide> });
1
Python
Python
implement ld/ldxx for ninja and fips
cbd3708c85e13b234e9ded0beaaf1780a537dc39
<ide><path>tools/gyp/pylib/gyp/generator/ninja.py <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> ld = os.path.join(build_to_root, value) <ide> if key == 'LD.host': <ide> ld_host = os.path.join(build_to_root, value) <add> if key == 'LDXX': <add> ldxx = os.path.join(build_to_root, value) <add> if key == 'LDXX.host': <add> ldxx_host = os.path.join(build_to_root, value) <ide> if key == 'NM': <ide> nm = os.path.join(build_to_root, value) <ide> if key == 'NM.host': <ide> def GenerateOutputForConfig(target_list, target_dicts, data, params, <ide> CommandWithWrapper('CXX.host', wrappers, cxx_host)) <ide> if flavor == 'win': <ide> master_ninja.variable('ld_host', ld_host) <add> master_ninja.variable('ldxx_host', ldxx_host) <ide> else: <ide> master_ninja.variable('ld_host', CommandWithWrapper( <ide> 'LINK', wrappers, ld_host))
1
Python
Python
fix mypy errors in `scripts/in_container`
96212cb8f5e7e1e8caba18d92f58755a33b07a67
<ide><path>scripts/in_container/check_junitxml_result.py <ide> with open(fname) as fh: <ide> root = ET.parse(fh) <ide> testsuite = root.find('.//testsuite') <del> num_failures = int(testsuite.get('failures')) <del> num_errors = int(testsuite.get('errors')) <del> if num_failures == 0 and num_errors == 0: <del> print(f'\n{TEXT_GREEN}==== No errors, no failures. Good to go! ===={TEXT_RESET}\n') <del> sys.exit(0) <add> if testsuite: <add> num_failures = testsuite.get('failures') <add> num_errors = testsuite.get('errors') <add> if num_failures == "0" and num_errors == "0": <add> print(f'\n{TEXT_GREEN}==== No errors, no failures. Good to go! ===={TEXT_RESET}\n') <add> sys.exit(0) <add> else: <add> print( <add> f'\n{TEXT_RED}==== Errors: {num_errors}, Failures: {num_failures}. ' <add> f'Failing the test! ===={TEXT_RESET}\n' <add> ) <add> sys.exit(1) <ide> else: <ide> print( <del> f'\n{TEXT_RED}==== Errors: {num_errors}, Failures: {num_failures}. ' <del> f'Failing the test! ===={TEXT_RESET}\n' <add> f'\n{TEXT_RED}==== The testsuite element does not exist in file {fname!r}. ' <add> f'Cannot evaluate status of the test! ===={TEXT_RESET}\n' <ide> ) <ide> sys.exit(1) <ide> except Exception as e:
1
Go
Go
fix service update of args
07b59ef210490df19f65da950d7d41176d104a31
<ide><path>api/client/service/update.go <ide> func runUpdate(dockerCli *client.DockerCli, flags *pflag.FlagSet, serviceID stri <ide> return err <ide> } <ide> <del> err = updateService(&service.Spec, flags) <add> err = updateService(flags, &service.Spec) <ide> if err != nil { <ide> return err <ide> } <ide> func runUpdate(dockerCli *client.DockerCli, flags *pflag.FlagSet, serviceID stri <ide> return nil <ide> } <ide> <del>func updateService(spec *swarm.ServiceSpec, flags *pflag.FlagSet) error { <add>func updateService(flags *pflag.FlagSet, spec *swarm.ServiceSpec) error { <ide> <ide> updateString := func(flag string, field *string) { <ide> if flags.Changed(flag) { <ide> func updateService(spec *swarm.ServiceSpec, flags *pflag.FlagSet) error { <ide> updateLabels(flags, &spec.Labels) <ide> updateString("image", &cspec.Image) <ide> updateSlice("command", &cspec.Command) <del> updateSlice("arg", &cspec.Command) <add> updateSlice("arg", &cspec.Args) <ide> updateListOpts("env", &cspec.Env) <ide> updateString("workdir", &cspec.Dir) <ide> updateString(flagUser, &cspec.User) <ide><path>api/client/service/update_test.go <add>package service <add> <add>import ( <add> "testing" <add> <add> "github.com/docker/docker/pkg/testutil/assert" <add> "github.com/docker/engine-api/types/swarm" <add>) <add> <add>func TestUpdateServiceCommandAndArgs(t *testing.T) { <add> flags := newUpdateCommand(nil).Flags() <add> flags.Set("command", "the") <add> flags.Set("command", "new") <add> flags.Set("command", "command") <add> flags.Set("arg", "the") <add> flags.Set("arg", "new args") <add> <add> spec := &swarm.ServiceSpec{} <add> cspec := &spec.TaskTemplate.ContainerSpec <add> cspec.Command = []string{"old", "command"} <add> cspec.Args = []string{"old", "args"} <add> <add> updateService(flags, spec) <add> assert.EqualStringSlice(t, cspec.Command, []string{"the", "new", "command"}) <add> assert.EqualStringSlice(t, cspec.Args, []string{"the", "new args"}) <add>} <ide><path>pkg/testutil/assert/assert.go <ide> func Equal(t TestingT, actual, expected interface{}) { <ide> } <ide> } <ide> <add>//EqualStringSlice compares two slices and fails the test if they do not contain <add>// the same items. <add>func EqualStringSlice(t TestingT, actual, expected []string) { <add> if len(actual) != len(expected) { <add> t.Fatalf("Expected (length %d): %q\nActual (length %d): %q", <add> len(expected), expected, len(actual), actual) <add> } <add> for i, item := range actual { <add> if item != expected[i] { <add> t.Fatalf("Slices differ at element %d, expected %q got %q", <add> i, expected[i], item) <add> } <add> } <add>} <add> <ide> // NilError asserts that the error is nil, otherwise it fails the test. <ide> func NilError(t TestingT, err error) { <ide> if err != nil {
3
Ruby
Ruby
inline path creation."
623e2d95af6c04dca5b3de94443095fb1d25ce3b
<ide><path>Library/Homebrew/test/cleanup_spec.rb <ide> describe "::cleanup_logs" do <ide> let(:path) { (HOMEBREW_LOGS/"delete_me") } <ide> <del> it "cleans all logs if prune is 0" do <add> before do <ide> path.mkpath <add> end <add> <add> it "cleans all logs if prune is 0" do <ide> described_class.new(days: 0).cleanup_logs <ide> expect(path).not_to exist <ide> end <ide> <ide> it "cleans up logs if older than 30 days" do <ide> allow_any_instance_of(Pathname).to receive(:ctime).and_return(31.days.ago) <ide> allow_any_instance_of(Pathname).to receive(:mtime).and_return(31.days.ago) <del> path.mkpath <ide> subject.cleanup_logs <ide> expect(path).not_to exist <ide> end <ide> <ide> it "does not clean up logs less than 30 days old" do <ide> allow_any_instance_of(Pathname).to receive(:ctime).and_return(15.days.ago) <ide> allow_any_instance_of(Pathname).to receive(:mtime).and_return(15.days.ago) <del> path.mkpath <ide> subject.cleanup_logs <ide> expect(path).to exist <ide> end
1
Ruby
Ruby
cache the instrumentor for a speed gain
fc088d4e8fdc7fcc710df094ce4ae6faa27d8c8d
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb <ide> def initialize(connection, logger = nil) #:nodoc: <ide> @runtime = 0 <ide> @query_cache_enabled = false <ide> @query_cache = {} <add> @instrumenter = ActiveSupport::Notifications.instrumenter <ide> end <ide> <ide> # Returns the human-readable name of the adapter. Use mixed case - one <ide> def current_savepoint_name <ide> <ide> def log(sql, name) <ide> name ||= "SQL" <del> instrumenter = ActiveSupport::Notifications.instrumenter <ide> info = {} <ide> <del> result = instrumenter.instrument("sql.active_record", <add> result = @instrumenter.instrument("sql.active_record", <ide> {:sql => sql, :name => name, :connection_id => object_id}, info) do <ide> yield <ide> end
1
Mixed
Javascript
remove converter scripts
3bc9e619f7822cf5bbd95ed8495c2063f6e26b6f
<ide><path>utils/converters/README.md <del>Utilities for converting model files to the Three.js JSON format. <del>It's necessary to install the [esm](https://www.npmjs.com/package/esm) npm package before you can use the converters. <del> <del>## obj2three.js <del> <del>Usage: <del> <del>``` <del>node -r esm obj2three.js model.obj <del>``` <del> <del>## fbx2three.js <del> <del>Usage: <del> <del>``` <del>node -r esm fbx2three.js model.fbx <del>``` <ide><path>utils/converters/fbx2three.js <del>import fs from 'fs'; <del>import path from 'path'; <del> <del>import { FBXLoader } from '../../examples/jsm/loaders/FBXLoader.js'; <del>import { ImageLoader, ImageUtils, LoaderUtils } from '../../build/three.module.js'; <del> <del>if ( process.argv.length <= 2 ) { <del> <del> console.log( `Usage: ${path.basename( __filename )} model.fbx` ); <del> process.exit( - 1 ); <del> <del>} <del> <del>// <del> <del>const PRECISION = 6; <del> <del>function parseNumber( key, value ) { <del> <del> return typeof value === 'number' ? parseFloat( value.toFixed( PRECISION ) ) : value; <del> <del>} <del> <del>global.window = { <del> innerWidth: 1024, <del> innerHeight: 768, <del> URL: { <del> <del> createObjectURL: function () { <del> <del> throw new Error( 'fbx2three: Images in binary format not yet supported.' ); <del> <del> } <del> <del> } <del>}; <del> <del>// HTML Images are not available, so use a Buffer instead. <del>ImageLoader.prototype.load = function ( url, onLoad ) { <del> <del> if ( this.path !== undefined ) url = this.path + url; <del> <del> // If image isn't found, try to ignore it. <del> if ( ! fs.existsSync( url ) ) { <del> <del> onLoad( new Buffer( '' ) ); <del> return; <del> <del> } <del> <del> onLoad( fs.readFileSync( url ) ); <del> <del>}; <del> <del>// Convert image buffer to data URL. <del>ImageUtils.getDataURL = function ( image ) { <del> <del> if ( ! ( image instanceof Buffer ) ) { <del> <del> throw new Error( 'fbx2three: Image should be loaded as Buffer.' ); <del> <del> } <del> <del> let dataURL = 'data:'; <del> dataURL += this.format === THREE.RGBAFormat ? 'image/png' : 'image/jpeg'; <del> dataURL += ';base64,'; <del> dataURL += image.toString( 'base64' ); <del> return dataURL; <del> <del>}; <del> <del>// <del> <del>const file = process.argv[ 2 ]; <del>const resourceDirectory = LoaderUtils.extractUrlBase( file ); <del>const loader = new FBXLoader(); <del> <del>const arraybuffer = fs.readFileSync( file ).buffer; <del>const object = loader.parse( arraybuffer, resourceDirectory ); <del>const content = JSON.stringify( object.toJSON(), parseNumber ); <del>fs.writeFileSync( path.basename( file, '.fbx' ) + '.json', content, 'utf8' ); <ide><path>utils/converters/obj2three.js <del>import fs from 'fs'; <del>import path from 'path'; <del> <del>import { OBJLoader } from '../../examples/jsm/loaders/OBJLoader.js'; <del> <del>if ( process.argv.length <= 2 ) { <del> <del> console.log( "Usage: " + path.basename( __filename ) + " model.obj" ); <del> process.exit( - 1 ); <del> <del>} <del> <del>// <del> <del>const PRECISION = 6; <del> <del>function parseNumber( key, value ) { <del> <del> return typeof value === 'number' ? parseFloat( value.toFixed( PRECISION ) ) : value; <del> <del>} <del> <del>const file = process.argv[ 2 ]; <del>const loader = new OBJLoader(); <del> <del>const text = fs.readFileSync( file, 'utf8' ); <del> <del>const content = JSON.stringify( loader.parse( text ).toJSON(), parseNumber ); <del>fs.writeFileSync( path.basename( file, '.obj' ) + '.json', content, 'utf8' );
3
Text
Text
remove unneeded node prefix
df7c3d066a433943c12e25327d3f76c679eb73ab
<ide><path>docs/building-atom.md <ide> atom][download]. <ide> find-generic-password -ws 'GitHub API Token'` on OSX to get your <ide> credentials). <ide> * Use the Windows GitHub shell and cd into `C:\Users\<user>\github\atom` <del>* Run `node script/bootstrap` <add>* Run `script\bootstrap` <ide> <ide> [download]: http://www.atom.io <ide> [win-node]: http://nodejs.org/download/
1
Text
Text
add chinese translation of js-spread
9c7dc5f3b8d7128cc2d5215b5a0c5351759deea1
<ide><path>docs/docs/02.2-jsx-spread.zh-CN.md <add>--- <add>id: jsx-spread-zh-CN <add>title: JSX 展开属性 (Spread Attributes) <add>permalink: jsx-spread-zh-CN.html <add>prev: jsx-in-depth-zh-CN.html <add>next: jsx-gotchas-zh-CN.html <add>--- <add> <add>如果你事先知道模块需要的全部 Props(属性),JSX 很容易地这样写: <add> <add>```javascript <add> var component = <Component foo={x} bar={y} />; <add>``` <add> <add>## 修改 Props 是不好的,明白吗 <add> <add>如果你不知道要设置哪些 Props,那么现在最好不要设置它: <add> <add>```javascript <add> var component = <Component />; <add> component.props.foo = x; // 不好 <add> component.props.bar = y; // 同样不好 <add>``` <add> <add>这样是反模式,因为 React 不能帮你检查属性类型(propTypes)。这样即使你的 属性类型有错误也不能得到清晰的错误提示。 <add> <add>Props 应该被当作禁止修改的。修改 props 对象可能会导致预料之外的结果,所以最好不要去修改 props 对象。 <add> <add>## 扩展属性 (Spread Attributes) <add> <add>现在你可以使用 JSX 的新特性 - 扩展属性: <add> <add>```javascript <add> var props = {}; <add> props.foo = x; <add> props.bar = y; <add> var component = <Component {...props} />; <add>``` <add> <add>传入对象的属性会被复制到模块内。 <add> <add>它能被多次使用,也可以和其它属性一起用。注意顺序很重要,后面的会覆盖掉前面的。 <add> <add>```javascript <add> var props = { foo: 'default' }; <add> var component = <Component {...props} foo={'override'} />; <add> console.log(component.props.foo); // 'override' <add>``` <add> <add>## 这个奇怪的 `...` 标记是什么? <add> <add>这个 `...` 操作符(也被叫做)已经被 [ES6 数组](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator) 支持。相关的还有 ES7 规范草案中的 [Object 剩余和展开属性(Rest and Spread Properties)](https://github.com/sebmarkbage/ecmascript-rest-spread)。我们利用了这些还在制定中标准中已经被支持的特性来使 JSX 拥有更优雅的语法。 <ide>\ No newline at end of file
1
Text
Text
add references to immutabledata.md
aaf15c3dc9ef008c2288e88e6d28d992b8465a43
<ide><path>docs/faq/ImmutableData.md <ide> Immutability can bring increased performance to your app, and leads to simpler p <ide> <ide> In particular, immutability in the context of a Web app enables sophisticated change detection techniques to be implemented simply and cheaply, ensuring the computationally expensive process of updating the DOM occurs only when it absolutely has to (a cornerstone of React’s performance improvements over other libraries). <ide> <add>#### Further information <add> <add>**Articles** <add>- [Introduction to Immutable.js and Functional Programming Concepts](https://auth0.com/blog/intro-to-immutable-js/) <add>- [JavaScript Immutability presentation (PDF - see slide 12 for benefits)](https://www.jfokus.se/jfokus16/preso/JavaScript-Immutability--Dont-Go-Changing.pdf) <add>- [Immutable.js - Immutable Collections for JavaScript](https://facebook.github.io/immutable-js/#the-case-for-immutability) <add>- [React: Optimizing Performance](https://facebook.github.io/react/docs/optimizing-performance.html) <add>- [JavaScript Application Architecture On The Road To 2015](https://medium.com/google-developers/javascript-application-architecture-on-the-road-to-2015-d8125811101b#.djje0rfys) <add> <ide> <ide> <a id="why-is-immutability-required"></a> <ide> ## Why is immutability required by Redux? <ide> Such [shallow checking requires immutability](#redux-shallow-checking-requires-i <ide> - Immutable data management ultimately makes data handling safer. <ide> - Time-travel debugging requires that reducers be pure functions with no side effects, so that you can correctly jump between different states. <ide> <add>#### Further Information <add> <add>**Documentation** <add>- [Recipes: Prerequisite Reducer Concepts](http://redux.js.org/docs/recipes/reducers/PrerequisiteConcepts.html) <add> <add>**Discussions** <add>- [Reddit: Why Redux Needs Reducers To Be Pure Functions](https://www.reddit.com/r/reactjs/comments/5ecqqv/why_redux_need_reducers_to_be_pure_functions/dacmmjh/?context=3) <add> <ide> <ide> <a id="redux-shallow-checking-requires-immutability"></a> <ide> ## Why does Redux’s use of shallow equality checking require immutability? <ide> Redux's use of shallow equality checking requires immutability if any connected <ide> <ide> <a id="shallow-and-deep-equality-checking"></a> <ide> ### How do shallow and deep equality checking differ? <del>Shallow equality checking simply checks that two different _variables_ reference the same object; in contrast, deep equality checking must check every _value_ of two objects' properties. <add>Shallow equality checking (or _reference equality_) simply checks that two different _variables_ reference the same object; in contrast, deep equality checking (or _value equality_) must check every _value_ of two objects' properties. <ide> <ide> A shallow equality check is therefore as simple (and as fast) as `a === b`, whereas a deep equality check involves a recursive traversal through the properties of two objects, comparing the value of each property at each step. <ide> <ide> It's for this improvement in performance that Redux uses shallow equality checking. <ide> <add>#### Further Information <add> <add>**Articles** <add>- [Pros and Cons of using immutability with React.js](http://reactkungfu.com/2015/08/pros-and-cons-of-using-immutability-with-react-js/) <add> <ide> <ide> <a id="how-redux-uses-shallow-checking"></a> <ide> ### How does Redux use shallow equality checking? <ide> Redux uses shallow equality checking in its `combineReducers` function to return either a new mutated copy of the root state object, or, if no mutations have been made, the current root state object. <ide> <add>#### Further Information <add> <add>**Documentation** <add>- [API: combineReducers](http://redux.js.org/docs/api/combineReducers.html) <add> <ide> <del><a id=“how-combine-reducers-uses-shallow-checking”></a> <add><a id="how-combine-reducers-uses-shallow-checking"></a> <ide> #### How does `combineReducers` use shallow equality checking? <ide> The [suggested structure](http://redux.js.org/docs/faq/Reducers.html#reducers-share-state) for a Redux store is to split the state object into multiple "slices" or "domains" by key, and provide a separate reducer function to manage each individual data slice. <ide> <ide> After the iterations have completed, `combineReducers` will check the state of t <ide> <ide> This is worth emphasising: *If the reducers all return the same `state` object passed to them, then `combineReducers` will return the _current_ root state object, not the newly updated one.* <ide> <add>#### Further Information <add> <add>**Documentation** <add>- [API: combineReducers](http://redux.js.org/docs/api/combineReducers.html) <add>- [Redux FAQ - How do I share state between two reducers? do I have to use `combineReducers`?](http://redux.js.org/docs/faq/Reducers.html#reducers-share-state) <add> <add>**Video** <add>- [Egghead.io: Redux: Implementing combineReducers() from Scratch](https://egghead.io/lessons/javascript-redux-implementing-combinereducers-from-scratch) <add> <ide> <ide> <a id="how-react-redux-uses-shallow-checking"></a> <ide> ### How does React-Redux use shallow equality checking? <ide> It detects a change by keeping a reference to the root state object, and a refer <ide> <ide> It then runs a shallow equality check on its reference to the root state object and the state object passed to it, and a separate series of shallow checks on each reference to the props object’s values and those that are returned from running the `mapStateToProps` function again. <ide> <add>#### Further Information <add> <add>**Documentation** <add>- [React-Redux Bindings](http://redux.js.org/docs/basics/UsageWithReact.html) <add> <add>**Articles** <add>- [API: React-Redux’s connect function and `mapStateToProps`](https://github.com/reactjs/react-redux/blob/master/docs/api.md#connectmapstatetoprops-mapdispatchtoprops-mergeprops-options) <add>- [Troubleshooting: My views aren’t updating when something changes outside of Redux](https://github.com/reactjs/react-redux/blob/f4d55840a14601c3a5bdc0c3d741fc5753e87f66/docs/troubleshooting.md#my-views-arent-updating-when-something-changes-outside-of-redux) <add> <add> <ide> ### Why does React-Redux shallowly check each value within the props object returned from `mapStateToProp`? <ide> React-Redux performs a shallow equality check on on each _value_ within the props object, not on the props object itself. <ide> <ide> As such, a shallow equality check of the props object returned from repeated cal <ide> <ide> React-Redux therefore maintains separate references to each _value_ in the returned props object. <ide> <add>#### Further Information <add> <add>**Articles** <add>- [React.js pure render performance anti-pattern](https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.gh07cm24f) <add> <ide> <ide> <a id="how-react-redux-determines-need-for-re-rendering"></a> <ide> ### How does React-Redux use shallow equality checking to determine whether a component needs re-rendering? <ide> export default connect(mapStateToProps)(TodoApp) <ide> <ide> If the shallow equality check fails between the new values returned from `mapStateToProps` and the previous values that React-Redux kept a reference to, then a re-rendering of the component will be triggered. <ide> <add>#### Further Information <add> <add>**Articles** <add>- [Practical Redux, Part 6: Connected Lists, Forms, and Performance](http://blog.isquaredsoftware.com/2017/01/practical-redux-part-6-connected-lists-forms-and-performance/) <add>- [React.js Pure Render Performance Anti-Pattern](https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.sb708slq6) <add>- [High Performance Redux Apps](http://somebody32.github.io/high-performance-redux/) <add> <add>**Discussions** <add>- [#1816: Component connected to state with `mapStateToProps`](https://github.com/reactjs/redux/issues/1816) <add>- [#300: Potential connect() optimization](https://github.com/reactjs/react-redux/issues/300) <add> <ide> <ide> <a id="no-shallow-equality-checking-with-mutable-objects"></a> <ide> ### Why will shallow equality checking not work with mutable objects? <ide> param === returnVal; <ide> <ide> The shallow check of `param` and `returnValue` simply checks whether both variables reference the same object, which they do.`mutateObj()` may return a mutated version of `obj`, but it's still the same object as that passed in. The fact that its values have been changed within `mutateObj` matters not at all to a shallow check. <ide> <add>#### Further Information <add> <add>**Articles** <add>- [Pros and Cons of using immutability with React.js](http://reactkungfu.com/2015/08/pros-and-cons-of-using-immutability-with-react-js/) <add> <ide> <ide> <a id="shallow-checking-problems-with-redux"></a> <ide> ### Does shallow equality checking with a mutable object cause problems with Redux? <ide> Accordingly, `combineReducers` will not set its `hasChanged` flag, even though t <ide> <ide> The store will still be updated with the new values for the root state, but because the root state object itself is still the same object, libraries that bind to Redux, such as React-Redux, will not be aware of the state’s mutation, and so will not trigger a wrapped component’s re-rendering. <ide> <add>#### Further Information <add> <add>**Documentation** <add>- [Recipes: Immutable Update Patterns](http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) <add>- [Troubleshooting: Never mutate reducer arguments](http://redux.js.org/docs/Troubleshooting.html#never-mutate-reducer-arguments) <add> <ide> <ide> <a id="shallow-checking-problems-with-react-redux"></a> <ide> ### Why does a reducer mutating the state prevent React-Redux from re-rendering a wrapped component? <ide> If a Redux reducer directly mutates, and returns, the state object passed into it, the values of the root state object will change, but the object itself will not. <ide> <ide> Because React-Redux performs a shallow check on the root state object to determine if its wrapped components need re-rendering or not, it will not be able to detect the state mutation, and so will not trigger a re-rendering. <ide> <add>#### Further Information <add> <add>**Documentation** <add>- [Troubleshooting: My views aren’t updating when something changes outside of Redux](https://github.com/reactjs/react-redux/blob/f4d55840a14601c3a5bdc0c3d741fc5753e87f66/docs/troubleshooting.md#my-views-arent-updating-when-something-changes-outside-of-redux) <add> <ide> <ide> <a id="shallow-checking-stops-component-re-rendering"></a> <ide> ### Why does a selector mutating and returning a persistent object to `mapStateToProps` prevent React-Redux from re-rendering a wrapped component? <ide> a.userRecord === b.userRecord; <ide> <ide> Note that, conversely, if an _immutable_ object is used, the [component may re-render when it should not](#immutability-issues-with-react-redux). <ide> <add>#### Further Information <add> <add>**Articles** <add>- [Practical Redux, Part 6: Connected Lists, Forms, and Performance](http://blog.isquaredsoftware.com/2017/01/practical-redux-part-6-connected-lists-forms-and-performance/) <add> <add>**Discussions** <add>- [#1948: Is getMappedItems an anti-pattern in mapStateToProps?](https://github.com/reactjs/redux/issues/1948) <add> <ide> <ide> <a id="immutability-enables-shallow-checking"></a> <ide> ### How does immutability enable a shallow check to detect object mutations? <ide> If an object is immutable, any changes that need to be made to it within a function must be made to a _copy_ of the object. <ide> <del>This mutated copy is a _separate_ object from that passed into the function, and so when it is returned, a shallow check will identify it as being a different object from that passed in, and so return false. <add>This mutated copy is a _separate_ object from that passed into the function, and so when it is returned, a shallow check will identify it as being a different object from that passed in, and so will fail. <add> <add>#### Further Information <add> <add>**Articles** <add>- [Pros and Cons of using immutability with React.js](http://reactkungfu.com/2015/08/pros-and-cons-of-using-immutability-with-react-js/) <ide> <ide> <ide> <a id="immutability-issues-with-redux"></a> <ide> That’s perfectly OK when you mutate the copy, but in the context of a reducer, <ide> <ide> To prevent this from happening, you must *always return the state slice object that’s passed into a reducer if the reducer does not mutate the state.* <ide> <add>#### Further Information <add> <add>**Articles** <add>- [React.js pure render performance anti-pattern](https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.5hmnwygsy) <add>- [Building Efficient UI with React and Redux](https://www.toptal.com/react/react-redux-and-immutablejs) <add> <ide> <ide> <a id="immutability-issues-with-react-redux"></a> <ide> ### How can immutability in `mapStateToProps` cause components to render unnecessarily? <ide> a.visibleToDos === b.visibleToDos; <ide> <ide> Note that, conversely, if the values in your props object refer to mutable objects, [your component may not render when it should](#shallow-checking-stops-component-re-rendering). <ide> <add>### Further Information <add> <add>**Articles** <add>- [React.js pure render performance anti-pattern](https://medium.com/@esamatti/react-js-pure-render-performance-anti-pattern-fb88c101332f#.b8bpx1ncj) <add>- [Building Efficient UI with React and Redux](https://www.toptal.com/react/react-redux-and-immutablejs) <add>- [ImmutableJS: worth the price?](https://medium.com/@AlexFaunt/immutablejs-worth-the-price-66391b8742d4#.a3alci2g8) <add> <ide> <ide> <a id="do-i-have-to-use-immutable-js"></a> <ide> ## What approaches are there for handling data immutably? Do I have to use Immutable.js? <ide> You do not need to use Immutable.JS with Redux. Plain JavaScript, if written correctly, is perfectly capable of providing immutability without having to use an immutable-focused library. <ide> <ide> However, guaranteeing immutability with JavaScript is difficult, and it can be easy to mutate an object accidentally, causing bugs in your app that are extremely difficult to locate. For this reason, using an immutable update utility library such as Immutable.JS can significantly improve the reliability of your app, and make your app’s development much easier. <ide> <add>### Further Information <add> <add>**Discussions** <add>- [#1185: Question: Should I use immutable data structures?](https://github.com/reactjs/redux/issues/1422) <add>- [Introduction to Immutable.js and Functional Programming Concepts](https://auth0.com/blog/intro-to-immutable-js/) <add> <ide> <ide> <a id="issues-with-es6-for-immutable-ops"></a> <ide> ## What are the issues with using plain JavaScript for immutable operations? <ide> JavaScript was never designed to provide guaranteed immutable operations. Accordingly, there are several issues you need to be aware of if you choose to use it for your immutable operations in your Redux app. <ide> <del>#### Accidental Object Mutation <add>### Accidental Object Mutation <ide> With JavaScript, you can accidentally mutate an object (such as the Redux state tree) quite easily without realising it. For example, updating deeply nested properties, creating a new *reference* to an object instead of a new object, or performing a shallow copy rather than a deep copy, can all lead to inadvertent object mutations, and can trip up even the most experienced JavaScript coder. <ide> <ide> To avoid these issues, ensure you follow the recommended [immutable update patterns for ES6](http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html). <ide> <del>#### Verbose Code <add>### Verbose Code <ide> Updating complex nested state trees can lead to verbose code that is tedious to write and difficult to debug. <ide> <del>#### Poor Performance <add>### Poor Performance <ide> Operating on JavaScript objects and arrays in an immutable way can be slow, particularly as your state tree grows larger. <ide> <ide> Remember, to change an immutable object, you must mutate a _copy_ of it, and copying large objects can be slow as every property must be copied. <ide> <del>In contrast, immutable libraries such as Immutable.js can employ sophisticated optimization techniques such as [structural sharing]( http://www.slideshare.net/mohitthatte/a-deep-dive-into-clojures-data-structures-euroclojure-2015) , which effectively returns a new object that reuses much of the existing object being copied from. <add>In contrast, immutable libraries such as Immutable.js can employ sophisticated optimization techniques such as [structural sharing](http://www.slideshare.net/mohitthatte/a-deep-dive-into-clojures-data-structures-euroclojure-2015) , which effectively returns a new object that reuses much of the existing object being copied from. <ide> <ide> For copying very large objects, [plain JavaScript can be over 100 times slower](https://medium.com/@dtinth/immutable-js-persistent-data-structures-and-structural-sharing-6d163fbd73d2#.z1g1ofrsi) than an optimized immutable library. <ide> <add>#### Further Information <add> <ide> **Documentation** <ide> - [Immutable Update Patterns for ES6](http://redux.js.org/docs/recipes/reducers/ImmutableUpdatePatterns.html) <add> <add>**Articles** <add>- [Immutable.js, persistent data structures and structural sharing](https://medium.com/@dtinth/immutable-js-persistent-data-structures-and-structural-sharing-6d163fbd73d2#.a2jimoiaf) <add>- [A deep dive into Clojure’s data structures](http://www.slideshare.net/mohitthatte/a-deep-dive-into-clojures-data-structures-euroclojure-2015) <add>- [Introduction to Immutable.js and Functional Programming Concepts](https://auth0.com/blog/intro-to-immutable-js/) <add>- [JavaScript and Immutability](http://t4d.io/javascript-and-immutability/) <add>- [Immutable Javascript using ES6 and beyond](http://wecodetheweb.com/2016/02/12/immutable-javascript-using-es6-and-beyond/) <add>- [Pros and Cons of using immutability with React.js - React Kung Fu](http://reactkungfu.com/2015/08/pros-and-cons-of-using-immutability-with-react-js/)
1
Python
Python
raise exception if django version used is < 1.8
0c5d01ddedb040fe224deebaeea4ad62b92c254d
<ide><path>celery/fixups/django.py <ide> <ide> from celery import _state <ide> from celery import signals <del>from celery.exceptions import FixupWarning <add>from celery.exceptions import FixupWarning, ImproperlyConfigured <ide> <ide> __all__ = ['DjangoFixup', 'fixup'] <ide> <ide> def _maybe_close_fd(fh): <ide> pass <ide> <ide> <add>def _verify_django_version(django): <add> if django.VERSION < (1, 8): <add> raise ImproperlyConfigured('Celery 4.x requires Django 1.8 or later.') <add> <add> <ide> def fixup(app, env='DJANGO_SETTINGS_MODULE'): <ide> """Install Django fixup if settings module environment is set.""" <ide> SETTINGS_MODULE = os.environ.get(env) <ide> def fixup(app, env='DJANGO_SETTINGS_MODULE'): <ide> except ImportError: <ide> warnings.warn(FixupWarning(ERR_NOT_INSTALLED)) <ide> else: <add> _verify_django_version(django) <ide> return DjangoFixup(app).install() <ide> <ide> <ide><path>t/unit/fixups/test_django.py <ide> def test_fixup(self, patching): <ide> fixup(self.app) <ide> Fixup.assert_not_called() <ide> with mock.module_exists('django'): <add> import django <add> django.VERSION = (1, 10, 1) <ide> fixup(self.app) <ide> Fixup.assert_called() <ide>
2