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
|
|---|---|---|---|---|---|
Ruby
|
Ruby
|
fix rdoc markup [ci skip]
|
8e7998cd5aff3f1351118ee3b254548dce4ba08e
|
<ide><path>actionpack/lib/action_controller/metal/mime_responds.rb
<ide> module MimeResponds
<ide> # and accept Rails' defaults, life will be much easier.
<ide> #
<ide> # If you need to use a MIME type which isn't supported by default, you can register your own handlers in
<del> # config/initializers/mime_types.rb as follows.
<add> # +config/initializers/mime_types.rb+ as follows.
<ide> #
<ide> # Mime::Type.register "image/jpg", :jpg
<ide> #
<del> # Respond to also allows you to specify a common block for different formats by using any:
<add> # Respond to also allows you to specify a common block for different formats by using +any+:
<ide> #
<ide> # def index
<ide> # @people = Person.all
<ide> module MimeResponds
<ide> # format.html.none { render "trash" }
<ide> # end
<ide> #
<del> # Variants also support common `any`/`all` block that formats have.
<add> # Variants also support common +any+/+all+ block that formats have.
<ide> #
<ide> # It works for both inline:
<ide> #
<ide> module MimeResponds
<ide> # request.variant = [:tablet, :phone]
<ide> #
<ide> # which will work similarly to formats and MIME types negotiation. If there will be no
<del> # :tablet variant declared, :phone variant will be picked:
<add> # +:tablet+ variant declared, +:phone+ variant will be picked:
<ide> #
<ide> # respond_to do |format|
<ide> # format.html.none
| 1
|
Java
|
Java
|
introduce defaultvaluesreactnativeconfig constant
|
5c9c901d0c76f9349ab2351510ce0e7e7ba07a26
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/fabric/ReactNativeConfig.java
<ide> */
<ide> @DoNotStrip
<ide> public interface ReactNativeConfig {
<add>
<add> public final ReactNativeConfig DefaultValuesReactNativeConfig =
<add> new ReactNativeConfig() {
<add> @Override
<add> public boolean getBool(@NonNull String param) {
<add> return false;
<add> }
<add>
<add> @Override
<add> public long getInt64(@NonNull String param) {
<add> return 0;
<add> }
<add>
<add> @Override
<add> public String getString(@NonNull String param) {
<add> return null;
<add> }
<add>
<add> @Override
<add> public double getDouble(@NonNull String param) {
<add> return 0;
<add> }
<add> };
<add>
<ide> /**
<ide> * Get a boolean param by string name. Default should be false.
<ide> *
<ide><path>packages/rn-tester/android/app/src/main/java/com/facebook/react/uiapp/RNTesterApplication.java
<ide> import com.facebook.react.config.ReactFeatureFlags;
<ide> import com.facebook.react.fabric.ComponentFactory;
<ide> import com.facebook.react.fabric.CoreComponentsRegistry;
<del>import com.facebook.react.fabric.EmptyReactNativeConfig;
<ide> import com.facebook.react.fabric.FabricJSIModuleProvider;
<add>import com.facebook.react.fabric.ReactNativeConfig;
<ide> import com.facebook.react.module.model.ReactModuleInfo;
<ide> import com.facebook.react.module.model.ReactModuleInfoProvider;
<ide> import com.facebook.react.shell.MainReactPackage;
<ide> public JSIModuleProvider<UIManager> getJSIModuleProvider() {
<ide> reactApplicationContext,
<ide> componentFactory,
<ide> // TODO: T71362667 add ReactNativeConfig's support in RNTester
<del> new EmptyReactNativeConfig(),
<add> ReactNativeConfig.DefaultValuesReactNativeConfig,
<ide> viewManagerRegistry);
<ide> }
<ide> });
| 2
|
Go
|
Go
|
use strconv instead of fmt.sprintf()
|
07b2e4cb7945e08feec99a7d1d2e80f0e6dc5aed
|
<ide><path>client/build_prune.go
<ide> package client // import "github.com/docker/docker/client"
<ide> import (
<ide> "context"
<ide> "encoding/json"
<del> "fmt"
<ide> "net/url"
<add> "strconv"
<ide>
<ide> "github.com/docker/docker/api/types"
<ide> "github.com/docker/docker/api/types/filters"
<ide> func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePru
<ide> if opts.All {
<ide> query.Set("all", "1")
<ide> }
<del> query.Set("keep-storage", fmt.Sprintf("%d", opts.KeepStorage))
<del> filters, err := filters.ToJSON(opts.Filters)
<add> query.Set("keep-storage", strconv.Itoa(int(opts.KeepStorage)))
<add> f, err := filters.ToJSON(opts.Filters)
<ide> if err != nil {
<ide> return nil, errors.Wrap(err, "prune could not marshal filters option")
<ide> }
<del> query.Set("filters", filters)
<add> query.Set("filters", f)
<ide>
<ide> serverResp, err := cli.post(ctx, "/build/prune", query, nil, nil)
<ide> defer ensureReaderClosed(serverResp)
<ide> func (cli *Client) BuildCachePrune(ctx context.Context, opts types.BuildCachePru
<ide> }
<ide>
<ide> if err := json.NewDecoder(serverResp.body).Decode(&report); err != nil {
<del> return nil, fmt.Errorf("Error retrieving disk usage: %v", err)
<add> return nil, errors.Wrap(err, "error retrieving disk usage")
<ide> }
<ide>
<ide> return &report, nil
| 1
|
Text
|
Text
|
remove double reference
|
8135cf594b23206dd62ff619e91eec130d2862a1
|
<ide><path>CHANGELOG-5.6.md
<ide>
<ide> ### Requests
<ide> - ⚠️ Return `false` from `expectsJson()` when requested content type isn't explicit ([#22506](https://github.com/laravel/framework/pull/22506), [3624d27](https://github.com/laravel/framework/commit/3624d2702c783d13bd23b852ce35662bee9a8fea))
<del>- Added `Request::getSession()` method ([e546a5b](https://github.com/laravel/framework/commit/e546a5b83aa9fb5bbcb8e80db0c263c09b5d5dd6), [e546a5b](https://github.com/laravel/framework/commit/e546a5b83aa9fb5bbcb8e80db0c263c09b5d5dd6))
<add>- Added `Request::getSession()` method ([e546a5b](https://github.com/laravel/framework/commit/e546a5b83aa9fb5bbcb8e80db0c263c09b5d5dd6))
<ide> - Accept array of keys on `Request::hasAny()` ([#22952](https://github.com/laravel/framework/pull/22952))
<ide>
<ide> ### Responses
| 1
|
Text
|
Text
|
document the location of experimental binary
|
01cfb70b0abb4a49c3f04101d8a8d6f59cd69ad0
|
<ide><path>experimental/README.md
<ide> issues associated with it. If necessary, links are provided to additional
<ide> documentation on an issue. As an active Docker user and community member,
<ide> please feel free to provide any feedback on these features you wish.
<ide>
<del>## Install Docker experimental
<add>## Install Docker experimental
<ide>
<ide> Unlike the regular Docker binary, the experimental channels is built and updated nightly on TO.BE.ANNOUNCED. From one day to the next, new features may appear, while existing experimental features may be refined or entirely removed.
<ide>
<ide> Unlike the regular Docker binary, the experimental channels is built and updated
<ide>
<ide> This command downloads a test image and runs it in a container.
<ide>
<add>### Get the Linux binary
<add>To download the latest experimental `docker` binary for Linux,
<add>use the following URLs:
<add>
<add> https://experimental.docker.com/builds/Linux/i386/docker-latest
<add>
<add> https://experimental.docker.com/builds/Linux/x86_64/docker-latest
<add>
<add>After downloading the appropriate binary, you can follow the instructions
<add>[here](https://docs.docker.com/installation/binaries/#get-the-docker-binary) to run the `docker` daemon.
<add>
<add>> **Note**
<add>>
<add>> 1) You can get the MD5 and SHA256 hashes by appending .md5 and .sha256 to the URLs respectively
<add>>
<add>> 2) You can get the compressed binaries by appending .tgz to the URLs
<add>
<ide> ## Current experimental features
<ide>
<ide> * [Support for Docker plugins](plugins.md)
| 1
|
PHP
|
PHP
|
add `@since` tags
|
834c7cc827d5b33ab55227dda86a1034a10782cf
|
<ide><path>src/View/View.php
<ide> public function loadHelper($name, array $config = [])
<ide> * Check whether the view has been rendered.
<ide> *
<ide> * @return bool
<add> * @since 3.7.0
<ide> */
<ide> public function hasRendered()
<ide> {
<ide> public function hasRendered()
<ide> * @param string $subDir Sub-directory name.
<ide> * @return $this
<ide> * @see \Cake\View\View::$subDir
<add> * @since 3.7.0
<ide> */
<ide> public function setSubDir($subDir)
<ide> {
<ide> public function setSubDir($subDir)
<ide> *
<ide> * @return string
<ide> * @see \Cake\View\View::$subDir
<add> * @since 3.7.0
<ide> */
<ide> public function getSubDir()
<ide> {
<ide> public function getSubDir()
<ide> * Returns the plugin name.
<ide> *
<ide> * @return string|null
<add> * @since 3.7.0
<ide> */
<ide> public function getPlugin()
<ide> {
<ide> public function getPlugin()
<ide> *
<ide> * @param string $name Plugin name.
<ide> * @return $this
<add> * @since 3.7.0
<ide> */
<ide> public function setPlugin($name)
<ide> {
<ide> public function setPlugin($name)
<ide> * @param string $elementCache Cache config name.
<ide> * @return $this
<ide> * @see \Cake\View\View::$elementCache
<add> * @since 3.7.0
<ide> */
<ide> public function setElementCache($elementCache)
<ide> {
| 1
|
Javascript
|
Javascript
|
remove stray console.log comment
|
07b7e8424def8408d6d394ebdfa00c5877c36f0c
|
<ide><path>src/browser/__tests__/validateDOMNesting-test.js
<ide> var formattingTags = [
<ide> function isTagStackValid(stack) {
<ide> for (var i = 0; i < stack.length; i++) {
<ide> if (!isTagValidInContext(stack[i], stack.slice(0, i))) {
<del> //console.log('invalid', stack[i], stack.slice(0, i));
<ide> return false;
<ide> }
<ide> }
| 1
|
Ruby
|
Ruby
|
assign rails.cache to sprockets
|
4a2b3275a167d6452c4c6b4453bc7406d13e8377
|
<ide><path>actionpack/lib/sprockets/railtie.rb
<ide> def asset_environment(app)
<ide>
<ide> env.logger = Rails.logger
<ide>
<add> if env.respond_to?(:cache)
<add> env.cache = Rails.cache
<add> end
<add>
<ide> if assets.compress
<ide> # temporarily hardcode default JS compressor to uglify. Soon, it will work
<ide> # the same as SCSS, where a default plugin sets the default.
| 1
|
Javascript
|
Javascript
|
provide rtl support in navigationcardstack
|
fc864a22bd00464c4219c6ddb6aa3d923aeb26dc
|
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStackPanResponder.js
<ide> 'use strict';
<ide>
<ide> const Animated = require('Animated');
<add>const I18nManager = require('I18nManager');
<ide> const NavigationAbstractPanResponder = require('NavigationAbstractPanResponder');
<ide>
<ide> const clamp = require('clamp');
<ide> class NavigationCardStackPanResponder extends NavigationAbstractPanResponder {
<ide> const distance = isVertical ?
<ide> layout.height.__getValue() :
<ide> layout.width.__getValue();
<add> const currentValue = I18nManager.isRTL && axis === 'dx' ?
<add> this._startValue + (gesture[axis] / distance) :
<add> this._startValue - (gesture[axis] / distance);
<ide>
<ide> const value = clamp(
<ide> index - 1,
<del> this._startValue - (gesture[axis] / distance),
<add> currentValue,
<ide> index
<ide> );
<ide>
<ide> class NavigationCardStackPanResponder extends NavigationAbstractPanResponder {
<ide> const isVertical = this._isVertical;
<ide> const axis = isVertical ? 'dy' : 'dx';
<ide> const index = props.navigationState.index;
<del> const distance = gesture[axis];
<add> const distance = I18nManager.isRTL && axis === 'dx' ?
<add> -gesture[axis] :
<add> gesture[axis];
<ide>
<ide> props.position.stopAnimation((value: number) => {
<ide> this._reset();
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationCardStackStyleInterpolator.js
<ide> */
<ide> 'use strict';
<ide>
<add>const I18nManager = require('I18nManager');
<add>
<ide> import type {
<ide> NavigationSceneRendererProps,
<ide> } from 'NavigationTypeDefinition';
<ide> function forHorizontal(props: NavigationSceneRendererProps): Object {
<ide> const index = scene.index;
<ide> const inputRange = [index - 1, index, index + 1];
<ide> const width = layout.initWidth;
<add> const outputRange = I18nManager.isRTL ?
<add> ([-width, 0, 10]: Array<number>) :
<add> ([width, 0, -10]: Array<number>);
<add>
<ide>
<ide> const opacity = position.interpolate({
<ide> inputRange,
<ide> function forHorizontal(props: NavigationSceneRendererProps): Object {
<ide> const translateY = 0;
<ide> const translateX = position.interpolate({
<ide> inputRange,
<del> outputRange: ([width, 0, -10]: Array<number>),
<add> outputRange,
<ide> });
<ide>
<ide> return {
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationHeaderBackButton.js
<ide> const React = require('react');
<ide> const ReactNative = require('react-native');
<ide>
<ide> const {
<add> I18nManager,
<ide> Image,
<ide> Platform,
<ide> StyleSheet,
<ide> const styles = StyleSheet.create({
<ide> height: 24,
<ide> width: 24,
<ide> margin: Platform.OS === 'ios' ? 10 : 16,
<del> resizeMode: 'contain'
<add> resizeMode: 'contain',
<add> transform: [{scaleX: I18nManager.isRTL ? -1 : 1}],
<ide> }
<ide> });
<ide>
<ide><path>Libraries/CustomComponents/NavigationExperimental/NavigationHeaderStyleInterpolator.js
<ide> */
<ide> 'use strict';
<ide>
<add>const I18nManager = require('I18nManager');
<ide>
<ide> import type {
<ide> NavigationSceneRendererProps,
<ide> function forCenter(props: NavigationSceneRendererProps): Object {
<ide> {
<ide> translateX: position.interpolate({
<ide> inputRange: [ index - 1, index + 1 ],
<del> outputRange: ([ 200, -200 ]: Array<number>),
<add> outputRange: I18nManager.isRTL ?
<add> ([ -200, 200 ]: Array<number>) :
<add> ([ 200, -200 ]: Array<number>),
<ide> }),
<ide> }
<ide> ],
| 4
|
Javascript
|
Javascript
|
fix version check test
|
2435b66840179a62826f917ea811c512a5e6abc3
|
<ide><path>grunt/tasks/version-check.js
<ide> var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
<ide>
<ide> module.exports = function() {
<ide> var reactVersion = reactVersionExp.exec(
<del> grunt.file.read('./src/core/React.js')
<add> grunt.file.read('./src/browser/React.js')
<ide> )[1];
<ide> var npmReactVersion = grunt.file.readJSON('./npm-react/package.json').version;
<ide> var reactToolsVersion = grunt.config.data.pkg.version;
| 1
|
Python
|
Python
|
fix yolos onnx export test
|
c99e984657b64dd8f19de74405bbf13763ab4f2b
|
<ide><path>tests/onnx/test_onnx_v2.py
<ide> def _onnx_export(self, test_name, name, model_name, feature, onnx_config_class_c
<ide> model_class = FeaturesManager.get_model_class_for_feature(feature)
<ide> config = AutoConfig.from_pretrained(model_name)
<ide> model = model_class.from_config(config)
<add>
<add> # Dynamic axes aren't supported for YOLO-like models. This means they cannot be exported to ONNX on CUDA devices.
<add> # See: https://github.com/ultralytics/yolov5/pull/8378
<add> if model.__class__.__name__.startswith("Yolos") and device != "cpu":
<add> return
<add>
<ide> onnx_config = onnx_config_class_constructor(model.config)
<ide>
<ide> if is_torch_available():
| 1
|
Java
|
Java
|
add aot processing of bean aliases
|
403cfefc28c1c4999023f0fa4d2daefbbaca275f
|
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationsAotContribution.java
<ide> import org.springframework.javapoet.ClassName;
<ide> import org.springframework.javapoet.CodeBlock;
<ide> import org.springframework.javapoet.MethodSpec;
<add>import org.springframework.util.MultiValueMap;
<ide>
<ide> /**
<ide> * AOT contribution from a {@link BeanRegistrationsAotProcessor} used to
<del> * register bean definitions.
<add> * register bean definitions and aliases.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sebastien Deleuze
<ide> * @since 6.0
<ide> * @see BeanRegistrationsAotProcessor
<ide> */
<ide>
<ide> private final Map<String, BeanDefinitionMethodGenerator> registrations;
<ide>
<add> private final MultiValueMap<String, String> aliases;
<add>
<ide>
<ide> BeanRegistrationsAotContribution(
<del> Map<String, BeanDefinitionMethodGenerator> registrations) {
<add> Map<String, BeanDefinitionMethodGenerator> registrations, MultiValueMap<String, String> aliases) {
<ide>
<ide> this.registrations = registrations;
<add> this.aliases = aliases;
<ide> }
<ide>
<ide>
<ide> public void applyTo(GenerationContext generationContext,
<ide> type.addModifiers(Modifier.PUBLIC);
<ide> });
<ide> BeanRegistrationsCodeGenerator codeGenerator = new BeanRegistrationsCodeGenerator(generatedClass);
<del> GeneratedMethod generatedMethod = codeGenerator.getMethods().add("registerBeanDefinitions", method ->
<del> generateRegisterMethod(method, generationContext, codeGenerator));
<del> beanFactoryInitializationCode.addInitializer(generatedMethod.toMethodReference());
<add> GeneratedMethod generatedBeanDefinitionsMethod = codeGenerator.getMethods().add("registerBeanDefinitions", method ->
<add> generateRegisterBeanDefinitionsMethod(method, generationContext, codeGenerator));
<add> beanFactoryInitializationCode.addInitializer(generatedBeanDefinitionsMethod.toMethodReference());
<add> GeneratedMethod generatedAliasesMethod = codeGenerator.getMethods().add("registerAliases",
<add> this::generateRegisterAliasesMethod);
<add> beanFactoryInitializationCode.addInitializer(generatedAliasesMethod.toMethodReference());
<ide> }
<ide>
<del> private void generateRegisterMethod(MethodSpec.Builder method,
<add> private void generateRegisterBeanDefinitionsMethod(MethodSpec.Builder method,
<ide> GenerationContext generationContext,
<ide> BeanRegistrationsCode beanRegistrationsCode) {
<ide>
<ide> private void generateRegisterMethod(MethodSpec.Builder method,
<ide> method.addCode(code.build());
<ide> }
<ide>
<add> private void generateRegisterAliasesMethod(MethodSpec.Builder method) {
<add> method.addJavadoc("Register the aliases.");
<add> method.addModifiers(Modifier.PUBLIC);
<add> method.addParameter(DefaultListableBeanFactory.class,
<add> BEAN_FACTORY_PARAMETER_NAME);
<add> CodeBlock.Builder code = CodeBlock.builder();
<add> this.aliases.forEach((beanName, beanAliases) ->
<add> beanAliases.forEach(alias -> code.addStatement("$L.registerAlias($S, $S)", BEAN_FACTORY_PARAMETER_NAME,
<add> beanName, alias)));
<add> method.addCode(code.build());
<add> }
<add>
<ide>
<ide> /**
<ide> * {@link BeanRegistrationsCode} with generation support.
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/aot/BeanRegistrationsAotProcessor.java
<ide>
<ide> import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
<ide> import org.springframework.beans.factory.support.RegisteredBean;
<add>import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<ide>
<ide> /**
<ide> * {@link BeanFactoryInitializationAotProcessor} that contributes code to
<ide> * register beans.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sebastien Deleuze
<ide> * @since 6.0
<ide> */
<ide> class BeanRegistrationsAotProcessor implements BeanFactoryInitializationAotProcessor {
<ide> public BeanRegistrationsAotContribution processAheadOfTime(ConfigurableListableB
<ide> BeanDefinitionMethodGeneratorFactory beanDefinitionMethodGeneratorFactory =
<ide> new BeanDefinitionMethodGeneratorFactory(beanFactory);
<ide> Map<String, BeanDefinitionMethodGenerator> registrations = new LinkedHashMap<>();
<add> MultiValueMap<String, String> aliases = new LinkedMultiValueMap<>();
<ide> for (String beanName : beanFactory.getBeanDefinitionNames()) {
<ide> RegisteredBean registeredBean = RegisteredBean.of(beanFactory, beanName);
<ide> BeanDefinitionMethodGenerator beanDefinitionMethodGenerator = beanDefinitionMethodGeneratorFactory
<ide> .getBeanDefinitionMethodGenerator(registeredBean);
<ide> if (beanDefinitionMethodGenerator != null) {
<ide> registrations.put(beanName, beanDefinitionMethodGenerator);
<ide> }
<add> for (String alias : beanFactory.getAliases(beanName)) {
<add> aliases.add(beanName, alias);
<add> }
<ide> }
<ide> if (registrations.isEmpty()) {
<ide> return null;
<ide> }
<del> return new BeanRegistrationsAotContribution(registrations);
<add> return new BeanRegistrationsAotContribution(registrations, aliases);
<ide> }
<ide>
<ide> }
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanRegistrationsAotContributionTests.java
<ide> import org.springframework.core.test.tools.Compiled;
<ide> import org.springframework.core.test.tools.SourceFile;
<ide> import org.springframework.core.test.tools.TestCompiler;
<add>import org.springframework.javapoet.ClassName;
<ide> import org.springframework.javapoet.CodeBlock;
<ide> import org.springframework.javapoet.MethodSpec;
<ide> import org.springframework.javapoet.ParameterizedTypeName;
<add>import org.springframework.util.LinkedMultiValueMap;
<add>import org.springframework.util.MultiValueMap;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide>
<ide> /**
<ide> * Tests for {@link BeanRegistrationsAotContribution}.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sebastien Deleuze
<ide> */
<ide> class BeanRegistrationsAotContributionTests {
<ide>
<ide> void applyToAppliesContribution() {
<ide> Collections.emptyList());
<ide> registrations.put("testBean", generator);
<ide> BeanRegistrationsAotContribution contribution = new BeanRegistrationsAotContribution(
<del> registrations);
<add> registrations, new LinkedMultiValueMap<>());
<ide> contribution.applyTo(this.generationContext, this.beanFactoryInitializationCode);
<ide> compile((consumer, compiled) -> {
<ide> DefaultListableBeanFactory freshBeanFactory = new DefaultListableBeanFactory();
<ide> void applyToAppliesContribution() {
<ide> });
<ide> }
<ide>
<add> @Test
<add> void applyToAppliesContributionWithAliases() {
<add> Map<String, BeanDefinitionMethodGenerator> registrations = new LinkedHashMap<>();
<add> RegisteredBean registeredBean = registerBean(
<add> new RootBeanDefinition(TestBean.class));
<add> BeanDefinitionMethodGenerator generator = new BeanDefinitionMethodGenerator(
<add> this.methodGeneratorFactory, registeredBean, null,
<add> Collections.emptyList());
<add> registrations.put("testBean", generator);
<add> MultiValueMap<String, String> aliases = new LinkedMultiValueMap<>();
<add> aliases.add("testBean", "testAlias");
<add> BeanRegistrationsAotContribution contribution = new BeanRegistrationsAotContribution(
<add> registrations, aliases);
<add> contribution.applyTo(this.generationContext, this.beanFactoryInitializationCode);
<add> compile((consumer, compiled) -> {
<add> DefaultListableBeanFactory freshBeanFactory = new DefaultListableBeanFactory();
<add> consumer.accept(freshBeanFactory);
<add> assertThat(freshBeanFactory.getAliases("testBean")).containsExactly("testAlias");
<add> });
<add> }
<add>
<ide> @Test
<ide> void applyToWhenHasNameGeneratesPrefixedFeatureName() {
<ide> this.generationContext = new TestGenerationContext(
<ide> void applyToWhenHasNameGeneratesPrefixedFeatureName() {
<ide> Collections.emptyList());
<ide> registrations.put("testBean", generator);
<ide> BeanRegistrationsAotContribution contribution = new BeanRegistrationsAotContribution(
<del> registrations);
<add> registrations, new LinkedMultiValueMap<>());
<ide> contribution.applyTo(this.generationContext, this.beanFactoryInitializationCode);
<ide> compile((consumer, compiled) -> {
<ide> SourceFile sourceFile = compiled.getSourceFile(".*BeanDefinitions");
<ide> MethodReference generateBeanDefinitionMethod(
<ide> };
<ide> registrations.put("testBean", generator);
<ide> BeanRegistrationsAotContribution contribution = new BeanRegistrationsAotContribution(
<del> registrations);
<add> registrations, new LinkedMultiValueMap<>());
<ide> contribution.applyTo(this.generationContext, this.beanFactoryInitializationCode);
<ide> assertThat(beanRegistrationsCodes).hasSize(1);
<ide> BeanRegistrationsCode actual = beanRegistrationsCodes.get(0);
<ide> private RegisteredBean registerBean(RootBeanDefinition rootBeanDefinition) {
<ide> @SuppressWarnings({ "unchecked", "cast" })
<ide> private void compile(
<ide> BiConsumer<Consumer<DefaultListableBeanFactory>, Compiled> result) {
<del> MethodReference methodReference = this.beanFactoryInitializationCode
<add> MethodReference beanRegistrationsMethodReference = this.beanFactoryInitializationCode
<ide> .getInitializers().get(0);
<add> MethodReference aliasesMethodReference = this.beanFactoryInitializationCode
<add> .getInitializers().get(1);
<ide> this.beanFactoryInitializationCode.getTypeBuilder().set(type -> {
<del> CodeBlock methodInvocation = methodReference.toInvokeCodeBlock(
<del> ArgumentCodeGenerator.of(DefaultListableBeanFactory.class, "beanFactory"),
<del> this.beanFactoryInitializationCode.getClassName());
<add> ArgumentCodeGenerator beanFactory = ArgumentCodeGenerator.of(DefaultListableBeanFactory.class, "beanFactory");
<add> ClassName className = this.beanFactoryInitializationCode.getClassName();
<add> CodeBlock beanRegistrationsMethodInvocation = beanRegistrationsMethodReference.toInvokeCodeBlock(beanFactory, className);
<add> CodeBlock aliasesMethodInvocation = aliasesMethodReference.toInvokeCodeBlock(beanFactory, className);
<ide> type.addModifiers(Modifier.PUBLIC);
<ide> type.addSuperinterface(ParameterizedTypeName.get(Consumer.class, DefaultListableBeanFactory.class));
<ide> type.addMethod(MethodSpec.methodBuilder("accept").addModifiers(Modifier.PUBLIC)
<ide> .addParameter(DefaultListableBeanFactory.class, "beanFactory")
<del> .addStatement(methodInvocation)
<add> .addStatement(beanRegistrationsMethodInvocation)
<add> .addStatement(aliasesMethodInvocation)
<ide> .build());
<ide> });
<ide> this.generationContext.writeGeneratedContent();
<ide><path>spring-beans/src/test/java/org/springframework/beans/factory/aot/BeanRegistrationsAotProcessorTests.java
<ide> * Tests for {@link BeanRegistrationsAotProcessor}.
<ide> *
<ide> * @author Phillip Webb
<add> * @author Sebastien Deleuze
<ide> */
<ide> class BeanRegistrationsAotProcessorTests {
<ide>
<ide> void processAheadOfTimeReturnsBeanRegistrationsAotContributionWithRegistrations(
<ide> .asInstanceOf(InstanceOfAssertFactories.MAP).containsKeys("b1", "b2");
<ide> }
<ide>
<add> @Test
<add> void processAheadOfTimeReturnsBeanRegistrationsAotContributionWithAliases() {
<add> BeanRegistrationsAotProcessor processor = new BeanRegistrationsAotProcessor();
<add> DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
<add> beanFactory.registerBeanDefinition("test", new RootBeanDefinition(TestBean.class));
<add> beanFactory.registerAlias("test", "testAlias");
<add> BeanRegistrationsAotContribution contribution = processor
<add> .processAheadOfTime(beanFactory);
<add> assertThat(contribution).extracting("aliases")
<add> .asInstanceOf(InstanceOfAssertFactories.MAP).hasEntrySatisfying("test", value ->
<add> assertThat(value).asList().singleElement().isEqualTo("testAlias"));
<add> }
<add>
<ide> }
| 4
|
Ruby
|
Ruby
|
do cleanup even without a cellar
|
04b350dce5d0ac7e87ab4b5882dd1a5f19f39a9d
|
<ide><path>Library/Homebrew/cmd/cleanup.rb
<ide>
<ide> module Homebrew
<ide> def cleanup
<del> # individual cleanup_ methods should also check for the existence of the
<del> # appropriate directories before assuming they exist
<del> return unless HOMEBREW_CELLAR.directory?
<del>
<ide> if ARGV.named.empty?
<ide> cleanup_cellar
<ide> cleanup_cache
<ide> def cleanup_logs
<ide> end
<ide>
<ide> def cleanup_cellar
<add> return unless HOMEBREW_CELLAR.directory?
<ide> HOMEBREW_CELLAR.subdirs.each do |rack|
<ide> begin
<ide> cleanup_formula Formulary.from_rack(rack)
<ide> def cleanup_cache
<ide> next unless version
<ide> next unless (name = file.basename.to_s[/(.*)-(?:#{Regexp.escape(version)})/, 1])
<ide>
<add> next unless HOMEBREW_CELLAR.directory?
<add>
<ide> begin
<ide> f = Formulary.from_rack(HOMEBREW_CELLAR/name)
<ide> rescue FormulaUnavailableError, TapFormulaAmbiguityError
| 1
|
Javascript
|
Javascript
|
apply bidi algorithm to the text in the worker
|
bd4434a7ea7be878360997849a2079e0ca39bec7
|
<ide><path>src/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide>
<ide> getTextContent: function partialEvaluatorGetIRQueue(stream, resources, state) {
<ide> if (!state) {
<del> state = [];
<add> var text = [];
<add> var dirs = [];
<add> state = {
<add> text: text,
<add> dirs: dirs
<add> };
<ide> }
<ide>
<ide> var self = this;
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> if ('Form' !== type.name)
<ide> break;
<ide>
<del> // Add some spacing between the text here and the text of the
<del> // xForm.
<del>
<ide> state = this.getTextContent(
<ide> xobj,
<ide> xobj.dict.get('Resources') || resources,
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> break;
<ide> } // switch
<ide> if (chunk !== '') {
<del> state.push(chunk);
<add> var bidiText = PDFJS.bidi(chunk, -1);
<add> text.push(bidiText.str);
<add> dirs.push(bidiText.ltr);
<add>
<ide> chunk = '';
<ide> }
<ide>
<ide><path>web/viewer.js
<ide> var TextLayerBuilder = function textLayerBuilder(textLayerDiv) {
<ide>
<ide> var textDivs = this.textDivs;
<ide> var textContent = this.textContent;
<add> var text = textContent.text;
<add> var dirs = textContent.dirs;
<ide>
<del> for (var i = 0; i < textContent.length; i++) {
<add> for (var i = 0; i < text.length; i++) {
<ide> var textDiv = textDivs[i];
<del> var bidiText = PDFJS.bidi(textContent[i], -1);
<ide>
<del> textDiv.textContent = bidiText.str;
<del> textDiv.dir = bidiText.ltr ? 'ltr' : 'rtl';
<add> textDiv.textContent = text[i];
<add> textDiv.dir = dirs[i] ? 'ltr' : 'rtl';
<ide> }
<ide>
<ide> this.setupRenderLayoutTimer();
| 2
|
Mixed
|
Python
|
fix typo about receptive field size
|
c1cc94a33aca9304a5351b3da7c9ebd923eea396
|
<ide><path>spacy/ml/models/tok2vec.py
<ide> def build_hash_embed_cnn_tok2vec(
<ide> window_size (int): The number of tokens on either side to concatenate during
<ide> the convolutions. The receptive field of the CNN will be
<ide> depth * (window_size * 2 + 1), so a 4-layer network with window_size of
<del> 2 will be sensitive to 17 words at a time. Recommended value is 1.
<add> 2 will be sensitive to 20 words at a time. Recommended value is 1.
<ide> embed_size (int): The number of rows in the hash embedding tables. This can
<ide> be surprisingly small, due to the use of the hash embeddings. Recommended
<ide> values are between 2000 and 10000.
<ide><path>website/docs/api/architectures.md
<ide> consisting of a CNN and a layer-normalized maxout activation function.
<ide> | `width` | The width of the input and output. These are required to be the same, so that residual connections can be used. Recommended values are `96`, `128` or `300`. ~~int~~ |
<ide> | `depth` | The number of convolutional layers to use. Recommended values are between `2` and `8`. ~~int~~ |
<ide> | `embed_size` | The number of rows in the hash embedding tables. This can be surprisingly small, due to the use of the hash embeddings. Recommended values are between `2000` and `10000`. ~~int~~ |
<del>| `window_size` | The number of tokens on either side to concatenate during the convolutions. The receptive field of the CNN will be `depth * (window_size * 2 + 1)`, so a 4-layer network with a window size of `2` will be sensitive to 17 words at a time. Recommended value is `1`. ~~int~~ |
<add>| `window_size` | The number of tokens on either side to concatenate during the convolutions. The receptive field of the CNN will be `depth * (window_size * 2 + 1)`, so a 4-layer network with a window size of `2` will be sensitive to 20 words at a time. Recommended value is `1`. ~~int~~ |
<ide> | `maxout_pieces` | The number of pieces to use in the maxout non-linearity. If `1`, the [`Mish`](https://thinc.ai/docs/api-layers#mish) non-linearity is used instead. Recommended values are `1`-`3`. ~~int~~ |
<ide> | `subword_features` | Whether to also embed subword features, specifically the prefix, suffix and word shape. This is recommended for alphabetic languages like English, but not if single-character tokens are used for a language such as Chinese. ~~bool~~ |
<ide> | `pretrained_vectors` | Whether to also use static vectors. ~~bool~~ |
| 2
|
PHP
|
PHP
|
fix no error on console preboot
|
14716e50812860f27fb0d3d93d13f79fe70b8d63
|
<ide><path>src/Illuminate/Exception/Handler.php
<ide> public function handleException($exception)
<ide> $response = $this->displayException($exception);
<ide> }
<ide>
<del> return $this->responsePreparer->readyForResponses()
<add> return $this->sendResponse($response);
<add> }
<add>
<add> /**
<add> * Send the repsonse back to the client.
<add> *
<add> * @param \Symfony\Component\HttpFoundation\Response $response
<add> * @return mixed
<add> */
<add> protected function sendResponse($response)
<add> {
<add> return $this->responsePreparer->readyForResponses() && ! $this->runningInConsole()
<ide> ? $response
<ide> : $response->send();
<ide> }
<ide> protected function prepareResponse($response)
<ide> return $this->responsePreparer->prepareResponse($response);
<ide> }
<ide>
<add> /**
<add> * Determine if we are running in the console.
<add> *
<add> * @return bool
<add> */
<add> public function runningInConsole()
<add> {
<add> return php_sapi_name() == 'cli';
<add> }
<add>
<ide> /**
<ide> * Set the debug level for the handler.
<ide> *
| 1
|
Ruby
|
Ruby
|
improve `_fetch` compatibility layer
|
ab04cfed831cf82232f4c1d815ada5f112133a71
|
<ide><path>Library/Homebrew/compat/early/download_strategy.rb
<ide> # frozen_string_literal: true
<ide>
<ide> class AbstractDownloadStrategy
<del> module Compat
<add> module CompatFetch
<ide> def fetch(timeout: nil)
<ide> super()
<ide> end
<ide> end
<ide>
<add> module Compat_Fetch # rubocop:disable Naming/ClassAndModuleCamelCase
<add> def _fetch(*args, **options)
<add> options[:timeout] = nil unless options.key?(:timeout)
<add>
<add> begin
<add> super
<add> rescue ArgumentError => e
<add> raise unless e.message.include?("timeout")
<add>
<add> odeprecated "`def _fetch` in a subclass of `CurlDownloadStrategy`"
<add> options.delete(:timeout)
<add> super(*args, **options)
<add> end
<add> end
<add> end
<add>
<ide> class << self
<ide> def method_added(method)
<ide> if method == :fetch && instance_method(method).arity.zero?
<del> odeprecated "`def fetch` in a subclass of #{self}",
<add> odeprecated "`def fetch` in a subclass of `#{self}`",
<ide> "`def fetch(timeout: nil, **options)` and output a warning " \
<ide> "when `options` contains new unhandled options"
<ide>
<ide> class_eval do
<del> prepend Compat
<add> prepend CompatFetch
<add> end
<add> elsif method == :_fetch
<add> class_eval do
<add> prepend Compat_Fetch
<ide> end
<ide> end
<ide>
<ide><path>Library/Homebrew/compat/late.rb
<ide> # typed: strict
<ide> # frozen_string_literal: true
<del>
<del>require_relative "late/download_strategy"
<ide><path>Library/Homebrew/compat/late/download_strategy.rb
<del># typed: false
<del># frozen_string_literal: true
<del>
<del>class CurlDownloadStrategy
<del> module Compat
<del> def _fetch(*args, **options)
<del> unless options.key?(:timeout)
<del> odeprecated "#{self.class}#_fetch"
<del> options[:timeout] = nil
<del> end
<del> super(*args, **options)
<del> end
<del> end
<del>
<del> prepend Compat
<del>end
<del>
<del>class CurlPostDownloadStrategy
<del> prepend Compat
<del>end
| 3
|
Javascript
|
Javascript
|
change bidi.js file format to unix
|
31839d8c7816ca1106daae9ff55c39ee65b651ee
|
<ide><path>src/bidi.js
<del>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
<del>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<del>
<del>'use strict';
<del>
<del>var bidi = PDFJS.bidi = (function bidiClosure() {
<del> // Character types for symbols from 0000 to 00FF.
<del> var baseTypes = [
<del> 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
<del> 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
<del> 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
<del> 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
<del> 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
<del> 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
<del> 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
<del> 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
<del> 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
<del> 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
<del> 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
<del> 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<del> 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
<del> ];
<del>
<del> // Character types for symbols from 0600 to 06FF
<del> var arabicTypes = [
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
<del> 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
<del> 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
<del> 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
<del> 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<del> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
<del> ];
<del>
<del> function isOdd(i) {
<del> return (i & 1) != 0;
<del> }
<del>
<del> function isEven(i) {
<del> return (i & 1) == 0;
<del> }
<del>
<del> function findUnequal(arr, start, value) {
<del> var j;
<del> for (var j = start, jj = arr.length; j < jj; ++j) {
<del> if (arr[j] != value)
<del> return j;
<del> }
<del> return j;
<del> }
<del>
<del> function setValues(arr, start, end, value) {
<del> for (var j = start; j < end; ++j) {
<del> arr[j] = value;
<del> }
<del> }
<del>
<del> function reverseValues(arr, start, end) {
<del> for (var i = start, j = end - 1; i < j; ++i, --j) {
<del> var temp = arr[i];
<del> arr[i] = arr[j];
<del> arr[j] = temp;
<del> }
<del> }
<del>
<del> function mirrorGlyphs(c) {
<del> /*
<del> # BidiMirroring-1.txt
<del> 0028; 0029 # LEFT PARENTHESIS
<del> 0029; 0028 # RIGHT PARENTHESIS
<del> 003C; 003E # LESS-THAN SIGN
<del> 003E; 003C # GREATER-THAN SIGN
<del> 005B; 005D # LEFT SQUARE BRACKET
<del> 005D; 005B # RIGHT SQUARE BRACKET
<del> 007B; 007D # LEFT CURLY BRACKET
<del> 007D; 007B # RIGHT CURLY BRACKET
<del> 00AB; 00BB # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
<del> 00BB; 00AB # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
<del> */
<del> switch (c) {
<del> case '(':
<del> return ')';
<del> case ')':
<del> return '(';
<del> case '<':
<del> return '>';
<del> case '>':
<del> return '<';
<del> case ']':
<del> return '[';
<del> case '[':
<del> return ']';
<del> case '}':
<del> return '{';
<del> case '{':
<del> return '}';
<del> case '\u00AB':
<del> return '\u00BB';
<del> case '\u00BB':
<del> return '\u00AB';
<del> default:
<del> return c;
<del> }
<del> }
<del>
<del> return (function bidi(text, startLevel) {
<del> var str = text.str;
<del> var strLength = str.length;
<del> if (strLength == 0)
<del> return str;
<del>
<del> // get types, fill arrays
<del>
<del> var chars = new Array(strLength);
<del> var types = new Array(strLength);
<del> var oldtypes = new Array(strLength);
<del> var numBidi = 0;
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> chars[i] = str.charAt(i);
<del>
<del> var charCode = str.charCodeAt(i);
<del> var charType = 'L';
<del> if (charCode <= 0x00ff)
<del> charType = baseTypes[charCode];
<del> else if (0x0590 <= charCode && charCode <= 0x05f4)
<del> charType = 'R';
<del> else if (0x0600 <= charCode && charCode <= 0x06ff)
<del> charType = arabicTypes[charCode & 0xff];
<del> else if (0x0700 <= charCode && charCode <= 0x08AC)
<del> charType = 'AL';
<del>
<del> if (charType == 'R' || charType == 'AL' || charType == 'AN')
<del> numBidi++;
<del>
<del> oldtypes[i] = types[i] = charType;
<del> }
<del>
<del> // detect the bidi method
<del> // if there are no rtl characters then no bidi needed
<del> // if less than 30% chars are rtl then string is primarily ltr
<del> // if more than 30% chars are rtl then string is primarily rtl
<del> if (numBidi == 0) {
<del> text.direction = 'ltr';
<del> return str;
<del> }
<del>
<del> if (startLevel == -1) {
<del> if ((strLength / numBidi) < 0.3) {
<del> text.direction = 'ltr';
<del> startLevel = 0;
<del> } else {
<del> text.direction = 'rtl';
<del> startLevel = 1;
<del> }
<del> }
<del>
<del> var levels = new Array(strLength);
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> levels[i] = startLevel;
<del> }
<del>
<del> var diffChars = new Array(strLength);
<del> var diffLevels = new Array(strLength);
<del> var diffTypes = new Array(strLength);
<del>
<del> /*
<del> X1-X10: skip most of this, since we are NOT doing the embeddings.
<del> */
<del>
<del> var e = isOdd(startLevel) ? 'R' : 'L';
<del> var sor = e;
<del> var eor = sor;
<del>
<del> /*
<del> W1. Examine each non-spacing mark (NSM) in the level run, and change the
<del> type of the NSM to the type of the previous character. If the NSM is at the
<del> start of the level run, it will get the type of sor.
<del> */
<del>
<del> var lastType = sor;
<del> for (var i = 0; i < strLength; ++i) {
<del> if (types[i] == 'NSM')
<del> types[i] = lastType;
<del> else
<del> lastType = types[i];
<del> }
<del>
<del> /*
<del> W2. Search backwards from each instance of a European number until the
<del> first strong type (R, L, AL, or sor) is found. If an AL is found, change
<del> the type of the European number to Arabic number.
<del> */
<del>
<del> var lastType = sor;
<del> for (var i = 0; i < strLength; ++i) {
<del> var t = types[i];
<del> if (t == 'EN')
<del> types[i] = (lastType == 'AL') ? 'AN' : 'EN';
<del> else if (t == 'R' || t == 'L' || t == 'AL')
<del> lastType = t;
<del> }
<del>
<del> /*
<del> W3. Change all ALs to R.
<del> */
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> var t = types[i];
<del> if (t == 'AL')
<del> types[i] = 'R';
<del> }
<del>
<del> /*
<del> W4. A single European separator between two European numbers changes to a
<del> European number. A single common separator between two numbers of the same
<del> type changes to that type:
<del> */
<del>
<del> for (var i = 1; i < strLength - 1; ++i) {
<del> if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN')
<del> types[i] = 'EN';
<del> if (types[i] == 'CS' && (types[i - 1] == 'EN' || types[i - 1] == 'AN') &&
<del> types[i + 1] == types[i - 1])
<del> types[i] = types[i - 1];
<del> }
<del>
<del> /*
<del> W5. A sequence of European terminators adjacent to European numbers changes
<del> to all European numbers:
<del> */
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> if (types[i] == 'EN') {
<del> // do before
<del> for (var j = i - 1; j >= 0; --j) {
<del> if (types[j] != 'ET')
<del> break;
<del> types[j] = 'EN';
<del> }
<del> // do after
<del> for (var j = i + 1; j < strLength; --j) {
<del> if (types[j] != 'ET')
<del> break;
<del> types[j] = 'EN';
<del> }
<del> }
<del> }
<del>
<del> /*
<del> W6. Otherwise, separators and terminators change to Other Neutral:
<del> */
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> var t = types[i];
<del> if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS')
<del> types[i] = 'ON';
<del> }
<del>
<del> /*
<del> W7. Search backwards from each instance of a European number until the
<del> first strong type (R, L, or sor) is found. If an L is found, then change
<del> the type of the European number to L.
<del> */
<del>
<del> var lastType = sor;
<del> for (var i = 0; i < strLength; ++i) {
<del> var t = types[i];
<del> if (t == 'EN')
<del> types[i] = (lastType == 'L') ? 'L' : 'EN';
<del> else if (t == 'R' || t == 'L')
<del> lastType = t;
<del> }
<del>
<del> /*
<del> N1. A sequence of neutrals takes the direction of the surrounding strong
<del> text if the text on both sides has the same direction. European and Arabic
<del> numbers are treated as though they were R. Start-of-level-run (sor) and
<del> end-of-level-run (eor) are used at level run boundaries.
<del> */
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> if (types[i] == 'ON') {
<del> var end = findUnequal(types, i + 1, 'ON');
<del> var before = sor;
<del> if (i > 0)
<del> before = types[i - 1];
<del> var after = eor;
<del> if (end + 1 < strLength)
<del> after = types[end + 1];
<del> if (before != 'L')
<del> before = 'R';
<del> if (after != 'L')
<del> after = 'R';
<del> if (before == after)
<del> setValues(types, i, end, before);
<del> i = end - 1; // reset to end (-1 so next iteration is ok)
<del> }
<del> }
<del>
<del> /*
<del> N2. Any remaining neutrals take the embedding direction.
<del> */
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> if (types[i] == 'ON')
<del> types[i] = e;
<del> }
<del>
<del> /*
<del> I1. For all characters with an even (left-to-right) embedding direction,
<del> those of type R go up one level and those of type AN or EN go up two
<del> levels.
<del> I2. For all characters with an odd (right-to-left) embedding direction,
<del> those of type L, EN or AN go up one level.
<del> */
<del>
<del> for (var i = 0; i < strLength; ++i) {
<del> var t = types[i];
<del> if (isEven(levels[i])) {
<del> if (t == 'R') {
<del> levels[i] += 1;
<del> } else if (t == 'AN' || t == 'EN') {
<del> levels[i] += 2;
<del> }
<del> } else { // isOdd, so
<del> if (t == 'L' || t == 'AN' || t == 'EN') {
<del> levels[i] += 1;
<del> }
<del> }
<del> }
<del>
<del> /*
<del> L1. On each line, reset the embedding level of the following characters to
<del> the paragraph embedding level:
<del>
<del> segment separators,
<del> paragraph separators,
<del> any sequence of whitespace characters preceding a segment separator or
<del> paragraph separator, and any sequence of white space characters at the end
<del> of the line.
<del> */
<del>
<del> // don't bother as text is only single line
<del>
<del> /*
<del> L2. From the highest level found in the text to the lowest odd level on
<del> each line, reverse any contiguous sequence of characters that are at that
<del> level or higher.
<del> */
<del>
<del> // find highest level & lowest odd level
<del>
<del> var highestLevel = -1;
<del> var lowestOddLevel = 99;
<del> for (var i = 0, ii = levels.length; i < ii; ++i) {
<del> var level = levels[i];
<del> if (highestLevel < level)
<del> highestLevel = level;
<del> if (lowestOddLevel > level && isOdd(level))
<del> lowestOddLevel = level;
<del> }
<del>
<del> // now reverse between those limits
<del>
<del> for (var level = highestLevel; level >= lowestOddLevel; --level) {
<del> // find segments to reverse
<del> var start = -1;
<del> for (var i = 0, ii = levels.length; i < ii; ++i) {
<del> if (levels[i] < level) {
<del> if (start >= 0) {
<del> reverseValues(chars, start, i);
<del> start = -1;
<del> }
<del> } else if (start < 0) {
<del> start = i;
<del> }
<del> }
<del> if (start >= 0) {
<del> reverseValues(chars, start, levels.length);
<del> }
<del> }
<del>
<del> /*
<del> L3. Combining marks applied to a right-to-left base character will at this
<del> point precede their base character. If the rendering engine expects them to
<del> follow the base characters in the final display process, then the ordering
<del> of the marks and the base character must be reversed.
<del> */
<del>
<del> // don't bother for now
<del>
<del> /*
<del> L4. A character that possesses the mirrored property as specified by
<del> Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
<del> directionality of that character is R.
<del> */
<del>
<del> // don't mirror as characters are already mirrored in the pdf
<del>
<del> // Finally, return string
<del>
<del> var result = '';
<del> for (var i = 0, ii = chars.length; i < ii; ++i) {
<del> var ch = chars[i];
<del> if (ch != '<' && ch != '>')
<del> result += ch;
<del> }
<del> return result;
<del> });
<del>})();
<add>/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
<add>/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
<add>
<add>'use strict';
<add>
<add>var bidi = PDFJS.bidi = (function bidiClosure() {
<add> // Character types for symbols from 0000 to 00FF.
<add> var baseTypes = [
<add> 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'S', 'B', 'S', 'WS',
<add> 'B', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
<add> 'BN', 'BN', 'B', 'B', 'B', 'S', 'WS', 'ON', 'ON', 'ET', 'ET', 'ET', 'ON',
<add> 'ON', 'ON', 'ON', 'ON', 'ON', 'CS', 'ON', 'CS', 'ON', 'EN', 'EN', 'EN',
<add> 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'EN', 'ON', 'ON', 'ON', 'ON', 'ON',
<add> 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'ON', 'ON',
<add> 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'ON', 'ON', 'ON', 'ON', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'B', 'BN',
<add> 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
<add> 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN', 'BN',
<add> 'BN', 'CS', 'ON', 'ET', 'ET', 'ET', 'ET', 'ON', 'ON', 'ON', 'ON', 'L', 'ON',
<add> 'ON', 'ON', 'ON', 'ON', 'ET', 'ET', 'EN', 'EN', 'ON', 'L', 'ON', 'ON', 'ON',
<add> 'EN', 'L', 'ON', 'ON', 'ON', 'ON', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L',
<add> 'L', 'L', 'L', 'ON', 'L', 'L', 'L', 'L', 'L', 'L', 'L', 'L'
<add> ];
<add>
<add> // Character types for symbols from 0600 to 06FF
<add> var arabicTypes = [
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'CS', 'AL', 'ON', 'ON', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
<add> 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN', 'AN',
<add> 'AN', 'ET', 'AN', 'AN', 'AL', 'AL', 'AL', 'NSM', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM',
<add> 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'NSM', 'ON', 'NSM',
<add> 'NSM', 'NSM', 'NSM', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL',
<add> 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL', 'AL'
<add> ];
<add>
<add> function isOdd(i) {
<add> return (i & 1) != 0;
<add> }
<add>
<add> function isEven(i) {
<add> return (i & 1) == 0;
<add> }
<add>
<add> function findUnequal(arr, start, value) {
<add> var j;
<add> for (var j = start, jj = arr.length; j < jj; ++j) {
<add> if (arr[j] != value)
<add> return j;
<add> }
<add> return j;
<add> }
<add>
<add> function setValues(arr, start, end, value) {
<add> for (var j = start; j < end; ++j) {
<add> arr[j] = value;
<add> }
<add> }
<add>
<add> function reverseValues(arr, start, end) {
<add> for (var i = start, j = end - 1; i < j; ++i, --j) {
<add> var temp = arr[i];
<add> arr[i] = arr[j];
<add> arr[j] = temp;
<add> }
<add> }
<add>
<add> function mirrorGlyphs(c) {
<add> /*
<add> # BidiMirroring-1.txt
<add> 0028; 0029 # LEFT PARENTHESIS
<add> 0029; 0028 # RIGHT PARENTHESIS
<add> 003C; 003E # LESS-THAN SIGN
<add> 003E; 003C # GREATER-THAN SIGN
<add> 005B; 005D # LEFT SQUARE BRACKET
<add> 005D; 005B # RIGHT SQUARE BRACKET
<add> 007B; 007D # LEFT CURLY BRACKET
<add> 007D; 007B # RIGHT CURLY BRACKET
<add> 00AB; 00BB # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
<add> 00BB; 00AB # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
<add> */
<add> switch (c) {
<add> case '(':
<add> return ')';
<add> case ')':
<add> return '(';
<add> case '<':
<add> return '>';
<add> case '>':
<add> return '<';
<add> case ']':
<add> return '[';
<add> case '[':
<add> return ']';
<add> case '}':
<add> return '{';
<add> case '{':
<add> return '}';
<add> case '\u00AB':
<add> return '\u00BB';
<add> case '\u00BB':
<add> return '\u00AB';
<add> default:
<add> return c;
<add> }
<add> }
<add>
<add> return (function bidi(text, startLevel) {
<add> var str = text.str;
<add> var strLength = str.length;
<add> if (strLength == 0)
<add> return str;
<add>
<add> // get types, fill arrays
<add>
<add> var chars = new Array(strLength);
<add> var types = new Array(strLength);
<add> var oldtypes = new Array(strLength);
<add> var numBidi = 0;
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> chars[i] = str.charAt(i);
<add>
<add> var charCode = str.charCodeAt(i);
<add> var charType = 'L';
<add> if (charCode <= 0x00ff)
<add> charType = baseTypes[charCode];
<add> else if (0x0590 <= charCode && charCode <= 0x05f4)
<add> charType = 'R';
<add> else if (0x0600 <= charCode && charCode <= 0x06ff)
<add> charType = arabicTypes[charCode & 0xff];
<add> else if (0x0700 <= charCode && charCode <= 0x08AC)
<add> charType = 'AL';
<add>
<add> if (charType == 'R' || charType == 'AL' || charType == 'AN')
<add> numBidi++;
<add>
<add> oldtypes[i] = types[i] = charType;
<add> }
<add>
<add> // detect the bidi method
<add> // if there are no rtl characters then no bidi needed
<add> // if less than 30% chars are rtl then string is primarily ltr
<add> // if more than 30% chars are rtl then string is primarily rtl
<add> if (numBidi == 0) {
<add> text.direction = 'ltr';
<add> return str;
<add> }
<add>
<add> if (startLevel == -1) {
<add> if ((strLength / numBidi) < 0.3) {
<add> text.direction = 'ltr';
<add> startLevel = 0;
<add> } else {
<add> text.direction = 'rtl';
<add> startLevel = 1;
<add> }
<add> }
<add>
<add> var levels = new Array(strLength);
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> levels[i] = startLevel;
<add> }
<add>
<add> var diffChars = new Array(strLength);
<add> var diffLevels = new Array(strLength);
<add> var diffTypes = new Array(strLength);
<add>
<add> /*
<add> X1-X10: skip most of this, since we are NOT doing the embeddings.
<add> */
<add>
<add> var e = isOdd(startLevel) ? 'R' : 'L';
<add> var sor = e;
<add> var eor = sor;
<add>
<add> /*
<add> W1. Examine each non-spacing mark (NSM) in the level run, and change the
<add> type of the NSM to the type of the previous character. If the NSM is at the
<add> start of the level run, it will get the type of sor.
<add> */
<add>
<add> var lastType = sor;
<add> for (var i = 0; i < strLength; ++i) {
<add> if (types[i] == 'NSM')
<add> types[i] = lastType;
<add> else
<add> lastType = types[i];
<add> }
<add>
<add> /*
<add> W2. Search backwards from each instance of a European number until the
<add> first strong type (R, L, AL, or sor) is found. If an AL is found, change
<add> the type of the European number to Arabic number.
<add> */
<add>
<add> var lastType = sor;
<add> for (var i = 0; i < strLength; ++i) {
<add> var t = types[i];
<add> if (t == 'EN')
<add> types[i] = (lastType == 'AL') ? 'AN' : 'EN';
<add> else if (t == 'R' || t == 'L' || t == 'AL')
<add> lastType = t;
<add> }
<add>
<add> /*
<add> W3. Change all ALs to R.
<add> */
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> var t = types[i];
<add> if (t == 'AL')
<add> types[i] = 'R';
<add> }
<add>
<add> /*
<add> W4. A single European separator between two European numbers changes to a
<add> European number. A single common separator between two numbers of the same
<add> type changes to that type:
<add> */
<add>
<add> for (var i = 1; i < strLength - 1; ++i) {
<add> if (types[i] == 'ES' && types[i - 1] == 'EN' && types[i + 1] == 'EN')
<add> types[i] = 'EN';
<add> if (types[i] == 'CS' && (types[i - 1] == 'EN' || types[i - 1] == 'AN') &&
<add> types[i + 1] == types[i - 1])
<add> types[i] = types[i - 1];
<add> }
<add>
<add> /*
<add> W5. A sequence of European terminators adjacent to European numbers changes
<add> to all European numbers:
<add> */
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> if (types[i] == 'EN') {
<add> // do before
<add> for (var j = i - 1; j >= 0; --j) {
<add> if (types[j] != 'ET')
<add> break;
<add> types[j] = 'EN';
<add> }
<add> // do after
<add> for (var j = i + 1; j < strLength; --j) {
<add> if (types[j] != 'ET')
<add> break;
<add> types[j] = 'EN';
<add> }
<add> }
<add> }
<add>
<add> /*
<add> W6. Otherwise, separators and terminators change to Other Neutral:
<add> */
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> var t = types[i];
<add> if (t == 'WS' || t == 'ES' || t == 'ET' || t == 'CS')
<add> types[i] = 'ON';
<add> }
<add>
<add> /*
<add> W7. Search backwards from each instance of a European number until the
<add> first strong type (R, L, or sor) is found. If an L is found, then change
<add> the type of the European number to L.
<add> */
<add>
<add> var lastType = sor;
<add> for (var i = 0; i < strLength; ++i) {
<add> var t = types[i];
<add> if (t == 'EN')
<add> types[i] = (lastType == 'L') ? 'L' : 'EN';
<add> else if (t == 'R' || t == 'L')
<add> lastType = t;
<add> }
<add>
<add> /*
<add> N1. A sequence of neutrals takes the direction of the surrounding strong
<add> text if the text on both sides has the same direction. European and Arabic
<add> numbers are treated as though they were R. Start-of-level-run (sor) and
<add> end-of-level-run (eor) are used at level run boundaries.
<add> */
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> if (types[i] == 'ON') {
<add> var end = findUnequal(types, i + 1, 'ON');
<add> var before = sor;
<add> if (i > 0)
<add> before = types[i - 1];
<add> var after = eor;
<add> if (end + 1 < strLength)
<add> after = types[end + 1];
<add> if (before != 'L')
<add> before = 'R';
<add> if (after != 'L')
<add> after = 'R';
<add> if (before == after)
<add> setValues(types, i, end, before);
<add> i = end - 1; // reset to end (-1 so next iteration is ok)
<add> }
<add> }
<add>
<add> /*
<add> N2. Any remaining neutrals take the embedding direction.
<add> */
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> if (types[i] == 'ON')
<add> types[i] = e;
<add> }
<add>
<add> /*
<add> I1. For all characters with an even (left-to-right) embedding direction,
<add> those of type R go up one level and those of type AN or EN go up two
<add> levels.
<add> I2. For all characters with an odd (right-to-left) embedding direction,
<add> those of type L, EN or AN go up one level.
<add> */
<add>
<add> for (var i = 0; i < strLength; ++i) {
<add> var t = types[i];
<add> if (isEven(levels[i])) {
<add> if (t == 'R') {
<add> levels[i] += 1;
<add> } else if (t == 'AN' || t == 'EN') {
<add> levels[i] += 2;
<add> }
<add> } else { // isOdd, so
<add> if (t == 'L' || t == 'AN' || t == 'EN') {
<add> levels[i] += 1;
<add> }
<add> }
<add> }
<add>
<add> /*
<add> L1. On each line, reset the embedding level of the following characters to
<add> the paragraph embedding level:
<add>
<add> segment separators,
<add> paragraph separators,
<add> any sequence of whitespace characters preceding a segment separator or
<add> paragraph separator, and any sequence of white space characters at the end
<add> of the line.
<add> */
<add>
<add> // don't bother as text is only single line
<add>
<add> /*
<add> L2. From the highest level found in the text to the lowest odd level on
<add> each line, reverse any contiguous sequence of characters that are at that
<add> level or higher.
<add> */
<add>
<add> // find highest level & lowest odd level
<add>
<add> var highestLevel = -1;
<add> var lowestOddLevel = 99;
<add> for (var i = 0, ii = levels.length; i < ii; ++i) {
<add> var level = levels[i];
<add> if (highestLevel < level)
<add> highestLevel = level;
<add> if (lowestOddLevel > level && isOdd(level))
<add> lowestOddLevel = level;
<add> }
<add>
<add> // now reverse between those limits
<add>
<add> for (var level = highestLevel; level >= lowestOddLevel; --level) {
<add> // find segments to reverse
<add> var start = -1;
<add> for (var i = 0, ii = levels.length; i < ii; ++i) {
<add> if (levels[i] < level) {
<add> if (start >= 0) {
<add> reverseValues(chars, start, i);
<add> start = -1;
<add> }
<add> } else if (start < 0) {
<add> start = i;
<add> }
<add> }
<add> if (start >= 0) {
<add> reverseValues(chars, start, levels.length);
<add> }
<add> }
<add>
<add> /*
<add> L3. Combining marks applied to a right-to-left base character will at this
<add> point precede their base character. If the rendering engine expects them to
<add> follow the base characters in the final display process, then the ordering
<add> of the marks and the base character must be reversed.
<add> */
<add>
<add> // don't bother for now
<add>
<add> /*
<add> L4. A character that possesses the mirrored property as specified by
<add> Section 4.7, Mirrored, must be depicted by a mirrored glyph if the resolved
<add> directionality of that character is R.
<add> */
<add>
<add> // don't mirror as characters are already mirrored in the pdf
<add>
<add> // Finally, return string
<add>
<add> var result = '';
<add> for (var i = 0, ii = chars.length; i < ii; ++i) {
<add> var ch = chars[i];
<add> if (ch != '<' && ch != '>')
<add> result += ch;
<add> }
<add> return result;
<add> });
<add>})();
| 1
|
Javascript
|
Javascript
|
fix objexporter without normals
|
5989d08230a8d5a6c82cc9c70172d2c920e79b0d
|
<ide><path>examples/js/exporters/OBJExporter.js
<ide> THREE.OBJExporter.prototype = {
<ide>
<ide> j = indices.getX( i + m ) + 1;
<ide>
<del> face[ m ] = ( indexVertex + j ) + '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + '/' + ( indexNormals + j );
<add> face[ m ] = ( indexVertex + j ) + '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + ( normals ? '/' + ( indexNormals + j ) : '' );
<ide>
<ide> }
<ide>
<ide> THREE.OBJExporter.prototype = {
<ide>
<ide> j = i + m + 1;
<ide>
<del> face[ m ] = ( indexVertex + j ) + '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + '/' + ( indexNormals + j );
<add> face[ m ] = ( indexVertex + j ) + '/' + ( uvs ? ( indexVertexUvs + j ) : '' ) + '/' + ( normals ? '/' + ( indexNormals + j ) : '' );
<ide>
<ide> }
<ide>
| 1
|
PHP
|
PHP
|
add test for empty read() calls on cakesession
|
7501fcf46dc9106e47768c54dbf4e136585d61a2
|
<ide><path>cake/libs/cake_session.php
<ide> public static function started() {
<ide> * @param string $name Variable name to check for
<ide> * @return boolean True if variable is there
<ide> */
<del> public static function check($name) {
<add> public static function check($name = null) {
<ide> if (empty($name)) {
<ide> return false;
<ide> }
<ide><path>cake/tests/cases/libs/cake_session.test.php
<ide> function testSimpleRead() {
<ide> $this->assertEqual('value', $result);
<ide> }
<ide>
<add>/**
<add> * testReadyEmpty
<add> *
<add> * @author Predominant
<add> * @access public
<add> */
<add> function testReadyEmpty() {
<add> $this->assertFalse(TestCakeSession::read(''));
<add> }
<add>
<ide> /**
<ide> * test writing a hash of values/
<ide> *
| 2
|
Python
|
Python
|
add default line (in case there's no stdout)
|
4ba1b1aeecb0b25c96502eacbde7abba8614e2ac
|
<ide><path>airflow/operators/bash_operator.py
<ide> def execute(self, context):
<ide> self.sp = sp
<ide>
<ide> logging.info("Output:")
<add> line = ''
<ide> for line in iter(sp.stdout.readline, b''):
<ide> logging.info(line.strip())
<ide> sp.wait()
| 1
|
Javascript
|
Javascript
|
improve testing on ci
|
da1c51f1492c48ba8738896d4256bc2d77302777
|
<ide><path>test/core.tooltip.tests.js
<ide> describe('tooltip tests', function() {
<ide> }],
<ide> afterBody: [],
<ide> footer: [],
<del> x: 269,
<del> y: 155,
<ide> caretPadding: 2,
<ide> labelColors: [{
<ide> borderColor: 'rgb(255, 0, 0)',
<ide> describe('tooltip tests', function() {
<ide> backgroundColor: 'rgb(0, 255, 255)'
<ide> }]
<ide> }));
<add>
<add> expect(tooltip._view.x).toBeCloseTo(269, 1);
<add> expect(tooltip._view.y).toBeCloseTo(155, 1);
<ide> });
<ide>
<ide> it('Should display in single mode', function() {
<ide> describe('tooltip tests', function() {
<ide> }],
<ide> afterBody: [],
<ide> footer: [],
<del> x: 269,
<del> y: 312,
<ide> caretPadding: 2,
<ide> labelColors: []
<ide> }));
<add>
<add> expect(tooltip._view.x).toBeCloseTo(269, 1);
<add> expect(tooltip._view.y).toBeCloseTo(312, 1);
<ide> });
<ide>
<ide> it('Should display information from user callbacks', function() {
<ide> describe('tooltip tests', function() {
<ide> }],
<ide> afterBody: ['afterBody'],
<ide> footer: ['beforeFooter', 'footer', 'afterFooter'],
<del> x: 216,
<del> y: 190,
<ide> caretPadding: 2,
<ide> labelColors: [{
<ide> borderColor: 'rgb(255, 0, 0)',
<ide> describe('tooltip tests', function() {
<ide> backgroundColor: 'rgb(0, 255, 255)'
<ide> }]
<ide> }));
<add>
<add> expect(tooltip._view.x).toBeCloseTo(216, 1);
<add> expect(tooltip._view.y).toBeCloseTo(190, 1);
<ide> });
<ide>
<ide> it('Should display information from user callbacks', function() {
<ide> describe('tooltip tests', function() {
<ide> }],
<ide> afterBody: [],
<ide> footer: [],
<del> x: 269,
<del> y: 155,
<ide> labelColors: [{
<ide> borderColor: 'rgb(0, 0, 255)',
<ide> backgroundColor: 'rgb(0, 255, 255)'
<ide> describe('tooltip tests', function() {
<ide> backgroundColor: 'rgb(0, 255, 0)'
<ide> }]
<ide> }));
<add>
<add> expect(tooltip._view.x).toBeCloseTo(269, 1);
<add> expect(tooltip._view.y).toBeCloseTo(155, 1);
<ide> });
<ide> });
| 1
|
Mixed
|
Ruby
|
remove deprecated method `supports_primary_key?`
|
c56ff22fc6e97df4656ddc22909d9bf8b0c2cbb1
|
<ide><path>activerecord/CHANGELOG.md
<add>* Remove deprecated method `supports_primary_key?`.
<add>
<add> *Rafael Mendonça França*
<add>
<ide> * Remove deprecated method `supports_migrations?`.
<ide>
<ide> *Rafael Mendonça França*
<ide><path>activerecord/lib/active_record/connection_adapters/abstract_adapter.rb
<ide> def adapter_name
<ide> self.class::ADAPTER_NAME
<ide> end
<ide>
<del> def supports_primary_key? # :nodoc:
<del> true
<del> end
<del> deprecate :supports_primary_key?
<del>
<ide> # Does this adapter support DDL rollbacks in transactions? That is, would
<ide> # CREATE TABLE or ALTER TABLE get rolled back by a transaction?
<ide> def supports_ddl_transactions?
<ide><path>activerecord/test/cases/primary_keys_test.rb
<ide> def test_instance_destroy_should_quote_pkey
<ide> assert_nothing_raised { MixedCaseMonkey.find(1).destroy }
<ide> end
<ide>
<del> def test_deprecate_supports_primary_key
<del> assert_deprecated { ActiveRecord::Base.connection.supports_primary_key? }
<del> end
<del>
<ide> def test_primary_key_returns_value_if_it_exists
<ide> klass = Class.new(ActiveRecord::Base) do
<ide> self.table_name = "developers"
| 3
|
Java
|
Java
|
refine throwable handling in spring-websocket
|
526d89e1e61807faffdb3686e4243ffa4c2831f0
|
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/jetty/JettyWebSocketHandlerAdapter.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 void onWebSocketConnect(Session session) {
<ide> this.wsSession.initializeNativeSession(session);
<ide> this.webSocketHandler.afterConnectionEstablished(this.wsSession);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> public void onWebSocketText(String payload) {
<ide> try {
<ide> this.webSocketHandler.handleMessage(this.wsSession, message);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> public void onWebSocketBinary(byte[] payload, int offset, int length) {
<ide> try {
<ide> this.webSocketHandler.handleMessage(this.wsSession, message);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> public void onWebSocketFrame(Frame frame) {
<ide> try {
<ide> this.webSocketHandler.handleMessage(this.wsSession, message);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> public void onWebSocketClose(int statusCode, String reason) {
<ide> try {
<ide> this.webSocketHandler.afterConnectionClosed(this.wsSession, closeStatus);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> if (logger.isWarnEnabled()) {
<ide> logger.warn("Unhandled exception after connection closed for " + this, ex);
<ide> }
<ide> public void onWebSocketError(Throwable cause) {
<ide> try {
<ide> this.webSocketHandler.handleTransportError(this.wsSession, cause);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/adapter/standard/StandardWebSocketHandlerAdapter.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 void onMessage(javax.websocket.PongMessage message) {
<ide> try {
<ide> this.handler.afterConnectionEstablished(this.wsSession);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> private void handleTextMessage(javax.websocket.Session session, String payload,
<ide> try {
<ide> this.handler.handleMessage(this.wsSession, textMessage);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> private void handleBinaryMessage(javax.websocket.Session session, ByteBuffer pay
<ide> try {
<ide> this.handler.handleMessage(this.wsSession, binaryMessage);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> private void handlePongMessage(javax.websocket.Session session, ByteBuffer paylo
<ide> try {
<ide> this.handler.handleMessage(this.wsSession, pongMessage);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide> public void onClose(javax.websocket.Session session, CloseReason reason) {
<ide> try {
<ide> this.handler.afterConnectionClosed(this.wsSession, closeStatus);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> if (logger.isWarnEnabled()) {
<ide> logger.warn("Unhandled on-close exception for " + this.wsSession, ex);
<ide> }
<ide> public void onError(javax.websocket.Session session, Throwable exception) {
<ide> try {
<ide> this.handler.handleTransportError(this.wsSession, exception);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> ExceptionWebSocketHandlerDecorator.tryCloseWithError(this.wsSession, ex, logger);
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/handler/ExceptionWebSocketHandlerDecorator.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 void afterConnectionEstablished(WebSocketSession session) {
<ide> try {
<ide> getDelegate().afterConnectionEstablished(session);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> tryCloseWithError(session, ex, logger);
<ide> }
<ide> }
<ide> public void handleMessage(WebSocketSession session, WebSocketMessage<?> message)
<ide> try {
<ide> getDelegate().handleMessage(session, message);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> tryCloseWithError(session, ex, logger);
<ide> }
<ide> }
<ide> public void handleTransportError(WebSocketSession session, Throwable exception)
<ide> try {
<ide> getDelegate().handleTransportError(session, exception);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> tryCloseWithError(session, ex, logger);
<ide> }
<ide> }
<ide> public void afterConnectionClosed(WebSocketSession session, CloseStatus closeSta
<ide> try {
<ide> getDelegate().afterConnectionClosed(session, closeStatus);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> if (logger.isWarnEnabled()) {
<ide> logger.warn("Unhandled exception after connection closed for " + this, ex);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/AbstractHandshakeHandler.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 (websphereWsPresent) {
<ide> Class<?> clazz = ClassUtils.forName(className, AbstractHandshakeHandler.class.getClassLoader());
<ide> return (RequestUpgradeStrategy) ReflectionUtils.accessibleConstructor(clazz).newInstance();
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> throw new IllegalStateException(
<ide> "Failed to instantiate RequestUpgradeStrategy: " + className, ex);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/HandshakeInterceptorChain.java
<ide> public void applyAfterHandshake(
<ide> try {
<ide> interceptor.afterHandshake(request, response, this.wsHandler, failure);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> if (logger.isWarnEnabled()) {
<ide> logger.warn(interceptor + " threw exception in afterHandshake: " + ex);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/server/support/WebSocketHttpRequestHandler.java
<ide> public void handleRequest(HttpServletRequest servletRequest, HttpServletResponse
<ide> catch (HandshakeFailureException ex) {
<ide> failure = ex;
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> failure = new HandshakeFailureException("Uncaught failure for request " + request.getURI(), ex);
<ide> }
<ide> finally {
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/AbstractClientSockJsSession.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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> private void handleOpenFrame() {
<ide> this.webSocketHandler.afterConnectionEstablished(this);
<ide> this.connectFuture.set(this);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> if (logger.isErrorEnabled()) {
<ide> logger.error("WebSocketHandler.afterConnectionEstablished threw exception in " + this, ex);
<ide> }
<ide> private void handleMessageFrame(SockJsFrame frame) {
<ide> try {
<ide> this.webSocketHandler.handleMessage(this, new TextMessage(message));
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> logger.error("WebSocketHandler.handleMessage threw an exception on " + frame + " in " + this, ex);
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/RestTemplateXhrTransport.java
<ide> protected void connectInternal(final TransportRequest transportRequest, final We
<ide> getRestTemplate().execute(receiveUrl, HttpMethod.POST, requestCallback, responseExtractor);
<ide> requestCallback = requestCallbackAfterHandshake;
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> if (!connectFuture.isDone()) {
<ide> connectFuture.setException(ex);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/client/SockJsClient.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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 final ListenableFuture<WebSocketSession> doHandshake(
<ide> ServerInfo serverInfo = getServerInfo(sockJsUrlInfo, getHttpRequestHeaders(headers));
<ide> createRequest(sockJsUrlInfo, headers, serverInfo).connect(handler, connectFuture);
<ide> }
<del> catch (Throwable exception) {
<add> catch (Exception exception) {
<ide> if (logger.isErrorEnabled()) {
<ide> logger.error("Initial SockJS \"Info\" request to server failed, url=" + url, exception);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/support/SockJsHttpRequestHandler.java
<ide> /*
<del> * Copyright 2002-2015 the original author or authors.
<add> * Copyright 2002-2019 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 void handleRequest(HttpServletRequest servletRequest, HttpServletResponse
<ide> try {
<ide> this.sockJsService.handleRequest(request, response, getSockJsPath(servletRequest), this.webSocketHandler);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> throw new SockJsException("Uncaught failure in SockJS request, uri=" + request.getURI(), ex);
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/TransportHandlingSockJsService.java
<ide> /*
<del> * Copyright 2002-2018 the original author or authors.
<add> * Copyright 2002-2019 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> protected void handleRawWebSocketRequest(ServerHttpRequest request, ServerHttpRe
<ide> catch (HandshakeFailureException ex) {
<ide> failure = ex;
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> failure = new HandshakeFailureException("Uncaught failure for request " + request.getURI(), ex);
<ide> }
<del> finally {
<add> finally {
<ide> if (failure != null) {
<ide> chain.applyAfterHandshake(request, response, failure);
<ide> throw failure;
<ide> else if (transportType.supportsCors()) {
<ide> catch (SockJsException ex) {
<ide> failure = ex;
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> failure = new SockJsException("Uncaught failure for request " + request.getURI(), sessionId, ex);
<ide> }
<ide> finally {
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/AbstractHttpReceivingTransportHandler.java
<ide> /*
<del> * Copyright 2002-2017 the original author or authors.
<add> * Copyright 2002-2019 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> protected void handleRequestInternal(ServerHttpRequest request, ServerHttpRespon
<ide> }
<ide> return;
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> logger.error("Failed to read message", ex);
<ide> handleReadError(response, "Failed to read message(s)", sockJsSession.getId());
<ide> return;
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/handler/WebSocketTransportHandler.java
<ide> public void handleRequest(ServerHttpRequest request, ServerHttpResponse response
<ide> wsHandler = new SockJsWebSocketHandler(getServiceConfig(), wsHandler, sockJsSession);
<ide> this.handshakeHandler.doHandshake(request, response, wsHandler, sockJsSession.getAttributes());
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> sockJsSession.tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
<ide> throw new SockJsTransportFailureException("WebSocket handshake failure", wsSession.getId(), ex);
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/AbstractSockJsSession.java
<ide> protected void writeFrame(SockJsFrame frame) throws SockJsTransportFailureExcept
<ide> try {
<ide> writeFrameInternal(frame);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> logWriteFrameFailure(ex);
<ide> try {
<ide> // Force disconnect (so we won't try to send close frame)
<ide> public void delegateMessages(String... messages) throws SockJsMessageDeliveryExc
<ide> undelivered.remove(0);
<ide> }
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> throw new SockJsMessageDeliveryException(this.id, undelivered, ex);
<ide> }
<ide> }
<ide><path>spring-websocket/src/main/java/org/springframework/web/socket/sockjs/transport/session/WebSocketServerSockJsSession.java
<ide> public void initializeDelegateSession(WebSocketSession session) {
<ide> scheduleHeartbeat();
<ide> this.openFrameSent = true;
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> tryCloseWithSockJsTransportError(ex, CloseStatus.SERVER_ERROR);
<ide> }
<ide> }
<ide> public void handleMessage(TextMessage message, WebSocketSession wsSession) throw
<ide> try {
<ide> messages = getSockJsServiceConfig().getMessageCodec().decode(payload);
<ide> }
<del> catch (Throwable ex) {
<add> catch (Exception ex) {
<ide> logger.error("Broken data received. Terminating WebSocket connection abruptly", ex);
<ide> tryCloseWithSockJsTransportError(ex, CloseStatus.BAD_DATA);
<ide> return;
| 15
|
Mixed
|
PHP
|
fix method psr-2 braces in docblock code examples
|
bf95aa1421394aa9d3086cc52db173ee7f261411
|
<ide><path>src/Auth/ControllerAuthorize.php
<ide> * return a boolean to indicate whether or not the user is authorized.
<ide> *
<ide> * ```
<del> * public function isAuthorized($user) {
<add> * public function isAuthorized($user)
<add> * {
<ide> * if ($this->request->param('admin')) {
<ide> * return $user['role'] === 'admin';
<ide> * }
<ide><path>src/Event/EventListenerInterface.php
<ide> interface EventListenerInterface
<ide> * ### Example:
<ide> *
<ide> * ```
<del> * public function implementedEvents() {
<add> * public function implementedEvents()
<add> * {
<ide> * return [
<ide> * 'Order.complete' => 'sendEmail',
<ide> * 'Article.afterBuy' => 'decrementInventory',
<ide><path>src/Event/README.md
<ide> class Orders {
<ide>
<ide> use EventManagerTrait;
<ide>
<del> public function placeOrder($order) {
<add> public function placeOrder($order)
<add> {
<ide> $this->doStuff();
<ide> $event = new Event('Orders.afterPlace', $this, [
<ide> 'order' => $order
<ide><path>src/ORM/Table.php
<ide> public static function defaultConnectionName()
<ide> * define validation and do any other initialization logic you need.
<ide> *
<ide> * ```
<del> * public function initialize(array $config) {
<add> * public function initialize(array $config)
<add> * {
<ide> * $this->belongsTo('Users');
<ide> * $this->belongsToMany('Tagging.Tags');
<ide> * $this->primaryKey('something_else');
<ide> public function updateAll($fields, $conditions)
<ide> * you will need to create a method in your Table subclass as follows:
<ide> *
<ide> * ```
<del> * public function validationForSubscription($validator) {
<add> * public function validationForSubscription($validator)
<add> * {
<ide> * return $validator
<ide> * ->add('email', 'valid-email', ['rule' => 'email'])
<ide> * ->add('password', 'valid', ['rule' => 'notEmpty'])
| 4
|
PHP
|
PHP
|
apply fixes from styleci
|
ee7398572518e7fe768cbea10d4bfddd87314c18
|
<ide><path>src/Illuminate/Cache/CacheServiceProvider.php
<ide> namespace Illuminate\Cache;
<ide>
<ide> use Illuminate\Support\ServiceProvider;
<del>use Illuminate\Contracts\Support\DeferrableProvider;
<ide> use Symfony\Component\Cache\Adapter\Psr16Adapter;
<add>use Illuminate\Contracts\Support\DeferrableProvider;
<ide>
<ide> class CacheServiceProvider extends ServiceProvider implements DeferrableProvider
<ide> {
| 1
|
Python
|
Python
|
fix unused imports
|
778ef8ec1d3c48f849aa13bee9f88419baeeb969
|
<ide><path>celery/utils/__init__.py
<ide> """
<ide> from __future__ import absolute_import, print_function, unicode_literals
<ide>
<del>from kombu.utils.objects import cached_property # noqa: F401
<del>from kombu.utils.uuid import uuid # noqa: F401
<add>from kombu.utils.objects import cached_property
<add>from kombu.utils.uuid import uuid
<ide>
<ide> from .functional import chunks, noop
<del>from .imports import gen_task_name, import_from_cwd, instantiate # noqa: F401
<del>from .imports import qualname as get_full_cls_name # noqa: F401
<del>from .imports import symbol_by_name as get_cls_by_name # noqa: F401
<add>from .functional import memoize
<add>from .imports import gen_task_name, import_from_cwd, instantiate
<add>from .imports import qualname as get_full_cls_name
<add>from .imports import symbol_by_name as get_cls_by_name
<ide> # ------------------------------------------------------------------------ #
<ide> # > XXX Compat
<del>from .log import LOG_LEVELS # noqa
<add>from .log import LOG_LEVELS
<ide> from .nodenames import nodename, nodesplit, worker_direct
<ide>
<del>from .functional import memoize # noqa: F401; noqa: F401
<del>
<del>__all__ = ('worker_direct', 'gen_task_name', 'nodename', 'nodesplit',
<del> 'cached_property', 'uuid')
<del>
<ide> gen_unique_id = uuid
<add>
<add>__all__ = (
<add> 'LOG_LEVELS',
<add> 'cached_property',
<add> 'chunks',
<add> 'gen_task_name',
<add> 'gen_task_name',
<add> 'gen_unique_id',
<add> 'get_cls_by_name',
<add> 'get_full_cls_name',
<add> 'import_from_cwd',
<add> 'instantiate',
<add> 'memoize',
<add> 'nodename',
<add> 'nodesplit',
<add> 'noop',
<add> 'uuid',
<add> 'worker_direct'
<add>)
<ide><path>celery/utils/log.py
<ide> from kombu.utils.encoding import safe_str
<ide>
<ide> from celery.five import string_t, text_t
<del>
<ide> from .term import colored
<ide>
<ide> __all__ = (
<ide> 'ColorFormatter', 'LoggingProxy', 'base_logger',
<ide> 'set_in_sighandler', 'in_sighandler', 'get_logger',
<ide> 'get_task_logger', 'mlevel',
<del> 'get_multiprocessing_logger', 'reset_multiprocessing_logger',
<add> 'get_multiprocessing_logger', 'reset_multiprocessing_logger', 'LOG_LEVELS'
<ide> )
<ide>
<ide> _process_aware = False
<ide><path>t/unit/tasks/test_tasks.py
<ide> def test_retry(self):
<ide>
<ide> def test_retry_priority(self):
<ide> priority = 7
<del>
<add>
<ide> # Technically, task.priority doesn't need to be set here
<ide> # since push_request() doesn't populate the delivery_info
<ide> # with it. However, setting task.priority here also doesn't
| 3
|
PHP
|
PHP
|
apply fixes from styleci
|
705642d1983443a94182973de3306b9144cee3bd
|
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function apiResource($name, $controller, array $options = [])
<ide> * @return void
<ide> */
<ide> public function group(array $attributes, $routes)
<del> {
<add> {
<ide> foreach (Arr::wrap($routes) as $groupRoutes) {
<ide> $this->updateGroupStack($attributes);
<ide>
| 1
|
Javascript
|
Javascript
|
improve explanation of attributes.$observe
|
40414827f42c8fb86abb835f7387d5b02923d532
|
<ide><path>src/ng/compile.js
<ide> function $CompileProvider($provide) {
<ide> * @function
<ide> *
<ide> * @description
<del> * Observe an interpolated attribute.
<del> * The observer will never be called, if given attribute is not interpolated.
<del> * The interpolated value of the attribute is passed to the observer function.
<add> * Observes an interpolated attribute.
<add> *
<add> * The observer function will be invoked once during the next `$digest` following
<add> * compilation. The observer is then invoked whenever the interpolated value
<add> * changes.
<ide> *
<ide> * @param {string} key Normalized key. (ie ngAttribute) .
<ide> * @param {function(interpolatedValue)} fn Function that will be called whenever
| 1
|
Text
|
Text
|
modify the translation.
|
d04713636c0df5ae876a85668b1aaf2448582f82
|
<ide><path>guide/chinese/algorithms/index.md
<ide> localeTitle: 算法
<ide>
<ide> #### 快速排序
<ide>
<del>没有快速排序可以完成排序讨论。基本概念在以下链接中。 [快速排序](http://me.dt.in.th/page/Quicksort/)
<add>几乎所有与排序相关的讨论都涉及快速排序。基本概念在以下链接中。 [快速排序](http://me.dt.in.th/page/Quicksort/)
<ide>
<ide> #### 合并排序
<ide>
<ide> freeCodeCamp的课程强调创建算法。这是因为学习算法是练习编
<ide>
<ide> [算法可视化器](http://algo-visualizer.jasonpark.me)
<ide>
<del>这也是一个非常好的开源项目,可以帮助您可视化算法。
<ide>\ No newline at end of file
<add>这也是一个非常好的开源项目,可以帮助您可视化算法。
| 1
|
PHP
|
PHP
|
add more tests
|
4cafe8801cbad081c2b5d0a0fbd2816679fb9060
|
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testInfo()
<ide> $this->Shell->info('Just a test');
<ide> }
<ide>
<add> /**
<add> * testInfo method with array
<add> *
<add> * @return void
<add> */
<add> public function testInfoArray()
<add> {
<add> $this->io->expects($this->once())
<add> ->method('out')
<add> ->with(['<info>Just</info>', '<info>a</info>', '<info>test</info>'], 1);
<add>
<add> $this->Shell->info(['Just', 'a', 'test']);
<add> }
<add>
<ide> /**
<ide> * testWarn method
<ide> *
<ide> public function testWarn()
<ide> $this->Shell->warn('Just a test');
<ide> }
<ide>
<add> /**
<add> * testWarn method with array
<add> *
<add> * @return void
<add> */
<add> public function testWarnArray()
<add> {
<add> $this->io->expects($this->once())
<add> ->method('err')
<add> ->with(['<warning>Just</warning>', '<warning>a</warning>', '<warning>test</warning>'], 1);
<add>
<add> $this->Shell->warn(['Just', 'a', 'test']);
<add> }
<add>
<ide> /**
<ide> * testSuccess method
<ide> *
<ide> public function testSuccess()
<ide> $this->Shell->success('Just a test');
<ide> }
<ide>
<add> /**
<add> * testSuccess method with array
<add> *
<add> * @return void
<add> */
<add> public function testSuccessArray()
<add> {
<add> $this->io->expects($this->once())
<add> ->method('out')
<add> ->with(['<success>Just</success>', '<success>a</success>', '<success>test</success>'], 1);
<add>
<add> $this->Shell->success(['Just', 'a', 'test']);
<add> }
<add>
<ide> /**
<ide> * testNl
<ide> *
| 1
|
Java
|
Java
|
remove stream#toblockingqueue use
|
b7b423a0033f22de8ce49c09fcb39e81eaecc94c
|
<ide><path>spring-web-reactive/src/main/java/org/springframework/core/io/buffer/support/DataBufferPublisherInputStream.java
<ide>
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<del>import java.util.concurrent.BlockingQueue;
<add>import java.util.Iterator;
<ide> import java.util.concurrent.atomic.AtomicBoolean;
<ide>
<ide> import org.reactivestreams.Publisher;
<ide> import org.reactivestreams.Subscription;
<del>import reactor.rx.Stream;
<add>import reactor.core.publisher.Flux;
<ide>
<ide> import org.springframework.core.io.buffer.DataBuffer;
<ide> import org.springframework.util.Assert;
<ide> class DataBufferPublisherInputStream extends InputStream {
<ide>
<ide> private final AtomicBoolean completed = new AtomicBoolean();
<ide>
<del> private final BlockingQueue<DataBuffer> queue;
<add> private final Iterator<DataBuffer> queue;
<ide>
<ide> private InputStream currentStream;
<ide>
<ide> public DataBufferPublisherInputStream(Publisher<DataBuffer> publisher,
<ide> int requestSize) {
<ide> Assert.notNull(publisher, "'publisher' must not be null");
<ide>
<del> // TODO Avoid using Reactor Stream, it should not be a mandatory dependency of Spring Reactive
<del> this.queue = Stream.from(publisher).toBlockingQueue(requestSize);
<add> this.queue = Flux.from(publisher).toIterable(requestSize).iterator();
<ide> }
<ide>
<ide> @Override
<ide> private InputStream currentStream() throws IOException {
<ide> return this.currentStream;
<ide> }
<ide> else {
<del> // take() blocks until next or complete() then return null,
<del> // but that's OK since this is a *blocking* InputStream
<del> DataBuffer signal = this.queue.take();
<del> if (signal == null) {
<add> // if upstream Publisher has completed, then complete() and return null,
<add> if (!this.queue.hasNext()) {
<ide> this.completed.set(true);
<ide> return null;
<ide> }
<add> // next() blocks until next
<add> // but that's OK since this is a *blocking* InputStream
<add> DataBuffer signal = this.queue.next();
<ide> this.currentStream = signal.asInputStream();
<ide> return this.currentStream;
<ide> }
<ide> }
<del> catch (InterruptedException ex) {
<del> Thread.currentThread().interrupt();
<del> }
<ide> catch (Throwable error) {
<ide> this.completed.set(true);
<ide> throw new IOException(error);
<ide> }
<del> throw new IOException();
<ide> }
<ide>
<ide>
| 1
|
Go
|
Go
|
update id of trace messages
|
8ccbc2c40a063dbd4251b684ded1573d99ded337
|
<ide><path>builder/builder-next/builder.go
<ide> func (b *Builder) Build(ctx context.Context, opt backend.BuildConfig) (*builder.
<ide> }
<ide> auxJSON := new(json.RawMessage)
<ide> *auxJSON = auxJSONBytes
<del> msgJSON, err := json.Marshal(&jsonmessage.JSONMessage{ID: "buildkit-trace", Aux: auxJSON})
<add> msgJSON, err := json.Marshal(&jsonmessage.JSONMessage{ID: "moby.buildkit.trace", Aux: auxJSON})
<ide> if err != nil {
<ide> return err
<ide> }
| 1
|
Python
|
Python
|
fix fab train
|
bdacedc434e5aad4065278a08ba668db867b6c78
|
<ide><path>fabfile.py
<ide> def train(json_dir=None, dev_loc=None, model_dir=None):
<ide> with virtualenv(VENV_DIR):
<ide> with lcd(path.dirname(__file__)):
<ide> local('python bin/init_model.py en lang_data/ corpora/ ' + model_dir)
<del> local('python bin/parser/train.py %s %s' % (json_dir, model_dir))
<add> local('python bin/parser/train.py -p en %s/train/ %s/development %s' % (json_dir, json_dir, model_dir))
<ide>
<ide>
<ide> def travis():
| 1
|
Javascript
|
Javascript
|
use gate pragma instead of if (__experimental__)
|
4f5fb56100fac50f2c8bb33f984301b550e71407
|
<ide><path>packages/react-dom/src/__tests__/ReactDOMServerIntegrationHooks-test.js
<ide> describe('ReactDOMServerHooks', () => {
<ide> expect(container.children[0].textContent).toEqual('0');
<ide> });
<ide>
<del> if (__EXPERIMENTAL__) {
<del> describe('useOpaqueIdentifier', () => {
<del> it('generates unique ids for server string render', async () => {
<del> function App(props) {
<del> const idOne = useOpaqueIdentifier();
<del> const idTwo = useOpaqueIdentifier();
<del> return (
<del> <div>
<del> <div aria-labelledby={idOne} />
<del> <div id={idOne} />
<del> <span aria-labelledby={idTwo} />
<del> <span id={idTwo} />
<del> </div>
<del> );
<del> }
<del>
<del> const domNode = await serverRender(<App />);
<del> expect(domNode.children.length).toEqual(4);
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[1].getAttribute('id'),
<del> );
<del> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[3].getAttribute('id'),
<del> );
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<add> describe('useOpaqueIdentifier', () => {
<add> // @gate experimental
<add> it('generates unique ids for server string render', async () => {
<add> function App(props) {
<add> const idOne = useOpaqueIdentifier();
<add> const idTwo = useOpaqueIdentifier();
<add> return (
<add> <div>
<add> <div aria-labelledby={idOne} />
<add> <div id={idOne} />
<add> <span aria-labelledby={idTwo} />
<add> <span id={idTwo} />
<add> </div>
<ide> );
<del> expect(
<del> domNode.children[0].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> expect(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> });
<add> }
<ide>
<del> it('generates unique ids for server stream render', async () => {
<del> function App(props) {
<del> const idOne = useOpaqueIdentifier();
<del> const idTwo = useOpaqueIdentifier();
<del> return (
<del> <div>
<del> <div aria-labelledby={idOne} />
<del> <div id={idOne} />
<del> <span aria-labelledby={idTwo} />
<del> <span id={idTwo} />
<del> </div>
<del> );
<del> }
<add> const domNode = await serverRender(<App />);
<add> expect(domNode.children.length).toEqual(4);
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[1].getAttribute('id'),
<add> );
<add> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[3].getAttribute('id'),
<add> );
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> );
<add> expect(
<add> domNode.children[0].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> expect(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> const domNode = await streamRender(<App />);
<del> expect(domNode.children.length).toEqual(4);
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[1].getAttribute('id'),
<del> );
<del> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[3].getAttribute('id'),
<del> );
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<add> // @gate experimental
<add> it('generates unique ids for server stream render', async () => {
<add> function App(props) {
<add> const idOne = useOpaqueIdentifier();
<add> const idTwo = useOpaqueIdentifier();
<add> return (
<add> <div>
<add> <div aria-labelledby={idOne} />
<add> <div id={idOne} />
<add> <span aria-labelledby={idTwo} />
<add> <span id={idTwo} />
<add> </div>
<ide> );
<del> expect(
<del> domNode.children[0].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> expect(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> });
<add> }
<ide>
<del> it('generates unique ids for client render', async () => {
<del> function App(props) {
<del> const idOne = useOpaqueIdentifier();
<del> const idTwo = useOpaqueIdentifier();
<del> return (
<del> <div>
<del> <div aria-labelledby={idOne} />
<del> <div id={idOne} />
<del> <span aria-labelledby={idTwo} />
<del> <span id={idTwo} />
<del> </div>
<del> );
<del> }
<add> const domNode = await streamRender(<App />);
<add> expect(domNode.children.length).toEqual(4);
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[1].getAttribute('id'),
<add> );
<add> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[3].getAttribute('id'),
<add> );
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> );
<add> expect(
<add> domNode.children[0].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> expect(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> const domNode = await clientCleanRender(<App />);
<del> expect(domNode.children.length).toEqual(4);
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[1].getAttribute('id'),
<del> );
<del> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[3].getAttribute('id'),
<del> );
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<add> // @gate experimental
<add> it('generates unique ids for client render', async () => {
<add> function App(props) {
<add> const idOne = useOpaqueIdentifier();
<add> const idTwo = useOpaqueIdentifier();
<add> return (
<add> <div>
<add> <div aria-labelledby={idOne} />
<add> <div id={idOne} />
<add> <span aria-labelledby={idTwo} />
<add> <span id={idTwo} />
<add> </div>
<ide> );
<del> expect(
<del> domNode.children[0].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> expect(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> });
<add> }
<ide>
<del> it('generates unique ids for client render on good server markup', async () => {
<del> function App(props) {
<del> const idOne = useOpaqueIdentifier();
<del> const idTwo = useOpaqueIdentifier();
<del> return (
<del> <div>
<del> <div aria-labelledby={idOne} />
<del> <div id={idOne} />
<del> <span aria-labelledby={idTwo} />
<del> <span id={idTwo} />
<del> </div>
<del> );
<del> }
<add> const domNode = await clientCleanRender(<App />);
<add> expect(domNode.children.length).toEqual(4);
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[1].getAttribute('id'),
<add> );
<add> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[3].getAttribute('id'),
<add> );
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> );
<add> expect(
<add> domNode.children[0].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> expect(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> const domNode = await clientRenderOnServerString(<App />);
<del> expect(domNode.children.length).toEqual(4);
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[1].getAttribute('id'),
<del> );
<del> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[3].getAttribute('id'),
<add> // @gate experimental
<add> it('generates unique ids for client render on good server markup', async () => {
<add> function App(props) {
<add> const idOne = useOpaqueIdentifier();
<add> const idTwo = useOpaqueIdentifier();
<add> return (
<add> <div>
<add> <div aria-labelledby={idOne} />
<add> <div id={idOne} />
<add> <span aria-labelledby={idTwo} />
<add> <span id={idTwo} />
<add> </div>
<ide> );
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<add> }
<add>
<add> const domNode = await clientRenderOnServerString(<App />);
<add> expect(domNode.children.length).toEqual(4);
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[1].getAttribute('id'),
<add> );
<add> expect(domNode.children[2].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[3].getAttribute('id'),
<add> );
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).not.toEqual(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> );
<add> expect(
<add> domNode.children[0].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> expect(
<add> domNode.children[2].getAttribute('aria-labelledby'),
<add> ).not.toBeNull();
<add> });
<add>
<add> // @gate experimental
<add> it('useOpaqueIdentifier does not change id even if the component updates during client render', async () => {
<add> let _setShowId;
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> const [showId, setShowId] = useState(false);
<add> _setShowId = setShowId;
<add> return (
<add> <div>
<add> <div aria-labelledby={id} />
<add> {showId && <div id={id} />}
<add> </div>
<ide> );
<del> expect(
<del> domNode.children[0].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> expect(
<del> domNode.children[2].getAttribute('aria-labelledby'),
<del> ).not.toBeNull();
<del> });
<add> }
<ide>
<del> it('useOpaqueIdentifier does not change id even if the component updates during client render', async () => {
<del> let _setShowId;
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> const [showId, setShowId] = useState(false);
<del> _setShowId = setShowId;
<del> return (
<del> <div>
<del> <div aria-labelledby={id} />
<del> {showId && <div id={id} />}
<del> </div>
<del> );
<del> }
<add> const domNode = await clientCleanRender(<App />);
<add> const oldClientId = domNode.children[0].getAttribute('aria-labelledby');
<ide>
<del> const domNode = await clientCleanRender(<App />);
<del> const oldClientId = domNode.children[0].getAttribute('aria-labelledby');
<add> expect(domNode.children.length).toEqual(1);
<add> expect(oldClientId).not.toBeNull();
<ide>
<del> expect(domNode.children.length).toEqual(1);
<del> expect(oldClientId).not.toBeNull();
<add> await ReactTestUtils.act(async () => _setShowId(true));
<ide>
<del> await ReactTestUtils.act(async () => _setShowId(true));
<add> expect(domNode.children.length).toEqual(2);
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<add> domNode.children[1].getAttribute('id'),
<add> );
<add> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<add> oldClientId,
<add> );
<add> });
<ide>
<del> expect(domNode.children.length).toEqual(2);
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<del> domNode.children[1].getAttribute('id'),
<del> );
<del> expect(domNode.children[0].getAttribute('aria-labelledby')).toEqual(
<del> oldClientId,
<add> // @gate experimental
<add> it('useOpaqueIdentifier identifierPrefix works for server renderer and does not clash', async () => {
<add> function ChildTwo({id}) {
<add> return <div id={id}>Child Three</div>;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> const idTwo = useOpaqueIdentifier();
<add>
<add> return (
<add> <div>
<add> <div aria-labelledby={id}>Child One</div>
<add> <ChildTwo id={id} />
<add> <div aria-labelledby={idTwo}>Child Three</div>
<add> <div id={idTwo}>Child Four</div>
<add> </div>
<ide> );
<add> }
<add>
<add> const containerOne = document.createElement('div');
<add> document.body.append(containerOne);
<add>
<add> containerOne.innerHTML = ReactDOMServer.renderToString(<App />, {
<add> identifierPrefix: 'one',
<ide> });
<ide>
<del> it('useOpaqueIdentifier identifierPrefix works for server renderer and does not clash', async () => {
<del> function ChildTwo({id}) {
<del> return <div id={id}>Child Three</div>;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> const idTwo = useOpaqueIdentifier();
<add> const containerTwo = document.createElement('div');
<add> document.body.append(containerTwo);
<ide>
<del> return (
<del> <div>
<del> <div aria-labelledby={id}>Child One</div>
<del> <ChildTwo id={id} />
<del> <div aria-labelledby={idTwo}>Child Three</div>
<del> <div id={idTwo}>Child Four</div>
<del> </div>
<del> );
<del> }
<add> containerTwo.innerHTML = ReactDOMServer.renderToString(<App />, {
<add> identifierPrefix: 'two',
<add> });
<ide>
<del> const containerOne = document.createElement('div');
<del> document.body.append(containerOne);
<add> expect(document.body.children.length).toEqual(2);
<add> const childOne = document.body.children[0];
<add> const childTwo = document.body.children[1];
<add>
<add> expect(
<add> childOne.children[0].children[0].getAttribute('aria-labelledby'),
<add> ).toEqual(childOne.children[0].children[1].getAttribute('id'));
<add> expect(
<add> childOne.children[0].children[2].getAttribute('aria-labelledby'),
<add> ).toEqual(childOne.children[0].children[3].getAttribute('id'));
<add>
<add> expect(
<add> childOne.children[0].children[0].getAttribute('aria-labelledby'),
<add> ).not.toEqual(
<add> childOne.children[0].children[2].getAttribute('aria-labelledby'),
<add> );
<ide>
<del> containerOne.innerHTML = ReactDOMServer.renderToString(<App />, {
<del> identifierPrefix: 'one',
<del> });
<add> expect(
<add> childOne.children[0].children[0]
<add> .getAttribute('aria-labelledby')
<add> .startsWith('one'),
<add> ).toBe(true);
<add> expect(
<add> childOne.children[0].children[2]
<add> .getAttribute('aria-labelledby')
<add> .includes('one'),
<add> ).toBe(true);
<add>
<add> expect(
<add> childTwo.children[0].children[0].getAttribute('aria-labelledby'),
<add> ).toEqual(childTwo.children[0].children[1].getAttribute('id'));
<add> expect(
<add> childTwo.children[0].children[2].getAttribute('aria-labelledby'),
<add> ).toEqual(childTwo.children[0].children[3].getAttribute('id'));
<add>
<add> expect(
<add> childTwo.children[0].children[0].getAttribute('aria-labelledby'),
<add> ).not.toEqual(
<add> childTwo.children[0].children[2].getAttribute('aria-labelledby'),
<add> );
<ide>
<del> const containerTwo = document.createElement('div');
<del> document.body.append(containerTwo);
<add> expect(
<add> childTwo.children[0].children[0]
<add> .getAttribute('aria-labelledby')
<add> .startsWith('two'),
<add> ).toBe(true);
<add> expect(
<add> childTwo.children[0].children[2]
<add> .getAttribute('aria-labelledby')
<add> .startsWith('two'),
<add> ).toBe(true);
<add> });
<ide>
<del> containerTwo.innerHTML = ReactDOMServer.renderToString(<App />, {
<del> identifierPrefix: 'two',
<del> });
<add> // @gate experimental
<add> it('useOpaqueIdentifier identifierPrefix works for multiple reads on a streaming server renderer', async () => {
<add> function ChildTwo() {
<add> const id = useOpaqueIdentifier();
<ide>
<del> expect(document.body.children.length).toEqual(2);
<del> const childOne = document.body.children[0];
<del> const childTwo = document.body.children[1];
<del>
<del> expect(
<del> childOne.children[0].children[0].getAttribute('aria-labelledby'),
<del> ).toEqual(childOne.children[0].children[1].getAttribute('id'));
<del> expect(
<del> childOne.children[0].children[2].getAttribute('aria-labelledby'),
<del> ).toEqual(childOne.children[0].children[3].getAttribute('id'));
<del>
<del> expect(
<del> childOne.children[0].children[0].getAttribute('aria-labelledby'),
<del> ).not.toEqual(
<del> childOne.children[0].children[2].getAttribute('aria-labelledby'),
<del> );
<add> return <div id={id}>Child Two</div>;
<add> }
<ide>
<del> expect(
<del> childOne.children[0].children[0]
<del> .getAttribute('aria-labelledby')
<del> .startsWith('one'),
<del> ).toBe(true);
<del> expect(
<del> childOne.children[0].children[2]
<del> .getAttribute('aria-labelledby')
<del> .includes('one'),
<del> ).toBe(true);
<del>
<del> expect(
<del> childTwo.children[0].children[0].getAttribute('aria-labelledby'),
<del> ).toEqual(childTwo.children[0].children[1].getAttribute('id'));
<del> expect(
<del> childTwo.children[0].children[2].getAttribute('aria-labelledby'),
<del> ).toEqual(childTwo.children[0].children[3].getAttribute('id'));
<del>
<del> expect(
<del> childTwo.children[0].children[0].getAttribute('aria-labelledby'),
<del> ).not.toEqual(
<del> childTwo.children[0].children[2].getAttribute('aria-labelledby'),
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add>
<add> return (
<add> <>
<add> <div id={id}>Child One</div>
<add> <ChildTwo />
<add> <div aria-labelledby={id}>Aria One</div>
<add> </>
<ide> );
<add> }
<ide>
<del> expect(
<del> childTwo.children[0].children[0]
<del> .getAttribute('aria-labelledby')
<del> .startsWith('two'),
<del> ).toBe(true);
<del> expect(
<del> childTwo.children[0].children[2]
<del> .getAttribute('aria-labelledby')
<del> .startsWith('two'),
<del> ).toBe(true);
<del> });
<add> const container = document.createElement('div');
<add> document.body.append(container);
<ide>
<del> it('useOpaqueIdentifier identifierPrefix works for multiple reads on a streaming server renderer', async () => {
<del> function ChildTwo() {
<del> const id = useOpaqueIdentifier();
<add> const streamOne = ReactDOMServer.renderToNodeStream(<App />, {
<add> identifierPrefix: 'one',
<add> }).setEncoding('utf8');
<add> const streamTwo = ReactDOMServer.renderToNodeStream(<App />, {
<add> identifierPrefix: 'two',
<add> }).setEncoding('utf8');
<ide>
<del> return <div id={id}>Child Two</div>;
<del> }
<add> const streamOneIsDone = new Promise((resolve, reject) => {
<add> streamOne.on('end', () => resolve());
<add> streamOne.on('error', e => reject(e));
<add> });
<add> const streamTwoIsDone = new Promise((resolve, reject) => {
<add> streamTwo.on('end', () => resolve());
<add> streamTwo.on('error', e => reject(e));
<add> });
<ide>
<del> function App() {
<del> const id = useOpaqueIdentifier();
<add> const containerOne = document.createElement('div');
<add> const containerTwo = document.createElement('div');
<ide>
<del> return (
<del> <>
<del> <div id={id}>Child One</div>
<del> <ChildTwo />
<del> <div aria-labelledby={id}>Aria One</div>
<del> </>
<del> );
<del> }
<add> streamOne._read(10);
<add> streamTwo._read(10);
<ide>
<del> const container = document.createElement('div');
<del> document.body.append(container);
<add> containerOne.innerHTML = streamOne.read();
<add> containerTwo.innerHTML = streamTwo.read();
<ide>
<del> const streamOne = ReactDOMServer.renderToNodeStream(<App />, {
<del> identifierPrefix: 'one',
<del> }).setEncoding('utf8');
<del> const streamTwo = ReactDOMServer.renderToNodeStream(<App />, {
<del> identifierPrefix: 'two',
<del> }).setEncoding('utf8');
<add> expect(containerOne.children[0].getAttribute('id')).not.toEqual(
<add> containerOne.children[1].getAttribute('id'),
<add> );
<add> expect(containerTwo.children[0].getAttribute('id')).not.toEqual(
<add> containerTwo.children[1].getAttribute('id'),
<add> );
<add> expect(containerOne.children[0].getAttribute('id')).not.toEqual(
<add> containerTwo.children[0].getAttribute('id'),
<add> );
<add> expect(containerOne.children[0].getAttribute('id').includes('one')).toBe(
<add> true,
<add> );
<add> expect(containerOne.children[1].getAttribute('id').includes('one')).toBe(
<add> true,
<add> );
<add> expect(containerTwo.children[0].getAttribute('id').includes('two')).toBe(
<add> true,
<add> );
<add> expect(containerTwo.children[1].getAttribute('id').includes('two')).toBe(
<add> true,
<add> );
<add>
<add> expect(containerOne.children[1].getAttribute('id')).not.toEqual(
<add> containerTwo.children[1].getAttribute('id'),
<add> );
<add> expect(containerOne.children[0].getAttribute('id')).toEqual(
<add> containerOne.children[2].getAttribute('aria-labelledby'),
<add> );
<add> expect(containerTwo.children[0].getAttribute('id')).toEqual(
<add> containerTwo.children[2].getAttribute('aria-labelledby'),
<add> );
<ide>
<del> const containerOne = document.createElement('div');
<del> const containerTwo = document.createElement('div');
<add> // Exhaust the rest of the stream
<add> class Sink extends require('stream').Writable {
<add> _write(chunk, encoding, done) {
<add> done();
<add> }
<add> }
<add> streamOne.pipe(new Sink());
<add> streamTwo.pipe(new Sink());
<ide>
<del> streamOne._read(10);
<del> streamTwo._read(10);
<add> await Promise.all([streamOneIsDone, streamTwoIsDone]);
<add> });
<ide>
<del> containerOne.innerHTML = streamOne.read();
<del> containerTwo.innerHTML = streamTwo.read();
<add> // @gate experimental
<add> it('useOpaqueIdentifier: IDs match when, after hydration, a new component that uses the ID is rendered', async () => {
<add> let _setShowDiv;
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> const [showDiv, setShowDiv] = useState(false);
<add> _setShowDiv = setShowDiv;
<ide>
<del> expect(containerOne.children[0].getAttribute('id')).not.toEqual(
<del> containerOne.children[1].getAttribute('id'),
<del> );
<del> expect(containerTwo.children[0].getAttribute('id')).not.toEqual(
<del> containerTwo.children[1].getAttribute('id'),
<del> );
<del> expect(containerOne.children[0].getAttribute('id')).not.toEqual(
<del> containerTwo.children[0].getAttribute('id'),
<del> );
<del> expect(
<del> containerOne.children[0].getAttribute('id').includes('one'),
<del> ).toBe(true);
<del> expect(
<del> containerOne.children[1].getAttribute('id').includes('one'),
<del> ).toBe(true);
<del> expect(
<del> containerTwo.children[0].getAttribute('id').includes('two'),
<del> ).toBe(true);
<del> expect(
<del> containerTwo.children[1].getAttribute('id').includes('two'),
<del> ).toBe(true);
<del>
<del> expect(containerOne.children[1].getAttribute('id')).not.toEqual(
<del> containerTwo.children[1].getAttribute('id'),
<del> );
<del> expect(containerOne.children[0].getAttribute('id')).toEqual(
<del> containerOne.children[2].getAttribute('aria-labelledby'),
<del> );
<del> expect(containerTwo.children[0].getAttribute('id')).toEqual(
<del> containerTwo.children[2].getAttribute('aria-labelledby'),
<add> return (
<add> <div>
<add> <div id={id}>Child One</div>
<add> {showDiv && <div id={id}>Child Two</div>}
<add> </div>
<ide> );
<del> });
<add> }
<ide>
<del> it('useOpaqueIdentifier: IDs match when, after hydration, a new component that uses the ID is rendered', async () => {
<del> let _setShowDiv;
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> const [showDiv, setShowDiv] = useState(false);
<del> _setShowDiv = setShowDiv;
<add> const container = document.createElement('div');
<add> document.body.append(container);
<ide>
<del> return (
<del> <div>
<del> <div id={id}>Child One</div>
<del> {showDiv && <div id={id}>Child Two</div>}
<del> </div>
<del> );
<del> }
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> root.render(<App />);
<add> Scheduler.unstable_flushAll();
<add> jest.runAllTimers();
<ide>
<del> const container = document.createElement('div');
<del> document.body.append(container);
<add> expect(container.children[0].children.length).toEqual(1);
<add> const oldServerId = container.children[0].children[0].getAttribute('id');
<add> expect(oldServerId).not.toBeNull();
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<del> root.render(<App />);
<del> Scheduler.unstable_flushAll();
<del> jest.runAllTimers();
<add> await ReactTestUtils.act(async () => {
<add> _setShowDiv(true);
<add> });
<add> expect(container.children[0].children.length).toEqual(2);
<add> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<add> container.children[0].children[1].getAttribute('id'),
<add> );
<add> expect(container.children[0].children[0].getAttribute('id')).not.toEqual(
<add> oldServerId,
<add> );
<add> expect(
<add> container.children[0].children[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> expect(container.children[0].children.length).toEqual(1);
<del> const oldServerId = container.children[0].children[0].getAttribute(
<del> 'id',
<del> );
<del> expect(oldServerId).not.toBeNull();
<add> // @gate experimental
<add> it('useOpaqueIdentifier: IDs match when, after hydration, a new component that uses the ID is rendered for legacy', async () => {
<add> let _setShowDiv;
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> const [showDiv, setShowDiv] = useState(false);
<add> _setShowDiv = setShowDiv;
<ide>
<del> await ReactTestUtils.act(async () => {
<del> _setShowDiv(true);
<del> });
<del> expect(container.children[0].children.length).toEqual(2);
<del> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<del> container.children[0].children[1].getAttribute('id'),
<add> return (
<add> <div>
<add> <div id={id}>Child One</div>
<add> {showDiv && <div id={id}>Child Two</div>}
<add> </div>
<ide> );
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toEqual(oldServerId);
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toBeNull();
<del> });
<add> }
<ide>
<del> it('useOpaqueIdentifier: IDs match when, after hydration, a new component that uses the ID is rendered for legacy', async () => {
<del> let _setShowDiv;
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> const [showDiv, setShowDiv] = useState(false);
<del> _setShowDiv = setShowDiv;
<add> const container = document.createElement('div');
<add> document.body.append(container);
<ide>
<del> return (
<del> <div>
<del> <div id={id}>Child One</div>
<del> {showDiv && <div id={id}>Child Two</div>}
<del> </div>
<del> );
<del> }
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> ReactDOM.hydrate(<App />, container);
<ide>
<del> const container = document.createElement('div');
<del> document.body.append(container);
<add> expect(container.children[0].children.length).toEqual(1);
<add> const oldServerId = container.children[0].children[0].getAttribute('id');
<add> expect(oldServerId).not.toBeNull();
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> ReactDOM.hydrate(<App />, container);
<add> await ReactTestUtils.act(async () => {
<add> _setShowDiv(true);
<add> });
<add> expect(container.children[0].children.length).toEqual(2);
<add> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<add> container.children[0].children[1].getAttribute('id'),
<add> );
<add> expect(container.children[0].children[0].getAttribute('id')).not.toEqual(
<add> oldServerId,
<add> );
<add> expect(
<add> container.children[0].children[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> expect(container.children[0].children.length).toEqual(1);
<del> const oldServerId = container.children[0].children[0].getAttribute(
<del> 'id',
<add> // @gate experimental
<add> it('useOpaqueIdentifier: ID is not used during hydration but is used in an update', async () => {
<add> let _setShow;
<add> function App({unused}) {
<add> Scheduler.unstable_yieldValue('App');
<add> const id = useOpaqueIdentifier();
<add> const [show, setShow] = useState(false);
<add> _setShow = setShow;
<add> return (
<add> <div>
<add> <span id={show ? id : null}>{'Child One'}</span>
<add> </div>
<ide> );
<del> expect(oldServerId).not.toBeNull();
<add> }
<ide>
<del> await ReactTestUtils.act(async () => {
<del> _setShowDiv(true);
<del> });
<del> expect(container.children[0].children.length).toEqual(2);
<del> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<del> container.children[0].children[1].getAttribute('id'),
<del> );
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toEqual(oldServerId);
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toBeNull();
<add> const container = document.createElement('div');
<add> document.body.append(container);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> ReactTestUtils.act(() => {
<add> root.render(<App />);
<ide> });
<del>
<del> it('useOpaqueIdentifier: ID is not used during hydration but is used in an update', async () => {
<del> let _setShow;
<del> function App({unused}) {
<del> Scheduler.unstable_yieldValue('App');
<del> const id = useOpaqueIdentifier();
<del> const [show, setShow] = useState(false);
<del> _setShow = setShow;
<del> return (
<del> <div>
<del> <span id={show ? id : null}>{'Child One'}</span>
<del> </div>
<del> );
<del> }
<del>
<del> const container = document.createElement('div');
<del> document.body.append(container);
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<del> ReactTestUtils.act(() => {
<del> root.render(<App />);
<del> });
<del> expect(Scheduler).toHaveYielded(['App', 'App']);
<del> // The ID goes from not being used to being added to the page
<del> ReactTestUtils.act(() => {
<del> _setShow(true);
<del> });
<del> expect(Scheduler).toHaveYielded(['App', 'App']);
<del> expect(
<del> container.getElementsByTagName('span')[0].getAttribute('id'),
<del> ).not.toBeNull();
<add> expect(Scheduler).toHaveYielded(['App', 'App']);
<add> // The ID goes from not being used to being added to the page
<add> ReactTestUtils.act(() => {
<add> _setShow(true);
<ide> });
<add> expect(Scheduler).toHaveYielded(['App', 'App']);
<add> expect(
<add> container.getElementsByTagName('span')[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> it('useOpaqueIdentifier: ID is not used during hydration but is used in an update in legacy', async () => {
<del> let _setShow;
<del> function App({unused}) {
<del> Scheduler.unstable_yieldValue('App');
<del> const id = useOpaqueIdentifier();
<del> const [show, setShow] = useState(false);
<del> _setShow = setShow;
<del> return (
<del> <div>
<del> <span id={show ? id : null}>{'Child One'}</span>
<del> </div>
<del> );
<del> }
<add> // @gate experimental
<add> it('useOpaqueIdentifier: ID is not used during hydration but is used in an update in legacy', async () => {
<add> let _setShow;
<add> function App({unused}) {
<add> Scheduler.unstable_yieldValue('App');
<add> const id = useOpaqueIdentifier();
<add> const [show, setShow] = useState(false);
<add> _setShow = setShow;
<add> return (
<add> <div>
<add> <span id={show ? id : null}>{'Child One'}</span>
<add> </div>
<add> );
<add> }
<ide>
<del> const container = document.createElement('div');
<del> document.body.append(container);
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> ReactDOM.hydrate(<App />, container);
<del> expect(Scheduler).toHaveYielded(['App', 'App']);
<del> // The ID goes from not being used to being added to the page
<del> ReactTestUtils.act(() => {
<del> _setShow(true);
<del> });
<del> expect(Scheduler).toHaveYielded(['App']);
<del> expect(
<del> container.getElementsByTagName('span')[0].getAttribute('id'),
<del> ).not.toBeNull();
<add> const container = document.createElement('div');
<add> document.body.append(container);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> ReactDOM.hydrate(<App />, container);
<add> expect(Scheduler).toHaveYielded(['App', 'App']);
<add> // The ID goes from not being used to being added to the page
<add> ReactTestUtils.act(() => {
<add> _setShow(true);
<ide> });
<add> expect(Scheduler).toHaveYielded(['App']);
<add> expect(
<add> container.getElementsByTagName('span')[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> it('useOpaqueIdentifier: flushSync', async () => {
<del> let _setShow;
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> const [show, setShow] = useState(false);
<del> _setShow = setShow;
<del> return (
<del> <div>
<del> <span id={show ? id : null}>{'Child One'}</span>
<del> </div>
<del> );
<del> }
<add> // @gate experimental
<add> it('useOpaqueIdentifier: flushSync', async () => {
<add> let _setShow;
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> const [show, setShow] = useState(false);
<add> _setShow = setShow;
<add> return (
<add> <div>
<add> <span id={show ? id : null}>{'Child One'}</span>
<add> </div>
<add> );
<add> }
<ide>
<del> const container = document.createElement('div');
<del> document.body.append(container);
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<del> ReactTestUtils.act(() => {
<del> root.render(<App />);
<del> });
<add> const container = document.createElement('div');
<add> document.body.append(container);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> ReactTestUtils.act(() => {
<add> root.render(<App />);
<add> });
<ide>
<del> // The ID goes from not being used to being added to the page
<del> ReactTestUtils.act(() => {
<del> ReactDOM.flushSync(() => {
<del> _setShow(true);
<del> });
<add> // The ID goes from not being used to being added to the page
<add> ReactTestUtils.act(() => {
<add> ReactDOM.flushSync(() => {
<add> _setShow(true);
<ide> });
<del> expect(
<del> container.getElementsByTagName('span')[0].getAttribute('id'),
<del> ).not.toBeNull();
<ide> });
<add> expect(
<add> container.getElementsByTagName('span')[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> it('useOpaqueIdentifier: children with id hydrates before other children if ID updates', async () => {
<del> let _setShow;
<del>
<del> const child1Ref = React.createRef();
<del> const childWithIDRef = React.createRef();
<del> const setShowRef = React.createRef();
<add> // @gate experimental
<add> it('useOpaqueIdentifier: children with id hydrates before other children if ID updates', async () => {
<add> let _setShow;
<ide>
<del> // RENAME THESE
<del> function Child1() {
<del> Scheduler.unstable_yieldValue('Child One');
<del> return <span ref={child1Ref}>{'Child One'}</span>;
<del> }
<add> const child1Ref = React.createRef();
<add> const childWithIDRef = React.createRef();
<add> const setShowRef = React.createRef();
<ide>
<del> function Child2() {
<del> Scheduler.unstable_yieldValue('Child Two');
<del> return <span>{'Child Two'}</span>;
<del> }
<add> // RENAME THESE
<add> function Child1() {
<add> Scheduler.unstable_yieldValue('Child One');
<add> return <span ref={child1Ref}>{'Child One'}</span>;
<add> }
<ide>
<del> const Children = React.memo(function Children() {
<del> return (
<del> <React.Suspense fallback="Loading 1...">
<del> <Child1 />
<del> <Child2 />
<del> </React.Suspense>
<del> );
<del> });
<add> function Child2() {
<add> Scheduler.unstable_yieldValue('Child Two');
<add> return <span>{'Child Two'}</span>;
<add> }
<ide>
<del> function ChildWithID({parentID}) {
<del> Scheduler.unstable_yieldValue('Child with ID');
<del> return (
<del> <span id={parentID} ref={childWithIDRef}>
<del> {'Child with ID'}
<del> </span>
<del> );
<del> }
<add> const Children = React.memo(function Children() {
<add> return (
<add> <React.Suspense fallback="Loading 1...">
<add> <Child1 />
<add> <Child2 />
<add> </React.Suspense>
<add> );
<add> });
<ide>
<del> const ChildrenWithID = React.memo(function ChildrenWithID({parentID}) {
<del> return (
<del> <React.Suspense fallback="Loading 2...">
<del> <ChildWithID parentID={parentID} />
<del> </React.Suspense>
<del> );
<del> });
<add> function ChildWithID({parentID}) {
<add> Scheduler.unstable_yieldValue('Child with ID');
<add> return (
<add> <span id={parentID} ref={childWithIDRef}>
<add> {'Child with ID'}
<add> </span>
<add> );
<add> }
<ide>
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> const [show, setShow] = useState(false);
<del> _setShow = setShow;
<del> return (
<del> <div>
<del> <Children />
<del> <ChildrenWithID parentID={id} />
<del> {show && (
<del> <span aria-labelledby={id} ref={setShowRef}>
<del> {'Child Three'}
<del> </span>
<del> )}
<del> </div>
<del> );
<del> }
<add> const ChildrenWithID = React.memo(function ChildrenWithID({parentID}) {
<add> return (
<add> <React.Suspense fallback="Loading 2...">
<add> <ChildWithID parentID={parentID} />
<add> </React.Suspense>
<add> );
<add> });
<ide>
<del> const container = document.createElement('div');
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> expect(Scheduler).toHaveYielded([
<del> 'Child One',
<del> 'Child Two',
<del> 'Child with ID',
<del> ]);
<del> expect(container.textContent).toEqual(
<del> 'Child OneChild TwoChild with ID',
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> const [show, setShow] = useState(false);
<add> _setShow = setShow;
<add> return (
<add> <div>
<add> <Children />
<add> <ChildrenWithID parentID={id} />
<add> {show && (
<add> <span aria-labelledby={id} ref={setShowRef}>
<add> {'Child Three'}
<add> </span>
<add> )}
<add> </div>
<ide> );
<add> }
<ide>
<del> const serverId = container
<del> .getElementsByTagName('span')[2]
<del> .getAttribute('id');
<del> expect(serverId).not.toBeNull();
<add> const container = document.createElement('div');
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> expect(Scheduler).toHaveYielded([
<add> 'Child One',
<add> 'Child Two',
<add> 'Child with ID',
<add> ]);
<add> expect(container.textContent).toEqual('Child OneChild TwoChild with ID');
<ide>
<del> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<del> root.render(<App show={false} />);
<del> expect(Scheduler).toHaveYielded([]);
<add> const serverId = container
<add> .getElementsByTagName('span')[2]
<add> .getAttribute('id');
<add> expect(serverId).not.toBeNull();
<ide>
<del> //Hydrate just child one before updating state
<del> expect(Scheduler).toFlushAndYieldThrough(['Child One']);
<del> expect(child1Ref.current).toBe(null);
<del> expect(Scheduler).toHaveYielded([]);
<add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> root.render(<App show={false} />);
<add> expect(Scheduler).toHaveYielded([]);
<ide>
<del> ReactTestUtils.act(() => {
<del> _setShow(true);
<add> //Hydrate just child one before updating state
<add> expect(Scheduler).toFlushAndYieldThrough(['Child One']);
<add> expect(child1Ref.current).toBe(null);
<add> expect(Scheduler).toHaveYielded([]);
<ide>
<del> // State update should trigger the ID to update, which changes the props
<del> // of ChildWithID. This should cause ChildWithID to hydrate before Children
<del>
<del> expect(Scheduler).toFlushAndYieldThrough([
<del> 'Child with ID',
<del> // Fallbacks are immediately committed in TestUtils version
<del> // of act
<del> // 'Child with ID',
<del> // 'Child with ID',
<del> 'Child One',
<del> 'Child Two',
<del> ]);
<del>
<del> expect(child1Ref.current).toBe(null);
<del> expect(childWithIDRef.current).toEqual(
<del> container.getElementsByTagName('span')[2],
<del> );
<add> ReactTestUtils.act(() => {
<add> _setShow(true);
<ide>
<del> expect(setShowRef.current).toEqual(
<del> container.getElementsByTagName('span')[3],
<del> );
<add> // State update should trigger the ID to update, which changes the props
<add> // of ChildWithID. This should cause ChildWithID to hydrate before Children
<ide>
<del> expect(childWithIDRef.current.getAttribute('id')).toEqual(
<del> setShowRef.current.getAttribute('aria-labelledby'),
<del> );
<del> expect(childWithIDRef.current.getAttribute('id')).not.toEqual(
<del> serverId,
<del> );
<del> });
<add> expect(Scheduler).toFlushAndYieldThrough([
<add> 'Child with ID',
<add> // Fallbacks are immediately committed in TestUtils version
<add> // of act
<add> // 'Child with ID',
<add> // 'Child with ID',
<add> 'Child One',
<add> 'Child Two',
<add> ]);
<ide>
<del> // Children hydrates after ChildWithID
<del> expect(child1Ref.current).toBe(
<del> container.getElementsByTagName('span')[0],
<add> expect(child1Ref.current).toBe(null);
<add> expect(childWithIDRef.current).toEqual(
<add> container.getElementsByTagName('span')[2],
<ide> );
<ide>
<del> Scheduler.unstable_flushAll();
<del>
<del> expect(Scheduler).toHaveYielded([]);
<del> });
<add> expect(setShowRef.current).toEqual(
<add> container.getElementsByTagName('span')[3],
<add> );
<ide>
<del> it('useOpaqueIdentifier: IDs match when part of the DOM tree is server rendered and part is client rendered', async () => {
<del> let suspend = true;
<del> let resolve;
<del> const promise = new Promise(
<del> resolvePromise => (resolve = resolvePromise),
<add> expect(childWithIDRef.current.getAttribute('id')).toEqual(
<add> setShowRef.current.getAttribute('aria-labelledby'),
<ide> );
<add> expect(childWithIDRef.current.getAttribute('id')).not.toEqual(serverId);
<add> });
<ide>
<del> function Child({text}) {
<del> if (suspend) {
<del> throw promise;
<del> } else {
<del> return text;
<del> }
<del> }
<add> // Children hydrates after ChildWithID
<add> expect(child1Ref.current).toBe(container.getElementsByTagName('span')[0]);
<ide>
<del> function RenderedChild() {
<del> useEffect(() => {
<del> Scheduler.unstable_yieldValue('Child did commit');
<del> });
<del> return null;
<del> }
<add> Scheduler.unstable_flushAll();
<ide>
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> useEffect(() => {
<del> Scheduler.unstable_yieldValue('Did commit');
<del> });
<del> return (
<del> <div>
<del> <div id={id}>Child One</div>
<del> <RenderedChild />
<del> <React.Suspense fallback={'Fallback'}>
<del> <div id={id}>
<del> <Child text="Child Two" />
<del> </div>
<del> </React.Suspense>
<del> </div>
<del> );
<del> }
<add> expect(Scheduler).toHaveYielded([]);
<add> });
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> // @gate experimental
<add> it('useOpaqueIdentifier: IDs match when part of the DOM tree is server rendered and part is client rendered', async () => {
<add> let suspend = true;
<add> let resolve;
<add> const promise = new Promise(resolvePromise => (resolve = resolvePromise));
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> function Child({text}) {
<add> if (suspend) {
<add> throw promise;
<add> } else {
<add> return text;
<add> }
<add> }
<ide>
<del> suspend = true;
<del> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<del> await ReactTestUtils.act(async () => {
<del> root.render(<App />);
<del> });
<del> jest.runAllTimers();
<del> expect(Scheduler).toHaveYielded(['Child did commit', 'Did commit']);
<del> expect(Scheduler).toFlushAndYield([]);
<del>
<del> const serverId = container.children[0].children[0].getAttribute('id');
<del> expect(container.children[0].children.length).toEqual(1);
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toBeNull();
<del>
<del> await ReactTestUtils.act(async () => {
<del> suspend = false;
<del> resolve();
<del> await promise;
<add> function RenderedChild() {
<add> useEffect(() => {
<add> Scheduler.unstable_yieldValue('Child did commit');
<ide> });
<add> return null;
<add> }
<ide>
<del> expect(Scheduler).toHaveYielded(['Child did commit', 'Did commit']);
<del> expect(Scheduler).toFlushAndYield([]);
<del> jest.runAllTimers();
<del>
<del> expect(container.children[0].children.length).toEqual(2);
<del> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<del> container.children[0].children[1].getAttribute('id'),
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> useEffect(() => {
<add> Scheduler.unstable_yieldValue('Did commit');
<add> });
<add> return (
<add> <div>
<add> <div id={id}>Child One</div>
<add> <RenderedChild />
<add> <React.Suspense fallback={'Fallback'}>
<add> <div id={id}>
<add> <Child text="Child Two" />
<add> </div>
<add> </React.Suspense>
<add> </div>
<ide> );
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toEqual(serverId);
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toBeNull();
<del> });
<add> }
<ide>
<del> it('useOpaqueIdentifier warn when there is a hydration error', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={appId} />;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return <Child appId={id} />;
<del> }
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<ide>
<del> // This is the wrong HTML string
<del> container.innerHTML = '<span></span>';
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<del> 'Warning: Expected server HTML to contain a matching <div> in <div>.',
<del> ]);
<add> suspend = true;
<add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> await ReactTestUtils.act(async () => {
<add> root.render(<App />);
<ide> });
<add> jest.runAllTimers();
<add> expect(Scheduler).toHaveYielded(['Child did commit', 'Did commit']);
<add> expect(Scheduler).toFlushAndYield([]);
<ide>
<del> it('useOpaqueIdentifier: IDs match when part of the DOM tree is server rendered and part is client rendered', async () => {
<del> let suspend = true;
<add> const serverId = container.children[0].children[0].getAttribute('id');
<add> expect(container.children[0].children.length).toEqual(1);
<add> expect(
<add> container.children[0].children[0].getAttribute('id'),
<add> ).not.toBeNull();
<ide>
<del> function Child({text}) {
<del> if (suspend) {
<del> throw new Promise(() => {});
<del> } else {
<del> return text;
<del> }
<del> }
<add> await ReactTestUtils.act(async () => {
<add> suspend = false;
<add> resolve();
<add> await promise;
<add> });
<ide>
<del> function RenderedChild() {
<del> useEffect(() => {
<del> Scheduler.unstable_yieldValue('Child did commit');
<del> });
<del> return null;
<del> }
<add> expect(Scheduler).toHaveYielded(['Child did commit', 'Did commit']);
<add> expect(Scheduler).toFlushAndYield([]);
<add> jest.runAllTimers();
<ide>
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> useEffect(() => {
<del> Scheduler.unstable_yieldValue('Did commit');
<del> });
<del> return (
<del> <div>
<del> <div id={id}>Child One</div>
<del> <RenderedChild />
<del> <React.Suspense fallback={'Fallback'}>
<del> <div id={id}>
<del> <Child text="Child Two" />
<del> </div>
<del> </React.Suspense>
<del> </div>
<del> );
<del> }
<add> expect(container.children[0].children.length).toEqual(2);
<add> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<add> container.children[0].children[1].getAttribute('id'),
<add> );
<add> expect(container.children[0].children[0].getAttribute('id')).not.toEqual(
<add> serverId,
<add> );
<add> expect(
<add> container.children[0].children[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> // @gate experimental
<add> it('useOpaqueIdentifier warn when there is a hydration error', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={appId} />;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return <Child appId={id} />;
<add> }
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> suspend = false;
<del> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<del> await ReactTestUtils.act(async () => {
<del> root.render(<App />);
<del> });
<del> jest.runAllTimers();
<del> expect(Scheduler).toHaveYielded([
<del> 'Child did commit',
<del> 'Did commit',
<del> 'Child did commit',
<del> 'Did commit',
<del> ]);
<del> expect(Scheduler).toFlushAndYield([]);
<add> // This is the wrong HTML string
<add> container.innerHTML = '<span></span>';
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<add> 'Warning: Expected server HTML to contain a matching <div> in <div>.',
<add> ]);
<add> });
<ide>
<del> expect(container.children[0].children.length).toEqual(2);
<del> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<del> container.children[0].children[1].getAttribute('id'),
<del> );
<del> expect(
<del> container.children[0].children[0].getAttribute('id'),
<del> ).not.toBeNull();
<del> });
<add> // @gate experimental
<add> it('useOpaqueIdentifier: IDs match when part of the DOM tree is server rendered and part is client rendered', async () => {
<add> let suspend = true;
<ide>
<del> it('useOpaqueIdentifier warn when there is a hydration error', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={appId} />;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return <Child appId={id} />;
<add> function Child({text}) {
<add> if (suspend) {
<add> throw new Promise(() => {});
<add> } else {
<add> return text;
<ide> }
<add> }
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> function RenderedChild() {
<add> useEffect(() => {
<add> Scheduler.unstable_yieldValue('Child did commit');
<add> });
<add> return null;
<add> }
<ide>
<del> // This is the wrong HTML string
<del> container.innerHTML = '<span></span>';
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> useEffect(() => {
<add> Scheduler.unstable_yieldValue('Did commit');
<add> });
<add> return (
<add> <div>
<add> <div id={id}>Child One</div>
<add> <RenderedChild />
<add> <React.Suspense fallback={'Fallback'}>
<add> <div id={id}>
<add> <Child text="Child Two" />
<add> </div>
<add> </React.Suspense>
<add> </div>
<ide> );
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<del> 'Warning: Expected server HTML to contain a matching <div> in <div>.',
<del> ]);
<del> });
<add> }
<ide>
<del> it('useOpaqueIdentifier warns when there is a hydration error and we are using ID as a string', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={appId + ''} />;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return <Child appId={id} />;
<del> }
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<ide>
<del> // This is the wrong HTML string
<del> container.innerHTML = '<span></span>';
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<del> [
<del> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<del> 'Warning: Did not expect server HTML to contain a <span> in <div>.',
<del> ],
<del> {withoutStack: 1},
<del> );
<add> suspend = false;
<add> const root = ReactDOM.unstable_createRoot(container, {hydrate: true});
<add> await ReactTestUtils.act(async () => {
<add> root.render(<App />);
<ide> });
<add> jest.runAllTimers();
<add> expect(Scheduler).toHaveYielded([
<add> 'Child did commit',
<add> 'Did commit',
<add> 'Child did commit',
<add> 'Did commit',
<add> ]);
<add> expect(Scheduler).toFlushAndYield([]);
<ide>
<del> it('useOpaqueIdentifier warns when there is a hydration error and we are using ID as a string', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={appId + ''} />;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return <Child appId={id} />;
<del> }
<add> expect(container.children[0].children.length).toEqual(2);
<add> expect(container.children[0].children[0].getAttribute('id')).toEqual(
<add> container.children[0].children[1].getAttribute('id'),
<add> );
<add> expect(
<add> container.children[0].children[0].getAttribute('id'),
<add> ).not.toBeNull();
<add> });
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> // @gate experimental
<add> it('useOpaqueIdentifier warn when there is a hydration error', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={appId} />;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return <Child appId={id} />;
<add> }
<ide>
<del> // This is the wrong HTML string
<del> container.innerHTML = '<span></span>';
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<del> [
<del> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<del> 'Warning: Did not expect server HTML to contain a <span> in <div>.',
<del> ],
<del> {withoutStack: 1},
<del> );
<del> });
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> it('useOpaqueIdentifier warns if you try to use the result as a string in a child component', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={appId + ''} />;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return <Child appId={id} />;
<del> }
<add> // This is the wrong HTML string
<add> container.innerHTML = '<span></span>';
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<add> 'Warning: Expected server HTML to contain a matching <div> in <div>.',
<add> ]);
<add> });
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> // @gate experimental
<add> it('useOpaqueIdentifier warns when there is a hydration error and we are using ID as a string', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={appId + ''} />;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return <Child appId={id} />;
<add> }
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<del> [
<del> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<del> 'Warning: Did not expect server HTML to contain a <div> in <div>.',
<del> ],
<del> {withoutStack: 1},
<del> );
<del> });
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add>
<add> // This is the wrong HTML string
<add> container.innerHTML = '<span></span>';
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<add> [
<add> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<add> 'Warning: Did not expect server HTML to contain a <span> in <div>.',
<add> ],
<add> {withoutStack: 1},
<add> );
<add> });
<ide>
<del> it('useOpaqueIdentifier warns if you try to use the result as a string', async () => {
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return <div aria-labelledby={id + ''} />;
<del> }
<add> // @gate experimental
<add> it('useOpaqueIdentifier warns when there is a hydration error and we are using ID as a string', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={appId + ''} />;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return <Child appId={id} />;
<add> }
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add>
<add> // This is the wrong HTML string
<add> container.innerHTML = '<span></span>';
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<add> [
<add> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<add> 'Warning: Did not expect server HTML to contain a <span> in <div>.',
<add> ],
<add> {withoutStack: 1},
<add> );
<add> });
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<del> [
<del> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<del> 'Warning: Did not expect server HTML to contain a <div> in <div>.',
<del> ],
<del> {withoutStack: 1},
<del> );
<del> });
<add> // @gate experimental
<add> it('useOpaqueIdentifier warns if you try to use the result as a string in a child component', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={appId + ''} />;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return <Child appId={id} />;
<add> }
<ide>
<del> it('useOpaqueIdentifier warns if you try to use the result as a string in a child component wrapped in a Suspense', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={appId + ''} />;
<del> }
<del> function App() {
<del> const id = useOpaqueIdentifier();
<del> return (
<del> <React.Suspense fallback={null}>
<del> <Child appId={id} />
<del> </React.Suspense>
<del> );
<del> }
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add>
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<add> [
<add> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<add> 'Warning: Did not expect server HTML to contain a <div> in <div>.',
<add> ],
<add> {withoutStack: 1},
<add> );
<add> });
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> // @gate experimental
<add> it('useOpaqueIdentifier warns if you try to use the result as a string', async () => {
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return <div aria-labelledby={id + ''} />;
<add> }
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add>
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev(
<add> [
<add> 'Warning: The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. Do not read the value directly.',
<add> 'Warning: Did not expect server HTML to contain a <div> in <div>.',
<add> ],
<add> {withoutStack: 1},
<add> );
<add> });
<ide>
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<add> // @gate experimental
<add> it('useOpaqueIdentifier warns if you try to use the result as a string in a child component wrapped in a Suspense', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={appId + ''} />;
<add> }
<add> function App() {
<add> const id = useOpaqueIdentifier();
<add> return (
<add> <React.Suspense fallback={null}>
<add> <Child appId={id} />
<add> </React.Suspense>
<ide> );
<add> }
<ide>
<del> if (gate(flags => flags.deferRenderPhaseUpdateToNextBatch)) {
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<del> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<del> 'Do not read the value directly.',
<del> ]);
<del> } else {
<del> // This error isn't surfaced to the user; only the warning is.
<del> // The error is just the mechanism that restarts the render.
<del> expect(() =>
<del> expect(() => Scheduler.unstable_flushAll()).toThrow(
<del> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<del> 'Do not read the value directly.',
<del> ),
<del> ).toErrorDev([
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<add>
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add>
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add>
<add> if (gate(flags => flags.deferRenderPhaseUpdateToNextBatch)) {
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<add> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<add> 'Do not read the value directly.',
<add> ]);
<add> } else {
<add> // This error isn't surfaced to the user; only the warning is.
<add> // The error is just the mechanism that restarts the render.
<add> expect(() =>
<add> expect(() => Scheduler.unstable_flushAll()).toThrow(
<ide> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<ide> 'Do not read the value directly.',
<del> ]);
<del> }
<del> });
<add> ),
<add> ).toErrorDev([
<add> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<add> 'Do not read the value directly.',
<add> ]);
<add> }
<add> });
<ide>
<del> it('useOpaqueIdentifier warns if you try to add the result as a number in a child component wrapped in a Suspense', async () => {
<del> function Child({appId}) {
<del> return <div aria-labelledby={+appId} />;
<del> }
<del> function App() {
<del> const [show] = useState(false);
<del> const id = useOpaqueIdentifier();
<del> return (
<del> <React.Suspense fallback={null}>
<del> {show && <div id={id} />}
<del> <Child appId={id} />
<del> </React.Suspense>
<del> );
<del> }
<add> // @gate experimental
<add> it('useOpaqueIdentifier warns if you try to add the result as a number in a child component wrapped in a Suspense', async () => {
<add> function Child({appId}) {
<add> return <div aria-labelledby={+appId} />;
<add> }
<add> function App() {
<add> const [show] = useState(false);
<add> const id = useOpaqueIdentifier();
<add> return (
<add> <React.Suspense fallback={null}>
<add> {show && <div id={id} />}
<add> <Child appId={id} />
<add> </React.Suspense>
<add> );
<add> }
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<ide>
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<ide>
<del> if (gate(flags => flags.deferRenderPhaseUpdateToNextBatch)) {
<del> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<del> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<del> 'Do not read the value directly.',
<del> ]);
<del> } else {
<del> // This error isn't surfaced to the user; only the warning is.
<del> // The error is just the mechanism that restarts the render.
<del> expect(() =>
<del> expect(() => Scheduler.unstable_flushAll()).toThrow(
<del> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<del> 'Do not read the value directly.',
<del> ),
<del> ).toErrorDev([
<add> if (gate(flags => flags.deferRenderPhaseUpdateToNextBatch)) {
<add> expect(() => Scheduler.unstable_flushAll()).toErrorDev([
<add> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<add> 'Do not read the value directly.',
<add> ]);
<add> } else {
<add> // This error isn't surfaced to the user; only the warning is.
<add> // The error is just the mechanism that restarts the render.
<add> expect(() =>
<add> expect(() => Scheduler.unstable_flushAll()).toThrow(
<ide> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<ide> 'Do not read the value directly.',
<del> ]);
<del> }
<del> });
<del>
<del> it('useOpaqueIdentifier with two opaque identifiers on the same page', () => {
<del> let _setShow;
<add> ),
<add> ).toErrorDev([
<add> 'The object passed back from useOpaqueIdentifier is meant to be passed through to attributes only. ' +
<add> 'Do not read the value directly.',
<add> ]);
<add> }
<add> });
<ide>
<del> function App() {
<del> const id1 = useOpaqueIdentifier();
<del> const id2 = useOpaqueIdentifier();
<del> const [show, setShow] = useState(true);
<del> _setShow = setShow;
<add> // @gate experimental
<add> it('useOpaqueIdentifier with two opaque identifiers on the same page', () => {
<add> let _setShow;
<ide>
<del> return (
<del> <div>
<del> <React.Suspense fallback={null}>
<del> {show ? (
<del> <span id={id1}>{'Child'}</span>
<del> ) : (
<del> <span id={id2}>{'Child'}</span>
<del> )}
<del> </React.Suspense>
<del> <span aria-labelledby={id1}>{'test'}</span>
<del> </div>
<del> );
<del> }
<add> function App() {
<add> const id1 = useOpaqueIdentifier();
<add> const id2 = useOpaqueIdentifier();
<add> const [show, setShow] = useState(true);
<add> _setShow = setShow;
<ide>
<del> const container = document.createElement('div');
<del> document.body.appendChild(container);
<add> return (
<add> <div>
<add> <React.Suspense fallback={null}>
<add> {show ? (
<add> <span id={id1}>{'Child'}</span>
<add> ) : (
<add> <span id={id2}>{'Child'}</span>
<add> )}
<add> </React.Suspense>
<add> <span aria-labelledby={id1}>{'test'}</span>
<add> </div>
<add> );
<add> }
<ide>
<del> container.innerHTML = ReactDOMServer.renderToString(<App />);
<add> const container = document.createElement('div');
<add> document.body.appendChild(container);
<ide>
<del> const serverID = container
<del> .getElementsByTagName('span')[0]
<del> .getAttribute('id');
<del> expect(serverID).not.toBeNull();
<del> expect(
<del> container
<del> .getElementsByTagName('span')[1]
<del> .getAttribute('aria-labelledby'),
<del> ).toEqual(serverID);
<add> container.innerHTML = ReactDOMServer.renderToString(<App />);
<ide>
<del> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(
<del> <App />,
<del> );
<del> jest.runAllTimers();
<del> expect(Scheduler).toHaveYielded([]);
<del> expect(Scheduler).toFlushAndYield([]);
<add> const serverID = container
<add> .getElementsByTagName('span')[0]
<add> .getAttribute('id');
<add> expect(serverID).not.toBeNull();
<add> expect(
<add> container
<add> .getElementsByTagName('span')[1]
<add> .getAttribute('aria-labelledby'),
<add> ).toEqual(serverID);
<ide>
<del> ReactTestUtils.act(() => {
<del> _setShow(false);
<del> });
<add> ReactDOM.unstable_createRoot(container, {hydrate: true}).render(<App />);
<add> jest.runAllTimers();
<add> expect(Scheduler).toHaveYielded([]);
<add> expect(Scheduler).toFlushAndYield([]);
<ide>
<del> expect(
<del> container
<del> .getElementsByTagName('span')[1]
<del> .getAttribute('aria-labelledby'),
<del> ).toEqual(serverID);
<del> expect(
<del> container.getElementsByTagName('span')[0].getAttribute('id'),
<del> ).not.toEqual(serverID);
<del> expect(
<del> container.getElementsByTagName('span')[0].getAttribute('id'),
<del> ).not.toBeNull();
<add> ReactTestUtils.act(() => {
<add> _setShow(false);
<ide> });
<add>
<add> expect(
<add> container
<add> .getElementsByTagName('span')[1]
<add> .getAttribute('aria-labelledby'),
<add> ).toEqual(serverID);
<add> expect(
<add> container.getElementsByTagName('span')[0].getAttribute('id'),
<add> ).not.toEqual(serverID);
<add> expect(
<add> container.getElementsByTagName('span')[0].getAttribute('id'),
<add> ).not.toBeNull();
<ide> });
<del> }
<add> });
<ide> });
<ide><path>packages/react-dom/src/__tests__/utils/ReactDOMServerIntegrationTestUtils.js
<ide> module.exports = function(initModules) {
<ide> async function renderIntoStream(reactElement, errorCount = 0) {
<ide> return await expectErrors(
<ide> () =>
<del> new Promise(resolve => {
<add> new Promise((resolve, reject) => {
<ide> const writable = new DrainWritable();
<del> ReactDOMServer.renderToNodeStream(reactElement).pipe(writable);
<add> const s = ReactDOMServer.renderToNodeStream(reactElement);
<add> s.on('error', e => reject(e));
<add> s.pipe(writable);
<ide> writable.on('finish', () => resolve(writable.buffer));
<ide> }),
<ide> errorCount,
| 2
|
PHP
|
PHP
|
apply fixes from styleci
|
fffc0729425278165d29a0b9f1d98aeb43e71057
|
<ide><path>src/Illuminate/Foundation/Console/ModelMakeCommand.php
<ide> protected function getOptions()
<ide> ['migration', 'm', InputOption::VALUE_NONE, 'Create a new migration file for the model.'],
<ide>
<ide> ['pivot', 'p', InputOption::VALUE_NONE, 'Indicates if the generated model should be a custom intermediate table model.'],
<del>
<add>
<ide> ['resource', 'r', InputOption::VALUE_NONE, 'Indicates if the generated controller should be a resource controller.'],
<ide> ];
<ide> }
| 1
|
PHP
|
PHP
|
change argument order
|
520544dc24772b421410a2528ba01fd47818eeea
|
<ide><path>src/Illuminate/View/Compilers/BladeCompiler.php
<ide> protected function compileComponentTags($value)
<ide> }
<ide>
<ide> return (new ComponentTagCompiler(
<del> $this, $this->classComponentAliases
<add> $this->classComponentAliases, $this
<ide> ))->compile($value);
<ide> }
<ide>
<ide><path>src/Illuminate/View/Compilers/ComponentTagCompiler.php
<ide> use Illuminate\Container\Container;
<ide> use Illuminate\Contracts\Foundation\Application;
<ide> use Illuminate\Contracts\View\Factory;
<add>use Illuminate\Filesystem\Filesystem;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\View\AnonymousComponent;
<ide> use InvalidArgumentException;
<ide> class ComponentTagCompiler
<ide> * Create new component tag compiler.
<ide> *
<ide> * @param array $aliases
<add> * @param \Illuminate\View\Compilers\BladeCompiler|null
<ide> * @return void
<ide> */
<del> public function __construct(BladeCompiler $blade, array $aliases = [])
<add> public function __construct(array $aliases = [], ?BladeCompiler $blade = null)
<ide> {
<del> $this->blade = $blade;
<ide> $this->aliases = $aliases;
<add>
<add> $this->blade = $blade ?: new BladeCompiler(new Filesystem, sys_get_temp_dir());
<ide> }
<ide>
<ide> /**
<ide><path>tests/View/Blade/BladeComponentTagCompilerTest.php
<ide> protected function mockViewFactory($existsSucceeds = true)
<ide> protected function compiler($aliases = [])
<ide> {
<ide> return new ComponentTagCompiler(
<del> new BladeCompiler(new Filesystem, __DIR__),
<del> $aliases
<add> $aliases,
<add> new BladeCompiler(new Filesystem, __DIR__)
<ide> );
<ide> }
<ide> }
| 3
|
Text
|
Text
|
add 4.13.4 changelog
|
51ebccc37482f84e41417ef2917b0e4e44cc7465
|
<ide><path>packages/react-devtools/CHANGELOG.md
<ide> ## 4.13.4 (May 20, 2021)
<ide> #### Bugfix
<ide> * Fix edge-case Fast Refresh bug that caused Fibers with warnings/errors to be untracked prematurely (which broke componentinspection in DevTools) ([bvaughn](https://github.com/bvaughn) in [#21536](https://github.com/facebook/react/pull/21536))
<add>* Revert force deep re-mount when Fast Refresh detected (was no longer necessary) ([bvaughn](https://github.com/bvaughn) in [#21539](https://github.com/facebook/react/pull/21539))
<ide>
<ide> ## 4.13.3 (May 19, 2021)
<ide> #### Misc
| 1
|
Javascript
|
Javascript
|
use the $jsonpcallbacks service
|
78e1ba1ef90c851204cfa816125bbd5b908468e3
|
<ide><path>src/ng/http.js
<ide> function $HttpProvider() {
<ide> *
<ide> * @description
<ide> * Shortcut method to perform `JSONP` request.
<add> * If you would like to customise where and how the callbacks are stored then try overriding
<add> * or decorating the {@link jsonpCallbacks} service.
<ide> *
<ide> * @param {string} url Relative or absolute URL specifying the destination of the request.
<ide> * The name of the callback should be the string `JSON_CALLBACK`.
<ide><path>src/ng/httpBackend.js
<ide> function $xhrFactoryProvider() {
<ide> /**
<ide> * @ngdoc service
<ide> * @name $httpBackend
<del> * @requires $window
<add> * @requires $jsonpCallbacks
<ide> * @requires $document
<ide> * @requires $xhrFactory
<ide> *
<ide> function $xhrFactoryProvider() {
<ide> * $httpBackend} which can be trained with responses.
<ide> */
<ide> function $HttpBackendProvider() {
<del> this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
<del> return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
<add> this.$get = ['$browser', '$jsonpCallbacks', '$document', '$xhrFactory', function($browser, $jsonpCallbacks, $document, $xhrFactory) {
<add> return createHttpBackend($browser, $xhrFactory, $browser.defer, $jsonpCallbacks, $document[0]);
<ide> }];
<ide> }
<ide>
<ide> function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc
<ide> url = url || $browser.url();
<ide>
<ide> if (lowercase(method) === 'jsonp') {
<del> var callbackId = '_' + (callbacks.counter++).toString(36);
<del> callbacks[callbackId] = function(data) {
<del> callbacks[callbackId].data = data;
<del> callbacks[callbackId].called = true;
<del> };
<del>
<del> var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
<del> callbackId, function(status, text) {
<del> completeRequest(callback, status, callbacks[callbackId].data, "", text);
<del> callbacks[callbackId] = noop;
<add> var callbackPath = callbacks.createCallback(url);
<add> var jsonpDone = jsonpReq(url, callbackPath, function(status, text) {
<add> // jsonpReq only ever sets status to 200 (OK), 404 (ERROR) or -1 (WAITING)
<add> var response = (status === 200) && callbacks.getResponse(callbackPath);
<add> completeRequest(callback, status, response, "", text);
<add> callbacks.removeCallback(callbackPath);
<ide> });
<ide> } else {
<ide>
<ide> function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc
<ide> }
<ide> };
<ide>
<del> function jsonpReq(url, callbackId, done) {
<add> function jsonpReq(url, callbackPath, done) {
<add> url = url.replace('JSON_CALLBACK', callbackPath);
<ide> // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
<ide> // - fetches local scripts via XHR and evals them
<ide> // - adds and immediately removes script elements from the document
<ide> function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDoc
<ide> var text = "unknown";
<ide>
<ide> if (event) {
<del> if (event.type === "load" && !callbacks[callbackId].called) {
<add> if (event.type === "load" && !callbacks.wasCalled(callbackPath)) {
<ide> event = { type: "error" };
<ide> }
<ide> text = event.type;
<ide><path>test/ng/httpBackendSpec.js
<ide>
<ide> describe('$httpBackend', function() {
<ide>
<del> var $backend, $browser, callbacks,
<add> var $backend, $browser, $jsonpCallbacks,
<ide> xhr, fakeDocument, callback;
<ide>
<del>
<ide> beforeEach(inject(function($injector) {
<del> callbacks = {counter: 0};
<add>
<ide> $browser = $injector.get('$browser');
<add>
<ide> fakeDocument = {
<ide> $$scripts: [],
<ide> createElement: jasmine.createSpy('createElement').and.callFake(function() {
<ide> describe('$httpBackend', function() {
<ide> })
<ide> }
<ide> };
<del> $backend = createHttpBackend($browser, createMockXhr, $browser.defer, callbacks, fakeDocument);
<add>
<add> $jsonpCallbacks = {
<add> createCallback: function(url) {
<add> $jsonpCallbacks[url] = function(data) {
<add> $jsonpCallbacks[url].called = true;
<add> $jsonpCallbacks[url].data = data;
<add> };
<add> return url;
<add> },
<add> wasCalled: function(callbackPath) {
<add> return $jsonpCallbacks[callbackPath].called;
<add> },
<add> getResponse: function(callbackPath) {
<add> return $jsonpCallbacks[callbackPath].data;
<add> },
<add> removeCallback: function(callbackPath) {
<add> delete $jsonpCallbacks[callbackPath];
<add> }
<add> };
<add>
<add> $backend = createHttpBackend($browser, createMockXhr, $browser.defer, $jsonpCallbacks, fakeDocument);
<ide> callback = jasmine.createSpy('done');
<ide> }));
<ide>
<ide> describe('$httpBackend', function() {
<ide>
<ide> it('should call $xhrFactory with method and url', function() {
<ide> var mockXhrFactory = jasmine.createSpy('mockXhrFactory').and.callFake(createMockXhr);
<del> $backend = createHttpBackend($browser, mockXhrFactory, $browser.defer, callbacks, fakeDocument);
<add> $backend = createHttpBackend($browser, mockXhrFactory, $browser.defer, $jsonpCallbacks, fakeDocument);
<ide> $backend('GET', '/some-url', 'some-data', noop);
<ide> expect(mockXhrFactory).toHaveBeenCalledWith('GET', '/some-url');
<ide> });
<ide> describe('$httpBackend', function() {
<ide>
<ide> describe('JSONP', function() {
<ide>
<del> var SCRIPT_URL = /([^\?]*)\?cb=angular\.callbacks\.(.*)/;
<add> var SCRIPT_URL = /([^\?]*)\?cb=(.*)/;
<ide>
<ide>
<ide> it('should add script tag for JSONP request', function() {
<ide> describe('$httpBackend', function() {
<ide> url = script.src.match(SCRIPT_URL);
<ide>
<ide> expect(url[1]).toBe('http://example.org/path');
<del> callbacks[url[2]]('some-data');
<add> $jsonpCallbacks[url[2]]('some-data');
<ide> browserTrigger(script, "load");
<ide>
<ide> expect(callback).toHaveBeenCalledOnce();
<ide> });
<ide>
<ide>
<ide> it('should clean up the callback and remove the script', function() {
<add> spyOn($jsonpCallbacks, 'removeCallback').and.callThrough();
<add>
<ide> $backend('JSONP', 'http://example.org/path?cb=JSON_CALLBACK', null, callback);
<ide> expect(fakeDocument.$$scripts.length).toBe(1);
<ide>
<ide>
<ide> var script = fakeDocument.$$scripts.shift(),
<ide> callbackId = script.src.match(SCRIPT_URL)[2];
<ide>
<del> callbacks[callbackId]('some-data');
<add> $jsonpCallbacks[callbackId]('some-data');
<ide> browserTrigger(script, "load");
<ide>
<del> expect(callbacks[callbackId]).toBe(angular.noop);
<add> expect($jsonpCallbacks.removeCallback).toHaveBeenCalledOnceWith(callbackId);
<ide> expect(fakeDocument.body.removeChild).toHaveBeenCalledOnceWith(script);
<ide> });
<ide>
<ide> describe('$httpBackend', function() {
<ide> });
<ide>
<ide>
<del> it('should abort request on timeout and replace callback with noop', function() {
<add> it('should abort request on timeout and remove JSONP callback', function() {
<add> spyOn($jsonpCallbacks, 'removeCallback').and.callThrough();
<add>
<ide> callback.and.callFake(function(status, response) {
<ide> expect(status).toBe(-1);
<ide> });
<ide> describe('$httpBackend', function() {
<ide> expect(fakeDocument.$$scripts.length).toBe(0);
<ide> expect(callback).toHaveBeenCalledOnce();
<ide>
<del> expect(callbacks[callbackId]).toBe(angular.noop);
<add> expect($jsonpCallbacks.removeCallback).toHaveBeenCalledOnceWith(callbackId);
<ide> });
<ide>
<ide>
| 3
|
Python
|
Python
|
remove unused import
|
ca0acc9a2cda57501e13f6e9741c6a92d730ad83
|
<ide><path>research/object_detection/utils/spatial_transform_ops.py
<ide> from __future__ import print_function
<ide>
<ide> import tensorflow.compat.v1 as tf
<del>import numpy as np
<ide>
<ide>
<ide> def _coordinate_vector_1d(start, end, size, align_endpoints):
| 1
|
Python
|
Python
|
write teardowns for openstack tests
|
9be9f9f22c8f7714afc62ba0cb02d13dd044e687
|
<ide><path>libcloud/test/common/test_openstack.py
<ide> import unittest
<ide>
<ide> from mock import Mock
<del>
<add>from libcloud.common.base import LibcloudConnection
<ide> from libcloud.common.openstack import OpenStackBaseConnection
<ide> from libcloud.utils.py3 import PY25
<ide>
<ide> def setUp(self):
<ide> self.connection.driver = Mock()
<ide> self.connection.driver.name = 'OpenStackDriver'
<ide>
<add> def tearDown(self):
<add> OpenStackBaseConnection.conn_class = LibcloudConnection
<add>
<ide> def test_base_connection_timeout(self):
<ide> self.connection.connect()
<ide> self.assertEqual(self.connection.timeout, self.timeout)
<ide><path>libcloud/test/compute/test_openstack.py
<ide> from libcloud.utils.py3 import method_type
<ide> from libcloud.utils.py3 import u
<ide>
<add>from libcloud.common.base import LibcloudConnection
<ide> from libcloud.common.types import InvalidCredsError, MalformedResponseError, \
<ide> LibcloudError
<ide> from libcloud.compute.types import Provider, KeyPairDoesNotExistError, StorageVolumeState, \
<ide> class OpenStackAuthTests(unittest.TestCase):
<ide> def setUp(self):
<ide> OpenStack_1_0_NodeDriver.connectionCls = OpenStack_1_0_Connection
<add> OpenStack_1_0_NodeDriver.connectionCls.conn_class = LibcloudConnection
<ide>
<ide> def test_auth_host_passed(self):
<ide> forced_auth = 'http://x.y.z.y:5000'
| 2
|
Ruby
|
Ruby
|
fix broken scaffold routes test
|
b09e5922e1d26b0867e7113309cc0696561cfd95
|
<ide><path>railties/test/generators/scaffold_generator_test.rb
<ide> def test_scaffold_with_namespace_on_invoke
<ide>
<ide> # Route
<ide> assert_file "config/routes.rb" do |route|
<del> assert_match(/namespace :admin do resources :roles end$/, route)
<add> assert_match(/^ namespace :admin do\n resources :roles\n end$/, route)
<ide> end
<ide>
<ide> # Controller
| 1
|
Ruby
|
Ruby
|
disconnect defined options from the build object
|
2f1d40a76437f94720c9969d11ff10555efc5809
|
<ide><path>Library/Homebrew/build_options.rb
<ide> require 'options'
<ide>
<del># This class holds the build-time options defined for a Formula,
<del># and provides named access to those options during install.
<ide> class BuildOptions
<ide> include Enumerable
<ide>
<ide><path>Library/Homebrew/cmd/info.rb
<ide> def info_formula f
<ide> end
<ide> end
<ide>
<del> unless f.build.empty?
<add> unless f.options.empty?
<ide> ohai "Options"
<ide> Homebrew.dump_options_for_formula f
<ide> end
<ide><path>Library/Homebrew/cmd/options.rb
<ide> def options
<ide>
<ide> def puts_options(formulae)
<ide> formulae.each do |f|
<del> next if f.build.empty?
<add> next if f.options.empty?
<ide> if ARGV.include? '--compact'
<del> puts f.build.as_flags.sort * " "
<add> puts f.options.as_flags.sort * " "
<ide> else
<ide> puts f.name if formulae.length > 1
<ide> dump_options_for_formula f
<ide> def puts_options(formulae)
<ide> end
<ide>
<ide> def dump_options_for_formula f
<del> f.build.sort_by(&:flag).each do |opt|
<add> f.options.sort_by(&:flag).each do |opt|
<ide> puts "#{opt.flag}\n\t#{opt.description}"
<ide> end
<ide> puts "--devel\n\tinstall development version #{f.devel.version}" if f.devel
<ide><path>Library/Homebrew/formula.rb
<ide> def patchlist
<ide> active_spec.patches
<ide> end
<ide>
<add> def options
<add> active_spec.options
<add> end
<add>
<ide> def option_defined?(name)
<ide> active_spec.option_defined?(name)
<ide> end
<ide> def to_hash
<ide> "caveats" => caveats
<ide> }
<ide>
<del> hsh["options"] = build.map { |opt|
<add> hsh["options"] = options.map { |opt|
<ide> { "option" => opt.flag, "description" => opt.description }
<ide> }
<ide>
<ide><path>Library/Homebrew/formula_installer.rb
<ide> def sanitized_ARGV_options
<ide> when f.devel then args << "--devel"
<ide> end
<ide>
<del> f.build.each do |opt, _|
<add> f.options.each do |opt, _|
<ide> name = opt.name[/\A(.+)=\z$/, 1]
<ide> value = ARGV.value(name)
<ide> args << "--#{name}=#{value}" if name && value
<ide><path>Library/Homebrew/tab.rb
<ide> def self.for_formula f
<ide>
<ide> def self.dummy_tab f=nil
<ide> Tab.new :used_options => [],
<del> :unused_options => (f.build.as_flags rescue []),
<add> :unused_options => (f.options.as_flags rescue []),
<ide> :built_as_bottle => false,
<ide> :poured_from_bottle => false,
<ide> :tapped_from => "",
| 6
|
Text
|
Text
|
add sandboxes for almost all examples
|
6ca30fbcda0db4ac007ddf451eba75920282113c
|
<ide><path>README.md
<ide> For Offline docs, please see: [devdocs](http://devdocs.io/redux/)
<ide>
<ide> ### Examples
<ide>
<add>Almost all examples have a corresponding CodeSandbox sandbox. This is an interactive version of the code that you can play with online.
<add>
<ide> * [Counter Vanilla](http://redux.js.org/docs/introduction/Examples.html#counter-vanilla) ([source](https://github.com/reactjs/redux/tree/master/examples/counter-vanilla))
<del>* [Counter](http://redux.js.org/docs/introduction/Examples.html#counter) ([source](https://github.com/reactjs/redux/tree/master/examples/counter))
<del>* [Todos](http://redux.js.org/docs/introduction/Examples.html#todos) ([source](https://github.com/reactjs/redux/tree/master/examples/todos))
<del>* [Todos with Undo](http://redux.js.org/docs/introduction/Examples.html#todos-with-undo) ([source](https://github.com/reactjs/redux/tree/master/examples/todos-with-undo))
<del>* [TodoMVC](http://redux.js.org/docs/introduction/Examples.html#todomvc) ([source](https://github.com/reactjs/redux/tree/master/examples/todomvc))
<del>* [Shopping Cart](http://redux.js.org/docs/introduction/Examples.html#shopping-cart) ([source](https://github.com/reactjs/redux/tree/master/examples/shopping-cart))
<del>* [Tree View](http://redux.js.org/docs/introduction/Examples.html#tree-view) ([source](https://github.com/reactjs/redux/tree/master/examples/tree-view))
<del>* [Async](http://redux.js.org/docs/introduction/Examples.html#async) ([source](https://github.com/reactjs/redux/tree/master/examples/async))
<add>* [Counter](http://redux.js.org/docs/introduction/Examples.html#counter) ([source](https://github.com/reactjs/redux/tree/master/examples/counter), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/counter))
<add>* [Todos](http://redux.js.org/docs/introduction/Examples.html#todos) ([source](https://github.com/reactjs/redux/tree/master/examples/todos), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos))
<add>* [Todos with Undo](http://redux.js.org/docs/introduction/Examples.html#todos-with-undo) ([source](https://github.com/reactjs/redux/tree/master/examples/todos-with-undo), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todos-with-undo))
<add>* [TodoMVC](http://redux.js.org/docs/introduction/Examples.html#todomvc) ([source](https://github.com/reactjs/redux/tree/master/examples/todomvc), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/todomvc))
<add>* [Shopping Cart](http://redux.js.org/docs/introduction/Examples.html#shopping-cart) ([source](https://github.com/reactjs/redux/tree/master/examples/shopping-cart), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/shopping-cart))
<add>* [Tree View](http://redux.js.org/docs/introduction/Examples.html#tree-view) ([source](https://github.com/reactjs/redux/tree/master/examples/tree-view), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/tree-view))
<add>* [Async](http://redux.js.org/docs/introduction/Examples.html#async) ([source](https://github.com/reactjs/redux/tree/master/examples/async), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/async))
<ide> * [Universal](http://redux.js.org/docs/introduction/Examples.html#universal) ([source](https://github.com/reactjs/redux/tree/master/examples/universal))
<del>* [Real World](http://redux.js.org/docs/introduction/Examples.html#real-world) ([source](https://github.com/reactjs/redux/tree/master/examples/real-world))
<add>* [Real World](http://redux.js.org/docs/introduction/Examples.html#real-world) ([source](https://github.com/reactjs/redux/tree/master/examples/real-world), [sandbox](https://codesandbox.io/s/github/reactjs/redux/tree/master/examples/real-world))
<ide>
<ide> If you're new to the NPM ecosystem and have troubles getting a project up and running, or aren't sure where to paste the gist above, check out [simplest-redux-example](https://github.com/jackielii/simplest-redux-example) that uses Redux together with React and Browserify.
<ide>
| 1
|
Javascript
|
Javascript
|
fix reference to wpt testharness.js
|
87a6b601325358d43ea9b649144417d3532ac58f
|
<ide><path>test/common/wpt.js
<ide> const path = require('path');
<ide> const { inspect } = require('util');
<ide> const { Worker } = require('worker_threads');
<ide>
<del>// https://github.com/w3c/testharness.js/blob/master/testharness.js
<add>// https://github.com/web-platform-tests/wpt/blob/master/resources/testharness.js
<ide> // TODO: get rid of this half-baked harness in favor of the one
<ide> // pulled from WPT
<ide> const harnessMock = {
| 1
|
Javascript
|
Javascript
|
fix rc7 version number
|
9c1a911eac841296fc483f8a26114c19f0151ae5
|
<ide><path>packages/ember-metal/lib/core.js
<ide> Ember.toString = function() { return "Ember"; };
<ide> /**
<ide> @property VERSION
<ide> @type String
<del> @default '1.0.0-rc.7.1'
<add> @default '1.0.0-rc.7'
<ide> @final
<ide> */
<del>Ember.VERSION = '1.0.0-rc.7.1';
<add>Ember.VERSION = '1.0.0-rc.7';
<ide>
<ide> /**
<ide> Standard environmental variables. You can define these in a global `ENV`
| 1
|
Ruby
|
Ruby
|
handle -—help for internal/external cmds
|
7ecffd2771c64356824a71e975a2216bc64fd159
|
<ide><path>Library/brew.rb
<ide> $:.unshift(HOMEBREW_LIBRARY_PATH.to_s)
<ide> require 'global'
<ide>
<del>if ARGV.empty? || ARGV[0] =~ /(-h$|--help$|--usage$|-\?$|help$)/
<del> # TODO - `brew help cmd` should display subcommand help
<del> require 'cmd/help'
<del> puts ARGV.usage
<del> exit ARGV.any? ? 0 : 1
<del>elsif ARGV.first == '--version'
<add>if ARGV.first == '--version'
<ide> puts HOMEBREW_VERSION
<ide> exit 0
<ide> elsif ARGV.first == '-v'
<ide> # odd exceptions. Reduce our support burden by showing a user-friendly error.
<ide> Dir.getwd rescue abort "The current working directory doesn't exist, cannot proceed."
<ide>
<del>
<ide> def require? path
<ide> require path
<ide> rescue LoadError => e
<ide> def require? path
<ide> '--config' => 'config',
<ide> }
<ide>
<del> cmd = ARGV.shift
<add> empty_argv = ARGV.empty?
<add> help_regex = /(-h$|--help$|--usage$|-\?$|help$)/
<add> help_flag = false
<add> cmd = nil
<add>
<add> ARGV.dup.each_with_index do |arg, i|
<add> if help_flag && cmd
<add> break
<add> elsif arg =~ help_regex
<add> help_flag = true
<add> elsif !cmd
<add> cmd = ARGV.delete_at(i)
<add> end
<add> end
<add>
<ide> cmd = aliases[cmd] if aliases[cmd]
<ide>
<ide> sudo_check = Set.new %w[ install link pin unpin upgrade ]
<ide> def require? path
<ide> # Add contributed commands to PATH before checking.
<ide> ENV['PATH'] += "#{File::PATH_SEPARATOR}#{HOMEBREW_CONTRIB}/cmd"
<ide>
<del> if require? HOMEBREW_LIBRARY_PATH.join("cmd", cmd)
<add> internal_cmd = require? HOMEBREW_LIBRARY_PATH.join("cmd", cmd)
<add>
<add> # Usage instructions should be displayed if and only if one of:
<add> # - a help flag is passed AND an internal command is matched
<add> # - no arguments are passed
<add> #
<add> # It should never affect external commands so they can handle usage
<add> # arguments themselves.
<add>
<add> if empty_argv || (internal_cmd && help_flag)
<add> # TODO - `brew help cmd` should display subcommand help
<add> require 'cmd/help'
<add> puts ARGV.usage
<add> exit ARGV.any? ? 0 : 1
<add> end
<add>
<add> if internal_cmd
<ide> Homebrew.send cmd.to_s.gsub('-', '_').downcase
<ide> elsif which "brew-#{cmd}"
<ide> %w[CACHE CELLAR LIBRARY_PATH PREFIX REPOSITORY].each do |e|
| 1
|
Python
|
Python
|
remove old comment
|
51d37033c8b2f280cfc0ddf2b1ecf0537f347532
|
<ide><path>spacy/tests/regression/test_issue4903.py
<ide> def test_issue4903():
<ide> nlp.add_pipe(custom_component, after="parser")
<ide>
<ide> text = ["I like bananas.", "Do you like them?", "No, I prefer wasabi."]
<del> # works without 'n_process'
<ide> for doc in nlp.pipe(text, n_process=2):
<ide> print(doc)
| 1
|
Mixed
|
Text
|
fix doc references
|
4b5b3b43212c0a1883c56321aedbffc605be31f9
|
<ide><path>api/client/commands.go
<ide> func (cli *DockerCli) CmdHelp(args ...string) error {
<ide> {"inspect", "Return low-level information on a container"},
<ide> {"kill", "Kill a running container"},
<ide> {"load", "Load an image from a tar archive"},
<del> {"login", "Register or log in to the Docker registry server"},
<del> {"logout", "Logout of the Docker registry server"},
<add> {"login", "Register or log in to a Docker registry server"},
<add> {"logout", "Log out from a Docker registry server"},
<ide> {"logs", "Fetch the logs of a container"},
<ide> {"port", "Lookup the public-facing port that is NAT-ed to PRIVATE_PORT"},
<ide> {"pause", "Pause all processes within a container"},
<ide> func (cli *DockerCli) CmdLogin(args ...string) error {
<ide> return nil
<ide> }
<ide>
<del>// logout of a registry service
<add>// log out from a Docker registry
<ide> func (cli *DockerCli) CmdLogout(args ...string) error {
<del> cmd := cli.Subcmd("logout", "[SERVER]", "Logout of a docker registry server, if no server is specified \""+registry.IndexServerAddress()+"\" is the default.")
<add> cmd := cli.Subcmd("logout", "[SERVER]", "Log out from a Docker registry, if no server is specified \""+registry.IndexServerAddress()+"\" is the default.")
<ide>
<ide> if err := cmd.Parse(args); err != nil {
<ide> return nil
<ide><path>docs/man/docker-logout.1.md
<ide> % DOCKER(1) Docker User Manuals
<del>% William Henry
<del>% APRIL 2014
<add>% Daniel, Dao Quang Minh
<add>% JUNE 2014
<ide> # NAME
<del>docker-logout - Log the user out of a Docker registry server
<add>docker-logout - Log out from a Docker registry
<ide>
<ide> # SYNOPSIS
<ide> **docker logout** [SERVER]
<ide>
<ide> # DESCRIPTION
<del>Log the user out of a docker registry server, , if no server is
<add>Log the user out from a Docker registry, if no server is
<ide> specified "https://index.docker.io/v1/" is the default. If you want to
<del>logout of a private registry you can specify this by adding the server name.
<add>log out from a private registry you can specify this by adding the server name.
<ide>
<ide> # EXAMPLE
<ide>
<del>## Logout of a local registry
<add>## Log out from a local registry
<ide>
<ide> # docker logout localhost:8080
<ide>
<ide> # HISTORY
<del>April 2014, Originally compiled by William Henry (whenry at redhat dot com)
<del>based on docker.io source material and internal work.
<add>June 2014, Originally compiled by Daniel, Dao Quang Minh (daniel at nitrous dot io)
<ide>
<ide><path>docs/sources/reference/commandline/cli.md
<ide> specify this by adding the server name.
<ide>
<ide> Usage: docker logout [SERVER]
<ide>
<del> Log the user out of a docker registry server, if no server is specified "https://index.docker.io/v1/" is the default.
<add> Log out from a Docker registry, if no server is specified "https://index.docker.io/v1/" is the default.
<ide>
<ide> example:
<ide> $ docker logout localhost:8080
| 3
|
Javascript
|
Javascript
|
add tests for requirejsstuffplugin
|
b25189a8b66b62499d02eae26702e810b8d9f2ce
|
<ide><path>test/RequireJsStuffPlugin.test.js
<add>var should = require("should");
<add>var sinon = require("sinon");
<add>var RequireJsStuffPlugin = require("../lib/RequireJsStuffPlugin");
<add>var applyPluginWithOptions = require("./helpers/applyPluginWithOptions");
<add>var PluginEnvironment = require("./helpers/PluginEnvironment");
<add>
<add>describe("RequireJsStuffPlugin", function() {
<add> it("has apply function", function() {
<add> (new RequireJsStuffPlugin()).apply.should.be.a.Function();
<add> });
<add>
<add> describe("when applied", function() {
<add> var eventBindings, eventBinding;
<add>
<add> beforeEach(function() {
<add> eventBindings = applyPluginWithOptions(RequireJsStuffPlugin);
<add> });
<add>
<add> it("binds one event handler", function() {
<add> eventBindings.length.should.be.exactly(1);
<add> });
<add>
<add> describe("compilation handler", function() {
<add> beforeEach(function() {
<add> eventBinding = eventBindings[0];
<add> });
<add>
<add> it("binds to compilation event", function() {
<add> eventBinding.name.should.be.exactly("compilation");
<add> });
<add>
<add> describe('when called', function() {
<add> var pluginEnvironment, compilationEventBindings, compilation;
<add>
<add> beforeEach(function() {
<add> pluginEnvironment = new PluginEnvironment();
<add> compilation = {
<add> dependencyFactories: {
<add> set: sinon.spy()
<add> },
<add> dependencyTemplates: {
<add> set: sinon.spy()
<add> }
<add> };
<add> var params = {
<add> normalModuleFactory: pluginEnvironment.getEnvironmentStub()
<add> };
<add> eventBinding.handler(compilation, params);
<add> compilationEventBindings = pluginEnvironment.getEventBindings();
<add> });
<add>
<add> it('sets the dependency factory', function() {
<add> compilation.dependencyFactories.set.callCount.should.be.exactly(1);
<add> });
<add>
<add> it('sets the dependency template', function() {
<add> compilation.dependencyTemplates.set.callCount.should.be.exactly(1);
<add> });
<add>
<add> it("binds one event handler", function() {
<add> compilationEventBindings.length.should.be.exactly(1);
<add> });
<add>
<add> describe("parser handler", function() {
<add> var parser, parserEventBindings;
<add>
<add> beforeEach(function() {
<add> compilationEventBinding = compilationEventBindings[0];
<add> pluginEnvironment = new PluginEnvironment();
<add> parser = pluginEnvironment.getEnvironmentStub();
<add> });
<add>
<add> it("binds to parser event", function() {
<add> compilationEventBinding.name.should.be.exactly("parser");
<add> });
<add>
<add> describe('when called with parser options of requirejs as false', function() {
<add> beforeEach(function() {
<add> compilationEventBinding.handler(parser, {
<add> requireJs: false
<add> });
<add> parserEventBindings = pluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("binds no event handlers", function() {
<add> parserEventBindings.length.should.be.exactly(0);
<add> });
<add> });
<add>
<add> describe('when called with empty parser options', function() {
<add> var parserEventBinding, parserEventContext, expressionMock;
<add>
<add> beforeEach(function() {
<add> parserEventContext = {
<add> state: {
<add> current: {
<add> addDependency: sinon.spy()
<add> }
<add> }
<add> };
<add> expressionMock = {
<add> range: 10,
<add> loc: 5
<add> };
<add> compilationEventBinding.handler(parser, {});
<add> parserEventBindings = pluginEnvironment.getEventBindings();
<add> });
<add>
<add> it("binds four event handlers", function() {
<add> parserEventBindings.length.should.be.exactly(4);
<add> });
<add>
<add> describe("'call require.config' handler", function() {
<add> beforeEach(function() {
<add> parserEventBinding = parserEventBindings[0];
<add> });
<add>
<add> it("binds to 'call require.config' event", function() {
<add> parserEventBinding.name.should.be.exactly("call require.config");
<add> });
<add>
<add> describe('when called', function() {
<add> beforeEach(function() {
<add> parserEventBinding.handler.call(parserEventContext, expressionMock);
<add> });
<add>
<add> it('adds dependency to current state', function() {
<add> var addDependencySpy = parserEventContext.state.current.addDependency;
<add> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> addDependencySpy.callCount.should.be.exactly(1);
<add> addedDependency.should.be.exactly('{"module":null,"expression":";","range":10,"loc":5}');
<add> });
<add> });
<add> });
<add>
<add> describe("'call requirejs.config' handler", function() {
<add> beforeEach(function() {
<add> parserEventBinding = parserEventBindings[1];
<add> });
<add>
<add> it("binds to 'call requirejs.config' event", function() {
<add> parserEventBinding.name.should.be.exactly("call requirejs.config");
<add> });
<add>
<add> describe('when called', function() {
<add> beforeEach(function() {
<add> parserEventBinding.handler.call(parserEventContext, expressionMock);
<add> });
<add>
<add> it('adds dependency to current state', function() {
<add> var addDependencySpy = parserEventContext.state.current.addDependency;
<add> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> addDependencySpy.callCount.should.be.exactly(1);
<add> addedDependency.should.be.exactly('{"module":null,"expression":";","range":10,"loc":5}');
<add> });
<add> });
<add> });
<add>
<add> describe("'expression require.version' handler", function() {
<add> beforeEach(function() {
<add> parserEventBinding = parserEventBindings[2];
<add> });
<add>
<add> it("binds to 'expression require.version' event", function() {
<add> parserEventBinding.name.should.be.exactly("expression require.version");
<add> });
<add>
<add> describe('when called', function() {
<add> beforeEach(function() {
<add> parserEventBinding.handler.call(parserEventContext, expressionMock);
<add> });
<add>
<add> it('adds dependency to current state', function() {
<add> var addDependencySpy = parserEventContext.state.current.addDependency;
<add> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> addDependencySpy.callCount.should.be.exactly(1);
<add> addedDependency.should.be.exactly('{"module":null,"expression":"\\"0.0.0\\"","range":10,"loc":5}');
<add> });
<add> });
<add> });
<add>
<add> describe("'expression requirejs.onError' handler", function() {
<add> beforeEach(function() {
<add> parserEventBinding = parserEventBindings[3];
<add> });
<add>
<add> it("binds to 'expression requirejs.onError' event", function() {
<add> parserEventBinding.name.should.be.exactly("expression requirejs.onError");
<add> });
<add>
<add> describe('when called', function() {
<add> beforeEach(function() {
<add> parserEventBinding.handler.call(parserEventContext, expressionMock);
<add> });
<add>
<add> it('adds dependency to current state', function() {
<add> var addDependencySpy = parserEventContext.state.current.addDependency;
<add> var addedDependency = JSON.stringify(addDependencySpy.getCall(0).args[0]);
<add> addDependencySpy.callCount.should.be.exactly(1);
<add> addedDependency.should.be.exactly('{"module":null,"expression":"\\"__webpack_require__.oe\\"","range":10,"loc":5}');
<add> });
<add> });
<add> });
<add> });
<add> });
<add> });
<add> });
<add> });
<add>});
<ide><path>test/helpers/PluginEnvironment.js
<add>module.exports = function PluginEnvironment() {
<add> var events = [];
<add>
<add> this.getEnvironmentStub = function() {
<add> return {
<add> plugin: function(name, handler) {
<add> events.push({
<add> name,
<add> handler
<add> });
<add> }
<add> };
<add> };
<add>
<add> this.getEventBindings = function() {
<add> return events;
<add> };
<add>};
<ide><path>test/helpers/applyPluginWithOptions.js
<del>function PluginEnvironment() {
<del> var events = [];
<del>
<del> this.getCompilerStub = function() {
<del> return {
<del> plugin: function(name, handler) {
<del> events.push({
<del> name,
<del> handler
<del> });
<del> }
<del> };
<del> };
<del>
<del> this.getEventBindings = function() {
<del> return events;
<del> };
<del>}
<add>var PluginEnvironment = require('./PluginEnvironment');
<ide>
<ide> module.exports = function applyPluginWithOptions(Plugin, options) {
<ide> var plugin = new Plugin(options);
<ide> var pluginEnvironment = new PluginEnvironment();
<del> plugin.apply(pluginEnvironment.getCompilerStub());
<add> plugin.apply(pluginEnvironment.getEnvironmentStub());
<ide> return pluginEnvironment.getEventBindings();
<ide> };
| 3
|
Python
|
Python
|
add new describequota api in outscale ec2 driver
|
e45b3d05200bd626d325c783158102dd8010f441
|
<ide><path>libcloud/compute/drivers/ec2.py
<ide> class OutscaleConnection(EC2Connection):
<ide> Connection class for Outscale
<ide> """
<ide>
<add> version = DEFAULT_OUTSCALE_API_VERSION
<ide> host = None
<ide>
<ide>
<ide> def list_sizes(self, location=None):
<ide> sizes.append(NodeSize(driver=self, **attributes))
<ide> return sizes
<ide>
<add> def _to_quota(self, elem):
<add> """
<add> To Quota
<add> """
<add>
<add> quota = {}
<add> for reference_quota_item in findall(element=elem,
<add> xpath='referenceQuotaSet/item',
<add> namespace=OUTSCALE_NAMESPACE):
<add> reference = findtext(element=reference_quota_item,
<add> xpath='reference',
<add> namespace=OUTSCALE_NAMESPACE)
<add> quota_set = []
<add> for quota_item in findall(element=reference_quota_item,
<add> xpath='quotaSet/item',
<add> namespace=OUTSCALE_NAMESPACE):
<add> ownerId = findtext(element=quota_item,
<add> xpath='ownerId',
<add> namespace=OUTSCALE_NAMESPACE)
<add> name = findtext(element=quota_item,
<add> xpath='name',
<add> namespace=OUTSCALE_NAMESPACE)
<add> displayName = findtext(element=quota_item,
<add> xpath='displayName',
<add> namespace=OUTSCALE_NAMESPACE)
<add> description = findtext(element=quota_item,
<add> xpath='description',
<add> namespace=OUTSCALE_NAMESPACE)
<add> groupName = findtext(element=quota_item,
<add> xpath='groupName',
<add> namespace=OUTSCALE_NAMESPACE)
<add> maxQuotaValue = findtext(element=quota_item,
<add> xpath='maxQuotaValue',
<add> namespace=OUTSCALE_NAMESPACE)
<add> usedQuotaValue = findtext(element=quota_item,
<add> xpath='usedQuotaValue',
<add> namespace=OUTSCALE_NAMESPACE)
<add> quota_set.append({'ownerId': ownerId,
<add> 'name': name,
<add> 'displayName': displayName,
<add> 'description': description,
<add> 'groupName': groupName,
<add> 'maxQuotaValue': maxQuotaValue,
<add> 'usedQuotaValue': usedQuotaValue})
<add> quota[reference] = quota_set
<add>
<add> return quota
<add>
<add> def ex_describe_quota(self, dry_run=False, filters=None,
<add> max_results=None, marker=None):
<add> """
<add> Describes one or more of your quotas.
<add>
<add> :param dry_run: dry_run
<add> :type dry_run: ``bool``
<add>
<add> :param filters: The filters so that the response includes
<add> information for only certain quotas
<add> :type filters: ``dict``
<add>
<add> :param max_results: The maximum number of items that can be
<add> returned in a single page (by default, 100)
<add> :type max_results: ``int``
<add>
<add> :param marker: Set quota marker
<add> :type marker: ``string``
<add>
<add> :return: (is_truncated, quota) tuple
<add> :rtype: ``(bool, dict)``
<add> """
<add>
<add> if filters:
<add> raise NotImplementedError(
<add> 'quota filters are not implemented')
<add>
<add> if marker:
<add> raise NotImplementedError(
<add> 'quota marker is not implemented')
<add>
<add> params = {'Action': 'DescribeQuota'}
<add>
<add> if dry_run:
<add> params.update({'DryRun': dry_run})
<add>
<add> if max_results:
<add> params.update({'MaxResults': max_results})
<add>
<add> response = self.connection.request(self.path, params=params,
<add> method='GET').object
<add>
<add> quota = self._to_quota(response)
<add>
<add> is_truncated = findtext(element=response, xpath='isTruncated',
<add> namespace=OUTSCALE_NAMESPACE)
<add>
<add> return is_truncated, quota
<add>
<ide>
<ide> class OutscaleSASNodeDriver(OutscaleNodeDriver):
<ide> """
| 1
|
Javascript
|
Javascript
|
fix printing of large numbers
|
d0c238cc81a7bc4d67453ae2952d7d9368069f89
|
<ide><path>benchmark/common.js
<ide> Benchmark.prototype.end = function(operations) {
<ide> Benchmark.prototype.report = function(value) {
<ide> var heading = this.getHeading();
<ide> if (!silent)
<del> console.log('%s: %s', heading, value.toPrecision(5));
<add> console.log('%s: %s', heading, value.toFixed(0));
<ide> process.exit(0);
<ide> };
<ide>
| 1
|
Javascript
|
Javascript
|
remove unnecessary loadgetinitialprops
|
c6535edc2736463dfc93b8543d7b8abd87e5ae39
|
<ide><path>packages/next/client/index.js
<ide> const wrapApp = (App) => (props) => {
<ide> }
<ide>
<ide> async function doRender({ App, Component, props, err }) {
<del> // Usual getInitialProps fetching is handled in next/router
<del> // this is for when ErrorComponent gets replaced by Component by HMR
<del> if (
<del> !props &&
<del> Component &&
<del> Component !== ErrorComponent &&
<del> lastAppProps.Component === ErrorComponent
<del> ) {
<del> const { pathname, query, asPath } = router
<del> const AppTree = wrapApp(App)
<del> const appCtx = {
<del> router,
<del> AppTree,
<del> Component: ErrorComponent,
<del> ctx: { err, pathname, query, asPath, AppTree },
<del> }
<del> props = await loadGetInitialProps(App, appCtx)
<del> }
<del>
<ide> Component = Component || lastAppProps.Component
<ide> props = props || lastAppProps.props
<ide>
| 1
|
Ruby
|
Ruby
|
add regression tests
|
bed91f842109c715903ebbe3ce9754629b3594fd
|
<ide><path>actionpack/test/controller/send_file_test.rb
<ide> def test_send_file_with_action_controller_live
<ide> response = process("file")
<ide> assert_equal 200, response.status
<ide> end
<add>
<add> def test_send_file_charset_with_type_options_key
<add> @controller = SendFileWithActionControllerLive.new
<add> @controller.options = { type: "text/calendar; charset=utf-8" }
<add> response = process("file")
<add> assert_equal "text/calendar; charset=utf-8", response.headers["Content-Type"]
<add> end
<add>
<add> def test_send_file_charset_with_content_type_options_key
<add> @controller = SendFileWithActionControllerLive.new
<add> @controller.options = { content_type: "text/calendar" }
<add> response = process("file")
<add> assert_equal "text/calendar; charset=utf-8", response.headers["Content-Type"]
<add> end
<ide> end
| 1
|
Python
|
Python
|
add an expected failng test for
|
6595fd81b17e83000f2ff2abce0e3a93036266f8
|
<ide><path>keras/engine/training_test.py
<ide> import collections
<ide> import io
<ide> import tempfile
<add>import unittest
<ide> import sys
<ide>
<ide> from absl.testing import parameterized
<ide> def test_outputs_are_floats(self):
<ide> self.assertIsInstance(loss, float)
<ide> self.assertIsInstance(accuracy, float)
<ide>
<add> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<add> @unittest.expectedFailure
<add> def test_loss_acc_is_corrupted(self):
<add> batch_size = 32
<add> n_samples, n_features = batch_size * 10, 5
<add> rng = np.random.RandomState(0)
<add> x = rng.normal(size=(n_samples, n_features))
<add> y = rng.randint(low=0, high=2, size=x.shape[0])
<add> model = sequential.Sequential([layers_module.Dense(1,)])
<add> model.compile('adam', 'binary_crossentropy', metrics=['accuracy'], run_eagerly=testing_utils.should_run_eagerly())
<add> loss = {}
<add> accurancy = {}
<add> loss_1 = {}
<add> accurancy_1 = {}
<add> for i in range(3):
<add> loss[i], accurancy[i] = model.test_on_batch(x[:batch_size], y[:batch_size])
<add> model.evaluate(x[:batch_size],y[:batch_size], batch_size=batch_size, verbose=0)
<add> for i in range(3):
<add> loss_1[i], accurancy_1[i] = model.test_on_batch(x[:batch_size], y[:batch_size])
<add> self.assertAllEqual(loss, loss_1,
<add> "https://github.com/keras-team/keras/issues/14086")
<add> self.assertAllEqual(accurancy, accurancy_1,
<add> "https://github.com/keras-team/keras/issues/14086")
<add>
<ide> @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
<ide> def test_int_output(self):
<ide> x, y = np.ones((10, 1)), np.ones((10, 1))
| 1
|
Python
|
Python
|
add test for new span.to_array method
|
4fda02c7e602df778e0648fcb86c9e2c8224e64d
|
<ide><path>spacy/tests/spans/test_span.py
<ide> from __future__ import unicode_literals
<ide>
<ide> from ..util import get_doc
<add>from ...attrs import ORTH, LENGTH
<ide>
<ide> import pytest
<ide>
<ide> def test_spans_by_character(doc):
<ide> assert span1.start_char == span2.start_char
<ide> assert span1.end_char == span2.end_char
<ide> assert span2.label_ == 'GPE'
<add>
<add>
<add>def test_span_to_array(doc):
<add> span = doc[1:-2]
<add> arr = span.to_array([ORTH, LENGTH])
<add> assert arr.shape == (len(span), 2)
<add> assert arr[0, 0] == span[0].orth
<add> assert arr[0, 1] == len(span[0])
<add>
| 1
|
Javascript
|
Javascript
|
avoid stack overflow
|
d18d555fe234c6d77d277a26f36ddc1657a49fdf
|
<ide><path>lib/FileSystemInfo.js
<ide> class FileSystemInfo {
<ide> path: directory
<ide> });
<ide> }
<del> callback();
<add> process.nextTick(callback);
<ide> break;
<ide> }
<ide> case RBDT_DIRECTORY_DEPENDENCIES: {
| 1
|
Mixed
|
Ruby
|
implement ar#inspect using paramterfilter
|
32b03b46150b0161eba2321ccac7678511e3d58e
|
<ide><path>activerecord/CHANGELOG.md
<ide> specify sensitive attributes to specific model.
<ide>
<ide> ```
<del> Rails.application.config.filter_parameters += [:credit_card_number]
<del> Account.last.inspect # => #<Account id: 123, name: "DHH", credit_card_number: [FILTERED] ...>
<add> Rails.application.config.filter_parameters += [:credit_card_number, /phone/]
<add> Account.last.inspect # => #<Account id: 123, name: "DHH", credit_card_number: [FILTERED], telephone_number: [FILTERED] ...>
<ide> SecureAccount.filter_attributes += [:name]
<ide> SecureAccount.last.inspect # => #<SecureAccount id: 42, name: [FILTERED], credit_card_number: [FILTERED] ...>
<ide> ```
<ide>
<del> *Zhang Kang*
<add> *Zhang Kang*, *Yoshiyuki Kinjo*
<ide>
<ide> * Deprecate `column_name_length`, `table_name_length`, `columns_per_table`,
<ide> `indexes_per_table`, `columns_per_multicolumn_index`, `sql_query_length`,
<ide><path>activerecord/lib/active_record/attribute_methods.rb
<ide> def attributes
<ide> # # => "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]"
<ide> def attribute_for_inspect(attr_name)
<ide> value = read_attribute(attr_name)
<del>
<del> if value.is_a?(String) && value.length > 50
<del> "#{value[0, 50]}...".inspect
<del> elsif value.is_a?(Date) || value.is_a?(Time)
<del> %("#{value.to_s(:db)}")
<del> else
<del> value.inspect
<del> end
<add> format_for_inspect(value)
<ide> end
<ide>
<ide> # Returns +true+ if the specified +attribute+ has been set by the user or by a
<ide> def attributes_for_create(attribute_names)
<ide> end
<ide> end
<ide>
<add> def format_for_inspect(value)
<add> if value.is_a?(String) && value.length > 50
<add> "#{value[0, 50]}...".inspect
<add> elsif value.is_a?(Date) || value.is_a?(Time)
<add> %("#{value.to_s(:db)}")
<add> else
<add> value.inspect
<add> end
<add> end
<add>
<ide> def readonly_attribute?(name)
<ide> self.class.readonly_attributes.include?(name)
<ide> end
<ide><path>activerecord/lib/active_record/core.rb
<ide>
<ide> require "active_support/core_ext/hash/indifferent_access"
<ide> require "active_support/core_ext/string/filters"
<add>require "active_support/parameter_filter"
<ide> require "concurrent/map"
<del>require "set"
<ide>
<ide> module ActiveRecord
<ide> module Core
<ide> extend ActiveSupport::Concern
<ide>
<del> FILTERED = "[FILTERED]" # :nodoc:
<del>
<ide> included do
<ide> ##
<ide> # :singleton-method:
<ide> def filter_attributes
<ide> end
<ide>
<ide> # Specifies columns which shouldn't be exposed while calling +#inspect+.
<del> def filter_attributes=(attributes_names)
<del> @filter_attributes = attributes_names.map(&:to_s).to_set
<del> end
<add> attr_writer :filter_attributes
<ide>
<ide> # Returns a string like 'Post(id:integer, title:string, body:text)'
<ide> def inspect # :nodoc:
<ide> def inspect
<ide> inspection = if defined?(@attributes) && @attributes
<ide> self.class.attribute_names.collect do |name|
<ide> if has_attribute?(name)
<del> if filter_attribute?(name)
<del> "#{name}: #{ActiveRecord::Core::FILTERED}"
<add> attr = read_attribute(name)
<add> value = if attr.nil?
<add> attr.inspect
<ide> else
<del> "#{name}: #{attribute_for_inspect(name)}"
<add> attr = format_for_inspect(attr)
<add> inspection_filter.filter_param(name, attr)
<ide> end
<add> "#{name}: #{value}"
<ide> end
<ide> end.compact.join(", ")
<ide> else
<ide> def pretty_print(pp)
<ide> return super if custom_inspect_method_defined?
<ide> pp.object_address_group(self) do
<ide> if defined?(@attributes) && @attributes
<del> column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? }
<del> pp.seplist(column_names, proc { pp.text "," }) do |column_name|
<add> attr_names = self.class.attribute_names.select { |name| has_attribute?(name) }
<add> pp.seplist(attr_names, proc { pp.text "," }) do |attr_name|
<ide> pp.breakable " "
<ide> pp.group(1) do
<del> pp.text column_name
<add> pp.text attr_name
<ide> pp.text ":"
<ide> pp.breakable
<del> if filter_attribute?(column_name)
<del> pp.text ActiveRecord::Core::FILTERED
<del> else
<del> pp.pp read_attribute(column_name)
<del> end
<add> value = read_attribute(attr_name)
<add> value = inspection_filter.filter_param(attr_name, value) unless value.nil?
<add> pp.pp value
<ide> end
<ide> end
<ide> else
<ide> def custom_inspect_method_defined?
<ide> self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner
<ide> end
<ide>
<del> def filter_attribute?(attribute_name)
<del> self.class.filter_attributes.include?(attribute_name) && !read_attribute(attribute_name).nil?
<add> def inspection_filter
<add> @inspection_filter ||= begin
<add> mask = DelegateClass(::String).new(ActiveSupport::ParameterFilter::FILTERED)
<add> def mask.pretty_print(pp)
<add> pp.text __getobj__
<add> end
<add> ActiveSupport::ParameterFilter.new(self.class.filter_attributes, mask: mask)
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/cases/filter_attributes_test.rb
<ide> require "models/admin"
<ide> require "models/admin/user"
<ide> require "models/admin/account"
<add>require "models/user"
<ide> require "pp"
<ide>
<ide> class FilterAttributesTest < ActiveRecord::TestCase
<ide> class FilterAttributesTest < ActiveRecord::TestCase
<ide> end
<ide> end
<ide>
<add> test "string filter_attributes perform pertial match" do
<add> ActiveRecord::Base.filter_attributes = ["n"]
<add> Admin::Account.all.each do |account|
<add> assert_includes account.inspect, "name: [FILTERED]"
<add> assert_equal 1, account.inspect.scan("[FILTERED]").length
<add> end
<add> end
<add>
<add> test "regex filter_attributes are accepted" do
<add> ActiveRecord::Base.filter_attributes = [/\An\z/]
<add> account = Admin::Account.find_by(name: "37signals")
<add> assert_includes account.inspect, 'name: "37signals"'
<add> assert_equal 0, account.inspect.scan("[FILTERED]").length
<add>
<add> ActiveRecord::Base.filter_attributes = [/\An/]
<add> account = Admin::Account.find_by(name: "37signals")
<add> assert_includes account.reload.inspect, "name: [FILTERED]"
<add> assert_equal 1, account.inspect.scan("[FILTERED]").length
<add> end
<add>
<add> test "proc filter_attributes are accepted" do
<add> ActiveRecord::Base.filter_attributes = [ lambda { |key, value| value.reverse! if key == "name" } ]
<add> account = Admin::Account.find_by(name: "37signals")
<add> assert_includes account.inspect, 'name: "slangis73"'
<add> end
<add>
<ide> test "filter_attributes could be overwritten by models" do
<ide> Admin::Account.all.each do |account|
<ide> assert_includes account.inspect, "name: [FILTERED]"
<ide> assert_equal 1, account.inspect.scan("[FILTERED]").length
<ide> end
<ide>
<ide> begin
<del> previous_account_filter_attributes = Admin::Account.filter_attributes
<ide> Admin::Account.filter_attributes = []
<ide>
<ide> # Above changes should not impact other models
<ide> class FilterAttributesTest < ActiveRecord::TestCase
<ide> assert_equal 0, account.inspect.scan("[FILTERED]").length
<ide> end
<ide> ensure
<del> Admin::Account.filter_attributes = previous_account_filter_attributes
<add> Admin::Account.remove_instance_variable(:@filter_attributes)
<ide> end
<ide> end
<ide>
<ide> class FilterAttributesTest < ActiveRecord::TestCase
<ide> assert_equal 0, account.inspect.scan("[FILTERED]").length
<ide> end
<ide>
<add> test "filter_attributes should handle [FILTERED] value properly" do
<add> begin
<add> User.filter_attributes = ["auth"]
<add> user = User.new(token: "[FILTERED]", auth_token: "[FILTERED]")
<add>
<add> assert_includes user.inspect, "auth_token: [FILTERED]"
<add> assert_includes user.inspect, 'token: "[FILTERED]"'
<add> ensure
<add> User.remove_instance_variable(:@filter_attributes)
<add> end
<add> end
<add>
<ide> test "filter_attributes on pretty_print" do
<ide> user = admin_users(:david)
<ide> actual = "".dup
<ide> class FilterAttributesTest < ActiveRecord::TestCase
<ide> assert_not_includes actual, "name: [FILTERED]"
<ide> assert_equal 0, actual.scan("[FILTERED]").length
<ide> end
<add>
<add> test "filter_attributes on pretty_print should handle [FILTERED] value properly" do
<add> begin
<add> User.filter_attributes = ["auth"]
<add> user = User.new(token: "[FILTERED]", auth_token: "[FILTERED]")
<add> actual = "".dup
<add> PP.pp(user, StringIO.new(actual))
<add>
<add> assert_includes actual, "auth_token: [FILTERED]"
<add> assert_includes actual, 'token: "[FILTERED]"'
<add> ensure
<add> User.remove_instance_variable(:@filter_attributes)
<add> end
<add> end
<ide> end
<ide><path>activesupport/lib/active_support/parameter_filter.rb
<ide> module ActiveSupport
<ide> class ParameterFilter
<ide> FILTERED = "[FILTERED]" # :nodoc:
<ide>
<del> def initialize(filters = [])
<add> # Create instance with given filters. Supported type of filters are +String+, +Regexp+, and +Proc+.
<add> # Other types of filters are treated as +String+ using +to_s+.
<add> # For +Proc+ filters, key, value, and optional original hash is passed to block arguments.
<add> #
<add> # ==== Options
<add> #
<add> # * <tt>:mask</tt> - A replaced object when filtered. Defaults to +"[FILTERED]"+
<add> def initialize(filters = [], mask: FILTERED)
<ide> @filters = filters
<add> @mask = mask
<ide> end
<ide>
<add> # Mask value of +params+ if key matches one of filters.
<ide> def filter(params)
<ide> compiled_filter.call(params)
<ide> end
<ide>
<add> # Returns filtered value for given key. For +Proc+ filters, third block argument is not populated.
<add> def filter_param(key, value)
<add> @filters.empty? ? value : compiled_filter.value_for_key(key, value)
<add> end
<add>
<ide> private
<ide>
<ide> def compiled_filter
<del> @compiled_filter ||= CompiledFilter.compile(@filters)
<add> @compiled_filter ||= CompiledFilter.compile(@filters, mask: @mask)
<ide> end
<ide>
<ide> class CompiledFilter # :nodoc:
<del> def self.compile(filters)
<add> def self.compile(filters, mask:)
<ide> return lambda { |params| params.dup } if filters.empty?
<ide>
<ide> strings, regexps, blocks = [], [], []
<ide> def self.compile(filters)
<ide> regexps << Regexp.new(strings.join("|"), true) unless strings.empty?
<ide> deep_regexps << Regexp.new(deep_strings.join("|"), true) unless deep_strings.empty?
<ide>
<del> new regexps, deep_regexps, blocks
<add> new regexps, deep_regexps, blocks, mask: mask
<ide> end
<ide>
<ide> attr_reader :regexps, :deep_regexps, :blocks
<ide>
<del> def initialize(regexps, deep_regexps, blocks)
<add> def initialize(regexps, deep_regexps, blocks, mask:)
<ide> @regexps = regexps
<ide> @deep_regexps = deep_regexps.any? ? deep_regexps : nil
<ide> @blocks = blocks
<add> @mask = mask
<ide> end
<ide>
<ide> def call(params, parents = [], original_params = params)
<ide> filtered_params = params.class.new
<ide>
<ide> params.each do |key, value|
<del> parents.push(key) if deep_regexps
<del> if regexps.any? { |r| key =~ r }
<del> value = FILTERED
<del> elsif deep_regexps && (joined = parents.join(".")) && deep_regexps.any? { |r| joined =~ r }
<del> value = FILTERED
<del> elsif value.is_a?(Hash)
<del> value = call(value, parents, original_params)
<del> elsif value.is_a?(Array)
<del> value = value.map { |v| v.is_a?(Hash) ? call(v, parents, original_params) : v }
<del> elsif blocks.any?
<del> key = key.dup if key.duplicable?
<del> value = value.dup if value.duplicable?
<del> blocks.each { |b| b.arity == 2 ? b.call(key, value) : b.call(key, value, original_params) }
<del> end
<del> parents.pop if deep_regexps
<del>
<del> filtered_params[key] = value
<add> filtered_params[key] = value_for_key(key, value, parents, original_params)
<ide> end
<ide>
<ide> filtered_params
<ide> end
<add>
<add> def value_for_key(key, value, parents = [], original_params = nil)
<add> parents.push(key) if deep_regexps
<add> if regexps.any? { |r| r.match?(key) }
<add> value = @mask
<add> elsif deep_regexps && (joined = parents.join(".")) && deep_regexps.any? { |r| r.match?(joined) }
<add> value = @mask
<add> elsif value.is_a?(Hash)
<add> value = call(value, parents, original_params)
<add> elsif value.is_a?(Array)
<add> value = value.map { |v| v.is_a?(Hash) ? call(v, parents, original_params) : v }
<add> elsif blocks.any?
<add> key = key.dup if key.duplicable?
<add> value = value.dup if value.duplicable?
<add> blocks.each { |b| b.arity == 2 ? b.call(key, value) : b.call(key, value, original_params) }
<add> end
<add> parents.pop if deep_regexps
<add> value
<add> end
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/test/parameter_filter_test.rb
<ide> class ParameterFilterTest < ActiveSupport::TestCase
<ide> end
<ide> end
<ide>
<add> test "filter should return mask option when value is filtered" do
<add> mask = Object.new.freeze
<add> test_hashes = [
<add> [{ "foo" => "bar" }, { "foo" => "bar" }, %w'food'],
<add> [{ "foo" => "bar" }, { "foo" => mask }, %w'foo'],
<add> [{ "foo" => "bar", "bar" => "foo" }, { "foo" => mask, "bar" => "foo" }, %w'foo baz'],
<add> [{ "foo" => "bar", "baz" => "foo" }, { "foo" => mask, "baz" => mask }, %w'foo baz'],
<add> [{ "bar" => { "foo" => "bar", "bar" => "foo" } }, { "bar" => { "foo" => mask, "bar" => "foo" } }, %w'fo'],
<add> [{ "foo" => { "foo" => "bar", "bar" => "foo" } }, { "foo" => mask }, %w'f banana'],
<add> [{ "deep" => { "cc" => { "code" => "bar", "bar" => "foo" }, "ss" => { "code" => "bar" } } }, { "deep" => { "cc" => { "code" => mask, "bar" => "foo" }, "ss" => { "code" => "bar" } } }, %w'deep.cc.code'],
<add> [{ "baz" => [{ "foo" => "baz" }, "1"] }, { "baz" => [{ "foo" => mask }, "1"] }, [/foo/]]]
<add>
<add> test_hashes.each do |before_filter, after_filter, filter_words|
<add> parameter_filter = ActiveSupport::ParameterFilter.new(filter_words, mask: mask)
<add> assert_equal after_filter, parameter_filter.filter(before_filter)
<add>
<add> filter_words << "blah"
<add> filter_words << lambda { |key, value|
<add> value.reverse! if key =~ /bargain/
<add> }
<add> filter_words << lambda { |key, value, original_params|
<add> value.replace("world!") if original_params["barg"]["blah"] == "bar" && key == "hello"
<add> }
<add>
<add> parameter_filter = ActiveSupport::ParameterFilter.new(filter_words, mask: mask)
<add> before_filter["barg"] = { :bargain => "gain", "blah" => "bar", "bar" => { "bargain" => { "blah" => "foo", "hello" => "world" } } }
<add> after_filter["barg"] = { :bargain => "niag", "blah" => mask, "bar" => { "bargain" => { "blah" => mask, "hello" => "world!" } } }
<add>
<add> assert_equal after_filter, parameter_filter.filter(before_filter)
<add> end
<add> end
<add>
<add> test "filter_param" do
<add> parameter_filter = ActiveSupport::ParameterFilter.new(["foo", /bar/])
<add> assert_equal "[FILTERED]", parameter_filter.filter_param("food", "secret vlaue")
<add> assert_equal "[FILTERED]", parameter_filter.filter_param("baz.foo", "secret vlaue")
<add> assert_equal "[FILTERED]", parameter_filter.filter_param("barbar", "secret vlaue")
<add> assert_equal "non secret value", parameter_filter.filter_param("baz", "non secret value")
<add> end
<add>
<add> test "filter_param can work with empty filters" do
<add> parameter_filter = ActiveSupport::ParameterFilter.new
<add> assert_equal "bar", parameter_filter.filter_param("foo", "bar")
<add> end
<add>
<ide> test "parameter filter should maintain hash with indifferent access" do
<ide> test_hashes = [
<ide> [{ "foo" => "bar" }.with_indifferent_access, ["blah"]],
<ide> class ParameterFilterTest < ActiveSupport::TestCase
<ide> parameter_filter.filter(before_filter)
<ide> end
<ide> end
<add>
<add> test "filter_param should return mask option when value is filtered" do
<add> mask = Object.new.freeze
<add> parameter_filter = ActiveSupport::ParameterFilter.new(["foo", /bar/], mask: mask)
<add> assert_equal mask, parameter_filter.filter_param("food", "secret vlaue")
<add> assert_equal mask, parameter_filter.filter_param("baz.foo", "secret vlaue")
<add> assert_equal mask, parameter_filter.filter_param("barbar", "secret vlaue")
<add> assert_equal "non secret value", parameter_filter.filter_param("baz", "non secret value")
<add> end
<ide> end
<ide><path>railties/test/application/configuration_test.rb
<ide> class ::DummySerializer < ActiveJob::Serializers::ObjectSerializer; end
<ide> RUBY
<ide> app "development"
<ide> assert_equal [ :password, :credit_card_number ], Rails.application.config.filter_parameters
<del> assert_equal [ "password", "credit_card_number" ].to_set, ActiveRecord::Base.filter_attributes
<add> assert_equal [ :password, :credit_card_number ], ActiveRecord::Base.filter_attributes
<ide> end
<ide>
<ide> test "ActiveStorage.routes_prefix can be configured via config.active_storage.routes_prefix" do
| 7
|
Java
|
Java
|
fix simplejdbccall and simplejdbcinsert javadoc
|
2344412e040bf734595141f6af7d695da061c2ef
|
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcCall.java
<ide> * when the stored procedure was created.
<ide> *
<ide> * <p>The meta data processing is based on the DatabaseMetaData provided by
<del> * the JDBC driver. Since we rely on the JDBC driver this "auto-detection"
<add> * the JDBC driver. Since we rely on the JDBC driver, this "auto-detection"
<ide> * can only be used for databases that are known to provide accurate meta data.
<ide> * These currently include Derby, MySQL, Microsoft SQL Server, Oracle, DB2,
<ide> * Sybase and PostgreSQL. For any other databases you are required to declare all
<ide> * parameters explicitly. You can of course declare all parameters explicitly even
<ide> * if the database provides the necessary meta data. In that case your declared
<del> * parameters will take precedence. You can also turn off any mete data processing
<add> * parameters will take precedence. You can also turn off any meta data processing
<ide> * if you want to use parameter names that do not match what is declared during
<ide> * the stored procedure compilation.
<ide> *
<ide> * <p>The actual insert is being handled using Spring's
<ide> * {@link org.springframework.jdbc.core.JdbcTemplate}.
<ide> *
<ide> * <p>Many of the configuration methods return the current instance of the SimpleJdbcCall
<del> * to provide the ability to string multiple ones together in a "fluid" interface style.
<add> * to provide the ability to chain multiple ones together in a "fluent" interface style.
<ide> *
<ide> * @author Thomas Risberg
<ide> * @since 2.5
<ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/core/simple/SimpleJdbcInsert.java
<ide> * {@link org.springframework.jdbc.core.JdbcTemplate}.
<ide> *
<ide> * <p>Many of the configuration methods return the current instance of the SimpleJdbcInsert
<del> * to provide the ability to string multiple ones together in a "fluid" interface style.
<add> * to provide the ability to chain multiple ones together in a "fluent" interface style.
<ide> *
<ide> * @author Thomas Risberg
<ide> * @since 2.5
| 2
|
Javascript
|
Javascript
|
initialize dev variables in dev mode only
|
a42dcf4f7b10eab60bc97d89719eca05731dda35
|
<ide><path>src/core/shouldUpdateReactComponent.js
<ide> function shouldUpdateReactComponent(prevElement, nextElement) {
<ide> prevElement.type === nextElement.type &&
<ide> prevElement.key === nextElement.key) {
<ide> var ownersMatch = prevElement._owner === nextElement._owner;
<del> var prevName = null;
<del> var nextName = null;
<del> var nextDisplayName = null;
<ide> if (__DEV__) {
<ide> if (!ownersMatch) {
<add> var prevName = null;
<add> var nextName = null;
<add> var nextDisplayName = null;
<ide> if (prevElement._owner != null &&
<ide> prevElement._owner.getPublicInstance() != null &&
<ide> prevElement._owner.getPublicInstance().constructor != null) {
| 1
|
Javascript
|
Javascript
|
test nativewatcher removal
|
0325a77d591f12d56d604fde9b0657a2436dc1ba
|
<ide><path>spec/native-watcher-registry-spec.js
<ide> /** @babel */
<ide>
<add>import path from 'path'
<add>import {Emitter} from 'event-kit'
<add>
<ide> import NativeWatcherRegistry from '../src/native-watcher-registry'
<ide>
<ide> class MockWatcher {
<ide> class MockNative {
<ide> this.attached = []
<ide> this.disposed = false
<ide> this.stopped = false
<add>
<add> this.emitter = new Emitter()
<ide> }
<ide>
<ide> reattachTo (newNative) {
<ide> class MockNative {
<ide> this.attached = []
<ide> }
<ide>
<add> onDidStop (callback) {
<add> return this.emitter.on('did-stop', callback)
<add> }
<add>
<ide> dispose () {
<ide> this.disposed = true
<ide> }
<ide>
<ide> stop () {
<ide> this.stopped = true
<add> this.emitter.emit('did-stop')
<ide> }
<ide> }
<ide>
<ide> describe('NativeWatcherRegistry', function () {
<ide> expect(EXISTING2.disposed).toBe(false)
<ide> })
<ide>
<del> it('removes NativeWatchers when all Watchers have been disposed')
<add> describe('removing NativeWatchers', function () {
<add> it('happens when they stop', function () {
<add> const STOPPED = new MockNative('stopped')
<add> const stoppedWatcher = new MockWatcher()
<add> const stoppedPath = ['watcher', 'that', 'will', 'be', 'stopped']
<add> registry.attach(path.join(...stoppedPath), stoppedWatcher, () => STOPPED)
<add>
<add> const RUNNING = new MockNative('running')
<add> const runningWatcher = new MockWatcher()
<add> const runningPath = ['watcher', 'that', 'will', 'continue', 'to', 'exist']
<add> registry.attach(path.join(...runningPath), runningWatcher, () => RUNNING)
<add>
<add> STOPPED.stop()
<add>
<add> const runningNode = registry.tree.lookup(runningPath).when({
<add> parent: node => node,
<add> missing: () => false,
<add> children: () => false
<add> })
<add> expect(runningNode).toBeTruthy()
<add> expect(runningNode.getNativeWatcher()).toBe(RUNNING)
<add>
<add> const stoppedNode = registry.tree.lookup(stoppedPath).when({
<add> parent: () => false,
<add> missing: () => true,
<add> children: () => false
<add> })
<add> expect(stoppedNode).toBe(true)
<add> })
<add>
<add> it("keeps a parent watcher that's still running")
<add>
<add> it('reassigns new child watchers when a parent watcher is stopped')
<add> })
<ide> })
| 1
|
PHP
|
PHP
|
add touchquietly convenience method
|
9a1ac305d4aaac772f12243aad2c84f19d774081
|
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasTimestamps.php
<ide> public function touch($attribute = null)
<ide> return $this->save();
<ide> }
<ide>
<add> /**
<add> * Update the model's update timestamp without raising any events.
<add> *
<add> * @param string|null $attribute
<add> * @return bool
<add> */
<add> public function touchQuietly($attribute = null)
<add> {
<add> return static::withoutEvents(fn () => $this->touch($attribute));
<add> }
<add>
<ide> /**
<ide> * Update the creation and update timestamps.
<ide> *
| 1
|
Python
|
Python
|
add compat helpers for urllib
|
da1f20036209af7950588ccb0877299ccf946f0e
|
<ide><path>spacy/compat.py
<ide> except ImportError:
<ide> from thinc.neural.optimizers import Adam as Optimizer
<ide>
<add>try:
<add> import urllib
<add>except ImportError:
<add> import urllib2 as urllib
<add>
<add>try:
<add> from urllib.error import HTTPError as url_error
<add>except ImportError:
<add> from urllib2 import HTTPError as url_error
<add>
<ide> pickle = pickle
<ide> copy_reg = copy_reg
<ide> CudaStream = CudaStream
<ide> cupy = cupy
<ide> copy_array = copy_array
<add>urllib = urllib
<add>url_error = url_error
<ide> izip = getattr(itertools, 'izip', zip)
<ide>
<ide> is_windows = sys.platform.startswith('win')
<ide> input_ = raw_input # noqa: F821
<ide> json_dumps = lambda data: ujson.dumps(data, indent=2, escape_forward_slashes=False).decode('utf8')
<ide> path2str = lambda path: str(path).decode('utf8')
<add> url_open = lambda url: urllib.urlopen(url)
<ide>
<ide> elif is_python3:
<ide> bytes_ = bytes
<ide> input_ = input
<ide> json_dumps = lambda data: ujson.dumps(data, indent=2, escape_forward_slashes=False)
<ide> path2str = lambda path: str(path)
<add> url_open = lambda url: urllib.request.urlopen(url)
<ide>
<ide>
<ide> def b_to_str(b_str):
| 1
|
Javascript
|
Javascript
|
replace lodash module imports with utils
|
9724f2cc2ed3cd02e20bb51f55ba95db087dbe70
|
<ide><path>src/components/createConnector.js
<del>import identity from 'lodash/utility/identity';
<add>import identity from '../utils/identity';
<ide> import shallowEqual from '../utils/shallowEqual';
<del>import isPlainObject from 'lodash/lang/isPlainObject';
<add>import isPlainObject from '../utils/isPlainObject';
<ide> import invariant from 'invariant';
<ide>
<ide> export default function createConnector(React) {
<ide><path>src/utils/composeStores.js
<ide> import mapValues from '../utils/mapValues';
<del>import pick from 'lodash/object/pick';
<add>import pick from '../utils/pick';
<ide>
<ide> export default function composeStores(stores) {
<ide> stores = pick(stores, (val) => typeof val === 'function');
| 2
|
PHP
|
PHP
|
fix date_format validation for all formats
|
71bb4e419b8d8f1fc3bae5c98c75b3c5ee3fe191
|
<ide><path>src/Illuminate/Validation/Validator.php
<ide> protected function validateDateFormat($attribute, $value, $parameters)
<ide> if (! is_string($value) && ! is_numeric($value)) {
<ide> return false;
<ide> }
<add>
<add> $date = DateTime::createFromFormat($parameters[0], $value);
<ide>
<del> $parsed = date_parse_from_format($parameters[0], $value);
<del>
<del> return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0;
<add> return $date && $date->format($parameters[0]) === $value;
<ide> }
<ide>
<ide> /**
| 1
|
Ruby
|
Ruby
|
remove unused requires
|
38baf946c31df229b3aac47671eef313aca05520
|
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb
<ide> require 'active_support/core_ext/hash/keys'
<del>require 'active_support/core_ext/module/attribute_accessors'
<del>require 'active_support/core_ext/object/blank'
<ide> require 'active_support/key_generator'
<ide> require 'active_support/message_verifier'
<ide> require 'active_support/json'
| 1
|
Mixed
|
Javascript
|
remove experimental warning for fs.promises
|
5583d4d73ef750b27c9068ea0f05fae0de9f7766
|
<ide><path>doc/api/fs.md
<ide> this API: [`fs.write(fd, string...)`][].
<ide>
<ide> ## fs Promises API
<ide>
<del>> Stability: 1 - Experimental
<add>> Stability: 2 - Stable
<ide>
<ide> The `fs.promises` API provides an alternative set of asynchronous file system
<ide> methods that return `Promise` objects rather than using callbacks. The
<ide><path>lib/fs.js
<ide> Object.defineProperties(fs, {
<ide> },
<ide> promises: {
<ide> configurable: true,
<del> enumerable: false,
<add> enumerable: true,
<ide> get() {
<del> if (promises === null) {
<add> if (promises === null)
<ide> promises = require('internal/fs/promises');
<del> process.emitWarning('The fs.promises API is experimental',
<del> 'ExperimentalWarning');
<del> }
<ide> return promises;
<ide> }
<ide> }
<ide><path>test/parallel/test-fs-promises.js
<ide> function nextdir() {
<ide> return `test${++dirc}`;
<ide> }
<ide>
<del>// fs.promises should not be enumerable as long as it causes a warning to be
<del>// emitted.
<del>assert.strictEqual(Object.keys(fs).includes('promises'), false);
<add>// fs.promises should not enumerable.
<add>assert.strictEqual(Object.keys(fs).includes('promises'), true);
<ide>
<ide> {
<ide> access(__filename, 'r')
| 3
|
Javascript
|
Javascript
|
shorten job name
|
0add0b30db54ecdc7f64c081d7abcb29ae5a8be4
|
<ide><path>grunt.js
<ide> module.exports = function( grunt ) {
<ide> }, {
<ide> authUsername: "jquery",
<ide> authToken: grunt.file.readJSON( configFile ).jquery.authToken,
<del> jobName: 'jQuery commit #<a href="https://github.com/jquery/jquery/commit/' + commit + '">' + commit + '</a>',
<add> jobName: 'jQuery commit #<a href="https://github.com/jquery/jquery/commit/' + commit + '">' + commit.substr( 0, 10 ) + '</a>',
<ide> runMax: 4,
<ide> "runNames[]": tests,
<ide> "runUrls[]": testUrls,
| 1
|
Javascript
|
Javascript
|
fix typo at i18n generation code
|
eb4afd45f77d7d67744e01ce63a831c13c2b22e8
|
<ide><path>i18n/src/parser.js
<ide> function parsePattern(pattern) {
<ide> var p = {
<ide> minInt: 1,
<ide> minFrac: 0,
<del> macFrac: 0,
<add> maxFrac: 0,
<ide> posPre: '',
<ide> posSuf: '',
<ide> negPre: '',
| 1
|
Javascript
|
Javascript
|
remove warning comment about `createhtmldocument`
|
3bfb687de395b3b1dca75539427e54a223541c93
|
<ide><path>src/test/getTestDocument.js
<ide> * @providesModule getTestDocument
<ide> */
<ide>
<del>/**
<del> * We need to work around the fact that we have two different
<del> * test implementations: once that breaks if we clobber document
<del> * (open-source) and one that doesn't support createHTMLDocument()
<del> * (jst).
<del> */
<ide> function getTestDocument() {
<ide> var iframe = document.createElement('iframe');
<ide> iframe.style.cssText = 'position:absolute; visibility:hidden; bottom:100%; right:100%';
| 1
|
Python
|
Python
|
add benchmarks for fp16 umath functions
|
6070491623528a648deb067fc5dce709de3631d5
|
<ide><path>benchmarks/benchmarks/bench_ufunc_strides.py
<ide>
<ide> stride = [1, 2, 4]
<ide> stride_out = [1, 2, 4]
<del>dtype = ['f', 'd']
<add>dtype = ['e', 'f', 'd']
<ide>
<ide> class Unary(Benchmark):
<ide> params = [UNARY_OBJECT_UFUNCS, stride, stride_out, dtype]
| 1
|
Python
|
Python
|
add names to keras application models
|
9f33f8af5f678a24e1585fdde893f1d7041640d4
|
<ide><path>keras/applications/inception_v3.py
<ide> def InceptionV3(include_top=True, weights='imagenet',
<ide> else:
<ide> inputs = img_input
<ide> # Create model.
<del> model = Model(inputs, x)
<add> model = Model(inputs, x, name='inception_v3')
<ide>
<ide> # load weights
<ide> if weights == 'imagenet':
<ide><path>keras/applications/music_tagger_crnn.py
<ide> def MusicTaggerCRNN(weights='msd', input_tensor=None,
<ide> else:
<ide> inputs = melgram_input
<ide> # Create model.
<del> model = Model(inputs, x)
<add> model = Model(inputs, x, name='music_tagger_crnn')
<ide>
<ide> if weights is None:
<ide> return model
<ide><path>keras/applications/resnet50.py
<ide> def ResNet50(include_top=True, weights='imagenet',
<ide> else:
<ide> inputs = img_input
<ide> # Create model.
<del> model = Model(inputs, x)
<add> model = Model(inputs, x, name='resnet50')
<ide>
<ide> # load weights
<ide> if weights == 'imagenet':
<ide><path>keras/applications/vgg16.py
<ide> def VGG16(include_top=True, weights='imagenet',
<ide> else:
<ide> inputs = img_input
<ide> # Create model.
<del> model = Model(inputs, x)
<add> model = Model(inputs, x, name='vgg16')
<ide>
<ide> # load weights
<ide> if weights == 'imagenet':
<ide><path>keras/applications/vgg19.py
<ide> def VGG19(include_top=True, weights='imagenet',
<ide> else:
<ide> inputs = img_input
<ide> # Create model.
<del> model = Model(inputs, x)
<add> model = Model(inputs, x, name='vgg19')
<ide>
<ide> # load weights
<ide> if weights == 'imagenet':
<ide><path>keras/applications/xception.py
<ide> def Xception(include_top=True, weights='imagenet',
<ide> else:
<ide> inputs = img_input
<ide> # Create model.
<del> model = Model(inputs, x)
<add> model = Model(inputs, x, name='xception')
<ide>
<ide> # load weights
<ide> if weights == 'imagenet':
| 6
|
Python
|
Python
|
improve add_dag_code_table migration
|
88e756e54c8d38fecb3a0d2b0b0dd4f9562b37b6
|
<ide><path>airflow/migrations/versions/952da73b5eff_add_dag_code_table.py
<ide>
<ide> # revision identifiers, used by Alembic.
<ide> from airflow.models.dagcode import DagCode
<del>from airflow.models.serialized_dag import SerializedDagModel
<ide>
<ide> revision = '952da73b5eff'
<ide> down_revision = '852ae6c715af'
<ide>
<ide>
<ide> def upgrade():
<add> from sqlalchemy.ext.declarative import declarative_base
<add>
<add> Base = declarative_base()
<add>
<add> class SerializedDagModel(Base):
<add> __tablename__ = 'serialized_dag'
<add>
<add> # There are other columns here, but these are the only ones we need for the SELECT/UPDATE we are doing
<add> dag_id = sa.Column(sa.String(250), primary_key=True)
<add> fileloc = sa.Column(sa.String(2000), nullable=False)
<add> fileloc_hash = sa.Column(sa.BigInteger, nullable=False)
<add>
<ide> """Apply add source code table"""
<ide> op.create_table('dag_code', # pylint: disable=no-member
<ide> sa.Column('fileloc_hash', sa.BigInteger(),
<ide> def upgrade():
<ide>
<ide> conn = op.get_bind()
<ide> if conn.dialect.name not in ('sqlite'):
<del> op.drop_index('idx_fileloc_hash', 'serialized_dag')
<add> if conn.dialect.name == "mssql":
<add> op.drop_index('idx_fileloc_hash', 'serialized_dag')
<add>
<ide> op.alter_column(table_name='serialized_dag', column_name='fileloc_hash',
<ide> type_=sa.BigInteger(), nullable=False)
<del> op.create_index( # pylint: disable=no-member
<del> 'idx_fileloc_hash', 'serialized_dag', ['fileloc_hash'])
<add> if conn.dialect.name == "mssql":
<add> op.create_index('idx_fileloc_hash', 'serialized_dag', ['fileloc_hash'])
<ide>
<ide> sessionmaker = sa.orm.sessionmaker()
<ide> session = sessionmaker(bind=conn)
| 1
|
Javascript
|
Javascript
|
fix sticky headers when rerendering
|
0518a0ba12e7cafc8228be0455403cc23b055a79
|
<ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = React.createClass({
<ide> },
<ide>
<ide> _updateAnimatedNodeAttachment: function() {
<add> if (this._scrollAnimatedValueAttachment) {
<add> this._scrollAnimatedValueAttachment.detach();
<add> }
<ide> if (this.props.stickyHeaderIndices && this.props.stickyHeaderIndices.length > 0) {
<del> if (!this._scrollAnimatedValueAttachment) {
<del> this._scrollAnimatedValueAttachment = Animated.attachNativeEvent(
<del> this._scrollViewRef,
<del> 'onScroll',
<del> [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}]
<del> );
<del> }
<del> } else {
<del> if (this._scrollAnimatedValueAttachment) {
<del> this._scrollAnimatedValueAttachment.detach();
<del> }
<add> this._scrollAnimatedValueAttachment = Animated.attachNativeEvent(
<add> this._scrollViewRef,
<add> 'onScroll',
<add> [{nativeEvent: {contentOffset: {y: this._scrollAnimatedValue}}}]
<add> );
<ide> }
<ide> },
<ide>
| 1
|
PHP
|
PHP
|
allow both bare string and _path key
|
5c1560ad5202faa1f7300344353c87638e5203d0
|
<ide><path>src/Routing/Router.php
<ide> public static function url($url = null, $full = false): string
<ide> return $url;
<ide> }
<ide>
<del> if (ctype_alnum($url[0]) && strpos($url, '::') > 0) {
<del> $url = static::parseRoutePath($url) + ['plugin' => false, 'prefix' => false];
<add> if ($url[0] !== '/' && strpos($url, '::') > 1) {
<add> $url = ['_path' => $url];
<ide>
<ide> if (is_array($full)) {
<del> foreach (['plugin', 'prefix', 'controller', 'action'] as $key) {
<del> if (isset($full[$key])) {
<del> throw new InvalidArgumentException(
<del> "`$key` cannot be used when defining route targets with a string route path."
<del> );
<del> }
<del> }
<del>
<ide> $url += $full;
<ide> $full = false;
<ide> }
<ide> }
<ide> }
<ide>
<ide> if (is_array($url)) {
<add> if (isset($url['_path'])) {
<add> $url = self::unwrapShortString($url);
<add> }
<add>
<ide> if (isset($url['_ssl'])) {
<ide> $url['_scheme'] = $url['_ssl'] === true ? 'https' : 'http';
<ide> }
<ide> public static function setRouteCollection(RouteCollection $routeCollection): voi
<ide> static::$_collection = $routeCollection;
<ide> }
<ide>
<add> /**
<add> * Inject route defaults from `_path` key
<add> *
<add> * @param array $url Route array with `_path` key
<add> * @return array
<add> */
<add> protected static function unwrapShortString(array $url)
<add> {
<add> foreach (['plugin', 'prefix', 'controller', 'action'] as $key) {
<add> if (array_key_exists($key, $url)) {
<add> throw new InvalidArgumentException(
<add> "`$key` cannot be used when defining route targets with a string route path."
<add> );
<add> }
<add> }
<add> $url += static::parseRoutePath($url['_path']);
<add> $url += [
<add> 'plugin' => false,
<add> 'prefix' => false,
<add> ];
<add> unset($url['_path']);
<add>
<add> return $url;
<add> }
<add>
<ide> /**
<ide> * Parse a string route path
<ide> *
| 1
|
Text
|
Text
|
fix typo and adjust examples
|
179a6f6bc8128ad008c7c6dccc2450f236324080
|
<ide><path>client/src/pages/guide/english/javascript/popup-boxes/index.md
<ide> There are three different kinds of popup methods used in JavaScript: <a href='ht
<ide> The <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/alert' target='_blank' rel='nofollow'>alert method</a> displays messages that don't require the user to enter a response. Once this function is called, an alert dialog box will appear with the specified (optional) message. Users will be required to confirm the message before the alert goes away.
<ide>
<ide> ### Example:
<del>`window.alert("Welcome to our website");`
<add>`window.alert("Hello world");`
<ide>
<ide> 
<ide>
<ide> The <a href='https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm' ta
<ide>
<ide> ### Example:
<ide> ```javascript
<del>var result = window.confirm('Are you sure?');
<add>var result = window.confirm('Do you really want to leave?');
<ide> if (result === true) {
<ide> window.alert('Okay, if you're sure.');
<ide> } else {
<ide> swal("Oops!", "Something went wrong on the page!", "error");
<ide> ```
<ide> The above code will produce the following popup:
<ide> 
<del>SweetAlert is by no means the only subsitute for standard modals, but it is clean and easy to implement.
<add>SweetAlert is by no means the only substitute for standard modals, but it is clean and easy to implement.
<ide>
<ide>
<ide>
| 1
|
Javascript
|
Javascript
|
fix missing documentation methods
|
3d1c1e6403b8c8fcf32ab58fd8fc3076ebaf8acb
|
<ide><path>pages/lib/collectMemberGroups.js
<ide> function collectMemberGroups(interfaceDef, options) {
<ide> });
<ide>
<ide> def.extends && def.extends.forEach(e => {
<del> var superModule = defs.Immutable.module[e.name];
<add> var superModule = defs.Immutable;
<add> e.name.split('.').forEach(part => {
<add> superModule =
<add> superModule && superModule.module && superModule.module[part];
<add> });
<ide> var superInterface = superModule && superModule.interface;
<ide> if (superInterface) {
<ide> collectFromDef(superInterface, e.name);
| 1
|
Python
|
Python
|
apply `repr` fixer
|
011f8a20044a3982b2441cb53876e9689a3f6d0c
|
<ide><path>numpy/_import_tools.py
<ide> class PackageLoaderDebug(PackageLoader):
<ide> def _execcmd(self,cmdstr):
<ide> """ Execute command in parent_frame."""
<ide> frame = self.parent_frame
<del> print('Executing',`cmdstr`,'...', end=' ')
<add> print('Executing',repr(cmdstr),'...', end=' ')
<ide> sys.stdout.flush()
<ide> exec (cmdstr, frame.f_globals,frame.f_locals)
<ide> print('ok')
<ide><path>numpy/core/records.py
<ide> def _setfieldnames(self, names, titles):
<ide> elif (type(names) == str):
<ide> names = names.split(',')
<ide> else:
<del> raise NameError("illegal input names %s" % `names`)
<add> raise NameError("illegal input names %s" % repr(names))
<ide>
<ide> self._names = [n.strip() for n in names[:self._nfields]]
<ide> else:
<ide> def fromarrays(arrayList, dtype=None, shape=None, formats=None,
<ide> raise ValueError("item in the array list must be an ndarray.")
<ide> formats += _typestr[obj.dtype.type]
<ide> if issubclass(obj.dtype.type, nt.flexible):
<del> formats += `obj.itemsize`
<add> formats += repr(obj.itemsize)
<ide> formats += ','
<ide> formats = formats[:-1]
<ide>
<ide><path>numpy/distutils/tests/test_misc_util.py
<ide> class TestGpaths(TestCase):
<ide> def test_gpaths(self):
<ide> local_path = minrelpath(join(dirname(__file__),'..'))
<ide> ls = gpaths('command/*.py', local_path)
<del> assert_(join(local_path,'command','build_src.py') in ls,`ls`)
<add> assert_(join(local_path,'command','build_src.py') in ls,repr(ls))
<ide> f = gpaths('system_info.py', local_path)
<del> assert_(join(local_path,'system_info.py')==f[0],`f`)
<add> assert_(join(local_path,'system_info.py')==f[0],repr(f))
<ide>
<ide>
<ide> if __name__ == "__main__":
<ide><path>numpy/f2py/auxfuncs.py
<ide> def getmultilineblock(rout,blockname,comment=1,counter=0):
<ide> r = r[counter]
<ide> if r[:3]=="'''":
<ide> if comment:
<del> r = '\t/* start ' + blockname + ' multiline ('+`counter`+') */\n' + r[3:]
<add> r = '\t/* start ' + blockname + ' multiline ('+repr(counter)+') */\n' + r[3:]
<ide> else:
<ide> r = r[3:]
<ide> if r[-3:]=="'''":
<ide> if comment:
<del> r = r[:-3] + '\n\t/* end multiline ('+`counter`+')*/'
<add> r = r[:-3] + '\n\t/* end multiline ('+repr(counter)+')*/'
<ide> else:
<ide> r = r[:-3]
<ide> else:
<ide> def applyrules(rules,d,var={}):
<ide> else: i=''
<ide> ret[k].append(replace(i,d))
<ide> else:
<del> errmess('applyrules: ignoring rule %s.\n'%`rules[k]`)
<add> errmess('applyrules: ignoring rule %s.\n'%repr(rules[k]))
<ide> if type(ret[k])==types.ListType:
<ide> if len(ret[k])==1:
<ide> ret[k]=ret[k][0]
<ide><path>numpy/f2py/capi_maps.py
<ide> def getstrlength(var):
<ide> else:
<ide> errmess('getstrlength: function %s has no return value?!\n'%a)
<ide> if not isstring(var):
<del> errmess('getstrlength: expected a signature of a string but got: %s\n'%(`var`))
<add> errmess('getstrlength: expected a signature of a string but got: %s\n'%(repr(var)))
<ide> len='1'
<ide> if 'charselector' in var:
<ide> a=var['charselector']
<ide> def getstrlength(var):
<ide> if re.match(r'\(\s*([*]|[:])\s*\)',len) or re.match(r'([*]|[:])',len):
<ide> #if len in ['(*)','*','(:)',':']:
<ide> if isintent_hide(var):
<del> errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n'%(`var`))
<add> errmess('getstrlength:intent(hide): expected a string with defined length but got: %s\n'%(repr(var)))
<ide> len='-1'
<ide> return len
<ide>
<ide> def getarrdims(a,var,verbose=0):
<ide> # var['dimension'].reverse()
<ide> dim=copy.copy(var['dimension'])
<ide> ret['size']='*'.join(dim)
<del> try: ret['size']=`eval(ret['size'])`
<add> try: ret['size']=repr(eval(ret['size']))
<ide> except: pass
<ide> ret['dims']=','.join(dim)
<del> ret['rank']=`len(dim)`
<del> ret['rank*[-1]']=`len(dim)*[-1]`[1:-1]
<add> ret['rank']=repr(len(dim))
<add> ret['rank*[-1]']=repr(len(dim)*[-1])[1:-1]
<ide> for i in range(len(dim)): # solve dim for dependecies
<ide> v=[]
<ide> if dim[i] in depargs: v=[dim[i]]
<ide> def getarrdims(a,var,verbose=0):
<ide> % (d))
<ide> ret['cbsetdims']='%s#varname#_Dims[%d]=%s,'%(ret['cbsetdims'],i,0)
<ide> elif verbose :
<del> errmess('getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n'%(`a`,`d`))
<add> errmess('getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n'%(repr(a),repr(d)))
<ide> if ret['cbsetdims']: ret['cbsetdims']=ret['cbsetdims'][:-1]
<ide> # if not isintent_c(var):
<ide> # var['dimension'].reverse()
<ide> def getpydocsign(a,var):
<ide> sigout='%s : string(len=%s)'%(out_a,getstrlength(var))
<ide> elif isarray(var):
<ide> dim=var['dimension']
<del> rank=`len(dim)`
<add> rank=repr(len(dim))
<ide> sig='%s : %s rank-%s array(\'%s\') with bounds (%s)%s'%(a,opt,rank,
<ide> c2pycode_map[ctype],
<ide> ','.join(dim), init)
<ide> def getarrdocsign(a,var):
<ide> c2pycode_map[ctype],)
<ide> elif isarray(var):
<ide> dim=var['dimension']
<del> rank=`len(dim)`
<add> rank=repr(len(dim))
<ide> sig='%s : rank-%s array(\'%s\') with bounds (%s)'%(a,rank,
<ide> c2pycode_map[ctype],
<ide> ','.join(dim))
<ide> def routsign2map(rout):
<ide> #else:
<ide> # errmess('routsign2map: cb_map does not contain module "%s" used in "use" statement.\n'%(u))
<ide> elif 'externals' in rout and rout['externals']:
<del> errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n'%(ret['name'],`rout['externals']`))
<add> errmess('routsign2map: Confused: function %s has externals %s but no "use" statement.\n'%(ret['name'],repr(rout['externals'])))
<ide> ret['callprotoargument'] = getcallprotoargument(rout,lcb_map) or ''
<ide> if isfunction(rout):
<ide> if 'result' in rout:
<ide> def routsign2map(rout):
<ide> ret['rformat']=c2buildvalue_map[ret['ctype']]
<ide> else:
<ide> ret['rformat']='O'
<del> errmess('routsign2map: no c2buildvalue key for type %s\n'%(`ret['ctype']`))
<add> errmess('routsign2map: no c2buildvalue key for type %s\n'%(repr(ret['ctype'])))
<ide> if debugcapi(rout):
<ide> if ret['ctype'] in cformat_map:
<ide> ret['routdebugshowvalue']='debug-capi:%s=%s'%(a,cformat_map[ret['ctype']])
<ide> def routsign2map(rout):
<ide> if isstringfunction(rout):
<ide> ret['rlength']=getstrlength(rout['vars'][a])
<ide> if ret['rlength']=='-1':
<del> errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n'%(`rout['name']`))
<add> errmess('routsign2map: expected explicit specification of the length of the string returned by the fortran function %s; taking 10.\n'%(repr(rout['name'])))
<ide> ret['rlength']='10'
<ide> if hasnote(rout):
<ide> ret['note']=rout['note']
<ide> def cb_routsign2map(rout,um):
<ide> nofargs=nofargs+1
<ide> if isoptional(var):
<ide> nofoptargs=nofoptargs+1
<del> ret['maxnofargs']=`nofargs`
<del> ret['nofoptargs']=`nofoptargs`
<add> ret['maxnofargs']=repr(nofargs)
<add> ret['nofoptargs']=repr(nofoptargs)
<ide> if hasnote(rout) and isfunction(rout) and 'result' in rout:
<ide> ret['routnote']=rout['note']
<ide> rout['note']=['See elsewhere.']
<ide><path>numpy/f2py/cfuncs.py
<ide> def append_needs(need,flag=1):
<ide> elif need in commonhooks:
<ide> n = 'commonhooks'
<ide> else:
<del> errmess('append_needs: unknown need %s\n'%(`need`))
<add> errmess('append_needs: unknown need %s\n'%(repr(need)))
<ide> return
<ide> if need in outneeds[n]: return
<ide> if flag:
<ide> def append_needs(need,flag=1):
<ide> tmp[n].append(need)
<ide> return tmp
<ide> else:
<del> errmess('append_needs: expected list or string but got :%s\n'%(`need`))
<add> errmess('append_needs: expected list or string but got :%s\n'%(repr(need)))
<ide>
<ide> def get_needs():
<ide> global outneeds,needs
<ide><path>numpy/f2py/crackfortran.py
<ide> def readfortrancode(ffile,dowithline=show,istop=1):
<ide> if strictf77: beginpattern=beginpattern77
<ide> else: beginpattern=beginpattern90
<ide> outmess('\tReading file %s (format:%s%s)\n'\
<del> %(`currentfilename`,sourcecodeform,
<add> %(repr(currentfilename),sourcecodeform,
<ide> strictf77 and ',strict' or ''))
<ide>
<ide> l=l.expandtabs().replace('\xa0',' ')
<ide> def readfortrancode(ffile,dowithline=show,istop=1):
<ide> if not (l[0] in spacedigits):
<ide> raise Exception('readfortrancode: Found non-(space,digit) char '
<ide> 'in the first column.\n\tAre you sure that '
<del> 'this code is in fix form?\n\tline=%s' % `l`)
<add> 'this code is in fix form?\n\tline=%s' % repr(l))
<ide>
<ide> if (not cont or strictf77) and (len(l)>5 and not l[5]==' '):
<ide> # Continuation of a previous line
<ide> def readfortrancode(ffile,dowithline=show,istop=1):
<ide> ll=l
<ide> cont=(r is not None)
<ide> else:
<del> raise ValueError("Flag sourcecodeform must be either 'fix' or 'free': %s"%`sourcecodeform`)
<add> raise ValueError("Flag sourcecodeform must be either 'fix' or 'free': %s"%repr(sourcecodeform))
<ide> filepositiontext='Line #%d in %s:"%s"\n\t' % (fin.filelineno()-1,currentfilename,l1)
<ide> m=includeline.match(origfinalline)
<ide> if m:
<ide> def readfortrancode(ffile,dowithline=show,istop=1):
<ide> readfortrancode(fn1,dowithline=dowithline,istop=0)
<ide> break
<ide> if not foundfile:
<del> outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n'%(`fn`, os.pathsep.join(include_dirs)))
<add> outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n'%(repr(fn), os.pathsep.join(include_dirs)))
<ide> else:
<ide> dowithline(finalline)
<ide> l1=ll
<ide> def readfortrancode(ffile,dowithline=show,istop=1):
<ide> readfortrancode(fn1,dowithline=dowithline,istop=0)
<ide> break
<ide> if not foundfile:
<del> outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n'%(`fn`, os.pathsep.join(include_dirs)))
<add> outmess('readfortrancode: could not find include file %s in %s. Ignoring.\n'%(repr(fn), os.pathsep.join(include_dirs)))
<ide> else:
<ide> dowithline(finalline)
<ide> filepositiontext=''
<ide> def crackline(line,reset=0):
<ide> if ';' in line and not (f2pyenhancementspattern[0].match(line) or
<ide> multilinepattern[0].match(line)):
<ide> for l in line.split(';'):
<del> assert reset==0,`reset` # XXX: non-zero reset values need testing
<add> assert reset==0,repr(reset) # XXX: non-zero reset values need testing
<ide> crackline(l,reset)
<ide> return
<ide> if reset<0:
<ide> def crackline(line,reset=0):
<ide> fl=0
<ide> if f77modulename and neededmodule==groupcounter: fl=2
<ide> while groupcounter>fl:
<del> outmess('crackline: groupcounter=%s groupname=%s\n'%(`groupcounter`,`groupname`))
<add> outmess('crackline: groupcounter=%s groupname=%s\n'%(repr(groupcounter),repr(groupname)))
<ide> outmess('crackline: Mismatch of blocks encountered. Trying to fix it by assuming "end" statement.\n')
<ide> grouplist[groupcounter-1].append(groupcache[groupcounter])
<ide> grouplist[groupcounter-1][-1]['body']=grouplist[groupcounter]
<ide> def crackline(line,reset=0):
<ide> else: line='callfun %s(%s)'%(name,a)
<ide> m = callfunpattern[0].match(line)
<ide> if not m:
<del> outmess('crackline: could not resolve function call for line=%s.\n'%`line`)
<add> outmess('crackline: could not resolve function call for line=%s.\n'%repr(line))
<ide> return
<ide> analyzeline(m,'callfun',line)
<ide> return
<ide> def crackline(line,reset=0):
<ide> if (m1) and (not m1.group('this')==groupname[groupcounter]):
<ide> raise Exception('crackline: End group %s does not match with '
<ide> 'previous Begin group %s\n\t%s' % \
<del> (`m1.group('this')`, `groupname[groupcounter]`,
<add> (repr(m1.group('this')), repr(groupname[groupcounter]),
<ide> filepositiontext)
<ide> )
<ide> if skipblocksuntil==groupcounter:
<ide> def markoutercomma(line,comma=','):
<ide> l=l+'@'+comma+'@'
<ide> continue
<ide> l=l+c
<del> assert not f,`f,line,l,cc`
<add> assert not f,repr((f,line,l,cc))
<ide> return l
<ide> def unmarkouterparen(line):
<ide> r = line.replace('@(@','(').replace('@)@',')')
<ide> def analyzeline(m,case,line):
<ide> grouplist[groupcounter]=[]
<ide> if needmodule:
<ide> if verbose>1:
<del> outmess('analyzeline: Creating module block %s\n'%`f77modulename`,0)
<add> outmess('analyzeline: Creating module block %s\n'%repr(f77modulename),0)
<ide> groupname[groupcounter]='module'
<ide> groupcache[groupcounter]['block']='python module'
<ide> groupcache[groupcounter]['name']=f77modulename
<ide> def analyzeline(m,case,line):
<ide> if args:
<ide> args=rmbadname([x.strip() for x in markoutercomma(args).split('@,@')])
<ide> else: args=[]
<del> assert result is None,`result`
<add> assert result is None,repr(result)
<ide> groupcache[groupcounter]['entry'][name] = args
<ide> previous_context = ('entry',name,groupcounter)
<ide> elif case=='type':
<ide> def analyzeline(m,case,line):
<ide> if case in ['public','private']: k=''
<ide> else:
<ide> print(m.groupdict())
<del> outmess('analyzeline: no name pattern found in %s statement for %s. Skipping.\n'%(case,`e`))
<add> outmess('analyzeline: no name pattern found in %s statement for %s. Skipping.\n'%(case,repr(e)))
<ide> continue
<ide> else:
<ide> k=rmbadname1(m1.group('name'))
<ide> def analyzeline(m,case,line):
<ide> m2=re.match(r'\A\s*(?P<local>\b[\w]+\b)\s*=\s*>\s*(?P<use>\b[\w]+\b)\s*\Z',l,re.I)
<ide> if m2: rl[m2.group('local').strip()]=m2.group('use').strip()
<ide> else:
<del> outmess('analyzeline: Not local=>use pattern found in %s\n'%`l`)
<add> outmess('analyzeline: Not local=>use pattern found in %s\n'%repr(l))
<ide> else:
<ide> rl[l]=l
<ide> groupcache[groupcounter]['use'][name]['map']=rl
<ide> def updatevars(typespec,selector,attrspec,entitydecl):
<ide> for e in el1:
<ide> m=namepattern.match(e)
<ide> if not m:
<del> outmess('updatevars: no name pattern found for entity=%s. Skipping.\n'%(`e`))
<add> outmess('updatevars: no name pattern found for entity=%s. Skipping.\n'%(repr(e)))
<ide> continue
<ide> ename=rmbadname1(m.group('name'))
<ide> edecl={}
<ide> def cracktypespec(typespec,selector):
<ide> if typespec in ['complex','integer','logical','real']:
<ide> kindselect=kindselector.match(selector)
<ide> if not kindselect:
<del> outmess('cracktypespec: no kindselector pattern found for %s\n'%(`selector`))
<add> outmess('cracktypespec: no kindselector pattern found for %s\n'%(repr(selector)))
<ide> return
<ide> kindselect=kindselect.groupdict()
<ide> kindselect['*']=kindselect['kind2']
<ide> def cracktypespec(typespec,selector):
<ide> elif typespec=='character':
<ide> charselect=charselector.match(selector)
<ide> if not charselect:
<del> outmess('cracktypespec: no charselector pattern found for %s\n'%(`selector`))
<add> outmess('cracktypespec: no charselector pattern found for %s\n'%(repr(selector)))
<ide> return
<ide> charselect=charselect.groupdict()
<ide> charselect['*']=charselect['charlen']
<ide> def cracktypespec(typespec,selector):
<ide> elif typespec=='type':
<ide> typename=re.match(r'\s*\(\s*(?P<name>\w+)\s*\)',selector,re.I)
<ide> if typename: typename=typename.group('name')
<del> else: outmess('cracktypespec: no typename found in %s\n'%(`typespec+selector`))
<add> else: outmess('cracktypespec: no typename found in %s\n'%(repr(typespec+selector)))
<ide> else:
<del> outmess('cracktypespec: no selector used for %s\n'%(`selector`))
<add> outmess('cracktypespec: no selector used for %s\n'%(repr(selector)))
<ide> return kindselect,charselect,typename
<ide> ######
<ide> def setattrspec(decl,attr,force=0):
<ide> def get_useparameters(block, param_map=None):
<ide> for k,v in list(params.items()):
<ide> if k in param_map:
<ide> outmess('get_useparameters: overriding parameter %s with'\
<del> ' value from module %s' % (`k`,`usename`))
<add> ' value from module %s' % (repr(k),repr(usename)))
<ide> param_map[k] = v
<ide>
<ide> return param_map
<ide> def buildimplicitrules(block):
<ide> if block['implicit'] is None:
<ide> implicitrules=None
<ide> if verbose>1:
<del> outmess('buildimplicitrules: no implicit rules for routine %s.\n'%`block['name']`)
<add> outmess('buildimplicitrules: no implicit rules for routine %s.\n'%repr(block['name']))
<ide> else:
<ide> for k in list(block['implicit'].keys()):
<ide> if block['implicit'][k].get('typespec') not in ['static','automatic']:
<ide> def getarrlen(dl,args,star='*'):
<ide> if p1==0: d='-(%s)' % (dl[0])
<ide> else: d='%s-(%s)' % (p1,dl[0])
<ide> else: d = '%s-(%s)+1'%(dl[1],dl[0])
<del> try: return `myeval(d,{},{})`,None,None
<add> try: return repr(myeval(d,{},{})),None,None
<ide> except: pass
<ide> d1,d2=getlincoef(dl[0],args),getlincoef(dl[1],args)
<ide> if None not in [d1[0],d2[0]]:
<ide> if (d1[0],d2[0])==(0,0):
<del> return `d2[1]-d1[1]+1`,None,None
<add> return repr(d2[1]-d1[1]+1),None,None
<ide> b = d2[1] - d1[1] + 1
<ide> d1 = (d1[0],0,d1[2])
<ide> d2 = (d2[0],b,d2[2])
<ide> def getarrlen(dl,args,star='*'):
<ide> else: return '%s * %s'%(-d1[0],d1[2]),d1[2],')/(%s)'%(-d1[0])
<ide> if d1[2]==d2[2] and d1[2] in args:
<ide> a = d2[0] - d1[0]
<del> if not a: return `b`,None,None
<add> if not a: return repr(b),None,None
<ide> if b<0: return '%s * %s - %s'%(a,d1[2],-b),d2[2],'+%s)/(%s)'%(-b,a)
<ide> elif b: return '%s * %s + %s'%(a,d1[2],b),d2[2],'-%s)/(%s)'%(b,a)
<ide> else: return '%s * %s'%(a,d1[2]),d2[2],')/(%s)'%(a)
<ide> def _get_depend_dict(name, vars, deps):
<ide> if w not in words:
<ide> words.append(w)
<ide> else:
<del> outmess('_get_depend_dict: no dependence info for %s\n' % (`name`))
<add> outmess('_get_depend_dict: no dependence info for %s\n' % (repr(name)))
<ide> words = []
<ide> deps[name] = words
<ide> return words
<ide> def get_parameters(vars, global_params={}):
<ide> except Exception as msg:
<ide> params[n] = v
<ide> #print params
<del> outmess('get_parameters: got "%s" on %s\n' % (msg,`v`))
<add> outmess('get_parameters: got "%s" on %s\n' % (msg,repr(v)))
<ide> if isstring(vars[n]) and type(params[n]) is type(0):
<ide> params[n] = chr(params[n])
<ide> nl = n.lower()
<ide> if nl!=n:
<ide> params[nl] = params[n]
<ide> else:
<ide> print(vars[n])
<del> outmess('get_parameters:parameter %s does not have value?!\n'%(`n`))
<add> outmess('get_parameters:parameter %s does not have value?!\n'%(repr(n)))
<ide> return params
<ide>
<ide> def _eval_length(length,params):
<ide> def analyzevars(block):
<ide> for l in implicitrules[ln0][k]:
<ide> vars[n]=setattrspec(vars[n],l)
<ide> elif n in block['args']:
<del> outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n'%(`n`,block['name']))
<add> outmess('analyzevars: typespec of variable %s is not defined in routine %s.\n'%(repr(n),block['name']))
<ide>
<ide> if 'charselector' in vars[n]:
<ide> if 'len' in vars[n]['charselector']:
<ide> def analyzevars(block):
<ide> if ispure: vars[n]=setattrspec(vars[n],'pure')
<ide> if isrec: vars[n]=setattrspec(vars[n],'recursive')
<ide> else:
<del> outmess('analyzevars: prefix (%s) were not used\n'%`block['prefix']`)
<add> outmess('analyzevars: prefix (%s) were not used\n'%repr(block['prefix']))
<ide> if not block['block'] in ['module','pythonmodule','python module','block data']:
<ide> if 'commonvars' in block:
<ide> neededvars=copy.copy(block['args']+block['commonvars'])
<ide> def _ensure_exprdict(r):
<ide> return {'typespec':'real'}
<ide> if type(r) is type(0j):
<ide> return {'typespec':'complex'}
<del> assert type(r) is type({}),`r`
<add> assert type(r) is type({}),repr(r)
<ide> return r
<ide>
<ide> def determineexprtype(expr,vars,rules={}):
<ide> def determineexprtype(expr,vars,rules={}):
<ide> m=determineexprtype_re_2.match(expr)
<ide> if m:
<ide> if 'name' in m.groupdict() and m.group('name'):
<del> outmess('determineexprtype: selected kind types not supported (%s)\n'%`expr`)
<add> outmess('determineexprtype: selected kind types not supported (%s)\n'%repr(expr))
<ide> return {'typespec':'integer'}
<ide> m = determineexprtype_re_3.match(expr)
<ide> if m:
<ide> if 'name' in m.groupdict() and m.group('name'):
<del> outmess('determineexprtype: selected kind types not supported (%s)\n'%`expr`)
<add> outmess('determineexprtype: selected kind types not supported (%s)\n'%repr(expr))
<ide> return {'typespec':'real'}
<ide> for op in ['+','-','*','/']:
<ide> for e in [x.strip() for x in markoutercomma(expr,comma=op).split('@'+op+'@')]:
<ide> def determineexprtype(expr,vars,rules={}):
<ide> if expr[0] in '\'"':
<ide> return {'typespec':'character','charselector':{'*':'*'}}
<ide> if not t:
<del> outmess('determineexprtype: could not determine expressions (%s) type.\n'%(`expr`))
<add> outmess('determineexprtype: could not determine expressions (%s) type.\n'%(repr(expr)))
<ide> return t
<ide>
<ide> ######
<ide> def crack2fortran(block):
<ide> elif l=='-m':
<ide> f3=1
<ide> elif l[0]=='-':
<del> errmess('Unknown option %s\n'%`l`)
<add> errmess('Unknown option %s\n'%repr(l))
<ide> elif f2:
<ide> f2=0
<ide> pyffilename=l
<ide> def crack2fortran(block):
<ide>
<ide> postlist=crackfortran(files,funcs)
<ide> if pyffilename:
<del> outmess('Writing fortran code to file %s\n'%`pyffilename`,0)
<add> outmess('Writing fortran code to file %s\n'%repr(pyffilename),0)
<ide> pyf=crack2fortran(postlist)
<ide> f=open(pyffilename,'w')
<ide> f.write(pyf)
<ide><path>numpy/f2py/f2py2e.py
<ide> def scaninputline(inputline):
<ide> elif l[:15] in '--include-paths':
<ide> f7=1
<ide> elif l[0]=='-':
<del> errmess('Unknown option %s\n'%`l`)
<add> errmess('Unknown option %s\n'%repr(l))
<ide> sys.exit()
<ide> elif f2: f2=0;signsfile=l
<ide> elif f3: f3=0;modulename=l
<ide> def run_main(comline_list):
<ide> if postlist[i]['block']!='python module':
<ide> if 'python module' not in options:
<ide> errmess('Tip: If your original code is Fortran source then you must use -m option.\n')
<del> raise TypeError('All blocks must be python module blocks but got %s'%(`postlist[i]['block']`))
<add> raise TypeError('All blocks must be python module blocks but got %s'%(repr(postlist[i]['block'])))
<ide> auxfuncs.debugoptions=options['debug']
<ide> f90mod_rules.options=options
<ide> auxfuncs.wrapfuncs=options['wrapfuncs']
<ide> def run_compile():
<ide> for s in del_list:
<ide> i = flib_flags.index(s)
<ide> del flib_flags[i]
<del> assert len(flib_flags)<=2,`flib_flags`
<add> assert len(flib_flags)<=2,repr(flib_flags)
<ide>
<ide> _reg5 = re.compile(r'[-][-](verbose)')
<ide> setup_flags = [_m for _m in sys.argv[1:] if _reg5.match(_m)]
<ide> def run_compile():
<ide> i = get_info(n)
<ide> if not i:
<ide> outmess('No %s resources found in system'\
<del> ' (try `f2py --help-link`)\n' % (`n`))
<add> ' (try `f2py --help-link`)\n' % (repr(n)))
<ide> dict_append(ext_args,**i)
<ide>
<ide> ext = Extension(**ext_args)
<ide><path>numpy/f2py/rules.py
<ide> def buildmodule(m,um):
<ide> elif k in cfuncs.commonhooks:
<ide> c=cfuncs.commonhooks[k]
<ide> else:
<del> errmess('buildmodule: unknown need %s.\n'%(`k`));continue
<add> errmess('buildmodule: unknown need %s.\n'%(repr(k)));continue
<ide> code[n].append(c)
<ide> mod_rules.append(code)
<ide> for r in mod_rules:
<ide> def buildapi(rout):
<ide> if not isintent_hide(var[a]):
<ide> if not isoptional(var[a]):
<ide> nth=nth+1
<del> vrd['nth']=`nth`+stnd[nth%10]+' argument'
<add> vrd['nth']=repr(nth)+stnd[nth%10]+' argument'
<ide> else:
<ide> nthk=nthk+1
<del> vrd['nth']=`nthk`+stnd[nthk%10]+' keyword'
<add> vrd['nth']=repr(nthk)+stnd[nthk%10]+' keyword'
<ide> else: vrd['nth']='hidden'
<ide> savevrd[a]=vrd
<ide> for r in _rules:
<ide><path>numpy/f2py/tests/test_array_from_pyobj.py
<ide> def __init__(self,typ,dims,intent,obj):
<ide> # arr.dtypechar may be different from typ.dtypechar
<ide> self.arr = wrap.call(typ.type_num,dims,intent.flags,obj)
<ide>
<del> assert_(isinstance(self.arr, ndarray),`type(self.arr)`)
<add> assert_(isinstance(self.arr, ndarray),repr(type(self.arr)))
<ide>
<ide> self.arr_attr = wrap.array_attrs(self.arr)
<ide>
<ide> if len(dims)>1:
<ide> if self.intent.is_intent('c'):
<ide> assert_(intent.flags & wrap.F2PY_INTENT_C)
<del> assert_(not self.arr.flags['FORTRAN'],`self.arr.flags,getattr(obj,'flags',None)`)
<add> assert_(not self.arr.flags['FORTRAN'],repr((self.arr.flags,getattr(obj,'flags',None))))
<ide> assert_(self.arr.flags['CONTIGUOUS'])
<ide> assert_(not self.arr_attr[6] & wrap.FORTRAN)
<ide> else:
<ide> def __init__(self,typ,dims,intent,obj):
<ide> return
<ide>
<ide> if intent.is_intent('cache'):
<del> assert_(isinstance(obj,ndarray),`type(obj)`)
<add> assert_(isinstance(obj,ndarray),repr(type(obj)))
<ide> self.pyarr = array(obj).reshape(*dims).copy()
<ide> else:
<ide> self.pyarr = array(array(obj,
<ide> dtype = typ.dtypechar).reshape(*dims),
<ide> order=self.intent.is_intent('c') and 'C' or 'F')
<ide> assert_(self.pyarr.dtype == typ, \
<del> `self.pyarr.dtype,typ`)
<add> repr((self.pyarr.dtype,typ)))
<ide> assert_(self.pyarr.flags['OWNDATA'], (obj, intent))
<ide> self.pyarr_attr = wrap.array_attrs(self.pyarr)
<ide>
<ide> def __init__(self,typ,dims,intent,obj):
<ide> assert_(self.arr_attr[2]==self.pyarr_attr[2]) # dimensions
<ide> if self.arr_attr[1]<=1:
<ide> assert_(self.arr_attr[3]==self.pyarr_attr[3],\
<del> `self.arr_attr[3],self.pyarr_attr[3],self.arr.tostring(),self.pyarr.tostring()`) # strides
<add> repr((self.arr_attr[3],self.pyarr_attr[3],self.arr.tostring(),self.pyarr.tostring()))) # strides
<ide> assert_(self.arr_attr[5][-2:]==self.pyarr_attr[5][-2:],\
<del> `self.arr_attr[5],self.pyarr_attr[5]`) # descr
<add> repr((self.arr_attr[5],self.pyarr_attr[5]))) # descr
<ide> assert_(self.arr_attr[6]==self.pyarr_attr[6],\
<del> `self.arr_attr[6],self.pyarr_attr[6],flags2names(0*self.arr_attr[6]-self.pyarr_attr[6]),flags2names(self.arr_attr[6]),intent`) # flags
<add> repr((self.arr_attr[6],self.pyarr_attr[6],flags2names(0*self.arr_attr[6]-self.pyarr_attr[6]),flags2names(self.arr_attr[6]),intent))) # flags
<ide>
<ide> if intent.is_intent('cache'):
<ide> assert_(self.arr_attr[5][3]>=self.type.elsize,\
<del> `self.arr_attr[5][3],self.type.elsize`)
<add> repr((self.arr_attr[5][3],self.type.elsize)))
<ide> else:
<ide> assert_(self.arr_attr[5][3]==self.type.elsize,\
<del> `self.arr_attr[5][3],self.type.elsize`)
<add> repr((self.arr_attr[5][3],self.type.elsize)))
<ide> assert_(self.arr_equal(self.pyarr,self.arr))
<ide>
<ide> if isinstance(self.obj,ndarray):
<ide> def test_in_from_2casttype(self):
<ide> obj = array(self.num2seq,dtype=t.dtype)
<ide> a = self.array([len(self.num2seq)],intent.in_,obj)
<ide> if t.elsize==self.type.elsize:
<del> assert_(a.has_shared_memory(),`self.type.dtype,t.dtype`)
<add> assert_(a.has_shared_memory(),repr((self.type.dtype,t.dtype)))
<ide> else:
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_inout_2seq(self):
<ide> obj = array(self.num2seq,dtype=self.type.dtype)
<ide> def test_in_copy_from_2casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = array(self.num2seq,dtype=t.dtype)
<ide> a = self.array([len(self.num2seq)],intent.in_.copy,obj)
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_c_in_from_23seq(self):
<ide> a = self.array([len(self.num23seq),len(self.num23seq[0])],
<ide> def test_in_from_23casttype(self):
<ide> obj = array(self.num23seq,dtype=t.dtype)
<ide> a = self.array([len(self.num23seq),len(self.num23seq[0])],
<ide> intent.in_,obj)
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_f_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = array(self.num23seq,dtype=t.dtype,order='F')
<ide> a = self.array([len(self.num23seq),len(self.num23seq[0])],
<ide> intent.in_,obj)
<ide> if t.elsize==self.type.elsize:
<del> assert_(a.has_shared_memory(),`t.dtype`)
<add> assert_(a.has_shared_memory(),repr(t.dtype))
<ide> else:
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_c_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = array(self.num23seq,dtype=t.dtype)
<ide> a = self.array([len(self.num23seq),len(self.num23seq[0])],
<ide> intent.in_.c,obj)
<ide> if t.elsize==self.type.elsize:
<del> assert_(a.has_shared_memory(),`t.dtype`)
<add> assert_(a.has_shared_memory(),repr(t.dtype))
<ide> else:
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_f_copy_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = array(self.num23seq,dtype=t.dtype,order='F')
<ide> a = self.array([len(self.num23seq),len(self.num23seq[0])],
<ide> intent.in_.copy,obj)
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_c_copy_in_from_23casttype(self):
<ide> for t in self.type.cast_types():
<ide> obj = array(self.num23seq,dtype=t.dtype)
<ide> a = self.array([len(self.num23seq),len(self.num23seq[0])],
<ide> intent.in_.c.copy,obj)
<del> assert_(not a.has_shared_memory(),`t.dtype`)
<add> assert_(not a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> def test_in_cache_from_2casttype(self):
<ide> for t in self.type.all_types():
<ide> def test_in_cache_from_2casttype(self):
<ide> obj = array(self.num2seq,dtype=t.dtype)
<ide> shape = (len(self.num2seq),)
<ide> a = self.array(shape,intent.in_.c.cache,obj)
<del> assert_(a.has_shared_memory(),`t.dtype`)
<add> assert_(a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> a = self.array(shape,intent.in_.cache,obj)
<del> assert_(a.has_shared_memory(),`t.dtype`)
<add> assert_(a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> obj = array(self.num2seq,dtype=t.dtype,order='F')
<ide> a = self.array(shape,intent.in_.c.cache,obj)
<del> assert_(a.has_shared_memory(),`t.dtype`)
<add> assert_(a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> a = self.array(shape,intent.in_.cache,obj)
<del> assert_(a.has_shared_memory(),`t.dtype`)
<add> assert_(a.has_shared_memory(),repr(t.dtype))
<ide>
<ide> try:
<ide> a = self.array(shape,intent.in_.cache,obj[::-1])
<ide> def test_inplace(self):
<ide> assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS'])
<ide> shape = obj.shape
<ide> a = self.array(shape,intent.inplace,obj)
<del> assert_(obj[1][2]==a.arr[1][2],`obj,a.arr`)
<add> assert_(obj[1][2]==a.arr[1][2],repr((obj,a.arr)))
<ide> a.arr[1][2]=54
<del> assert_(obj[1][2]==a.arr[1][2]==array(54,dtype=self.type.dtype),`obj,a.arr`)
<add> assert_(obj[1][2]==a.arr[1][2]==array(54,dtype=self.type.dtype),repr((obj,a.arr)))
<ide> assert_(a.arr is obj)
<ide> assert_(obj.flags['FORTRAN']) # obj attributes are changed inplace!
<ide> assert_(not obj.flags['CONTIGUOUS'])
<ide> def test_inplace_from_casttype(self):
<ide> assert_(not obj.flags['FORTRAN'] and obj.flags['CONTIGUOUS'])
<ide> shape = obj.shape
<ide> a = self.array(shape,intent.inplace,obj)
<del> assert_(obj[1][2]==a.arr[1][2],`obj,a.arr`)
<add> assert_(obj[1][2]==a.arr[1][2],repr((obj,a.arr)))
<ide> a.arr[1][2]=54
<del> assert_(obj[1][2]==a.arr[1][2]==array(54,dtype=self.type.dtype),`obj,a.arr`)
<add> assert_(obj[1][2]==a.arr[1][2]==array(54,dtype=self.type.dtype),repr((obj,a.arr)))
<ide> assert_(a.arr is obj)
<ide> assert_(obj.flags['FORTRAN']) # obj attributes are changed inplace!
<ide> assert_(not obj.flags['CONTIGUOUS'])
<ide><path>numpy/f2py/tests/test_assumed_shape.py
<ide> class TestAssumedShapeSumExample(util.F2PyTest):
<ide> @dec.slow
<ide> def test_all(self):
<ide> r = self.module.fsum([1,2])
<del> assert_(r==3,`r`)
<add> assert_(r==3,repr(r))
<ide> r = self.module.sum([1,2])
<del> assert_(r==3,`r`)
<add> assert_(r==3,repr(r))
<ide> r = self.module.sum_with_use([1,2])
<del> assert_(r==3,`r`)
<add> assert_(r==3,repr(r))
<ide>
<ide> r = self.module.mod.sum([1,2])
<del> assert_(r==3,`r`)
<add> assert_(r==3,repr(r))
<ide> r = self.module.mod.fsum([1,2])
<del> assert_(r==3,`r`)
<add> assert_(r==3,repr(r))
<ide>
<ide> if __name__ == "__main__":
<ide> import nose
<ide><path>numpy/f2py/tests/test_callback.py
<ide> def fun(): return a
<ide> def check_function(self, name):
<ide> t = getattr(self.module, name)
<ide> r = t(lambda : 4)
<del> assert_( r==4,`r`)
<add> assert_( r==4,repr(r))
<ide> r = t(lambda a:5,fun_extra_args=(6,))
<del> assert_( r==5,`r`)
<add> assert_( r==5,repr(r))
<ide> r = t(lambda a:a,fun_extra_args=(6,))
<del> assert_( r==6,`r`)
<add> assert_( r==6,repr(r))
<ide> r = t(lambda a:5+a,fun_extra_args=(7,))
<del> assert_( r==12,`r`)
<add> assert_( r==12,repr(r))
<ide> r = t(lambda a:math.degrees(a),fun_extra_args=(math.pi,))
<del> assert_( r==180,`r`)
<add> assert_( r==180,repr(r))
<ide> r = t(math.degrees,fun_extra_args=(math.pi,))
<del> assert_( r==180,`r`)
<add> assert_( r==180,repr(r))
<ide>
<ide> r = t(self.module.func, fun_extra_args=(6,))
<del> assert_( r==17,`r`)
<add> assert_( r==17,repr(r))
<ide> r = t(self.module.func0)
<del> assert_( r==11,`r`)
<add> assert_( r==11,repr(r))
<ide> r = t(self.module.func0._cpointer)
<del> assert_( r==11,`r`)
<add> assert_( r==11,repr(r))
<ide> class A(object):
<ide> def __call__(self):
<ide> return 7
<ide> def mth(self):
<ide> return 9
<ide> a = A()
<ide> r = t(a)
<del> assert_( r==7,`r`)
<add> assert_( r==7,repr(r))
<ide> r = t(a.mth)
<del> assert_( r==9,`r`)
<add> assert_( r==9,repr(r))
<ide>
<ide> if __name__ == "__main__":
<ide> import nose
<ide><path>numpy/f2py/tests/test_return_character.py
<ide> def check_function(self, t):
<ide> tname = t.__doc__.split()[0]
<ide> if tname in ['t0','t1','s0','s1']:
<ide> assert_( t(23)==asbytes('2'))
<del> r = t('ab');assert_( r==asbytes('a'),`r`)
<del> r = t(array('ab'));assert_( r==asbytes('a'),`r`)
<del> r = t(array(77,'u1'));assert_( r==asbytes('M'),`r`)
<add> r = t('ab');assert_( r==asbytes('a'),repr(r))
<add> r = t(array('ab'));assert_( r==asbytes('a'),repr(r))
<add> r = t(array(77,'u1'));assert_( r==asbytes('M'),repr(r))
<ide> #assert_(_raises(ValueError, t, array([77,87])))
<ide> #assert_(_raises(ValueError, t, array(77)))
<ide> elif tname in ['ts','ss']:
<del> assert_( t(23)==asbytes('23 '),`t(23)`)
<add> assert_( t(23)==asbytes('23 '),repr(t(23)))
<ide> assert_( t('123456789abcdef')==asbytes('123456789a'))
<ide> elif tname in ['t5','s5']:
<del> assert_( t(23)==asbytes('23 '),`t(23)`)
<del> assert_( t('ab')==asbytes('ab '),`t('ab')`)
<add> assert_( t(23)==asbytes('23 '),repr(t(23)))
<add> assert_( t('ab')==asbytes('ab '),repr(t('ab')))
<ide> assert_( t('123456789abcdef')==asbytes('12345'))
<ide> else:
<ide> raise NotImplementedError
<ide><path>numpy/f2py/tests/test_return_complex.py
<ide> def check_function(self, t):
<ide>
<ide> try:
<ide> r = t(10l**400)
<del> assert_( `r` in ['(inf+0j)','(Infinity+0j)'],`r`)
<add> assert_( repr(r) in ['(inf+0j)','(Infinity+0j)'],repr(r))
<ide> except OverflowError:
<ide> pass
<ide>
<ide><path>numpy/f2py/tests/test_return_integer.py
<ide>
<ide> class TestReturnInteger(util.F2PyTest):
<ide> def check_function(self, t):
<del> assert_( t(123)==123,`t(123)`)
<add> assert_( t(123)==123,repr(t(123)))
<ide> assert_( t(123.6)==123)
<ide> assert_( t(123l)==123)
<ide> assert_( t('123')==123)
<ide><path>numpy/f2py/tests/test_return_logical.py
<ide>
<ide> class TestReturnLogical(util.F2PyTest):
<ide> def check_function(self, t):
<del> assert_( t(True)==1,`t(True)`)
<del> assert_( t(False)==0,`t(False)`)
<add> assert_( t(True)==1,repr(t(True)))
<add> assert_( t(False)==0,repr(t(False)))
<ide> assert_( t(0)==0)
<ide> assert_( t(None)==0)
<ide> assert_( t(0.0)==0)
<ide><path>numpy/f2py/tests/test_return_real.py
<ide> def check_function(self, t):
<ide>
<ide> try:
<ide> r = t(10l**400)
<del> assert_( `r` in ['inf','Infinity'],`r`)
<add> assert_( repr(r) in ['inf','Infinity'],repr(r))
<ide> except OverflowError:
<ide> pass
<ide>
<ide><path>numpy/f2py/tests/test_size.py
<ide> class TestSizeSumExample(util.F2PyTest):
<ide> @dec.slow
<ide> def test_all(self):
<ide> r = self.module.foo([[1,2]])
<del> assert_equal(r, [3],`r`)
<add> assert_equal(r, [3],repr(r))
<ide>
<ide> r = self.module.foo([[1,2],[3,4]])
<del> assert_equal(r, [3,7],`r`)
<add> assert_equal(r, [3,7],repr(r))
<ide>
<ide> r = self.module.foo([[1,2],[3,4],[5,6]])
<del> assert_equal(r, [3,7,11],`r`)
<add> assert_equal(r, [3,7,11],repr(r))
<ide>
<ide> @dec.slow
<ide> def test_transpose(self):
<ide> r = self.module.trans([[1,2]])
<del> assert_equal(r, [[1],[2]],`r`)
<add> assert_equal(r, [[1],[2]],repr(r))
<ide>
<ide> r = self.module.trans([[1,2,3],[4,5,6]])
<del> assert_equal(r, [[1,4],[2,5],[3,6]],`r`)
<add> assert_equal(r, [[1,4],[2,5],[3,6]],repr(r))
<ide>
<ide> @dec.slow
<ide> def test_flatten(self):
<ide> r = self.module.flatten([[1,2]])
<del> assert_equal(r, [1,2],`r`)
<add> assert_equal(r, [1,2],repr(r))
<ide>
<ide> r = self.module.flatten([[1,2,3],[4,5,6]])
<del> assert_equal(r, [1,2,3,4,5,6],`r`)
<add> assert_equal(r, [1,2,3,4,5,6],repr(r))
<ide>
<ide> if __name__ == "__main__":
<ide> import nose
<ide><path>numpy/f2py/use_rules.py
<ide> def buildusevar(name,realname,vars,usemodulename):
<ide> nummap={0:'Ro',1:'Ri',2:'Rii',3:'Riii',4:'Riv',5:'Rv',6:'Rvi',7:'Rvii',8:'Rviii',9:'Rix'}
<ide> vrd['texnamename']=name
<ide> for i in nummap.keys():
<del> vrd['texnamename']=vrd['texnamename'].replace(`i`,nummap[i])
<add> vrd['texnamename']=vrd['texnamename'].replace(repr(i),nummap[i])
<ide> if hasnote(vars[realname]): vrd['note']=vars[realname]['note']
<ide> rd=dictappend({},vrd)
<ide> var=vars[realname]
<ide><path>numpy/ma/mrecords.py
<ide> def _getformats(data):
<ide> obj = np.asarray(obj)
<ide> formats += _typestr[obj.dtype.type]
<ide> if issubclass(obj.dtype.type, ntypes.flexible):
<del> formats += `obj.itemsize`
<add> formats += repr(obj.itemsize)
<ide> formats += ','
<ide> return formats[:-1]
<ide>
<ide> def _checknames(descr, names=None):
<ide> elif isinstance(names, str):
<ide> new_names = names.split(',')
<ide> else:
<del> raise NameError("illegal input names %s" % `names`)
<add> raise NameError("illegal input names %s" % repr(names))
<ide> nnames = len(new_names)
<ide> if nnames < ndescr:
<ide> new_names += default_names[nnames:]
<ide><path>numpy/testing/utils.py
<ide> def assert_string_equal(actual, desired):
<ide> import difflib
<ide>
<ide> if not isinstance(actual, str) :
<del> raise AssertionError(`type(actual)`)
<add> raise AssertionError(repr(type(actual)))
<ide> if not isinstance(desired, str):
<del> raise AssertionError(`type(desired)`)
<add> raise AssertionError(repr(type(desired)))
<ide> if re.match(r'\A'+desired+r'\Z', actual, re.M): return
<ide> diff = list(difflib.Differ().compare(actual.splitlines(1), desired.splitlines(1)))
<ide> diff_list = []
<ide> def assert_string_equal(actual, desired):
<ide> l.append(d2)
<ide> d2 = diff.pop(0)
<ide> if not d2.startswith('+ ') :
<del> raise AssertionError(`d2`)
<add> raise AssertionError(repr(d2))
<ide> l.append(d2)
<ide> d3 = diff.pop(0)
<ide> if d3.startswith('? '):
<ide> def assert_string_equal(actual, desired):
<ide> continue
<ide> diff_list.extend(l)
<ide> continue
<del> raise AssertionError(`d1`)
<add> raise AssertionError(repr(d1))
<ide> if not diff_list:
<ide> return
<ide> msg = 'Differences in strings:\n%s' % (''.join(diff_list)).rstrip()
<ide><path>tools/py3tool.py
<ide> 'imports2',
<ide> 'print',
<ide> 'dict',
<add> 'repr',
<ide> ]
<ide>
<ide> skip_fixes= []
| 22
|
PHP
|
PHP
|
add support for tinyint/smallint to mysql schema
|
c77e646c623105d8e94204c93ec480c1c68f561e
|
<ide><path>src/Database/Schema/MysqlSchema.php
<ide> protected function _convertColumn($column)
<ide> if (strpos($col, 'bigint') !== false || $col === 'bigint') {
<ide> return ['type' => 'biginteger', 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<add> if ($col === 'tinyint') {
<add> return ['type' => 'tinyint', 'length' => $length, 'unsigned' => $unsigned];
<add> }
<add> if ($col === 'smallint') {
<add> return ['type' => 'smallint', 'length' => $length, 'unsigned' => $unsigned];
<add> }
<ide> if (in_array($col, ['int', 'integer', 'tinyint', 'smallint', 'mediumint'])) {
<ide> return ['type' => 'integer', 'length' => $length, 'unsigned' => $unsigned];
<ide> }
<ide> public function columnSql(TableSchema $schema, $name)
<ide> $nativeJson = $this->_driver->supportsNativeJson();
<ide>
<ide> $typeMap = [
<add> 'tinyint' => ' TINYINT',
<add> 'smallint' => ' SMALLINT',
<ide> 'integer' => ' INTEGER',
<ide> 'biginteger' => ' BIGINT',
<ide> 'boolean' => ' BOOLEAN',
<ide> public function columnSql(TableSchema $schema, $name)
<ide> break;
<ide> }
<ide> }
<del> $hasLength = ['integer', 'string'];
<add> $hasLength = ['integer', 'smallint', 'tinyint', 'string'];
<ide> if (in_array($data['type'], $hasLength, true) && isset($data['length'])) {
<ide> $out .= '(' . (int)$data['length'] . ')';
<ide> }
<ide> public function columnSql(TableSchema $schema, $name)
<ide> $out .= '(' . (int)$data['length'] . ',' . (int)$data['precision'] . ')';
<ide> }
<ide>
<del> $hasUnsigned = ['float', 'decimal', 'integer', 'biginteger'];
<add> $hasUnsigned = ['float', 'decimal', 'tinyint', 'smallint', 'integer', 'biginteger'];
<ide> if (in_array($data['type'], $hasUnsigned, true) &&
<ide> isset($data['unsigned']) && $data['unsigned'] === true
<ide> ) {
<ide><path>src/Database/Schema/TableSchema.php
<ide> class TableSchema
<ide> 'text' => [
<ide> 'collate' => null,
<ide> ],
<add> 'tinyint' => [
<add> 'unsigned' => null,
<add> ],
<add> 'smallint' => [
<add> 'unsigned' => null,
<add> ],
<ide> 'integer' => [
<ide> 'unsigned' => null,
<ide> 'autoIncrement' => null,
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> public static function convertColumnProvider()
<ide> ],
<ide> [
<ide> 'TINYINT(2)',
<del> ['type' => 'integer', 'length' => 2, 'unsigned' => false]
<add> ['type' => 'tinyint', 'length' => 2, 'unsigned' => false]
<add> ],
<add> [
<add> 'TINYINT(3)',
<add> ['type' => 'tinyint', 'length' => 3, 'unsigned' => false]
<add> ],
<add> [
<add> 'TINYINT(3) UNSIGNED',
<add> ['type' => 'tinyint', 'length' => 3, 'unsigned' => true]
<add> ],
<add> [
<add> 'SMALLINT(4)',
<add> ['type' => 'smallint', 'length' => 4, 'unsigned' => false]
<add> ],
<add> [
<add> 'SMALLINT(4) UNSIGNED',
<add> ['type' => 'smallint', 'length' => 4, 'unsigned' => true]
<ide> ],
<ide> [
<ide> 'INTEGER(11)',
<ide> public static function columnSqlProvider()
<ide> '`body` LONGBLOB NOT NULL'
<ide> ],
<ide> // Integers
<add> [
<add> 'post_id',
<add> ['type' => 'tinyint', 'length' => 2],
<add> '`post_id` TINYINT(2)'
<add> ],
<add> [
<add> 'post_id',
<add> ['type' => 'tinyint', 'length' => 2, 'unsigned' => true],
<add> '`post_id` TINYINT(2) UNSIGNED'
<add> ],
<add> [
<add> 'post_id',
<add> ['type' => 'smallint', 'length' => 4],
<add> '`post_id` SMALLINT(4)'
<add> ],
<add> [
<add> 'post_id',
<add> ['type' => 'smallint', 'length' => 4, 'unsigned' => true],
<add> '`post_id` SMALLINT(4) UNSIGNED'
<add> ],
<ide> [
<ide> 'post_id',
<ide> ['type' => 'integer', 'length' => 11],
| 3
|
Python
|
Python
|
fix minor typos in numpy/core/fromnumeric.py
|
0d749ad8dd9468a44ef1e6ed67f22eab03646d53
|
<ide><path>numpy/core/fromnumeric.py
<ide> def reshape(a, newshape, order='C'):
<ide> Notes
<ide> -----
<ide> It is not always possible to change the shape of an array without
<del> copying the data. If you want an error to be raise if the data is copied,
<add> copying the data. If you want an error to be raised when the data is copied,
<ide> you should assign the new shape to the shape attribute of the array::
<ide>
<ide> >>> a = np.zeros((10, 2))
<del> # A transpose make the array non-contiguous
<add> # A transpose makes the array non-contiguous
<ide> >>> b = a.T
<ide> # Taking a view makes it possible to modify the shape without modifying
<ide> # the initial object.
| 1
|
Python
|
Python
|
fix typo and grammar errors
|
59353708cdead64da92d29d6f38b970d7a8e0586
|
<ide><path>official/core/base_task.py
<ide> def logging_dir(self) -> str:
<ide> def initialize(self, model: tf.keras.Model):
<ide> """A callback function used as CheckpointManager's init_fn.
<ide>
<del> This function will be called when no checkpoint found for the model.
<add> This function will be called when no checkpoint is found for the model.
<ide> If there is a checkpoint, the checkpoint will be loaded and this function
<ide> will not be called. You can use this callback function to load a pretrained
<ide> checkpoint, saved under a directory other than the model_dir.
<ide> def initialize(self, model: tf.keras.Model):
<ide>
<ide> @abc.abstractmethod
<ide> def build_model(self) -> tf.keras.Model:
<del> """Creates the model architecture.
<add> """Creates model architecture.
<ide>
<ide> Returns:
<ide> A model instance.
<ide> def build_losses(self, labels, model_outputs, aux_losses=None) -> tf.Tensor:
<ide> Args:
<ide> labels: optional label tensors.
<ide> model_outputs: a nested structure of output tensors.
<del> aux_losses: auxiliarly loss tensors, i.e. `losses` in keras.Model.
<add> aux_losses: auxiliary loss tensors, i.e. `losses` in keras.Model.
<ide>
<ide> Returns:
<ide> The total loss tensor.
<ide> def train_step(self,
<ide> return logs
<ide>
<ide> def validation_step(self, inputs, model: tf.keras.Model, metrics=None):
<del> """Validatation step.
<add> """Validation step.
<ide>
<ide> With distribution strategies, this method runs on devices.
<ide>
| 1
|
Python
|
Python
|
add another test for ssl stuff
|
3ef5655840334aededf70ffb5d44f754ba41459f
|
<ide><path>test/test_httplib_ssl.py
<ide> import unittest
<ide> import os.path
<ide>
<add>import mock
<add>
<ide> import libcloud.security
<ide> from libcloud.httplib_ssl import LibcloudHTTPSConnection
<ide>
<ide> class TestHttpLibSSLTests(unittest.TestCase):
<ide> def setUp(self):
<ide> self.httplib_object = LibcloudHTTPSConnection('foo.bar')
<ide>
<del> def test_connect(self):
<del> pass
<add> def test_verify_hostname(self):
<add> cert1 = {'notAfter': 'Feb 16 16:54:50 2013 GMT',
<add> 'subject': ((('countryName', 'US'),),
<add> (('stateOrProvinceName', 'Delaware'),),
<add> (('localityName', 'Wilmington'),),
<add> (('organizationName', 'Python Software Foundation'),),
<add> (('organizationalUnitName', 'SSL'),),
<add> (('commonName', 'somemachine.python.org'),))}
<add>
<add> cert2 = {'notAfter': 'Feb 16 16:54:50 2013 GMT',
<add> 'subject': ((('countryName', 'US'),),
<add> (('stateOrProvinceName', 'Delaware'),),
<add> (('localityName', 'Wilmington'),),
<add> (('organizationName', 'Python Software Foundation'),),
<add> (('organizationalUnitName', 'SSL'),),
<add> (('commonName', 'somemachine.python.org'),)),
<add> 'subjectAltName': ((('DNS', 'foo.alt.name')),
<add> (('DNS', 'foo.alt.name.1')))}
<add>
<add> self.assertFalse(self.httplib_object._verify_hostname(
<add> hostname='invalid', cert=cert1))
<add> self.assertTrue(self.httplib_object._verify_hostname(
<add> hostname='somemachine.python.org', cert=cert1))
<add>
<add> self.assertFalse(self.httplib_object._verify_hostname(
<add> hostname='invalid', cert=cert2))
<add> self.assertTrue(self.httplib_object._verify_hostname(
<add> hostname='foo.alt.name.1', cert=cert2))
<ide>
<ide> def test_get_subject_alt_names(self):
<ide> cert1 = {'notAfter': 'Feb 16 16:54:50 2013 GMT',
| 1
|
Javascript
|
Javascript
|
add htmlbars component hook
|
549416bf59908c3844ace759478aca943bbe9496
|
<ide><path>packages/ember-htmlbars/lib/hooks.js
<add>import Ember from "ember-metal/core";
<ide> import { lookupHelper } from "ember-htmlbars/system/lookup-helper";
<ide> import { sanitizeOptionsForHelper } from "ember-htmlbars/system/sanitize-for-helper";
<ide>
<ide> export function content(morph, path, view, params, hash, options, env) {
<ide> return helper.call(view, params, hash, options, env);
<ide> }
<ide>
<add>export function component(morph, tagName, view, hash, options, env) {
<add> var params = [];
<add> var helper = lookupHelper(tagName, view, env);
<add>
<add> Ember.assert('You specified `' + tagName + '` in your template, but a component for `' + tagName + '` could not be found.', !!helper);
<add>
<add> streamifyArgs(view, params, hash, options, env);
<add> sanitizeOptionsForHelper(options);
<add> return helper.call(view, params, hash, options, env);
<add>}
<add>
<ide> export function element(element, path, view, params, hash, options, env) { //jshint ignore:line
<ide> var helper = lookupHelper(path, view, env);
<ide>
<ide><path>packages/ember-htmlbars/lib/main.js
<ide> import Ember from "ember-metal/core";
<del>import { content, element, subexpr } from "ember-htmlbars/hooks";
<add>import {
<add> content,
<add> element,
<add> subexpr,
<add> component
<add>} from "ember-htmlbars/hooks";
<ide> import { DOMHelper } from "morph";
<ide> import template from "ember-htmlbars/system/template";
<ide> import compile from "ember-htmlbars/system/compile";
<ide> export var defaultEnv = {
<ide> hooks: {
<ide> content: content,
<ide> element: element,
<del> subexpr: subexpr
<add> subexpr: subexpr,
<add> component: component
<ide> },
<ide>
<ide> helpers: helpers
<ide><path>packages/ember-htmlbars/tests/hooks/component_test.js
<add>import ComponentLookup from "ember-views/component_lookup";
<add>import Container from "container";
<add>import EmberView from "ember-views/views/view";
<add>import run from "ember-metal/run_loop";
<add>import compile from "ember-htmlbars/system/compile";
<add>
<add>var view, container;
<add>
<add>function generateContainer() {
<add> var container = new Container();
<add>
<add> container.optionsForType('template', { instantiate: false });
<add> container.register('component-lookup:main', ComponentLookup);
<add>
<add> return container;
<add>}
<add>
<add>function appendView(view) {
<add> run(function() { view.appendTo('#qunit-fixture'); });
<add>}
<add>
<add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) {
<add>
<add>QUnit.module("ember-htmlbars: component hook", {
<add> setup: function() {
<add> container = generateContainer();
<add> },
<add>
<add> teardown: function(){
<add> if (view) {
<add> run(view, view.destroy);
<add> }
<add> }
<add>});
<add>
<add>test("component is looked up from the container", function() {
<add> container.register('template:components/foo-bar', compile('yippie!'));
<add>
<add> view = EmberView.create({
<add> container: container,
<add> template: compile("<foo-bar />")
<add> });
<add>
<add> appendView(view);
<add>
<add> equal(view.$().text(), 'yippie!', 'component was looked up and rendered');
<add>});
<add>
<add>test("asserts if component is not found", function() {
<add> view = EmberView.create({
<add> container: container,
<add> template: compile("<foo-bar />")
<add> });
<add>
<add> expectAssertion(function() {
<add> appendView(view);
<add> }, 'You specified `foo-bar` in your template, but a component for `foo-bar` could not be found.');
<add>});
<add>}
| 3
|
Text
|
Text
|
add question marks
|
afeb4768189d5e303af53c6db060deb78a5fb25c
|
<ide><path>docs/i18n-languages/spanish/README.md
<ide> Nuestra comunidad además cuenta con:
<ide>
<ide> ### [Unite a nuestra comunidad aquí](https://www.freecodecamp.org/signin).
<ide>
<del>### Encontraste un bug?
<add>### Informar bugs y problemas
<ide>
<del>Si piensas que encontraste un bug, primero lee [How to Report a Bug](https://www.freecodecamp.org/forum/t/how-to-report-a-bug/19543) y sigue las instrucciones. Si estás seguro de que es un bug nuevo y has confirmado que afecta a otras personas, continúa y crea un ticket en GitHub. Asegúrate de incluir tanta información como sea posible para poder reproducir el bug..
<add>Si piensas que encontraste un bug, primero lee [How to Report a Bug](https://www.freecodecamp.org/forum/t/how-to-report-a-bug/19543) y sigue las instrucciones. Si estás seguro de que es un bug nuevo y has confirmado que afecta a otras personas, continúa y crea un ticket en GitHub. Asegúrate de incluir tanta información como sea posible para poder reproducir el bug.
<ide>
<del>### Encontraste un problema de seguridad?
<add>### Informar problemas de seguridad
<ide>
<ide> Por favor, no crees un ticket en GitHub sobre problemas de seguridad. En cambio, envía un correo electrónico a `security @ freecodecamp.org` y lo veremos de inmediato.
<ide>
| 1
|
Ruby
|
Ruby
|
drop object allocation during routes setup
|
559e7f94506ac3c3e8553f9510f43923e7c804da
|
<ide><path>actionpack/lib/action_dispatch/journey/nodes/node.rb
<ide> def initialize(left)
<ide> end
<ide>
<ide> def each(&block)
<del> Visitors::Each.new(block).accept(self)
<add> Visitors::Each::INSTANCE.accept(self, block)
<ide> end
<ide>
<ide> def to_s
<del> Visitors::String.new.accept(self)
<add> Visitors::String::INSTANCE.accept(self, '')
<ide> end
<ide>
<ide> def to_dot
<del> Visitors::Dot.new.accept(self)
<add> Visitors::Dot::INSTANCE.accept(self)
<ide> end
<ide>
<ide> def to_sym
<ide><path>actionpack/lib/action_dispatch/journey/visitors.rb
<ide> def visit_DOT(n); terminal(n); end
<ide> end
<ide> end
<ide>
<add> class FunctionalVisitor # :nodoc:
<add> DISPATCH_CACHE = {}
<add>
<add> def accept(node, seed)
<add> visit(node, seed)
<add> end
<add>
<add> def visit node, seed
<add> send(DISPATCH_CACHE[node.type], node, seed)
<add> end
<add>
<add> def binary(node, seed)
<add> visit(node.right, visit(node.left, seed))
<add> end
<add> def visit_CAT(n, seed); binary(n, seed); end
<add>
<add> def nary(node, seed)
<add> node.children.inject(seed) { |s, c| visit(c, s) }
<add> end
<add> def visit_OR(n, seed); nary(n, seed); end
<add>
<add> def unary(node, seed)
<add> visit(node.left, seed)
<add> end
<add> def visit_GROUP(n, seed); unary(n, seed); end
<add> def visit_STAR(n, seed); unary(n, seed); end
<add>
<add> def terminal(node, seed); seed; end
<add> def visit_LITERAL(n, seed); terminal(n, seed); end
<add> def visit_SYMBOL(n, seed); terminal(n, seed); end
<add> def visit_SLASH(n, seed); terminal(n, seed); end
<add> def visit_DOT(n, seed); terminal(n, seed); end
<add>
<add> instance_methods(false).each do |pim|
<add> next unless pim =~ /^visit_(.*)$/
<add> DISPATCH_CACHE[$1.to_sym] = pim
<add> end
<add> end
<add>
<ide> class FormatBuilder < Visitor # :nodoc:
<ide> def accept(node); Journey::Format.new(super); end
<ide> def terminal(node); [node.left]; end
<ide> def visit_SYMBOL(n)
<ide> end
<ide>
<ide> # Loop through the requirements AST
<del> class Each < Visitor # :nodoc:
<del> attr_reader :block
<del>
<del> def initialize(block)
<del> @block = block
<del> end
<del>
<del> def visit(node)
<add> class Each < FunctionalVisitor # :nodoc:
<add> def visit(node, block)
<ide> block.call(node)
<ide> super
<ide> end
<add>
<add> INSTANCE = new
<ide> end
<ide>
<del> class String < Visitor # :nodoc:
<add> class String < FunctionalVisitor # :nodoc:
<ide> private
<ide>
<del> def binary(node)
<del> [visit(node.left), visit(node.right)].join
<add> def binary(node, seed)
<add> visit(node.right, visit(node.left, seed))
<ide> end
<ide>
<del> def nary(node)
<del> node.children.map { |c| visit(c) }.join '|'
<add> def nary(node, seed)
<add> last_child = node.children.last
<add> node.children.inject(seed) { |s, c|
<add> string = visit(c, s)
<add> string << "|".freeze unless last_child == c
<add> string
<add> }
<ide> end
<ide>
<del> def terminal(node)
<del> node.left
<add> def terminal(node, seed)
<add> seed + node.left
<ide> end
<ide>
<del> def visit_GROUP(node)
<del> "(#{visit(node.left)})"
<add> def visit_GROUP(node, seed)
<add> visit(node.left, seed << "(".freeze) << ")".freeze
<ide> end
<add>
<add> INSTANCE = new
<ide> end
<ide>
<del> class Dot < Visitor # :nodoc:
<add> class Dot < FunctionalVisitor # :nodoc:
<ide> def initialize
<ide> @nodes = []
<ide> @edges = []
<ide> end
<ide>
<del> def accept(node)
<add> def accept(node, seed = [[], []])
<ide> super
<add> nodes, edges = seed
<ide> <<-eodot
<ide> digraph parse_tree {
<ide> size="8,5"
<ide> node [shape = none];
<ide> edge [dir = none];
<del> #{@nodes.join "\n"}
<del> #{@edges.join("\n")}
<add> #{nodes.join "\n"}
<add> #{edges.join("\n")}
<ide> }
<ide> eodot
<ide> end
<ide>
<ide> private
<ide>
<del> def binary(node)
<del> node.children.each do |c|
<del> @edges << "#{node.object_id} -> #{c.object_id};"
<del> end
<add> def binary(node, seed)
<add> seed.last.concat node.children.map { |c|
<add> "#{node.object_id} -> #{c.object_id};"
<add> }
<ide> super
<ide> end
<ide>
<del> def nary(node)
<del> node.children.each do |c|
<del> @edges << "#{node.object_id} -> #{c.object_id};"
<del> end
<add> def nary(node, seed)
<add> seed.last.concat node.children.map { |c|
<add> "#{node.object_id} -> #{c.object_id};"
<add> }
<ide> super
<ide> end
<ide>
<del> def unary(node)
<del> @edges << "#{node.object_id} -> #{node.left.object_id};"
<add> def unary(node, seed)
<add> seed.last << "#{node.object_id} -> #{node.left.object_id};"
<ide> super
<ide> end
<ide>
<del> def visit_GROUP(node)
<del> @nodes << "#{node.object_id} [label=\"()\"];"
<add> def visit_GROUP(node, seed)
<add> seed.first << "#{node.object_id} [label=\"()\"];"
<ide> super
<ide> end
<ide>
<del> def visit_CAT(node)
<del> @nodes << "#{node.object_id} [label=\"○\"];"
<add> def visit_CAT(node, seed)
<add> seed.first << "#{node.object_id} [label=\"○\"];"
<ide> super
<ide> end
<ide>
<del> def visit_STAR(node)
<del> @nodes << "#{node.object_id} [label=\"*\"];"
<add> def visit_STAR(node, seed)
<add> seed.first << "#{node.object_id} [label=\"*\"];"
<ide> super
<ide> end
<ide>
<del> def visit_OR(node)
<del> @nodes << "#{node.object_id} [label=\"|\"];"
<add> def visit_OR(node, seed)
<add> seed.first << "#{node.object_id} [label=\"|\"];"
<ide> super
<ide> end
<ide>
<del> def terminal(node)
<add> def terminal(node, seed)
<ide> value = node.left
<ide>
<del> @nodes << "#{node.object_id} [label=\"#{value}\"];"
<add> seed.first << "#{node.object_id} [label=\"#{value}\"];"
<add> seed
<ide> end
<add> INSTANCE = new
<ide> end
<ide> end
<ide> end
| 2
|
Python
|
Python
|
avoid deadlock when rescheduling task
|
6d110b565a505505351d1ff19592626fb24e4516
|
<ide><path>airflow/models/taskinstance.py
<ide> from airflow.utils.platform import getuser
<ide> from airflow.utils.retries import run_with_db_retries
<ide> from airflow.utils.session import NEW_SESSION, create_session, provide_session
<del>from airflow.utils.sqlalchemy import ExtendedJSON, UtcDateTime
<add>from airflow.utils.sqlalchemy import ExtendedJSON, UtcDateTime, with_row_locks
<ide> from airflow.utils.state import DagRunState, State, TaskInstanceState
<ide> from airflow.utils.timeout import timeout
<ide>
<ide> def _handle_reschedule(
<ide> # Don't record reschedule request in test mode
<ide> if test_mode:
<ide> return
<add>
<add> from airflow.models.dagrun import DagRun # Avoid circular import
<add>
<ide> self.refresh_from_db(session)
<ide>
<ide> self.end_date = timezone.utcnow()
<ide> self.set_duration()
<ide>
<add> # Lock DAG run to be sure not to get into a deadlock situation when trying to insert
<add> # TaskReschedule which apparently also creates lock on corresponding DagRun entity
<add> with_row_locks(
<add> session.query(DagRun).filter_by(
<add> dag_id=self.dag_id,
<add> run_id=self.run_id,
<add> ),
<add> session=session,
<add> ).one()
<add>
<ide> # Log reschedule request
<ide> session.add(
<ide> TaskReschedule(
| 1
|
Javascript
|
Javascript
|
fix cancellation error on build master.
|
c282e7ea8e5f714bfc19127c71edd4a6711534d1
|
<ide><path>test/specs/instance.spec.js
<ide> describe('instance', function () {
<ide> });
<ide> });
<ide>
<del> it('should make an http request with url instead of baseURL', function () {
<add> it('should make an http request with url instead of baseURL', function (done) {
<ide> var instance = axios.create({
<ide> url: 'https://api.example.com'
<ide> });
| 1
|
Ruby
|
Ruby
|
fix failure to retain value of allow_concurrency
|
37b0b36918f14519b28326057bba38ca6fcfbd3b
|
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb
<ide> def set_connection(spec) #:nodoc:
<ide> if spec.kind_of?(ActiveRecord::ConnectionAdapters::AbstractAdapter)
<ide> active_connections[active_connection_name] = spec
<ide> elsif spec.kind_of?(ActiveRecord::Base::ConnectionSpecification)
<del> self.set_connection ActiveRecord::Base.send(spec.adapter_method, spec.config)
<add> config = spec.config.reverse_merge(:allow_concurrency => ActiveRecord::Base.allow_concurrency)
<add> self.set_connection ActiveRecord::Base.send(spec.adapter_method, config)
<ide> else
<ide> raise ConnectionNotEstablished
<ide> end
<ide><path>activerecord/lib/active_record/connection_adapters/abstract/connection_specification.rb
<ide> class << self
<ide> # multi-threaded access of the connection pools hash is synchronized.
<ide> def allow_concurrency=(flag)
<ide> if @@allow_concurrency != flag
<add> @@allow_concurrency = flag
<ide> if flag
<ide> self.connection_pools_lock = Monitor.new
<ide> else
| 2
|
PHP
|
PHP
|
add test for carbon deserialization
|
0466d4aadfa8268db4fc8fd97e18b36247769192
|
<ide><path>tests/Support/SupportCarbonTest.php
<ide> public function testSetStateReturnsCorrectType()
<ide>
<ide> $this->assertInstanceOf(Carbon::class, $carbon);
<ide> }
<add>
<add> public function testDeserializationOccursCorrectly()
<add> {
<add> $carbon = new Carbon('2017-06-27 13:14:15.000000');
<add> $serialized = 'return '.var_export($carbon, true).';';
<add> $deserialized = eval($serialized);
<add>
<add> $this->assertInstanceOf(Carbon::class, $deserialized);
<add> }
<ide> }
| 1
|
Javascript
|
Javascript
|
add cache expire time to test server
|
74926995431cf3f0204fb8385d0b1fa45294d84a
|
<ide><path>test/test.js
<ide> function startServer() {
<ide> server.host = host;
<ide> server.port = options.port;
<ide> server.root = '..';
<add> server.cacheExpirationTime = 3600;
<ide> server.start();
<ide> }
<ide>
<ide><path>test/webserver.js
<ide> function WebServer() {
<ide> this.port = 8000;
<ide> this.server = null;
<ide> this.verbose = false;
<add> this.cacheExpirationTime = 0;
<ide> this.disableRangeRequests = false;
<ide> this.hooks = {
<ide> 'GET': [],
<ide> WebServer.prototype = {
<ide> }
<ide>
<ide> var disableRangeRequests = this.disableRangeRequests;
<add> var cacheExpirationTime = this.cacheExpirationTime;
<ide>
<ide> var filePath;
<ide> fs.realpath(path.join(this.root, pathPart), checkFile);
<ide> WebServer.prototype = {
<ide> }
<ide> res.setHeader('Content-Type', contentType);
<ide> res.setHeader('Content-Length', fileSize);
<add> if (cacheExpirationTime > 0) {
<add> var expireTime = new Date();
<add> expireTime.setSeconds(expireTime.getSeconds() + cacheExpirationTime);
<add> res.setHeader('Expires', expireTime.toUTCString());
<add> }
<ide> res.writeHead(200);
<ide>
<ide> stream.pipe(res);
| 2
|
Java
|
Java
|
use andexpectall() in example in mockmvc javadoc
|
38f94799f4bd53b68a1409b02152b1d960e1f838
|
<ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/MockMvc.java
<ide> * MockMvc mockMvc = webAppContextSetup(wac).build();
<ide> *
<ide> * mockMvc.perform(get("/form"))
<del> * .andExpect(status().isOk())
<del> * .andExpect(content().contentType("text/html"))
<del> * .andExpect(forwardedUrl("/WEB-INF/layouts/main.jsp"));
<add> * .andExpectAll(
<add> * status().isOk(),
<add> * content().contentType("text/html"),
<add> * forwardedUrl("/WEB-INF/layouts/main.jsp")
<add> * );
<ide> * </pre>
<ide> *
<ide> * @author Rossen Stoyanchev
| 1
|
Javascript
|
Javascript
|
test strict mode
|
e83e9b8c233e465e05850f26813c943efce96f83
|
<ide><path>lib/FunctionModuleTemplatePlugin.js
<ide> FunctionModuleTemplatePlugin.prototype.apply = function(moduleTemplate) {
<ide> defaultArguments.push("__webpack_require__");
<ide> }
<ide> source.add("/***/ function(" + defaultArguments.concat(module.arguments || []).join(", ") + ") {\n\n");
<del> if(module.strict) source.add("\"use strict\";\n");
<add> if(module.strict) source.add(this.outputOptions.sourcePrefix + "\"use strict\";\n");
<ide> source.add(new PrefixSource(this.outputOptions.sourcePrefix, moduleSource));
<ide> source.add("\n\n/***/ }");
<ide> return source;
<ide><path>lib/dependencies/HarmonyExportDependencyParserPlugin.js
<ide> module.exports = AbstractPlugin.create({
<ide> dep.loc = statement.loc;
<ide> this.state.current.addDependency(dep);
<ide> this.state.module.meta.harmonyModule = true;
<add> this.state.module.strict = true;
<ide> return true;
<ide> },
<ide> "export import": function(statement, source) {
<ide> module.exports = AbstractPlugin.create({
<ide> this.state.current.addDependency(dep);
<ide> this.state.lastHarmoryImport = dep;
<ide> this.state.module.meta.harmonyModule = true;
<add> this.state.module.strict = true;
<ide> return true;
<ide> },
<ide> "export expression": function(statement, expr) {
<ide> var dep = new HarmonyExportExpressionDependency(this.state.module, expr.range, statement.range);
<ide> dep.loc = statement.loc;
<ide> this.state.current.addDependency(dep);
<add> this.state.module.strict = true;
<ide> return true;
<ide> },
<ide> "export declaration": function() {},
<ide><path>lib/dependencies/HarmonyImportDependencyParserPlugin.js
<ide> module.exports = AbstractPlugin.create({
<ide> dep.loc = statement.loc;
<ide> this.state.current.addDependency(dep);
<ide> this.state.lastHarmonyImport = dep;
<add> this.state.module.strict = true;
<ide> return true;
<ide> },
<ide> "import specifier": function(statement, source, id, name) {
<ide><path>test/cases/parsing/strict-mode/abc.js
<add>export default function() {
<add> return typeof this;
<add>};
<ide>\ No newline at end of file
<ide><path>test/cases/parsing/strict-mode/index.js
<add>"use strict";
<add>define(["./abc"], function(abc) {
<add> // AMD is used here, because it adds stuff to the top of the code
<add> // we make sure to keep strict mode
<add>
<add> var a = abc.default;
<add>
<add> it("should keep strict mode", function() {
<add> var x = (function() {
<add> return this;
<add> })();
<add> (typeof x).should.be.eql("undefined");
<add> });
<add>
<add> it("should import modules in strict mode", function() {
<add> a().should.be.eql("undefined");
<add> });
<add>
<add>});
<ide>\ No newline at end of file
| 5
|
Java
|
Java
|
add missing package-info
|
c991aa9a78fc6a8cab6714f42e2ec30d7329344a
|
<ide><path>spring-core/src/main/java/org/springframework/aot/package-info.java
<add>/**
<add> * Core package for Spring AOT infrastructure.
<add> */
<add>@NonNullApi
<add>@NonNullFields
<add>package org.springframework.aot;
<add>
<add>import org.springframework.lang.NonNullApi;
<add>import org.springframework.lang.NonNullFields;
| 1
|
PHP
|
PHP
|
fix additional failing tests
|
a830750838c5b8328587974a98bab77560e61742
|
<ide><path>lib/Cake/Test/TestCase/Network/Email/SmtpTransportTest.php
<ide> public function testRcpt() {
<ide> * @return void
<ide> */
<ide> public function testRcptWithReturnPath() {
<del> $email = new CakeEmail();
<add> $email = new Email();
<ide> $email->from('noreply@cakephp.org', 'CakePHP Test');
<ide> $email->to('cake@cakephp.org', 'CakePHP');
<ide> $email->returnPath('pleasereply@cakephp.org', 'CakePHP Return');
<ide><path>lib/Cake/Test/TestCase/Network/RequestTest.php
<ide> public function testBaseUrlAndWebrootWithModRewrite() {
<ide> Configure::write('App.baseUrl', false);
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
<del> $_SERVER['PHP_SELF'] = '/urlencode me/app/webroot/index.php';
<add> $_SERVER['PHP_SELF'] = '/urlencode me/App/webroot/index.php';
<ide> $_SERVER['PATH_INFO'] = '/posts/view/1';
<ide>
<ide> $request = Request::createFromGlobals();
<ide> public function testBaseUrlAndWebrootWithModRewrite() {
<ide> $this->assertEquals('posts/view/1', $request->url);
<ide>
<ide> $_SERVER['DOCUMENT_ROOT'] = '/cake/repo/branches';
<del> $_SERVER['PHP_SELF'] = '/1.2.x.x/app/webroot/index.php';
<add> $_SERVER['PHP_SELF'] = '/1.2.x.x/App/webroot/index.php';
<ide> $_SERVER['PATH_INFO'] = '/posts/view/1';
<ide>
<ide> $request = Request::createFromGlobals();
| 2
|
PHP
|
PHP
|
fix typo in validator class comment
|
808543844d473bd63a252fad142408d9ec4bb290
|
<ide><path>system/validator.php
<ide> protected function has_rule($attribute, $rules)
<ide> }
<ide>
<ide> /**
<del> * Extrac the rule name and parameters from a rule.
<add> * Extract the rule name and parameters from a rule.
<ide> *
<ide> * @param string $rule
<ide> * @return array
| 1
|
Python
|
Python
|
remove hack by only importing when configured
|
5881436bea688ee49175192452dec18fad4ba9b2
|
<ide><path>airflow/executors/__init__.py
<ide> from airflow.executors.local_executor import LocalExecutor
<ide> from airflow.executors.sequential_executor import SequentialExecutor
<ide>
<del># TODO Fix this emergency fix
<del>try:
<del> from airflow.executors.celery_executor import CeleryExecutor
<del>except:
<del> pass
<del>try:
<del> from airflow.contrib.executors.mesos_executor import MesosExecutor
<del>except:
<del> pass
<del>
<ide> from airflow.utils import AirflowException
<ide>
<ide> _EXECUTOR = configuration.get('core', 'EXECUTOR')
<ide>
<ide> if _EXECUTOR == 'LocalExecutor':
<ide> DEFAULT_EXECUTOR = LocalExecutor()
<ide> elif _EXECUTOR == 'CeleryExecutor':
<add> from airflow.executors.celery_executor import CeleryExecutor
<ide> DEFAULT_EXECUTOR = CeleryExecutor()
<ide> elif _EXECUTOR == 'SequentialExecutor':
<ide> DEFAULT_EXECUTOR = SequentialExecutor()
<ide> elif _EXECUTOR == 'MesosExecutor':
<add> from airflow.contrib.executors.mesos_executor import MesosExecutor
<ide> DEFAULT_EXECUTOR = MesosExecutor()
<ide> else:
<ide> # Loading plugins
| 1
|
Javascript
|
Javascript
|
remove misleading comment
|
f065c87bcf65c3ffa50980bba5562ed7159b86db
|
<ide><path>lib/events.js
<ide> EventEmitter.prototype.emit = function() {
<ide> }
<ide> };
<ide>
<del>// EventEmitter is defined in src/node_events.cc
<del>// EventEmitter.prototype.emit() is also defined there.
<ide> EventEmitter.prototype.addListener = function(type, listener) {
<ide> if ('function' !== typeof listener) {
<ide> throw new Error('addListener only takes instances of Function');
| 1
|
Javascript
|
Javascript
|
fix small typo in the help text
|
b6719b247d3b650fc46ed65d9e62af9a0dd6afa3
|
<ide><path>Libraries/CustomComponents/Navigator/Navigator.js
<ide> var Navigator = React.createClass({
<ide> * (route, routeStack) => Navigator.SceneConfigs.FloatFromRight
<ide> * ```
<ide> *
<del> * Available scene configutation options are:
<add> * Available scene configuration options are:
<ide> *
<ide> * - Navigator.SceneConfigs.PushFromRight (default)
<ide> * - Navigator.SceneConfigs.FloatFromRight
| 1
|
Text
|
Text
|
add translation kr/threejs-voxel-geometry.md
|
d30d88526bb8c4017084e473d2a125225590bc8e
|
<ide><path>threejs/lessons/kr/threejs-voxel-geometry.md
<add>Title: Three.js 복셀 Geometry
<add>Description: 마인크래프트 같은 복셀 geometry를 만드는 법을 알아봅니다
<add>TOC: 복셀 Geometry(마인크래프트) 만들기
<add>
<add>※ [복셀](https://ko.wikipedia.org/wiki/%EB%B3%B5%EC%85%80): Voxel, 볼륨(volume, 부피)과 픽셀(pixel)의 합성어로, 마인크래프트의 블록처럼 부피가 있는 픽셀을 말합니다. 역주.
<add>
<add>이 주제는 꽤 많은 커뮤니티에 공통적으로 올라오는 주제입니다. "마인크래프트 블록 같은 복셀을 어떻게 만들 수 있나요?"라는 것이죠.
<add>
<add>대부분의 초심자가 이를 정육면체 geometry를 만들고 각 복셀의 위치에 mesh를 따로 만들어 구현하려고 합니다. 재미삼아 이 방식으로 한 번 구현해보죠. 먼저 256x256x256짜리 복셀 큐브를 만들기 위해 16,777,216개의 요소를 가진 `Uint8Array`를 만듭니다.
<add>
<add>```js
<add>const cellSize = 256;
<add>const cell = new Uint8Array(cellSize * cellSize * cellSize);
<add>```
<add>
<add>그리고 사인(sine) 함수 곡선으로 언덕을 한 겹 만듭니다.
<add>
<add>```js
<add>for (let y = 0; y < cellSize; ++y) {
<add> for (let z = 0; z < cellSize; ++z) {
<add> for (let x = 0; x < cellSize; ++x) {
<add> const height = (Math.sin(x / cellSize * Math.PI * 4) + Math.sin(z / cellSize * Math.PI * 6)) * 20 + cellSize / 2;
<add> if (height > y && height < y + 1) {
<add> const offset = y * cellSize * cellSize +
<add> z * cellSize +
<add> x;
<add> cell[offset] = 1;
<add> }
<add> }
<add> }
<add>}
<add>```
<add>
<add>다음으로 모든 블럭을 돌면서 0이 아닐 경우 정육면체를 새로 만듭니다.
<add>
<add>```js
<add>const geometry = new THREE.BoxBufferGeometry(1, 1, 1);
<add>const material = new THREE.MeshPhongMaterial({ color: 'green' });
<add>
<add>for (let y = 0; y < cellSize; ++y) {
<add> for (let z = 0; z < cellSize; ++z) {
<add> for (let x = 0; x < cellSize; ++x) {
<add> const offset = y * cellSize * cellSize +
<add> z * cellSize +
<add> x;
<add> const block = cell[offset];
<add> const mesh = new THREE.Mesh(geometry, material);
<add> mesh.position.set(x, y, z);
<add> scene.add(mesh);
<add> }
<add> }
<add>}
<add>```
<add>
<add>나머지 코드는 [불필요한 렌더링 제거하기](threejs-rendering-on-demand.html)에서 가져왔습니다.
<add>
<add>{{{example url="../threejs-voxel-geometry-separate-cubes.html" }}}
<add>
<add>처음 초기화하는 데도 시간이 오래 걸리고 카메라를 움직이면 굉장히 버벅일 겁니다. [다중 요소 최적화하기](threejs-optimize-lots-of-objects.html)의 경우와 마찬가지로 너무 많은 물체가 있는 탓이죠. 256x256, 육면체가 총 65,536개나 있으니 그럴 만합니다.
<add>
<add>[geometry를 합치면](threejs-rendering-on-demand.html) 이 문제를 해결할 수 있습니다. 내친김에 언덕 한 겹이 아니라 땅까지 복셀을 채워보도록 하죠. 반복문을 다음처럼 수정해 빈 공간을 전부 채우도록 합니다.
<add>
<add>```js
<add>for (let y = 0; y < cellSize; ++y) {
<add> for (let z = 0; z < cellSize; ++z) {
<add> for (let x = 0; x < cellSize; ++x) {
<add> const height = (Math.sin(x / cellSize * Math.PI * 4) + Math.sin(z / cellSize * Math.PI * 6)) * 20 + cellSize / 2;
<add>- if (height > y && height < y + 1) {
<add>+ if (height < y + 1) {
<add> const offset = y * cellSize * cellSize +
<add> z * cellSize +
<add> x;
<add> cell[offset] = 1;
<add> }
<add> }
<add> }
<add>}
<add>```
<add>
<add>테스트를 돌려봤더니 잠시 멈췄다가 *out of memery* 오류가 뜹니다 😅.
<add>
<add>몇 가지 문제가 있을 테지만 현재 가장 큰 문제는 전혀 볼 일이 없는 정육면체 안쪽도 렌더링한다는 겁니다.
<add>
<add>쉽게 설명해 복셀로 이루어진 3x2x2짜리 육면체가 있다고 해보죠. 각 복셀을 합치면 아래와 같은 모습이 될 겁니다.
<add>
<add><div class="spread">
<add> <div data-diagram="mergedCubes" style="height: 300px;"></div>
<add></div>
<add>
<add>문제를 해결하려면 아래와 같은 형태로 구현해야 하죠.
<add>
<add><div class="spread">
<add> <div data-diagram="culledCubes" style="height: 300px;"></div>
<add></div>
<add>
<add>위쪽 예제에는 복셀 사이에 면들이 있습니다. 밖에서는 전혀 볼 일이 없기에 불필요한 것들이죠. 거기다 각 복셀 사이에는 면이 하나도 아니고 마주 보는 면당 하나씩, 총 두 개가 있습니다. 이 역시 낭비이죠. 복셀에 이런 면들이 많아질수록 성능은 처참해질 겁니다.
<add>
<add>이쯤에서 그냥 말해야겠네요. 단순히 geometry를 합쳐버려서는 이 문제를 해결할 수 없습니다. 복셀이 서로 마주 본다면 해당 면을 만들지 않도록 직접 복셀을 만들어야 하죠.
<add>
<add>다른 문제는 크기가 너무 크다는 겁니다. 256x256x256이면 16MB 정도로 메모리 점유율이 꽤 큰 편에 속하죠. 특히 빈 공간은 아무것도 있을 필요가 없습니다. 복셀의 숫자도 약 천육백만 개가 넘으니 연산이 버거울 만합니다.
<add>
<add>한 가지 해결 방법은 영역을 작은 영역으로 쪼개는 겁니다. 아무것도 없는 영역에는 메모리를 할당할 필요가 없으니, 32x32x32 크기(32KB)의 영역을 만들어 안에 요소가 있는 영역만 렌더링하도록 하겠습니다. 이 32x32x32 영역은 편의상 "cell"이라고 부르도록 하죠.
<add>
<add>먼저 복셀 데이터를 관리할 클래스를 만듭니다.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(cellSize) {
<add> this.cellSize = cellSize;
<add> }
<add>}
<add>```
<add>
<add>다음으로 각 cell의 geometry를 생성하는 메서드를 작성합니다. 이 메서드는 cell의 위치값을 인자로 받는데, 쉽게 말해 (x축 0-31, y축 0-31, z축 0-31)을 포함하는 복셀들을 생성하려면 (0,0,0)을 넘겨주면 됩니다. (x축 32-63, y축 0-31, z축 0-31)을 포함하는 복셀을 생성하려면 (1,0,0)을 넘겨주면 되죠.
<add>
<add>그리고 이웃하는 복셀을 검사해야 합니다. 일단 해당 위치의 복셀값을 반환하는 `getVoxel` 메서드가 있다고 가정합시다. 예를 들어 cell의 크기가 32일 경우, 이 메서드에 (35,0,0)을 넘겨주면 (1,0,0) 쪽 cell을 찾아 해당 cell의 (3,0,0)에 위치한 복셀값을 반환할 겁니다. 다른 cell의 복셀이라고 해도 이웃 복셀을 얼마든지 찾아낼 수 있다는 이야기죠.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(cellSize) {
<add> this.cellSize = cellSize;
<add> }
<add>+ generateGeometryDataForCell(cellX, cellY, cellZ) {
<add>+ const { cellSize } = this;
<add>+ const startX = cellX * cellSize;
<add>+ const startY = cellY * cellSize;
<add>+ const startZ = cellZ * cellSize;
<add>+
<add>+ for (let y = 0; y < cellSize; ++y) {
<add>+ const voxelY = startY + y;
<add>+ for (let z = 0; z < cellSize; ++z) {
<add>+ const voxelZ = startZ + z;
<add>+ for (let x = 0; x < cellSize; ++x) {
<add>+ const voxelX = startX + x;
<add>+ const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
<add>+ if (voxel) {
<add>+ for (const { dir } of VoxelWorld.faces) {
<add>+ const neighbor = this.getVoxel(
<add>+ voxelX + dir[0],
<add>+ voxelY + dir[1],
<add>+ voxelZ + dir[2]);
<add>+ if (!neighbor) {
<add>+ // 이 복셀은 이 방향에 이웃하는 복셀이 없으므로
<add>+ // 이쪽에 면을 만듭니다.
<add>+ }
<add>+ }
<add>+ }
<add>+ }
<add>+ }
<add>+ }
<add>+ }
<add>}
<add>
<add>+VoxelWorld.faces = [
<add>+ { // 왼쪽
<add>+ dir: [ -1, 0, 0, ],
<add>+ },
<add>+ { // 오른쪽
<add>+ dir: [ 1, 0, 0, ],
<add>+ },
<add>+ { // 아래
<add>+ dir: [ 0, -1, 0, ],
<add>+ },
<add>+ { // 위
<add>+ dir: [ 0, 1, 0, ],
<add>+ },
<add>+ { // 뒤
<add>+ dir: [ 0, 0, -1, ],
<add>+ },
<add>+ { // 앞
<add>+ dir: [ 0, 0, 1, ],
<add>+ },
<add>+];
<add>```
<add>
<add>이제 언제 면을 만들 기준이 생겼으니 한 번 면들을 만들어봅시다.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(cellSize) {
<add> this.cellSize = cellSize;
<add> }
<add> generateGeometryDataForCell(cellX, cellY, cellZ) {
<add> const { cellSize } = this;
<add>+ const positions = [];
<add>+ const normals = [];
<add>+ const indices = [];
<add> const startX = cellX * cellSize;
<add> const startY = cellY * cellSize;
<add> const startZ = cellZ * cellSize;
<add>
<add> for (let y = 0; y < cellSize; ++y) {
<add> const voxelY = startY + y;
<add> for (let z = 0; z < cellSize; ++z) {
<add> const voxelZ = startZ + z;
<add> for (let x = 0; x < cellSize; ++x) {
<add> const voxelX = startX + x;
<add> const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
<add> if (voxel) {
<add>- for (const { dir } of VoxelWorld.faces) {
<add>+ for (const { dir, corners } of VoxelWorld.faces) {
<add> const neighbor = this.getVoxel(
<add> voxelX + dir[0],
<add> voxelY + dir[1],
<add> voxelZ + dir[2]);
<add> if (!neighbor) {
<add>+ // 이 복셀은 이 방향에 이웃하는 복셀이 없으므로
<add>+ // 이쪽에 면을 만듭니다.
<add>+ const ndx = positions.length / 3;
<add>+ for (const pos of corners) {
<add>+ positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
<add>+ normals.push(...dir);
<add>+ }
<add>+ indices.push(
<add>+ ndx, ndx + 1, ndx + 2,
<add>+ ndx + 2, ndx + 1, ndx + 3,
<add>+ );
<add> }
<add> }
<add> }
<add> }
<add> }
<add> }
<add>+ return {
<add>+ positions,
<add>+ normals,
<add>+ indices,
<add> };
<add> }
<add>}
<add>
<add>VoxelWorld.faces = [
<add> { // 왼쪽
<add> dir: [ -1, 0, 0, ],
<add>+ corners: [
<add>+ [ 0, 1, 0 ],
<add>+ [ 0, 0, 0 ],
<add>+ [ 0, 1, 1 ],
<add>+ [ 0, 0, 1 ],
<add>+ ],
<add> },
<add> { // 오른쪽
<add> dir: [ 1, 0, 0, ],
<add>+ corners: [
<add>+ [ 1, 1, 1 ],
<add>+ [ 1, 0, 1 ],
<add>+ [ 1, 1, 0 ],
<add>+ [ 1, 0, 0 ],
<add>+ ],
<add> },
<add> { // 아래
<add> dir: [ 0, -1, 0, ],
<add>+ corners: [
<add>+ [ 1, 0, 1 ],
<add>+ [ 0, 0, 1 ],
<add>+ [ 1, 0, 0 ],
<add>+ [ 0, 0, 0 ],
<add>+ ],
<add> },
<add> { // 위
<add> dir: [ 0, 1, 0, ],
<add>+ corners: [
<add>+ [ 0, 1, 1 ],
<add>+ [ 1, 1, 1 ],
<add>+ [ 0, 1, 0 ],
<add>+ [ 1, 1, 0 ],
<add>+ ],
<add> },
<add> { // 뒤
<add> dir: [ 0, 0, -1, ],
<add>+ corners: [
<add>+ [ 1, 0, 0 ],
<add>+ [ 0, 0, 0 ],
<add>+ [ 1, 1, 0 ],
<add>+ [ 0, 1, 0 ],
<add>+ ],
<add> },
<add> { // 앞
<add> dir: [ 0, 0, 1, ],
<add>+ corners: [
<add>+ [ 0, 0, 1 ],
<add>+ [ 1, 0, 1 ],
<add>+ [ 0, 1, 1 ],
<add>+ [ 1, 1, 1 ],
<add>+ ],
<add> },
<add>];
<add>```
<add>
<add>위 코드는 기본 geometry 데이터를 만들어줍니다. 이제 `getVoxel` 메서드만 만들면 되겠네요. 일단 약간의 하드코딩을 더해 cell을 만듭니다.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(cellSize) {
<add> this.cellSize = cellSize;
<add>+ this.cell = new Uint8Array(cellSize * cellSize * cellSize);
<add> }
<add>+ getCellForVoxel(x, y, z) {
<add>+ const { cellSize } = this;
<add>+ const cellX = Math.floor(x / cellSize);
<add>+ const cellY = Math.floor(y / cellSize);
<add>+ const cellZ = Math.floor(z / cellSize);
<add>+ if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
<add>+ return null
<add>+ }
<add>+ return this.cell;
<add>+ }
<add>+ getVoxel(x, y, z) {
<add>+ const cell = this.getCellForVoxel(x, y, z);
<add>+ if (!cell) {
<add>+ return 0;
<add>+ }
<add>+ const { cellSize } = this;
<add>+ const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add>+ const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
<add>+ const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
<add>+ const voxelOffset = voxelY * cellSize * cellSize +
<add>+ voxelZ * cellSize +
<add>+ voxelX;
<add>+ return cell[voxelOffset];
<add>+ }
<add> generateGeometryDataForCell(cellX, cellY, cellZ) {
<add>
<add> ...
<add>}
<add>```
<add>
<add>딱히 문제는 없어보입니다. 데이터를 지정할 수 있는 `setVoxel` 메서드도 만들도록 하죠.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(cellSize) {
<add> this.cellSize = cellSize;
<add> this.cell = new Uint8Array(cellSize * cellSize * cellSize);
<add> }
<add> getCellForVoxel(x, y, z) {
<add> const { cellSize } = this;
<add> const cellX = Math.floor(x / cellSize);
<add> const cellY = Math.floor(y / cellSize);
<add> const cellZ = Math.floor(z / cellSize);
<add> if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
<add> return null
<add> }
<add> return this.cell;
<add> }
<add>+ setVoxel(x, y, z, v) {
<add>+ let cell = this.getCellForVoxel(x, y, z);
<add>+ if (!cell) {
<add>+ return; // 할 일: 새로운 cell 추가 기능?
<add>+ }
<add>+ const { cellSize } = this;
<add>+ const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add>+ const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
<add>+ const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
<add>+ const voxelOffset = voxelY * cellSize * cellSize +
<add>+ voxelZ * cellSize +
<add>+ voxelX;
<add>+ cell[voxelOffset] = v;
<add>+ }
<add> getVoxel(x, y, z) {
<add> const cell = this.getCellForVoxel(x, y, z);
<add> if (!cell) {
<add> return 0;
<add> }
<add> const {cellSize} = this;
<add> const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add> const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
<add> const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
<add> const voxelOffset = voxelY * cellSize * cellSize +
<add> voxelZ * cellSize +
<add> voxelX;
<add> return cell[voxelOffset];
<add> }
<add> generateGeometryDataForCell(cellX, cellY, cellZ) {
<add>
<add> ...
<add>}
<add>```
<add>
<add>흠, 반복되는 코드가 많네요. 코드를 좀 정리해봅시다.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(cellSize) {
<add> this.cellSize = cellSize;
<add>+ this.cellSliceSize = cellSize * cellSize;
<add> this.cell = new Uint8Array(cellSize * cellSize * cellSize);
<add> }
<add> getCellForVoxel(x, y, z) {
<add> const { cellSize } = this;
<add> const cellX = Math.floor(x / cellSize);
<add> const cellY = Math.floor(y / cellSize);
<add> const cellZ = Math.floor(z / cellSize);
<add> if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
<add> return null;
<add> }
<add> return this.cell;
<add> }
<add>+ computeVoxelOffset(x, y, z) {
<add>+ const { cellSize, cellSliceSize } = this;
<add>+ const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add>+ const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
<add>+ const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
<add>+ return voxelY * cellSliceSize +
<add>+ voxelZ * cellSize +
<add>+ voxelX;
<add>+ }
<add> setVoxel(x, y, z, v) {
<add> const cell = this.getCellForVoxel(x, y, z);
<add> if (!cell) {
<add> return; // 할 일: 새로운 cell 추가 기능?
<add> }
<add>- const { cellSize } = this;
<add>- const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add>- const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
<add>- const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
<add>- const voxelOffset = voxelY * cellSize * cellSize +
<add>- voxelZ * cellSize +
<add>- voxelX;
<add>+ const voxelOffset = this.computeVoxelOffset(x, y, z);
<add> cell[voxelOffset] = v;
<add> }
<add> getVoxel(x, y, z) {
<add> const cell = this.getCellForVoxel(x, y, z);
<add> if (!cell) {
<add> return 0;
<add> }
<add>- const { cellSize } = this;
<add>- const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add>- const voxelY = THREE.MathUtils.euclideanModulo(y, cellSize) | 0;
<add>- const voxelZ = THREE.MathUtils.euclideanModulo(z, cellSize) | 0;
<add>- const voxelOffset = voxelY * cellSize * cellSize +
<add>- voxelZ * cellSize +
<add>- voxelX;
<add>+ const voxelOffset = this.computeVoxelOffset(x, y, z);
<add> return cell[voxelOffset];
<add> }
<add> generateGeometryDataForCell(cellX, cellY, cellZ) {
<add>
<add> ...
<add>}
<add>```
<add>
<add>다음으로 첫 번째 cell을 복셀로 채우는 코드를 작성합니다.
<add>
<add>```js
<add>const cellSize = 32;
<add>
<add>const world = new VoxelWorld(cellSize);
<add>
<add>for (let y = 0; y < cellSize; ++y) {
<add> for (let z = 0; z < cellSize; ++z) {
<add> for (let x = 0; x < cellSize; ++x) {
<add> const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
<add> if (y < height) {
<add> world.setVoxel(x, y, z, 1);
<add> }
<add> }
<add> }
<add>}
<add>```
<add>
<add>[BufferGeometry에 관한 글](threejs-custom-buffergeometry.html)에서 다뤘던 대로 실제 geometry를 생성하는 코드도 작성합니다.
<add>
<add>```js
<add>const { positions, normals, indices } = world.generateGeometryDataForCell(0, 0, 0);
<add>const geometry = new THREE.BufferGeometry();
<add>const material = new THREE.MeshLambertMaterial({ color: 'green' });
<add>
<add>const positionNumComponents = 3;
<add>const normalNumComponents = 3;
<add>geometry.setAttribute(
<add> 'position',
<add> new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
<add>geometry.setAttribute(
<add> 'normal',
<add> new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
<add>geometry.setIndex(indices);
<add>const mesh = new THREE.Mesh(geometry, material);
<add>scene.add(mesh);
<add>```
<add>
<add>한 번 테스트해보죠.
<add>
<add>{{{example url="../threejs-voxel-geometry-culled-faces.html" }}}
<add>
<add>잘 완성한 것 같네요! 여기에 실제 마인크래프트처럼 텍스처를 넣어봅시다.
<add>
<add>인터넷을 뒤져 이 [텍스처들](https://www.minecraftforum.net/forums/mapping-and-modding-java-edition/resource-packs/1245961-16x-1-7-4-wip-flourish)을 찾았습니다(라이선스: [CC-BY-NC-SA](https://creativecommons.org/licenses/by-nc-sa/4.0/), 작가: [Joshtimus](https://www.minecraftforum.net/members/Joshtimus)). 그리고 여기서 몇 가지를 임의로 골라 [텍스처 아틀라스(texture atlas)](https://www.google.com/search?q=texture+atlas)를 만들었습니다.
<add>
<add><div class="threejs_center"><img class="checkerboard" src="../resources/images/minecraft/flourish-cc-by-nc-sa.png" style="width: 512px; image-rendering: pixelated;"></div>
<add>
<add>작업을 간단히 하기 위해 텍스처를 열별로 정렬했습니다. 첫 번째 줄은 복셀의 옆면, 두 번째 줄은 복셀의 윗면, 세 번째 줄은 복셀의 아랫면이죠.
<add>
<add>이 데이터를 바탕으로 `VoxelWorld.faces`에 각 복셀에 사용할 텍스처의 줄 번호와 복셀의 각 면에 사용할 UV 좌표 데이터를 지정합니다.
<add>
<add>```js
<add>VoxelWorld.faces = [
<add> { // 왼쪽
<add>+ uvRow: 0,
<add> dir: [ -1, 0, 0, ],
<add> corners: [
<add>- [ 0, 1, 0 ],
<add>- [ 0, 0, 0 ],
<add>- [ 0, 1, 1 ],
<add>- [ 0, 0, 1 ],
<add>+ { pos: [ 0, 1, 0 ], uv: [ 0, 1 ], },
<add>+ { pos: [ 0, 0, 0 ], uv: [ 0, 0 ], },
<add>+ { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
<add>+ { pos: [ 0, 0, 1 ], uv: [ 1, 0 ], },
<add> ],
<add> },
<add> { // 오른쪽
<add>+ uvRow: 0,
<add> dir: [ 1, 0, 0, ],
<add> corners: [
<add>- [ 1, 1, 1 ],
<add>- [ 1, 0, 1 ],
<add>- [ 1, 1, 0 ],
<add>- [ 1, 0, 0 ],
<add>+ { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
<add>+ { pos: [ 1, 0, 1 ], uv: [ 0, 0 ], },
<add>+ { pos: [ 1, 1, 0 ], uv: [ 1, 1 ], },
<add>+ { pos: [ 1, 0, 0 ], uv: [ 1, 0 ], },
<add> ],
<add> },
<add> { // 아래
<add>+ uvRow: 1,
<add> dir: [ 0, -1, 0, ],
<add> corners: [
<add>- [ 1, 0, 1 ],
<add>- [ 0, 0, 1 ],
<add>- [ 1, 0, 0 ],
<add>- [ 0, 0, 0 ],
<add>+ { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
<add>+ { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
<add>+ { pos: [ 1, 0, 0 ], uv: [ 1, 1 ], },
<add>+ { pos: [ 0, 0, 0 ], uv: [ 0, 1 ], },
<add> ],
<add> },
<add> { // 위
<add>+ uvRow: 2,
<add> dir: [ 0, 1, 0, ],
<add> corners: [
<add>- [ 0, 1, 1 ],
<add>- [ 1, 1, 1 ],
<add>- [ 0, 1, 0 ],
<add>- [ 1, 1, 0 ],
<add>+ { pos: [ 0, 1, 1 ], uv: [ 1, 1 ], },
<add>+ { pos: [ 1, 1, 1 ], uv: [ 0, 1 ], },
<add>+ { pos: [ 0, 1, 0 ], uv: [ 1, 0 ], },
<add>+ { pos: [ 1, 1, 0 ], uv: [ 0, 0 ], },
<add> ],
<add> },
<add> { // 뒤
<add>+ uvRow: 0,
<add> dir: [ 0, 0, -1, ],
<add> corners: [
<add>- [ 1, 0, 0 ],
<add>- [ 0, 0, 0 ],
<add>- [ 1, 1, 0 ],
<add>- [ 0, 1, 0 ],
<add>+ { pos: [ 1, 0, 0 ], uv: [ 0, 0 ], },
<add>+ { pos: [ 0, 0, 0 ], uv: [ 1, 0 ], },
<add>+ { pos: [ 1, 1, 0 ], uv: [ 0, 1 ], },
<add>+ { pos: [ 0, 1, 0 ], uv: [ 1, 1 ], },
<add> ],
<add> },
<add> { // 앞
<add>+ uvRow: 0,
<add> dir: [ 0, 0, 1, ],
<add> corners: [
<add>- [ 0, 0, 1 ],
<add>- [ 1, 0, 1 ],
<add>- [ 0, 1, 1 ],
<add>- [ 1, 1, 1 ],
<add>+ { pos: [ 0, 0, 1 ], uv: [ 0, 0 ], },
<add>+ { pos: [ 1, 0, 1 ], uv: [ 1, 0 ], },
<add>+ { pos: [ 0, 1, 1 ], uv: [ 0, 1 ], },
<add>+ { pos: [ 1, 1, 1 ], uv: [ 1, 1 ], },
<add> ],
<add> },
<add>];
<add>```
<add>
<add>방금 지정한 데이터를 사용하도록 코드를 수정합니다. 텍스처 아틀라스 타일 하나의 크기와 텍스처의 크기를 알아야 하니 생성 시에 넘겨 받도록 합니다.
<add>
<add>```js
<add>class VoxelWorld {
<add>- constructor(cellSize) {
<add>- this.cellSize = cellSize;
<add>+ constructor(options) {
<add>+ this.cellSize = options.cellSize;
<add>+ this.tileSize = options.tileSize;
<add>+ this.tileTextureWidth = options.tileTextureWidth;
<add>+ this.tileTextureHeight = options.tileTextureHeight;
<add>+ const { cellSize } = this;
<add>+ this.cellSliceSize = cellSize * cellSize;
<add>+ this.cell = new Uint8Array(cellSize * cellSize * cellSize);
<add> }
<add>
<add> ...
<add>
<add> generateGeometryDataForCell(cellX, cellY, cellZ) {
<add>- const { cellSize } = this;
<add>+ const { cellSize, tileSize, tileTextureWidth, tileTextureHeight } = this;
<add> const positions = [];
<add> const normals = [];
<add>+ const uvs = [];
<add> const indices = [];
<add> const startX = cellX * cellSize;
<add> const startY = cellY * cellSize;
<add> const startZ = cellZ * cellSize;
<add>
<add> for (let y = 0; y < cellSize; ++y) {
<add> const voxelY = startY + y;
<add> for (let z = 0; z < cellSize; ++z) {
<add> const voxelZ = startZ + z;
<add> for (let x = 0; x < cellSize; ++x) {
<add> const voxelX = startX + x;
<add> const voxel = this.getVoxel(voxelX, voxelY, voxelZ);
<add> if (voxel) {
<add> const uvVoxel = voxel - 1; // 0 위치의 복셀은 하늘이므로 UV의 경우는 0에서 시작하도록 합니다.
<add> // 현재 위치에 복셀이 있을 때 해당 위치에 면이 필요한지 검사합니다.
<add>- for (const { dir, corners } of VoxelWorld.faces) {
<add>+ for (const { dir, corners, uvRow } of VoxelWorld.faces) {
<add> const neighbor = this.getVoxel(
<add> voxelX + dir[0],
<add> voxelY + dir[1],
<add> voxelZ + dir[2]);
<add> if (!neighbor) {
<add> // 이 복셀은 이 방향에 이웃하는 복셀이 없으므로
<add> // 이쪽에 면을 만듭니다.
<add> const ndx = positions.length / 3;
<add>- for (const pos of corners) {
<add>+ for (const {pos, uv} of corners) {
<add> positions.push(pos[0] + x, pos[1] + y, pos[2] + z);
<add> normals.push(...dir);
<add>+ uvs.push(
<add>+ (uvVoxel + uv[0]) * tileSize / tileTextureWidth,
<add>+ 1 - (uvRow + 1 - uv[1]) * tileSize / tileTextureHeight);
<add> }
<add> indices.push(
<add> ndx, ndx + 1, ndx + 2,
<add> ndx + 2, ndx + 1, ndx + 3,
<add> );
<add> }
<add> }
<add> }
<add> }
<add> }
<add> }
<add>
<add> return {
<add> positions,
<add> normals,
<add> uvs,
<add> indices,
<add> };
<add> }
<add>}
<add>```
<add>
<add>다음으로 텍스처를 불러옵니다.
<add>
<add>```js
<add>const loader = new THREE.TextureLoader();
<add>const texture = loader.load('resources/images/minecraft/flourish-cc-by-nc-sa.png', render);
<add>texture.magFilter = THREE.NearestFilter;
<add>texture.minFilter = THREE.NearestFilter;
<add>```
<add>
<add>그리고 `VoxelWorld`에 설정값을 넘겨줍니다.
<add>
<add>```js
<add>+const tileSize = 16;
<add>+const tileTextureWidth = 256;
<add>+const tileTextureHeight = 64;
<add>-const world = new VoxelWorld(cellSize);
<add>+const world = new VoxelWorld({
<add>+ cellSize,
<add>+ tileSize,
<add>+ tileTextureWidth,
<add>+ tileTextureHeight,
<add>+});
<add>```
<add>
<add>geometry를 만들 때 UV 좌표를, 재질을 만들 때 텍스처를 사용하도록 변경합니다.
<add>
<add>```js
<add>-const { positions, normals, indices } = world.generateGeometryDataForCell(0, 0, 0);
<add>+const { positions, normals, uvs, indices } = world.generateGeometryDataForCell(0, 0, 0);
<add>const geometry = new THREE.BufferGeometry();
<add>-const material = new THREE.MeshLambertMaterial({ color: 'green' });
<add>+const material = new THREE.MeshLambertMaterial({
<add>+ map: texture,
<add>+ side: THREE.DoubleSide,
<add>+ alphaTest: 0.1,
<add>+ transparent: true,
<add>+});
<add>
<add>const positionNumComponents = 3;
<add>const normalNumComponents = 3;
<add>+const uvNumComponents = 2;
<add>geometry.setAttribute(
<add> 'position',
<add> new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
<add>geometry.setAttribute(
<add> 'normal',
<add> new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
<add>+geometry.setAttribute(
<add>+ 'uv',
<add>+ new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
<add>geometry.setIndex(indices);
<add>const mesh = new THREE.Mesh(geometry, material);
<add>scene.add(mesh);
<add>```
<add>
<add>마지막으로 복셀이 서로 다른 텍스처를 쓰도록 설정합니다.
<add>
<add>```js
<add>for (let y = 0; y < cellSize; ++y) {
<add> for (let z = 0; z < cellSize; ++z) {
<add> for (let x = 0; x < cellSize; ++x) {
<add> const height = (Math.sin(x / cellSize * Math.PI * 2) + Math.sin(z / cellSize * Math.PI * 3)) * (cellSize / 6) + (cellSize / 2);
<add> if (y < height) {
<add>- world.setVoxel(x, y, z, 1);
<add>+ world.setVoxel(x, y, z, randInt(1, 17));
<add> }
<add> }
<add> }
<add>}
<add>
<add>+function randInt(min, max) {
<add>+ return Math.floor(Math.random() * (max - min) + min);
<add>+}
<add>```
<add>
<add>한 번 실행해보죠!
<add>
<add>{{{example url="../threejs-voxel-geometry-culled-faces-with-textures.html"}}}
<add>
<add>코드를 좀 더 발전시켜 하나 이상의 cell을 추가할 수 있도록 해봅시다.
<add>
<add>먼저 각 cell에 id를 부여해 객체 형태로 저장하도록 합니다. 이 id는 각 cell의 위치값을 쉼표로 분할한 문자열로 지정할 겁니다. 예를 들어 (35,0,0) 복셀은 cell (1,0,0)에 있을 테니 해당 cell의 id는 `"1,0,0"`이 되겠죠.
<add>
<add>```js
<add>class VoxelWorld {
<add> constructor(options) {
<add> this.cellSize = options.cellSize;
<add> this.tileSize = options.tileSize;
<add> this.tileTextureWidth = options.tileTextureWidth;
<add> this.tileTextureHeight = options.tileTextureHeight;
<add> const { cellSize } = this;
<add> this.cellSliceSize = cellSize * cellSize;
<add>- this.cell = new Uint8Array(cellSize * cellSize * cellSize);
<add>+ this.cells = {};
<add> }
<add>+ computeCellId(x, y, z) {
<add>+ const { cellSize } = this;
<add>+ const cellX = Math.floor(x / cellSize);
<add>+ const cellY = Math.floor(y / cellSize);
<add>+ const cellZ = Math.floor(z / cellSize);
<add>+ return `${cellX},${cellY},${cellZ}`;
<add>+ }
<add>+ getCellForVoxel(x, y, z) {
<add>- const cellX = Math.floor(x / cellSize);
<add>- const cellY = Math.floor(y / cellSize);
<add>- const cellZ = Math.floor(z / cellSize);
<add>- if (cellX !== 0 || cellY !== 0 || cellZ !== 0) {
<add>- return null;
<add>- }
<add>- return this.cell;
<add>+ return this.cells[this.computeCellId(x, y, z)];
<add> }
<add>
<add> ...
<add>}
<add>```
<add>
<add>그리고 `setVoxel` 메서드를 수정해 존재하지 않는 cell의 복셀을 추가할 때 새로운 cell을 추가하도록 합니다.
<add>
<add>```js
<add> setVoxel(x, y, z, v) {
<add>- const cell = this.getCellForVoxel(x, y, z);
<add>+ let cell = this.getCellForVoxel(x, y, z);
<add> if (!cell) {
<add>- return 0;
<add>+ cell = this.addCellForVoxel(x, y, z);
<add> }
<add> const voxelOffset = this.computeVoxelOffset(x, y, z);
<add> cell[voxelOffset] = v;
<add> }
<add>+ addCellForVoxel(x, y, z) {
<add>+ const cellId = this.computeCellId(x, y, z);
<add>+ let cell = this.cells[cellId];
<add>+ if (!cell) {
<add>+ const { cellSize } = this;
<add>+ cell = new Uint8Array(cellSize * cellSize * cellSize);
<add>+ this.cells[cellId] = cell;
<add>+ }
<add>+ return cell;
<add>+ }
<add>```
<add>
<add>준비를 마쳤으니 복셀을 마음대로 수정할 수 있도록 해봅시다.
<add>
<add>먼저 라디오 버튼을 이용해 타일을 8x2짜리 UI로 만듭니다.
<add>
<add>```html
<add><body>
<add> <canvas id="c"></canvas>
<add>+ <div id="ui">
<add>+ <div class="tiles">
<add>+ <input type="radio" name="voxel" id="voxel1" value="1"><label for="voxel1" style="background-position: -0% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel2" value="2"><label for="voxel2" style="background-position: -100% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel3" value="3"><label for="voxel3" style="background-position: -200% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel4" value="4"><label for="voxel4" style="background-position: -300% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel5" value="5"><label for="voxel5" style="background-position: -400% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel6" value="6"><label for="voxel6" style="background-position: -500% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel7" value="7"><label for="voxel7" style="background-position: -600% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel8" value="8"><label for="voxel8" style="background-position: -700% -0%"></label>
<add>+ </div>
<add>+ <div class="tiles">
<add>+ <input type="radio" name="voxel" id="voxel9" value="9" ><label for="voxel9" style="background-position: -800% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel10" value="10"><label for="voxel10" style="background-position: -900% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel11" value="11"><label for="voxel11" style="background-position: -1000% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel12" value="12"><label for="voxel12" style="background-position: -1100% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel13" value="13"><label for="voxel13" style="background-position: -1200% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel14" value="14"><label for="voxel14" style="background-position: -1300% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel15" value="15"><label for="voxel15" style="background-position: -1400% -0%"></label>
<add>+ <input type="radio" name="voxel" id="voxel16" value="16"><label for="voxel16" style="background-position: -1500% -0%"></label>
<add>+ </div>
<add>+ </div>
<add></body>
<add>```
<add>
<add>UI가 현재 선택한 타일을 보여주도록 CSS도 추가합니다.
<add>
<add>```css
<add>body {
<add> margin: 0;
<add>}
<add>#c {
<add> width: 100vw;
<add> height: 100vh;
<add> display: block;
<add>}
<add>+#ui {
<add>+ position: absolute;
<add>+ left: 10px;
<add>+ top: 10px;
<add>+ background: rgba(0, 0, 0, 0.8);
<add>+ padding: 5px;
<add>+}
<add>+#ui input[type=radio] {
<add>+ width: 0;
<add>+ height: 0;
<add>+ display: none;
<add>+}
<add>+#ui input[type=radio] + label {
<add>+ background-image: url('resources/images/minecraft/flourish-cc-by-nc-sa.png');
<add>+ background-size: 1600% 400%;
<add>+ image-rendering: pixelated;
<add>+ width: 64px;
<add>+ height: 64px;
<add>+ display: inline-block;
<add>+}
<add>+#ui input[type=radio]:checked + label {
<add>+ outline: 3px solid red;
<add>+}
<add>+@media (max-width: 600px), (max-height: 600px) {
<add>+ #ui input[type=radio] + label {
<add>+ width: 32px;
<add>+ height: 32px;
<add>+ }
<add>+}
<add>```
<add>
<add>기능은 다음처럼 구현할 겁니다. 선택한 타일이 없거나 shift 키를 누르고 있는 경우, 복셀을 클릭하면 해당 복셀이 지워집니다. 반대로 선택한 타일이 있는 경우 선택한 타일이 추가되죠. 선택한 타일을 다시 클릭하면 선택을 해제할 수 있습니다.
<add>
<add>아래는 사용자가 선택한 라디오 버튼을 해제할 수 있게끔 해주는 코드입니다.
<add>
<add>```js
<add>let currentVoxel = 0;
<add>let currentId;
<add>
<add>document.querySelectorAll('#ui .tiles input[type=radio][name=voxel]').forEach((elem) => {
<add> elem.addEventListener('click', allowUncheck);
<add>});
<add>
<add>function allowUncheck() {
<add> if (this.id === currentId) {
<add> this.checked = false;
<add> currentId = undefined;
<add> currentVoxel = 0;
<add> } else {
<add> currentId = this.id;
<add> currentVoxel = parseInt(this.value);
<add> }
<add>}
<add>```
<add>
<add>아래 코드는 사용자가 클릭한 지점에 복셀을 추가하는 역할입니다. [피킹에 관한 글](threejs-picking.html)에서 썼던 것과 비슷한 방법을 사용하는데, Three.js의 내장 `RayCaster`가 아닌 교차하는 지점의 좌표와 교차한 점의 법선(normal)을 반환하는 `VoxelWorld.intersectRay`를 사용합니다.
<add>
<add>```js
<add>function getCanvasRelativePosition(event) {
<add> const rect = canvas.getBoundingClientRect();
<add> return {
<add> x: (event.clientX - rect.left) * canvas.width / rect.width,
<add> y: (event.clientY - rect.top ) * canvas.height / rect.height,
<add> };
<add>}
<add>
<add>function placeVoxel(event) {
<add> const pos = getCanvasRelativePosition(event);
<add> const x = (pos.x / canvas.width ) * 2 - 1;
<add> const y = (pos.y / canvas.height) * -2 + 1; // Y축을 뒤집었음
<add>
<add> const start = new THREE.Vector3();
<add> const end = new THREE.Vector3();
<add> start.setFromMatrixPosition(camera.matrixWorld);
<add> end.set(x, y, 1).unproject(camera);
<add>
<add> const intersection = world.intersectRay(start, end);
<add> if (intersection) {
<add> const voxelId = event.shiftKey ? 0 : currentVoxel;
<add> /**
<add> * 교차점은 면 위에 있습니다. 이는 수학적 오차로 인해 교차점이 면의 양면
<add> * 어디로 떨어질지 모른다는 이야기죠.
<add> * 그래서 복셀을 제거하는 경우(currentVoxel = 0)는 normal의 값을 반으로
<add> * 줄이고, 추가하는 경우(currentVoxel > 0)에는 방향을 바꾼 뒤 반만큼 줄입니다.
<add> **/
<add> const pos = intersection.position.map((v, ndx) => {
<add> return v + intersection.normal[ndx] * (voxelId > 0 ? 0.5 : -0.5);
<add> });
<add> world.setVoxel(...pos, voxelId);
<add> updateVoxelGeometry(...pos);
<add> requestRenderIfNotRequested();
<add> }
<add>}
<add>
<add>const mouse = {
<add> x: 0,
<add> y: 0,
<add>};
<add>
<add>function recordStartPosition(event) {
<add> mouse.x = event.clientX;
<add> mouse.y = event.clientY;
<add> mouse.moveX = 0;
<add> mouse.moveY = 0;
<add>}
<add>function recordMovement(event) {
<add> mouse.moveX += Math.abs(mouse.x - event.clientX);
<add> mouse.moveY += Math.abs(mouse.y - event.clientY);
<add>}
<add>function placeVoxelIfNoMovement(event) {
<add> if (mouse.moveX < 5 && mouse.moveY < 5) {
<add> placeVoxel(event);
<add> }
<add> window.removeEventListener('mousemove', recordMovement);
<add> window.removeEventListener('mouseup', placeVoxelIfNoMovement);
<add>}
<add>canvas.addEventListener('mousedown', (event) => {
<add> event.preventDefault();
<add> recordStartPosition(event);
<add> window.addEventListener('mousemove', recordMovement);
<add> window.addEventListener('mouseup', placeVoxelIfNoMovement);
<add>}, { passive: false });
<add>canvas.addEventListener('touchstart', (event) => {
<add> event.preventDefault();
<add> recordStartPosition(event.touches[0]);
<add>}, { passive: false });
<add>canvas.addEventListener('touchmove', (event) => {
<add> event.preventDefault();
<add> recordMovement(event.touches[0]);
<add>}, { passive: false });
<add>canvas.addEventListener('touchend', () => {
<add> placeVoxelIfNoMovement({
<add> clientX: mouse.x,
<add> clientY: mouse.y,
<add> });
<add>});
<add>```
<add>
<add>마우스는 두 가지 용도로 사용합니다. 하나는 카메라를 움직이는 용도이고, 다른 하나는 복셀을 수정하는 용도이죠. 복셀의 추가/제거 액션은 마우스를 누르고 전혀 움직이지 않았을 때만 발생합니다. 마우스를 누른 뒤 움직였다면 카메라를 돌리려는 의도로 간주한 것이죠. `moveX`와 `moveY`는 절대값으로, 왼쪽으로 10픽셀, 오른쪽으로 다시 10픽셀을 움직였다면 `moveX`는 20픽셀이 됩니다. 이러면 화면을 돌렸다가 다시 제자리에 놓는 경우에도 복셀의 추가/제거 액션이 발생하지 않을 겁니다. 5픽셀 이상 움직이지 않았을 경우 클릭으로 간주했는데, 별도 테스트는 진행하지 않은 임의의 값이니 참고 바랍니다.
<add>
<add>위 코드에서는 `world.setVoxel`로 복셀을 추가한 뒤 `updateVoxelGeometry`를 호출해 Three.js가 변경된 geometry를 반영하도록 했습니다.
<add>
<add>이제 이 `updateVoxelGeometry`를 만들어야 합니다. 사용자가 cell 가장자리의 복셀을 클릭했다면 새로운 cell geometry를 만들어야 할 수도 있죠. 때문에 방금 추가한 복셀 뿐만 아니라 해당 복셀의 cell 주변 cell들도 전부 확인해야 합니다.
<add>
<add>```js
<add>const neighborOffsets = [
<add> [ 0, 0, 0], // 자신
<add> [-1, 0, 0], // 왼쪽
<add> [ 1, 0, 0], // 오른쪽
<add> [ 0, -1, 0], // 아래
<add> [ 0, 1, 0], // 위
<add> [ 0, 0, -1], // 뒤
<add> [ 0, 0, 1], // 앞
<add>];
<add>function updateVoxelGeometry(x, y, z) {
<add> const updatedCellIds = {};
<add> for (const offset of neighborOffsets) {
<add> const ox = x + offset[0];
<add> const oy = y + offset[1];
<add> const oz = z + offset[2];
<add> const cellId = world.computeCellId(ox, oy, oz);
<add> if (!updatedCellIds[cellId]) {
<add> updatedCellIds[cellId] = true;
<add> updateCellGeometry(ox, oy, oz);
<add> }
<add> }
<add>}
<add>```
<add>
<add>처음에는 아래처럼 인접한 cell을 검사하려 했습니다.
<add>
<add>```js
<add>const voxelX = THREE.MathUtils.euclideanModulo(x, cellSize) | 0;
<add>if (voxelX === 0) {
<add> // cell을 왼쪽에 추가합니다.
<add>} else if (voxelX === cellSize - 1) {
<add> // cell을 오른쪽에 추가합니다.
<add>}
<add>```
<add>
<add>여기에 다른 4방향을 검사하는 코드를 추가하려 했지만, 이때 그냥 좌표값 배열을 만들어 이미 만든 cell의 id로 사용하는 게 더 낫다는 생각이 들었습니다. 추가한 복셀이 cell의 안에 있는 게 아니라면 해당 복셀을 추가하길 거부하는 게 더 빠를 테니까요.
<add>
<add>`updateCellGeometry`는 간단히 이전에 cell을 만들었던 코드를 가져와 여러 cell을 만들 수 있도록 수정했습니다.
<add>
<add>```js
<add>const cellIdToMesh = {};
<add>function updateCellGeometry(x, y, z) {
<add> const cellX = Math.floor(x / cellSize);
<add> const cellY = Math.floor(y / cellSize);
<add> const cellZ = Math.floor(z / cellSize);
<add> const cellId = world.computeCellId(x, y, z);
<add> let mesh = cellIdToMesh[cellId];
<add> const geometry = mesh ? mesh.geometry : new THREE.BufferGeometry();
<add>
<add> const { positions, normals, uvs, indices } = world.generateGeometryDataForCell(cellX, cellY, cellZ);
<add> const positionNumComponents = 3;
<add> geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array(positions), positionNumComponents));
<add> const normalNumComponents = 3;
<add> geometry.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(normals), normalNumComponents));
<add> const uvNumComponents = 2;
<add> geometry.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(uvs), uvNumComponents));
<add> geometry.setIndex(indices);
<add> geometry.computeBoundingSphere();
<add>
<add> if (!mesh) {
<add> mesh = new THREE.Mesh(geometry, material);
<add> mesh.name = cellId;
<add> cellIdToMesh[cellId] = mesh;
<add> scene.add(mesh);
<add> mesh.position.set(cellX * cellSize, cellY * cellSize, cellZ * cellSize);
<add> }
<add>}
<add>```
<add>
<add>위 함수는 인덱스 맵과 cell의 id로 미리 만든 mesh가 있는지 확인합니다. 만약 해당 id(좌표)에 해당하는 cell이 없다면 새로운 cell mesh를 만들어 장면에 추가한 뒤 mesh의 속성과 인덱스 맵을 업데이트합니다.
<add>
<add>{{{example url="../threejs-voxel-geometry-culled-faces-ui.html"}}}
<add>
<add>참고:
<add>
<add>예제의 방법 대신 `RayCaster`를 써도 괜찮은 결과가 나올 수 있습니다. 따로 테스트를 해보진 않았지만, 대신 [복셀에 최적화된 raycaster](http://www.cse.chalmers.se/edu/year/2010/course/TDA361/grid.pdf)를 찾아 이걸 적용했습니다.
<add>
<add>`intersectRay`를 VoxelWorld의 메서드로 만든 건 성능 때문입니다. 복셀 단위로 체크하는 게 너무 느릴 경우 cell 단위로 먼저 체크해 성능을 좀 더 높혀보려는 계획이었죠.
<add>
<add>현재 raycaster의 길이는 z-far까지인데, 이 값을 바꿔도 됩니다. 이건 제가 예제를 만들 때 1-2픽셀 정도로 보이는 먼 곳에는 복셀을 만들 일이 없다고 생각했기 때문이니까요.
<add>
<add>`geometry.computeBoundingSphere` 메서드의 성능은 다소 느릴 수 있습니다. 이 경우 cell을 전부 포함하는 경계 구체를 직접 만들 수 있죠.
<add>
<add>실제 프로젝트였다면 아마 복셀이 아예 없는 cell도 제거하는 게 좋았을 겁니다.
<add>
<add>이 방법이 가장 별로일 경우는 당연히 체크판 형태로 복셀을 배치하는 경우(예를 들어 체크판의 흰색 칸에만 배치)일 겁니다. 당장은 이런 경우에 어떻게 성능을 향상시킬지 생각나는 방법이 없네요. 아마 사용자가 성능 때문에 거대한 체크판 만들기를 포기하는 게 더 빠를 겁니다.
<add>
<add>예제에서는 간단한 형태만 구현하기 위해 텍스처 아틀라스를 텍스처 한 종류당 한 열씩만 만들었습니다. 각 복셀의 면에 다른 텍스처를 지정할 수 있도록 별도의 테이블을 만들면 좀 더 범용성을 추구할 수 있겠죠. 예제에서는 불필요한 낭비라고 생각해 해당 부분을 제외했습니다.
<add>
<add>실제 마인크래프트에는 복셀도, 정육면체도 아닌 타일(tile)이라는 것이 있습니다. 울타리나 꽃 같은 것이 여기에 해당하죠. 이걸 구현하려면 각 복셀이 정육면체인지, 다른 geometry인지 판별하는 테이블을 만들어 복셀이 정육면체가 아닐 경우, 맞닿는 면을 제거하지 않도록 해야 합니다. 꽃 복셀 아래에 있는 땅 복셀이 지워져서는 안 되니까요.
<add>
<add>이 글이 Three.js로 마인크래프트 같은 그래픽을 구현할 때 좋은 시작점을 마련하고, geometry를 최적화하는 데 도움이 되었으면 합니다.
<add>
<add><canvas id="c"></canvas>
<add><script type="module" src="../resources/threejs-voxel-geometry.js"></script>
| 1
|
Javascript
|
Javascript
|
fix one warning
|
4bb58e59f70ef41da3bf50aa93ee771d23c4bed1
|
<ide><path>Examples/UIExplorer/NavigatorIOSColorsExample.js
<ide> var NavigatorIOSColors = React.createClass({
<ide> tintColor="#FFFFFF"
<ide> barTintColor="#183E63"
<ide> titleTextColor="#FFFFFF"
<del> translucent="true"
<add> translucent={true}
<ide> />
<ide> );
<ide> },
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.