content_type stringclasses 8 values | main_lang stringclasses 7 values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Python | Python | add test for np.tensordot on 0d arrays | 3a75d8660066132cfc7f4a538ddabfbafcc29267 | <ide><path>numpy/core/tests/test_numeric.py
<ide> def test_zero_dimension(self):
<ide> td = np.tensordot(a, b, (1, 0))
<ide> assert_array_equal(td, np.dot(a, b))
<ide> assert_array_equal(td, np.einsum('ij,jk', a, b))
<add>
<add> def test_zero_dimensional(self):
<add> # gh-12130
<add> arr_0d = np.array(1)
<add> ret = np.tensordot(arr_0d, arr_0d, ([], [])) # contracting no axes is well defined
<add> assert_array_equal(ret, arr_0d) | 1 |
Text | Text | add draft of "atom nightly releases" rfc | 16ed259c4d7c7cfdf4f16e5c2991667a7d995b70 | <ide><path>docs/rfcs/002-atom-nightly-releases.md
<add># Atom Nightly Releases
<add>
<add>## Status
<add>
<add>Proposed
<add>
<add>## Summary
<add>
<add>This RFC proposes that Atom add a third official release channel which delivers new builds of Atom nightly from the `master` branch. Nightly releases will allow new improvements to reach users long before a new Stable or Beta release is shipped. This effort will also give us the opportunity to experiment with new release automation strategies that could eventually be used to speed up the Stable and Beta release cadence.
<add>
<add>## Motivation
<add>
<add>Atom currently uses a monthly release cycle with staged Stable and Beta releases so that major issues get caught early in Beta before reaching the Stable release. Because Atom releases updates monthly, this means that a new feature merged into `master` right after a new Atom release could take one month to reach the next Beta and then another month to reach Stable.
<add>
<add>This release process works well for delivering stable improvements to users on a regular basis but it results in friction for users who want to try out the latest Atom improvements and provide feedback. If we deliver a nightly release channel, it will be possible to deliver new features and bug fixes on a regular basis and get valuable feedback to guide our work.
<add>
<add>Today, a bleeding-edge user must manually pull Atom's `master` branch and compile their own build. There is a source of `dev` builds from `master` across our CI services but those aren't made available to users as an official distribution.
<add>
<add>## Explanation
<add>
<add>A user who wants to use the latest improvements to Atom each day can go to atom.io, download the Atom Nightly release, and install it on their machine. This release can be installed alongside Atom Stable and Atom Beta.
<add>
<add>Each night when there are new commits to Atom's `master` branch, a scheduled CI build creates a new Atom Nightly release with packages for Windows, macOS, and Linux. These packages are automatically uploaded to a new GitHub release on the `atom/atom-nightly` repository using a nightly version based off of the current `dev` version in `master` (e.g. v1.29.0-dev.1 or v1.29.0-dev.20180601).
<add>
<add>Every 6 hours, an Atom Nightly release installed on Windows or macOS checks for a new update by consulting Electron's [update.electronjs.org](update-electron) service. If a new update is available, it is downloaded in the background and the user is notified to restart Atom once it's complete. This update flow is the same as what users experience in Atom Stable or Beta releases but occurs more frequently.
<add>
<add>Linux users must manually download nightly releases for now as there isn't an easy way to automatically install new updates across the various Linux distrubutions. We may consider providing updatable [AppImage](http://appimage.org/) packages in the future; this will be proposed in a separate RFC.
<add>
<add>## Drawbacks
<add>
<add>There isn't a major downside to this effort since it would run in parallel to the existing Atom release process without affecting it.
<add>
<add>## Rationale and alternatives
<add>
<add>This is a useful approach because it allows us to achieve a much more rapid feedback loop with highly engaged users to ensure that Atom is improving regularly. It's the best approach because it allows us to get rapid feedback without sacrificing the stability of the Stable and Beta releases.
<add>
<add>Another option is to speed up Atom's release cadence to ship Stable and Beta every two weeks (or more regularly). This approach could shorten our feedback loop but at the expense of greater instability since new improvements would not have as much time to be polished before release.
<add>
<add>The impact of not taking this approach is that we continue to have to wait 1-2 months to get feedback from users about new features or bugs in Stable and Beta releases.
<add>
<add>## Unresolved questions
<add>
<add>- **What should we call this release channel?**
<add>
<add> Some ideas:
<add>
<add> - Atom Nightly
<add> - Atom Reactor
<add> - Atom Dev - Currently the name of dev builds but it might make sense to leave that for "normal" builds from `master`
<add>
<add>- **Will Electron's new autoUpdate service work for all Atom releases?**
<add>
<add> One outcome of this effort is to use the new [update.electronjs.org](update-electron) service for Atom's update checks so that we can deprecate on our own custom update service. Building the Nightly channel on this service will allow us to evaluate it to see if it meets the needs of the Stable and Beta channels.
<add>
<add>[update-elctron]: https://github.com/electron/update.electronjs.org | 1 |
Text | Text | update chinese usage for spacy-pkuseg | aa9c9f3bf0acf88c596b006c157b5f56ed306aeb | <ide><path>website/docs/usage/models.md
<ide> The Chinese language class supports three word segmentation options, `char`,
<ide> > # Jieba
<ide> > cfg = {"segmenter": "jieba"}
<ide> > nlp = Chinese.from_config({"nlp": {"tokenizer": cfg}})
<del>> # PKUSeg with "default" model provided by pkuseg
<add>> # PKUSeg with "mixed" model provided by pkuseg
<ide> > cfg = {"segmenter": "pkuseg"}
<ide> > nlp = Chinese.from_config({"nlp": {"tokenizer": cfg}})
<del>> nlp.tokenizer.initialize(pkuseg_model="default")
<add>> nlp.tokenizer.initialize(pkuseg_model="mixed")
<ide> > ```
<ide>
<ide> ```ini
<ide> segmenter = "char"
<ide> | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
<ide> | `char` | **Character segmentation:** Character segmentation is the default segmentation option. It's enabled when you create a new `Chinese` language class or call `spacy.blank("zh")`. |
<ide> | `jieba` | **Jieba:** to use [Jieba](https://github.com/fxsjy/jieba) for word segmentation, you can set the option `segmenter` to `"jieba"`. |
<del>| `pkuseg` | **PKUSeg**: As of spaCy v2.3.0, support for [PKUSeg](https://github.com/lancopku/PKUSeg-python) has been added to support better segmentation for Chinese OntoNotes and the provided [Chinese pipelines](/models/zh). Enable PKUSeg by setting tokenizer option `segmenter` to `"pkuseg"`. |
<add>| `pkuseg` | **PKUSeg**: As of spaCy v2.3.0, support for [PKUSeg](https://github.com/explosion/spacy-pkuseg) has been added to support better segmentation for Chinese OntoNotes and the provided [Chinese pipelines](/models/zh). Enable PKUSeg by setting tokenizer option `segmenter` to `"pkuseg"`. |
<ide>
<ide> <Infobox title="Changed in v3.0" variant="warning">
<ide>
<ide> runtime.
<ide> The `initialize` method for the Chinese tokenizer class supports the following
<ide> config settings for loading `pkuseg` models:
<ide>
<del>| Name | Description |
<del>| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
<del>| `pkuseg_model` | Name of a model provided by `pkuseg` or the path to a local model directory. ~~str~~ |
<del>| `pkuseg_user_dict` | Optional path to a file with one word per line which overrides the default `pkuseg` user dictionary. Defaults to `"default"`. ~~str~~ |
<add>| Name | Description |
<add>| ------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
<add>| `pkuseg_model` | Name of a model provided by `spacy-pkuseg` or the path to a local model directory. ~~str~~ |
<add>| `pkuseg_user_dict` | Optional path to a file with one word per line which overrides the default `pkuseg` user dictionary. Defaults to `"default"`, the default provided dictionary. ~~str~~ |
<ide>
<ide> The initialization settings are typically provided in the
<ide> [training config](/usage/training#config) and the data is loaded in before
<ide> You can also initialize the tokenizer for a blank language class by calling its
<ide> cfg = {"segmenter": "pkuseg"}
<ide> nlp = Chinese.from_config({"nlp": {"tokenizer": cfg}})
<ide>
<del># Load "default" model
<del>nlp.tokenizer.initialize(pkuseg_model="default")
<add># Load spaCy's OntoNotes model
<add>nlp.tokenizer.initialize(pkuseg_model="spacy_ontonotes")
<add>
<add># Load pkuseg's "news" model
<add>nlp.tokenizer.initialize(pkuseg_model="news")
<ide>
<ide> # Load local model
<ide> nlp.tokenizer.initialize(pkuseg_model="/path/to/pkuseg_model")
<ide>
<ide> # Override the user directory
<del>nlp.tokenizer.initialize(pkuseg_model="default", pkuseg_user_dict="/path/to/user_dict")
<add>nlp.tokenizer.initialize(pkuseg_model="spacy_ontonotes", pkuseg_user_dict="/path/to/user_dict")
<ide> ```
<ide>
<ide> You can also modify the user dictionary on-the-fly:
<ide> The [Chinese pipelines](/models/zh) provided by spaCy include a custom `pkuseg`
<ide> model trained only on
<ide> [Chinese OntoNotes 5.0](https://catalog.ldc.upenn.edu/LDC2013T19), since the
<ide> models provided by `pkuseg` include data restricted to research use. For
<del>research use, `pkuseg` provides models for several different domains
<del>(`"default"`, `"news"` `"web"`, `"medicine"`, `"tourism"`) and for other uses,
<del>`pkuseg` provides a simple
<del>[training API](https://github.com/lancopku/pkuseg-python/blob/master/readme/readme_english.md#usage):
<add>research use, `pkuseg` provides models for several different domains (`"mixed"`
<add>(equivalent to `"default"` from `pkuseg` packages), `"news"` `"web"`,
<add>`"medicine"`, `"tourism"`) and for other uses, `pkuseg` provides a simple
<add>[training API](https://github.com/explosion/spacy-pkuseg/blob/master/readme/readme_english.md#usage):
<ide>
<ide> ```python
<del>import pkuseg
<add>import spacy_pkuseg as pkuseg
<ide> from spacy.lang.zh import Chinese
<ide>
<ide> # Train pkuseg model | 1 |
Python | Python | update ut 6th | dee8f31c68e71dc13a6d69917804c684689b11e7 | <ide><path>keras/utils/conv_utils.py
<ide> def normalize_tuple(value, n, name, allow_zero=False):
<ide> req_msg = '> 0'
<ide>
<ide> if len(unqualified_values) > 0:
<del> error_msg += (f' including {unqualified_values}'
<add> error_msg += (f' including {set(unqualified_values)}'
<ide> f' that does not satisfy the requirement `{req_msg}`.')
<ide> raise ValueError(error_msg)
<ide>
<ide><path>keras/utils/conv_utils_test.py
<ide> def test_normalize_tuple(self):
<ide> 3, n=3, name='pool_size'))
<ide>
<ide> with self.assertRaisesRegex(
<del> ValueError, r'including \[-1\] that does not satisfy the requirement `> 0`'):
<add> ValueError, r'including \{-1\} that does not satisfy the requirement `> 0`'):
<ide> conv_utils.normalize_tuple((3, -1, 3), n=3, name='negative_size')
<ide>
<ide> with self.assertRaisesRegex(
<ide> def test_normalize_tuple(self):
<ide> conv_utils.normalize_tuple(None, n=3, name='kernel_size')
<ide>
<ide> with self.assertRaisesRegex(
<del> ValueError, r'including \[-4, -4, -4\] that does not .* `>= 0`'):
<add> ValueError, r'including \{-4\} that does not .* `>= 0`'):
<ide> conv_utils.normalize_tuple(-4, n=3, name='strides', allow_zero=True)
<ide>
<ide> with self.assertRaisesRegex(
<del> ValueError, r'including \[0\] that does not .* `> 0`'):
<add> ValueError, r'including \{0\} that does not .* `> 0`'):
<ide> conv_utils.normalize_tuple((0, 1, 2), n=3, name='pool_size')
<ide>
<ide> def test_normalize_data_format(self): | 2 |
Ruby | Ruby | improve std_cmake_parameters comments | 8eaa812711ef73597e2287222393b5630dc6a7d8 | <ide><path>Library/Homebrew/formula.rb
<ide> def brew
<ide> end
<ide> end
<ide>
<del> # we don't have a std_autotools variant because autotools is a lot less
<del> # consistent and the standard parameters are more memorable
<del> # really Homebrew should determine what works inside brew() then
<del> # we could add --disable-dependency-tracking when it will work
<add> # Standard parameters for CMake builds.
<add> # Using Build Type "None" tells cmake to use our CFLAGS,etc. settings.
<add> # Setting it to Release would ignore our flags.
<add> # Note: there isn't a std_autotools variant because autotools is a lot
<add> # less consistent and the standard parameters are more memorable.
<ide> def std_cmake_parameters
<del> # The None part makes cmake use the environment's CFLAGS etc. settings
<ide> "-DCMAKE_INSTALL_PREFIX='#{prefix}' -DCMAKE_BUILD_TYPE=None -Wno-dev"
<ide> end
<ide> | 1 |
Java | Java | add a missing space in exception message | 469eb8146e3ac278b396a43c1b7cd8432e6f64e4 | <ide><path>spring-web/src/main/java/org/springframework/web/cors/CorsConfiguration.java
<ide> public void validateAllowCredentials() {
<ide> this.allowedOrigins != null && this.allowedOrigins.contains(ALL)) {
<ide>
<ide> throw new IllegalArgumentException(
<del> "When allowCredentials is true, allowedOrigins cannot contain the special value \"*\"" +
<add> "When allowCredentials is true, allowedOrigins cannot contain the special value \"*\" " +
<ide> "since that cannot be set on the \"Access-Control-Allow-Origin\" response header. " +
<ide> "To allow credentials to a set of origins, list them explicitly " +
<ide> "or consider using \"allowedOriginPatterns\" instead."); | 1 |
Go | Go | remove unused graphdriver.isinitialized() | 2bc07370ec2f6e3ed80d53484e300cee1e24d13c | <ide><path>daemon/graphdriver/driver.go
<ide> func scanPriorDrivers(root string) map[string]bool {
<ide> return driversMap
<ide> }
<ide>
<del>// IsInitialized checks if the driver's home-directory exists and is non-empty.
<del>func IsInitialized(driverHome string) bool {
<del> _, err := os.Stat(driverHome)
<del> if os.IsNotExist(err) {
<del> return false
<del> }
<del> if err != nil {
<del> logrus.Warnf("graphdriver.IsInitialized: stat failed: %v", err)
<del> }
<del> return !isEmptyDir(driverHome)
<del>}
<del>
<ide> // isEmptyDir checks if a directory is empty. It is used to check if prior
<ide> // storage-driver directories exist. If an error occurs, it also assumes the
<ide> // directory is not empty (which preserves the behavior _before_ this check | 1 |
Python | Python | apply lxml elementtree import pattern properly | 3a20e92cab01a7c6634067e589e980fd99dfe87f | <ide><path>libcloud/compute/drivers/abiquo.py
<ide>
<ide> * Abiquo 3.1 (http://wiki.abiquo.com/display/ABI31/The+Abiquo+API)
<ide> """
<del>import xml.etree.ElementTree as ET
<add>try:
<add> from lxml import etree as ET
<add>except ImportError:
<add> from xml.etree import ElementTree as ET
<ide>
<ide> from libcloud.compute.base import NodeDriver, NodeSize
<ide> from libcloud.compute.types import Provider, LibcloudError | 1 |
Python | Python | fix various lint errors | ba4154144ca0efd38ac92ea41c4c6c3b6c231e8b | <ide><path>official/recommendation/ncf_common.py
<ide> def get_distribution_strategy(params):
<ide> "coordinator": tpu_cluster_resolver.cluster_spec()
<ide> .as_dict()["coordinator"]
<ide> }
<del> os.environ['TF_CONFIG'] = json.dumps(tf_config_env)
<add> os.environ["TF_CONFIG"] = json.dumps(tf_config_env)
<ide>
<ide> distribution = tf.distribute.experimental.TPUStrategy(
<ide> tpu_cluster_resolver, steps_per_run=100)
<ide> def xla_validator(flag_dict):
<ide> name="clone_model_in_keras_dist_strat",
<ide> default=True,
<ide> help=flags_core.help_wrap(
<del> 'If False, then the experimental code path is used that doesn\'t '
<add> "If False, then the experimental code path is used that does not "
<ide> "clone models for distribution."))
<ide>
<ide> flags.DEFINE_bool(
<ide> name="early_stopping",
<ide> default=False,
<ide> help=flags_core.help_wrap(
<del> 'If True, we stop the training when it reaches hr_threshold'))
<add> "If True, we stop the training when it reaches hr_threshold"))
<ide>
<ide> flags.DEFINE_bool(
<ide> name="keras_use_ctl",
<ide> default=False,
<ide> help=flags_core.help_wrap(
<del> 'If True, we use a custom training loop for keras.'))
<add> "If True, we use a custom training loop for keras."))
<ide>
<ide> def convert_to_softmax_logits(logits):
<ide> '''Convert the logits returned by the base model to softmax logits.
<ide><path>official/recommendation/ncf_keras_main.py
<ide> def on_epoch_end(self, epoch, logs=None):
<ide>
<ide> def on_train_end(self, logs=None):
<ide> if self.stopped_epoch > 0:
<del> print('Epoch %05d: early stopping' % (self.stopped_epoch + 1))
<add> print("Epoch %05d: early stopping" % (self.stopped_epoch + 1))
<ide>
<ide> def get_monitor_value(self, logs):
<ide> logs = logs or {}
<ide> monitor_value = logs.get(self.monitor)
<ide> if monitor_value is None:
<del> logging.warning('Early stopping conditioned on metric `%s` '
<del> 'which is not available. Available metrics are: %s',
<del> self.monitor, ','.join(list(logs.keys())))
<add> logging.warning("Early stopping conditioned on metric `%s` "
<add> "which is not available. Available metrics are: %s",
<add> self.monitor, ",".join(list(logs.keys())))
<ide> return monitor_value
<ide>
<ide>
<ide> def _get_keras_model(params):
<ide> """Constructs and returns the model."""
<del> batch_size = params['batch_size']
<add> batch_size = params["batch_size"]
<ide>
<ide> # The input layers are of shape (1, batch_size), to match the size of the
<ide> # input data. The first dimension is needed because the input data are
<ide> def run_ncf(_):
<ide>
<ide> params = ncf_common.parse_flags(FLAGS)
<ide>
<del> if params['keras_use_ctl'] and int(tf.__version__.split('.')[0]) == 1:
<add> if params["keras_use_ctl"] and int(tf.__version__.split(".")[0]) == 1:
<ide> logging.error(
<ide> "Custom training loop only works with tensorflow 2.0 and above.")
<ide> return
<ide>
<ide> # ncf_common rounds eval_batch_size (this is needed due to a reshape during
<ide> # eval). This carries over that rounding to batch_size as well. This is the
<ide> # per device batch size
<del> params['batch_size'] = params['eval_batch_size']
<add> params["batch_size"] = params["eval_batch_size"]
<ide> batch_size = params["batch_size"]
<ide>
<ide> num_users, num_items, num_train_steps, num_eval_steps, producer = (
<ide> def run_ncf(_):
<ide> beta_2=params["beta2"],
<ide> epsilon=params["epsilon"])
<ide>
<del> if params['keras_use_ctl']:
<add> if params["keras_use_ctl"]:
<ide> loss_object = tf.losses.SparseCategoricalCrossentropy(
<ide> reduction=tf.keras.losses.Reduction.SUM,
<ide> from_logits=True)
<ide> def step_fn(inputs):
<ide> time_callback.on_batch_begin(step+epoch*num_train_steps)
<ide> train_loss += train_step()
<ide> time_callback.on_batch_end(step+epoch*num_train_steps)
<del> logging.info("Done training epoch {}, epoch loss={}.".format(
<del> epoch+1, train_loss/num_train_steps))
<add> logging.info("Done training epoch %s, epoch loss=%s.",
<add> epoch+1, train_loss/num_train_steps)
<ide> eval_input_iterator.initialize()
<ide> hr_sum = 0
<ide> hr_count = 0
<ide> for _ in range(num_eval_steps):
<ide> step_hr_sum, step_hr_count = eval_step()
<ide> hr_sum += step_hr_sum
<ide> hr_count += step_hr_count
<del> logging.info("Done eval epoch {}, hr={}.".format(epoch+1,
<del> hr_sum/hr_count))
<add> logging.info("Done eval epoch %s, hr=%s.", epoch+1, hr_sum/hr_count)
<ide>
<ide> if (FLAGS.early_stopping and
<ide> float(hr_sum/hr_count) > params["hr_threshold"]):
<ide> def step_fn(inputs):
<ide>
<ide> if history and history.history:
<ide> train_history = history.history
<del> train_loss = train_history['loss'][-1]
<add> train_loss = train_history["loss"][-1]
<ide>
<ide> stats = build_stats(train_loss, eval_results, time_callback)
<ide> return stats
<ide> def step_fn(inputs):
<ide> def build_stats(loss, eval_result, time_callback):
<ide> """Normalizes and returns dictionary of stats.
<ide>
<del> Args:
<del> loss: The final loss at training time.
<del> eval_output: Output of the eval step. Assumes first value is eval_loss and
<del> second value is accuracy_top_1.
<del> time_callback: Time tracking callback likely used during keras.fit.
<del> Returns:
<del> Dictionary of normalized results.
<add> Args:
<add> loss: The final loss at training time.
<add> eval_result: Output of the eval step. Assumes first value is eval_loss and
<add> second value is accuracy_top_1.
<add> time_callback: Time tracking callback likely used during keras.fit.
<add>
<add> Returns:
<add> Dictionary of normalized results.
<ide> """
<ide> stats = {}
<ide> if loss:
<del> stats['loss'] = loss
<add> stats["loss"] = loss
<ide>
<ide> if eval_result:
<del> stats['eval_loss'] = eval_result[0]
<del> stats['eval_hit_rate'] = eval_result[1]
<add> stats["eval_loss"] = eval_result[0]
<add> stats["eval_hit_rate"] = eval_result[1]
<ide>
<ide> if time_callback:
<ide> timestamp_log = time_callback.timestamp_log
<del> stats['step_timestamp_log'] = timestamp_log
<del> stats['train_finish_time'] = time_callback.train_finish_time
<add> stats["step_timestamp_log"] = timestamp_log
<add> stats["train_finish_time"] = time_callback.train_finish_time
<ide> if len(timestamp_log) > 1:
<del> stats['avg_exp_per_second'] = (
<add> stats["avg_exp_per_second"] = (
<ide> time_callback.batch_size * time_callback.log_steps *
<ide> (len(time_callback.timestamp_log)-1) /
<ide> (timestamp_log[-1].timestamp - timestamp_log[0].timestamp))
<ide><path>official/transformer/transformer_main.py
<ide> def run_transformer(flags_obj):
<ide> params["static_batch"] = flags_obj.static_batch or params["use_tpu"]
<ide> params["allow_ffn_pad"] = not params["use_tpu"]
<ide>
<del> params["max_length"] = flags_obj.max_length or params['max_length']
<add> params["max_length"] = flags_obj.max_length or params["max_length"]
<ide>
<ide> params["use_synthetic_data"] = flags_obj.use_synthetic_data
<ide>
<ide><path>official/transformer/v2/data_pipeline.py
<ide> def example_to_bucket_id(example_input, example_target):
<ide> """Return int64 bucket id for this example, calculated based on length."""
<ide> seq_length = _get_example_length((example_input, example_target))
<ide>
<del> # TODO: investigate whether removing code branching improves performance.
<add> # TODO(xunkai): investigate if removing code branching improves performance.
<ide> conditions_c = tf.logical_and(
<ide> tf.less_equal(buckets_min, seq_length),
<ide> tf.less(seq_length, buckets_max))
<ide><path>official/transformer/v2/metrics.py
<ide> def get_config(self):
<ide>
<ide> def call(self, inputs):
<ide> logits, targets = inputs[0], inputs[1]
<del> # TODO(guptapriya): Remove this check when underlying issue to create metrics
<del> # with dist strat in cross replica context is fixed.
<del> if tf.distribute.has_strategy() and not tf.distribute.in_cross_replica_context():
<del> for mean, fn in self.metric_mean_fns:
<del> m = mean(*fn(logits, targets))
<del> self.add_metric(m)
<add> # TODO(guptapriya): Remove this check when underlying issue to create
<add> # metrics with dist strat in cross replica context is fixed.
<add> if (tf.distribute.has_strategy() and
<add> not tf.distribute.in_cross_replica_context()):
<add> for mean, fn in self.metric_mean_fns:
<add> m = mean(*fn(logits, targets))
<add> self.add_metric(m)
<ide> return logits
<ide>
<ide>
<ide><path>official/transformer/v2/transformer_benchmark.py
<ide> def benchmark_8_gpu_static_batch(self):
<ide> bleu_min=27,
<ide> bleu_max=28)
<ide>
<add>
<ide> class TransformerBigKerasAccuracy(TransformerBenchmark):
<ide> """Benchmark accuracy tests for Transformer Big model w/ Keras."""
<ide>
<ide> def benchmark_8_gpu_static_batch(self):
<ide> FLAGS.batch_size = self.batch_per_gpu * 8
<ide> FLAGS.model_dir = self._get_model_dir('benchmark_8_gpu_static_batch')
<ide> FLAGS.static_batch = True
<del> FLAGS.max_length = 64
<add> FLAGS.max_length = 64
<ide> self._run_and_report_benchmark(total_batch_size=FLAGS.batch_size,
<ide> log_steps=FLAGS.log_steps)
<ide>
<ide><path>official/transformer/v2/transformer_main.py
<ide> def train(self):
<ide>
<ide> model.summary()
<ide>
<del> # TODO(guptapriya): Figure out a way to structure input that works in both
<add> # TODO(guptapriya): Figure out a way to structure input that works in both
<ide> # distributed and non distributed cases.
<ide> train_ds = data_pipeline.train_input_fn(params)
<ide> if not self.distribution_strategy: | 7 |
Java | Java | use transactional connection during db population | 49c9a2a9157861bad53ec47b67c8d821b0b4655a | <ide><path>spring-jdbc/src/main/java/org/springframework/jdbc/datasource/init/DatabasePopulatorUtils.java
<ide> /*
<del> * Copyright 2002-2011 the original author or authors.
<add> * Copyright 2002-2012 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> package org.springframework.jdbc.datasource.init;
<ide>
<ide> import java.sql.Connection;
<del>import java.sql.SQLException;
<add>
<ide> import javax.sql.DataSource;
<ide>
<ide> import org.springframework.dao.DataAccessResourceFailureException;
<add>import org.springframework.jdbc.datasource.DataSourceUtils;
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<ide> * Utility methods for executing a DatabasePopulator.
<ide> *
<ide> * @author Juergen Hoeller
<add> * @author Oliver Gierke
<ide> * @since 3.1
<ide> */
<ide> public abstract class DatabasePopulatorUtils {
<ide> public static void execute(DatabasePopulator populator, DataSource dataSource) {
<ide> Assert.notNull(populator, "DatabasePopulator must be provided");
<ide> Assert.notNull(dataSource, "DataSource must be provided");
<ide> try {
<del> Connection connection = dataSource.getConnection();
<add> Connection connection = DataSourceUtils.getConnection(dataSource);
<ide> try {
<ide> populator.populate(connection);
<ide> }
<ide> finally {
<del> try {
<del> connection.close();
<del> }
<del> catch (SQLException ex) {
<del> // ignore
<add> if (connection != null) {
<add> DataSourceUtils.releaseConnection(connection, dataSource);
<ide> }
<ide> }
<ide> }
<ide><path>spring-jdbc/src/test/java/org/springframework/jdbc/datasource/init/DatabasePopulatorTests.java
<ide> /*
<del> * Copyright 2002-2010 the original author or authors.
<add> * Copyright 2002-2012 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> import static org.junit.Assert.assertEquals;
<ide>
<ide> import java.sql.Connection;
<add>import java.sql.SQLException;
<add>
<add>import org.easymock.EasyMock;
<ide>
<ide> import org.junit.After;
<ide> import org.junit.Test;
<add>
<ide> import org.springframework.core.io.ClassRelativeResourceLoader;
<ide> import org.springframework.jdbc.core.JdbcTemplate;
<add>import org.springframework.jdbc.datasource.DataSourceUtils;
<ide> import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase;
<ide> import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
<add>import org.springframework.transaction.support.TransactionSynchronizationManager;
<ide>
<ide> /**
<ide> * @author Dave Syer
<ide> * @author Sam Brannen
<add> * @author Oliver Gierke
<ide> */
<ide> public class DatabasePopulatorTests {
<ide>
<ide> private void assertUsersDatabaseCreated() {
<ide>
<ide> @After
<ide> public void shutDown() {
<add>
<add> if (TransactionSynchronizationManager.isSynchronizationActive()) {
<add> TransactionSynchronizationManager.clear();
<add> TransactionSynchronizationManager.unbindResource(db);
<add> }
<add>
<ide> db.shutdown();
<ide> }
<ide>
<ide> public void testBuildWithSelectStatements() throws Exception {
<ide> assertEquals(1, jdbcTemplate.queryForInt("select COUNT(NAME) from T_TEST where NAME='Dave'"));
<ide> }
<ide>
<add> /**
<add> * @see SPR-9457
<add> */
<add> @Test
<add> public void usesBoundConnectionIfAvailable() throws SQLException {
<add>
<add> TransactionSynchronizationManager.initSynchronization();
<add> Connection connection = DataSourceUtils.getConnection(db);
<add>
<add> DatabasePopulator populator = EasyMock.createMock(DatabasePopulator.class);
<add> populator.populate(connection);
<add> EasyMock.expectLastCall();
<add> EasyMock.replay(populator);
<add>
<add> DatabasePopulatorUtils.execute(populator, db);
<add>
<add> EasyMock.verify(populator);
<add> }
<ide> } | 2 |
Go | Go | add a way to get a pid of a process | 0fc52ca6dd628f2b9163f5d328d1d749c6708de4 | <ide><path>internal/procfs/procfs_linux.go
<add>package procfs
<add>
<add>/*
<add>Copyright 2015 The Kubernetes Authors.
<add>
<add>Licensed under the Apache License, Version 2.0 (the "License");
<add>you may not use this file except in compliance with the License.
<add>You may obtain a copy of the License at
<add>
<add>http://www.apache.org/licenses/LICENSE-2.0
<add>
<add>Unless required by applicable law or agreed to in writing, software
<add>distributed under the License is distributed on an "AS IS" BASIS,
<add>WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add>See the License for the specific language governing permissions and
<add>limitations under the License.
<add>*/
<add>
<add>import (
<add> "bytes"
<add> "fmt"
<add> "io"
<add> "io/ioutil"
<add> "os"
<add> "path/filepath"
<add> "regexp"
<add> "strconv"
<add> "strings"
<add> "unicode"
<add>
<add> "github.com/sirupsen/logrus"
<add>)
<add>
<add>// PidOf finds process(es) with a specified name (regexp match)
<add>// and return their pid(s)
<add>func PidOf(name string) ([]int, error) {
<add> if len(name) == 0 {
<add> return []int{}, fmt.Errorf("name should not be empty")
<add> }
<add> re, err := regexp.Compile("(^|/)" + name + "$")
<add> if err != nil {
<add> return []int{}, err
<add> }
<add> return getPids(re), nil
<add>}
<add>
<add>func getPids(re *regexp.Regexp) []int {
<add> pids := []int{}
<add>
<add> dirFD, err := os.Open("/proc")
<add> if err != nil {
<add> return nil
<add> }
<add> defer dirFD.Close()
<add>
<add> for {
<add> // Read a small number at a time in case there are many entries, we don't want to
<add> // allocate a lot here.
<add> ls, err := dirFD.Readdir(10)
<add> if err == io.EOF {
<add> break
<add> }
<add> if err != nil {
<add> return nil
<add> }
<add>
<add> for _, entry := range ls {
<add> if !entry.IsDir() {
<add> continue
<add> }
<add>
<add> // If the directory is not a number (i.e. not a PID), skip it
<add> pid, err := strconv.Atoi(entry.Name())
<add> if err != nil {
<add> continue
<add> }
<add>
<add> cmdline, err := ioutil.ReadFile(filepath.Join("/proc", entry.Name(), "cmdline"))
<add> if err != nil {
<add> logrus.Infof("Error reading file %s: %+v", filepath.Join("/proc", entry.Name(), "cmdline"), err)
<add> continue
<add> }
<add>
<add> // The bytes we read have '\0' as a separator for the command line
<add> parts := bytes.SplitN(cmdline, []byte{0}, 2)
<add> if len(parts) == 0 {
<add> continue
<add> }
<add> // Split the command line itself we are interested in just the first part
<add> exe := strings.FieldsFunc(string(parts[0]), func(c rune) bool {
<add> return unicode.IsSpace(c) || c == ':'
<add> })
<add> if len(exe) == 0 {
<add> continue
<add> }
<add> // Check if the name of the executable is what we are looking for
<add> if re.MatchString(exe[0]) {
<add> // Grab the PID from the directory path
<add> pids = append(pids, pid)
<add> }
<add> }
<add> }
<add>
<add> return pids
<add>}
<ide><path>internal/procfs/procfs_linux_test.go
<add>package procfs
<add>
<add>import (
<add> "os"
<add> "path/filepath"
<add> "regexp"
<add> "runtime"
<add> "testing"
<add>
<add> "gotest.tools/assert"
<add>)
<add>
<add>func TestPidOf(t *testing.T) {
<add> pids, err := PidOf(filepath.Base(os.Args[0]))
<add> assert.NilError(t, err)
<add> assert.Check(t, len(pids) == 1)
<add> assert.DeepEqual(t, pids[0], os.Getpid())
<add>}
<add>
<add>func BenchmarkGetPids(b *testing.B) {
<add> if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
<add> b.Skipf("not supported on GOOS=%s", runtime.GOOS)
<add> }
<add>
<add> re, err := regexp.Compile("(^|/)" + filepath.Base(os.Args[0]) + "$")
<add> assert.Check(b, err == nil)
<add>
<add> for i := 0; i < b.N; i++ {
<add> pids := getPids(re)
<add>
<add> b.StopTimer()
<add> assert.Check(b, len(pids) > 0)
<add> assert.Check(b, pids[0] == os.Getpid())
<add> b.StartTimer()
<add> }
<add>}
<ide><path>vendor/github.com/docker/libnetwork/osl/namespace_linux.go
<ide> func (n *networkNamespace) InvokeFunc(f func()) error {
<ide> // InitOSContext initializes OS context while configuring network resources
<ide> func InitOSContext() func() {
<ide> runtime.LockOSThread()
<del> if err := ns.SetNamespace(); err != nil {
<del> logrus.Error(err)
<del> }
<ide> return runtime.UnlockOSThread
<ide> }
<ide>
<del>func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD int) error) error {
<add>func nsInvoke(path string, prefunc, postfunc func(int) error) error {
<ide> defer InitOSContext()()
<ide>
<ide> newNs, err := netns.GetFromPath(path)
<ide> func nsInvoke(path string, prefunc func(nsFD int) error, postfunc func(callerFD
<ide> return fmt.Errorf("failed in prefunc: %v", err)
<ide> }
<ide>
<add> // save the current namespace (host namespace)
<add> curNs, _ := netns.Get()
<ide> if err = netns.Set(newNs); err != nil {
<ide> return err
<ide> }
<del> defer ns.SetNamespace()
<add> defer curNs.Close()
<add> // will restore the previous namespace before unlocking the thread
<add> defer netns.Set(curNs)
<ide>
<ide> // Invoked after the namespace switch.
<ide> return postfunc(ns.ParseHandlerInt())
<ide> func (n *networkNamespace) ApplyOSTweaks(types []SandboxType) {
<ide> for _, t := range types {
<ide> switch t {
<ide> case SandboxTypeLoadBalancer:
<del> kernel.ApplyOSTweaks(loadBalancerConfig)
<add> nsInvoke(n.nsPath(),
<add> func(nsFD int) error { return nil },
<add> func(callerFD int) error { kernel.ApplyOSTweaks(loadBalancerConfig); return nil },
<add> )
<ide> }
<ide> }
<ide> } | 3 |
Python | Python | add a reference paper for adagrad | 52c1a7456fe8fc8ecb91ed7a5122d566aa2cb4af | <ide><path>keras/optimizers.py
<ide> class Adagrad(Optimizer):
<ide> # Arguments
<ide> lr: float >= 0. Learning rate.
<ide> epsilon: float >= 0.
<add>
<add> # References
<add> - [Adaptive Subgradient Methods for Online Learning and Stochastic Optimization](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)
<ide> '''
<ide> def __init__(self, lr=0.01, epsilon=1e-8, **kwargs):
<ide> super(Adagrad, self).__init__(**kwargs) | 1 |
Text | Text | remove d3-voronoi, add d3-delaunay | 0fab3304d2ba381c3213336535fb5ecba2f15215 | <ide><path>API.md
<ide> D3 is a [collection of modules](https://github.com/d3) that are designed to work
<ide> * [Axes](#axes-d3-axis)
<ide> * [Brushes](#brushes-d3-brush)
<ide> * [Chords](#chords-d3-chord)
<del>* [XXXCollections](#collections-d3-collection) ([Objects](#objects), [Maps](#maps), [Sets](#sets), [Nests](#nests))
<ide> * [Colors](#colors-d3-color)
<ide> * [Color Schemes](#color-schemes-d3-scale-chromatic)
<ide> * [Contours](#contours-d3-contour)
<add>* [Voronoi Diagrams](#voronoi-diagrams-d3-delaunay)
<ide> * [Dispatches](#dispatches-d3-dispatch)
<ide> * [Dragging](#dragging-d3-drag)
<ide> * [Delimiter-Separated Values](#delimiter-separated-values-d3-dsv)
<ide> D3 is a [collection of modules](https://github.com/d3) that are designed to work
<ide> * [Time Intervals](#time-intervals-d3-time)
<ide> * [Timers](#timers-d3-timer)
<ide> * [Transitions](#transitions-d3-transition)
<del>* [XXXVoronoi Diagrams](#voronoi-diagrams-d3-voronoi)
<ide> * [Zooming](#zooming-d3-zoom)
<ide>
<ide> D3 uses [semantic versioning](http://semver.org/). The current version is exposed as d3.version.
<ide> Compute contour polygons using marching squares.
<ide> * [*density*.thresholds](https://github.com/d3/d3-contour/blob/v2.0.0/README.md#density_thresholds) - xxxxxxxxx
<ide> * [*density*.bandwidth](https://github.com/d3/d3-contour/blob/v2.0.0/README.md#density_bandwidth) - xxxxxxxxx
<ide>
<add>## [Voronoi Diagrams (d3-delaunay)](https://github.com/d3/d3-delaunay/tree/v5.3.0)
<add>
<add>Compute the Voronoi diagram of a set of two-dimensional points.
<add>
<add>* [new Delaunay](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#new_Delaunay) - xxxxxxxxx
<add>* [Delaunay.from](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_from) - xxxxxxxxx
<add>* [*delaunay*.points](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_points) - xxxxxxxxx
<add>* [*delaunay*.halfedges](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_halfedges) - xxxxxxxxx
<add>* [*delaunay*.hull](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_hull) - xxxxxxxxx
<add>* [*delaunay*.triangles](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_triangles) - xxxxxxxxx
<add>* [*delaunay*.inedges](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_inedges) - xxxxxxxxx
<add>* [*delaunay*.find](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_find) - xxxxxxxxx
<add>* [*delaunay*.neighbors](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_neighbors) - xxxxxxxxx
<add>* [*delaunay*.render](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_render) - xxxxxxxxx
<add>* [*delaunay*.renderHull](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_renderHull) - xxxxxxxxx
<add>* [*delaunay*.renderTriangle](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_renderTriangle) - xxxxxxxxx
<add>* [*delaunay*.renderPoints](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_renderPoints) - xxxxxxxxx
<add>* [*delaunay*.hullPolygon](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_hullPolygon) - xxxxxxxxx
<add>* [*delaunay*.trianglePolygons](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_trianglePolygons) - xxxxxxxxx
<add>* [*delaunay*.trianglePolygon](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_trianglePolygon) - xxxxxxxxx
<add>* [*delaunay*.update](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_update) - xxxxxxxxx
<add>* [*delaunay*.voronoi](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#delaunay_voronoi) - xxxxxxxxx
<add>* [*voronoi*.delaunay](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_delaunay) - xxxxxxxxx
<add>* [*voronoi*.circumcenters](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_circumcenters) - xxxxxxxxx
<add>* [*voronoi*.vectors](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_vectors) - xxxxxxxxx
<add>* [*voronoi*.xmin](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_xmin) - xxxxxxxxx
<add>* [*voronoi*.ymin](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_ymin) - xxxxxxxxx
<add>* [*voronoi*.xmax](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_xmax) - xxxxxxxxx
<add>* [*voronoi*.ymax](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_ymax) - xxxxxxxxx
<add>* [*voronoi*.contains](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_contains) - xxxxxxxxx
<add>* [*voronoi*.neighbors](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_neighbors) - xxxxxxxxx
<add>* [*voronoi*.render](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_render) - xxxxxxxxx
<add>* [*voronoi*.renderBounds](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_renderBounds) - xxxxxxxxx
<add>* [*voronoi*.renderCell](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_renderCell) - xxxxxxxxx
<add>* [*voronoi*.cellPolygons](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_cellPolygons) - xxxxxxxxx
<add>* [*voronoi*.cellPolygon](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_cellPolygon) - xxxxxxxxx
<add>* [*voronoi*.update](https://github.com/d3/d3-delaunay/blob/v5.3.0/README.md#voronoi_update) - xxxxxxxxx
<add>
<ide> ## [Dispatches (d3-dispatch)](https://github.com/d3/d3-dispatch/tree/v2.0.0)
<ide>
<ide> Separate concerns using named callbacks.
<ide> Animated transitions for [selections](#selections).
<ide> * [*transition*.node](https://github.com/d3/d3-transition/blob/v2.0.0/README.md#transition_node) - returns the first (non-null) element.
<ide> * [*transition*.size](https://github.com/d3/d3-transition/blob/v2.0.0/README.md#transition_size) - returns the count of elements.
<ide>
<del>## [XXXVoronoi Diagrams (d3-voronoi)](https://github.com/d3/d3-voronoi/tree/v1.1.4)
<del>
<del>Compute the XXXVoronoi diagram of a given set of points.
<del>
<del>* [d3.voronoi](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi) - create a new XXXVoronoi generator.
<del>* [*voronoi*](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#_voronoi) - generate a new XXXVoronoi diagram for the given points.
<del>* [*voronoi*.polygons](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_polygons) - compute the XXXVoronoi polygons for the given points.
<del>* [*voronoi*.triangles](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_triangles) - compute the Delaunay triangles for the given points.
<del>* [*voronoi*.links](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_links) - compute the Delaunay links for the given points.
<del>* [*voronoi*.x](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_x) - set the *x* accessor.
<del>* [*voronoi*.y](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_y) - set the *y* accessor.
<del>* [*voronoi*.extent](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_extent) - set the observed extent of points.
<del>* [*voronoi*.size](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#voronoi_size) - set the observed extent of points.
<del>* [*diagram*.polygons](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#diagram_polygons) - compute the polygons for this XXXVoronoi diagram.
<del>* [*diagram*.triangles](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#diagram_triangles) - compute the triangles for this XXXVoronoi diagram.
<del>* [*diagram*.links](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#diagram_links) - compute the links for this XXXVoronoi diagram.
<del>* [*diagram*.find](https://github.com/d3/d3-voronoi/blob/v1.1.4/README.md#diagram_find) - find the closest point in this XXXVoronoi diagram.
<del>
<ide> ## [Zooming (d3-zoom)](https://github.com/d3/d3-zoom/tree/v2.0.0)
<ide>
<ide> Pan and zoom SVG, HTML or Canvas using mouse or touch input. | 1 |
Javascript | Javascript | remove unneeded flag check in test-vm-memleak | 2d2a812645db794698abec602a10366e41305b98 | <ide><path>test/pummel/test-vm-memleak.js
<ide> const vm = require('vm');
<ide> const start = Date.now();
<ide> let maxMem = 0;
<ide>
<del>const ok = process.execArgv.some(function(arg) {
<del> return arg === '--max_old_space_size=32';
<del>});
<del>assert(ok, 'Run this test with --max_old_space_size=32.');
<del>
<ide> const interval = setInterval(function() {
<ide> try {
<ide> vm.runInNewContext('throw 1;'); | 1 |
Text | Text | update russian localization | 3fec01a28d4809badfaee4c37a751781e0457f6d | <ide><path>curriculum/challenges/russian/05-apis-and-microservices/basic-node-and-express/chain-middleware-to-create-a-time-server.russian.md
<ide> localeTitle: Промежуточное ПО для создания серве
<ide> Посмотрите на следующий пример:
<ide> <blockquote>app.get('/user', function(req, res, next) {<br> req.user = getTheUserSync(); // Hypothetical synchronous operation<br> next();<br>}, function(req, res) {<br> res.send(req.user);<br>})</blockquote>
<ide> Этот подход полезен для разделения операций сервера на более мелкие единицы. Это приводит к лучшей структуре приложения и возможности повторного использования кода в разных местах. Этот подход также можно использовать для проверки данных. В каждой точке стека промежуточного программного обеспечения вы можете заблокировать выполнение текущей цепочки и передать управление функциям, специально разработанным для обработки ошибок. Или вы можете передать управление следующему подходящему маршруту для обработки особых случаев. Мы увидим, как в расширенном разделе Экспресс.
<del>В маршруте <code>app.get('/now', ...)</code> функцию промежуточного программного обеспечения и конечный обработчик. В функции промежуточного программного обеспечения вы должны добавить текущее время к объекту запроса в ключе <code>req.time</code> . Вы можете использовать <code>new Date().toString()</code> . В обработчике ответьте объектом JSON, взяв структуру <code>{time: req.time}</code> .
<del>Подсказка: тест не пройдет, если вы не подключите промежуточное ПО. Если вы смонтируете функцию где-то еще, тест не пройдёт, даже если результат вывода верный.
<ide> </section>
<ide>
<ide> ## Instructions
<ide> <section id='instructions'>
<del>In the route <code>app.get('/now', ...)</code> chain a middleware function and the final handler. In the middleware function you should add the current time to the request object in the <code>req.time</code> key. You can use <code>new Date().toString()</code>. In the handler, respond with a JSON object, taking the structure <code>{time: req.time}</code>.
<del><strong>Note:</strong> The test will not pass if you don’t chain the middleware. If you mount the function somewhere else, the test will fail, even if the output result is correct.
<add>В маршруте <code>app.get('/now', ...)</code> связывает функцию промежуточного программного обеспечения и конечный обработчик. В функции промежуточного программного обеспечения вы должны добавить текущее время к объекту запроса в ключе <code>req.time</code> . Вы можете использовать <code>new Date().toString()</code> . В обработчике ответьте объектом JSON, взяв структуру <code>{time: req.time}</code> .
<add>Подсказка: тест не пройдет, если вы не подключите промежуточное ПО. Если вы смонтируете функцию где-то еще, тест не пройдёт, даже если результат вывода верный.
<ide> </section>
<ide>
<ide> ## Tests | 1 |
PHP | PHP | fix failing auth strategy tests | 238c190add4e6631cc7d154d86c5df92d55a6e08 | <ide><path>tests/TestCase/Auth/BasicAuthenticateTest.php
<ide> public function testAuthenticateNoData()
<ide> $request = new ServerRequest('posts/index');
<ide>
<ide> $this->response->expects($this->never())
<del> ->method('header');
<add> ->method('withHeader');
<ide>
<ide> $this->assertFalse($this->auth->getUser($request));
<ide> }
<ide><path>tests/TestCase/Auth/DigestAuthenticateTest.php
<ide> public function testAuthenticateNoData()
<ide> $request = new ServerRequest('posts/index');
<ide>
<ide> $this->response->expects($this->never())
<del> ->method('header');
<add> ->method('withHeader');
<ide>
<ide> $this->assertFalse($this->auth->getUser($request, $this->response));
<ide> } | 2 |
Python | Python | update the version to 2.9 | d15302ffb6432fb2242985010d2f0dbf14af0cfb | <ide><path>official/pip_package/setup.py
<ide> from setuptools import find_packages
<ide> from setuptools import setup
<ide>
<del>version = '2.8.0'
<del>tf_version = '2.8.0' # Major version.
<add>version = '2.9.0'
<add>tf_version = '2.9.0' # Major version.
<ide>
<ide> project_name = 'tf-models-official'
<ide> | 1 |
Python | Python | remove unused import | 8c1c86baf0220164c355198708a1c613d27d4132 | <ide><path>tests/keras/layers/test_core.py
<del>import unittest
<ide> import pytest
<ide> import numpy as np
<ide> from numpy.testing import assert_allclose | 1 |
Javascript | Javascript | remove unused property | f8ce2f9f70962370720d83990014167e2e314ef6 | <ide><path>packager/react-packager/src/Bundler/Bundle.js
<ide> class Bundle extends BundleBase {
<ide> this._ramBundle = {
<ide> startupModules,
<ide> lazyModules,
<del> allModules: modules,
<ide> };
<ide> }
<ide> | 1 |
Ruby | Ruby | add collectionproxy#clear documentation | 3f46f73d004eb19616ad9863fefa4c21ef1d76c3 | <ide><path>activerecord/lib/active_record/associations/collection_proxy.rb
<ide> def <<(*records)
<ide> end
<ide> alias_method :push, :<<
<ide>
<add> # Removes every object from the collection. This does not destroy
<add> # the objects, it sets their foreign keys to +NULL+. Returns +self+
<add> # so methods can be chained.
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :pets
<add> # end
<add> #
<add> # person.pets # => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]
<add> # person.pets.clear # => []
<add> # person.pets.size # => 0
<add> #
<add> # Pet.find(1) # => #<Pet id: 1, name: "Snoop", group: "dogs", person_id: nil>
<add> #
<add> # If they are associated with +dependent: :destroy+ option, it deletes
<add> # them directly from the database.
<add> #
<add> # class Person < ActiveRecord::Base
<add> # has_many :pets, dependent: :destroy
<add> # end
<add> #
<add> # person.pets # => [#<Pet id: 2, name: "Wy", group: "cats", person_id: 2>]
<add> # person.pets.clear # => []
<add> # person.pets.size # => 0
<add> #
<add> # Pet.find(2) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=2
<ide> def clear
<ide> delete_all
<ide> self | 1 |
Text | Text | fix typos in image preprocessing docs | ce51e199701e71cf68a7187075d2a0115f5baf22 | <ide><path>docs/templates/preprocessing/image.md
<ide> Generate batches of tensor image data with real-time data augmentation. The data
<ide> - __shuffle__: boolean (defaut: False).
<ide> - __save_to_dir__: None or str (default: None). This allows you to optimally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing).
<ide> - __save_prefix__: str (default: `''`). Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set).
<del> - __save_format__: one of "png", jpeg" (only relevant if `save_to_dir` is set). Default: "jpeg".
<add> - __save_format__: one of "png", "jpeg" (only relevant if `save_to_dir` is set). Default: "jpeg".
<ide> - ___yields__: Tuples of `(x, y)` where `x` is a numpy array of image data and `y` is a numpy array of corresponding labels.
<ide> The generator loops indefinitely.
<ide> - __flow_from_directory(directory)__: Takes the path to a directory, and generates batches of augmented/normalized data. Yields batches indefinitely, in an infinite loop.
<ide> Generate batches of tensor image data with real-time data augmentation. The data
<ide> - __seed__: optional random seed for shuffling.
<ide> - __save_to_dir__: None or str (default: None). This allows you to optimally specify a directory to which to save the augmented pictures being generated (useful for visualizing what you are doing).
<ide> - __save_prefix__: str. Prefix to use for filenames of saved pictures (only relevant if `save_to_dir` is set).
<del> - __save_format__: one of "png", jpeg" (only relevant if `save_to_dir` is set). Default: "jpeg".
<add> - __save_format__: one of "png", "jpeg" (only relevant if `save_to_dir` is set). Default: "jpeg".
<ide>
<ide>
<ide> - __Examples__: | 1 |
Python | Python | add problem 32 solution | 6e6920866662f314a9cbb125667c64e421046a4b | <ide><path>project_euler/problem_32/solution.py
<add>"""
<add>We shall say that an n-digit number is pandigital if it makes use of all the
<add>digits 1 to n exactly once; for example, the 5-digit number, 15234, is 1 through
<add>5 pandigital.
<add>
<add>The product 7254 is unusual, as the identity, 39 × 186 = 7254, containing
<add>multiplicand, multiplier, and product is 1 through 9 pandigital.
<add>
<add>Find the sum of all products whose multiplicand/multiplier/product identity can
<add>be written as a 1 through 9 pandigital.
<add>
<add>HINT: Some products can be obtained in more than one way so be sure to only
<add>include it once in your sum.
<add>"""
<add>import itertools
<add>
<add>
<add>def isCombinationValid(combination):
<add> """
<add> Checks if a combination (a tuple of 9 digits)
<add> is a valid product equation.
<add>
<add> >>> isCombinationValid(('3', '9', '1', '8', '6', '7', '2', '5', '4'))
<add> True
<add>
<add> >>> isCombinationValid(('1', '2', '3', '4', '5', '6', '7', '8', '9'))
<add> False
<add>
<add> """
<add> return (
<add> int(''.join(combination[0:2])) *
<add> int(''.join(combination[2:5])) ==
<add> int(''.join(combination[5:9]))
<add> ) or (
<add> int(''.join(combination[0])) *
<add> int(''.join(combination[1:5])) ==
<add> int(''.join(combination[5:9]))
<add> )
<add>
<add>
<add>def solution():
<add> """
<add> Finds the sum of all products whose multiplicand/multiplier/product identity
<add> can be written as a 1 through 9 pandigital
<add>
<add> >>> solution()
<add> 45228
<add> """
<add>
<add> return sum(
<add> set(
<add> [
<add> int(''.join(pandigital[5:9]))
<add> for pandigital
<add> in itertools.permutations('123456789')
<add> if isCombinationValid(pandigital)
<add> ]
<add> )
<add> )
<add>
<add>if __name__ == "__main__":
<add> print(solution()) | 1 |
PHP | PHP | update helpers.php | 35a8805603b63e18949cab5bb1c260261ddc1435 | <ide><path>src/Illuminate/Support/helpers.php
<ide> function class_basename($class)
<ide>
<ide> if (! function_exists('class_uses_recursive')) {
<ide> /**
<del> * Returns all traits used by a class, its subclasses and trait of their traits.
<add> * Returns all traits used by a class, its parent classes and trait of their traits.
<ide> *
<ide> * @param object|string $class
<ide> * @return array | 1 |
PHP | PHP | add prefix to key | c6d4546ad866cd32d7bd9b2d8a2ed7a0a03ff346 | <ide><path>src/Illuminate/Cache/RedisTaggedCache.php
<ide> public function forever($key, $value)
<ide> {
<ide> $this->pushForeverKeys($namespace = $this->tags->getNamespace(), $key);
<ide>
<del> parent::forever($key, $value);
<add> $this->store->forever($this->getPrefix().sha1($namespace).':'.$key, $value);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | add backend challenges to test | 78c5b11d08c1e68b2ecf2a0d396c7b1bdf941f8f | <ide><path>curriculum/test/test-challenges.js
<ide> const jQueryScript = fs.readFileSync(
<ide> if (challengeType !== challengeTypes.html &&
<ide> challengeType !== challengeTypes.js &&
<ide> challengeType !== challengeTypes.bonfire &&
<del> challengeType !== challengeTypes.modern
<add> challengeType !== challengeTypes.modern &&
<add> challengeType !== challengeTypes.backend
<ide> ) {
<ide> return;
<ide> } | 1 |
Ruby | Ruby | remove audacity from denylist.rb | 69cf697e2ee94ec7e793d5022bbe9e9f1d09ab15 | <ide><path>Library/Homebrew/cask/denylist.rb
<ide> def self.reason(name)
<ide> case name
<ide> when /^adobe-(after|illustrator|indesign|photoshop|premiere)/
<ide> "Adobe casks were removed because they are too difficult to maintain."
<del> when /^audacity$/
<del> "Audacity was removed because it is too difficult to download programmatically."
<ide> when /^pharo$/
<ide> "Pharo developers maintain their own tap."
<ide> end | 1 |
Javascript | Javascript | fix param name and improve example variable name | 30252a05049c557cf3c05cdf4a8d36fa9e4ab395 | <ide><path>src/ng/compile.js
<ide> * example would not point to the clone, but rather to the original template that was cloned. In
<ide> * this case, you can access the clone via the cloneAttachFn:
<ide> * <pre>
<del> * var templateHTML = angular.element('<p>{{total}}</p>'),
<add> * var templateElement = angular.element('<p>{{total}}</p>'),
<ide> * scope = ....;
<ide> *
<del> * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
<add> * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
<ide> * //attach the clone to DOM document at the right place
<ide> * });
<ide> *
<del> * //now we have reference to the cloned DOM via `clone`
<add> * //now we have reference to the cloned DOM via `clonedElement`
<ide> * </pre>
<ide> *
<ide> *
<ide> function $CompileProvider($provide, $$sanitizeUriProvider) {
<ide> * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
<ide> * the rootElement must be set the jqLite collection of the compile root. This is
<ide> * needed so that the jqLite collection items can be replaced with widgets.
<del> * @param {number=} max directive priority
<add> * @param {number=} maxPriority Max directive priority.
<ide> * @returns {?function} A composite linking function of all of the matched directives or null.
<ide> */
<ide> function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective, | 1 |
Text | Text | add hurb.com as airflow user | d7982577f4e57f3b9fcb1a655a320fd883c457e9 | <ide><path>README.md
<ide> Currently **officially** using Airflow:
<ide> 1. [Hostnfly](https://www.hostnfly.com/) [[@CyrilLeMat](https://github.com/CyrilLeMat) & [@pierrechopin](https://github.com/pierrechopin) & [@alexisrosuel](https://github.com/alexisrosuel)]
<ide> 1. [HotelQuickly](https://github.com/HotelQuickly) [[@zinuzoid](https://github.com/zinuzoid)]
<ide> 1. [Huq Industries](https://huq.io) [[@huqindustries](https://github.com/huq-industries), [@alepuccetti](https://github.com/alepuccetti), [@turbomerl](https://github.com/turbomerl)]
<add>1. [Hurb](https://hurb.com/) [[@hurbcom](https://github.com/hurbcom)]
<ide> 1. [Iflix](https://piay.iflix.com) [[@ChaturvediSulabh](https://github.com/ChaturvediSulabh)]
<ide> 1. [IFTTT](https://www.ifttt.com/) [[@apurvajoshi](https://github.com/apurvajoshi)]
<ide> 1. [iHeartRadio](http://www.iheart.com/)[[@yiwang](https://github.com/yiwang)] | 1 |
Python | Python | add test to show libcloud-910 failure | 4e5ddfbf2ab6c3bbaf7b2092ce3094dff54d5b59 | <ide><path>libcloud/test/test_logging_connection.py
<ide>
<ide> import sys
<ide> from io import StringIO
<add>import zlib
<ide> import requests_mock
<ide>
<ide> import libcloud
<ide> from libcloud.test import unittest
<ide> from libcloud.common.base import Connection
<add>from libcloud.utils.py3 import b
<ide> from libcloud.httplib_ssl import LibcloudConnection
<ide> from libcloud.utils.loggingconnection import LoggingConnection
<ide>
<ide> def test_debug_log_class_handles_request(self):
<ide> self.assertIn('-i -X GET', log)
<ide> self.assertIn('data', log)
<ide>
<add> def test_debug_log_class_handles_request_with_compression(self):
<add> with StringIO() as fh:
<add> libcloud.enable_debug(fh)
<add> conn = Connection(url='http://test.com/')
<add> conn.connect()
<add> self.assertEqual(conn.connection.host, 'http://test.com')
<add> with requests_mock.mock() as m:
<add> m.get('http://test.com/test', content=zlib.compress(b'test'),
<add> headers={'content-encoding': 'zlib'})
<add> conn.request('/test')
<add> log = fh.getvalue()
<add> self.assertTrue(isinstance(conn.connection, LoggingConnection))
<add> self.assertIn('-i -X GET', log)
<add> self.assertIn('data', log)
<add>
<ide> if __name__ == '__main__':
<ide> sys.exit(unittest.main()) | 1 |
Javascript | Javascript | add routenames to rendering assertion warning msg | f31afaea169d6645ff9c7786cdecf30b788dd5a1 | <ide><path>packages/ember-routing/lib/system/route.js
<ide> function parentTemplate(route, isRecursive) {
<ide>
<ide> if (!parent) { return; }
<ide>
<del> Ember.warn("The immediate parent route did not render into the main outlet and the default 'into' option may not be expected", !isRecursive);
<add> Ember.warn("The immediate parent route ('%@') did not render into the main outlet and the default 'into' option ('%@') may not be expected".fmt(get(parent, 'routeName'), get(route, 'routeName')), !isRecursive);
<ide>
<ide> if (template = parent.lastRenderedTemplate) {
<ide> return template; | 1 |
Javascript | Javascript | check queue size before starting animated batch | 55ee8ce0c4157ce5d8a95eaa60b9945b435fc988 | <ide><path>Libraries/Animated/NativeAnimatedHelper.js
<ide> const API = {
<ide> },
<ide> disableQueue: function (): void {
<ide> invariant(NativeAnimatedModule, 'Native animated module is not available');
<del>
<del> if (Platform.OS === 'android') {
<del> NativeAnimatedModule.startOperationBatch();
<del> }
<del> for (let q = 0, l = queue.length; q < l; q++) {
<del> queue[q]();
<del> }
<del> queue.length = 0;
<del> if (Platform.OS === 'android') {
<del> NativeAnimatedModule.finishOperationBatch();
<add> const queueLength = queue.length;
<add> if (queueLength > 0) {
<add> if (Platform.OS === 'android') {
<add> NativeAnimatedModule.startOperationBatch();
<add> }
<add> for (let i = 0; i < queueLength; i++) {
<add> queue[i]();
<add> }
<add> queue.length = 0;
<add> if (Platform.OS === 'android') {
<add> NativeAnimatedModule.finishOperationBatch();
<add> }
<ide> }
<ide> },
<ide> queueOperation: (fn: () => void): void => { | 1 |
Python | Python | fix default num_attention_heads in segformer doc | d55fcbcc50a27f4f5ad8a5c83786905e55212fa0 | <ide><path>src/transformers/models/segformer/configuration_segformer.py
<ide> class SegformerConfig(PretrainedConfig):
<ide> Patch size before each encoder block.
<ide> strides (`List[int]`, *optional*, defaults to [4, 2, 2, 2]):
<ide> Stride before each encoder block.
<del> num_attention_heads (`List[int]`, *optional*, defaults to [1, 2, 4, 8]):
<add> num_attention_heads (`List[int]`, *optional*, defaults to [1, 2, 5, 8]):
<ide> Number of attention heads for each attention layer in each block of the Transformer encoder.
<ide> mlp_ratios (`List[int]`, *optional*, defaults to [4, 4, 4, 4]):
<ide> Ratio of the size of the hidden layer compared to the size of the input layer of the Mix FFNs in the | 1 |
Java | Java | revise use of filterchain in mockmvc | ed9b2966c079b73094f293e5d0c35abd9d59db09 | <ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvc.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<add>import javax.servlet.Filter;
<ide> import javax.servlet.ServletContext;
<ide>
<ide> import org.springframework.beans.Mergeable;
<ide> public final class MockMvc {
<ide>
<ide> static String MVC_RESULT_ATTRIBUTE = MockMvc.class.getName().concat(".MVC_RESULT_ATTRIBUTE");
<ide>
<del> private final MockFilterChain filterChain;
<add> private final TestDispatcherServlet servlet;
<add>
<add> private final Filter[] filters;
<ide>
<ide> private final ServletContext servletContext;
<ide>
<ide> public final class MockMvc {
<ide> * Private constructor, not for direct instantiation.
<ide> * @see org.springframework.test.web.servlet.setup.MockMvcBuilders
<ide> */
<del> MockMvc(MockFilterChain filterChain, ServletContext servletContext) {
<add> MockMvc(TestDispatcherServlet servlet, Filter[] filters, ServletContext servletContext) {
<add>
<add> Assert.notNull(servlet, "DispatcherServlet is required");
<add> Assert.notNull(filters, "filters cannot be null");
<add> Assert.noNullElements(filters, "filters cannot contain null values");
<ide> Assert.notNull(servletContext, "A ServletContext is required");
<del> Assert.notNull(filterChain, "A MockFilterChain is required");
<ide>
<del> this.filterChain = filterChain;
<add> this.servlet = servlet;
<add> this.filters = filters;
<ide> this.servletContext = servletContext;
<ide> }
<ide>
<ide> public ResultActions perform(RequestBuilder requestBuilder) throws Exception {
<ide> final MvcResult mvcResult = new DefaultMvcResult(request, response);
<ide> request.setAttribute(MVC_RESULT_ATTRIBUTE, mvcResult);
<ide>
<del> this.filterChain.reset();
<del> this.filterChain.doFilter(request, response);
<add> MockFilterChain filterChain = new MockFilterChain(this.servlet, this.filters);
<add> filterChain.doFilter(request, response);
<ide>
<ide> applyDefaultResultActions(mvcResult);
<ide>
<ide><path>spring-test-mvc/src/main/java/org/springframework/test/web/servlet/MockMvcBuilderSupport.java
<ide> import javax.servlet.ServletException;
<ide>
<ide> import org.springframework.core.NestedRuntimeException;
<del>import org.springframework.mock.web.MockFilterChain;
<ide> import org.springframework.mock.web.MockServletConfig;
<ide> import org.springframework.web.context.WebApplicationContext;
<ide>
<ide> protected final MockMvc createMockMvc(Filter[] filters, MockServletConfig servle
<ide> throw new MockMvcBuildException("Failed to initialize TestDispatcherServlet", ex);
<ide> }
<ide>
<del> MockFilterChain filterChain = new MockFilterChain(dispatcherServlet, filters);
<del>
<del> MockMvc mockMvc = new MockMvc(filterChain, servletContext);
<add> MockMvc mockMvc = new MockMvc(dispatcherServlet, filters, servletContext);
<ide> mockMvc.setDefaultRequest(defaultRequestBuilder);
<ide> mockMvc.setGlobalResultMatchers(globalResultMatchers);
<ide> mockMvc.setGlobalResultHandlers(globalResultHandlers); | 2 |
Ruby | Ruby | reduce footprint of fails_with_llvm compat code | 456386c9b1cbe599bcc42c96099321ea13afc544 | <ide><path>Library/Homebrew/compat/compatibility.rb
<ide> def self.resolve_alias name
<ide> # up in the DSL section.
<ide> def fails_with_llvm msg=nil, data=nil
<ide> opoo "Calling fails_with_llvm in the install method is deprecated"
<del> puts "Use the fails_with DSL instead."
<del> FailsWithLLVM.new(msg, data).handle_failure
<add> puts "Use the fails_with DSL instead"
<ide> end
<ide>
<ide> def fails_with_llvm?
<ide> fails_with? :llvm
<ide> end
<ide>
<del> def self.fails_with_llvm msg=nil, data=nil
<del> fails_with_llvm_reason = FailsWithLLVM.new(msg, data)
<add> def self.fails_with_llvm msg=nil, data={}
<add> case msg when Hash then data = msg end
<add> failure = CompilerFailure.new(:llvm) { build(data.delete(:build).to_i) }
<ide> @cc_failures ||= Set.new
<del> @cc_failures << fails_with_llvm_reason
<add> @cc_failures << failure
<ide> end
<ide>
<ide> def std_cmake_parameters
<ide> def use_llvm?
<ide> end
<ide> end
<ide>
<del>class FailsWithLLVM
<del> attr_reader :compiler, :build, :cause
<del>
<del> def initialize msg=nil, data=nil
<del> if msg.nil? or msg.kind_of? Hash
<del> @cause = "(No specific reason was given)"
<del> data = msg
<del> else
<del> @cause = msg
<del> end
<del> @build = (data.delete :build rescue nil).to_i
<del> @compiler = :llvm
<del> end
<del>
<del> def handle_failure
<del> return unless ENV.compiler == :llvm
<del>
<del> # version 2336 is the latest version as of Xcode 4.2, so it is the
<del> # latest version we have tested against so we will switch to GCC and
<del> # bump this integer when Xcode 4.3 is released. TODO do that!
<del> if build.to_i >= 2336
<del> if MacOS::Xcode.version < "4.2"
<del> opoo "Formula will not build with LLVM, using GCC"
<del> ENV.gcc
<del> else
<del> opoo "Formula will not build with LLVM, trying Clang"
<del> ENV.clang
<del> end
<del> return
<del> end
<del> opoo "Building with LLVM, but this formula is reported to not work with LLVM:"
<del> puts
<del> puts cause
<del> puts
<del> puts <<-EOS.undent
<del> We are continuing anyway so if the build succeeds, please open a ticket with
<del> the following information: #{MacOS.llvm_build_version}-#{MACOS_VERSION}. So
<del> that we can update the formula accordingly. Thanks!
<del> EOS
<del> puts
<del> if MacOS::Xcode.version < "4.2"
<del> puts "If it doesn't work you can: brew install --use-gcc"
<del> else
<del> puts "If it doesn't work you can try: brew install --use-clang"
<del> end
<del> puts
<del> end
<del>end
<del>
<ide> # TODO eventually some of these should print deprecation warnings
<ide> module MacOS extend self
<ide> def xcode_folder | 1 |
Javascript | Javascript | fix shared handles on windows | 7ca4fa56d054926873e22f390f9ddc97e3182e3e | <ide><path>lib/net.js
<ide> var createServerHandle = exports._createServerHandle =
<ide> return err;
<ide> }
<ide>
<del> if (process.platform === 'win32') {
<del> // On Windows, we always listen to the socket before sending it to
<del> // the worker (see uv_tcp_duplicate_socket). So we better do it here
<del> // so that we can handle any bind-time or listen-time errors early.
<del> err = _listen(handle);
<del> if (err) {
<del> handle.close();
<del> return err;
<del> }
<del> }
<del>
<ide> return handle;
<ide> };
<ide>
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<ide> debug('listen2', address, port, addressType, backlog);
<ide> var self = this;
<ide>
<del> var alreadyListening = false;
<del>
<ide> // If there is not yet a handle, we need to create one and bind.
<ide> // In the case of a server sent via IPC, we don't need to do this.
<ide> if (!self._handle) {
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<ide> });
<ide> return;
<ide> }
<del> alreadyListening = (process.platform === 'win32');
<ide> self._handle = rval;
<ide> } else {
<ide> debug('_listen2: have a handle already');
<ide> Server.prototype._listen2 = function(address, port, addressType, backlog, fd) {
<ide> self._handle.onconnection = onconnection;
<ide> self._handle.owner = self;
<ide>
<del> var err = 0;
<del> if (!alreadyListening)
<del> err = _listen(self._handle, backlog);
<add> var err = _listen(self._handle, backlog);
<ide>
<ide> if (err) {
<ide> var ex = errnoException(err, 'listen'); | 1 |
Java | Java | add requestbody resolver and minor improvements | 2d2726b8f77d7139c2dfdd0e4c0bc1b7591282d7 | <ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/HttpExchange.java
<ide>
<ide> import org.springframework.core.annotation.AliasFor;
<ide> import org.springframework.web.bind.annotation.Mapping;
<add>import org.springframework.web.service.invoker.UrlArgumentResolver;
<ide>
<ide>
<ide> /**
<ide> * <tr>
<ide> * <th>Method Argument</th>
<ide> * <th>Description</th>
<add> * <th>Resolver</th>
<ide> * </tr>
<ide> * <tr>
<del> * <td>{@link org.springframework.http.HttpMethod}</td>
<del> * <td>Set the HTTP method for the request, overriding the annotation
<del> * {@link #method()} attribute value</td>
<add> * <td>{@link java.net.URI URI}</td>
<add> * <td>Dynamically set the URL for the request, overriding the annotation
<add> * {@link #url()} attribute</td>
<add> * <td>{@link UrlArgumentResolver
<add> * HttpUrlArgumentResolver}</td>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.http.HttpMethod HttpMethod}</td>
<add> * <td>Dynamically set the HTTP method for the request, overriding the annotation
<add> * {@link #method()} attribute</td>
<add> * <td>{@link org.springframework.web.service.invoker.HttpMethodArgumentResolver
<add> * HttpMethodArgumentResolver}</td>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.web.bind.annotation.RequestHeader @RequestHeader}</td>
<add> * <td>Add a request header</td>
<add> * <td>{@link org.springframework.web.service.invoker.RequestHeaderArgumentResolver
<add> * RequestHeaderArgumentResolver}</td>
<ide> * </tr>
<ide> * <tr>
<ide> * <td>{@link org.springframework.web.bind.annotation.PathVariable @PathVariable}</td>
<del> * <td>Provide a path variable to expand the URI template with. This may be an
<del> * individual value or a Map of values.</td>
<add> * <td>Add a path variable for the URI template</td>
<add> * <td>{@link org.springframework.web.service.invoker.PathVariableArgumentResolver
<add> * PathVariableArgumentResolver}</td>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.web.bind.annotation.RequestBody @RequestBody}</td>
<add> * <td>Set the body of the request</td>
<add> * <td>{@link org.springframework.web.service.invoker.RequestBodyArgumentResolver
<add> * RequestBodyArgumentResolver}</td>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.web.bind.annotation.RequestParam @RequestParam}</td>
<add> * <td>Add a request parameter, either form data if {@code "Content-Type"} is
<add> * {@code "application/x-www-form-urlencoded"} or query params otherwise</td>
<add> * <td>{@link org.springframework.web.service.invoker.RequestParamArgumentResolver
<add> * RequestParamArgumentResolver}</td>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.web.bind.annotation.CookieValue @CookieValue}</td>
<add> * <td>Add a cookie</td>
<add> * <td>{@link org.springframework.web.service.invoker.CookieValueArgumentResolver
<add> * CookieValueArgumentResolver}</td>
<ide> * </tr>
<ide> * </table>
<ide> *
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpMethodArgumentResolver.java
<ide> public class HttpMethodArgumentResolver implements HttpServiceArgumentResolver {
<ide> public boolean resolve(
<ide> @Nullable Object argument, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
<ide>
<del> if (argument instanceof HttpMethod httpMethod) {
<add> if (!parameter.getParameterType().equals(HttpMethod.class)) {
<add> return false;
<add> }
<add>
<add> if (argument != null) {
<add> HttpMethod httpMethod = (HttpMethod) argument;
<add> requestValues.setHttpMethod(httpMethod);
<ide> if (logger.isTraceEnabled()) {
<ide> logger.trace("Resolved HTTP method to: " + httpMethod.name());
<ide> }
<del> requestValues.setHttpMethod(httpMethod);
<del> return true;
<ide> }
<ide>
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpRequestValues.java
<ide> public void setBodyValue(Object bodyValue) {
<ide> * <p>This is mutually exclusive with, and resets any previously set
<ide> * {@link #setBodyValue(Object) body value}.
<ide> */
<del> public <T, P extends Publisher<T>> void setBody(Publisher<P> body, ParameterizedTypeReference<?> elementTye) {
<add> public <T, P extends Publisher<T>> void setBody(P body, ParameterizedTypeReference<T> elementTye) {
<ide> this.body = body;
<ide> this.bodyElementType = elementTye;
<ide> this.bodyValue = null;
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpServiceMethod.java
<ide> private void applyArguments(HttpRequestValues.Builder requestValues, Object[] ar
<ide> Assert.isTrue(arguments.length == this.parameters.length, "Method argument mismatch");
<ide> for (int i = 0; i < arguments.length; i++) {
<ide> Object value = arguments[i];
<add> boolean resolved = false;
<ide> for (HttpServiceArgumentResolver resolver : this.argumentResolvers) {
<ide> if (resolver.resolve(value, this.parameters[i], requestValues)) {
<add> resolved = true;
<ide> break;
<ide> }
<ide> }
<add> Assert.state(resolved, formatArgumentError(this.parameters[i], "No suitable resolver"));
<ide> }
<ide> }
<ide>
<add> private static String formatArgumentError(MethodParameter param, String message) {
<add> return "Could not resolve parameter [" + param.getParameterIndex() + "] in " +
<add> param.getExecutable().toGenericString() + (StringUtils.hasText(message) ? ": " + message : "");
<add> }
<add>
<ide>
<ide> /**
<ide> * Factory for an {@link HttpRequestValues} with values extracted from
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpServiceProxyFactory.java
<ide> private ConversionService initConversionService() {
<ide> private List<HttpServiceArgumentResolver> initArgumentResolvers(ConversionService conversionService) {
<ide> List<HttpServiceArgumentResolver> resolvers = new ArrayList<>(this.customResolvers);
<ide> resolvers.add(new RequestHeaderArgumentResolver(conversionService));
<add> resolvers.add(new RequestBodyArgumentResolver(this.reactiveAdapterRegistry));
<ide> resolvers.add(new PathVariableArgumentResolver(conversionService));
<del> resolvers.add(new CookieValueArgumentResolver(conversionService));
<ide> resolvers.add(new RequestParamArgumentResolver(conversionService));
<del> resolvers.add(new HttpUrlArgumentResolver());
<add> resolvers.add(new CookieValueArgumentResolver(conversionService));
<add> resolvers.add(new UrlArgumentResolver());
<ide> resolvers.add(new HttpMethodArgumentResolver());
<ide> return resolvers;
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/RequestBodyArgumentResolver.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.service.invoker;
<add>
<add>import org.reactivestreams.Publisher;
<add>
<add>import org.springframework.core.MethodParameter;
<add>import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.core.ReactiveAdapter;
<add>import org.springframework.core.ReactiveAdapterRegistry;
<add>import org.springframework.lang.Nullable;
<add>import org.springframework.util.Assert;
<add>import org.springframework.web.bind.annotation.RequestBody;
<add>
<add>
<add>/**
<add> * {@link HttpServiceArgumentResolver} for {@link RequestBody @RequestBody}
<add> * annotated arguments.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 6.0
<add> */
<add>public class RequestBodyArgumentResolver implements HttpServiceArgumentResolver {
<add>
<add> private final ReactiveAdapterRegistry reactiveAdapterRegistry;
<add>
<add>
<add> public RequestBodyArgumentResolver(ReactiveAdapterRegistry reactiveAdapterRegistry) {
<add> Assert.notNull(reactiveAdapterRegistry, "ReactiveAdapterRegistry is required");
<add> this.reactiveAdapterRegistry = reactiveAdapterRegistry;
<add> }
<add>
<add>
<add> @Override
<add> public boolean resolve(
<add> @Nullable Object argument, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
<add>
<add> RequestBody annot = parameter.getParameterAnnotation(RequestBody.class);
<add> if (annot == null) {
<add> return false;
<add> }
<add>
<add> if (argument != null) {
<add> ReactiveAdapter reactiveAdapter = this.reactiveAdapterRegistry.getAdapter(parameter.getParameterType());
<add> if (reactiveAdapter != null) {
<add> setBody(argument, parameter, reactiveAdapter, requestValues);
<add> }
<add> else {
<add> requestValues.setBodyValue(argument);
<add> }
<add> }
<add>
<add> return true;
<add> }
<add>
<add> private <E> void setBody(
<add> Object argument, MethodParameter parameter, ReactiveAdapter reactiveAdapter,
<add> HttpRequestValues.Builder requestValues) {
<add>
<add> String message = "Async type for @RequestBody should produce value(s)";
<add> Assert.isTrue(!reactiveAdapter.isNoValue(), message);
<add>
<add> parameter = parameter.nested();
<add> Class<?> elementClass = parameter.getNestedParameterType();
<add> Assert.isTrue(elementClass != Void.class, message);
<add> ParameterizedTypeReference<E> typeRef = ParameterizedTypeReference.forType(parameter.getNestedGenericParameterType());
<add> Publisher<E> publisher = reactiveAdapter.toPublisher(argument);
<add>
<add> requestValues.setBody(publisher, typeRef);
<add> }
<add>
<add>}
<add><path>spring-web/src/main/java/org/springframework/web/service/invoker/UrlArgumentResolver.java
<del><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpUrlArgumentResolver.java
<ide> import java.net.URI;
<ide>
<ide> import org.springframework.core.MethodParameter;
<del>import org.springframework.http.HttpMethod;
<ide> import org.springframework.lang.Nullable;
<ide>
<ide>
<ide> /**
<del> * {@link HttpServiceArgumentResolver} that resolves the target
<del> * request's URL from an {@link HttpMethod} argument.
<add> * {@link HttpServiceArgumentResolver} that resolves the URL for the request
<add> * from an {@link URI} argument.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 6.0
<ide> */
<del>public class HttpUrlArgumentResolver implements HttpServiceArgumentResolver {
<add>public class UrlArgumentResolver implements HttpServiceArgumentResolver {
<ide>
<ide> @Override
<ide> public boolean resolve(
<ide> @Nullable Object argument, MethodParameter parameter, HttpRequestValues.Builder requestValues) {
<ide>
<del> if (argument instanceof URI uri) {
<del> requestValues.setUri(uri);
<add> if (!parameter.getParameterType().equals(URI.class)) {
<add> return false;
<add> }
<add>
<add> if (argument != null) {
<add> requestValues.setUri((URI) argument);
<ide> return true;
<ide> }
<ide>
<del> return false;
<add> return true;
<ide> }
<ide>
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/web/service/invoker/HttpMethodArgumentResolverTests.java
<ide> import org.springframework.web.service.annotation.GetExchange;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<ide>
<ide>
<ide> /**
<ide> void requestMethodOverride() {
<ide> }
<ide>
<ide> @Test
<del> void ignoreOtherArgumentTypes() {
<del> this.service.execute("test");
<del> assertThat(getActualMethod()).isEqualTo(HttpMethod.GET);
<add> void notHttpMethod() {
<add> assertThatIllegalStateException()
<add> .isThrownBy(() -> this.service.executeNotHttpMethod("test"))
<add> .withMessage("Could not resolve parameter [0] in " +
<add> "public abstract void org.springframework.web.service.invoker." +
<add> "HttpMethodArgumentResolverTests$Service.executeNotHttpMethod(java.lang.String): " +
<add> "No suitable resolver");
<ide> }
<ide>
<ide> @Test
<ide> void ignoreNull() {
<del> this.service.execute((HttpMethod) null);
<add> this.service.execute(null);
<ide> assertThat(getActualMethod()).isEqualTo(HttpMethod.GET);
<ide> }
<ide>
<ide> private interface Service {
<ide> void execute(HttpMethod method);
<ide>
<ide> @GetExchange
<del> void execute(String test);
<add> void executeNotHttpMethod(String test);
<ide>
<ide> }
<ide>
<ide><path>spring-web/src/test/java/org/springframework/web/service/invoker/RequestBodyArgumentResolverTests.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.service.invoker;
<add>
<add>import io.reactivex.rxjava3.core.Completable;
<add>import io.reactivex.rxjava3.core.Single;
<add>import org.junit.jupiter.api.Test;
<add>import org.reactivestreams.Publisher;
<add>import reactor.core.publisher.Mono;
<add>
<add>import org.springframework.core.ParameterizedTypeReference;
<add>import org.springframework.web.bind.annotation.RequestBody;
<add>import org.springframework.web.service.annotation.GetExchange;
<add>
<add>import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<add>
<add>
<add>/**
<add> * Unit tests for {@link RequestBodyArgumentResolver}.
<add> *
<add> * @author Rossen Stoyanchev
<add> */
<add>public class RequestBodyArgumentResolverTests {
<add>
<add> private final TestHttpClientAdapter client = new TestHttpClientAdapter();
<add>
<add> private final Service service = HttpServiceProxyFactory.builder(this.client).build().createClient(Service.class);
<add>
<add>
<add> @Test
<add> void stringBody() {
<add> String body = "bodyValue";
<add> this.service.execute(body);
<add>
<add> assertThat(getRequestValues().getBodyValue()).isEqualTo(body);
<add> assertThat(getRequestValues().getBody()).isNull();
<add> }
<add>
<add> @Test
<add> void monoBody() {
<add> Mono<String> bodyMono = Mono.just("bodyValue");
<add> this.service.executeMono(bodyMono);
<add>
<add> assertThat(getRequestValues().getBodyValue()).isNull();
<add> assertThat(getRequestValues().getBody()).isSameAs(bodyMono);
<add> assertThat(getRequestValues().getBodyElementType()).isEqualTo(new ParameterizedTypeReference<String>() {});
<add> }
<add>
<add> @Test
<add> void singleBody() {
<add> String bodyValue = "bodyValue";
<add> this.service.executeSingle(Single.just(bodyValue));
<add>
<add> assertThat(getRequestValues().getBodyValue()).isNull();
<add> assertThat(getRequestValues().getBodyElementType()).isEqualTo(new ParameterizedTypeReference<String>() {});
<add>
<add> Publisher<?> body = getRequestValues().getBody();
<add> assertThat(body).isNotNull();
<add> assertThat(((Mono<String>) body).block()).isEqualTo(bodyValue);
<add> }
<add>
<add> @Test
<add> void monoVoid() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> this.service.executeMonoVoid(Mono.empty()))
<add> .withMessage("Async type for @RequestBody should produce value(s)");
<add> }
<add>
<add> @Test
<add> void completable() {
<add> assertThatIllegalArgumentException()
<add> .isThrownBy(() -> this.service.executeCompletable(Completable.complete()))
<add> .withMessage("Async type for @RequestBody should produce value(s)");
<add> }
<add>
<add> @Test
<add> void notRequestBody() {
<add> assertThatIllegalStateException()
<add> .isThrownBy(() -> this.service.executeNotRequestBody("value"))
<add> .withMessage("Could not resolve parameter [0] in " +
<add> "public abstract void org.springframework.web.service.invoker." +
<add> "RequestBodyArgumentResolverTests$Service.executeNotRequestBody(java.lang.String): " +
<add> "No suitable resolver");
<add> }
<add>
<add> @Test
<add> void ignoreNull() {
<add> this.service.execute(null);
<add>
<add> assertThat(getRequestValues().getBodyValue()).isNull();
<add> assertThat(getRequestValues().getBody()).isNull();
<add>
<add> this.service.executeMono(null);
<add>
<add> assertThat(getRequestValues().getBodyValue()).isNull();
<add> assertThat(getRequestValues().getBody()).isNull();
<add> }
<add>
<add> private HttpRequestValues getRequestValues() {
<add> return this.client.getRequestValues();
<add> }
<add>
<add>
<add> private interface Service {
<add>
<add> @GetExchange
<add> void execute(@RequestBody String body);
<add>
<add> @GetExchange
<add> void executeMono(@RequestBody Mono<String> body);
<add>
<add> @GetExchange
<add> void executeSingle(@RequestBody Single<String> body);
<add>
<add> @GetExchange
<add> void executeMonoVoid(@RequestBody Mono<Void> body);
<add>
<add> @GetExchange
<add> void executeCompletable(@RequestBody Completable body);
<add>
<add> @GetExchange
<add> void executeNotRequestBody(String body);
<add> }
<add>
<add>}
<add><path>spring-web/src/test/java/org/springframework/web/service/invoker/UrlArgumentResolverTests.java
<del><path>spring-web/src/test/java/org/springframework/web/service/invoker/HttpUrlArgumentResolverTests.java
<ide> import org.springframework.web.service.annotation.GetExchange;
<ide>
<ide> import static org.assertj.core.api.Assertions.assertThat;
<add>import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<ide>
<ide>
<ide> /**
<del> * Unit tests for {@link HttpUrlArgumentResolver}.
<add> * Unit tests for {@link UrlArgumentResolver}.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class HttpUrlArgumentResolverTests {
<add>public class UrlArgumentResolverTests {
<ide>
<ide> private final TestHttpClientAdapter client = new TestHttpClientAdapter();
<ide>
<ide> void url() {
<ide> assertThat(getRequestValues().getUriTemplate()).isNull();
<ide> }
<ide>
<add> @Test
<add> void notUrl() {
<add> assertThatIllegalStateException()
<add> .isThrownBy(() -> this.service.executeNotUri("test"))
<add> .withMessage("Could not resolve parameter [0] in " +
<add> "public abstract void org.springframework.web.service.invoker." +
<add> "UrlArgumentResolverTests$Service.executeNotUri(java.lang.String): " +
<add> "No suitable resolver");
<add> }
<add>
<add> @Test
<add> void ignoreNull() {
<add> this.service.execute(null);
<add> assertThat(getRequestValues().getUri()).isNull();
<add> }
<add>
<ide> private HttpRequestValues getRequestValues() {
<ide> return this.client.getRequestValues();
<ide> }
<ide> private interface Service {
<ide> @GetExchange("/path")
<ide> void execute(URI uri);
<ide>
<add> @GetExchange
<add> void executeNotUri(String other);
<ide> }
<ide>
<ide> } | 10 |
Python | Python | increase docker compose test wait time | af76f64ccd4064e60953c6c5aa956102a553f597 | <ide><path>docker_tests/test_docker_compose_quick_start.py
<ide> def wait_for_container(container_id: str, timeout: int = 300):
<ide>
<ide>
<ide> def wait_for_terminal_dag_state(dag_id, dag_run_id):
<del> # Wait 30 seconds
<del> for _ in range(30):
<add> # Wait 80 seconds
<add> for _ in range(80):
<ide> dag_state = api_request("GET", f"dags/{dag_id}/dagRuns/{dag_run_id}").get("state")
<ide> print(f"Waiting for DAG Run: dag_state={dag_state}")
<ide> sleep(1) | 1 |
Javascript | Javascript | exclude graceful-fs from snapshot | 54a813eda91803066fc1bd4e91ba591931588750 | <ide><path>script/lib/generate-startup-snapshot.js
<ide> module.exports = function (packagedAppPath) {
<ide> relativePath == path.join('..', 'node_modules', 'debug', 'node.js') ||
<ide> relativePath == path.join('..', 'node_modules', 'git-utils', 'lib', 'git.js') ||
<ide> relativePath == path.join('..', 'node_modules', 'glob', 'glob.js') ||
<add> relativePath == path.join('..', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
<ide> relativePath == path.join('..', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
<ide> relativePath == path.join('..', 'node_modules', 'iconv-lite', 'encodings', 'index.js') ||
<ide> relativePath == path.join('..', 'node_modules', 'less', 'index.js') || | 1 |
Ruby | Ruby | remove return guard and use code convetions | f058e565c1f7ab36199887a56696edb01d85e2cf | <ide><path>activerecord/lib/active_record/persistence.rb
<ide> def update_attribute(name, value)
<ide> name = name.to_s
<ide> verify_readonly_attribute(name)
<ide> send("#{name}=", value)
<del> save(:validate => false)
<add> save(validate: false)
<ide> end
<ide>
<ide> # Updates the attributes of the model from the passed-in hash and saves the
<ide> def update_columns(attributes)
<ide>
<ide> updated_count = self.class.where(self.class.primary_key => id).update_all(attributes)
<ide>
<del> attributes.each do |k,v|
<del> raw_write_attribute(k,v)
<add> attributes.each do |k, v|
<add> raw_write_attribute(k, v)
<ide> end
<ide>
<ide> updated_count == 1
<ide> def create_or_update
<ide> # Returns the number of affected rows.
<ide> def update(attribute_names = @attributes.keys)
<ide> attributes_with_values = arel_attributes_with_values_for_update(attribute_names)
<del> return 0 if attributes_with_values.empty?
<del> klass = self.class
<del> stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
<del> klass.connection.update stmt
<add>
<add> if attributes_with_values.empty?
<add> 0
<add> else
<add> klass = self.class
<add> stmt = klass.unscoped.where(klass.arel_table[klass.primary_key].eq(id)).arel.compile_update(attributes_with_values)
<add> klass.connection.update stmt
<add> end
<ide> end
<ide>
<ide> # Creates a record with values matching those of the instance attributes | 1 |
Ruby | Ruby | fix errors with check suites without workflow runs | 17ee0eefb8107067fa3d1793a008dce6a8b352a8 | <ide><path>Library/Homebrew/utils/github.rb
<ide> def get_workflow_run(user, repo, pr, workflow_id: "tests.yml", artifact_name: "b
<ide> commit_node = result["repository"]["pullRequest"]["commits"]["nodes"].first
<ide> check_suite = if commit_node.present?
<ide> commit_node["commit"]["checkSuites"]["nodes"].select do |suite|
<del> suite["workflowRun"]["workflow"]["databaseId"] == workflow_id_num
<add> suite.dig("workflowRun", "workflow", "databaseId") == workflow_id_num
<ide> end
<ide> else
<ide> [] | 1 |
Text | Text | add short description of asp.net frameworks | 9c95c7cf564c89657cf76d7c27ee9adca44dc33f | <ide><path>guide/english/aspnet/index.md
<ide> title: ASPNET
<ide> ASP.Net is a web development platform provided by Microsoft. It is used for creating web-based applications and websites using HTML, CSS, and JavaScript as front end.
<ide> Server-side programming languages like C# and VB .NET may be used to code the back end.
<ide>
<del>ASP.NET offers different frameworks for creating web applications, e.g. Web Forms, ASP.NET MVC, ASP.NET Web API, SignalR etc.
<add>ASP.NET offers different frameworks for creating web applications: For e.g ASP.NET Web Forms, ASP.NET Web Pages, ASP.NET MVC.
<add>
<add>#### ASP.NET Web Forms
<add>ASP.NET Web Forms is the oldest part of ASP.NET for building websites. The workflow is based on events and the pages are created using large number of components that are available for rapid application development, HTML language and any server-side language supported by the .NET common language runtime, such as Microsoft Visual Basic and Microsoft Visual C#. Websites are compiled on the server side and the HTML code is send to the browser.
<add>
<add>Advantages of Web Forms:
<add>- separation of user interface from application logic
<add>- large number of components that are available for rapid application development (drag and drop)
<add>- ensures fast implementation of small projects
<add>- easy to learn
<add>
<add>Disadvantages of Web Forms:
<add>- poor performance in large projects because of state control of components
<add>- no support for unit tests
<add>- poor search enginge optimization
<add>- low reusability of code
<add>- no support for Separation of Concern
<add>
<add>#### ASP.NET Web Pages
<add>ASP.NET Web Pages is a framework for creating small and simple websites. Web Pages can be created using free WebMatrix editor. WebMatrix is an application containing text editor, tools for managing databases and application test server. In Web Pages views are created using Razor language (just like in ASP.NET MVC).
<add>
<add>#### ASP.NET MVC
<add>ASP.NET MVC is a framework for building web applications based on MVC pattern (model-view-controller). ASP.NET MVC is a great solution for creating large web applications as it support Separation of Concern, unit tests, has modular constuction and make it easy to maintain even large applications. With MVC pattern there is a clear separation between business logic and views. For creating views razor language is used and for business logic can be used any language supported by the .NET common language runtime (ex. C#, VB).
<ide>
<ide> #### More Information:
<ide> - [ASP .NET Tutorials](https://www.tutorialspoint.com/asp.net/) | 1 |
Javascript | Javascript | invalidate concatenated module on dep change | bd7652823c5c682f43d0c8c02fb34be516ac6afb | <ide><path>lib/optimize/ConcatenatedModule.js
<ide> class ConcatenatedModule extends Module {
<ide> moduleToInfoMap
<ide> )
<ide> );
<add>
<add> // Must use full identifier in our cache here to ensure that the source
<add> // is updated should our dependencies list change.
<ide> innerDependencyTemplates.set(
<ide> "hash",
<del> innerDependencyTemplates.get("hash") + this.rootModule.identifier()
<add> innerDependencyTemplates.get("hash") + this.identifier()
<ide> );
<ide>
<ide> // Generate source code and analyse scopes | 1 |
Java | Java | add remaining httpexchange annotations | 8a46e968751f566b3bc87623bc0a2957789d47ce | <ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/DeleteExchange.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.service.annotation;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>import org.springframework.core.annotation.AliasFor;
<add>
<add>
<add>/**
<add> * Shortcut for {@link HttpExchange} for HTTP DELETE requests.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 6.0
<add> */
<add>@Target(ElementType.METHOD)
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@Documented
<add>@HttpExchange(method = "DELETE")
<add>public @interface DeleteExchange {
<add>
<add> /**
<add> * Alias for {@link HttpExchange#value}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] value() default {};
<add>
<add> /**
<add> * Alias for {@link HttpExchange#url()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] url() default {};
<add>
<add> /**
<add> * Alias for {@link HttpExchange#contentType()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String contentType() default "";
<add>
<add> /**
<add> * Alias for {@link HttpExchange#accept()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] accept() default {};
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/HeadExchange.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.service.annotation;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>import org.springframework.core.annotation.AliasFor;
<add>
<add>
<add>/**
<add> * Shortcut for {@link HttpExchange} for HTTP HEAD requests.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 6.0
<add> */
<add>@Target(ElementType.METHOD)
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@Documented
<add>@HttpExchange(method = "HEAD")
<add>public @interface HeadExchange {
<add>
<add> /**
<add> * Alias for {@link HttpExchange#value}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String value() default "";
<add>
<add> /**
<add> * Alias for {@link HttpExchange#url()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String url() default "";
<add>
<add> /**
<add> * Alias for {@link HttpExchange#accept()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] accept() default {};
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/HttpExchange.java
<ide> import org.springframework.core.annotation.AliasFor;
<ide> import org.springframework.web.bind.annotation.Mapping;
<ide>
<add>
<ide> /**
<del> * Supported method parameters:
<add> * Annotation that declares an HTTP service method as an HTTP endpoint defined
<add> * through attributes of the annotation and method argument values.
<add> *
<add> * <p>The annotation may only be used at the type level for example to specify
<add> * a base URL path. At the method level, use one of the HTTP method specific,
<add> * shortcut annotations, each of which is <em>meta-annotated</em> with
<add> * {@link HttpExchange}:
<ide> * <ul>
<del> * <li>{@link java.net.URI} -- dynamic URL
<del> * <li>{@link org.springframework.http.HttpMethod} - dynamic HTTP method
<del> * <li>{@link org.springframework.http.HttpHeaders} - request headers
<del> * <li>{@link org.springframework.http.HttpCookie} - request headers
<del> * <li>...
<add> * <li>{@link GetExchange}
<add> * <li>{@link PostExchange}
<add> * <li>{@link PutExchange}
<add> * <li>{@link PatchExchange}
<add> * <li>{@link DeleteExchange}
<add> * <li>{@link OptionsExchange}
<add> * <li>{@link HeadExchange}
<ide> * </ul>
<ide> *
<add> * <p>Supported method arguments:
<add> * <table>
<add> * <tr>
<add> * <th>Method Argument</th>
<add> * <th>Description</th>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.http.HttpMethod}</td>
<add> * <td>Set the HTTP method for the request, overriding the annotation
<add> * {@link #method()} attribute value</td>
<add> * </tr>
<add> * <tr>
<add> * <td>{@link org.springframework.web.bind.annotation.PathVariable @PathVariable}</td>
<add> * <td>Provide a path variable to expand the URI template with. This may be an
<add> * individual value or a Map of values.</td>
<add> * </tr>
<add> * </table>
<add> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 6.0
<ide> */
<del>@Target({ElementType.TYPE, ElementType.METHOD})
<add>@Target(ElementType.TYPE)
<ide> @Retention(RetentionPolicy.RUNTIME)
<ide> @Documented
<ide> @Mapping
<ide> */
<ide> String[] accept() default {};
<ide>
<del>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/OptionsExchange.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.service.annotation;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>import org.springframework.core.annotation.AliasFor;
<add>
<add>
<add>/**
<add> * Shortcut for {@link HttpExchange} for HTTP OPTIONS requests.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 6.0
<add> */
<add>@Target(ElementType.METHOD)
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@Documented
<add>@HttpExchange(method = "OPTIONS")
<add>public @interface OptionsExchange {
<add>
<add> /**
<add> * Alias for {@link HttpExchange#value}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String value() default "";
<add>
<add> /**
<add> * Alias for {@link HttpExchange#url()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String url() default "";
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/PatchExchange.java
<add>/*
<add> * Copyright 2002-2022 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * https://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.web.service.annotation;
<add>
<add>import java.lang.annotation.Documented;
<add>import java.lang.annotation.ElementType;
<add>import java.lang.annotation.Retention;
<add>import java.lang.annotation.RetentionPolicy;
<add>import java.lang.annotation.Target;
<add>
<add>import org.springframework.core.annotation.AliasFor;
<add>
<add>
<add>/**
<add> * Shortcut for {@link HttpExchange} for HTTP PATCH requests.
<add> *
<add> * @author Rossen Stoyanchev
<add> * @since 6.0
<add> */
<add>@Target(ElementType.METHOD)
<add>@Retention(RetentionPolicy.RUNTIME)
<add>@Documented
<add>@HttpExchange(method = "PATCH")
<add>public @interface PatchExchange {
<add>
<add> /**
<add> * Alias for {@link HttpExchange#value}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] value() default {};
<add>
<add> /**
<add> * Alias for {@link HttpExchange#url()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] url() default {};
<add>
<add> /**
<add> * Alias for {@link HttpExchange#contentType()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String contentType() default "";
<add>
<add> /**
<add> * Alias for {@link HttpExchange#accept()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] accept() default {};
<add>
<add>}
<ide><path>spring-web/src/main/java/org/springframework/web/service/annotation/PutExchange.java
<ide> @AliasFor(annotation = HttpExchange.class)
<ide> String contentType() default "";
<ide>
<add> /**
<add> * Alias for {@link HttpExchange#accept()}.
<add> */
<add> @AliasFor(annotation = HttpExchange.class)
<add> String[] accept() default {};
<add>
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/web/service/invoker/HttpClientAdapter.java
<ide> */
<ide> public interface HttpClientAdapter {
<ide>
<add> /**
<add> * Perform the given request, and release the response content, if any.
<add> * @param requestValues the request to perform
<add> * @return {@code Mono} that completes when the request is fully executed
<add> * and the response content is released.
<add> */
<ide> Mono<Void> requestToVoid(HttpRequestValues requestValues);
<ide>
<add> /**
<add> * Perform the given request, release the response content, and return the
<add> * response headers.
<add> * @param requestValues the request to perform
<add> * @return {@code Mono} that returns the response headers the request is
<add> * fully executed and the response content released.
<add> */
<ide> Mono<HttpHeaders> requestToHeaders(HttpRequestValues requestValues);
<ide>
<add> /**
<add> * Perform the given request and decode the response content to the given type.
<add> * @param requestValues the request to perform
<add> * @param bodyType the target type to decode to
<add> * @return {@code Mono} that returns the decoded response.
<add> * @param <T> the type the response is decoded to
<add> */
<ide> <T> Mono<T> requestToBody(HttpRequestValues requestValues, ParameterizedTypeReference<T> bodyType);
<ide>
<add> /**
<add> * Perform the given request and decode the response content to a stream with
<add> * elements of the given type.
<add> * @param requestValues the request to perform
<add> * @param bodyType the target stream element type to decode to
<add> * @return {@code Flux} with decoded stream elements.
<add> * @param <T> the type the response is decoded to
<add> */
<ide> <T> Flux<T> requestToBodyFlux(HttpRequestValues requestValues, ParameterizedTypeReference<T> bodyType);
<ide>
<add> /**
<add> * Variant of {@link #requestToVoid(HttpRequestValues)} with additional
<add> * access to the response status and headers.
<add> */
<ide> Mono<ResponseEntity<Void>> requestToBodilessEntity(HttpRequestValues requestValues);
<ide>
<add> /**
<add> * Variant of {@link #requestToBody(HttpRequestValues, ParameterizedTypeReference)}
<add> * with additional access to the response status and headers.
<add> */
<ide> <T> Mono<ResponseEntity<T>> requestToEntity(HttpRequestValues requestValues, ParameterizedTypeReference<T> bodyType);
<ide>
<add> /**
<add> * Variant of {@link #requestToBodyFlux(HttpRequestValues, ParameterizedTypeReference)}
<add> * with additional access to the response status and headers.
<add> */
<ide> <T> Mono<ResponseEntity<Flux<T>>> requestToEntityFlux(HttpRequestValues requestValues, ParameterizedTypeReference<T> bodyType);
<ide>
<ide> } | 7 |
Text | Text | remove white space for quick fix | bce3d5b372934c5d94ff18d52dc6b7375c2405fb | <ide><path>curriculum/challenges/english/02-javascript-algorithms-and-data-structures/functional-programming/use-higher-order-functions-map-filter-or-reduce-to-solve-a-complex-problem.md
<ide> ---
<ide> id: 587d7b88367417b2b2512b45
<del>title: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem
<add>title: Use Higher-Order Functions map, filter, or reduce to Solve a Complex Problem
<ide> challengeType: 1
<ide> forumTopicId: 301311
<ide> ---
<ide>
<ide> ## Description
<add>
<ide> <section id='description'>
<ide> Now that you have worked through a few challenges using higher-order functions like <code>map()</code>, <code>filter()</code>, and <code>reduce()</code>, you now get to apply them to solve a more complex challenge.
<ide> </section>
<ide>
<ide> ## Instructions
<add>
<ide> <section id='instructions'>
<ide> We have defined a function named <code>squareList</code>. You need to complete the code for the <code>squareList</code> function using any combination of <code>map()</code>, <code>filter()</code>, and <code>reduce()</code> so that it returns a new array containing only the square of <em>only</em> the positive integers (decimal numbers are not integers) when an array of real numbers is passed to it. An example of an array containing only real numbers is <code>[-3, 4.8, 5, 3, -3.2]</code>.
<ide> <strong>Note:</strong> Your function should not use any kind of <code>for</code> or <code>while</code> loops or the <code>forEach()</code> function.
<ide> </section>
<ide>
<ide> ## Tests
<add>
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<ide> - text: <code>squareList</code> should be a <code>function</code>.
<ide> testString: assert.typeOf(squareList, 'function'), '<code>squareList</code> should be a <code>function</code>';
<del> - text: for or while loops or forEach should not be used.
<add> - text: <code>for</code>, <code>while</code>, and <code>forEach</code> should not be used.
<ide> testString: assert(!__helpers.removeJSComments(code).match(/for|while|forEach/g));
<ide> - text: <code>map</code>, <code>filter</code>, or <code>reduce</code> should be used.
<del> testString: assert(__helpers.removeJSComments(code).match(/\.(map|filter|reduce)\s*\(/g));
<add> testString: assert(__helpers.removeWhiteSpace(__helpers.removeJSComments(code)).match(/\.(map|filter|reduce)\(/g));
<ide> - text: The function should return an <code>array</code>.
<ide> testString: assert(Array.isArray(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])));
<ide> - text: <code>squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2])</code> should return <code>[16, 1764, 36]</code>.
<ide> testString: assert.deepStrictEqual(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]), [16, 1764, 36]);
<ide> - text: <code>squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3])</code> should return <code>[9, 100, 49]</code>.
<del> testString: assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [9, 100, 49]);
<add> testString: assert.deepStrictEqual(squareList([-3.7, -5, 3, 10, 12.5, 7, -4.5, -17, 0.3]), [9, 100, 49]);
<ide> ```
<ide>
<ide> </section>
<ide>
<ide> ## Challenge Seed
<add>
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide>
<ide> ```js
<del>const squareList = (arr) => {
<add>const squareList = arr => {
<ide> // Only change code below this line
<ide> return arr;
<ide> // Only change code above this line
<ide> console.log(squaredIntegers);
<ide> </section>
<ide>
<ide> ## Solution
<add>
<ide> <section id='solution'>
<ide>
<ide> ```js
<del>const squareList = (arr) => {
<add>const squareList = arr => {
<ide> const positiveIntegers = arr.filter(num => {
<ide> return num >= 0 && Number.isInteger(num);
<ide> }); | 1 |
PHP | PHP | reject controller names that are not camel case | 8994971b67bc712b5096730cd379371c63f80dc1 | <ide><path>src/Controller/Controller.php
<ide> public function __construct(Request $request = null, Response $response = null,
<ide> }
<ide>
<ide> if ($this->name === null && isset($request->params['controller'])) {
<del> $this->name = Inflector::camelize($request->params['controller']);
<add> $this->name = $request->params['controller'];
<ide> }
<ide>
<ide> if ($this->name === null) {
<ide><path>src/Routing/Filter/ControllerFactoryFilter.php
<ide> protected function _getController($request, $response)
<ide> );
<ide> $namespace .= '/' . implode('/', $prefixes);
<ide> }
<del> if (strpos($controller, '\\') !== false || strpos($controller, '.') !== false) {
<add> $firstChar = substr($controller, 0, 1);
<add> if (
<add> strpos($controller, '\\') !== false ||
<add> strpos($controller, '.') !== false ||
<add> $firstChar === strtolower($firstChar)
<add> ) {
<ide> return false;
<ide> }
<ide> $className = false;
<ide><path>tests/TestCase/Controller/ControllerTest.php
<ide> public function testConstructSetModelClass()
<ide> $this->assertEquals('Posts', $controller->modelClass);
<ide> $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
<ide>
<del> $request->params['controller'] = 'posts';
<del> $controller = new \TestApp\Controller\PostsController($request, $response);
<del> $this->assertEquals('Posts', $controller->modelClass);
<del> $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
<del> unset($request->params['controller']);
<del>
<ide> $controller = new \TestApp\Controller\Admin\PostsController($request, $response);
<ide> $this->assertEquals('Posts', $controller->modelClass);
<ide> $this->assertInstanceOf('Cake\ORM\Table', $controller->Posts);
<ide><path>tests/TestCase/Routing/DispatcherTest.php
<ide> public function testMissingControllerAbstract()
<ide> $this->dispatcher->dispatch($request, $response, ['return' => 1]);
<ide> }
<ide>
<add> /**
<add> * Test that lowercase controller names result in missing controller errors.
<add> *
<add> * In case-insensitive file systems, lowercase controller names will kind of work.
<add> * This causes annoying deployment issues for lots of folks.
<add> *
<add> * @expectedException \Cake\Routing\Exception\MissingControllerException
<add> * @expectedExceptionMessage Controller class somepages could not be found.
<add> * @return void
<add> */
<add> public function testMissingControllerLowercase()
<add> {
<add> $request = new Request([
<add> 'url' => 'pages/home',
<add> 'params' => [
<add> 'controller' => 'somepages',
<add> 'action' => 'display',
<add> 'pass' => ['home'],
<add> ]
<add> ]);
<add> $response = $this->getMock('Cake\Network\Response');
<add> $this->dispatcher->dispatch($request, $response, ['return' => 1]);
<add> }
<add>
<ide> /**
<ide> * testDispatch method
<ide> *
<ide> public function testDispatcherFilter()
<ide> $request = new Request([
<ide> 'url' => '/',
<ide> 'params' => [
<del> 'controller' => 'pages',
<add> 'controller' => 'Pages',
<ide> 'action' => 'display',
<ide> 'home',
<ide> 'pass' => [] | 4 |
Javascript | Javascript | use regular expression literals | 6bcf65d4a788a73b3c3f27d75796609f948f7885 | <ide><path>lib/_http_outgoing.js
<ide> const outHeadersKey = require('internal/http').outHeadersKey;
<ide> const CRLF = common.CRLF;
<ide> const debug = common.debug;
<ide>
<del>var RE_FIELDS = new RegExp('^(?:Connection|Transfer-Encoding|Content-Length|' +
<del> 'Date|Expect|Trailer|Upgrade)$', 'i');
<add>var RE_FIELDS =
<add> /^(?:Connection|Transfer-Encoding|Content-Length|Date|Expect|Trailer|Upgrade)$/i;
<ide> var RE_CONN_VALUES = /(?:^|\W)close|upgrade(?:$|\W)/ig;
<ide> var RE_TE_CHUNKED = common.chunkExpression;
<ide>
<ide><path>test/parallel/test-buffer-alloc.js
<ide> Buffer.poolSize = ps;
<ide> assert.throws(() => Buffer.allocUnsafe(10).copy(),
<ide> /TypeError: argument should be a Buffer/);
<ide>
<del>const regErrorMsg = new RegExp('First argument must be a string, Buffer, ' +
<del> 'ArrayBuffer, Array, or array-like object\\.');
<add>const regErrorMsg =
<add> /First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object\./;
<ide>
<ide> assert.throws(() => Buffer.from(), regErrorMsg);
<ide> assert.throws(() => Buffer.from(null), regErrorMsg);
<ide><path>test/parallel/test-crypto-dh.js
<ide> assert.strictEqual(secret2.toString('base64'), secret1);
<ide> assert.strictEqual(dh1.verifyError, 0);
<ide> assert.strictEqual(dh2.verifyError, 0);
<ide>
<del>const argumentsError = new RegExp('^TypeError: First argument should be ' +
<del> 'number, string, Buffer, TypedArray, or ' +
<del> 'DataView$');
<add>const argumentsError =
<add> /^TypeError: First argument should be number, string, Buffer, TypedArray, or DataView$/;
<ide>
<ide> assert.throws(() => {
<ide> crypto.createDiffieHellman([0x1, 0x2]);
<ide> const secret3 = dh3.computeSecret(key2, 'hex', 'base64');
<ide> assert.strictEqual(secret1, secret3);
<ide>
<ide> const wrongBlockLength =
<del> new RegExp('^Error: error:0606506D:digital envelope' +
<del> ' routines:EVP_DecryptFinal_ex:wrong final block length$');
<add> /^Error: error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length$/;
<ide>
<ide> // Run this one twice to make sure that the dh3 clears its error properly
<ide> {
<ide><path>test/parallel/test-crypto-rsa-dsa.js
<ide> const dsaKeyPem = fs.readFileSync(common.fixturesDir + '/test_dsa_privkey.pem',
<ide> const dsaKeyPemEncrypted = fs.readFileSync(
<ide> common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii');
<ide>
<del>const decryptError = new RegExp('^Error: error:06065064:digital envelope ' +
<del> 'routines:EVP_DecryptFinal_ex:bad decrypt$');
<add>const decryptError =
<add> /^Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt$/;
<ide>
<ide> // Test RSA encryption/decryption
<ide> {
<ide><path>test/parallel/test-dgram-send-address-types.js
<ide> client.send(buf, port, undefined, onMessage);
<ide> // valid address: not provided
<ide> client.send(buf, port, onMessage);
<ide>
<del>const expectedError = new RegExp('^TypeError: Invalid arguments: address ' +
<del> 'must be a nonempty string or falsy$');
<add>const expectedError =
<add> /^TypeError: Invalid arguments: address must be a nonempty string or falsy$/;
<ide>
<ide> // invalid address: object
<ide> assert.throws(() => {
<ide><path>test/parallel/test-fs-write-stream-throw-type-error.js
<ide> const assert = require('assert');
<ide> const fs = require('fs');
<ide> const path = require('path');
<ide>
<del>const numberError = new RegExp('^TypeError: "options" must be a string ' +
<del> 'or an object, got number instead\\.$');
<add>const numberError =
<add> /^TypeError: "options" must be a string or an object, got number instead\.$/;
<ide>
<del>const booleanError = new RegExp('^TypeError: "options" must be a string ' +
<del> 'or an object, got boolean instead\\.$');
<add>const booleanError =
<add> /^TypeError: "options" must be a string or an object, got boolean instead\.$/;
<ide>
<ide> const example = path.join(common.tmpDir, 'dummy');
<ide>
<ide><path>test/parallel/test-tls-env-bad-extra-ca.js
<ide> fork(__filename, opts)
<ide> assert.strictEqual(status, 0, 'client did not succeed in connecting');
<ide> }))
<ide> .on('close', common.mustCall(function() {
<del> assert(stderr.match(new RegExp(
<del> 'Warning: Ignoring extra certs from.*no-such-file-exists' +
<del> '.* load failed:.*No such file or directory'
<del> )), stderr);
<add> assert(stderr.match(
<add> /Warning: Ignoring extra certs from.*no-such-file-exists.* load failed:.*No such file or directory/
<add> ), stderr);
<ide> }))
<ide> .stderr.setEncoding('utf8').on('data', function(str) {
<ide> stderr += str;
<ide><path>test/parallel/test-tls-key-mismatch.js
<ide> if (!common.hasCrypto) {
<ide> const assert = require('assert');
<ide> const tls = require('tls');
<ide> const fs = require('fs');
<del>const errorMessageRegex = new RegExp('^Error: error:0B080074:x509 ' +
<del> 'certificate routines:X509_check_private_key:key values mismatch$');
<add>const errorMessageRegex =
<add> /^Error: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch$/;
<ide>
<ide> const options = {
<ide> key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'),
<ide><path>test/parallel/test-util-inherits.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const inherits = require('util').inherits;
<ide> const errCheck =
<del> new RegExp('^TypeError: The super constructor to "inherits" must not be ' +
<del> 'null or undefined$');
<add> /^TypeError: The super constructor to "inherits" must not be null or undefined$/;
<ide>
<ide>
<ide> // super constructor
<ide><path>test/parallel/test-whatwg-url-properties.js
<ide> assert.strictEqual(url.searchParams, oldParams); // [SameObject]
<ide> // non-writable property should throw.
<ide> // Note: this error message is subject to change in V8 updates
<ide> assert.throws(() => url.origin = 'http://foo.bar.com:22',
<del> new RegExp('TypeError: Cannot set property origin of' +
<del> ' \\[object URL\\] which has only a getter'));
<add> /TypeError: Cannot set property origin of \[object URL\] which has only a getter$/);
<ide> assert.strictEqual(url.origin, 'http://foo.bar.com:21');
<ide> assert.strictEqual(url.toString(),
<ide> 'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
<ide> assert.strictEqual(url.hash, '#abcd');
<ide> // non-writable property should throw.
<ide> // Note: this error message is subject to change in V8 updates
<ide> assert.throws(() => url.searchParams = '?k=88',
<del> new RegExp('TypeError: Cannot set property searchParams of' +
<del> ' \\[object URL\\] which has only a getter'));
<add> /^TypeError: Cannot set property searchParams of \[object URL\] which has only a getter$/);
<ide> assert.strictEqual(url.searchParams, oldParams);
<ide> assert.strictEqual(url.toString(),
<ide> 'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#abcd');
<ide><path>test/parallel/test-zlib-deflate-constructors.js
<ide> assert.throws(
<ide> // Throws if opts.dictionary is not a Buffer
<ide> assert.throws(
<ide> () => { new zlib.Deflate({dictionary: 'not a buffer'}); },
<del> new RegExp('^TypeError: Invalid dictionary: it should be a Buffer, ' +
<del> 'TypedArray, or DataView$')
<add> /^TypeError: Invalid dictionary: it should be a Buffer, TypedArray, or DataView$/
<ide> );
<ide><path>test/parallel/test-zlib-not-string-or-buffer.js
<ide> require('../common');
<ide> const assert = require('assert');
<ide> const zlib = require('zlib');
<ide>
<del>const expected = new RegExp('^TypeError: "buffer" argument must be a string, ' +
<del> 'Buffer, TypedArray, or DataView$');
<add>const expected = /^TypeError: "buffer" argument must be a string, Buffer, TypedArray, or DataView$/;
<ide>
<ide> assert.throws(() => { zlib.deflateSync(undefined); }, expected);
<ide> assert.throws(() => { zlib.deflateSync(null); }, expected); | 12 |
Javascript | Javascript | revert recent flow changes | fe7890d569c5aa94c371bdb27c5db7bde4ec385a | <ide><path>packages/events/PluginModuleType.js
<ide> import type {
<ide> DispatchConfig,
<ide> ReactSyntheticEvent,
<ide> } from './ReactSyntheticEventType';
<del>import type {TopLevelType} from 'events/TopLevelEventTypes';
<add>import type {TopLevelType} from './TopLevelEventTypes';
<ide>
<ide> export type EventTypes = {[key: string]: DispatchConfig};
<ide>
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide>
<ide> import type {AnyNativeEvent} from 'events/PluginModuleType';
<ide> import type {Fiber} from 'react-reconciler/src/ReactFiber';
<del>import type {DOMTopLevelEventType} from 'react-dom/src/events/DOMTopLevelEventTypes';
<add>import type {DOMTopLevelEventType} from './DOMTopLevelEventTypes';
<ide>
<ide> import {batchedUpdates, interactiveUpdates} from 'events/ReactGenericBatching';
<ide> import {runExtractedEventsInBatch} from 'events/EventPluginHub';
<ide> import {addEventBubbleListener, addEventCaptureListener} from './EventListener';
<ide> import getEventTarget from './getEventTarget';
<ide> import {getClosestInstanceFromNode} from '../client/ReactDOMComponentTree';
<ide> import SimpleEventPlugin from './SimpleEventPlugin';
<del>import {getRawEventName} from 'react-dom/src/events/DOMTopLevelEventTypes';
<add>import {getRawEventName} from './DOMTopLevelEventTypes';
<ide>
<ide> const {isInteractiveTopLevelEventType} = SimpleEventPlugin;
<ide>
<ide><path>packages/react-dom/src/events/SimpleEventPlugin.js
<ide> */
<ide>
<ide> import type {TopLevelType} from 'events/TopLevelEventTypes';
<add>import type {DOMTopLevelEventType} from './DOMTopLevelEventTypes';
<ide> import type {
<ide> DispatchConfig,
<ide> ReactSyntheticEvent,
<ide> import type {EventTypes, PluginModule} from 'events/PluginModuleType';
<ide> import {accumulateTwoPhaseDispatches} from 'events/EventPropagators';
<ide> import SyntheticEvent from 'events/SyntheticEvent';
<ide>
<del>import * as DOMTopLevelEventTypes from 'react-dom/src/events/DOMTopLevelEventTypes';
<add>import * as DOMTopLevelEventTypes from './DOMTopLevelEventTypes';
<ide> import warning from 'fbjs/lib/warning';
<ide>
<ide> import SyntheticAnimationEvent from './SyntheticAnimationEvent';
<ide> import getEventCharCode from './getEventCharCode';
<ide> * [TOP_ABORT, { sameConfig }],
<ide> * ]);
<ide> */
<del>type EventTuple = [TopLevelType, string];
<add>type EventTuple = [DOMTopLevelEventType, string];
<ide> const interactiveEventTypeNames: Array<EventTuple> = [
<ide> [DOMTopLevelEventTypes.TOP_BLUR, 'blur'],
<ide> [DOMTopLevelEventTypes.TOP_CANCEL, 'cancel'],
<ide> nonInteractiveEventTypeNames.forEach(eventTuple => {
<ide> });
<ide>
<ide> // Only used in DEV for exhaustiveness validation.
<del>const knownHTMLTopLevelTypes: Array<TopLevelType> = [
<add>const knownHTMLTopLevelTypes: Array<DOMTopLevelEventType> = [
<ide> DOMTopLevelEventTypes.TOP_ABORT,
<ide> DOMTopLevelEventTypes.TOP_CANCEL,
<ide> DOMTopLevelEventTypes.TOP_CAN_PLAY, | 3 |
Ruby | Ruby | remove onos deprecation comment. | 20f2b14c38dcfb1962d6cb41f4beabd7396e4eea | <ide><path>Library/Homebrew/formula.rb
<ide> class Formula
<ide> include Utils::Shebang
<ide> include Utils::Shell
<ide> include Context
<del> include OnOS # TODO: 3.4.0: odeprecate OnOS usage in instance methods.
<add> include OnOS
<ide> extend Forwardable
<ide> extend Cachable
<ide> extend Predicable | 1 |
Ruby | Ruby | fix failing test due to hard coded year | 543f7892404381f828a9e29d221d0d361cdb5401 | <ide><path>actionpack/test/template/date_helper_test.rb
<ide> def test_date_select_with_zero_value_and_no_start_year
<ide>
<ide> def test_date_select_with_zero_value_and_no_end_year
<ide> expected = %(<select name="date[first][year]">\n)
<del> 2003.upto(2010) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
<add> last_year = Time.now.year + 5
<add> 2003.upto(last_year) { |y| expected << %(<option value="#{y}">#{y}</option>\n) }
<ide> expected << "</select>\n"
<ide>
<ide> expected << %(<select name="date[first][month]">\n) | 1 |
Python | Python | update gyp to b3cef02 | 1d65b99d5de3078a450101a9166b4168fbcba6fb | <ide><path>tools/gyp/PRESUBMIT.py
<ide> def CheckChangeOnCommit(input_api, output_api):
<ide>
<ide>
<ide> TRYBOTS = [
<del> 'gyp-win32',
<del> 'gyp-win64',
<del> 'gyp-linux',
<del> 'gyp-mac',
<add> 'linux_try',
<add> 'mac_try',
<add> 'win_try',
<ide> ]
<ide>
<ide>
<ide> def GetPreferredTryMasters(_, change):
<ide> return {
<del> 'tryserver.nacl': { t: set(['defaulttests']) for t in TRYBOTS },
<add> 'client.gyp': { t: set(['defaulttests']) for t in TRYBOTS },
<ide> }
<ide><path>tools/gyp/gyp_main.py
<ide> # Use of this source code is governed by a BSD-style license that can be
<ide> # found in the LICENSE file.
<ide>
<add>import os
<ide> import sys
<ide>
<del># TODO(mark): sys.path manipulation is some temporary testing stuff.
<del>try:
<del> import gyp
<del>except ImportError, e:
<del> import os.path
<del> sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), 'pylib'))
<del> import gyp
<add># Make sure we're using the version of pylib in this repo, not one installed
<add># elsewhere on the system.
<add>sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), 'pylib'))
<add>import gyp
<ide>
<ide> if __name__ == '__main__':
<ide> sys.exit(gyp.script_main())
<ide><path>tools/gyp/pylib/gyp/MSVSSettings.py
<ide> def _ValidateSettings(validators, settings, stderr):
<ide> _MSBuildOnly(_compile, 'BuildingInIDE', _boolean)
<ide> _MSBuildOnly(_compile, 'CompileAsManaged',
<ide> _Enumeration([], new=['false',
<del> 'true', # /clr
<del> 'Pure', # /clr:pure
<del> 'Safe', # /clr:safe
<del> 'OldSyntax'])) # /clr:oldSyntax
<add> 'true'])) # /clr
<ide> _MSBuildOnly(_compile, 'CreateHotpatchableImage', _boolean) # /hotpatch
<ide> _MSBuildOnly(_compile, 'MultiProcessorCompilation', _boolean) # /MP
<ide> _MSBuildOnly(_compile, 'PreprocessOutputPath', _string) # /Fi
<ide><path>tools/gyp/pylib/gyp/MSVSSettings_test.py
<ide> def testValidateMSBuildSettings_settings(self):
<ide> 'BuildingInIDE': 'true',
<ide> 'CallingConvention': 'Cdecl',
<ide> 'CompileAs': 'CompileAsC',
<del> 'CompileAsManaged': 'Pure',
<add> 'CompileAsManaged': 'true',
<ide> 'CreateHotpatchableImage': 'true',
<ide> 'DebugInformationFormat': 'ProgramDatabase',
<ide> 'DisableLanguageExtensions': 'true',
<ide><path>tools/gyp/pylib/gyp/common.py
<ide> def QualifiedTarget(build_file, target, toolset):
<ide>
<ide>
<ide> @memoize
<del>def RelativePath(path, relative_to):
<add>def RelativePath(path, relative_to, follow_path_symlink=True):
<ide> # Assuming both |path| and |relative_to| are relative to the current
<ide> # directory, returns a relative path that identifies path relative to
<ide> # relative_to.
<add> # If |follow_symlink_path| is true (default) and |path| is a symlink, then
<add> # this method returns a path to the real file represented by |path|. If it is
<add> # false, this method returns a path to the symlink. If |path| is not a
<add> # symlink, this option has no effect.
<ide>
<ide> # Convert to normalized (and therefore absolute paths).
<del> path = os.path.realpath(path)
<add> if follow_path_symlink:
<add> path = os.path.realpath(path)
<add> else:
<add> path = os.path.abspath(path)
<ide> relative_to = os.path.realpath(relative_to)
<ide>
<ide> # On Windows, we can't create a relative path to a different drive, so just
<ide><path>tools/gyp/pylib/gyp/generator/analyzer.py
<ide> def _GenerateTargets(data, target_list, target_dicts, toplevel_dir, files,
<ide> sources = _ExtractSources(target_name, target_dicts[target_name],
<ide> toplevel_dir)
<ide> for source in sources:
<del> if source in files:
<add> if _ToGypPath(os.path.normpath(source)) in files:
<ide> print 'target', target_name, 'matches', source
<ide> target.match_status = MATCH_STATUS_MATCHES
<ide> matching_targets.append(target)
<ide> def _WasGypIncludeFileModified(params, files):
<ide> files."""
<ide> if params['options'].includes:
<ide> for include in params['options'].includes:
<del> if _ToGypPath(include) in files:
<add> if _ToGypPath(os.path.normpath(include)) in files:
<ide> print 'Include file modified, assuming all changed', include
<ide> return True
<ide> return False
<ide><path>tools/gyp/pylib/gyp/generator/make.py
<ide> def CalculateGeneratorInputInfo(params):
<ide>
<ide> LINK_COMMANDS_AIX = """\
<ide> quiet_cmd_alink = AR($(TOOLSET)) $@
<del>cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
<add>cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^)
<ide>
<ide> quiet_cmd_alink_thin = AR($(TOOLSET)) $@
<del>cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
<add>cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) -X32_64 crs $@ $(filter %.o,$^)
<ide>
<ide> quiet_cmd_link = LINK($(TOOLSET)) $@
<ide> cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(LD_INPUTS) $(LIBS)
<ide> def CalculateGeneratorInputInfo(params):
<ide> %(make_global_settings)s
<ide>
<ide> CC.target ?= %(CC.target)s
<del>CFLAGS.target ?= $(CFLAGS)
<add>CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS)
<ide> CXX.target ?= %(CXX.target)s
<del>CXXFLAGS.target ?= $(CXXFLAGS)
<add>CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS)
<ide> LINK.target ?= %(LINK.target)s
<ide> LDFLAGS.target ?= $(LDFLAGS)
<ide> AR.target ?= $(AR)
<ide> def CalculateGeneratorInputInfo(params):
<ide> # TODO(evan): move all cross-compilation logic to gyp-time so we don't need
<ide> # to replicate this environment fallback in make as well.
<ide> CC.host ?= %(CC.host)s
<del>CFLAGS.host ?=
<add>CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host)
<ide> CXX.host ?= %(CXX.host)s
<del>CXXFLAGS.host ?=
<add>CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host)
<ide> LINK.host ?= %(LINK.host)s
<ide> LDFLAGS.host ?=
<ide> AR.host ?= %(AR.host)s
<ide> def CalculateGeneratorInputInfo(params):
<ide>
<ide> quiet_cmd_copy = COPY $@
<ide> # send stderr to /dev/null to ignore messages when linking directories.
<del>cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp -af "$<" "$@")
<add>cmd_copy = ln -f "$<" "$@" 2>/dev/null || (rm -rf "$@" && cp %(copy_archive_args)s "$<" "$@")
<ide>
<ide> %(link_commands)s
<ide> """
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> srcdir_prefix = '$(srcdir)/'
<ide>
<ide> flock_command= 'flock'
<add> copy_archive_arguments = '-af'
<ide> header_params = {
<ide> 'default_target': default_target,
<ide> 'builddir': builddir_name,
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> 'link_commands': LINK_COMMANDS_LINUX,
<ide> 'extra_commands': '',
<ide> 'srcdir': srcdir,
<add> 'copy_archive_args': copy_archive_arguments,
<ide> }
<ide> if flavor == 'mac':
<ide> flock_command = './gyp-mac-tool flock'
<ide> def CalculateMakefilePath(build_file, base_name):
<ide> 'flock': 'lockf',
<ide> })
<ide> elif flavor == 'aix':
<add> copy_archive_arguments = '-pPRf'
<ide> header_params.update({
<add> 'copy_archive_args': copy_archive_arguments,
<ide> 'link_commands': LINK_COMMANDS_AIX,
<ide> 'flock': './gyp-flock-tool flock',
<ide> 'flock_index': 2,
<ide><path>tools/gyp/pylib/gyp/generator/msvs.py
<ide> def _import_OrderedDict():
<ide> 'msvs_requires_importlibrary',
<ide> 'msvs_enable_winphone',
<ide> 'msvs_application_type_revision',
<add> 'msvs_target_platform_version',
<add> 'msvs_target_platform_minversion',
<ide> ]
<ide>
<ide>
<ide> def _GetMSBuildGlobalProperties(spec, guid, gyp_file_name):
<ide> else:
<ide> properties[0].append(['ApplicationTypeRevision', '8.1'])
<ide>
<add> if spec.get('msvs_target_platform_version'):
<add> target_platform_version = spec.get('msvs_target_platform_version')
<add> properties[0].append(['WindowsTargetPlatformVersion',
<add> target_platform_version])
<add> if spec.get('msvs_target_platform_minversion'):
<add> target_platform_minversion = spec.get('msvs_target_platform_minversion')
<add> properties[0].append(['WindowsTargetPlatformMinVersion',
<add> target_platform_minversion])
<add> else:
<add> properties[0].append(['WindowsTargetPlatformMinVersion',
<add> target_platform_version])
<ide> if spec.get('msvs_enable_winphone'):
<ide> properties[0].append(['ApplicationType', 'Windows Phone'])
<ide> else:
<ide><path>tools/gyp/pylib/gyp/generator/ninja.py
<ide> def WriteSourcesForArch(self, ninja_file, config_name, config, sources,
<ide> os.environ.get('CFLAGS', '').split() + cflags_c)
<ide> cflags_cc = (os.environ.get('CPPFLAGS', '').split() +
<ide> os.environ.get('CXXFLAGS', '').split() + cflags_cc)
<add> elif self.toolset == 'host':
<add> cflags_c = (os.environ.get('CPPFLAGS_host', '').split() +
<add> os.environ.get('CFLAGS_host', '').split() + cflags_c)
<add> cflags_cc = (os.environ.get('CPPFLAGS_host', '').split() +
<add> os.environ.get('CXXFLAGS_host', '').split() + cflags_cc)
<ide>
<ide> defines = config.get('defines', []) + extra_defines
<ide> self.WriteVariableList(ninja_file, 'defines',
<ide> def CommandWithWrapper(cmd, wrappers, prog):
<ide>
<ide> def GetDefaultConcurrentLinks():
<ide> """Returns a best-guess for a number of concurrent links."""
<del> pool_size = int(os.getenv('GYP_LINK_CONCURRENCY', 0))
<add> pool_size = int(os.environ.get('GYP_LINK_CONCURRENCY', 0))
<ide> if pool_size:
<ide> return pool_size
<ide>
<ide> class MEMORYSTATUSEX(ctypes.Structure):
<ide> stat.dwLength = ctypes.sizeof(stat)
<ide> ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(stat))
<ide>
<del> mem_limit = max(1, stat.ullTotalPhys / (4 * (2 ** 30))) # total / 4GB
<del> hard_cap = max(1, int(os.getenv('GYP_LINK_CONCURRENCY_MAX', 2**32)))
<add> # VS 2015 uses 20% more working set than VS 2013 and can consume all RAM
<add> # on a 64 GB machine.
<add> mem_limit = max(1, stat.ullTotalPhys / (5 * (2 ** 30))) # total / 5GB
<add> hard_cap = max(1, int(os.environ.get('GYP_LINK_CONCURRENCY_MAX', 2**32)))
<ide> return min(mem_limit, hard_cap)
<ide> elif sys.platform.startswith('linux'):
<ide> if os.path.exists("/proc/meminfo"):
<ide> def GenerateOutputForConfig(target_list, target_dicts, data, params,
<ide> if flavor == 'mac':
<ide> gyp.xcode_emulation.MergeGlobalXcodeSettingsToSpec(data[build_file], spec)
<ide>
<del> build_file = gyp.common.RelativePath(build_file, options.toplevel_dir)
<add> # If build_file is a symlink, we must not follow it because there's a chance
<add> # it could point to a path above toplevel_dir, and we cannot correctly deal
<add> # with that case at the moment.
<add> build_file = gyp.common.RelativePath(build_file, options.toplevel_dir,
<add> False)
<ide>
<ide> qualified_target_for_hash = gyp.common.QualifiedTarget(build_file, name,
<ide> toolset)
<ide><path>tools/gyp/pylib/gyp/input.py
<ide> def IsPathSection(section):
<ide> # If section ends in one of the '=+?!' characters, it's applied to a section
<ide> # without the trailing characters. '/' is notably absent from this list,
<ide> # because there's no way for a regular expression to be treated as a path.
<del> while section[-1:] in '=+?!':
<add> while section and section[-1:] in '=+?!':
<ide> section = section[:-1]
<ide>
<ide> if section in path_sections:
<ide> def ExpandVariables(input, phase, variables, build_file):
<ide> else:
<ide> # Fix up command with platform specific workarounds.
<ide> contents = FixupPlatformCommand(contents)
<del> p = subprocess.Popen(contents, shell=use_shell,
<del> stdout=subprocess.PIPE,
<del> stderr=subprocess.PIPE,
<del> stdin=subprocess.PIPE,
<del> cwd=build_file_dir)
<add> try:
<add> p = subprocess.Popen(contents, shell=use_shell,
<add> stdout=subprocess.PIPE,
<add> stderr=subprocess.PIPE,
<add> stdin=subprocess.PIPE,
<add> cwd=build_file_dir)
<add> except Exception, e:
<add> raise GypError("%s while executing command '%s' in %s" %
<add> (e, contents, build_file))
<ide>
<ide> p_stdout, p_stderr = p.communicate('')
<ide>
<ide> if p.wait() != 0 or p_stderr:
<ide> sys.stderr.write(p_stderr)
<ide> # Simulate check_call behavior, since check_call only exists
<ide> # in python 2.5 and later.
<del> raise GypError("Call to '%s' returned exit status %d." %
<del> (contents, p.returncode))
<add> raise GypError("Call to '%s' returned exit status %d while in %s." %
<add> (contents, p.returncode, build_file))
<ide> replacement = p_stdout.rstrip()
<ide>
<ide> cached_command_results[cache_key] = replacement
<ide><path>tools/gyp/pylib/gyp/msvs_emulation.py
<ide> def GetCflags(self, config):
<ide> cl('FloatingPointModel',
<ide> map={'0': 'precise', '1': 'strict', '2': 'fast'}, prefix='/fp:',
<ide> default='0')
<add> cl('CompileAsManaged', map={'false': '', 'true': '/clr'})
<ide> cl('WholeProgramOptimization', map={'true': '/GL'})
<ide> cl('WarningLevel', prefix='/W')
<ide> cl('WarnAsError', map={'true': '/WX'})
<ide> def GetLdflags(self, config, gyp_to_build_path, expand_special,
<ide> '2': 'WINDOWS%s' % minimum_required_version},
<ide> prefix='/SUBSYSTEM:')
<ide>
<add> stack_reserve_size = self._Setting(
<add> ('VCLinkerTool', 'StackReserveSize'), config, default='')
<add> if stack_reserve_size:
<add> stack_commit_size = self._Setting(
<add> ('VCLinkerTool', 'StackCommitSize'), config, default='')
<add> if stack_commit_size:
<add> stack_commit_size = ',' + stack_commit_size
<add> ldflags.append('/STACK:%s%s' % (stack_reserve_size, stack_commit_size))
<add>
<ide> ld('TerminalServerAware', map={'1': ':NO', '2': ''}, prefix='/TSAWARE')
<ide> ld('LinkIncremental', map={'1': ':NO', '2': ''}, prefix='/INCREMENTAL')
<ide> ld('BaseAddress', prefix='/BASE:')
<ide><path>tools/gyp/pylib/gyp/win_tool.py
<ide> def ExecLinkWrapper(self, arch, use_separate_mspdbsrv, *args):
<ide> stderr=subprocess.STDOUT)
<ide> out, _ = link.communicate()
<ide> for line in out.splitlines():
<del> if not line.startswith(' Creating library '):
<add> if (not line.startswith(' Creating library ') and
<add> not line.startswith('Generating code') and
<add> not line.startswith('Finished generating code')):
<ide> print line
<ide> return link.returncode
<ide>
<ide><path>tools/gyp/pylib/gyp/xcode_emulation.py
<ide> def _AdjustLibrary(self, library, config_name=None):
<ide> sdk_root = self._SdkPath(config_name)
<ide> if not sdk_root:
<ide> sdk_root = ''
<del> return l.replace('$(SDKROOT)', sdk_root)
<add> # Xcode 7 started shipping with ".tbd" (text based stubs) files instead of
<add> # ".dylib" without providing a real support for them. What it does, for
<add> # "/usr/lib" libraries, is do "-L/usr/lib -lname" which is dependent on the
<add> # library order and cause collision when building Chrome.
<add> #
<add> # Instead substitude ".tbd" to ".dylib" in the generated project when the
<add> # following conditions are both true:
<add> # - library is referenced in the gyp file as "$(SDKROOT)/**/*.dylib",
<add> # - the ".dylib" file does not exists but a ".tbd" file do.
<add> library = l.replace('$(SDKROOT)', sdk_root)
<add> if l.startswith('$(SDKROOT)'):
<add> basename, ext = os.path.splitext(library)
<add> if ext == '.dylib' and not os.path.exists(library):
<add> tbd_library = basename + '.tbd'
<add> if os.path.exists(tbd_library):
<add> library = tbd_library
<add> return library
<ide>
<ide> def AdjustLibraries(self, libraries, config_name=None):
<ide> """Transforms entries like 'Cocoa.framework' in libraries into entries like
<ide> def _GetXcodeEnv(xcode_settings, built_products_dir, srcroot, configuration,
<ide> sdk_root = xcode_settings._SdkRoot(configuration)
<ide> if not sdk_root:
<ide> sdk_root = xcode_settings._XcodeSdkPath('')
<del> if sdk_root is None:
<del> sdk_root = ''
<ide> env['SDKROOT'] = sdk_root
<ide>
<ide> if not additional_settings: | 13 |
Ruby | Ruby | modify comments and other text | 40b0070bebf6ef34435ebd521c14c5a3770fca34 | <ide><path>Library/Homebrew/livecheck/livecheck.rb
<ide> def run_checks(
<ide> version_info[:latest] if version_info.present?
<ide> end
<ide>
<del> # Check current and latest resources (if "--resources" flag is given)
<del> # Only check current and latest versions if we have resources to check against
<ide> check_for_resources = check_resources && formula_or_cask.is_a?(Formula) && formula_or_cask.resources.present?
<ide> if check_for_resources
<ide> resource_version_info = formula_or_cask.resources.map do |resource|
<ide> def livecheck_url_to_string(livecheck_url, package_or_resource)
<ide> end
<ide> end
<ide>
<del> # Returns an Array containing the formula/resource/cask URLs that can be used by livecheck.
<add> # Returns an Array containing the formula/cask/resource URLs that can be used by livecheck.
<ide> sig { params(package_or_resource: T.any(Formula, Cask::Cask, Resource)).returns(T::Array[String]) }
<ide> def checkable_urls(package_or_resource)
<ide> urls = []
<ide><path>Library/Homebrew/livecheck/skip_conditions.rb
<ide> def cask_url_unversioned(cask, livecheckable, full_name: false, verbose: false)
<ide> :cask_url_unversioned,
<ide> ].freeze
<ide>
<del> # Skip conditions for resource.
<add> # Skip conditions for resources.
<ide> RESOURCE_CHECKS = [
<ide> :package_or_resource_skip,
<ide> ].freeze
<ide><path>Library/Homebrew/test/livecheck/livecheck_spec.rb
<ide> RUBY
<ide> end
<ide>
<del> it "returns a URL string when given a livecheck_url string for formula" do
<add> it "returns a URL string when given a livecheck_url string for a formula" do
<ide> expect(livecheck.livecheck_url_to_string(livecheck_url, f_livecheck_url)).to eq(livecheck_url)
<ide> end
<ide>
<del> it "returns a URL string when given a livecheck_url string for resource" do
<add> it "returns a URL string when given a livecheck_url string for a resource" do
<ide> expect(livecheck.livecheck_url_to_string(livecheck_url, r_livecheck_url)).to eq(livecheck_url)
<ide> end
<ide> | 3 |
Javascript | Javascript | improve markdown link checker | 77f9e0c814e1fafef2e84eabd24c135748217b26 | <ide><path>tools/doc/checkLinks.js
<ide> 'use strict';
<ide>
<ide> const fs = require('fs');
<del>const { Worker, isMainThread, workerData: path } = require('worker_threads');
<add>const { extname, join, resolve } = require('path');
<add>const unified = require('unified');
<add>const { pathToFileURL } = require('url');
<add>const DIR = resolve(process.argv[2]);
<add>
<add>console.log('Running Markdown link checker...');
<add>findMarkdownFilesRecursively(DIR);
<ide>
<ide> function* getLinksRecursively(node) {
<del> if (
<del> (node.type === 'link' && !node.url.startsWith('#')) ||
<del> node.type === 'image'
<del> ) {
<add> if (node.url && !node.url.startsWith('#')) {
<ide> yield node;
<ide> }
<ide> for (const child of node.children || []) {
<ide> yield* getLinksRecursively(child);
<ide> }
<ide> }
<ide>
<del>if (isMainThread) {
<del> const { extname, join, resolve } = require('path');
<del> const DIR = resolve(process.argv[2]);
<del>
<del> console.log('Running Markdown link checker...');
<del>
<del> async function* findMarkdownFilesRecursively(dirPath) {
<del> const fileNames = await fs.promises.readdir(dirPath);
<del>
<del> for (const fileName of fileNames) {
<del> const path = join(dirPath, fileName);
<del>
<del> const stats = await fs.promises.stat(path);
<del> if (
<del> stats.isDirectory() &&
<del> fileName !== 'api' &&
<del> fileName !== 'deps' &&
<del> fileName !== 'node_modules'
<del> ) {
<del> yield* findMarkdownFilesRecursively(path);
<del> } else if (extname(fileName) === '.md') {
<del> yield path;
<del> }
<add>function findMarkdownFilesRecursively(dirPath) {
<add> const entries = fs.readdirSync(dirPath, { withFileTypes: true });
<add>
<add> for (const entry of entries) {
<add> const path = join(dirPath, entry.name);
<add>
<add> if (
<add> entry.isDirectory() &&
<add> entry.name !== 'api' &&
<add> entry.name !== 'deps' &&
<add> entry.name !== 'node_modules'
<add> ) {
<add> findMarkdownFilesRecursively(path);
<add> } else if (entry.isFile() && extname(entry.name) === '.md') {
<add> checkFile(path);
<ide> }
<ide> }
<add>}
<ide>
<del> function errorHandler(error) {
<del> console.error(error);
<del> process.exitCode = 1;
<del> }
<del>
<del> setImmediate(async () => {
<del> for await (const path of findMarkdownFilesRecursively(DIR)) {
<del> new Worker(__filename, { workerData: path }).on('error', errorHandler);
<del> }
<del> });
<del>} else {
<del> const unified = require('unified');
<del> const { pathToFileURL } = require('url');
<del>
<add>function checkFile(path) {
<ide> const tree = unified()
<ide> .use(require('remark-parse'))
<ide> .parse(fs.readFileSync(path));
<ide> if (isMainThread) {
<ide> for (const node of getLinksRecursively(tree)) {
<ide> const targetURL = new URL(node.url, base);
<ide> if (targetURL.protocol === 'file:' && !fs.existsSync(targetURL)) {
<del> const error = new Error('Broken link in a Markdown document.');
<del> const { start } = node.position;
<del> error.stack =
<del> error.stack.substring(0, error.stack.indexOf('\n') + 5) +
<del> `at ${node.type} (${path}:${start.line}:${start.column})`;
<del> throw error;
<add> const { line, column } = node.position.start;
<add> console.error(`Broken link at ${path}:${line}:${column} (${node.url})`);
<add> process.exitCode = 1;
<ide> }
<ide> }
<ide> } | 1 |
Go | Go | fix error on successful login | 35703d4f0c79e936bbff1804167ae9e8dde9b76c | <ide><path>registry/auth.go
<ide> func Login(authConfig *AuthConfig, factory *utils.HTTPRequestFactory) (string, e
<ide> return "", err
<ide> }
<ide> if resp.StatusCode == 200 {
<del> status = "Login Succeeded"
<add> return "Login Succeeded", nil
<ide> } else if resp.StatusCode == 401 {
<ide> return "", fmt.Errorf("Wrong login/password, please try again")
<ide> } else if resp.StatusCode == 403 {
<ide> func Login(authConfig *AuthConfig, factory *utils.HTTPRequestFactory) (string, e
<ide> return "", err
<ide> }
<ide> if resp.StatusCode == 200 {
<del> status = "Login Succeeded"
<add> return "Login Succeeded", nil
<ide> } else if resp.StatusCode == 401 {
<ide> return "", fmt.Errorf("Wrong login/password, please try again")
<ide> } else { | 1 |
Python | Python | replace _linear_ramp with linspace | 5c55d2b3d2946c1d581dcea252d6cea0e1602217 | <ide><path>numpy/lib/arraypad.py
<ide> # Private utility functions.
<ide>
<ide>
<del>def _linear_ramp(ndim, axis, start, stop, size, reverse=False):
<del> """
<del> Create a linear ramp of `size` in `axis` with `ndim`.
<del>
<del> This algorithm behaves like a vectorized version of `numpy.linspace`.
<del> The resulting linear ramp is broadcastable to any array that matches the
<del> ramp in `shape[axis]` and `ndim`.
<del>
<del> Parameters
<del> ----------
<del> ndim : int
<del> Number of dimensions of the resulting array. All dimensions except
<del> the one specified by `axis` will have the size 1.
<del> axis : int
<del> The dimension that contains the linear ramp of `size`.
<del> start : int or ndarray
<del> The starting value(s) of the linear ramp. If given as an array, its
<del> size must match `size`.
<del> stop : int or ndarray
<del> The stop value(s) (not included!) of the linear ramp. If given as an
<del> array, its size must match `size`.
<del> size : int
<del> The number of elements in the linear ramp. If this argument is 0 the
<del> dimensions of `ramp` will all be of length 1 except for the one given
<del> by `axis` which will be 0.
<del> reverse : bool
<del> If False, increment in a positive fashion, otherwise decrement.
<del>
<del> Returns
<del> -------
<del> ramp : ndarray
<del> Output array of dtype np.float64 that in- or decrements along the given
<del> `axis`.
<del>
<del> Examples
<del> --------
<del> >>> _linear_ramp(ndim=2, axis=0, start=np.arange(3), stop=10, size=2)
<del> array([[0. , 1. , 2. ],
<del> [5. , 5.5, 6. ]])
<del> >>> _linear_ramp(ndim=3, axis=0, start=2, stop=0, size=0)
<del> array([], shape=(0, 1, 1), dtype=float64)
<del> """
<del> # Create initial ramp
<del> ramp = np.arange(size, dtype=np.float64)
<del> if reverse:
<del> ramp = ramp[::-1]
<del>
<del> # Make sure, that ramp is broadcastable
<del> init_shape = (1,) * axis + (size,) + (1,) * (ndim - axis - 1)
<del> ramp = ramp.reshape(init_shape)
<del>
<del> if size != 0:
<del> # And scale to given start and stop values
<del> gain = (stop - start) / float(size)
<del> ramp = ramp * gain
<del> ramp += start
<del>
<del> return ramp
<del>
<del>
<ide> def _round_if_needed(arr, dtype):
<ide> """
<ide> Rounds arr inplace if destination dtype is integer.
<ide> def _get_linear_ramps(padded, axis, width_pair, end_value_pair):
<ide> """
<ide> edge_pair = _get_edges(padded, axis, width_pair)
<ide>
<del> left_ramp = _linear_ramp(
<del> padded.ndim, axis, start=end_value_pair[0], stop=edge_pair[0],
<del> size=width_pair[0], reverse=False
<add> left_ramp = np.linspace(
<add> start=end_value_pair[0],
<add> stop=edge_pair[0].squeeze(axis), # Dimensions is replaced by linspace
<add> num=width_pair[0],
<add> endpoint=False,
<add> dtype=padded.dtype,
<add> axis=axis,
<ide> )
<del> _round_if_needed(left_ramp, padded.dtype)
<ide>
<del> right_ramp = _linear_ramp(
<del> padded.ndim, axis, start=end_value_pair[1], stop=edge_pair[1],
<del> size=width_pair[1], reverse=True
<add> right_ramp = np.linspace(
<add> start=end_value_pair[1],
<add> stop=edge_pair[1].squeeze(axis), # Dimension is replaced by linspace
<add> num=width_pair[1],
<add> endpoint=False,
<add> dtype=padded.dtype,
<add> axis=axis,
<ide> )
<del> _round_if_needed(right_ramp, padded.dtype)
<add> # Reverse linear space in appropriate dimension
<add> right_ramp = right_ramp[_slice_at_axis(slice(None, None, -1), axis)]
<ide>
<ide> return left_ramp, right_ramp
<ide>
<ide><path>numpy/lib/tests/test_arraypad.py
<ide>
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<del>from itertools import chain
<ide>
<ide> import pytest
<ide>
<ide> from numpy.lib.arraypad import _as_pairs
<ide>
<ide>
<add>_numeric_dtypes = (
<add> np.sctypes["uint"]
<add> + np.sctypes["int"]
<add> + np.sctypes["float"]
<add> + np.sctypes["complex"]
<add>)
<ide> _all_modes = {
<ide> 'constant': {'constant_values': 0},
<ide> 'edge': {},
<ide> def test_end_values(self):
<ide> assert_equal(a[0, :], 0.)
<ide> assert_equal(a[-1, :], 0.)
<ide>
<add> @pytest.mark.parametrize("dtype", _numeric_dtypes)
<add> def test_negative_difference(self, dtype):
<add> """
<add> Check correct behavior of unsigned dtypes if there is a negative
<add> difference between the edge to pad and `end_values`. Check both cases
<add> to be independent of implementation. Test behavior for all other dtypes
<add> in case dtype casting interferes with complex dtypes. See gh-14191.
<add> """
<add> x = np.array([3], dtype=dtype)
<add> result = np.pad(x, 3, mode="linear_ramp", end_values=0)
<add> expected = np.array([0, 1, 2, 3, 2, 1, 0], dtype=dtype)
<add> assert_equal(result, expected)
<add>
<add> x = np.array([0], dtype=dtype)
<add> result = np.pad(x, 3, mode="linear_ramp", end_values=3)
<add> expected = np.array([3, 2, 1, 0, 1, 2, 3], dtype=dtype)
<add> assert_equal(result, expected)
<add>
<ide>
<ide> class TestReflect(object):
<ide> def test_check_simple(self):
<ide> def test_memory_layout_persistence(mode):
<ide> assert np.pad(x, 5, mode).flags["F_CONTIGUOUS"]
<ide>
<ide>
<del>@pytest.mark.parametrize("dtype", chain(
<del> # Skip "other" dtypes as they are not supported by all modes
<del> np.sctypes["int"],
<del> np.sctypes["uint"],
<del> np.sctypes["float"],
<del> np.sctypes["complex"]
<del>))
<add>@pytest.mark.parametrize("dtype", _numeric_dtypes)
<ide> @pytest.mark.parametrize("mode", _all_modes.keys())
<ide> def test_dtype_persistence(dtype, mode):
<ide> arr = np.zeros((3, 2, 1), dtype=dtype) | 2 |
Javascript | Javascript | remove dead code | 45a321d686231c85e8d6ec5b56b888fe6614afff | <ide><path>src/renderers/shared/reconciler/ReactCompositeComponent.js
<ide> var ReactCompositeComponentMixin = {
<ide> if (this._pendingElement != null) {
<ide> ReactReconciler.receiveComponent(
<ide> this,
<del> this._pendingElement || this._currentElement,
<add> this._pendingElement,
<ide> transaction,
<ide> this._context
<ide> ); | 1 |
Python | Python | update affected tests | 65970f33208ffb84a31ebc551e330fd39e6e25c0 | <ide><path>libcloud/test/storage/test_azure_blobs.py
<ide> def _foo_bar_container_foo_bar_object_range(self, method, url, body, headers):
<ide> # test_download_object_range_success
<ide> body = '0123456789123456789'
<ide>
<del> self.assertTrue('Range' in headers)
<del> self.assertEqual(headers['Range'], 'bytes=5-6')
<add> self.assertTrue('x-ms-range' in headers)
<add> self.assertEqual(headers['x-ms-range'], 'bytes=5-6')
<ide>
<del> start_bytes, end_bytes = self._get_start_and_end_bytes_from_range_str(headers['Range'], body)
<add> start_bytes, end_bytes = self._get_start_and_end_bytes_from_range_str(headers['x-ms-range'], body)
<ide>
<ide> return (httplib.PARTIAL_CONTENT,
<ide> body[start_bytes:end_bytes + 1],
<ide> def _foo_bar_container_foo_bar_object_range_stream(self, method, url, body, head
<ide> # test_download_object_range_as_stream_success
<ide> body = '0123456789123456789'
<ide>
<del> self.assertTrue('Range' in headers)
<del> self.assertEqual(headers['Range'], 'bytes=4-5')
<add> self.assertTrue('x-ms-range' in headers)
<add> self.assertEqual(headers['x-ms-range'], 'bytes=4-5')
<ide>
<del> start_bytes, end_bytes = self._get_start_and_end_bytes_from_range_str(headers['Range'], body)
<add> start_bytes, end_bytes = self._get_start_and_end_bytes_from_range_str(headers['x-ms-range'], body)
<ide>
<ide> return (httplib.PARTIAL_CONTENT,
<ide> body[start_bytes:end_bytes + 1], | 1 |
Javascript | Javascript | tweak the bundle validation script | 646781b0b4f95d90cf08b7799bbd196e16136f06 | <ide><path>scripts/rollup/validate/index.js
<ide> function lint({format, filePatterns}) {
<ide>
<ide> function checkFilesExist(bundle) {
<ide> const {format, filePatterns} = bundle;
<del> filePatterns.map(pattern => {
<del> console.log(`Check if files exist in ${pattern}`);
<add> filePatterns.forEach(pattern => {
<add> console.log(`Checking if files exist in ${pattern}...`);
<ide> const files = glob.sync(pattern);
<ide> if (files.length === 0) {
<del> console.error(
<del> chalk.red(
<del> `No files found in glob pattern ${pattern} in ${format} bundle.`
<del> )
<del> );
<del> process.exit();
<add> console.error(chalk.red(`Found no ${format} bundles in ${pattern}`));
<add> process.exit(1);
<ide> } else {
<del> console.log(chalk.green(`${files.length} files found.`));
<add> console.log(chalk.green(`Found ${files.length} bundles.`));
<ide> console.log();
<ide> }
<ide> }); | 1 |
Javascript | Javascript | fix broken freebsd test | a804026c9b5b9f8d6316fd5e9fdb9f96f7e1c6b3 | <ide><path>test/parallel/test-net-server-max-connections-close-makes-more-available.js
<ide> var createConnection = function(index) {
<ide> sent.push(msg);
<ide> });
<ide>
<add> connection.on('error', function(err) {
<add> assert.equal(err.code, 'ECONNRESET');
<add> resolve();
<add> });
<add>
<ide> connection.on('data', function(e) {
<ide> console.error('connection ' + index + ' received response');
<ide> resolve(); | 1 |
Javascript | Javascript | add test with combining data-uri and coffee-loader | f65ab7e21d399176f7342d8ccfd9a99cf54424f1 | <ide><path>test/cases/resolving/data-uri/index.js
<ide> it("should import js module from base64 data-uri", function() {
<ide> expect(mod.number).toBe(42);
<ide> expect(mod.fn()).toBe("Hello world");
<ide> });
<add>
<add>it("should require coffee module from base64 data-uri", function() {
<add> const mod = require('coffee-loader!data:text/javascript;charset=utf-8;base64,bW9kdWxlLmV4cG9ydHMgPQogIG51bWJlcjogNDIKICBmbjogKCkgLT4gIkhlbGxvIHdvcmxkIg==');
<add> expect(mod.number).toBe(42);
<add> expect(mod.fn()).toBe("Hello world");
<add>}); | 1 |
Text | Text | add arguments to test case titles. | 7a51540127b5526135339a60fe51bc8e36b51568 | <ide><path>curriculum/challenges/english/10-coding-interview-prep/rosetta-code/heronian-triangles.english.md
<ide> Implement a function based on Hero's formula that returns the first <code>n<sub>
<ide> tests:
<ide> - text: <code>heronianTriangle</code> should be a function.
<ide> testString: assert(typeof heronianTriangle === 'function');
<del> - text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]</code>
<add> - text: <code>heronianTriangle(10)</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17]]</code>
<ide> testString: assert.deepEqual(heronianTriangle(testCases[0]), res[0]);
<del> - text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],</code>
<add> - text: <code>heronianTriangle(15)</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15]],</code>
<ide> testString: assert.deepEqual(heronianTriangle(testCases[1]), res[1]);
<del> - text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],</code>
<add> - text: <code>heronianTriangle(20)</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53]],</code>
<ide> testString: assert.deepEqual(heronianTriangle(testCases[2]), res[2]);
<del> - text: <code>heronianTriangle()</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]</code>
<add> - text: <code>heronianTriangle(25)</code> should return <code>[[3, 4, 5], [5, 5, 6], [5, 5, 8], [4, 13, 15], [5, 12, 13], [9, 10, 17], [3, 25, 26], [7, 15, 20], [10, 13, 13], [8, 15, 17], [13, 13, 24], [6, 25, 29], [11, 13, 20], [5, 29, 30], [13, 14, 15], [10, 17, 21], [7, 24, 25], [8, 29, 35], [12, 17, 25], [4, 51, 53], [19, 20, 37],[16, 17, 17], [17, 17, 30], [16, 25, 39], [13, 20, 21]]</code>
<ide> testString: assert.deepEqual(heronianTriangle(testCases[3]), res[3]);
<ide>
<ide> ``` | 1 |
Java | Java | introduce importselector interface | 9a271ce6c92695b9421aa603c9aa56e805c7920c | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
<ide> import java.util.Set;
<ide> import java.util.Stack;
<ide>
<add>import org.springframework.beans.BeanUtils;
<ide> import org.springframework.beans.factory.parsing.Location;
<ide> import org.springframework.beans.factory.parsing.Problem;
<ide> import org.springframework.beans.factory.parsing.ProblemReporter;
<ide> import org.springframework.core.type.StandardAnnotationMetadata;
<ide> import org.springframework.core.type.classreading.MetadataReader;
<ide> import org.springframework.core.type.classreading.MetadataReaderFactory;
<add>import org.springframework.core.type.filter.AssignableTypeFilter;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> protected void doProcessConfigurationClass(ConfigurationClass configClass, Annot
<ide> List<Map<String, Object>> allImportAttribs =
<ide> AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
<ide> for (Map<String, Object> importAttribs : allImportAttribs) {
<del> processImport(configClass, (String[]) importAttribs.get("value"));
<add> processImport(configClass, (String[]) importAttribs.get("value"), true);
<ide> }
<ide>
<ide> if (metadata.isAnnotated(ImportResource.class.getName())) {
<ide> protected void doProcessConfigurationClass(ConfigurationClass configClass, Annot
<ide> }
<ide> }
<ide>
<del> private void processImport(ConfigurationClass configClass, String[] classesToImport) throws IOException {
<del> if (this.importStack.contains(configClass)) {
<add> private void processImport(ConfigurationClass configClass, String[] classesToImport, boolean checkForCircularImports) throws IOException {
<add> if (checkForCircularImports && this.importStack.contains(configClass)) {
<ide> this.problemReporter.error(new CircularImportProblem(configClass, this.importStack, configClass.getMetadata()));
<ide> }
<ide> else {
<ide> this.importStack.push(configClass);
<del> for (String classToImport : classesToImport) {
<del> this.importStack.registerImport(configClass.getMetadata().getClassName(), classToImport);
<del> MetadataReader reader = this.metadataReaderFactory.getMetadataReader(classToImport);
<del> processConfigurationClass(new ConfigurationClass(reader, null));
<add> AnnotationMetadata importingClassMetadata = configClass.getMetadata();
<add> for (String candidate : classesToImport) {
<add> MetadataReader reader = this.metadataReaderFactory.getMetadataReader(candidate);
<add> if (new AssignableTypeFilter(ImportSelector.class).match(reader, metadataReaderFactory)) {
<add> // the candidate class is an ImportSelector -> delegate to it to determine imports
<add> try {
<add> ImportSelector selector = BeanUtils.instantiateClass(Class.forName(candidate), ImportSelector.class);
<add> processImport(configClass, selector.selectImports(importingClassMetadata), false);
<add> } catch (ClassNotFoundException ex) {
<add> throw new IllegalStateException(ex);
<add> }
<add> }
<add> else {
<add> // the candidate class not an ImportSelector -> process it as a @Configuration class
<add> this.importStack.registerImport(importingClassMetadata.getClassName(), candidate);
<add> processConfigurationClass(new ConfigurationClass(reader, null));
<add> }
<ide> }
<ide> this.importStack.pop();
<ide> }
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ImportSelector.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation;
<add>
<add>import org.springframework.core.type.AnnotationMetadata;
<add>
<add>
<add>/**
<add> * Interface to be implemented by types that determine
<add> * which @{@link Configuration} class(es) should be imported based on
<add> * a given selection criteria, usually an annotation attribute.
<add> *
<add> * @author Chris Beams
<add> * @since 3.1
<add> * @see Import
<add> */
<add>public interface ImportSelector {
<add>
<add> /**
<add> * Select and return the names of which class(es) should be imported.
<add> * @param importingClassMetadata the AnnotationMetodata of the
<add> * importing @{@link Configuration} class.
<add> */
<add> String[] selectImports(AnnotationMetadata importingClassMetadata);
<add>
<add>} | 2 |
Javascript | Javascript | add @flow back to view.js | 28fb6ca5a4f011f74735f820dbe2e2c6c3ecff90 | <ide><path>Libraries/Components/View/View.js
<ide> * of patent rights can be found in the PATENTS file in the same directory.
<ide> *
<ide> * @providesModule View
<add> * @flow
<ide> */
<ide> 'use strict';
<ide> | 1 |
Python | Python | add additional assertions | 260e676a4a505ec27ffb72c7fea1e17e446d0b23 | <ide><path>libcloud/test/storage/test_local.py
<ide> def test_objects_success(self):
<ide> prefix = os.path.join("path", "to")
<ide> objects = self.driver.list_container_objects(container=container, prefix=prefix)
<ide> self.assertEqual(len(objects), 2)
<add> self.assertEqual(objects[0].name, "path/to/object4.ext")
<add> self.assertEqual(objects[1].name, "path/to/object3")
<ide>
<ide> prefix = "foo"
<ide> objects = self.driver.list_container_objects(container=container, prefix=prefix)
<ide> self.assertEqual(len(objects), 2)
<add> self.assertEqual(objects[0].name, "foo6")
<add> self.assertEqual(objects[1].name, "foo5")
<ide>
<ide> prefix = "foo5"
<ide> objects = self.driver.list_container_objects(container=container, prefix=prefix)
<ide> self.assertEqual(len(objects), 1)
<add> self.assertEqual(objects[0].name, "foo5")
<add>
<add> prefix = "foo6"
<add> objects = self.driver.list_container_objects(container=container, prefix=prefix)
<add> self.assertEqual(len(objects), 1)
<add> self.assertEqual(objects[0].name, "foo6")
<ide>
<ide> for obj in objects:
<ide> self.assertNotEqual(obj.hash, None) | 1 |
Mixed | Javascript | add store arg in asynclocalstorage | 6510a741c4ed04288d56486a1384b1fbecd08eaf | <ide><path>benchmark/async_hooks/async-resource-vs-destroy.js
<ide> function buildDestroy(getServe) {
<ide> function buildAsyncLocalStorage(getServe) {
<ide> const asyncLocalStorage = new AsyncLocalStorage();
<ide> const server = createServer((req, res) => {
<del> asyncLocalStorage.runSyncAndReturn(() => {
<add> asyncLocalStorage.runSyncAndReturn({}, () => {
<ide> getServe(getCLS, setCLS)(req, res);
<ide> });
<ide> });
<ide> function buildAsyncLocalStorage(getServe) {
<ide>
<ide> function getCLS() {
<ide> const store = asyncLocalStorage.getStore();
<del> return store.get('store');
<add> return store.state;
<ide> }
<ide>
<ide> function setCLS(state) {
<ide> const store = asyncLocalStorage.getStore();
<del> store.set('store', state);
<add> store.state = state;
<ide> }
<ide>
<ide> function close() {
<ide><path>doc/api/async_hooks.md
<ide> function log(...args) {
<ide> }
<ide>
<ide> http.createServer((request, response) => {
<del> asyncLocalStorage.run(() => {
<add> asyncLocalStorage.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set(kReq, request);
<ide> someAsyncOperation((err, result) => {
<ide> in the current process.
<ide> added: REPLACEME
<ide> -->
<ide>
<del>* Returns: {Map}
<add>* Returns: {any}
<ide>
<ide> This method returns the current store.
<ide> If this method is called outside of an asynchronous context initialized by
<ide> calling `asyncLocalStorage.run` or `asyncLocalStorage.runAndReturn`, it will
<ide> return `undefined`.
<ide>
<del>### `asyncLocalStorage.run(callback[, ...args])`
<add>### `asyncLocalStorage.run(store, callback[, ...args])`
<ide> <!-- YAML
<ide> added: REPLACEME
<ide> -->
<ide>
<add>* `store` {any}
<ide> * `callback` {Function}
<ide> * `...args` {any}
<ide>
<ide> Calling `asyncLocalStorage.run(callback)` will create a new asynchronous
<del>context.
<del>Within the callback function and the asynchronous operations from the callback,
<del>`asyncLocalStorage.getStore()` will return an instance of `Map` known as
<del>"the store". This store will be persistent through the following
<del>asynchronous calls.
<add>context. Within the callback function and the asynchronous operations from
<add>the callback, `asyncLocalStorage.getStore()` will return the object or
<add>the primitive value passed into the `store` argument (known as "the store").
<add>This store will be persistent through the following asynchronous calls.
<ide>
<ide> The callback will be ran asynchronously. Optionally, arguments can be passed
<ide> to the function. They will be passed to the callback function.
<ide> Also, the stacktrace will be impacted by the asynchronous call.
<ide> Example:
<ide>
<ide> ```js
<del>asyncLocalStorage.run(() => {
<del> asyncLocalStorage.getStore(); // Returns a Map
<add>const store = { id: 1 };
<add>asyncLocalStorage.run(store, () => {
<add> asyncLocalStorage.getStore(); // Returns the store object
<ide> someAsyncOperation(() => {
<del> asyncLocalStorage.getStore(); // Returns the same Map
<add> asyncLocalStorage.getStore(); // Returns the same object
<ide> });
<ide> });
<ide> asyncLocalStorage.getStore(); // Returns undefined
<ide> Also, the stacktrace will be impacted by the asynchronous call.
<ide> Example:
<ide>
<ide> ```js
<del>asyncLocalStorage.run(() => {
<del> asyncLocalStorage.getStore(); // Returns a Map
<add>asyncLocalStorage.run('store value', () => {
<add> asyncLocalStorage.getStore(); // Returns 'store value'
<ide> asyncLocalStorage.exit(() => {
<ide> asyncLocalStorage.getStore(); // Returns undefined
<ide> });
<del> asyncLocalStorage.getStore(); // Returns the same Map
<add> asyncLocalStorage.getStore(); // Returns 'store value'
<ide> });
<ide> ```
<ide>
<del>### `asyncLocalStorage.runSyncAndReturn(callback[, ...args])`
<add>### `asyncLocalStorage.runSyncAndReturn(store, callback[, ...args])`
<ide> <!-- YAML
<ide> added: REPLACEME
<ide> -->
<ide>
<add>* `store` {any}
<ide> * `callback` {Function}
<ide> * `...args` {any}
<ide>
<ide> the context will be exited.
<ide> Example:
<ide>
<ide> ```js
<add>const store = { id: 2 };
<ide> try {
<del> asyncLocalStorage.runSyncAndReturn(() => {
<del> asyncLocalStorage.getStore(); // Returns a Map
<add> asyncLocalStorage.runSyncAndReturn(store, () => {
<add> asyncLocalStorage.getStore(); // Returns the store object
<ide> throw new Error();
<ide> });
<ide> } catch (e) {
<ide> Example:
<ide> ```js
<ide> // Within a call to run or runSyncAndReturn
<ide> try {
<del> asyncLocalStorage.getStore(); // Returns a Map
<add> asyncLocalStorage.getStore(); // Returns the store object or value
<ide> asyncLocalStorage.exitSyncAndReturn(() => {
<ide> asyncLocalStorage.getStore(); // Returns undefined
<ide> throw new Error();
<ide> });
<ide> } catch (e) {
<del> asyncLocalStorage.getStore(); // Returns the same Map
<add> asyncLocalStorage.getStore(); // Returns the same object or value
<ide> // The error will be caught here
<ide> }
<ide> ```
<ide> It cannot be promisified using `util.promisify`. If needed, the `Promise`
<ide> constructor can be used:
<ide>
<ide> ```js
<add>const store = new Map(); // initialize the store
<ide> new Promise((resolve, reject) => {
<del> asyncLocalStorage.run(() => {
<add> asyncLocalStorage.run(store, () => {
<ide> someFunction((err, result) => {
<ide> if (err) {
<ide> return reject(err);
<ide> the following pattern should be used:
<ide>
<ide> ```js
<ide> async function fn() {
<del> await asyncLocalStorage.runSyncAndReturn(() => {
<add> await asyncLocalStorage.runSyncAndReturn(new Map(), () => {
<ide> asyncLocalStorage.getStore().set('key', value);
<ide> return foo(); // The return value of foo will be awaited
<ide> });
<ide><path>lib/async_hooks.js
<ide> 'use strict';
<ide>
<ide> const {
<del> Map,
<ide> NumberIsSafeInteger,
<ide> ReflectApply,
<ide> Symbol,
<del>
<ide> } = primordials;
<ide>
<ide> const {
<ide> class AsyncLocalStorage {
<ide> }
<ide> }
<ide>
<del> _enter() {
<add> _enter(store) {
<ide> if (!this.enabled) {
<ide> this.enabled = true;
<ide> storageList.push(this);
<ide> storageHook.enable();
<ide> }
<ide> const resource = executionAsyncResource();
<del> resource[this.kResourceStore] = new Map();
<add> resource[this.kResourceStore] = store;
<ide> }
<ide>
<ide> _exit() {
<ide> class AsyncLocalStorage {
<ide> }
<ide> }
<ide>
<del> runSyncAndReturn(callback, ...args) {
<del> this._enter();
<add> runSyncAndReturn(store, callback, ...args) {
<add> this._enter(store);
<ide> try {
<ide> return callback(...args);
<ide> } finally {
<ide> class AsyncLocalStorage {
<ide> }
<ide> }
<ide>
<del> run(callback, ...args) {
<del> this._enter();
<add> run(store, callback, ...args) {
<add> this._enter(store);
<ide> process.nextTick(callback, ...args);
<ide> this._exit();
<ide> }
<ide><path>test/async-hooks/test-async-local-storage-args.js
<ide> const { AsyncLocalStorage } = require('async_hooks');
<ide>
<ide> const asyncLocalStorage = new AsyncLocalStorage();
<ide>
<del>asyncLocalStorage.run((runArg) => {
<add>asyncLocalStorage.run({}, (runArg) => {
<ide> assert.strictEqual(runArg, 1);
<ide> asyncLocalStorage.exit((exitArg) => {
<ide> assert.strictEqual(exitArg, 2);
<ide> }, 2);
<ide> }, 1);
<ide>
<del>asyncLocalStorage.runSyncAndReturn((runArg) => {
<add>asyncLocalStorage.runSyncAndReturn({}, (runArg) => {
<ide> assert.strictEqual(runArg, 'foo');
<ide> asyncLocalStorage.exitSyncAndReturn((exitArg) => {
<ide> assert.strictEqual(exitArg, 'bar');
<ide><path>test/async-hooks/test-async-local-storage-async-await.js
<ide> async function test() {
<ide> }
<ide>
<ide> async function main() {
<del> await asyncLocalStorage.runSyncAndReturn(test);
<add> await asyncLocalStorage.runSyncAndReturn(new Map(), test);
<ide> assert.strictEqual(asyncLocalStorage.getStore(), undefined);
<ide> }
<ide>
<ide><path>test/async-hooks/test-async-local-storage-async-functions.js
<ide> async function testAwait() {
<ide> await asyncLocalStorage.exitSyncAndReturn(testOut);
<ide> }
<ide>
<del>asyncLocalStorage.run(() => {
<add>asyncLocalStorage.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set('key', 'value');
<ide> testAwait(); // should not reject
<ide><path>test/async-hooks/test-async-local-storage-enable-disable.js
<ide> const { AsyncLocalStorage } = require('async_hooks');
<ide>
<ide> const asyncLocalStorage = new AsyncLocalStorage();
<ide>
<del>asyncLocalStorage.runSyncAndReturn(() => {
<add>asyncLocalStorage.runSyncAndReturn(new Map(), () => {
<ide> asyncLocalStorage.getStore().set('foo', 'bar');
<ide> process.nextTick(() => {
<ide> assert.strictEqual(asyncLocalStorage.getStore().get('foo'), 'bar');
<ide> asyncLocalStorage.disable();
<ide> assert.strictEqual(asyncLocalStorage.getStore(), undefined);
<ide> process.nextTick(() => {
<ide> assert.strictEqual(asyncLocalStorage.getStore(), undefined);
<del> asyncLocalStorage.runSyncAndReturn(() => {
<add> asyncLocalStorage.runSyncAndReturn(new Map(), () => {
<ide> assert.notStrictEqual(asyncLocalStorage.getStore(), undefined);
<ide> });
<ide> });
<ide><path>test/async-hooks/test-async-local-storage-errors-async.js
<ide> process.setUncaughtExceptionCaptureCallback((err) => {
<ide> assert.strictEqual(asyncLocalStorage.getStore().get('hello'), 'node');
<ide> });
<ide>
<del>asyncLocalStorage.run(() => {
<add>asyncLocalStorage.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set('hello', 'node');
<ide> setTimeout(() => {
<ide><path>test/async-hooks/test-async-local-storage-errors-sync-ret.js
<ide> process.setUncaughtExceptionCaptureCallback((err) => {
<ide> });
<ide>
<ide> try {
<del> asyncLocalStorage.runSyncAndReturn(() => {
<add> asyncLocalStorage.runSyncAndReturn(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set('hello', 'node');
<ide> setTimeout(() => {
<ide><path>test/async-hooks/test-async-local-storage-http.js
<ide> const server = http.createServer((req, res) => {
<ide> });
<ide>
<ide> server.listen(0, () => {
<del> asyncLocalStorage.run(() => {
<add> asyncLocalStorage.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set('hello', 'world');
<ide> http.get({ host: 'localhost', port: server.address().port }, () => {
<ide><path>test/async-hooks/test-async-local-storage-misc-stores.js
<add>'use strict';
<add>require('../common');
<add>const assert = require('assert');
<add>const { AsyncLocalStorage } = require('async_hooks');
<add>
<add>const asyncLocalStorage = new AsyncLocalStorage();
<add>
<add>asyncLocalStorage.run(42, () => {
<add> assert.strictEqual(asyncLocalStorage.getStore(), 42);
<add>});
<add>
<add>const runStore = { foo: 'bar' };
<add>asyncLocalStorage.run(runStore, () => {
<add> assert.strictEqual(asyncLocalStorage.getStore(), runStore);
<add>});
<add>
<add>asyncLocalStorage.runSyncAndReturn('hello node', () => {
<add> assert.strictEqual(asyncLocalStorage.getStore(), 'hello node');
<add>});
<add>
<add>const runSyncStore = { hello: 'node' };
<add>asyncLocalStorage.runSyncAndReturn(runSyncStore, () => {
<add> assert.strictEqual(asyncLocalStorage.getStore(), runSyncStore);
<add>});
<ide><path>test/async-hooks/test-async-local-storage-nested.js
<ide> const { AsyncLocalStorage } = require('async_hooks');
<ide> const asyncLocalStorage = new AsyncLocalStorage();
<ide>
<ide> setTimeout(() => {
<del> asyncLocalStorage.run(() => {
<add> asyncLocalStorage.run(new Map(), () => {
<ide> const asyncLocalStorage2 = new AsyncLocalStorage();
<del> asyncLocalStorage2.run(() => {
<add> asyncLocalStorage2.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> const store2 = asyncLocalStorage2.getStore();
<ide> store.set('hello', 'world');
<ide><path>test/async-hooks/test-async-local-storage-no-mix-contexts.js
<ide> const asyncLocalStorage = new AsyncLocalStorage();
<ide> const asyncLocalStorage2 = new AsyncLocalStorage();
<ide>
<ide> setTimeout(() => {
<del> asyncLocalStorage.run(() => {
<del> asyncLocalStorage2.run(() => {
<add> asyncLocalStorage.run(new Map(), () => {
<add> asyncLocalStorage2.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> const store2 = asyncLocalStorage2.getStore();
<ide> store.set('hello', 'world');
<ide> setTimeout(() => {
<ide> }, 100);
<ide>
<ide> setTimeout(() => {
<del> asyncLocalStorage.run(() => {
<add> asyncLocalStorage.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set('hello', 'earth');
<ide> setTimeout(() => {
<ide><path>test/async-hooks/test-async-local-storage-promises.js
<ide> async function main() {
<ide> throw err;
<ide> });
<ide> await new Promise((resolve, reject) => {
<del> asyncLocalStorage.run(() => {
<add> asyncLocalStorage.run(new Map(), () => {
<ide> const store = asyncLocalStorage.getStore();
<ide> store.set('a', 1);
<ide> next().then(resolve, reject); | 14 |
Java | Java | use action instead of func0<void> | 40be93bf7afef40fa5eb079f5d27aaa6164f93de | <ide><path>src/main/java/rx/internal/operators/OperatorOnBackpressureBuffer.java
<ide> import rx.Observable.Operator;
<ide> import rx.Producer;
<ide> import rx.Subscriber;
<del>import rx.functions.Func0;
<add>import rx.functions.Action0;
<ide>
<ide> public class OperatorOnBackpressureBuffer<T> implements Operator<T, T> {
<ide>
<ide> private final NotificationLite<T> on = NotificationLite.instance();
<ide>
<ide> private final Long capacity;
<del> private final Func0 onOverflow;
<add> private final Action0 onOverflow;
<ide>
<ide> public OperatorOnBackpressureBuffer() {
<ide> this.capacity = null;
<ide> public OperatorOnBackpressureBuffer(long capacity) {
<ide> this(capacity, null);
<ide> }
<ide>
<del> public OperatorOnBackpressureBuffer(long capacity, Func0<Void> onOverflow) {
<add> public OperatorOnBackpressureBuffer(long capacity, Action0 onOverflow) {
<ide> if (capacity <= 0) {
<ide> throw new IllegalArgumentException("Buffer capacity must be > 0");
<ide> }
<ide><path>src/test/java/rx/internal/operators/OperatorOnBackpressureBufferTest.java
<ide> */
<ide> package rx.internal.operators;
<ide>
<add>import static org.junit.Assert.assertEquals;
<add>import static org.junit.Assert.assertTrue;
<add>
<ide> import java.nio.BufferOverflowException;
<ide> import java.util.concurrent.CountDownLatch;
<ide>
<ide> import rx.Observer;
<ide> import rx.Subscriber;
<ide> import rx.Subscription;
<del>import rx.functions.Func0;
<add>import rx.functions.Action0;
<ide> import rx.observables.ConnectableObservable;
<ide> import rx.observers.TestSubscriber;
<ide> import rx.schedulers.Schedulers;
<ide>
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertTrue;
<del>
<ide> public class OperatorOnBackpressureBufferTest {
<ide>
<ide> @Test
<ide> public void onNext(Long t) {
<ide> .publish();
<ide> final ConnectableObservable<Long> batch =
<ide> infinite.subscribeOn(Schedulers.computation())
<del> .onBackpressureBuffer(100, new Func0<Void>() {
<add> .onBackpressureBuffer(100, new Action0() {
<ide> @Override
<del> public Void call() {
<add> public void call() {
<ide> l3.countDown();
<del> return null;
<ide> }
<ide> }).publish();
<ide> Subscription s = batch.subscribe(ts); | 2 |
Text | Text | add changelog for | 6caaec74bb4e3e476f43185ca030cdaad5b0e124 | <ide><path>activerecord/CHANGELOG.md
<ide> end
<ide> ```
<ide>
<add> Active Record logs will also include timing info for the duration of how long
<add> the main thread had to wait to access the result. This timing is useful to know
<add> whether or not it's worth to load the query asynchronously.
<add>
<add> ```
<add> DEBUG -- : Category Load (62.1ms) SELECT * FROM `categories` LIMIT 50
<add> DEBUG -- : ASYNC Post Load (64ms) (db time 126.1ms) SELECT * FROM `posts` LIMIT 100
<add> ```
<add>
<add> The duration in the first set of parens is how long the main thread was blocked
<add> waiting for the results, and the second set of parens with "db time" is how long
<add> the entire query took to execute.
<add>
<ide> *Jean Boussier*
<ide>
<ide> * Implemented `ActiveRecord::Relation#excluding` method. | 1 |
Python | Python | add anyprecisionadamw optimizer | 84c9cc6d1599e1a64ee73e14ce33727ec865baef | <ide><path>src/transformers/trainer.py
<ide> import time
<ide> import warnings
<ide> from collections.abc import Mapping
<add>from distutils.util import strtobool
<ide> from pathlib import Path
<ide> from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
<ide>
<ide> def get_optimizer_cls_and_kwargs(args: TrainingArguments) -> Tuple[Any, Any]:
<ide> The training arguments for the training session.
<ide>
<ide> """
<add>
<add> # parse args.optim_args
<add> optim_args = {}
<add> if args.optim_args:
<add> for mapping in args.optim_args.replace(" ", "").split(","):
<add> key, value = mapping.split("=")
<add> optim_args[key] = value
<add>
<ide> optimizer_kwargs = {"lr": args.learning_rate}
<add>
<ide> adam_kwargs = {
<ide> "betas": (args.adam_beta1, args.adam_beta2),
<ide> "eps": args.adam_epsilon,
<ide> def get_optimizer_cls_and_kwargs(args: TrainingArguments) -> Tuple[Any, Any]:
<ide> optimizer_kwargs.update(adam_kwargs)
<ide> except ImportError:
<ide> raise ValueError("Trainer tried to instantiate bnb Adam8bit but bnb is not installed!")
<add> elif args.optim == OptimizerNames.ADAMW_ANYPRECISION:
<add> try:
<add> from torchdistx.optimizers import AnyPrecisionAdamW
<add>
<add> optimizer_cls = AnyPrecisionAdamW
<add> optimizer_kwargs.update(adam_kwargs)
<add>
<add> # TODO Change dtypes back to M=FP32, Var = BF16, Kahan = False once they can be cast together in torchdistx.
<add> optimizer_kwargs.update(
<add> {
<add> "use_kahan_summation": strtobool(optim_args.get("use_kahan_summation", "False")),
<add> "momentum_dtype": getattr(torch, optim_args.get("momentum_dtype", "float32")),
<add> "variance_dtype": getattr(torch, optim_args.get("variance_dtype", "float32")),
<add> "compensation_buffer_dtype": getattr(
<add> torch, optim_args.get("compensation_buffer_dtype", "bfloat16")
<add> ),
<add> }
<add> )
<add> except ImportError:
<add> raise ValueError("Please install https://github.com/pytorch/torchdistx")
<ide> elif args.optim == OptimizerNames.SGD:
<ide> optimizer_cls = torch.optim.SGD
<ide> elif args.optim == OptimizerNames.ADAGRAD:
<ide><path>src/transformers/training_args.py
<ide> class OptimizerNames(ExplicitEnum):
<ide> ADAMW_APEX_FUSED = "adamw_apex_fused"
<ide> ADAFACTOR = "adafactor"
<ide> ADAMW_BNB = "adamw_bnb_8bit"
<add> ADAMW_ANYPRECISION = "adamw_anyprecision"
<ide> SGD = "sgd"
<ide> ADAGRAD = "adagrad"
<ide>
<ide> class TrainingArguments:
<ide>
<ide> The options should be separated by whitespaces.
<ide> optim (`str` or [`training_args.OptimizerNames`], *optional*, defaults to `"adamw_hf"`):
<del> The optimizer to use: adamw_hf, adamw_torch, adamw_apex_fused, or adafactor.
<add> The optimizer to use: adamw_hf, adamw_torch, adamw_apex_fused, adamw_anyprecision or adafactor.
<add> optim_args (`str`, *optional*):
<add> Optional arguments that are supplied to AnyPrecisionAdamW.
<ide> adafactor (`bool`, *optional*, defaults to `False`):
<ide> This argument is deprecated. Use `--optim adafactor` instead.
<ide> group_by_length (`bool`, *optional*, defaults to `False`):
<ide> class TrainingArguments:
<ide> default="adamw_hf",
<ide> metadata={"help": "The optimizer to use."},
<ide> )
<add> optim_args: Optional[str] = field(default=None, metadata={"help": "Optional arguments to supply to optimizer."})
<ide> adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
<ide> group_by_length: bool = field(
<ide> default=False,
<ide><path>src/transformers/utils/__init__.py
<ide> is_torch_tf32_available,
<ide> is_torch_tpu_available,
<ide> is_torchaudio_available,
<add> is_torchdistx_available,
<ide> is_torchdynamo_available,
<ide> is_training_run_on_sagemaker,
<ide> is_vision_available,
<ide><path>src/transformers/utils/import_utils.py
<ide> def is_bitsandbytes_available():
<ide> return importlib.util.find_spec("bitsandbytes") is not None
<ide>
<ide>
<add>def is_torchdistx_available():
<add> return importlib.util.find_spec("torchdistx") is not None
<add>
<add>
<ide> def is_faiss_available():
<ide> return _faiss_available
<ide>
<ide><path>tests/trainer/test_trainer.py
<ide> )
<ide> from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR
<ide> from transformers.training_args import OptimizerNames
<del>from transformers.utils import WEIGHTS_INDEX_NAME, WEIGHTS_NAME, is_apex_available, is_bitsandbytes_available
<add>from transformers.utils import (
<add> WEIGHTS_INDEX_NAME,
<add> WEIGHTS_NAME,
<add> is_apex_available,
<add> is_bitsandbytes_available,
<add> is_torchdistx_available,
<add>)
<ide> from transformers.utils.hp_naming import TrialShortNamer
<ide>
<ide>
<ide> def hp_name(trial):
<ide> "lr": TrainingArguments.learning_rate,
<ide> }
<ide>
<add> default_anyprecision_kwargs = {
<add> "use_kahan_summation": False,
<add> "momentum_dtype": torch.float32,
<add> "variance_dtype": torch.float32,
<add> "compensation_buffer_dtype": torch.bfloat16,
<add> }
<add>
<ide> optim_test_params = [
<ide> (
<del> OptimizerNames.ADAMW_HF,
<add> TrainingArguments(optim=OptimizerNames.ADAMW_HF, output_dir="None"),
<ide> transformers.optimization.AdamW,
<ide> default_adam_kwargs,
<ide> ),
<ide> (
<del> OptimizerNames.ADAMW_HF.value,
<add> TrainingArguments(optim=OptimizerNames.ADAMW_HF.value, output_dir="None"),
<ide> transformers.optimization.AdamW,
<ide> default_adam_kwargs,
<ide> ),
<ide> (
<del> OptimizerNames.ADAMW_TORCH,
<add> TrainingArguments(optim=OptimizerNames.ADAMW_TORCH, output_dir="None"),
<ide> torch.optim.AdamW,
<ide> default_adam_kwargs,
<ide> ),
<ide> (
<del> OptimizerNames.ADAFACTOR,
<add> TrainingArguments(optim=OptimizerNames.ADAFACTOR, output_dir="None"),
<ide> transformers.optimization.Adafactor,
<ide> {
<ide> "scale_parameter": False,
<ide> def hp_name(trial):
<ide>
<ide> optim_test_params.append(
<ide> (
<del> OptimizerNames.ADAMW_APEX_FUSED,
<add> TrainingArguments(OptimizerNames.ADAMW_APEX_FUSED, output_dir="None"),
<ide> apex.optimizers.FusedAdam,
<ide> default_adam_kwargs,
<ide> )
<ide> def hp_name(trial):
<ide>
<ide> optim_test_params.append(
<ide> (
<del> OptimizerNames.ADAMW_BNB,
<add> TrainingArguments(optim=OptimizerNames.ADAMW_BNB, ouput_dir="None"),
<ide> bnb.optim.Adam8bit,
<ide> default_adam_kwargs,
<ide> )
<ide> )
<ide>
<add> if is_torchdistx_available():
<add> import torchdistx
<add>
<add> optim_test_params.append(
<add> (
<add> TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir="None"),
<add> torchdistx.optimizers.AnyPrecisionAdamW,
<add> dict(default_adam_kwargs, **default_anyprecision_kwargs),
<add> )
<add> )
<add>
<ide>
<ide> @require_torch
<ide> class TrainerOptimizerChoiceTest(unittest.TestCase):
<del> def check_optim_and_kwargs(self, optim: OptimizerNames, mandatory_kwargs, expected_cls):
<del> args = TrainingArguments(optim=optim, output_dir="None")
<del> actual_cls, optim_kwargs = Trainer.get_optimizer_cls_and_kwargs(args)
<add> def check_optim_and_kwargs(self, training_args: TrainingArguments, expected_cls, expected_kwargs):
<add> actual_cls, optim_kwargs = Trainer.get_optimizer_cls_and_kwargs(training_args)
<ide> self.assertEqual(expected_cls, actual_cls)
<ide> self.assertIsNotNone(optim_kwargs)
<ide>
<del> for p, v in mandatory_kwargs.items():
<add> for p, v in expected_kwargs.items():
<ide> self.assertTrue(p in optim_kwargs)
<ide> actual_v = optim_kwargs[p]
<ide> self.assertTrue(actual_v == v, f"Failed check for {p}. Expected {v}, but got {actual_v}.")
<ide>
<ide> @parameterized.expand(optim_test_params, skip_on_empty=True)
<del> def test_optim_supported(self, name: str, expected_cls, mandatory_kwargs):
<add> def test_optim_supported(self, training_args: TrainingArguments, expected_cls, expected_kwargs):
<ide> # exercises all the valid --optim options
<del> self.check_optim_and_kwargs(name, mandatory_kwargs, expected_cls)
<add> self.check_optim_and_kwargs(training_args, expected_cls, expected_kwargs)
<ide>
<del> trainer = get_regression_trainer(optim=name)
<add> trainer = get_regression_trainer(**training_args.to_dict())
<ide> trainer.train()
<ide>
<ide> def test_fused_adam(self):
<ide> def test_fused_adam(self):
<ide> }
<ide> with patch.dict("sys.modules", modules):
<ide> self.check_optim_and_kwargs(
<del> OptimizerNames.ADAMW_APEX_FUSED,
<del> default_adam_kwargs,
<add> TrainingArguments(optim=OptimizerNames.ADAMW_APEX_FUSED, output_dir="None"),
<ide> mock.optimizers.FusedAdam,
<add> default_adam_kwargs,
<ide> )
<ide>
<ide> def test_fused_adam_no_apex(self):
<ide> def test_bnb_adam8bit(self):
<ide> }
<ide> with patch.dict("sys.modules", modules):
<ide> self.check_optim_and_kwargs(
<del> OptimizerNames.ADAMW_BNB,
<del> default_adam_kwargs,
<add> TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir="None"),
<ide> mock.optim.Adam8bit,
<add> default_adam_kwargs,
<ide> )
<ide>
<ide> def test_bnb_adam8bit_no_bnb(self):
<ide> def test_bnb_adam8bit_no_bnb(self):
<ide> with self.assertRaises(ValueError):
<ide> Trainer.get_optimizer_cls_and_kwargs(args)
<ide>
<add> def test_anyprecision_adamw(self):
<add> # Pretend that torchdistx is installed and mock torchdistx.optimizers.AnyPrecisionAdamW exists.
<add> # Trainer.get_optimizer_cls_and_kwargs does not use AnyPrecisioinAdamW. It only has to return the
<add> # class given, so mocking torchdistx.optimizers.AnyPrecisionAdamW should be fine for testing and allow
<add> # the test to run without requiring a bnb installation.
<add> mock = Mock()
<add> modules = {
<add> "torchdistx": mock,
<add> "torchdistx.optimizers": mock.optimizers,
<add> "torchdistx.optimizers.AnyPrecisionAdamW.": mock.optimizers.AnyPrecisionAdamW,
<add> }
<add> with patch.dict("sys.modules", modules):
<add> self.check_optim_and_kwargs(
<add> TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir="None"),
<add> mock.optimizers.AnyPrecisionAdamW,
<add> dict(default_adam_kwargs, **default_anyprecision_kwargs),
<add> )
<add>
<add> def test_no_torchdistx_anyprecision_adamw(self):
<add> args = TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir="None")
<add>
<add> # Pretend that torchdistx does not exist, even if installed. By setting torchdistx to None, importing
<add> # torchdistx.optimizers will fail even if torchdistx is installed.
<add> with patch.dict("sys.modules", {"torchdistx.optimizers": None}):
<add> with self.assertRaises(ValueError):
<add> Trainer.get_optimizer_cls_and_kwargs(args)
<add>
<ide>
<ide> @require_torch
<ide> @require_wandb | 5 |
Text | Text | add list of events in remote api docs | fc7f0550965d06dd8dd31fb55c74fe02e9a436dc | <ide><path>docs/sources/reference/api/docker_remote_api_v1.17.md
<ide> polling (using since).
<ide>
<ide> Docker containers will report the following events:
<ide>
<del> create, destroy, die, export, kill, oom, pause, restart, start, stop, unpause
<add> create, destroy, die, exec_create, exec_start, export, kill, oom, pause, restart, start, stop, unpause
<ide>
<ide> and Docker images will report:
<ide> | 1 |
Go | Go | move toolsscratchpath to /tmp | 993f4072874ee5cdce93ec9b6525e1fa3ebda4c8 | <ide><path>daemon/graphdriver/lcow/lcow.go
<ide> const (
<ide>
<ide> // toolsScratchPath is a location in a service utility VM that the tools can use as a
<ide> // scratch space to avoid running out of memory.
<del> // TODO @jhowardmsft. I really dislike this path! But needs a platform change or passing parameters to the tools.
<del> toolsScratchPath = "/mnt/gcs/LinuxServiceVM/scratch"
<add> toolsScratchPath = "/tmp/scratch"
<ide>
<ide> // svmGlobalID is the ID used in the serviceVMs map for the global service VM when running in "global" mode.
<ide> svmGlobalID = "_lcow_global_svm_" | 1 |
Text | Text | add some examples for getting current_user | 839250e26267a5d7438338665c2d7533dda10786 | <ide><path>guides/source/action_cable_overview.md
<ide> specific connection later. Note that anything marked as an identifier will autom
<ide> create a delegate by the same name on any channel instances created off the connection.
<ide>
<ide> This example relies on the fact that you will already have handled authentication of the user
<del>somewhere else in your application, and that a successful authentication sets a signed
<add>somewhere else in your application, and that a successful authentication sets an encrypted
<ide> cookie with the user ID.
<ide>
<ide> The cookie is then automatically sent to the connection instance when a new connection
<ide> by this same current user, you're also ensuring that you can later retrieve all
<ide> connections by a given user (and potentially disconnect them all if the user is deleted
<ide> or unauthorized).
<ide>
<add>If you use Device for authenticaion, you can get `current_user` from warden:
<add>
<add>```ruby
<add> verified_user = env['warden'].user
<add>```
<add>
<add>In any other authentication approach you can access the session cookie. If you use cookie store for the session, your session cookie is named "\_session" and the user ID key is "user_id" you can use this approach:
<add>```ruby
<add> verified_user = User.find_by(id: cookies.encrypted['_session']['user_id'])
<add>```
<add>
<ide> ### Channels
<ide>
<ide> A *channel* encapsulates a logical unit of work, similar to what a controller does in a | 1 |
Java | Java | avoid unnecessary sorting | 2093e35f27cf742e6b447c87a8e2c37df5256a16 | <ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/annotation/ReflectiveAspectJAdvisorFactory.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> private List<Method> getAdvisorMethods(Class<?> aspectClass) {
<ide> methods.add(method);
<ide> }
<ide> }, ReflectionUtils.USER_DECLARED_METHODS);
<del> methods.sort(METHOD_COMPARATOR);
<add> if (methods.size() > 1) {
<add> methods.sort(METHOD_COMPARATOR);
<add> }
<ide> return methods;
<ide> }
<ide>
<ide><path>spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Stream<T> stream() {
<ide> @Override
<ide> public Stream<T> orderedStream() {
<ide> String[] beanNames = getBeanNamesForTypedStream(requiredType);
<add> if (beanNames.length == 0) {
<add> return Stream.empty();
<add> }
<ide> Map<String, T> matchingBeans = new LinkedHashMap<>(beanNames.length);
<ide> for (String beanName : beanNames) {
<ide> Object beanInstance = getBean(beanName);
<ide> else if (Collection.class.isAssignableFrom(type) && type.isInterface()) {
<ide> TypeConverter converter = (typeConverter != null ? typeConverter : getTypeConverter());
<ide> Object result = converter.convertIfNecessary(matchingBeans.values(), type);
<ide> if (result instanceof List) {
<del> Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
<del> if (comparator != null) {
<del> ((List<?>) result).sort(comparator);
<add> if (((List<?>) result).size() > 1) {
<add> Comparator<Object> comparator = adaptDependencyComparator(matchingBeans);
<add> if (comparator != null) {
<add> ((List<?>) result).sort(comparator);
<add> }
<ide> }
<ide> }
<ide> return result;
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/ConsumesRequestCondition.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public ConsumesRequestCondition(String... consumes) {
<ide> */
<ide> public ConsumesRequestCondition(String[] consumes, String[] headers) {
<ide> this.expressions = new ArrayList<>(parseExpressions(consumes, headers));
<del> Collections.sort(this.expressions);
<add> if (this.expressions.size() > 1) {
<add> Collections.sort(this.expressions);
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/ProducesRequestCondition.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public ProducesRequestCondition(String[] produces, String[] headers) {
<ide> */
<ide> public ProducesRequestCondition(String[] produces, String[] headers, RequestedContentTypeResolver resolver) {
<ide> this.expressions = new ArrayList<>(parseExpressions(produces, headers));
<del> Collections.sort(this.expressions);
<add> if (this.expressions.size() > 1) {
<add> Collections.sort(this.expressions);
<add> }
<ide> this.contentTypeResolver = resolver != null ? resolver : DEFAULT_CONTENT_TYPE_RESOLVER;
<ide> }
<ide>
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ConsumesRequestCondition.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public ConsumesRequestCondition(String... consumes) {
<ide> */
<ide> public ConsumesRequestCondition(String[] consumes, @Nullable String[] headers) {
<ide> this.expressions = new ArrayList<>(parseExpressions(consumes, headers));
<del> Collections.sort(this.expressions);
<add> if (this.expressions.size() > 1) {
<add> Collections.sort(this.expressions);
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/condition/ProducesRequestCondition.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public ProducesRequestCondition(String[] produces, @Nullable String[] headers,
<ide> @Nullable ContentNegotiationManager manager) {
<ide>
<ide> this.expressions = new ArrayList<>(parseExpressions(produces, headers));
<del> Collections.sort(this.expressions);
<add> if (this.expressions.size() > 1) {
<add> Collections.sort(this.expressions);
<add> }
<ide> this.contentNegotiationManager = manager != null ? manager : DEFAULT_CONTENT_NEGOTIATION_MANAGER;
<ide> }
<ide> | 6 |
Java | Java | fix memory leak in headlessjstaskcontext | 3af104fbd3ba61160ddb1868283ff4e3debe533e | <ide><path>ReactAndroid/src/main/java/com/facebook/react/jstasks/HeadlessJsTaskContext.java
<ide>
<ide> package com.facebook.react.jstasks;
<ide>
<add>import java.lang.ref.WeakReference;
<ide> import java.util.Set;
<ide> import java.util.WeakHashMap;
<ide> import java.util.concurrent.CopyOnWriteArraySet;
<ide> public static HeadlessJsTaskContext getInstance(ReactContext context) {
<ide> return helper;
<ide> }
<ide>
<del> private final ReactContext mReactContext;
<add> private final WeakReference<ReactContext> mReactContext;
<ide> private final Set<HeadlessJsTaskEventListener> mHeadlessJsTaskEventListeners =
<ide> new CopyOnWriteArraySet<>();
<ide> private final AtomicInteger mLastTaskId = new AtomicInteger(0);
<ide> public static HeadlessJsTaskContext getInstance(ReactContext context) {
<ide> private final SparseArray<Runnable> mTaskTimeouts = new SparseArray<>();
<ide>
<ide> private HeadlessJsTaskContext(ReactContext reactContext) {
<del> mReactContext = reactContext;
<add> mReactContext = new WeakReference<ReactContext>(reactContext);
<ide> }
<ide>
<ide> /**
<ide> public boolean hasActiveTasks() {
<ide> */
<ide> public synchronized int startTask(final HeadlessJsTaskConfig taskConfig) {
<ide> UiThreadUtil.assertOnUiThread();
<del> if (mReactContext.getLifecycleState() == LifecycleState.RESUMED &&
<add> ReactContext reactContext = Assertions.assertNotNull(
<add> mReactContext.get(),
<add> "Tried to start a task on a react context that has already been destroyed");
<add> if (reactContext.getLifecycleState() == LifecycleState.RESUMED &&
<ide> !taskConfig.isAllowedInForeground()) {
<ide> throw new IllegalStateException(
<ide> "Tried to start task " + taskConfig.getTaskKey() +
<ide> " while in foreground, but this is not allowed.");
<ide> }
<ide> final int taskId = mLastTaskId.incrementAndGet();
<del> mReactContext.getJSModule(AppRegistry.class)
<add> reactContext.getJSModule(AppRegistry.class)
<ide> .startHeadlessTask(taskId, taskConfig.getTaskKey(), taskConfig.getData());
<ide> if (taskConfig.getTimeout() > 0) {
<ide> scheduleTaskTimeout(taskId, taskConfig.getTimeout()); | 1 |
Python | Python | remove unused imports | 983df1fe3f66ab53c254ee37aa29a82554029d3d | <ide><path>keras/layers/dense_attention.py
<ide> from keras.engine import base_layer
<ide> from keras.utils import control_flow_util
<ide> import tensorflow.compat.v2 as tf
<del>from tensorflow.python.platform import tf_logging
<ide> from tensorflow.python.util.tf_export import keras_export
<ide>
<ide>
<ide> class BaseDenseAttention(base_layer.BaseRandomLayer):
<ide> flow of information from the future towards the past.
<ide> dropout: Float between 0 and 1. Fraction of the units to drop for the
<ide> attention scores.
<del> return_attention_scores: bool, if `True`, layer returns the attention scores.
<del> If `True`, the layer is incompatible with TimeDistributed wrapper.
<del> Default is `False`.
<ide>
<ide> Call Args:
<ide>
<ide> class BaseDenseAttention(base_layer.BaseRandomLayer):
<ide> `mask==False` do not contribute to the result.
<ide> training: Python boolean indicating whether the layer should behave in
<ide> training mode (adding dropout) or in inference mode (no dropout).
<del> return_attention_scores: bool, (deprecated) if `True`, returns the attention scores
<add> return_attention_scores: bool, if `True`, returns the attention scores
<ide> (after masking and softmax) as an additional output argument.
<ide>
<ide> Output: | 1 |
Python | Python | fix typo in docstring | 4ed53ae5a488b08cd9d65bc12f03859b56e79a88 | <ide><path>keras/preprocessing/sequence.py
<ide> def pad_sequences(sequences, maxlen=None, dtype='int32', padding='pre', truncating='pre', value=0.):
<ide> """
<ide> Pad each sequence to the same length:
<del> the length of the longuest sequence.
<add> the length of the longest sequence.
<ide>
<ide> If maxlen is provided, any sequence longer
<ide> than maxlen is truncated to maxlen. Truncation happens off either the beginning (default) or | 1 |
Ruby | Ruby | fix orderedhash.select to return self instance | a94966ea094fcfd94cf09642d3a561af80c64602 | <ide><path>activesupport/lib/active_support/ordered_hash.rb
<ide> def encode_with(coder)
<ide> coder.represent_seq '!omap', map { |k,v| { k => v } }
<ide> end
<ide>
<add> def select(*args, &block)
<add> dup.tap { |hash| hash.select!(*args, &block) }
<add> end
<add>
<ide> def reject(*args, &block)
<ide> dup.tap { |hash| hash.reject!(*args, &block) }
<ide> end
<ide><path>activesupport/test/ordered_hash_test.rb
<ide> def test_find_all
<ide> end
<ide>
<ide> def test_select
<del> assert_equal @keys, @ordered_hash.select { true }.map(&:first)
<add> new_ordered_hash = @ordered_hash.select { true }
<add> assert_equal @keys, new_ordered_hash.map(&:first)
<add> assert_instance_of ActiveSupport::OrderedHash, new_ordered_hash
<ide> end
<ide>
<ide> def test_delete_if
<ide> def test_reject
<ide> assert_equal copy, @ordered_hash
<ide> assert !new_ordered_hash.keys.include?('pink')
<ide> assert @ordered_hash.keys.include?('pink')
<add> assert_instance_of ActiveSupport::OrderedHash, new_ordered_hash
<ide> end
<ide>
<ide> def test_clear | 2 |
PHP | PHP | fix possible notice errors | 87677e4cdfa0fee3374cd645d6acb59b9c6f2c04 | <ide><path>lib/Cake/TestSuite/Reporter/CakeHtmlReporter.php
<ide> public function paintFail($message, $test) {
<ide> $trace = $this->_getStackTrace($message);
<ide> $testName = get_class($test) . '(' . $test->getName() . ')';
<ide>
<add> $actualMsg = $expectedMsg = null;
<ide> $failure = $message->getComparisonFailure();
<ide> if (is_object($failure)) {
<del> $actualMsg = $message->getComparisonFailure()->getActualAsString();
<del> $expectedMsg = $message->getComparisonFailure()->getExpectedAsString();
<add> $actualMsg = $message->getComparisonFailure()->getActualAsString();
<add> $expectedMsg = $message->getComparisonFailure()->getExpectedAsString();
<ide> }
<ide>
<ide> echo "<li class='fail'>\n";
<ide> echo "<span>Failed</span>";
<ide> echo "<div class='msg'><pre>" . $this->_htmlEntities($message->toString());
<ide>
<del>
<ide> if ((is_string($actualMsg) && is_string($expectedMsg)) || (is_array($actualMsg) && is_array($expectedMsg))) {
<del> echo "<br />" . PHPUnit_Util_Diff::diff($expectedMsg, $actualMsg);
<add> echo "<br />" . PHPUnit_Util_Diff::diff($expectedMsg, $actualMsg);
<ide> }
<ide>
<ide> echo "</pre></div>\n"; | 1 |
PHP | PHP | sortrecursive | dd5e57940222878298423c6ba72f45160aca00ab | <ide><path>src/Illuminate/Collections/Arr.php
<ide> public static function sort($array, $callback = null)
<ide> * Recursively sort an array by keys and values.
<ide> *
<ide> * @param array $array
<add> * @param int $options
<add> * @param bool $descending
<ide> * @return array
<ide> */
<del> public static function sortRecursive($array)
<add> public static function sortRecursive($array, $options = SORT_REGULAR, $descending = false)
<ide> {
<ide> foreach ($array as &$value) {
<ide> if (is_array($value)) {
<del> $value = static::sortRecursive($value);
<add> $value = static::sortRecursive($value, $options, $descending);
<ide> }
<ide> }
<ide>
<ide> if (static::isAssoc($array)) {
<del> ksort($array);
<add> $descending ? krsort($array, $options)
<add> : ksort($array, $options);
<ide> } else {
<del> sort($array);
<add> $descending ? rsort($array, $options)
<add> : sort($array, $options);
<ide> }
<ide>
<ide> return $array; | 1 |
Java | Java | add marbles for single.from operators | 396f2f6d15a52e5c79d0ee7b4dcfb62f6a8029b7 | <ide><path>src/main/java/io/reactivex/Single.java
<ide> public static <T> Single<T> error(final Throwable exception) {
<ide> * Allows you to defer execution of passed function until SingleObserver subscribes to the {@link Single}.
<ide> * It makes passed function "lazy".
<ide> * Result of the function invocation will be emitted by the {@link Single}.
<add> * <p>
<add> * <img width="640" height="467" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromCallable.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd>
<ide> public static <T> Single<T> fromFuture(Future<? extends T> future, Scheduler sch
<ide> * Note that even though {@link Publisher} appears to be a functional interface, it
<ide> * is not recommended to implement it through a lambda as the specification requires
<ide> * state management that is not achievable with a stateless lambda.
<add> * <p>
<add> * <img width="640" height="322" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromPublisher.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Backpressure:</b></dt>
<ide> * <dd>The {@code publisher} is consumed in an unbounded fashion but will be cancelled
<ide> public static <T> Single<T> fromPublisher(final Publisher<? extends T> publisher
<ide> * Wraps a specific ObservableSource into a Single and signals its single element or error.
<ide> * <p>If the ObservableSource is empty, a NoSuchElementException is signalled.
<ide> * If the source has more than one element, an IndexOutOfBoundsException is signalled.
<add> * <p>
<add> * <img width="640" height="343" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.fromObservable.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code fromObservable} does not operate by default on a particular {@link Scheduler}.</dd> | 1 |
PHP | PHP | make code a little cleaner | edccb7c6cd8cb668b7303cdbcf73e0d0a6235d03 | <ide><path>src/Illuminate/Queue/BeanstalkdQueue.php
<ide> <?php namespace Illuminate\Queue;
<ide>
<del>use Pheanstalk\Job as Pheanstalk_Job;
<del>use Pheanstalk\Pheanstalk as Pheanstalk;
<add>use Pheanstalk\Job as PheanstalkJob;
<add>use Pheanstalk\Pheanstalk;
<ide> use Illuminate\Queue\Jobs\BeanstalkdJob;
<ide>
<ide> class BeanstalkdQueue extends Queue implements QueueInterface {
<ide> public function pop($queue = null)
<ide>
<ide> $job = $this->pheanstalk->watchOnly($queue)->reserve(0);
<ide>
<del> if ($job instanceof Pheanstalk_Job)
<add> if ($job instanceof PheanstalkJob)
<ide> {
<ide> return new BeanstalkdJob($this->container, $this->pheanstalk, $job, $queue);
<ide> }
<ide><path>src/Illuminate/Queue/Connectors/BeanstalkdConnector.php
<ide> <?php namespace Illuminate\Queue\Connectors;
<ide>
<ide> use Illuminate\Queue\BeanstalkdQueue;
<del>use Pheanstalk\Pheanstalk as Pheanstalk;
<add>use Pheanstalk\Pheanstalk;
<ide>
<ide> class BeanstalkdConnector implements ConnectorInterface {
<ide> | 2 |
Python | Python | add missing imports | fb514fcecddf73ecc20a4796abcc711699508182 | <ide><path>numpy/distutils/conv_template.py
<ide> import sys
<ide> import re
<ide>
<add>from numpy.compat import contextlib_nullcontext
<ide> from numpy.distutils.compat import get_exception
<ide>
<ide> # names for replacement that are already global.
<ide><path>numpy/distutils/from_template.py
<ide> import sys
<ide> import re
<ide>
<add>from numpy.compat import contextlib_nullcontext
<add>
<ide> routine_start_re = re.compile(r'(\n|\A)(( (\$|\*))|)\s*(subroutine|function)\b', re.I)
<ide> routine_end_re = re.compile(r'\n\s*end\s*(subroutine|function)\b.*(\n|\Z)', re.I)
<ide> function_start_re = re.compile(r'\n (\$|\*)\s*function\b', re.I) | 2 |
Javascript | Javascript | fix a test using an undefined context | f73264d685fda7e9b9d9d17bc7d39f9477ed225c | <ide><path>packages/ember-htmlbars/lib/helpers/each.js
<ide> import { get } from "ember-metal/property_get";
<ide> import { forEach } from "ember-metal/enumerable_utils";
<add>import normalizeSelf from "ember-htmlbars/utils/normalize-self";
<ide>
<ide> export default function eachHelper(params, hash, blocks) {
<ide> var list = params[0];
<ide> export default function eachHelper(params, hash, blocks) {
<ide> var self;
<ide> if (blocks.template.arity === 0) {
<ide> Ember.deprecate(deprecation);
<del> self = item;
<add> self = normalizeSelf(item);
<ide> }
<ide>
<ide> var key = keyPath ? get(item, keyPath) : String(i);
<ide><path>packages/ember-htmlbars/lib/helpers/with.js
<ide> @submodule ember-htmlbars
<ide> */
<ide>
<add>import normalizeSelf from "ember-htmlbars/utils/normalize-self";
<add>
<ide> /**
<ide> Use the `{{with}}` helper when you want to aliases the to a new name. It's helpful
<ide> for semantic clarity and to retain default scope or to reference from another
<ide> export default function withHelper(params, hash, options) {
<ide> if (preserveContext) {
<ide> this.yield([params[0]]);
<ide> } else {
<del> this.yield([], params[0]);
<add> this.yield([], normalizeSelf(params[0]));
<ide> }
<ide> }
<ide><path>packages/ember-htmlbars/lib/utils/normalize-self.js
<add>export default function normalizeSelf(self) {
<add> if (self === undefined) {
<add> return null;
<add> } else {
<add> return self;
<add> }
<add>}
<ide><path>packages/ember-htmlbars/tests/compat/make_bound_helper_test.js
<ide> QUnit.test("shouldn't treat quoted strings as bound paths", function() {
<ide> equal(helperCount, 5, "changing controller property with same name as quoted string doesn't re-render helper");
<ide> });
<ide>
<del>QUnit.skip("bound helpers can handle nulls in array (with primitives) [DEPRECATED]", function() {
<add>QUnit.test("bound helpers can handle nulls in array (with primitives) [DEPRECATED]", function() {
<ide> expectDeprecationInHTMLBars();
<ide>
<ide> // The problem here is that `undefined` is treated as "use the parent scope" in yieldItem | 4 |
Python | Python | add backend info in saved models | e1a283e9d1aa327a25719003c99dbd282943bfe8 | <ide><path>keras/engine/topology.py
<ide> def _updated_config(self):
<ide> model_config = {
<ide> 'class_name': self.__class__.__name__,
<ide> 'config': config,
<del> 'keras_version': keras_version
<add> 'keras_version': keras_version,
<add> 'backend': K.backend()
<ide> }
<ide> return model_config
<ide>
<ide> def _collect_input_shape(input_tensors):
<ide>
<ide>
<ide> def save_weights_to_hdf5_group(f, layers):
<add> from . import __version__ as keras_version
<add>
<ide> f.attrs['layer_names'] = [layer.name.encode('utf8') for layer in layers]
<add> f.attrs['backend'] = K.backend().encode('utf8')
<add> f.attrs['keras_version'] = str(keras_version).encode('utf8')
<ide>
<ide> for layer in layers:
<ide> g = f.create_group(layer.name)
<ide><path>keras/models.py
<ide> def get_json_type(obj):
<ide>
<ide> f = h5py.File(filepath, 'w')
<ide> f.attrs['keras_version'] = str(keras_version).encode('utf8')
<add> f.attrs['backend'] = K.backend().encode('utf8')
<ide> f.attrs['model_config'] = json.dumps({
<ide> 'class_name': model.__class__.__name__,
<ide> 'config': model.get_config() | 2 |
Java | Java | allow recursive use of @componentscan | d0c31ad84cffd7af718a45d679483a1c51f9e552 | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/CircularComponentScanException.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation;
<add>
<add>/**
<add> * Exception thrown upon detection of circular {@link ComponentScan} use.
<add> *
<add> * @author Chris Beams
<add> * @since 3.1
<add> */
<add>@SuppressWarnings("serial")
<add>class CircularComponentScanException extends IllegalStateException {
<add>
<add> public CircularComponentScanException(String message, Exception cause) {
<add> super(message, cause);
<add> }
<add>
<add>}
<ide>\ No newline at end of file
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ClassPathBeanDefinitionScanner.java
<ide> protected void registerBeanDefinition(BeanDefinitionHolder definitionHolder, Bea
<ide> * @return <code>true</code> if the bean can be registered as-is;
<ide> * <code>false</code> if it should be skipped because there is an
<ide> * existing, compatible bean definition for the specified name
<del> * @throws IllegalStateException if an existing, incompatible
<add> * @throws ConflictingBeanDefinitionException if an existing, incompatible
<ide> * bean definition has been found for the specified name
<ide> */
<ide> protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
<ide> protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition)
<ide> if (isCompatible(beanDefinition, existingDef)) {
<ide> return false;
<ide> }
<del> throw new IllegalStateException("Annotation-specified bean name '" + beanName +
<add> throw new ConflictingBeanDefinitionException("Annotation-specified bean name '" + beanName +
<ide> "' for bean class [" + beanDefinition.getBeanClassName() + "] conflicts with existing, " +
<ide> "non-compatible bean definition of same name and class [" + existingDef.getBeanClassName() + "]");
<ide> }
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ComponentScanAnnotationParser.java
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Set;
<ide>
<ide> import org.springframework.beans.BeanUtils;
<add>import org.springframework.beans.factory.config.BeanDefinitionHolder;
<ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry;
<ide> import org.springframework.beans.factory.support.BeanNameGenerator;
<ide> import org.springframework.context.annotation.ComponentScan.Filter;
<ide> import org.springframework.core.env.Environment;
<ide> import org.springframework.core.io.ResourceLoader;
<del>import org.springframework.core.type.AnnotationMetadata;
<ide> import org.springframework.core.type.filter.AnnotationTypeFilter;
<ide> import org.springframework.core.type.filter.AssignableTypeFilter;
<ide> import org.springframework.core.type.filter.TypeFilter;
<ide> public ComponentScanAnnotationParser(ResourceLoader resourceLoader, Environment
<ide> this.registry = registry;
<ide> }
<ide>
<del> public void parse(AnnotationMetadata annotationMetadata) {
<del> Map<String, Object> attribs = annotationMetadata.getAnnotationAttributes(ComponentScan.class.getName());
<del> if (attribs == null) {
<del> // @ComponentScan annotation is not present -> do nothing
<del> return;
<del> }
<del>
<add> public Set<BeanDefinitionHolder> parse(Map<String, Object> componentScanAttributes) {
<ide> ClassPathBeanDefinitionScanner scanner =
<del> new ClassPathBeanDefinitionScanner(registry, (Boolean)attribs.get("useDefaultFilters"));
<add> new ClassPathBeanDefinitionScanner(registry, (Boolean)componentScanAttributes.get("useDefaultFilters"));
<ide>
<ide> Assert.notNull(this.environment, "Environment must not be null");
<ide> scanner.setEnvironment(this.environment);
<ide> public void parse(AnnotationMetadata annotationMetadata) {
<ide> scanner.setResourceLoader(this.resourceLoader);
<ide>
<ide> scanner.setBeanNameGenerator(BeanUtils.instantiateClass(
<del> (Class<?>)attribs.get("nameGenerator"), BeanNameGenerator.class));
<add> (Class<?>)componentScanAttributes.get("nameGenerator"), BeanNameGenerator.class));
<ide>
<del> ScopedProxyMode scopedProxyMode = (ScopedProxyMode) attribs.get("scopedProxy");
<add> ScopedProxyMode scopedProxyMode = (ScopedProxyMode) componentScanAttributes.get("scopedProxy");
<ide> if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
<ide> scanner.setScopedProxyMode(scopedProxyMode);
<ide> } else {
<ide> scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(
<del> (Class<?>)attribs.get("scopeResolver"), ScopeMetadataResolver.class));
<add> (Class<?>)componentScanAttributes.get("scopeResolver"), ScopeMetadataResolver.class));
<ide> }
<ide>
<del> scanner.setResourcePattern((String)attribs.get("resourcePattern"));
<add> scanner.setResourcePattern((String)componentScanAttributes.get("resourcePattern"));
<ide>
<del> for (Filter filter : (Filter[])attribs.get("includeFilters")) {
<add> for (Filter filter : (Filter[])componentScanAttributes.get("includeFilters")) {
<ide> scanner.addIncludeFilter(createTypeFilter(filter));
<ide> }
<del> for (Filter filter : (Filter[])attribs.get("excludeFilters")) {
<add> for (Filter filter : (Filter[])componentScanAttributes.get("excludeFilters")) {
<ide> scanner.addExcludeFilter(createTypeFilter(filter));
<ide> }
<ide>
<ide> List<String> basePackages = new ArrayList<String>();
<del> for (String pkg : (String[])attribs.get("value")) {
<add> for (String pkg : (String[])componentScanAttributes.get("value")) {
<ide> if (StringUtils.hasText(pkg)) {
<ide> basePackages.add(pkg);
<ide> }
<ide> }
<del> for (String pkg : (String[])attribs.get("basePackages")) {
<add> for (String pkg : (String[])componentScanAttributes.get("basePackages")) {
<ide> if (StringUtils.hasText(pkg)) {
<ide> basePackages.add(pkg);
<ide> }
<ide> }
<del> for (Class<?> clazz : (Class<?>[])attribs.get("basePackageClasses")) {
<add> for (Class<?> clazz : (Class<?>[])componentScanAttributes.get("basePackageClasses")) {
<ide> // TODO: loading user types directly here. implications on load-time
<ide> // weaving may mean we need to revert to stringified class names in
<ide> // annotation metadata
<ide> public void parse(AnnotationMetadata annotationMetadata) {
<ide> throw new IllegalStateException("At least one base package must be specified");
<ide> }
<ide>
<del> scanner.scan(basePackages.toArray(new String[]{}));
<add> return scanner.doScan(basePackages.toArray(new String[]{}));
<ide> }
<ide>
<ide> private TypeFilter createTypeFilter(Filter filter) {
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> import org.apache.commons.logging.LogFactory;
<del>import org.springframework.beans.BeanUtils;
<ide> import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
<ide> import org.springframework.beans.factory.annotation.Autowire;
<ide> import org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor;
<ide> import org.springframework.beans.factory.support.BeanDefinitionRegistry;
<ide> import org.springframework.beans.factory.support.GenericBeanDefinition;
<ide> import org.springframework.beans.factory.support.RootBeanDefinition;
<del>import org.springframework.context.EnvironmentAware;
<del>import org.springframework.context.ResourceLoaderAware;
<del>import org.springframework.core.Conventions;
<del>import org.springframework.core.env.Environment;
<ide> import org.springframework.core.io.Resource;
<ide> import org.springframework.core.io.ResourceLoader;
<ide> import org.springframework.core.type.AnnotationMetadata;
<ide> import org.springframework.core.type.MethodMetadata;
<del>import org.springframework.core.type.StandardAnnotationMetadata;
<ide> import org.springframework.core.type.classreading.MetadataReader;
<ide> import org.springframework.core.type.classreading.MetadataReaderFactory;
<del>import org.springframework.core.type.classreading.SimpleMetadataReaderFactory;
<del>import org.springframework.stereotype.Component;
<ide> import org.springframework.util.StringUtils;
<ide>
<ide> /**
<ide> */
<ide> public class ConfigurationClassBeanDefinitionReader {
<ide>
<del> private static final String CONFIGURATION_CLASS_FULL = "full";
<del>
<del> private static final String CONFIGURATION_CLASS_LITE = "lite";
<del>
<del> private static final String CONFIGURATION_CLASS_ATTRIBUTE =
<del> Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
<del>
<ide> private static final Log logger = LogFactory.getLog(ConfigurationClassBeanDefinitionReader.class);
<del>
<add>
<ide> private final BeanDefinitionRegistry registry;
<ide>
<ide> private final SourceExtractor sourceExtractor;
<ide> public class ConfigurationClassBeanDefinitionReader {
<ide>
<ide> private ResourceLoader resourceLoader;
<ide>
<del> private Environment environment;
<del>
<del> private final ComponentScanAnnotationParser componentScanParser;
<del>
<ide> /**
<ide> * Create a new {@link ConfigurationClassBeanDefinitionReader} instance that will be used
<ide> * to populate the given {@link BeanDefinitionRegistry}.
<ide> * @param problemReporter
<ide> * @param metadataReaderFactory
<ide> */
<del> public ConfigurationClassBeanDefinitionReader(final BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
<add> public ConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry, SourceExtractor sourceExtractor,
<ide> ProblemReporter problemReporter, MetadataReaderFactory metadataReaderFactory,
<del> ResourceLoader resourceLoader, Environment environment) {
<add> ResourceLoader resourceLoader) {
<ide>
<ide> this.registry = registry;
<ide> this.sourceExtractor = sourceExtractor;
<ide> this.problemReporter = problemReporter;
<ide> this.metadataReaderFactory = metadataReaderFactory;
<ide> this.resourceLoader = resourceLoader;
<del> this.environment = environment;
<del>
<del> this.componentScanParser = new ComponentScanAnnotationParser(resourceLoader, environment, registry);
<ide> }
<ide>
<ide>
<ide> public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
<ide> * class itself, all its {@link Bean} methods
<ide> */
<ide> private void loadBeanDefinitionsForConfigurationClass(ConfigurationClass configClass) {
<del> AnnotationMetadata metadata = configClass.getMetadata();
<del> componentScanParser.parse(metadata);
<ide> doLoadBeanDefinitionForConfigurationClassIfNecessary(configClass);
<ide> for (BeanMethod beanMethod : configClass.getBeanMethods()) {
<ide> loadBeanDefinitionsForBeanMethod(beanMethod);
<ide> private void doLoadBeanDefinitionForConfigurationClassIfNecessary(ConfigurationC
<ide> BeanDefinition configBeanDef = new GenericBeanDefinition();
<ide> String className = configClass.getMetadata().getClassName();
<ide> configBeanDef.setBeanClassName(className);
<del> if (checkConfigurationClassCandidate(configBeanDef, this.metadataReaderFactory)) {
<add> if (ConfigurationClassUtils.checkConfigurationClassCandidate(configBeanDef, this.metadataReaderFactory)) {
<ide> String configBeanName = BeanDefinitionReaderUtils.registerWithGeneratedName((AbstractBeanDefinition)configBeanDef, this.registry);
<ide> configClass.setBeanName(configBeanName);
<ide> if (logger.isDebugEnabled()) {
<ide> private void loadBeanDefinitionsFromImportedResources(Map<String, Class<?>> impo
<ide> }
<ide>
<ide>
<del> /**
<del> * Check whether the given bean definition is a candidate for a configuration class,
<del> * and mark it accordingly.
<del> * @param beanDef the bean definition to check
<del> * @param metadataReaderFactory the current factory in use by the caller
<del> * @return whether the candidate qualifies as (any kind of) configuration class
<del> */
<del> public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
<del> AnnotationMetadata metadata = null;
<del>
<del> // Check already loaded Class if present...
<del> // since we possibly can't even load the class file for this Class.
<del> if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
<del> metadata = new StandardAnnotationMetadata(((AbstractBeanDefinition) beanDef).getBeanClass());
<del> }
<del> else {
<del> String className = beanDef.getBeanClassName();
<del> if (className != null) {
<del> try {
<del> MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
<del> metadata = metadataReader.getAnnotationMetadata();
<del> }
<del> catch (IOException ex) {
<del> if (logger.isDebugEnabled()) {
<del> logger.debug("Could not find class file for introspecting factory methods: " + className, ex);
<del> }
<del> return false;
<del> }
<del> }
<del> }
<del>
<del> if (metadata != null) {
<del> if (metadata.isAnnotated(Configuration.class.getName())) {
<del> beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
<del> return true;
<del> }
<del> else if (metadata.isAnnotated(Component.class.getName()) ||
<del> metadata.hasAnnotatedMethods(Bean.class.getName())) {
<del> beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
<del> return true;
<del> }
<del> }
<del> return false;
<del> }
<del>
<del> /**
<del> * Determine whether the given bean definition indicates a full @Configuration class.
<del> */
<del> public static boolean isFullConfigurationClass(BeanDefinition beanDef) {
<del> return CONFIGURATION_CLASS_FULL.equals(beanDef.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE));
<del> }
<del>
<del>
<ide> /**
<ide> * {@link RootBeanDefinition} marker subclass used to signify that a bean definition
<ide> * was created from a configuration class as opposed to any other configuration source.
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassParser.java
<ide> import java.util.Stack;
<ide>
<ide> import org.springframework.beans.BeanUtils;
<add>import org.springframework.beans.factory.config.BeanDefinitionHolder;
<ide> import org.springframework.beans.factory.parsing.Location;
<ide> import org.springframework.beans.factory.parsing.Problem;
<ide> import org.springframework.beans.factory.parsing.ProblemReporter;
<add>import org.springframework.beans.factory.support.BeanDefinitionRegistry;
<ide> import org.springframework.core.annotation.AnnotationUtils;
<ide> import org.springframework.core.env.Environment;
<add>import org.springframework.core.io.ResourceLoader;
<ide> import org.springframework.core.type.AnnotationMetadata;
<ide> import org.springframework.core.type.MethodMetadata;
<ide> import org.springframework.core.type.StandardAnnotationMetadata;
<ide> class ConfigurationClassParser {
<ide>
<ide> private final Environment environment;
<ide>
<add> private final ResourceLoader resourceLoader;
<add>
<add> private final ComponentScanAnnotationParser componentScanParser;
<add>
<ide>
<ide> /**
<ide> * Create a new {@link ConfigurationClassParser} instance that will be used
<ide> * to populate the set of configuration classes.
<ide> */
<ide> public ConfigurationClassParser(MetadataReaderFactory metadataReaderFactory,
<del> ProblemReporter problemReporter, Environment environment) {
<add> ProblemReporter problemReporter, Environment environment,
<add> ResourceLoader resourceLoader, BeanDefinitionRegistry registry) {
<ide> this.metadataReaderFactory = metadataReaderFactory;
<ide> this.problemReporter = problemReporter;
<ide> this.environment = environment;
<add> this.resourceLoader = resourceLoader;
<add>
<add> this.componentScanParser = new ComponentScanAnnotationParser(this.resourceLoader, this.environment, registry);
<ide> }
<ide>
<ide>
<ide> protected void processConfigurationClass(ConfigurationClass configClass) throws
<ide> }
<ide>
<ide> protected void doProcessConfigurationClass(ConfigurationClass configClass, AnnotationMetadata metadata) throws IOException {
<add> Map<String, Object> componentScanAttributes = metadata.getAnnotationAttributes(ComponentScan.class.getName());
<add> if (componentScanAttributes != null) {
<add> // the config class is annotated with @ComponentScan -> perform the scan immediately
<add> Set<BeanDefinitionHolder> scannedBeanDefinitions = this.componentScanParser.parse(componentScanAttributes);
<add>
<add> // check the set of scanned definitions for any further config classes and parse recursively if necessary
<add> for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
<add> if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), metadataReaderFactory)) {
<add> try {
<add> this.parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
<add> } catch (ConflictingBeanDefinitionException ex) {
<add> throw new CircularComponentScanException(
<add> "A conflicting bean definition was detected while processing @ComponentScan annotations. " +
<add> "This usually indicates a circle between scanned packages.", ex);
<add> }
<add> }
<add> }
<add> }
<add>
<ide> List<Map<String, Object>> allImportAttribs =
<ide> AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
<ide> for (Map<String, Object> importAttribs : allImportAttribs) {
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassPostProcessor.java
<ide> public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
<ide> */
<ide> private void processConfigurationClasses(BeanDefinitionRegistry registry) {
<ide> ConfigurationClassBeanDefinitionReader reader = getConfigurationClassBeanDefinitionReader(registry);
<del> ConfigurationClassParser parser = new ConfigurationClassParser(this.metadataReaderFactory, this.problemReporter, this.environment);
<add> ConfigurationClassParser parser = new ConfigurationClassParser(
<add> this.metadataReaderFactory, this.problemReporter, this.environment, this.resourceLoader, registry);
<ide> processConfigBeanDefinitions(parser, reader, registry);
<ide> enhanceConfigurationClasses((ConfigurableListableBeanFactory)registry);
<ide> }
<ide>
<ide> private ConfigurationClassBeanDefinitionReader getConfigurationClassBeanDefinitionReader(BeanDefinitionRegistry registry) {
<ide> if (this.reader == null) {
<ide> this.reader = new ConfigurationClassBeanDefinitionReader(
<del> registry, this.sourceExtractor, this.problemReporter, this.metadataReaderFactory, this.resourceLoader, this.environment);
<add> registry, this.sourceExtractor, this.problemReporter, this.metadataReaderFactory, this.resourceLoader);
<ide> }
<ide> return this.reader;
<ide> }
<ide> public void processConfigBeanDefinitions(ConfigurationClassParser parser, Config
<ide> Set<BeanDefinitionHolder> configCandidates = new LinkedHashSet<BeanDefinitionHolder>();
<ide> for (String beanName : registry.getBeanDefinitionNames()) {
<ide> BeanDefinition beanDef = registry.getBeanDefinition(beanName);
<del> if (ConfigurationClassBeanDefinitionReader.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
<add> if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
<ide> configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
<ide> }
<ide> }
<ide> public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFact
<ide> Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<String, AbstractBeanDefinition>();
<ide> for (String beanName : beanFactory.getBeanDefinitionNames()) {
<ide> BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
<del> if (ConfigurationClassBeanDefinitionReader.isFullConfigurationClass(beanDef)) {
<add> if (ConfigurationClassUtils.isFullConfigurationClass(beanDef)) {
<ide> if (!(beanDef instanceof AbstractBeanDefinition)) {
<ide> throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
<ide> beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassUtils.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation;
<add>
<add>import java.io.IOException;
<add>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>import org.springframework.beans.factory.config.BeanDefinition;
<add>import org.springframework.beans.factory.support.AbstractBeanDefinition;
<add>import org.springframework.core.Conventions;
<add>import org.springframework.core.type.AnnotationMetadata;
<add>import org.springframework.core.type.StandardAnnotationMetadata;
<add>import org.springframework.core.type.classreading.MetadataReader;
<add>import org.springframework.core.type.classreading.MetadataReaderFactory;
<add>import org.springframework.stereotype.Component;
<add>
<add>/**
<add> * Utilities for processing @{@link Configuration} classes.
<add> *
<add> * @author Chris Beams
<add> * @since 3.1
<add> */
<add>abstract class ConfigurationClassUtils {
<add>
<add> private static final Log logger = LogFactory.getLog(ConfigurationClassUtils.class);
<add>
<add> private static final String CONFIGURATION_CLASS_FULL = "full";
<add>
<add> private static final String CONFIGURATION_CLASS_LITE = "lite";
<add>
<add> private static final String CONFIGURATION_CLASS_ATTRIBUTE =
<add> Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
<add>
<add>
<add> /**
<add> * Check whether the given bean definition is a candidate for a configuration class,
<add> * and mark it accordingly.
<add> * @param beanDef the bean definition to check
<add> * @param metadataReaderFactory the current factory in use by the caller
<add> * @return whether the candidate qualifies as (any kind of) configuration class
<add> */
<add> public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
<add> AnnotationMetadata metadata = null;
<add>
<add> // Check already loaded Class if present...
<add> // since we possibly can't even load the class file for this Class.
<add> if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
<add> metadata = new StandardAnnotationMetadata(((AbstractBeanDefinition) beanDef).getBeanClass());
<add> }
<add> else {
<add> String className = beanDef.getBeanClassName();
<add> if (className != null) {
<add> try {
<add> MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
<add> metadata = metadataReader.getAnnotationMetadata();
<add> }
<add> catch (IOException ex) {
<add> if (logger.isDebugEnabled()) {
<add> logger.debug("Could not find class file for introspecting factory methods: " + className, ex);
<add> }
<add> return false;
<add> }
<add> }
<add> }
<add>
<add> if (metadata != null) {
<add> if (metadata.isAnnotated(Configuration.class.getName())) {
<add> beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
<add> return true;
<add> }
<add> else if (metadata.isAnnotated(Component.class.getName()) ||
<add> metadata.hasAnnotatedMethods(Bean.class.getName())) {
<add> beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
<add> return true;
<add> }
<add> }
<add> return false;
<add> }
<add>
<add> /**
<add> * Determine whether the given bean definition indicates a full @Configuration class.
<add> */
<add> public static boolean isFullConfigurationClass(BeanDefinition beanDef) {
<add> return CONFIGURATION_CLASS_FULL.equals(beanDef.getAttribute(CONFIGURATION_CLASS_ATTRIBUTE));
<add> }
<add>
<add>}
<ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConflictingBeanDefinitionException.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation;
<add>
<add>/**
<add> * Marker subclass of {@link IllegalStateException}, allowing for explicit
<add> * catch clauses in calling code.
<add> *
<add> * @author Chris Beams
<add> * @since 3.1
<add> */
<add>@SuppressWarnings("serial")
<add>class ConflictingBeanDefinitionException extends IllegalStateException {
<add>
<add> public ConflictingBeanDefinitionException(String message) {
<add> super(message);
<add> }
<add>
<add>}
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/AsmCircularImportDetectionTests.java
<ide> package org.springframework.context.annotation;
<ide>
<ide> import org.springframework.beans.factory.parsing.FailFastProblemReporter;
<add>import org.springframework.beans.factory.support.DefaultListableBeanFactory;
<ide> import org.springframework.core.env.DefaultEnvironment;
<add>import org.springframework.core.io.DefaultResourceLoader;
<ide> import org.springframework.core.type.classreading.CachingMetadataReaderFactory;
<ide>
<ide> /**
<ide> public class AsmCircularImportDetectionTests extends AbstractCircularImportDetec
<ide>
<ide> @Override
<ide> protected ConfigurationClassParser newParser() {
<del> return new ConfigurationClassParser(new CachingMetadataReaderFactory(), new FailFastProblemReporter(), new DefaultEnvironment());
<add> return new ConfigurationClassParser(
<add> new CachingMetadataReaderFactory(),
<add> new FailFastProblemReporter(),
<add> new DefaultEnvironment(),
<add> new DefaultResourceLoader(),
<add> new DefaultListableBeanFactory());
<ide> }
<ide>
<ide> @Override
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/ComponentScanAnnotationRecursionTests.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation;
<add>
<add>import static org.hamcrest.CoreMatchers.sameInstance;
<add>import static org.junit.Assert.assertThat;
<add>
<add>import org.junit.Test;
<add>import org.springframework.context.annotation.componentscan.cycle.left.LeftConfig;
<add>import org.springframework.context.annotation.componentscan.level1.Level1Config;
<add>import org.springframework.context.annotation.componentscan.level2.Level2Config;
<add>import org.springframework.context.annotation.componentscan.level3.Level3Component;
<add>
<add>/**
<add> * Tests ensuring that configuration clasess marked with @ComponentScan
<add> * may be processed recursively
<add> *
<add> * @author Chris Beams
<add> * @since 3.1
<add> */
<add>public class ComponentScanAnnotationRecursionTests {
<add>
<add> @Test
<add> public void recursion() {
<add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
<add> ctx.register(Level1Config.class);
<add> ctx.refresh();
<add>
<add> // assert that all levels have been detected
<add> ctx.getBean(Level1Config.class);
<add> ctx.getBean(Level2Config.class);
<add> ctx.getBean(Level3Component.class);
<add>
<add> // assert that enhancement is working
<add> assertThat(ctx.getBean("level1Bean"), sameInstance(ctx.getBean("level1Bean")));
<add> assertThat(ctx.getBean("level2Bean"), sameInstance(ctx.getBean("level2Bean")));
<add> }
<add>
<add> @Test(expected=CircularComponentScanException.class)
<add> public void cycleDetection() {
<add> AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
<add> ctx.register(LeftConfig.class);
<add> ctx.refresh();
<add> }
<add>
<add>}
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/cycle/left/LeftConfig.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation.componentscan.cycle.left;
<add>
<add>import org.springframework.context.annotation.ComponentScan;
<add>import org.springframework.context.annotation.Configuration;
<add>
<add>@Configuration
<add>@ComponentScan("org.springframework.context.annotation.componentscan.cycle.right")
<add>public class LeftConfig {
<add>
<add>}
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/cycle/right/RightConfig.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation.componentscan.cycle.right;
<add>
<add>import org.springframework.context.annotation.ComponentScan;
<add>import org.springframework.context.annotation.Configuration;
<add>
<add>@Configuration
<add>@ComponentScan("org.springframework.context.annotation.componentscan.cycle.left")
<add>public class RightConfig {
<add>
<add>}
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/level1/Level1Config.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation.componentscan.level1;
<add>
<add>import org.springframework.beans.TestBean;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.ComponentScan;
<add>import org.springframework.context.annotation.Configuration;
<add>
<add>@Configuration
<add>@ComponentScan("org.springframework.context.annotation.componentscan.level2")
<add>public class Level1Config {
<add> @Bean
<add> public TestBean level1Bean() {
<add> return new TestBean("level1Bean");
<add> }
<add>}
<ide>\ No newline at end of file
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/level2/Level2Config.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation.componentscan.level2;
<add>
<add>import org.springframework.beans.TestBean;
<add>import org.springframework.context.annotation.Bean;
<add>import org.springframework.context.annotation.ComponentScan;
<add>import org.springframework.context.annotation.Configuration;
<add>
<add>@Configuration
<add>@ComponentScan("org.springframework.context.annotation.componentscan.level3")
<add>public class Level2Config {
<add> @Bean
<add> public TestBean level2Bean() {
<add> return new TestBean("level2Bean");
<add> }
<add>}
<ide><path>org.springframework.context/src/test/java/org/springframework/context/annotation/componentscan/level3/Level3Component.java
<add>/*
<add> * Copyright 2002-2011 the original author or authors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License");
<add> * you may not use this file except in compliance with the License.
<add> * You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software
<add> * distributed under the License is distributed on an "AS IS" BASIS,
<add> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add> * See the License for the specific language governing permissions and
<add> * limitations under the License.
<add> */
<add>
<add>package org.springframework.context.annotation.componentscan.level3;
<add>
<add>import org.springframework.stereotype.Component;
<add>
<add>@Component
<add>public class Level3Component {
<add>
<add>} | 15 |
Ruby | Ruby | use rack namespace for routing args | c20c72e3d9321f8c00587aab479d962e80b02c35 | <ide><path>actionpack/lib/action_controller/request.rb
<ide> def parameters
<ide> end
<ide>
<ide> def path_parameters=(parameters) #:nodoc:
<del> @env["routing_args"] = parameters
<add> @env["rack.routing_args"] = parameters
<ide> @symbolized_path_parameters = @parameters = nil
<ide> end
<ide>
<ide> def symbolized_path_parameters
<ide> #
<ide> # See <tt>symbolized_path_parameters</tt> for symbolized keys.
<ide> def path_parameters
<del> @env["routing_args"] ||= {}
<add> @env["rack.routing_args"] ||= {}
<ide> end
<ide>
<ide> def body | 1 |
Java | Java | use urldecoder for query params in webflux | 645e3492dba42ec14553fca642344cafba571ed0 | <ide><path>spring-web/src/main/java/org/springframework/http/server/reactive/AbstractServerHttpRequest.java
<ide>
<ide> package org.springframework.http.server.reactive;
<ide>
<add>import java.io.UnsupportedEncodingException;
<ide> import java.net.URI;
<del>import java.nio.charset.StandardCharsets;
<add>import java.net.URLDecoder;
<ide> import java.util.regex.Matcher;
<ide> import java.util.regex.Pattern;
<ide>
<add>import org.apache.commons.logging.Log;
<add>import org.apache.commons.logging.LogFactory;
<add>
<ide> import org.springframework.http.HttpCookie;
<ide> import org.springframework.http.HttpHeaders;
<ide> import org.springframework.http.server.RequestPath;
<ide> */
<ide> public abstract class AbstractServerHttpRequest implements ServerHttpRequest {
<ide>
<add> private static final Log logger = LogFactory.getLog(ServerHttpRequest.class);
<add>
<ide> private static final Pattern QUERY_PATTERN = Pattern.compile("([^&=]+)(=?)([^&]+)?");
<ide>
<ide>
<ide> protected MultiValueMap<String, String> initQueryParams() {
<ide> return queryParams;
<ide> }
<ide>
<add> @SuppressWarnings("deprecation")
<ide> private String decodeQueryParam(String value) {
<del> return StringUtils.uriDecode(value, StandardCharsets.UTF_8);
<add> try {
<add> return URLDecoder.decode(value, "UTF-8");
<add> }
<add> catch (UnsupportedEncodingException ex) {
<add> if (logger.isWarnEnabled()) {
<add> logger.warn("Could not decode query param [" + value + "] as 'UTF-8'. " +
<add> "Falling back on default encoding; exception message: " + ex.getMessage());
<add> }
<add> return URLDecoder.decode(value);
<add> }
<ide> }
<ide>
<ide> @Override
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestTests.java
<ide> /*
<del> * Copyright 2002-2016 the original author or authors.
<add> * Copyright 2002-2017 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void queryParamsWithMulitpleValues() throws Exception {
<ide> public void queryParamsWithEncodedValue() throws Exception {
<ide> MultiValueMap<String, String> params = createHttpRequest("/path?a=%20%2B+%C3%A0").getQueryParams();
<ide> assertEquals(1, params.size());
<del> assertEquals(Collections.singletonList(" ++\u00e0"), params.get("a"));
<add> assertEquals(Collections.singletonList(" + \u00e0"), params.get("a"));
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingIntegrationTests.java
<ide> public void handleWithParam() throws Exception {
<ide>
<ide> @Test // SPR-15140
<ide> public void handleWithEncodedParam() throws Exception {
<del> String expected = "Hello ++\u00e0!";
<add> String expected = "Hello + \u00e0!";
<ide> assertEquals(expected, performGet("/param?name=%20%2B+%C3%A0", new HttpHeaders(), String.class).getBody());
<ide> }
<ide> | 3 |
PHP | PHP | fix tests for changes in previous commit | 71464917c3846672b6f6e15dfd6181981a06f336 | <ide><path>tests/TestCase/ORM/TableTest.php
<ide> public function testAddBehaviorMissing() {
<ide> public function testCallBehaviorMethod() {
<ide> $table = TableRegistry::get('article');
<ide> $table->addBehavior('Sluggable');
<del> $this->assertEquals('some_value', $table->slugify('some value'));
<add> $this->assertEquals('some-value', $table->slugify('some value'));
<ide> }
<ide>
<ide> /**
<ide> public function testCallBehaviorMethod() {
<ide> public function testCallBehaviorAliasedMethod() {
<ide> $table = TableRegistry::get('article');
<ide> $table->addBehavior('Sluggable', ['implementedMethods' => ['wednesday' => 'slugify']]);
<del> $this->assertEquals('some_value', $table->wednesday('some value'));
<add> $this->assertEquals('some-value', $table->wednesday('some value'));
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | use memcached api instead of memcache | f316553bb7a692dde72a4a3ba08c6bfc6de00283 | <ide><path>laravel/cache/drivers/memcached.php
<del><?php namespace Laravel\Cache\Drivers; use Memcache;
<add><?php namespace Laravel\Cache\Drivers; use Memcached;
<ide>
<ide> class Memcached extends Driver {
<ide>
<ide> /**
<ide> * The Memcache instance.
<ide> *
<del> * @var Memcache
<add> * @var Memcached
<ide> */
<ide> protected $memcache;
<ide>
<ide> class Memcached extends Driver {
<ide> /**
<ide> * Create a new Memcached cache driver instance.
<ide> *
<del> * @param Memcache $memcache
<add> * @param Memcached $memcache
<ide> * @return void
<ide> */
<del> public function __construct(Memcache $memcache, $key)
<add> public function __construct(Memcached $memcache, $key)
<ide> {
<ide> $this->key = $key;
<ide> $this->memcache = $memcache;
<ide><path>laravel/memcached.php
<ide> public static function connection()
<ide> /**
<ide> * Create a new Memcached connection instance.
<ide> *
<del> * @param array $servers
<add> * @param array $servers
<ide> * @return Memcached
<ide> */
<ide> protected static function connect($servers)
<ide> {
<del> $memcache = new \Memcache;
<add> $memcache = new \Memcached;
<ide>
<ide> foreach ($servers as $server)
<ide> { | 2 |
Text | Text | clarify incomingmessage.destroy() description | c8930fb9bf647b88bba9b6e7be4f4ea119fb3d57 | <ide><path>doc/api/http.md
<ide> added: v0.3.0
<ide> * `error` {Error}
<ide>
<ide> Calls `destroy()` on the socket that received the `IncomingMessage`. If `error`
<del>is provided, an `'error'` event is emitted and `error` is passed as an argument
<del>to any listeners on the event.
<add>is provided, an `'error'` event is emitted on the socket and `error` is passed
<add>as an argument to any listeners on the event.
<ide>
<ide> ### message.headers
<ide> <!-- YAML | 1 |
Go | Go | fix root detection | d263aa6ca916ba9141f341447a2387e7a6316717 | <ide><path>utils.go
<ide> func RootIsShared() bool {
<ide> if data, err := ioutil.ReadFile("/proc/self/mountinfo"); err == nil {
<ide> for _, line := range strings.Split(string(data), "\n") {
<ide> cols := strings.Split(line, " ")
<del> if len(cols) >= 6 && cols[3] == "/" && cols[4] == "/" {
<add> if len(cols) >= 6 && cols[4] == "/" {
<ide> return strings.HasPrefix(cols[6], "shared")
<ide> }
<ide> } | 1 |
Text | Text | revise collaborator guide on reverting | cf43846e25c67c9f36152d0643faf181df247527 | <ide><path>COLLABORATOR_GUIDE.md
<ide> after-the-fact.
<ide>
<ide> ##### Reverting commits
<ide>
<del>Commits are reverted with `git revert <HASH>`, or `git revert <FROM>..<TO>` for
<del>multiple commits. Commit metadata and the reason for the revert should be
<del>appended. Commit message rules about line length and subsystem can be ignored.
<del>A Pull Request should be raised and approved like any other change.
<add>Revert commits with `git revert <HASH>` or `git revert <FROM>..<TO>`. The
<add>generated commit message will not have a subsystem and may violate line length
<add>rules. That is OK. Append the reason for the revert and any `Refs` or `Fixes`
<add>metadata. Raise a Pull Request like any other change.
<ide>
<ide> ### Introducing New Modules
<ide> | 1 |
Javascript | Javascript | add prettier for examples directory | 9c4eefcdbf4058b65c8b88fe98387166acad127b | <ide><path>examples/active-class-name/components/Link.js
<ide> const ActiveLink = ({ router, children, ...props }) => {
<ide>
<ide> let className = child.props.className || null
<ide> if (router.pathname === props.href && props.activeClassName) {
<del> className = `${className !== null ? className : ''} ${props.activeClassName}`.trim()
<add> className = `${className !== null ? className : ''} ${
<add> props.activeClassName
<add> }`.trim()
<ide> }
<ide>
<ide> delete props.activeClassName
<ide><path>examples/analyze-bundles/pages/about.js
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/analyze-bundles/pages/contact.js
<del>export default () => (
<del> <div>
<del> This is the contact page.
<del> </div>
<del>)
<add>export default () => <div>This is the contact page.</div>
<ide><path>examples/analyze-bundles/pages/index.js
<ide> export default class Index extends React.Component {
<ide> <h1>Home Page</h1>
<ide> <p>Welcome, {name}</p>
<ide> <div>
<del> <Link href='/about'><a>About Page</a></Link>
<add> <Link href='/about'>
<add> <a>About Page</a>
<add> </Link>
<ide> </div>
<ide> </div>
<ide> )
<ide><path>examples/basic-export/pages/about.js
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/basic-export/pages/about2.js
<del>export default () => (
<del> <div>About 2</div>
<del>)
<add>export default () => <div>About 2</div>
<ide><path>examples/basic-export/pages/day/index.js
<del>export default () => (
<del> <div>Hello Day</div>
<del>)
<add>export default () => <div>Hello Day</div>
<ide><path>examples/basic-export/pages/index.js
<ide> import Link from 'next/link'
<ide> export default () => (
<del> <div>Hello World. <Link href='/about'><a>About</a></Link></div>
<add> <div>
<add> Hello World.{' '}
<add> <Link href='/about'>
<add> <a>About</a>
<add> </Link>
<add> </div>
<ide> )
<ide><path>examples/custom-charset/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> res.setHeader('Content-Type', 'text/html; charset=iso-8859-2')
<del> handle(req, res, parsedUrl)
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> res.setHeader('Content-Type', 'text/html; charset=iso-8859-2')
<add> handle(req, res, parsedUrl)
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/custom-server-actionhero/actions/render.js
<ide> 'use strict'
<del>const {Action, api} = require('actionhero')
<add>const { Action, api } = require('actionhero')
<ide>
<ide> module.exports = class CreateChatRoom extends Action {
<ide> constructor () {
<ide><path>examples/custom-server-actionhero/config/api.js
<ide> const path = require('path')
<ide>
<ide> exports['default'] = {
<del> general: (api) => {
<add> general: api => {
<ide> const packageJSON = require(api.projectRoot + path.sep + 'package.json')
<ide>
<ide> return {
<ide> exports['default'] = {
<ide> cliIncludeInternal: true,
<ide> // configuration for your actionhero project structure
<ide> paths: {
<del> 'action': [path.join(__dirname, '/../actions')],
<del> 'task': [path.join(__dirname, '/../tasks')],
<del> 'public': [path.join(__dirname, '/../static')],
<del> 'pid': [path.join(__dirname, '/../pids')],
<del> 'log': [path.join(__dirname, '/../log')],
<del> 'server': [path.join(__dirname, '/../servers')],
<del> 'cli': [path.join(__dirname, '/../bin')],
<del> 'initializer': [path.join(__dirname, '/../initializers')],
<del> 'plugin': [path.join(__dirname, '/../node_modules')],
<del> 'locale': [path.join(__dirname, '/../locales')]
<add> action: [path.join(__dirname, '/../actions')],
<add> task: [path.join(__dirname, '/../tasks')],
<add> public: [path.join(__dirname, '/../static')],
<add> pid: [path.join(__dirname, '/../pids')],
<add> log: [path.join(__dirname, '/../log')],
<add> server: [path.join(__dirname, '/../servers')],
<add> cli: [path.join(__dirname, '/../bin')],
<add> initializer: [path.join(__dirname, '/../initializers')],
<add> plugin: [path.join(__dirname, '/../node_modules')],
<add> locale: [path.join(__dirname, '/../locales')]
<ide> },
<ide> // hash containing chat rooms you wish to be created at server boot
<ide> startingChatRooms: {
<ide> exports['default'] = {
<ide> }
<ide>
<ide> exports.test = {
<del> general: (api) => {
<add> general: api => {
<ide> return {
<ide> id: 'test-server-' + process.pid,
<ide> serverToken: 'serverToken-' + process.pid,
<ide> developmentMode: true,
<ide> startingChatRooms: {
<del> 'defaultRoom': {},
<del> 'otherRoom': {}
<add> defaultRoom: {},
<add> otherRoom: {}
<ide> },
<ide> paths: {
<del> 'locale': [
<add> locale: [
<ide> // require('os').tmpdir() + require('path').sep + 'locales',
<ide> path.join(__dirname, '/../locales')
<ide> ]
<ide> exports.test = {
<ide> }
<ide>
<ide> exports.production = {
<del> general: (api) => {
<add> general: api => {
<ide> return {
<ide> fileRequestLogLevel: 'debug',
<ide> developmentMode: false
<ide><path>examples/custom-server-actionhero/config/errors.js
<ide>
<ide> // error messages can be strings of objects
<ide> exports['default'] = {
<del> errors: (api) => {
<add> errors: api => {
<ide> return {
<del> '_toExpand': false,
<add> _toExpand: false,
<ide>
<ide> // ///////////////
<ide> // SERIALIZERS //
<ide> // ///////////////
<ide>
<ide> serializers: {
<ide> servers: {
<del> web: (error) => {
<add> web: error => {
<ide> if (error.message) {
<ide> return String(error.message)
<ide> } else {
<ide> return error
<ide> }
<ide> },
<del> websocket: (error) => {
<add> websocket: error => {
<ide> if (error.message) {
<ide> return String(error.message)
<ide> } else {
<ide> return error
<ide> }
<ide> },
<del> socket: (error) => {
<add> socket: error => {
<ide> if (error.message) {
<ide> return String(error.message)
<ide> } else {
<ide> return error
<ide> }
<ide> },
<del> specHelper: (error) => {
<add> specHelper: error => {
<ide> if (error.message) {
<ide> return 'Error: ' + String(error.message)
<ide> } else {
<ide> exports['default'] = {
<ide>
<ide> // When a params for an action is invalid
<ide> invalidParams: (data, validationErrors) => {
<del> if (validationErrors.length >= 0) { return validationErrors[0] }
<add> if (validationErrors.length >= 0) {
<add> return validationErrors[0]
<add> }
<ide> return data.connection.localize('actionhero.errors.invalidParams')
<ide> },
<ide>
<ide> // When a required param for an action is not provided
<ide> missingParams: (data, missingParams) => {
<del> return data.connection.localize(['actionhero.errors.missingParams', {param: missingParams[0]}])
<add> return data.connection.localize([
<add> 'actionhero.errors.missingParams',
<add> { param: missingParams[0] }
<add> ])
<ide> },
<ide>
<ide> // user requested an unknown action
<del> unknownAction: (data) => {
<add> unknownAction: data => {
<ide> return data.connection.localize('actionhero.errors.unknownAction')
<ide> },
<ide>
<ide> // action not useable by this client/server type
<del> unsupportedServerType: (data) => {
<del> return data.connection.localize(['actionhero.errors.unsupportedServerType', {type: data.connection.type}])
<add> unsupportedServerType: data => {
<add> return data.connection.localize([
<add> 'actionhero.errors.unsupportedServerType',
<add> { type: data.connection.type }
<add> ])
<ide> },
<ide>
<ide> // action failed because server is mid-shutdown
<del> serverShuttingDown: (data) => {
<add> serverShuttingDown: data => {
<ide> return data.connection.localize('actionhero.errors.serverShuttingDown')
<ide> },
<ide>
<ide> // action failed because this client already has too many pending acitons
<ide> // limit defined in api.config.general.simultaneousActions
<del> tooManyPendingActions: (data) => {
<del> return data.connection.localize('actionhero.errors.tooManyPendingActions')
<add> tooManyPendingActions: data => {
<add> return data.connection.localize(
<add> 'actionhero.errors.tooManyPendingActions'
<add> )
<ide> },
<ide>
<ide> dataLengthTooLarge: (maxLength, receivedLength) => {
<del> return api.i18n.localize(['actionhero.errors.dataLengthTooLarge', {maxLength: maxLength, receivedLength: receivedLength}])
<add> return api.i18n.localize([
<add> 'actionhero.errors.dataLengthTooLarge',
<add> { maxLength: maxLength, receivedLength: receivedLength }
<add> ])
<ide> },
<ide>
<ide> // ///////////////
<ide> exports['default'] = {
<ide>
<ide> // The body message to accompany 404 (file not found) errors regarding flat files
<ide> // You may want to load in the contnet of 404.html or similar
<del> fileNotFound: (connection) => {
<add> fileNotFound: connection => {
<ide> return connection.localize(['actionhero.errors.fileNotFound'])
<ide> },
<ide>
<ide> // user didn't request a file
<del> fileNotProvided: (connection) => {
<add> fileNotProvided: connection => {
<ide> return connection.localize('actionhero.errors.fileNotProvided')
<ide> },
<ide>
<ide> // something went wrong trying to read the file
<ide> fileReadError: (connection, error) => {
<del> return connection.localize(['actionhero.errors.fileReadError', {error: String(error)}])
<add> return connection.localize([
<add> 'actionhero.errors.fileReadError',
<add> { error: String(error) }
<add> ])
<ide> },
<ide>
<ide> // ///////////////
<ide> // CONNECTIONS //
<ide> // ///////////////
<ide>
<ide> verbNotFound: (connection, verb) => {
<del> return connection.localize(['actionhero.errors.verbNotFound', {verb: verb}])
<add> return connection.localize([
<add> 'actionhero.errors.verbNotFound',
<add> { verb: verb }
<add> ])
<ide> },
<ide>
<ide> verbNotAllowed: (connection, verb) => {
<del> return connection.localize(['actionhero.errors.verbNotAllowed', {verb: verb}])
<add> return connection.localize([
<add> 'actionhero.errors.verbNotAllowed',
<add> { verb: verb }
<add> ])
<ide> },
<ide>
<del> connectionRoomAndMessage: (connection) => {
<add> connectionRoomAndMessage: connection => {
<ide> return connection.localize('actionhero.errors.connectionRoomAndMessage')
<ide> },
<ide>
<ide> connectionNotInRoom: (connection, room) => {
<del> return connection.localize(['actionhero.errors.connectionNotInRoom', {room: room}])
<add> return connection.localize([
<add> 'actionhero.errors.connectionNotInRoom',
<add> { room: room }
<add> ])
<ide> },
<ide>
<ide> connectionAlreadyInRoom: (connection, room) => {
<del> return connection.localize(['actionhero.errors.connectionAlreadyInRoom', {room: room}])
<add> return connection.localize([
<add> 'actionhero.errors.connectionAlreadyInRoom',
<add> { room: room }
<add> ])
<ide> },
<ide>
<del> connectionRoomHasBeenDeleted: (room) => {
<del> return api.i18n.localize('actionhero.errors.connectionRoomHasBeenDeleted')
<add> connectionRoomHasBeenDeleted: room => {
<add> return api.i18n.localize(
<add> 'actionhero.errors.connectionRoomHasBeenDeleted'
<add> )
<ide> },
<ide>
<del> connectionRoomNotExist: (room) => {
<add> connectionRoomNotExist: room => {
<ide> return api.i18n.localize('actionhero.errors.connectionRoomNotExist')
<ide> },
<ide>
<del> connectionRoomExists: (room) => {
<add> connectionRoomExists: room => {
<ide> return api.i18n.localize('actionhero.errors.connectionRoomExists')
<ide> },
<ide>
<del> connectionRoomRequired: (room) => {
<add> connectionRoomRequired: room => {
<ide> return api.i18n.localize('actionhero.errors.connectionRoomRequired')
<ide> }
<del>
<ide> }
<ide> }
<ide> }
<ide><path>examples/custom-server-actionhero/config/i18n.js
<ide> exports['default'] = {
<del> i18n: (api) => {
<add> i18n: api => {
<ide> return {
<ide> // visit https://github.com/mashpie/i18n-node to see all configuration options
<ide> // locale path can be configired from within ./config/api.js
<ide> exports['default'] = {
<ide> }
<ide>
<ide> exports.test = {
<del> i18n: (api) => {
<add> i18n: api => {
<ide> return {
<ide> updateFiles: true
<ide> }
<ide><path>examples/custom-server-actionhero/config/logger.js
<ide> const fs = require('fs')
<ide> const cluster = require('cluster')
<ide>
<ide> exports['default'] = {
<del> logger: (api) => {
<del> let logger = {transports: []}
<add> logger: api => {
<add> let logger = { transports: [] }
<ide>
<ide> // console logger
<ide> if (cluster.isMaster) {
<ide> logger.transports.push(function (api, winston) {
<del> return new (winston.transports.Console)({
<add> return new winston.transports.Console({
<ide> colorize: true,
<ide> level: 'info',
<del> timestamp: function () { return api.id + ' @ ' + new Date().toISOString() }
<add> timestamp: function () {
<add> return api.id + ' @ ' + new Date().toISOString()
<add> }
<ide> })
<ide> })
<ide> }
<ide> exports['default'] = {
<ide> fs.mkdirSync(logDirectory)
<ide> } catch (e) {
<ide> if (e.code !== 'EEXIST') {
<del> throw (new Error('Cannot create log directory @ ' + logDirectory))
<add> throw new Error('Cannot create log directory @ ' + logDirectory)
<ide> }
<ide> }
<ide> }
<ide>
<del> return new (winston.transports.File)({
<del> filename: api.config.general.paths.log[0] + '/' + api.pids.title + '.log',
<add> return new winston.transports.File({
<add> filename:
<add> api.config.general.paths.log[0] + '/' + api.pids.title + '.log',
<ide> level: 'info',
<del> timestamp: function () { return api.id + ' @ ' + new Date().toISOString() }
<add> timestamp: function () {
<add> return api.id + ' @ ' + new Date().toISOString()
<add> }
<ide> })
<ide> })
<ide>
<ide> exports['default'] = {
<ide> }
<ide>
<ide> exports.test = {
<del> logger: (api) => {
<add> logger: api => {
<ide> return {
<ide> transports: null
<ide> }
<ide><path>examples/custom-server-actionhero/config/plugins.js
<ide> exports['default'] = {
<del> plugins: (api) => {
<add> plugins: api => {
<ide> /*
<ide> If you want to use plugins in your application, include them here:
<ide>
<ide><path>examples/custom-server-actionhero/config/redis.js
<ide> if (process.env.REDIS_URL) {
<ide> }
<ide>
<ide> exports['default'] = {
<del> redis: (api) => {
<add> redis: api => {
<ide> // konstructor: The redis client constructor method. All redis methods must be promises
<ide> // args: The arguments to pass to the constructor
<ide> // buildNew: is it `new konstructor()` or just `konstructor()`?
<ide>
<ide> function retryStrategy (times) {
<ide> if (times === 1) {
<del> const error = 'Unable to connect to Redis - please check your Redis config!'
<del> if (process.env.NODE_ENV === 'test') { console.error(error) } else { api.log(error, 'error') }
<add> const error =
<add> 'Unable to connect to Redis - please check your Redis config!'
<add> if (process.env.NODE_ENV === 'test') {
<add> console.error(error)
<add> } else {
<add> api.log(error, 'error')
<add> }
<ide> return 5000
<ide> }
<ide> return Math.min(times * 50, maxBackoff)
<ide> exports['default'] = {
<ide> return {
<ide> enabled: true,
<ide>
<del> '_toExpand': false,
<add> _toExpand: false,
<ide> client: {
<ide> konstructor: require('ioredis'),
<del> args: [{ port: port, host: host, password: password, db: db, retryStrategy: retryStrategy }],
<add> args: [
<add> {
<add> port: port,
<add> host: host,
<add> password: password,
<add> db: db,
<add> retryStrategy: retryStrategy
<add> }
<add> ],
<ide> buildNew: true
<ide> },
<ide> subscriber: {
<ide> konstructor: require('ioredis'),
<del> args: [{ port: port, host: host, password: password, db: db, retryStrategy: retryStrategy }],
<add> args: [
<add> {
<add> port: port,
<add> host: host,
<add> password: password,
<add> db: db,
<add> retryStrategy: retryStrategy
<add> }
<add> ],
<ide> buildNew: true
<ide> },
<ide> tasks: {
<ide> konstructor: require('ioredis'),
<del> args: [{ port: port, host: host, password: password, db: db, retryStrategy: retryStrategy }],
<add> args: [
<add> {
<add> port: port,
<add> host: host,
<add> password: password,
<add> db: db,
<add> retryStrategy: retryStrategy
<add> }
<add> ],
<ide> buildNew: true
<ide> }
<ide> }
<ide><path>examples/custom-server-actionhero/config/routes.js
<ide> exports['default'] = {
<del> routes: (api) => {
<add> routes: api => {
<ide> return {
<del> get: [
<del> { path: '/', matchTrailingPathParts: true, action: 'render' }
<del> ]
<add> get: [{ path: '/', matchTrailingPathParts: true, action: 'render' }]
<ide> }
<ide> }
<ide> }
<ide><path>examples/custom-server-actionhero/config/servers/socket.js
<ide>
<ide> exports['default'] = {
<ide> servers: {
<del> socket: (api) => {
<add> socket: api => {
<ide> return {
<del> enabled: (process.env.ENABLE_TCP_SERVER !== undefined),
<add> enabled: process.env.ENABLE_TCP_SERVER !== undefined,
<ide> // TCP or TLS?
<ide> secure: false,
<ide> // Passed to tls.createServer if secure=true. Should contain SSL certificates
<ide> exports['default'] = {
<ide>
<ide> exports.test = {
<ide> servers: {
<del> socket: (api) => {
<add> socket: api => {
<ide> return {
<ide> enabled: true,
<ide> port: 1001 + (process.pid % 64535),
<ide><path>examples/custom-server-actionhero/config/servers/web.js
<ide> const os = require('os')
<ide>
<ide> exports['default'] = {
<ide> servers: {
<del> web: (api) => {
<add> web: api => {
<ide> return {
<ide> enabled: true,
<ide> // HTTP or HTTPS?
<ide> exports['default'] = {
<ide> serverOptions: {},
<ide> // Should we redirect all traffic to the first host in this array if hte request header doesn't match?
<ide> // i.e.: [ 'https://www.site.com' ]
<del> allowedRequestHosts: process.env.ALLOWED_HOSTS ? process.env.ALLOWED_HOSTS.split(',') : [],
<add> allowedRequestHosts: process.env.ALLOWED_HOSTS
<add> ? process.env.ALLOWED_HOSTS.split(',')
<add> : [],
<ide> // Port or Socket Path
<ide> port: process.env.PORT || 8080,
<ide> // Which IP to listen on (use '0.0.0.0' for all; '::' for all on ipv4 and ipv6)
<ide> exports['default'] = {
<ide> httpHeaders: {
<ide> 'X-Powered-By': api.config.general.serverName,
<ide> 'Access-Control-Allow-Origin': '*',
<del> 'Access-Control-Allow-Methods': 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE',
<add> 'Access-Control-Allow-Methods':
<add> 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS, TRACE',
<ide> 'Access-Control-Allow-Headers': 'Content-Type'
<ide> },
<ide> // Route that actions will be served from; secondary route against this route will be treated as actions,
<ide> exports['default'] = {
<ide>
<ide> exports.production = {
<ide> servers: {
<del> web: (api) => {
<add> web: api => {
<ide> return {
<ide> padding: null,
<ide> metadataOptions: {
<ide> exports.production = {
<ide>
<ide> exports.test = {
<ide> servers: {
<del> web: (api) => {
<add> web: api => {
<ide> return {
<ide> secure: false,
<ide> port: process.env.PORT || 1000 + (process.pid % 64535),
<ide><path>examples/custom-server-actionhero/config/servers/websocket.js
<ide>
<ide> exports['default'] = {
<ide> servers: {
<del> websocket: (api) => {
<add> websocket: api => {
<ide> return {
<ide> enabled: true,
<ide> // you can pass a FQDN (string) here or 'window.location.origin'
<ide> exports['default'] = {
<ide>
<ide> exports['test'] = {
<ide> servers: {
<del> websocket: (api) => {
<add> websocket: api => {
<ide> return { clientUrl: null }
<ide> }
<ide> }
<ide><path>examples/custom-server-actionhero/config/tasks.js
<ide> exports['default'] = {
<del> tasks: (api) => {
<add> tasks: api => {
<ide> return {
<ide> // Should this node run a scheduler to promote delayed tasks?
<ide> scheduler: false,
<ide> exports['default'] = {
<ide> }
<ide>
<ide> exports.test = {
<del> tasks: (api) => {
<add> tasks: api => {
<ide> return {
<ide> timeout: 100,
<ide> checkTimeout: 50
<ide><path>examples/custom-server-actionhero/initializers/next.js
<ide> 'use strict'
<del>const {Initializer, api} = require('actionhero')
<add>const { Initializer, api } = require('actionhero')
<ide> const next = require('next')
<ide>
<ide> module.exports = class NextInitializer extends Initializer {
<ide> module.exports = class NextInitializer extends Initializer {
<ide>
<ide> async initialize () {
<ide> api.next = {
<del> render: async (connection) => {
<del> if (connection.type !== 'web') { throw new Error('Connections for NEXT apps must be of type "web"') }
<add> render: async connection => {
<add> if (connection.type !== 'web') {
<add> throw new Error('Connections for NEXT apps must be of type "web"')
<add> }
<ide> const req = connection.rawConnection.req
<ide> const res = connection.rawConnection.res
<ide> return api.next.handle(req, res)
<ide> }
<ide> }
<ide>
<del> api.next.dev = (api.env === 'development')
<del> if (api.next.dev) { api.log('Running next in development mode...') }
<add> api.next.dev = api.env === 'development'
<add> if (api.next.dev) {
<add> api.log('Running next in development mode...')
<add> }
<ide>
<del> api.next.app = next({dev: api.next.dev})
<add> api.next.app = next({ dev: api.next.dev })
<ide> api.next.handle = api.next.app.getRequestHandler()
<ide> await api.next.app.prepare()
<ide> }
<ide><path>examples/custom-server-actionhero/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server-express/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<ide> <li>
<del> <Link
<del> href={{pathname: '/posts', query: { id: '2' }}}
<del> as='/posts/2'
<del> >
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href={{ pathname: '/posts', query: { id: '2' } }} as='/posts/2'>
<ide> <a>post #2</a>
<ide> </Link>
<ide> </li>
<ide><path>examples/custom-server-express/pages/posts.js
<ide> export default class extends Component {
<ide> }
<ide>
<ide> render () {
<del> return <div>
<del> <h1>My blog post #{this.props.postId}</h1>
<del> <p>
<del> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
<del> tempor incididunt ut labore et dolore magna aliqua.
<del> </p>
<del> </div>
<add> return (
<add> <div>
<add> <h1>My blog post #{this.props.postId}</h1>
<add> <p>
<add> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
<add> eiusmod tempor incididunt ut labore et dolore magna aliqua.
<add> </p>
<add> </div>
<add> )
<ide> }
<ide> }
<ide><path>examples/custom-server-express/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> const server = express()
<add>app.prepare().then(() => {
<add> const server = express()
<ide>
<del> server.get('/a', (req, res) => {
<del> return app.render(req, res, '/b', req.query)
<del> })
<add> server.get('/a', (req, res) => {
<add> return app.render(req, res, '/b', req.query)
<add> })
<ide>
<del> server.get('/b', (req, res) => {
<del> return app.render(req, res, '/a', req.query)
<del> })
<add> server.get('/b', (req, res) => {
<add> return app.render(req, res, '/a', req.query)
<add> })
<ide>
<del> server.get('/posts/:id', (req, res) => {
<del> return app.render(req, res, '/posts', { id: req.params.id })
<del> })
<add> server.get('/posts/:id', (req, res) => {
<add> return app.render(req, res, '/posts', { id: req.params.id })
<add> })
<ide>
<del> server.get('*', (req, res) => {
<del> return handle(req, res)
<del> })
<add> server.get('*', (req, res) => {
<add> return handle(req, res)
<add> })
<ide>
<del> server.listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> server.listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/custom-server-fastify/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server-fastify/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide>
<ide> fastify.register((fastify, opts, next) => {
<ide> const app = Next({ dev })
<del> app.prepare()
<add> app
<add> .prepare()
<ide> .then(() => {
<ide> if (dev) {
<ide> fastify.get('/_next/*', (req, reply) => {
<del> return app.handleRequest(req.req, reply.res)
<del> .then(() => {
<del> reply.sent = true
<del> })
<add> return app.handleRequest(req.req, reply.res).then(() => {
<add> reply.sent = true
<add> })
<ide> })
<ide> }
<ide>
<ide> fastify.get('/a', (req, reply) => {
<del> return app.render(req.req, reply.res, '/b', req.query)
<del> .then(() => {
<del> reply.sent = true
<del> })
<add> return app.render(req.req, reply.res, '/b', req.query).then(() => {
<add> reply.sent = true
<add> })
<ide> })
<ide>
<ide> fastify.get('/b', (req, reply) => {
<del> return app.render(req.req, reply.res, '/a', req.query)
<del> .then(() => {
<del> reply.sent = true
<del> })
<add> return app.render(req.req, reply.res, '/a', req.query).then(() => {
<add> reply.sent = true
<add> })
<ide> })
<ide>
<ide> fastify.get('/*', (req, reply) => {
<del> return app.handleRequest(req.req, reply.res)
<del> .then(() => {
<del> reply.sent = true
<del> })
<add> return app.handleRequest(req.req, reply.res).then(() => {
<add> reply.sent = true
<add> })
<ide> })
<ide>
<ide> fastify.setNotFoundHandler((request, reply) => {
<del> return app.render404(request.req, reply.res)
<del> .then(() => {
<del> reply.sent = true
<del> })
<add> return app.render404(request.req, reply.res).then(() => {
<add> reply.sent = true
<add> })
<ide> })
<ide>
<ide> next()
<ide> })
<del> .catch((err) => next(err))
<add> .catch(err => next(err))
<ide> })
<ide>
<del>fastify.listen(port, (err) => {
<add>fastify.listen(port, err => {
<ide> if (err) throw err
<ide> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<ide><path>examples/custom-server-hapi/next-wrapper.js
<ide> const defaultHandlerWrapper = app => async ({ raw: { req, res }, url }) => {
<ide> }
<ide>
<ide> const pathWrapper = (app, pathName, opts) => async ({ raw, query, params }) => {
<del> return app.renderToHTML(raw.req, raw.res, pathName, { ...query, ...params }, opts)
<add> return app.renderToHTML(
<add> raw.req,
<add> raw.res,
<add> pathName,
<add> { ...query, ...params },
<add> opts
<add> )
<ide> }
<ide>
<ide> module.exports = { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper }
<ide><path>examples/custom-server-hapi/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server-hapi/server.js
<ide> const next = require('next')
<ide> const Hapi = require('hapi')
<del>const { pathWrapper, defaultHandlerWrapper, nextHandlerWrapper } = require('./next-wrapper')
<add>const {
<add> pathWrapper,
<add> defaultHandlerWrapper,
<add> nextHandlerWrapper
<add>} = require('./next-wrapper')
<ide>
<ide> const port = parseInt(process.env.PORT, 10) || 3000
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const server = new Hapi.Server({
<ide> port
<ide> })
<ide>
<del>app
<del> .prepare()
<del> .then(async () => {
<del> server.route({
<del> method: 'GET',
<del> path: '/a',
<del> handler: pathWrapper(app, '/a')
<del> })
<del>
<del> server.route({
<del> method: 'GET',
<del> path: '/b',
<del> handler: pathWrapper(app, '/b')
<del> })
<add>app.prepare().then(async () => {
<add> server.route({
<add> method: 'GET',
<add> path: '/a',
<add> handler: pathWrapper(app, '/a')
<add> })
<ide>
<del> server.route({
<del> method: 'GET',
<del> path: '/_next/{p*}', /* next specific routes */
<del> handler: nextHandlerWrapper(app)
<del> })
<add> server.route({
<add> method: 'GET',
<add> path: '/b',
<add> handler: pathWrapper(app, '/b')
<add> })
<ide>
<del> server.route({
<del> method: 'GET',
<del> path: '/{p*}', /* catch all route */
<del> handler: defaultHandlerWrapper(app)
<del> })
<add> server.route({
<add> method: 'GET',
<add> path: '/_next/{p*}' /* next specific routes */,
<add> handler: nextHandlerWrapper(app)
<add> })
<ide>
<del> try {
<del> await server.start()
<del> console.log(`> Ready on http://localhost:${port}`)
<del> } catch (error) {
<del> console.log('Error starting server')
<del> console.log(error)
<del> }
<add> server.route({
<add> method: 'GET',
<add> path: '/{p*}' /* catch all route */,
<add> handler: defaultHandlerWrapper(app)
<ide> })
<add>
<add> try {
<add> await server.start()
<add> console.log(`> Ready on http://localhost:${port}`)
<add> } catch (error) {
<add> console.log('Error starting server')
<add> console.log(error)
<add> }
<add>})
<ide><path>examples/custom-server-koa/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server-koa/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> const server = new Koa()
<del> const router = new Router()
<add>app.prepare().then(() => {
<add> const server = new Koa()
<add> const router = new Router()
<ide>
<del> router.get('/a', async ctx => {
<del> await app.render(ctx.req, ctx.res, '/b', ctx.query)
<del> ctx.respond = false
<del> })
<add> router.get('/a', async ctx => {
<add> await app.render(ctx.req, ctx.res, '/b', ctx.query)
<add> ctx.respond = false
<add> })
<ide>
<del> router.get('/b', async ctx => {
<del> await app.render(ctx.req, ctx.res, '/a', ctx.query)
<del> ctx.respond = false
<del> })
<add> router.get('/b', async ctx => {
<add> await app.render(ctx.req, ctx.res, '/a', ctx.query)
<add> ctx.respond = false
<add> })
<ide>
<del> router.get('*', async ctx => {
<del> await handle(ctx.req, ctx.res)
<del> ctx.respond = false
<del> })
<add> router.get('*', async ctx => {
<add> await handle(ctx.req, ctx.res)
<add> ctx.respond = false
<add> })
<ide>
<del> server.use(async (ctx, next) => {
<del> ctx.res.statusCode = 200
<del> await next()
<del> })
<add> server.use(async (ctx, next) => {
<add> ctx.res.statusCode = 200
<add> await next()
<add> })
<ide>
<del> server.use(router.routes())
<del> server.listen(port, () => {
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> server.use(router.routes())
<add> server.listen(port, () => {
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/custom-server-micro/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server-nodemon/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server-nodemon/server/index.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> const { pathname, query } = parsedUrl
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> const { pathname, query } = parsedUrl
<ide>
<del> if (pathname === '/a') {
<del> app.render(req, res, '/b', query)
<del> } else if (pathname === '/b') {
<del> app.render(req, res, '/a', query)
<del> } else {
<del> handle(req, res, parsedUrl)
<del> }
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> if (pathname === '/a') {
<add> app.render(req, res, '/b', query)
<add> } else if (pathname === '/b') {
<add> app.render(req, res, '/a', query)
<add> } else {
<add> handle(req, res, parsedUrl)
<add> }
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/custom-server/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/b' as='/a'><a>a</a></Link></li>
<del> <li><Link href='/a' as='/b'><a>b</a></Link></li>
<add> <li>
<add> <Link href='/b' as='/a'>
<add> <a>a</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/a' as='/b'>
<add> <a>b</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/custom-server/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> const { pathname, query } = parsedUrl
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> const { pathname, query } = parsedUrl
<ide>
<del> if (pathname === '/a') {
<del> app.render(req, res, '/b', query)
<del> } else if (pathname === '/b') {
<del> app.render(req, res, '/a', query)
<del> } else {
<del> handle(req, res, parsedUrl)
<del> }
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> if (pathname === '/a') {
<add> app.render(req, res, '/b', query)
<add> } else if (pathname === '/b') {
<add> app.render(req, res, '/a', query)
<add> } else {
<add> handle(req, res, parsedUrl)
<add> }
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/data-fetch/pages/index.js
<ide> export default class Index extends React.Component {
<ide> return (
<ide> <div>
<ide> <p>Next.js has {this.props.stars} ⭐️</p>
<del> <Link prefetch href='/preact'><a>How about preact?</a></Link>
<add> <Link prefetch href='/preact'>
<add> <a>How about preact?</a>
<add> </Link>
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/data-fetch/pages/preact.js
<ide> export default class Preact extends React.Component {
<ide> return (
<ide> <div>
<ide> <p>Preact has {this.props.stars} ⭐️</p>
<del> <Link prefetch href='/'><a>I bet next has more stars (?)</a></Link>
<add> <Link prefetch href='/'>
<add> <a>I bet next has more stars (?)</a>
<add> </Link>
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/form-handler/actions/formActionsCreators.js
<ide> import { INPUT_VALUE } from '../constants'
<ide>
<ide> export const inputChange = (title, name, val) => dispatch => {
<del> return dispatch({type: INPUT_VALUE, title, name, val})
<add> return dispatch({ type: INPUT_VALUE, title, name, val })
<ide> }
<ide><path>examples/form-handler/components/DisplayForm.js
<del>import React, {Component} from 'react'
<add>import React, { Component } from 'react'
<ide> import { Col, Row } from 'react-bootstrap'
<ide> import { connect } from 'react-redux'
<ide>
<ide> class DisplayForm extends Component {
<ide> <div>
<ide> <Row>
<ide> <Col lg={8} lgOffset={2}>
<del> <pre>{JSON.stringify(state, null, 2) }</pre>
<add> <pre>{JSON.stringify(state, null, 2)}</pre>
<ide> </Col>
<ide> </Row>
<ide> </div>
<ide><path>examples/form-handler/components/Header.js
<ide> const Header = () => {
<ide> <Row style={{ marginTop: '10px' }}>
<ide> <Col lg={8} lgOffset={2}>
<ide> <Jumbotron style={{ borderRadius: '15px' }}>
<del> <h1 style={{textAlign: 'center'}}>Form Handler</h1>
<add> <h1 style={{ textAlign: 'center' }}>Form Handler</h1>
<ide> </Jumbotron>
<ide> </Col>
<ide> </Row>
<ide><path>examples/form-handler/components/UserForm.js
<ide> const UserForm = () => {
<ide> <Input controlLabel='Email' type='email' title='user' name='email' />
<ide> </Col>
<ide> <Col lg={8} lgOffset={4}>
<del> <Input controlLabel='Password' type='password' title='user' name='password' />
<add> <Input
<add> controlLabel='Password'
<add> type='password'
<add> title='user'
<add> name='password'
<add> />
<ide> </Col>
<ide> </Row>
<ide> </div>
<ide><path>examples/form-handler/components/index.js
<del>import React, {Component} from 'react'
<add>import React, { Component } from 'react'
<ide> import Head from 'next/head'
<ide> import { Col, Row } from 'react-bootstrap'
<ide>
<ide> class Main extends Component {
<ide> <div>
<ide> <Head>
<ide> <title>Form Handler</title>
<del> <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css' />
<add> <link
<add> rel='stylesheet'
<add> href='https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css'
<add> />
<ide> </Head>
<ide> <Header />
<ide> <DisplayForm />
<ide><path>examples/form-handler/handlers/Input.js
<del>import React, {Component} from 'react'
<add>import React, { Component } from 'react'
<ide> import { FormGroup, ControlLabel, FormControl } from 'react-bootstrap'
<ide> import { connect } from 'react-redux'
<ide> import { bindActionCreators } from 'redux'
<ide>
<ide> import { inputChange } from '../actions'
<ide>
<ide> class Input extends Component {
<del> inputChange = (e) => {
<add> inputChange = e => {
<ide> const { inputChange, title, name } = this.props
<ide> inputChange(title, name, e.target.value)
<ide> }
<ide> const mapDispatchToProps = dispatch => {
<ide> }
<ide> }
<ide>
<del>export default connect(null, mapDispatchToProps)(Input)
<add>export default connect(
<add> null,
<add> mapDispatchToProps
<add>)(Input)
<ide><path>examples/form-handler/reducers/formReducer.js
<ide> import { INPUT_VALUE } from '../constants'
<ide> export default (state = {}, action) => {
<ide> switch (action.type) {
<ide> case INPUT_VALUE:
<del> return { ...state,
<del> [action.title]:
<del> { ...state[action.title],
<del> [action.name]: action.val
<del> }
<add> return {
<add> ...state,
<add> [action.title]: { ...state[action.title], [action.name]: action.val }
<ide> }
<ide> default:
<ide> return state
<ide><path>examples/form-handler/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<add>app
<add> .prepare()
<ide> .then(() => {
<ide> const server = express()
<ide>
<ide> app.prepare()
<ide> return handle(req, res)
<ide> })
<ide>
<del> server.listen(3000, (err) => {
<add> server.listen(3000, err => {
<ide> if (err) throw err
<ide> console.log('> Ready on http://localhost:3000')
<ide> })
<ide> })
<del> .catch((ex) => {
<add> .catch(ex => {
<ide> console.error(ex.stack)
<ide> process.exit(1)
<ide> })
<ide><path>examples/gh-pages/.babelrc.js
<ide> const env = require('./env-config')
<ide>
<ide> module.exports = {
<del> 'presets': [
<del> 'next/babel'
<del> ],
<del> 'plugins': [
<del> ['transform-define', env]
<del> ]
<add> presets: ['next/babel'],
<add> plugins: [['transform-define', env]]
<ide> }
<ide><path>examples/gh-pages/pages/about.js
<ide> import Link from 'next/link'
<ide> export default () => (
<ide> <div>
<ide> <div>About us</div>
<del> <div>Back to <Link href='/' as={process.env.BACKEND_URL + '/'}><a>Home</a></Link></div>
<add> <div>
<add> Back to{' '}
<add> <Link href='/' as={process.env.BACKEND_URL + '/'}>
<add> <a>Home</a>
<add> </Link>
<add> </div>
<ide> </div>
<ide> )
<ide><path>examples/gh-pages/pages/index.js
<ide> import Link from 'next/link'
<ide> export default () => (
<del> <div>Hello World. <Link href='/about' as={process.env.BACKEND_URL + '/about'}><a>About</a></Link></div>
<add> <div>
<add> Hello World.{' '}
<add> <Link href='/about' as={process.env.BACKEND_URL + '/about'}>
<add> <a>About</a>
<add> </Link>
<add> </div>
<ide> )
<ide><path>examples/hello-world/pages/about.js
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/hello-world/pages/day/index.js
<del>export default () => (
<del> <div>Hello Day</div>
<del>)
<add>export default () => <div>Hello Day</div>
<ide><path>examples/hello-world/pages/index.js
<ide> import Link from 'next/link'
<ide> export default () => (
<del> <div>Hello World. <Link href='/about'><a>About</a></Link></div>
<add> <div>
<add> Hello World.{' '}
<add> <Link href='/about'>
<add> <a>About</a>
<add> </Link>
<add> </div>
<ide> )
<ide><path>examples/layout-component/components/layout.js
<ide> import Head from 'next/head'
<ide> export default ({ children, title = 'This is the default title' }) => (
<ide> <div>
<ide> <Head>
<del> <title>{ title }</title>
<add> <title>{title}</title>
<ide> <meta charSet='utf-8' />
<ide> <meta name='viewport' content='initial-scale=1.0, width=device-width' />
<ide> </Head>
<ide> <header>
<ide> <nav>
<del> <Link href='/'><a>Home</a></Link> |
<del> <Link href='/about'><a>About</a></Link> |
<del> <Link href='/contact'><a>Contact</a></Link>
<add> <Link href='/'>
<add> <a>Home</a>
<add> </Link>{' '}
<add> |
<add> <Link href='/about'>
<add> <a>About</a>
<add> </Link>{' '}
<add> |
<add> <Link href='/contact'>
<add> <a>Contact</a>
<add> </Link>
<ide> </nav>
<ide> </header>
<ide>
<del> { children }
<add> {children}
<ide>
<del> <footer>
<del> {'I`m here to stay'}
<del> </footer>
<add> <footer>{'I`m here to stay'}</footer>
<ide> </div>
<ide> )
<ide><path>examples/nested-components/components/post.js
<ide> export default ({ title, children }) => (
<ide> <div className='main'>
<del> <h1>{ title }</h1>
<del> { children }
<add> <h1>{title}</h1>
<add> {children}
<ide> <style jsx>{`
<ide> .main {
<ide> font: 15px Helvetica, Arial;
<ide><path>examples/nested-components/pages/index.js
<ide> export default () => (
<ide> }
<ide>
<ide> hr::before {
<del> content: "***";
<add> content: '***';
<ide> color: #ccc;
<ide> }
<ide> `}</style>
<ide><path>examples/only-client-render-external-dependencies/components/BarChart.js
<ide> export default dynamic({
<ide> BarChart: import('recharts').then(({ BarChart }) => BarChart),
<ide> Bar: import('recharts').then(({ Bar }) => Bar)
<ide> }),
<del> render: (props, { BarChart, Bar }) =>
<add> render: (props, { BarChart, Bar }) => (
<ide> <BarChart width={props.width} height={props.height} data={props.data}>
<ide> <Bar dataKey='uv' fill='#8884d8' />
<ide> </BarChart>
<add> )
<ide> })
<ide><path>examples/only-client-render-external-dependencies/components/LineChart.js
<ide> export default dynamic({
<ide> LineChart: import('recharts').then(({ LineChart }) => LineChart),
<ide> Line: import('recharts').then(({ Line }) => Line)
<ide> }),
<del> render: (props, { LineChart, Line }) =>
<add> render: (props, { LineChart, Line }) => (
<ide> <LineChart width={props.width} height={props.height} data={props.data}>
<ide> <Line type='monotone' dataKey='uv' stroke='#8884d8' />
<ide> </LineChart>
<add> )
<ide> })
<ide><path>examples/only-client-render-external-dependencies/pages/chart.js
<ide> import React from 'react'
<ide> import BarChart from '../components/BarChart'
<ide>
<ide> const data = [
<del> {name: 'Page A', uv: 4000, pv: 2400, amt: 2400},
<del> {name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
<del> {name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
<del> {name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
<del> {name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
<del> {name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
<del> {name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
<add> { name: 'Page A', uv: 4000, pv: 2400, amt: 2400 },
<add> { name: 'Page B', uv: 3000, pv: 1398, amt: 2210 },
<add> { name: 'Page C', uv: 2000, pv: 9800, amt: 2290 },
<add> { name: 'Page D', uv: 2780, pv: 3908, amt: 2000 },
<add> { name: 'Page E', uv: 1890, pv: 4800, amt: 2181 },
<add> { name: 'Page F', uv: 2390, pv: 3800, amt: 2500 },
<add> { name: 'Page G', uv: 3490, pv: 4300, amt: 2100 }
<ide> ]
<ide>
<ide> const Chart = () => (
<ide><path>examples/only-client-render-external-dependencies/pages/index.js
<ide> import Link from 'next/link'
<ide> import LineChart from '../components/LineChart'
<ide>
<ide> const data = [
<del> {name: 'Page A', uv: 1000, pv: 2400, amt: 2400},
<del> {name: 'Page B', uv: 3000, pv: 1398, amt: 2210},
<del> {name: 'Page C', uv: 2000, pv: 9800, amt: 2290},
<del> {name: 'Page D', uv: 2780, pv: 3908, amt: 2000},
<del> {name: 'Page E', uv: 1890, pv: 4800, amt: 2181},
<del> {name: 'Page F', uv: 2390, pv: 3800, amt: 2500},
<del> {name: 'Page G', uv: 3490, pv: 4300, amt: 2100}
<add> { name: 'Page A', uv: 1000, pv: 2400, amt: 2400 },
<add> { name: 'Page B', uv: 3000, pv: 1398, amt: 2210 },
<add> { name: 'Page C', uv: 2000, pv: 9800, amt: 2290 },
<add> { name: 'Page D', uv: 2780, pv: 3908, amt: 2000 },
<add> { name: 'Page E', uv: 1890, pv: 4800, amt: 2181 },
<add> { name: 'Page F', uv: 2390, pv: 3800, amt: 2500 },
<add> { name: 'Page G', uv: 3490, pv: 4300, amt: 2100 }
<ide> ]
<ide>
<ide> const Index = () => (
<ide><path>examples/parameterized-routing/pages/blog.js
<ide> export default class extends React.Component {
<ide> }
<ide>
<ide> render () {
<del> return <div>
<del> <h1>My {this.props.id} blog post</h1>
<del> <p>
<del> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
<del> tempor incididunt ut labore et dolore magna aliqua.
<del> </p>
<del> </div>
<add> return (
<add> <div>
<add> <h1>My {this.props.id} blog post</h1>
<add> <p>
<add> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
<add> eiusmod tempor incididunt ut labore et dolore magna aliqua.
<add> </p>
<add> </div>
<add> )
<ide> }
<ide> }
<ide><path>examples/parameterized-routing/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/blog?id=first' as='/blog/first'><a>My first blog post</a></Link></li>
<del> <li><Link href='/blog?id=second' as='/blog/second'><a>My second blog post</a></Link></li>
<del> <li><Link href='/blog?id=last' as='/blog/last'><a>My last blog post</a></Link></li>
<add> <li>
<add> <Link href='/blog?id=first' as='/blog/first'>
<add> <a>My first blog post</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/blog?id=second' as='/blog/second'>
<add> <a>My second blog post</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/blog?id=last' as='/blog/last'>
<add> <a>My last blog post</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/parameterized-routing/server.js
<ide> const handle = app.getRequestHandler()
<ide> const route = pathMatch()
<ide> const match = route('/blog/:id')
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const { pathname, query } = parse(req.url, true)
<del> const params = match(pathname)
<del> if (params === false) {
<del> handle(req, res)
<del> return
<del> }
<del> // assigning `query` into the params means that we still
<del> // get the query string passed to our application
<del> // i.e. /blog/foo?show-comments=true
<del> app.render(req, res, '/blog', Object.assign(params, query))
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const { pathname, query } = parse(req.url, true)
<add> const params = match(pathname)
<add> if (params === false) {
<add> handle(req, res)
<add> return
<add> }
<add> // assigning `query` into the params means that we still
<add> // get the query string passed to our application
<add> // i.e. /blog/foo?show-comments=true
<add> app.render(req, res, '/blog', Object.assign(params, query))
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/pass-server-data/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/item'><a>View Item</a></Link></li>
<add> <li>
<add> <Link href='/item'>
<add> <a>View Item</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/pass-server-data/pages/item.js
<del>import {Component} from 'react'
<add>import { Component } from 'react'
<ide> import Link from 'next/link'
<ide> import fetch from 'isomorphic-unfetch'
<ide>
<ide> export default class extends Component {
<ide> return { item: query.itemData }
<ide> } else {
<ide> // On the client, we should fetch the data remotely
<del> const res = await fetch('/_data/item', {headers: {'Accept': 'application/json'}})
<add> const res = await fetch('/_data/item', {
<add> headers: { Accept: 'application/json' }
<add> })
<ide> const json = await res.json()
<ide> return { item: json }
<ide> }
<ide> export default class extends Component {
<ide> render () {
<ide> return (
<ide> <div className='item'>
<del> <div><Link href='/'><a>Back Home</a></Link></div>
<add> <div>
<add> <Link href='/'>
<add> <a>Back Home</a>
<add> </Link>
<add> </div>
<ide> <h1>{this.props.item.title}</h1>
<del> <h2>{this.props.item.subtitle} - {this.props.item.seller}</h2>
<add> <h2>
<add> {this.props.item.subtitle} - {this.props.item.seller}
<add> </h2>
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/pass-server-data/server.js
<ide> app.prepare().then(() => {
<ide> return handle(req, res)
<ide> })
<ide>
<del> server.listen(3000, (err) => {
<add> server.listen(3000, err => {
<ide> if (err) throw err
<ide> console.log('> Ready on http://localhost:3000')
<ide> })
<ide><path>examples/progressive-render/pages/index.js
<ide> import Loading from '../components/Loading'
<ide> export default () => (
<ide> <main>
<ide> <section>
<del> <h1>
<del> This section is server-side rendered.
<del> </h1>
<add> <h1>This section is server-side rendered.</h1>
<ide> </section>
<ide>
<ide> <NoSSR onSSR={<Loading />}>
<ide><path>examples/root-static-files/pages/index.js
<ide> export default () => (
<ide> <ul>
<del> <li><a href='/robots.txt'>/robots.txt</a></li>
<del> <li><a href='/sitemap.xml'>/sitemap.xml</a></li>
<del> <li><a href='/favicon.ico'>/favicon.ico</a></li>
<add> <li>
<add> <a href='/robots.txt'>/robots.txt</a>
<add> </li>
<add> <li>
<add> <a href='/sitemap.xml'>/sitemap.xml</a>
<add> </li>
<add> <li>
<add> <a href='/favicon.ico'>/favicon.ico</a>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/root-static-files/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> const rootStaticFiles = [
<del> '/robots.txt',
<del> '/sitemap.xml',
<del> '/favicon.ico'
<del> ]
<del> if (rootStaticFiles.indexOf(parsedUrl.pathname) > -1) {
<del> const path = join(__dirname, 'static', parsedUrl.pathname)
<del> app.serveStatic(req, res, path)
<del> } else {
<del> handle(req, res, parsedUrl)
<del> }
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> const rootStaticFiles = ['/robots.txt', '/sitemap.xml', '/favicon.ico']
<add> if (rootStaticFiles.indexOf(parsedUrl.pathname) > -1) {
<add> const path = join(__dirname, 'static', parsedUrl.pathname)
<add> app.serveStatic(req, res, path)
<add> } else {
<add> handle(req, res, parsedUrl)
<add> }
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/shared-modules/components/Header.js
<ide> import Link from 'next/link'
<ide> export default () => (
<ide> <div>
<ide> <Link href='/'>
<del> <a style={styles.a} >Home</a>
<add> <a style={styles.a}>Home</a>
<ide> </Link>
<ide>
<ide> <Link href='/about'>
<del> <a style={styles.a} >About</a>
<add> <a style={styles.a}>About</a>
<ide> </Link>
<ide> </div>
<ide> )
<ide><path>examples/ssr-caching/pages/blog.js
<ide> export default class extends React.Component {
<ide> }
<ide>
<ide> render () {
<del> return <div>
<del> <h1>My {this.props.id} blog post</h1>
<del> <p>
<del> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
<del> tempor incididunt ut labore et dolore magna aliqua.
<del> </p>
<del> </div>
<add> return (
<add> <div>
<add> <h1>My {this.props.id} blog post</h1>
<add> <p>
<add> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
<add> eiusmod tempor incididunt ut labore et dolore magna aliqua.
<add> </p>
<add> </div>
<add> )
<ide> }
<ide> }
<ide><path>examples/ssr-caching/pages/index.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link href='/blog?id=first' as='/blog/first'><a>My first blog post</a></Link></li>
<del> <li><Link href='/blog?id=second' as='/blog/second'><a>My second blog post</a></Link></li>
<del> <li><Link href='/blog?id=last' as='/blog/last'><a>My last blog post</a></Link></li>
<add> <li>
<add> <Link href='/blog?id=first' as='/blog/first'>
<add> <a>My first blog post</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/blog?id=second' as='/blog/second'>
<add> <a>My second blog post</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link href='/blog?id=last' as='/blog/last'>
<add> <a>My last blog post</a>
<add> </Link>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/ssr-caching/server.js
<ide> const ssrCache = new LRUCache({
<ide> maxAge: 1000 * 60 * 60 // 1hour
<ide> })
<ide>
<del>app.prepare()
<del> .then(() => {
<del> const server = express()
<add>app.prepare().then(() => {
<add> const server = express()
<ide>
<del> // Use the `renderAndCache` utility defined below to serve pages
<del> server.get('/', (req, res) => {
<del> renderAndCache(req, res, '/')
<del> })
<add> // Use the `renderAndCache` utility defined below to serve pages
<add> server.get('/', (req, res) => {
<add> renderAndCache(req, res, '/')
<add> })
<ide>
<del> server.get('/blog/:id', (req, res) => {
<del> const queryParams = { id: req.params.id }
<del> renderAndCache(req, res, '/blog', queryParams)
<del> })
<add> server.get('/blog/:id', (req, res) => {
<add> const queryParams = { id: req.params.id }
<add> renderAndCache(req, res, '/blog', queryParams)
<add> })
<ide>
<del> server.get('*', (req, res) => {
<del> return handle(req, res)
<del> })
<add> server.get('*', (req, res) => {
<add> return handle(req, res)
<add> })
<ide>
<del> server.listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> server.listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide>
<ide> /*
<ide> * NB: make sure to modify this to take into account anything that should trigger
<ide><path>examples/using-inferno/next.config.js
<ide> module.exports = {
<ide> }
<ide>
<ide> config.resolve.alias = {
<del> 'react': 'inferno-compat',
<add> react: 'inferno-compat',
<ide> 'react-dom': 'inferno-compat'
<ide> }
<ide> return config
<ide><path>examples/using-inferno/pages/about.js
<ide> import React from 'react'
<ide>
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/using-inferno/pages/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<del> <div>Hello World. <Link prefetch href='/about'><a>About</a></Link></div>
<add> <div>
<add> Hello World.{' '}
<add> <Link prefetch href='/about'>
<add> <a>About</a>
<add> </Link>
<add> </div>
<ide> )
<ide><path>examples/using-inferno/server.js
<ide> const next = require('next')
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> handle(req, res, parsedUrl)
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> handle(req, res, parsedUrl)
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/using-nerv/pages/about.js
<ide> import React from 'react'
<ide>
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/using-nerv/pages/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<del> <div>Hello World. <Link href='/about'><a>About</a></Link></div>
<add> <div>
<add> Hello World.{' '}
<add> <Link href='/about'>
<add> <a>About</a>
<add> </Link>
<add> </div>
<ide> )
<ide><path>examples/using-nerv/server.js
<ide> const next = require('next')
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> handle(req, res, parsedUrl)
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> handle(req, res, parsedUrl)
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/using-preact/pages/about.js
<ide> import React from 'react'
<ide>
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/using-preact/pages/index.js
<ide> import React from 'react'
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<del> <div>Hello World. <Link href='/about'><a>About</a></Link></div>
<add> <div>
<add> Hello World.{' '}
<add> <Link href='/about'>
<add> <a>About</a>
<add> </Link>
<add> </div>
<ide> )
<ide><path>examples/using-preact/server.js
<ide> const next = require('next')
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => {
<del> const parsedUrl = parse(req.url, true)
<del> handle(req, res, parsedUrl)
<del> })
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) => {
<add> const parsedUrl = parse(req.url, true)
<add> handle(req, res, parsedUrl)
<add> }).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/using-router/components/Header.js
<ide> export default () => (
<ide> // and use it manually
<ide>
<ide> function onClickHandler (href) {
<del> return (e) => {
<add> return e => {
<ide> e.preventDefault()
<ide> Router.push(href)
<ide> }
<ide><path>examples/using-router/pages/error.js
<del>import {Component} from 'react'
<add>import { Component } from 'react'
<ide> import Header from '../components/Header'
<ide> import Router from 'next/router'
<ide>
<ide><path>examples/using-with-router/components/ActiveLink.js
<ide> const ActiveLink = ({ children, router, href }) => {
<ide> color: router.pathname === href ? 'red' : 'black'
<ide> }
<ide>
<del> const handleClick = (e) => {
<add> const handleClick = e => {
<ide> e.preventDefault()
<ide> router.push(href)
<ide> }
<ide><path>examples/using-with-router/pages/error.js
<del>import {Component} from 'react'
<add>import { Component } from 'react'
<ide> import Header from '../components/Header'
<ide> import Router from 'next/router'
<ide>
<ide><path>examples/with-algolia-react-instantsearch/components/app.js
<ide> import {
<ide> } from 'react-instantsearch/dom'
<ide> import { InstantSearch } from './instantsearch'
<ide>
<del>const HitComponent = ({ hit }) =>
<add>const HitComponent = ({ hit }) => (
<ide> <div className='hit'>
<ide> <div>
<ide> <div className='hit-picture'>
<ide> const HitComponent = ({ hit }) =>
<ide> <div className='hit-content'>
<ide> <div>
<ide> <Highlight attributeName='name' hit={hit} />
<del> <span>
<del> {' '}- ${hit.price}
<del> </span>
<del> <span>
<del> {' '}- {hit.rating} stars
<del> </span>
<add> <span> - ${hit.price}</span>
<add> <span> - {hit.rating} stars</span>
<ide> </div>
<ide> <div className='hit-type'>
<ide> <Highlight attributeName='type' hit={hit} />
<ide> const HitComponent = ({ hit }) =>
<ide> </div>
<ide> </div>
<ide> </div>
<add>)
<ide>
<ide> HitComponent.propTypes = {
<ide> hit: PropTypes.object
<ide> export default class extends React.Component {
<ide> searchState: PropTypes.object,
<ide> resultsState: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
<ide> onSearchStateChange: PropTypes.func
<del> };
<add> }
<ide>
<ide> render () {
<ide> return (
<ide><path>examples/with-algolia-react-instantsearch/components/head.js
<ide> const defaultDescription = ''
<ide> const defaultOGURL = ''
<ide> const defaultOGImage = ''
<ide>
<del>export const Head = props =>
<add>export const Head = props => (
<ide> <NextHead>
<ide> <meta charSet='UTF-8' />
<ide> <title>{props.title || ''}</title>
<ide> export const Head = props =>
<ide> />
<ide> <link rel='stylesheet' href='../static/instantsearch.css' />
<ide> </NextHead>
<add>)
<ide>
<ide> Head.propTypes = {
<ide> title: string,
<ide><path>examples/with-algolia-react-instantsearch/pages/index.js
<ide> export default class extends React.Component {
<ide> static propTypes = {
<ide> resultsState: PropTypes.object,
<ide> searchState: PropTypes.object
<del> };
<add> }
<ide>
<ide> constructor (props) {
<ide> super(props)
<ide> export default class extends React.Component {
<ide> })
<ide> }, updateAfter)
<ide> this.setState({ searchState })
<del> };
<add> }
<ide>
<ide> componentDidMount () {
<ide> this.setState({ searchState: qs.parse(window.location.search.slice(1)) })
<ide><path>examples/with-amp/components/Byline.js
<del>export default ({ author }) => (
<del> <div className='byline'>
<del> By {author}
<del> </div>
<del>)
<add>export default ({ author }) => <div className='byline'>By {author}</div>
<ide><path>examples/with-amp/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> <Head>
<ide> <link rel='canonical' href='/' />
<ide> <meta name='viewport' content='width=device-width,minimum-scale=1' />
<del> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto' />
<del> <style amp-boilerplate=''>{`body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}`}</style><noscript><style amp-boilerplate=''>{`body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}`}</style></noscript>
<add> <link
<add> rel='stylesheet'
<add> href='https://fonts.googleapis.com/css?family=Roboto'
<add> />
<add> <style amp-boilerplate=''>{`body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}`}</style>
<add> <noscript>
<add> <style amp-boilerplate=''>{`body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}`}</style>
<add> </noscript>
<ide> <style amp-custom=''>{`body {font-family: Roboto, sans-serif; padding: 30px; color: #444;} h1 {margin-bottom: 5px;} .byline { color: #aaa; margin-bottom: 25px; } p {font-size: 18px; line-height: 30px; margin-top: 30px;} .caption {color: #ccc; margin-top: 0; font-size: 14px; text-align: center;}`}</style>
<ide> <script async src='https://cdn.ampproject.org/v0.js' />
<ide> </Head>
<ide><path>examples/with-amp/pages/dog.js
<ide> export default () => (
<ide> </Head>
<ide> <h1>The Dog</h1>
<ide> <Byline author='Meow Meow Fuzzyface' />
<del> <amp-img src='/static/dog.jpg' width='470' height='350' layout='responsive' alt='Woof' />
<add> <amp-img
<add> src='/static/dog.jpg'
<add> width='470'
<add> height='350'
<add> layout='responsive'
<add> alt='Woof'
<add> />
<ide> <p className='caption'>Woooooooooooof</p>
<del> <p>Wafer donut candy soufflé lemon drops icing. Marzipan gummi bears pie danish lollipop pudding powder gummi bears sweet. Pie sweet roll sweet roll topping chocolate bar dragée pudding chocolate cake. Croissant sweet chocolate bar cheesecake candy canes. Tootsie roll icing macaroon bonbon cupcake apple pie candy canes biscuit candy canes. Jujubes jelly liquorice toffee gingerbread. Candy tootsie roll macaroon chocolate bar icing sugar plum pie. Icing gummies chocolate bar chocolate marzipan bonbon cookie chocolate tart. Caramels danish halvah croissant. Cheesecake cookie tootsie roll ice cream. Powder dessert carrot cake muffin tiramisu lemon drops liquorice topping brownie. Soufflé chocolate cake croissant cupcake jelly.</p>
<del> <p>Muffin gummies dessert cheesecake candy canes. Candy canes danish cotton candy tart dessert powder bear claw marshmallow. Muffin chocolate marshmallow danish. Chocolate bar biscuit cake tiramisu. Topping sweet brownie jujubes powder marzipan. Croissant wafer bonbon chupa chups cake cake marzipan caramels jujubes. Cupcake cheesecake sweet roll marshmallow lollipop danish jujubes jelly icing. Apple pie chupa chups lollipop jelly-o cheesecake jelly beans cake dessert. Tootsie roll tootsie roll bonbon pastry croissant gummi bears cake cake. Fruitcake sugar plum halvah gingerbread cookie pastry chupa chups wafer lemon drops. Marshmallow liquorice oat cake lollipop. Lemon drops oat cake halvah liquorice danish powder cupcake soufflé. Cake tart topping jelly-o tart sugar plum. Chocolate bar cookie wafer tootsie roll candy cotton candy toffee pie donut.</p>
<del> <p>Ice cream lollipop marshmallow tiramisu jujubes croissant. Bear claw lemon drops marzipan candy bonbon cupcake powder. Candy canes cheesecake bear claw pastry cake donut jujubes. Icing tart jelly-o soufflé bonbon apple pie. Cheesecake pie chupa chups toffee powder. Bonbon lemon drops carrot cake pudding candy halvah cheesecake lollipop cupcake. Pudding marshmallow fruitcake. Gummi bears bonbon chupa chups lemon drops. Wafer dessert gummies gummi bears biscuit donut tiramisu gummi bears brownie. Tootsie roll liquorice bonbon cookie. Sesame snaps chocolate bar cake croissant chupa chups cheesecake gingerbread tiramisu jelly. Cheesecake ice cream muffin lollipop gummies. Sesame snaps jelly beans sweet bear claw tart.</p>
<del> <p>Sweet topping chupa chups chocolate cake jelly-o liquorice danish. Pastry jelly beans apple pie dessert pastry lemon drops marzipan gummies. Jelly beans macaroon bear claw cotton candy. Toffee sweet lollipop toffee oat cake. Jelly-o oat cake fruitcake chocolate bar sweet. Lemon drops gummies chocolate cake lollipop bear claw croissant danish icing. Chocolate bar donut brownie chocolate cake lemon drops chocolate bar. Cake fruitcake pudding chocolate apple pie. Brownie tiramisu chocolate macaroon lemon drops wafer soufflé jujubes icing. Cheesecake tiramisu cake macaroon tart lollipop donut. Gummi bears dragée pudding bear claw. Muffin cake cupcake candy canes. Soufflé candy canes biscuit. Macaroon gummies danish.</p>
<del> <p>Cupcake cupcake tart. Cotton candy danish candy canes oat cake ice cream candy canes powder wafer. Chocolate sesame snaps oat cake dragée cheesecake. Sesame snaps marshmallow topping liquorice cookie marshmallow. Liquorice pudding chocolate bar. Cake powder brownie fruitcake. Carrot cake dessert marzipan sugar plum cupcake cheesecake pastry. Apple pie macaroon ice cream fruitcake apple pie cookie. Tootsie roll ice cream oat cake cheesecake donut cheesecake bear claw. Sesame snaps marzipan jelly beans chocolate tootsie roll. Chocolate bar donut dragée ice cream biscuit. Pie candy canes muffin candy canes ice cream tiramisu.</p>
<add> <p>
<add> Wafer donut candy soufflé lemon drops icing. Marzipan gummi bears pie
<add> danish lollipop pudding powder gummi bears sweet. Pie sweet roll sweet
<add> roll topping chocolate bar dragée pudding chocolate cake. Croissant sweet
<add> chocolate bar cheesecake candy canes. Tootsie roll icing macaroon bonbon
<add> cupcake apple pie candy canes biscuit candy canes. Jujubes jelly liquorice
<add> toffee gingerbread. Candy tootsie roll macaroon chocolate bar icing sugar
<add> plum pie. Icing gummies chocolate bar chocolate marzipan bonbon cookie
<add> chocolate tart. Caramels danish halvah croissant. Cheesecake cookie
<add> tootsie roll ice cream. Powder dessert carrot cake muffin tiramisu lemon
<add> drops liquorice topping brownie. Soufflé chocolate cake croissant cupcake
<add> jelly.
<add> </p>
<add> <p>
<add> Muffin gummies dessert cheesecake candy canes. Candy canes danish cotton
<add> candy tart dessert powder bear claw marshmallow. Muffin chocolate
<add> marshmallow danish. Chocolate bar biscuit cake tiramisu. Topping sweet
<add> brownie jujubes powder marzipan. Croissant wafer bonbon chupa chups cake
<add> cake marzipan caramels jujubes. Cupcake cheesecake sweet roll marshmallow
<add> lollipop danish jujubes jelly icing. Apple pie chupa chups lollipop
<add> jelly-o cheesecake jelly beans cake dessert. Tootsie roll tootsie roll
<add> bonbon pastry croissant gummi bears cake cake. Fruitcake sugar plum halvah
<add> gingerbread cookie pastry chupa chups wafer lemon drops. Marshmallow
<add> liquorice oat cake lollipop. Lemon drops oat cake halvah liquorice danish
<add> powder cupcake soufflé. Cake tart topping jelly-o tart sugar plum.
<add> Chocolate bar cookie wafer tootsie roll candy cotton candy toffee pie
<add> donut.
<add> </p>
<add> <p>
<add> Ice cream lollipop marshmallow tiramisu jujubes croissant. Bear claw lemon
<add> drops marzipan candy bonbon cupcake powder. Candy canes cheesecake bear
<add> claw pastry cake donut jujubes. Icing tart jelly-o soufflé bonbon apple
<add> pie. Cheesecake pie chupa chups toffee powder. Bonbon lemon drops carrot
<add> cake pudding candy halvah cheesecake lollipop cupcake. Pudding marshmallow
<add> fruitcake. Gummi bears bonbon chupa chups lemon drops. Wafer dessert
<add> gummies gummi bears biscuit donut tiramisu gummi bears brownie. Tootsie
<add> roll liquorice bonbon cookie. Sesame snaps chocolate bar cake croissant
<add> chupa chups cheesecake gingerbread tiramisu jelly. Cheesecake ice cream
<add> muffin lollipop gummies. Sesame snaps jelly beans sweet bear claw tart.
<add> </p>
<add> <p>
<add> Sweet topping chupa chups chocolate cake jelly-o liquorice danish. Pastry
<add> jelly beans apple pie dessert pastry lemon drops marzipan gummies. Jelly
<add> beans macaroon bear claw cotton candy. Toffee sweet lollipop toffee oat
<add> cake. Jelly-o oat cake fruitcake chocolate bar sweet. Lemon drops gummies
<add> chocolate cake lollipop bear claw croissant danish icing. Chocolate bar
<add> donut brownie chocolate cake lemon drops chocolate bar. Cake fruitcake
<add> pudding chocolate apple pie. Brownie tiramisu chocolate macaroon lemon
<add> drops wafer soufflé jujubes icing. Cheesecake tiramisu cake macaroon tart
<add> lollipop donut. Gummi bears dragée pudding bear claw. Muffin cake cupcake
<add> candy canes. Soufflé candy canes biscuit. Macaroon gummies danish.
<add> </p>
<add> <p>
<add> Cupcake cupcake tart. Cotton candy danish candy canes oat cake ice cream
<add> candy canes powder wafer. Chocolate sesame snaps oat cake dragée
<add> cheesecake. Sesame snaps marshmallow topping liquorice cookie marshmallow.
<add> Liquorice pudding chocolate bar. Cake powder brownie fruitcake. Carrot
<add> cake dessert marzipan sugar plum cupcake cheesecake pastry. Apple pie
<add> macaroon ice cream fruitcake apple pie cookie. Tootsie roll ice cream oat
<add> cake cheesecake donut cheesecake bear claw. Sesame snaps marzipan jelly
<add> beans chocolate tootsie roll. Chocolate bar donut dragée ice cream
<add> biscuit. Pie candy canes muffin candy canes ice cream tiramisu.
<add> </p>
<ide> </div>
<ide> )
<ide><path>examples/with-amp/pages/index.js
<ide> export default () => (
<ide> </Head>
<ide> <h1>The Cat</h1>
<ide> <Byline author='Dan Zajdband' />
<del> <amp-img src='/static/cat.jpg' width='470' height='350' layout='responsive' alt='Meow' />
<add> <amp-img
<add> src='/static/cat.jpg'
<add> width='470'
<add> height='350'
<add> layout='responsive'
<add> alt='Meow'
<add> />
<ide> <p className='caption'>Meowwwwwwww</p>
<del> <p>Cat ipsum dolor <a href='/dog'>sit amet</a>, eat grass, throw it back up but refuse to leave cardboard box or groom yourself 4 hours - checked, have your beauty sleep 18 hours - checked, be fabulous for the rest of the day - checked!. Hide from vacuum cleaner. Chirp at birds chew foot chase the pig around the house and meoooow!. Chase ball of string climb a tree, wait for a fireman jump to fireman then scratch his face claw drapes, for meow to be let in yet attack dog, run away and pretend to be victim meow loudly just to annoy owners. Touch water with paw then recoil in horror hide when guests come over, and tuxedo cats always looking dapper so has closed eyes but still sees you or a nice warm laptop for me to sit on pee in human's bed until he cleans the litter box. Steal the warm chair right after you get up cat not kitten around yet claws in your leg eat all the power cords. Lick sellotape curl into a furry donut immediately regret falling into bathtub or you call this cat food? and fall asleep on the washing machine. Purr for no reason hack up furballs and pelt around the house and up and down stairs chasing phantoms. If it smells like fish eat as much as you wish. Unwrap toilet paper chew iPad power cord white cat sleeps on a black shirt lick the other cats. Lounge in doorway mew. Has closed eyes but still sees you sleep on keyboard, so hunt anything that moves lick sellotape but slap owner's face at 5am until human fills food dish if it smells like fish eat as much as you wish. Meow to be let in find empty spot in cupboard and sleep all day and thug cat sit by the fire burrow under covers always hungry. Swat at dog hide when guests come over purrrrrr chew on cable so mark territory, yet howl on top of tall thing or find something else more interesting. Chase mice kitten is playing with dead mouse. Sit and stare if it fits, i sits. Mark territory damn that dog , but step on your keyboard while you're gaming and then turn in a circle put butt in owner's face human give me attention meow or eat and than sleep on your face. Friends are not food jump around on couch, meow constantly until given food, or walk on car leaving trail of paw prints on hood and windshield, and spread kitty litter all over house, going to catch the red dot today going to catch the red dot today. Jump off balcony, onto stranger's head.</p>
<del> <p>Meow to be let out damn that dog howl uncontrollably for no reason caticus cuteicus for play riveting piece on synthesizer keyboard. Meow loudly just to annoy owners the dog smells bad for eat the fat cats food, yet ignore the squirrels, you'll never catch them anyway cat snacks spread kitty litter all over house or hopped up on catnip. Spit up on light gray carpet instead of adjacent linoleum throwup on your pillow, so cat is love, cat is life yet human is washing you why halp oh the horror flee scratch hiss bite. Chase mice. Swat turds around the house hide at bottom of staircase to trip human. Meowing non stop for food howl on top of tall thing. Shake treat bag pee in human's bed until he cleans the litter box missing until dinner time. Have secret plans climb a tree, wait for a fireman jump to fireman then scratch his face bleghbleghvomit my furball really tie the room together. Chase dog then run away purr shake treat bag spit up on light gray carpet instead of adjacent linoleum but dream about hunting birds. Hiss at vacuum cleaner milk the cow lay on arms while you're using the keyboard sleep in the bathroom sink. Stare at ceiling touch water with paw then recoil in horror or refuse to leave cardboard box. Paw at your fat belly plan steps for world domination for going to catch the red dot today going to catch the red dot today slap owner's face at 5am until human fills food dish scratch at the door then walk away for intrigued by the shower, but steal the warm chair right after you get up. Fall asleep on the washing machine destroy couch as revenge scream at teh bath so love to play with owner's hair tie. Howl uncontrollably for no reason rub whiskers on bare skin act innocent. Cats making all the muffins lick butt and make a weird face meow all night having their mate disturbing sleeping humans human give me attention meow intently stare at the same spot. Sleep on dog bed, force dog to sleep on floor spot something, big eyes, big eyes, crouch, shake butt, prepare to pounce for wake up human for food at 4am or pooping rainbow while flying in a toasted bread costume in space sleep on keyboard put toy mouse in food bowl run out of litter box at full speed . Jump off balcony, onto stranger's head lick butt and make a weird face but go into a room to decide you didn't want to be in there anyway so then cats take over the world, pee in human's bed until he cleans the litter box and if it fits, i sits caticus cuteicus. Eats owners hair then claws head lounge in doorway, and hide when guests come over chase ball of string eat owner's food play riveting piece on synthesizer keyboard. Purrr purr littel cat, little cat purr purr spit up on light gray carpet instead of adjacent linoleum kitty loves pigs yet damn that dog meow or walk on car leaving trail of paw prints on hood and windshield. Roll on the floor purring your whiskers off meow all night having their mate disturbing sleeping humans need to chase tail meow hide when guests come over. Soft kitty warm kitty little ball of furr destroy the blinds meow leave hair everywhere attack dog, run away and pretend to be victim. Going to catch the red dot today going to catch the red dot today instantly break out into full speed gallop across the house for no reason meow so hide when guests come over, yet hide at bottom of staircase to trip human toy mouse squeak roll over claws in your leg. Cat slap dog in face lick plastic bags why must they do that.</p>
<del> <p>Jump launch to pounce upon little yarn mouse, bare fangs at toy run hide in litter box until treats are fed touch water with paw then recoil in horror then cats take over the world i could pee on this if i had the energy. Lie on your belly and purr when you are asleep toy mouse squeak roll over so stick butt in face you call this cat food? and behind the couch curl up and sleep on the freshly laundered towels yet love to play with owner's hair tie. Knock dish off table head butt cant eat out of my own dish walk on car leaving trail of paw prints on hood and windshield find something else more interesting cats go for world domination, spit up on light gray carpet instead of adjacent linoleum sit in box. Missing until dinner time put toy mouse in food bowl run out of litter box at full speed but poop in the plant pot and nap all day caticus cuteicus. Leave hair everywhere attack feet mrow bleghbleghvomit my furball really tie the room together meowwww eat grass, throw it back up. Hate dog meowzer! find something else more interesting, yet cat snacks, so scratch at the door then walk away chase mice. Chase laser scratch the box plan steps for world domination massacre a bird in the living room and then look like the cutest and most innocent animal on the planet for stare at ceiling light and who's the baby. Stare at ceiling Gate keepers of hell, for licks paws intently sniff hand. Pooping rainbow while flying in a toasted bread costume in space. Gnaw the corn cob. Lick yarn hanging out of own butt stare at ceiling lick butt and make a weird face eat and than sleep on your face. Meow all night having their mate disturbing sleeping humans attack feet, so poop on grasses stare at wall turn and meow stare at wall some more meow again continue staring yet purr. Have my breakfast spaghetti yarn. Cats secretly make all the worlds muffins throwup on your pillow plays league of legends. Lick the plastic bag scratch at the door then walk away. Unwrap toilet paper meow to be let in walk on car leaving trail of paw prints on hood and windshield yet hide from vacuum cleaner or massacre a bird in the living room and then look like the cutest and most innocent animal on the planet. Purr lick the curtain just to be annoying go into a room to decide you didn't want to be in there anyway attack feet, and spit up on light gray carpet instead of adjacent linoleum yet lick plastic bags. Spit up on light gray carpet instead of adjacent linoleum touch water with paw then recoil in horror so cat snacks. Purr. Lick sellotape please stop looking at your phone and pet me yet stick butt in face meow. Groom yourself 4 hours - checked, have your beauty sleep 18 hours - checked, be fabulous for the rest of the day - checked! tuxedo cats always looking dapper but purrrrrr. Claws in your leg i could pee on this if i had the energy. Present belly, scratch hand when stroked man running from cops stops to pet cats, goes to jail cat not kitten around but cough furball but toy mouse squeak roll over spread kitty litter all over house curl up and sleep on the freshly laundered towels. Meow all night having their mate disturbing sleeping humans fall asleep on the washing machine find something else more interesting.</p>
<del> <p>Ignore the squirrels, you'll never catch them anyway missing until dinner time, for intrigued by the shower, so i could pee on this if i had the energy for purrrrrr for vommit food and eat it again lick butt and make a weird face. Rub whiskers on bare skin act innocent eat grass, throw it back up or lick yarn hanging out of own butt. I am the best cat is love, cat is life, or sleep nap, mew but meoooow!. Meowzer!. Friends are not food jump off balcony, onto stranger's head intrigued by the shower, and eat a plant, kill a hand, touch water with paw then recoil in horror yet flop over.</p>
<del> <p>Step on your keyboard while you're gaming and then turn in a circle wake up human for food at 4am so shove bum in owner's face like camera lens for see owner, run in terror run outside as soon as door open. Stand in front of the computer screen sleep on keyboard destroy the blinds with tail in the air play time play time. Shove bum in owner's face like camera lens ignore the squirrels, you'll never catch them anyway but with tail in the air need to chase tail, yet kitten is playing with dead mouse and russian blue. Hopped up on catnip refuse to leave cardboard box you call this cat food? walk on car leaving trail of paw prints on hood and windshield. Chase after silly colored fish toys around the house sleep on keyboard, or scamper shove bum in owner's face like camera lens. Groom yourself 4 hours - checked, have your beauty sleep 18 hours - checked, be fabulous for the rest of the day - checked! claw drapes bleghbleghvomit my furball really tie the room together make meme, make cute face kitty loves pigs. Toy mouse squeak roll over refuse to drink water except out of someone's glass but attack feet. Sleep on keyboard. Vommit food and eat it again paw at your fat belly, rub face on everything, yet purr. Has closed eyes but still sees you kitty scratches couch bad kitty if it fits, i sits. Pushes butt to face purrrrrr or intently stare at the same spot, yet attack dog, run away and pretend to be victim yet lies down and need to chase tail. Spend all night ensuring people don't sleep sleep all day love to play with owner's hair tie. I could pee on this if i had the energy lick butt stare out the window. Make meme, make cute face. Chase after silly colored fish toys around the house. Leave fur on owners clothes poop in the plant pot. Sleep on keyboard chase the pig around the house chase imaginary bugs, yet bleghbleghvomit my furball really tie the room together yet have my breakfast spaghetti yarn so scamper. Need to chase tail meow for food, then when human fills food dish, take a few bites of food and continue meowing for pee in the shoe thinking longingly about tuna brine yet purrr purr littel cat, little cat purr purr lie on your belly and purr when you are asleep. Lounge in doorway poop on grasses for lounge in doorway for chew iPad power cord.</p>
<add> <p>
<add> Cat ipsum dolor <a href='/dog'>sit amet</a>, eat grass, throw it back up
<add> but refuse to leave cardboard box or groom yourself 4 hours - checked,
<add> have your beauty sleep 18 hours - checked, be fabulous for the rest of the
<add> day - checked!. Hide from vacuum cleaner. Chirp at birds chew foot chase
<add> the pig around the house and meoooow!. Chase ball of string climb a tree,
<add> wait for a fireman jump to fireman then scratch his face claw drapes, for
<add> meow to be let in yet attack dog, run away and pretend to be victim meow
<add> loudly just to annoy owners. Touch water with paw then recoil in horror
<add> hide when guests come over, and tuxedo cats always looking dapper so has
<add> closed eyes but still sees you or a nice warm laptop for me to sit on pee
<add> in human's bed until he cleans the litter box. Steal the warm chair right
<add> after you get up cat not kitten around yet claws in your leg eat all the
<add> power cords. Lick sellotape curl into a furry donut immediately regret
<add> falling into bathtub or you call this cat food? and fall asleep on the
<add> washing machine. Purr for no reason hack up furballs and pelt around the
<add> house and up and down stairs chasing phantoms. If it smells like fish eat
<add> as much as you wish. Unwrap toilet paper chew iPad power cord white cat
<add> sleeps on a black shirt lick the other cats. Lounge in doorway mew. Has
<add> closed eyes but still sees you sleep on keyboard, so hunt anything that
<add> moves lick sellotape but slap owner's face at 5am until human fills food
<add> dish if it smells like fish eat as much as you wish. Meow to be let in
<add> find empty spot in cupboard and sleep all day and thug cat sit by the fire
<add> burrow under covers always hungry. Swat at dog hide when guests come over
<add> purrrrrr chew on cable so mark territory, yet howl on top of tall thing or
<add> find something else more interesting. Chase mice kitten is playing with
<add> dead mouse. Sit and stare if it fits, i sits. Mark territory damn that dog
<add> , but step on your keyboard while you're gaming and then turn in a circle
<add> put butt in owner's face human give me attention meow or eat and than
<add> sleep on your face. Friends are not food jump around on couch, meow
<add> constantly until given food, or walk on car leaving trail of paw prints on
<add> hood and windshield, and spread kitty litter all over house, going to
<add> catch the red dot today going to catch the red dot today. Jump off
<add> balcony, onto stranger's head.
<add> </p>
<add> <p>
<add> Meow to be let out damn that dog howl uncontrollably for no reason caticus
<add> cuteicus for play riveting piece on synthesizer keyboard. Meow loudly just
<add> to annoy owners the dog smells bad for eat the fat cats food, yet ignore
<add> the squirrels, you'll never catch them anyway cat snacks spread kitty
<add> litter all over house or hopped up on catnip. Spit up on light gray carpet
<add> instead of adjacent linoleum throwup on your pillow, so cat is love, cat
<add> is life yet human is washing you why halp oh the horror flee scratch hiss
<add> bite. Chase mice. Swat turds around the house hide at bottom of staircase
<add> to trip human. Meowing non stop for food howl on top of tall thing. Shake
<add> treat bag pee in human's bed until he cleans the litter box missing until
<add> dinner time. Have secret plans climb a tree, wait for a fireman jump to
<add> fireman then scratch his face bleghbleghvomit my furball really tie the
<add> room together. Chase dog then run away purr shake treat bag spit up on
<add> light gray carpet instead of adjacent linoleum but dream about hunting
<add> birds. Hiss at vacuum cleaner milk the cow lay on arms while you're using
<add> the keyboard sleep in the bathroom sink. Stare at ceiling touch water with
<add> paw then recoil in horror or refuse to leave cardboard box. Paw at your
<add> fat belly plan steps for world domination for going to catch the red dot
<add> today going to catch the red dot today slap owner's face at 5am until
<add> human fills food dish scratch at the door then walk away for intrigued by
<add> the shower, but steal the warm chair right after you get up. Fall asleep
<add> on the washing machine destroy couch as revenge scream at teh bath so love
<add> to play with owner's hair tie. Howl uncontrollably for no reason rub
<add> whiskers on bare skin act innocent. Cats making all the muffins lick butt
<add> and make a weird face meow all night having their mate disturbing sleeping
<add> humans human give me attention meow intently stare at the same spot. Sleep
<add> on dog bed, force dog to sleep on floor spot something, big eyes, big
<add> eyes, crouch, shake butt, prepare to pounce for wake up human for food at
<add> 4am or pooping rainbow while flying in a toasted bread costume in space
<add> sleep on keyboard put toy mouse in food bowl run out of litter box at full
<add> speed . Jump off balcony, onto stranger's head lick butt and make a weird
<add> face but go into a room to decide you didn't want to be in there anyway so
<add> then cats take over the world, pee in human's bed until he cleans the
<add> litter box and if it fits, i sits caticus cuteicus. Eats owners hair then
<add> claws head lounge in doorway, and hide when guests come over chase ball of
<add> string eat owner's food play riveting piece on synthesizer keyboard. Purrr
<add> purr littel cat, little cat purr purr spit up on light gray carpet instead
<add> of adjacent linoleum kitty loves pigs yet damn that dog meow or walk on
<add> car leaving trail of paw prints on hood and windshield. Roll on the floor
<add> purring your whiskers off meow all night having their mate disturbing
<add> sleeping humans need to chase tail meow hide when guests come over. Soft
<add> kitty warm kitty little ball of furr destroy the blinds meow leave hair
<add> everywhere attack dog, run away and pretend to be victim. Going to catch
<add> the red dot today going to catch the red dot today instantly break out
<add> into full speed gallop across the house for no reason meow so hide when
<add> guests come over, yet hide at bottom of staircase to trip human toy mouse
<add> squeak roll over claws in your leg. Cat slap dog in face lick plastic bags
<add> why must they do that.
<add> </p>
<add> <p>
<add> Jump launch to pounce upon little yarn mouse, bare fangs at toy run hide
<add> in litter box until treats are fed touch water with paw then recoil in
<add> horror then cats take over the world i could pee on this if i had the
<add> energy. Lie on your belly and purr when you are asleep toy mouse squeak
<add> roll over so stick butt in face you call this cat food? and behind the
<add> couch curl up and sleep on the freshly laundered towels yet love to play
<add> with owner's hair tie. Knock dish off table head butt cant eat out of my
<add> own dish walk on car leaving trail of paw prints on hood and windshield
<add> find something else more interesting cats go for world domination, spit up
<add> on light gray carpet instead of adjacent linoleum sit in box. Missing
<add> until dinner time put toy mouse in food bowl run out of litter box at full
<add> speed but poop in the plant pot and nap all day caticus cuteicus. Leave
<add> hair everywhere attack feet mrow bleghbleghvomit my furball really tie the
<add> room together meowwww eat grass, throw it back up. Hate dog meowzer! find
<add> something else more interesting, yet cat snacks, so scratch at the door
<add> then walk away chase mice. Chase laser scratch the box plan steps for
<add> world domination massacre a bird in the living room and then look like the
<add> cutest and most innocent animal on the planet for stare at ceiling light
<add> and who's the baby. Stare at ceiling Gate keepers of hell, for licks paws
<add> intently sniff hand. Pooping rainbow while flying in a toasted bread
<add> costume in space. Gnaw the corn cob. Lick yarn hanging out of own butt
<add> stare at ceiling lick butt and make a weird face eat and than sleep on
<add> your face. Meow all night having their mate disturbing sleeping humans
<add> attack feet, so poop on grasses stare at wall turn and meow stare at wall
<add> some more meow again continue staring yet purr. Have my breakfast
<add> spaghetti yarn. Cats secretly make all the worlds muffins throwup on your
<add> pillow plays league of legends. Lick the plastic bag scratch at the door
<add> then walk away. Unwrap toilet paper meow to be let in walk on car leaving
<add> trail of paw prints on hood and windshield yet hide from vacuum cleaner or
<add> massacre a bird in the living room and then look like the cutest and most
<add> innocent animal on the planet. Purr lick the curtain just to be annoying
<add> go into a room to decide you didn't want to be in there anyway attack
<add> feet, and spit up on light gray carpet instead of adjacent linoleum yet
<add> lick plastic bags. Spit up on light gray carpet instead of adjacent
<add> linoleum touch water with paw then recoil in horror so cat snacks. Purr.
<add> Lick sellotape please stop looking at your phone and pet me yet stick butt
<add> in face meow. Groom yourself 4 hours - checked, have your beauty sleep 18
<add> hours - checked, be fabulous for the rest of the day - checked! tuxedo
<add> cats always looking dapper but purrrrrr. Claws in your leg i could pee on
<add> this if i had the energy. Present belly, scratch hand when stroked man
<add> running from cops stops to pet cats, goes to jail cat not kitten around
<add> but cough furball but toy mouse squeak roll over spread kitty litter all
<add> over house curl up and sleep on the freshly laundered towels. Meow all
<add> night having their mate disturbing sleeping humans fall asleep on the
<add> washing machine find something else more interesting.
<add> </p>
<add> <p>
<add> Ignore the squirrels, you'll never catch them anyway missing until dinner
<add> time, for intrigued by the shower, so i could pee on this if i had the
<add> energy for purrrrrr for vommit food and eat it again lick butt and make a
<add> weird face. Rub whiskers on bare skin act innocent eat grass, throw it
<add> back up or lick yarn hanging out of own butt. I am the best cat is love,
<add> cat is life, or sleep nap, mew but meoooow!. Meowzer!. Friends are not
<add> food jump off balcony, onto stranger's head intrigued by the shower, and
<add> eat a plant, kill a hand, touch water with paw then recoil in horror yet
<add> flop over.
<add> </p>
<add> <p>
<add> Step on your keyboard while you're gaming and then turn in a circle wake
<add> up human for food at 4am so shove bum in owner's face like camera lens for
<add> see owner, run in terror run outside as soon as door open. Stand in front
<add> of the computer screen sleep on keyboard destroy the blinds with tail in
<add> the air play time play time. Shove bum in owner's face like camera lens
<add> ignore the squirrels, you'll never catch them anyway but with tail in the
<add> air need to chase tail, yet kitten is playing with dead mouse and russian
<add> blue. Hopped up on catnip refuse to leave cardboard box you call this cat
<add> food? walk on car leaving trail of paw prints on hood and windshield.
<add> Chase after silly colored fish toys around the house sleep on keyboard, or
<add> scamper shove bum in owner's face like camera lens. Groom yourself 4 hours
<add> - checked, have your beauty sleep 18 hours - checked, be fabulous for the
<add> rest of the day - checked! claw drapes bleghbleghvomit my furball really
<add> tie the room together make meme, make cute face kitty loves pigs. Toy
<add> mouse squeak roll over refuse to drink water except out of someone's glass
<add> but attack feet. Sleep on keyboard. Vommit food and eat it again paw at
<add> your fat belly, rub face on everything, yet purr. Has closed eyes but
<add> still sees you kitty scratches couch bad kitty if it fits, i sits. Pushes
<add> butt to face purrrrrr or intently stare at the same spot, yet attack dog,
<add> run away and pretend to be victim yet lies down and need to chase tail.
<add> Spend all night ensuring people don't sleep sleep all day love to play
<add> with owner's hair tie. I could pee on this if i had the energy lick butt
<add> stare out the window. Make meme, make cute face. Chase after silly colored
<add> fish toys around the house. Leave fur on owners clothes poop in the plant
<add> pot. Sleep on keyboard chase the pig around the house chase imaginary
<add> bugs, yet bleghbleghvomit my furball really tie the room together yet have
<add> my breakfast spaghetti yarn so scamper. Need to chase tail meow for food,
<add> then when human fills food dish, take a few bites of food and continue
<add> meowing for pee in the shoe thinking longingly about tuna brine yet purrr
<add> purr littel cat, little cat purr purr lie on your belly and purr when you
<add> are asleep. Lounge in doorway poop on grasses for lounge in doorway for
<add> chew iPad power cord.
<add> </p>
<ide> </div>
<ide> )
<ide><path>examples/with-ant-design-less/next.config.js
<ide> const path = require('path')
<ide>
<ide> // Where your antd-custom.less file lives
<ide> const themeVariables = lessToJS(
<del> fs.readFileSync(
<del> path.resolve(__dirname, './assets/antd-custom.less'),
<del> 'utf8'
<del> )
<add> fs.readFileSync(path.resolve(__dirname, './assets/antd-custom.less'), 'utf8')
<ide> )
<ide>
<ide> // fix: prevents error when .less files are required by node
<ide> if (typeof require !== 'undefined') {
<del> require.extensions['.less'] = (file) => {}
<add> require.extensions['.less'] = file => {}
<ide> }
<ide>
<ide> module.exports = withLess({
<ide> lessLoaderOptions: {
<ide> javascriptEnabled: true,
<ide> modifyVars: themeVariables // make your antd custom effective
<del> },
<del>
<add> }
<ide> })
<ide><path>examples/with-ant-design-less/pages/index.js
<del>import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button } from 'antd'
<add>import {
<add> Form,
<add> Select,
<add> InputNumber,
<add> DatePicker,
<add> Switch,
<add> Slider,
<add> Button
<add>} from 'antd'
<ide>
<ide> const FormItem = Form.Item
<ide> const Option = Select.Option
<ide> export default () => (
<ide> labelCol={{ span: 8 }}
<ide> wrapperCol={{ span: 8 }}
<ide> >
<del> <InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' />
<add> <InputNumber
<add> size='large'
<add> min={1}
<add> max={10}
<add> style={{ width: 100 }}
<add> defaultValue={3}
<add> name='inputNumber'
<add> />
<ide> <a href='#'>Link</a>
<ide> </FormItem>
<ide>
<del> <FormItem
<del> label='Switch'
<del> labelCol={{ span: 8 }}
<del> wrapperCol={{ span: 8 }}
<del> >
<add> <FormItem label='Switch' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<ide> <Switch defaultChecked name='switch' />
<ide> </FormItem>
<ide>
<del> <FormItem
<del> label='Slider'
<del> labelCol={{ span: 8 }}
<del> wrapperCol={{ span: 8 }}
<del> >
<add> <FormItem label='Slider' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<ide> <Slider defaultValue={70} />
<ide> </FormItem>
<ide>
<del> <FormItem
<del> label='Select'
<del> labelCol={{ span: 8 }}
<del> wrapperCol={{ span: 8 }}
<del> >
<del> <Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'>
<add> <FormItem label='Select' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<add> <Select
<add> size='large'
<add> defaultValue='lucy'
<add> style={{ width: 192 }}
<add> name='select'
<add> >
<ide> <Option value='jack'>jack</Option>
<ide> <Option value='lucy'>lucy</Option>
<del> <Option value='disabled' disabled>disabled</Option>
<add> <Option value='disabled' disabled>
<add> disabled
<add> </Option>
<ide> <Option value='yiminghe'>yiminghe</Option>
<ide> </Select>
<ide> </FormItem>
<ide> export default () => (
<ide> >
<ide> <DatePicker name='startDate' />
<ide> </FormItem>
<del> <FormItem
<del> style={{ marginTop: 48 }}
<del> wrapperCol={{ span: 8, offset: 8 }}
<del> >
<add> <FormItem style={{ marginTop: 48 }} wrapperCol={{ span: 8, offset: 8 }}>
<ide> <Button size='large' type='primary' htmlType='submit'>
<del> OK
<add> OK
<ide> </Button>
<ide> <Button size='large' style={{ marginLeft: 8 }}>
<del> Cancel
<add> Cancel
<ide> </Button>
<ide> </FormItem>
<ide> </Form>
<ide><path>examples/with-ant-design/next.config.js
<ide> const withCss = require('@zeit/next-css')
<ide>
<ide> // fix: prevents error when .css files are required by node
<ide> if (typeof require !== 'undefined') {
<del> require.extensions['.css'] = (file) => {}
<add> require.extensions['.css'] = file => {}
<ide> }
<ide>
<ide> module.exports = withCss()
<ide><path>examples/with-ant-design/pages/index.js
<del>import { Form, Select, InputNumber, DatePicker, Switch, Slider, Button } from 'antd'
<add>import {
<add> Form,
<add> Select,
<add> InputNumber,
<add> DatePicker,
<add> Switch,
<add> Slider,
<add> Button
<add>} from 'antd'
<ide>
<ide> const FormItem = Form.Item
<ide> const Option = Select.Option
<ide> export default () => (
<ide> labelCol={{ span: 8 }}
<ide> wrapperCol={{ span: 8 }}
<ide> >
<del> <InputNumber size='large' min={1} max={10} style={{ width: 100 }} defaultValue={3} name='inputNumber' />
<add> <InputNumber
<add> size='large'
<add> min={1}
<add> max={10}
<add> style={{ width: 100 }}
<add> defaultValue={3}
<add> name='inputNumber'
<add> />
<ide> <a href='#'>Link</a>
<ide> </FormItem>
<ide>
<del> <FormItem
<del> label='Switch'
<del> labelCol={{ span: 8 }}
<del> wrapperCol={{ span: 8 }}
<del> >
<add> <FormItem label='Switch' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<ide> <Switch defaultChecked name='switch' />
<ide> </FormItem>
<ide>
<del> <FormItem
<del> label='Slider'
<del> labelCol={{ span: 8 }}
<del> wrapperCol={{ span: 8 }}
<del> >
<add> <FormItem label='Slider' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<ide> <Slider defaultValue={70} />
<ide> </FormItem>
<ide>
<del> <FormItem
<del> label='Select'
<del> labelCol={{ span: 8 }}
<del> wrapperCol={{ span: 8 }}
<del> >
<del> <Select size='large' defaultValue='lucy' style={{ width: 192 }} name='select'>
<add> <FormItem label='Select' labelCol={{ span: 8 }} wrapperCol={{ span: 8 }}>
<add> <Select
<add> size='large'
<add> defaultValue='lucy'
<add> style={{ width: 192 }}
<add> name='select'
<add> >
<ide> <Option value='jack'>jack</Option>
<ide> <Option value='lucy'>lucy</Option>
<del> <Option value='disabled' disabled>disabled</Option>
<add> <Option value='disabled' disabled>
<add> disabled
<add> </Option>
<ide> <Option value='yiminghe'>yiminghe</Option>
<ide> </Select>
<ide> </FormItem>
<ide> export default () => (
<ide> >
<ide> <DatePicker name='startDate' />
<ide> </FormItem>
<del> <FormItem
<del> style={{ marginTop: 48 }}
<del> wrapperCol={{ span: 8, offset: 8 }}
<del> >
<add> <FormItem style={{ marginTop: 48 }} wrapperCol={{ span: 8, offset: 8 }}>
<ide> <Button size='large' type='primary' htmlType='submit'>
<del> OK
<add> OK
<ide> </Button>
<ide> <Button size='large' style={{ marginLeft: 8 }}>
<del> Cancel
<add> Cancel
<ide> </Button>
<ide> </FormItem>
<ide> </Form>
<ide><path>examples/with-antd-mobile/components/Layout.js
<ide> export default withRouter(({ router, children, title }) => (
<ide> position: relative;
<ide> }
<ide> `}</style>
<del> <WingBlank>
<del> {children}
<del> </WingBlank>
<add> <WingBlank>{children}</WingBlank>
<ide> </div>
<ide> ))
<ide><path>examples/with-antd-mobile/next.config.js
<ide> const withCSS = require('@zeit/next-css')
<ide> // fix: prevents error when .css files are required by node
<ide> if (typeof require !== 'undefined') {
<ide> // eslint-disable-next-line
<del> require.extensions['.css'] = (file) => {}
<add> require.extensions['.css'] = file => {}
<ide> }
<ide>
<ide> module.exports = withCSS()
<ide><path>examples/with-antd-mobile/pages/_app.js
<ide> export default class CustomApp extends App {
<ide> return (
<ide> <Container>
<ide> <Head>
<del> <meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no' />
<add> <meta
<add> name='viewport'
<add> content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no'
<add> />
<ide> <style global jsx>{`
<ide> html,
<ide> body {
<del> font-family: "Helvetica Neue", "Hiragino Sans GB", Helvetica, "Microsoft YaHei", Arial;
<add> font-family: 'Helvetica Neue', 'Hiragino Sans GB', Helvetica,
<add> 'Microsoft YaHei', Arial;
<ide> margin: 0;
<ide> }
<ide> `}</style>
<ide><path>examples/with-aphrodite/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> return (
<ide> <html>
<ide> <Head>
<del> <style data-aphrodite dangerouslySetInnerHTML={{ __html: this.props.css.content }} />
<add> <style
<add> data-aphrodite
<add> dangerouslySetInnerHTML={{ __html: this.props.css.content }}
<add> />
<ide> </Head>
<ide> <body>
<ide> <Main />
<ide><path>examples/with-apollo-and-redux-saga/components/App.js
<ide> export default ({ children }) => (
<ide> {children}
<ide> <style jsx global>{`
<ide> * {
<del> font-family: Menlo, Monaco, "Lucida Console", "Liberation Mono", "DejaVu Sans Mono", "Bitstream Vera Sans Mono", "Courier New", monospace, serif;
<add> font-family: Menlo, Monaco, 'Lucida Console', 'Liberation Mono',
<add> 'DejaVu Sans Mono', 'Bitstream Vera Sans Mono', 'Courier New',
<add> monospace, serif;
<ide> }
<ide> body {
<ide> margin: 0;
<ide> padding: 25px 50px;
<ide> }
<ide> a {
<del> color: #22BAD9;
<add> color: #22bad9;
<ide> }
<ide> p {
<ide> font-size: 14px;
<ide> export default ({ children }) => (
<ide> }
<ide> button {
<ide> align-items: center;
<del> background-color: #22BAD9;
<add> background-color: #22bad9;
<ide> border: 0;
<ide> color: white;
<ide> display: flex;
<ide> padding: 5px 7px;
<ide> }
<ide> button:active {
<del> background-color: #1B9DB7;
<del> transition: background-color .3s
<add> background-color: #1b9db7;
<add> transition: background-color 0.3s;
<ide> }
<ide> button:focus {
<ide> outline: none;
<ide><path>examples/with-apollo-and-redux-saga/components/ErrorMessage.js
<del>export default ({message}) => (
<add>export default ({ message }) => (
<ide> <aside>
<ide> {message}
<ide> <style jsx>{`
<ide><path>examples/with-apollo-and-redux-saga/components/PageCount.js
<ide> class PageCount extends Component {
<ide> this.props.dispatch(countDecrease())
<ide> }
<ide>
<del> render () {
<add> render() {
<ide> const { count } = this.props
<ide> return (
<ide> <div>
<ide><path>examples/with-apollo-and-redux-saga/components/Placeholder.js
<ide> import React from 'react'
<ide>
<del>export default ({placeholder}) => (
<add>export default ({ placeholder }) => (
<ide> <React.Fragment>
<ide> <h2>JSON:</h2>
<ide> {placeholder.data && (
<ide><path>examples/with-apollo-and-redux-saga/components/Post.js
<ide> function Post ({ id, data: { error, Post } }) {
<ide> <section>
<ide> <div key={Post.id}>
<ide> <h1>{Post.title}</h1>
<del> <p>ID: {Post.id}<br />URL: {Post.url}</p>
<add> <p>
<add> ID: {Post.id}
<add> <br />
<add> URL: {Post.url}
<add> </p>
<ide> <span>
<ide> <PostVoteUp id={Post.id} votes={Post.votes} />
<ide> <PostVoteCount votes={Post.votes} />
<ide><path>examples/with-apollo-and-redux-saga/components/PostList.js
<ide> function PostList ({
<ide> <span>{index + 1}. </span>
<ide> <a
<ide> href={`/blog/${post.id}`}
<del> onClick={(event) => handleClick(event, post.id)}
<add> onClick={event => handleClick(event, post.id)}
<ide> >
<ide> {post.title}
<ide> </a>
<ide><path>examples/with-apollo-and-redux-saga/components/PostVoteButton.js
<del>export default ({id, votes, onClickHandler, className}) => (
<add>export default ({ id, votes, onClickHandler, className }) => (
<ide> <button className={className} onClick={() => onClickHandler()}>
<ide> <style jsx>{`
<ide> button {
<ide><path>examples/with-apollo-and-redux-saga/components/PostVoteCount.js
<del>export default ({votes}) => (
<add>export default ({ votes }) => (
<ide> <span>
<ide> {votes}
<ide> <style jsx>{`
<ide><path>examples/with-apollo-and-redux-saga/lib/withApollo.js
<ide> export default ComposedComponent => {
<ide> const state = {}
<ide>
<ide> // Extract query data from the Apollo store
<del> serverState = Object.assign(
<del> state,
<del> { apollo: { data: apollo.cache.extract() } }
<del> )
<add> serverState = Object.assign(state, {
<add> apollo: { data: apollo.cache.extract() }
<add> })
<ide> }
<ide>
<ide> return {
<ide><path>examples/with-apollo-and-redux-saga/pages/about.js
<ide> export default () => (
<ide> <article>
<ide> <h1>The Idea Behind This Example</h1>
<ide> <p>
<del> <a href='https://www.apollographql.com/client/'>Apollo</a> is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server.
<add> <a href='https://www.apollographql.com/client/'>Apollo</a> is a GraphQL
<add> client that allows you to easily query the exact data you need from a
<add> GraphQL server. In addition to fetching and mutating data, Apollo
<add> analyzes your queries and their results to construct a client-side cache
<add> of your data, which is kept up to date as further queries and mutations
<add> are run, fetching more results from the server.
<ide> </p>
<ide> <p>
<del> In this simple example, we integrate Apollo seamlessly with <a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages inside a <a href='https://facebook.github.io/react/docs/higher-order-components.html'>higher-order component (HOC)</a>. Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application.
<add> In this simple example, we integrate Apollo seamlessly with{' '}
<add> <a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages
<add> inside a{' '}
<add> <a href='https://facebook.github.io/react/docs/higher-order-components.html'>
<add> higher-order component (HOC)
<add> </a>
<add> . Using the HOC pattern we're able to pass down a central store of query
<add> result data created by Apollo into our React component hierarchy defined
<add> inside each page of our Next application.
<ide> </p>
<ide> <p>
<del> On initial page load, while on the server and inside getInitialProps, we invoke the Apollo method, <a href='https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree'>getDataFromTree</a>. This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized.
<add> On initial page load, while on the server and inside getInitialProps, we
<add> invoke the Apollo method,{' '}
<add> <a href='https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree'>
<add> getDataFromTree
<add> </a>
<add> . This method returns a promise; at the point in which the promise
<add> resolves, our Apollo Client store is completely initialized.
<ide> </p>
<ide> <p>
<del> This example relies on <a href='http://graph.cool'>graph.cool</a> for its GraphQL backend.
<add> This example relies on <a href='http://graph.cool'>graph.cool</a> for
<add> its GraphQL backend.
<ide> </p>
<ide> </article>
<ide> </App>
<ide><path>examples/with-apollo-and-redux-saga/pages/blog/index.js
<ide> class BlogIndex extends React.Component {
<ide> }
<ide> }
<ide>
<del>export default withReduxSaga(
<del> withApollo(BlogIndex)
<del>)
<add>export default withReduxSaga(withApollo(BlogIndex))
<ide><path>examples/with-apollo-and-redux-saga/routes.js
<ide> * Parameterized Routing with next-route
<ide> *
<ide> * Benefits: Less code, and easily handles complex url structures
<del>**/
<add> **/
<ide> const routes = (module.exports = require('next-routes')())
<ide>
<ide> routes.add('blog/entry', '/blog/:id')
<ide><path>examples/with-apollo-and-redux-saga/server.js
<ide> * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
<ide> */
<ide>
<del>const {createServer} = require('http')
<add>const { createServer } = require('http')
<ide> const next = require('next')
<ide>
<ide> const port = parseInt(process.env.PORT, 10) || 3000
<ide> const dev = process.env.NODE_ENV !== 'production'
<del>const app = next({dev})
<add>const app = next({ dev })
<ide> const routes = require('./routes')
<ide>
<ide> const handler = routes.getRequestHandler(app)
<ide> app.prepare().then(() => {
<del> createServer(handler)
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> createServer(handler).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<add> })
<ide> })
<ide><path>examples/with-apollo-and-redux/components/AddCount.js
<del>import React, {Component} from 'react'
<add>import React, { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide> import { bindActionCreators } from 'redux'
<ide> import { addCount } from '../lib/store'
<ide> class AddCount extends Component {
<ide> const { count } = this.props
<ide> return (
<ide> <div>
<del> <h1>AddCount: <span>{count}</span></h1>
<add> <h1>
<add> AddCount: <span>{count}</span>
<add> </h1>
<ide> <button onClick={this.add}>Add To Count</button>
<ide> <style jsx>{`
<ide> h1 {
<ide> class AddCount extends Component {
<ide>
<ide> const mapStateToProps = ({ count }) => ({ count })
<ide>
<del>const mapDispatchToProps = (dispatch) => {
<add>const mapDispatchToProps = dispatch => {
<ide> return {
<ide> addCount: bindActionCreators(addCount, dispatch)
<ide> }
<ide> }
<ide>
<del>export default connect(mapStateToProps, mapDispatchToProps)(AddCount)
<add>export default connect(
<add> mapStateToProps,
<add> mapDispatchToProps
<add>)(AddCount)
<ide><path>examples/with-apollo-and-redux/components/Clock.js
<ide> export default ({ lastUpdate, light }) => {
<ide> div {
<ide> padding: 15px;
<ide> display: inline-block;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> }
<ide> export default ({ lastUpdate, light }) => {
<ide> )
<ide> }
<ide>
<del>const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<add>const format = t =>
<add> `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<ide>
<del>const pad = n => n < 10 ? `0${n}` : n
<add>const pad = n => (n < 10 ? `0${n}` : n)
<ide><path>examples/with-apollo-and-redux/lib/store.js
<ide> export const actionTypes = {
<ide> export const reducer = (state = exampleInitialState, action) => {
<ide> switch (action.type) {
<ide> case actionTypes.TICK:
<del> return Object.assign({}, state, { lastUpdate: action.ts, light: !!action.light })
<add> return Object.assign({}, state, {
<add> lastUpdate: action.ts,
<add> light: !!action.light
<add> })
<ide> case actionTypes.ADD:
<ide> return Object.assign({}, state, {
<ide> count: state.count + 1
<ide> })
<del> default: return state
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<ide> // ACTIONS
<del>export const serverRenderClock = (isServer) => dispatch => {
<add>export const serverRenderClock = isServer => dispatch => {
<ide> return dispatch({ type: actionTypes.TICK, light: !isServer, ts: Date.now() })
<ide> }
<ide>
<ide> export const startClock = () => dispatch => {
<del> return setInterval(() => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }), 800)
<add> return setInterval(
<add> () => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }),
<add> 800
<add> )
<ide> }
<ide>
<ide> export const addCount = () => dispatch => {
<ide> return dispatch({ type: actionTypes.ADD })
<ide> }
<ide>
<ide> export const initStore = (initialState = exampleInitialState) => {
<del> return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
<add> return createStore(
<add> reducer,
<add> initialState,
<add> composeWithDevTools(applyMiddleware(thunkMiddleware))
<add> )
<ide> }
<ide><path>examples/with-apollo-and-redux/pages/index.js
<ide> const mapDispatchToProps = dispatch => {
<ide> }
<ide> }
<ide>
<del>export default withApollo(
<del> withRedux(initStore, null, mapDispatchToProps)(Index)
<del>)
<add>export default withApollo(withRedux(initStore, null, mapDispatchToProps)(Index))
<ide><path>examples/with-apollo-auth/components/RegisterBox.js
<ide> import cookie from 'cookie'
<ide> import redirect from '../lib/redirect'
<ide>
<ide> const CREATE_USER = gql`
<del> mutation Create($name: String!, $email: String!, $password: String!) {
<del> createUser(name: $name, authProvider: { email: { email: $email, password: $password }}) {
<del> id
<del> }
<del> signinUser(email: { email: $email, password: $password }) {
<del> token
<add> mutation Create($name: String!, $email: String!, $password: String!) {
<add> createUser(
<add> name: $name
<add> authProvider: { email: { email: $email, password: $password } }
<add> ) {
<add> id
<ide> }
<del>}
<add> signinUser(email: { email: $email, password: $password }) {
<add> token
<add> }
<add> }
<ide> `
<ide>
<ide> const RegisterBox = ({ client }) => {
<ide> let name, email, password
<ide>
<ide> return (
<del> <Mutation mutation={CREATE_USER} onCompleted={(data) => {
<del> // Store the token in cookie
<del> document.cookie = cookie.serialize('token', data.signinUser.token, {
<del> maxAge: 30 * 24 * 60 * 60 // 30 days
<del> })
<del> // Force a reload of all the current queries now that the user is
<del> // logged in
<del> client.cache.reset().then(() => {
<del> redirect({}, '/')
<del> })
<del> }} onError={(error) => {
<del> // If you want to send error to external service?
<del> console.log(error)
<del> }}>
<add> <Mutation
<add> mutation={CREATE_USER}
<add> onCompleted={data => {
<add> // Store the token in cookie
<add> document.cookie = cookie.serialize('token', data.signinUser.token, {
<add> maxAge: 30 * 24 * 60 * 60 // 30 days
<add> })
<add> // Force a reload of all the current queries now that the user is
<add> // logged in
<add> client.cache.reset().then(() => {
<add> redirect({}, '/')
<add> })
<add> }}
<add> onError={error => {
<add> // If you want to send error to external service?
<add> console.log(error)
<add> }}
<add> >
<ide> {(create, { data, error }) => (
<del> <form onSubmit={e => {
<del> e.preventDefault()
<del> e.stopPropagation()
<add> <form
<add> onSubmit={e => {
<add> e.preventDefault()
<add> e.stopPropagation()
<ide>
<del> create({
<del> variables: {
<del> name: name.value,
<del> email: email.value,
<del> password: password.value
<del> }
<del> })
<add> create({
<add> variables: {
<add> name: name.value,
<add> email: email.value,
<add> password: password.value
<add> }
<add> })
<ide>
<del> name.value = email.value = password.value = ''
<del> }}>
<add> name.value = email.value = password.value = ''
<add> }}
<add> >
<ide> {error && <p>Issue occurred while registering :(</p>}
<del> <input name='name' placeholder='Name' ref={node => { name = node }} /><br />
<del> <input name='email' placeholder='Email' ref={node => { email = node }} /><br />
<del> <input name='password' placeholder='Password' ref={node => { password = node }} type='password' /><br />
<add> <input
<add> name='name'
<add> placeholder='Name'
<add> ref={node => {
<add> name = node
<add> }}
<add> />
<add> <br />
<add> <input
<add> name='email'
<add> placeholder='Email'
<add> ref={node => {
<add> email = node
<add> }}
<add> />
<add> <br />
<add> <input
<add> name='password'
<add> placeholder='Password'
<add> ref={node => {
<add> password = node
<add> }}
<add> type='password'
<add> />
<add> <br />
<ide> <button>Register</button>
<ide> </form>
<ide> )}
<del>
<ide> </Mutation>
<ide> )
<ide> }
<ide><path>examples/with-apollo-auth/components/SigninBox.js
<ide> import cookie from 'cookie'
<ide> import redirect from '../lib/redirect'
<ide>
<ide> const SIGN_IN = gql`
<del> mutation Signin($email: String!, $password: String!) {
<del> signinUser(email: { email: $email, password: $password}) {
<del> token
<del> }
<add> mutation Signin($email: String!, $password: String!) {
<add> signinUser(email: { email: $email, password: $password }) {
<add> token
<ide> }
<add> }
<ide> `
<ide>
<ide> // TODO: Find a better name for component.
<ide> const SigninBox = ({ client }) => {
<ide> let email, password
<ide>
<ide> return (
<del> <Mutation mutation={SIGN_IN} onCompleted={(data) => {
<del> // Store the token in cookie
<del> document.cookie = cookie.serialize('token', data.signinUser.token, {
<del> maxAge: 30 * 24 * 60 * 60 // 30 days
<del> })
<del> // Force a reload of all the current queries now that the user is
<del> // logged in
<del> client.cache.reset().then(() => {
<del> redirect({}, '/')
<del> })
<del> }} onError={(error) => {
<del> // If you want to send error to external service?
<del> console.log(error)
<del> }}>
<add> <Mutation
<add> mutation={SIGN_IN}
<add> onCompleted={data => {
<add> // Store the token in cookie
<add> document.cookie = cookie.serialize('token', data.signinUser.token, {
<add> maxAge: 30 * 24 * 60 * 60 // 30 days
<add> })
<add> // Force a reload of all the current queries now that the user is
<add> // logged in
<add> client.cache.reset().then(() => {
<add> redirect({}, '/')
<add> })
<add> }}
<add> onError={error => {
<add> // If you want to send error to external service?
<add> console.log(error)
<add> }}
<add> >
<ide> {(signinUser, { data, error }) => (
<del> <form onSubmit={e => {
<del> e.preventDefault()
<del> e.stopPropagation()
<add> <form
<add> onSubmit={e => {
<add> e.preventDefault()
<add> e.stopPropagation()
<ide>
<del> signinUser({
<del> variables: {
<del> email: email.value,
<del> password: password.value
<del> }
<del> })
<add> signinUser({
<add> variables: {
<add> email: email.value,
<add> password: password.value
<add> }
<add> })
<ide>
<del> email.value = password.value = ''
<del> }}>
<add> email.value = password.value = ''
<add> }}
<add> >
<ide> {error && <p>No user found with that information.</p>}
<del> <input name='email' placeholder='Email' ref={node => { email = node }} /><br />
<del> <input name='password' placeholder='Password' ref={node => { password = node }} type='password' /><br />
<add> <input
<add> name='email'
<add> placeholder='Email'
<add> ref={node => {
<add> email = node
<add> }}
<add> />
<add> <br />
<add> <input
<add> name='password'
<add> placeholder='Password'
<add> ref={node => {
<add> password = node
<add> }}
<add> type='password'
<add> />
<add> <br />
<ide> <button>Sign in</button>
<ide> </form>
<ide> )}
<ide><path>examples/with-apollo-auth/lib/checkLoggedIn.js
<ide> import gql from 'graphql-tag'
<ide>
<del>export default apolloClient => (
<del> apolloClient.query({
<del> query: gql`
<del> query getUser {
<del> user {
<del> id
<del> name
<add>export default apolloClient =>
<add> apolloClient
<add> .query({
<add> query: gql`
<add> query getUser {
<add> user {
<add> id
<add> name
<add> }
<ide> }
<del> }
<del> `
<del> }).then(({ data }) => {
<del> return { loggedInUser: data }
<del> }).catch(() => {
<del> // Fail gracefully
<del> return { loggedInUser: {} }
<del> })
<del>)
<add> `
<add> })
<add> .then(({ data }) => {
<add> return { loggedInUser: data }
<add> })
<add> .catch(() => {
<add> // Fail gracefully
<add> return { loggedInUser: {} }
<add> })
<ide><path>examples/with-apollo-auth/lib/withApollo.js
<ide> import Head from 'next/head'
<ide> import initApollo from './initApollo'
<ide>
<ide> function parseCookies (req, options = {}) {
<del> return cookie.parse(
<del> req ? req.headers.cookie || '' : document.cookie,
<del> options
<del> )
<add> return cookie.parse(req ? req.headers.cookie || '' : document.cookie, options)
<ide> }
<ide>
<ide> export default App => {
<ide> export default App => {
<ide> }
<ide>
<ide> static async getInitialProps (ctx) {
<del> const { Component, router, ctx: { req, res } } = ctx
<del> const apollo = initApollo({}, {
<del> getToken: () => parseCookies(req).token
<del> })
<add> const {
<add> Component,
<add> router,
<add> ctx: { req, res }
<add> } = ctx
<add> const apollo = initApollo(
<add> {},
<add> {
<add> getToken: () => parseCookies(req).token
<add> }
<add> )
<ide>
<ide> ctx.ctx.apolloClient = apollo
<ide>
<ide><path>examples/with-apollo-auth/pages/_app.js
<ide> import withApollo from '../lib/withApollo'
<ide> class MyApp extends App {
<ide> render () {
<ide> const { Component, pageProps, apolloClient } = this.props
<del> return <Container>
<del> <ApolloProvider client={apolloClient}>
<del> <Component {...pageProps} />
<del> </ApolloProvider>
<del> </Container>
<add> return (
<add> <Container>
<add> <ApolloProvider client={apolloClient}>
<add> <Component {...pageProps} />
<add> </ApolloProvider>
<add> </Container>
<add> )
<ide> }
<ide> }
<ide>
<ide><path>examples/with-apollo-auth/pages/create-account.js
<ide> export default class CreateAccount extends React.Component {
<ide> {/* RegisterBox handles all register logic. */}
<ide> <RegisterBox />
<ide> <hr />
<del> Already have an account? <Link prefetch href='/signin'><a>Sign in</a></Link>
<add> Already have an account?{' '}
<add> <Link prefetch href='/signin'>
<add> <a>Sign in</a>
<add> </Link>
<ide> </React.Fragment>
<ide> )
<ide> }
<del>};
<add>}
<ide><path>examples/with-apollo-auth/pages/index.js
<ide> export default class Index extends React.Component {
<ide> </ApolloConsumer>
<ide> )
<ide> }
<del>};
<add>}
<ide><path>examples/with-apollo-auth/pages/signin.js
<ide> export default class Signin extends React.Component {
<ide> {/* SigninBox handles all login logic. */}
<ide> <SigninBox />
<ide> <hr />
<del> New? <Link prefetch href='/create-account'><a>Create account</a></Link>
<add> New?{' '}
<add> <Link prefetch href='/create-account'>
<add> <a>Create account</a>
<add> </Link>
<ide> </React.Fragment>
<ide> )
<ide> }
<del>};
<add>}
<ide><path>examples/with-apollo/lib/with-apollo-client.js
<ide> import initApollo from './init-apollo'
<ide> import Head from 'next/head'
<ide> import { getDataFromTree } from 'react-apollo'
<ide>
<del>export default (App) => {
<add>export default App => {
<ide> return class Apollo extends React.Component {
<ide> static displayName = 'withApollo(App)'
<ide> static async getInitialProps (ctx) {
<ide><path>examples/with-apollo/pages/_app.js
<del>import App, {Container} from 'next/app'
<add>import App, { Container } from 'next/app'
<ide> import React from 'react'
<ide> import withApolloClient from '../lib/with-apollo-client'
<ide> import { ApolloProvider } from 'react-apollo'
<ide>
<ide> class MyApp extends App {
<ide> render () {
<del> const {Component, pageProps, apolloClient} = this.props
<del> return <Container>
<del> <ApolloProvider client={apolloClient}>
<del> <Component {...pageProps} />
<del> </ApolloProvider>
<del> </Container>
<add> const { Component, pageProps, apolloClient } = this.props
<add> return (
<add> <Container>
<add> <ApolloProvider client={apolloClient}>
<add> <Component {...pageProps} />
<add> </ApolloProvider>
<add> </Container>
<add> )
<ide> }
<ide> }
<ide>
<ide><path>examples/with-apollo/pages/about.js
<ide> export default () => (
<ide> <article>
<ide> <h1>The Idea Behind This Example</h1>
<ide> <p>
<del> <a href='https://www.apollographql.com/client/'>Apollo</a> is a GraphQL client that
<del> allows you to easily query the exact data you need from a GraphQL
<del> server. In addition to fetching and mutating data, Apollo analyzes your
<del> queries and their results to construct a client-side cache of your data,
<del> which is kept up to date as further queries and mutations are run,
<del> fetching more results from the server.
<add> <a href='https://www.apollographql.com/client/'>Apollo</a> is a GraphQL
<add> client that allows you to easily query the exact data you need from a
<add> GraphQL server. In addition to fetching and mutating data, Apollo
<add> analyzes your queries and their results to construct a client-side cache
<add> of your data, which is kept up to date as further queries and mutations
<add> are run, fetching more results from the server.
<ide> </p>
<ide> <p>
<ide> In this simple example, we integrate Apollo seamlessly with{' '}
<ide> <a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages
<ide> inside a{' '}
<ide> <a href='https://facebook.github.io/react/docs/higher-order-components.html'>
<ide> higher-order component (HOC)
<del> </a>. Using the HOC pattern we're able to pass down a central store of
<del> query result data created by Apollo into our React component hierarchy
<del> defined inside each page of our Next application.
<add> </a>
<add> . Using the HOC pattern we're able to pass down a central store of query
<add> result data created by Apollo into our React component hierarchy defined
<add> inside each page of our Next application.
<ide> </p>
<ide> <p>
<ide> On initial page load, while on the server and inside getInitialProps, we
<ide> invoke the Apollo method,{' '}
<ide> <a href='https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree'>
<ide> getDataFromTree
<del> </a>. This method returns a promise; at the point in which the promise
<add> </a>
<add> . This method returns a promise; at the point in which the promise
<ide> resolves, our Apollo Client store is completely initialized.
<ide> </p>
<ide> <p>
<ide><path>examples/with-app-layout/pages/_app.js
<ide> import React from 'react'
<del>import App, {Container} from 'next/app'
<add>import App, { Container } from 'next/app'
<ide>
<ide> class Layout extends React.Component {
<ide> render () {
<del> const {children} = this.props
<del> return <div className='layout'>
<del> {children}
<del> </div>
<add> const { children } = this.props
<add> return <div className='layout'>{children}</div>
<ide> }
<ide> }
<ide>
<ide> export default class MyApp extends App {
<ide> render () {
<del> const {Component, pageProps} = this.props
<del> return <Container>
<del> <Layout>
<del> <Component {...pageProps} />
<del> </Layout>
<del> </Container>
<add> const { Component, pageProps } = this.props
<add> return (
<add> <Container>
<add> <Layout>
<add> <Component {...pageProps} />
<add> </Layout>
<add> </Container>
<add> )
<ide> }
<ide> }
<ide><path>examples/with-asset-imports/pages/index.js
<ide> import avatar from '../static/logo.png'
<ide>
<del>export default () =>
<del> <img src={avatar} />
<add>export default () => <img src={avatar} />
<ide><path>examples/with-babel-macros/pages/_document.js
<ide> import React from 'react'
<del>import Document, {Head, Main, NextScript} from 'next/document'
<add>import Document, { Head, Main, NextScript } from 'next/document'
<ide>
<ide> export default class MyDocument extends Document {
<ide> render () {
<ide> return (
<ide> <html>
<ide> <Head>
<del> <style dangerouslySetInnerHTML={{__html: this.props.css}} />
<add> <style dangerouslySetInnerHTML={{ __html: this.props.css }} />
<ide> </Head>
<ide> <body>
<ide> <Main />
<ide><path>examples/with-babel-macros/pages/index.js
<ide> export default WhoAmI
<ide>
<ide> function WhoAmI () {
<ide> return (
<del> <div style={{display: 'flex', justifyContent: 'center'}}>
<add> <div style={{ display: 'flex', justifyContent: 'center' }}>
<ide> <h1>
<del> <pre>
<del> whoami: {whoami}
<del> </pre>
<add> <pre>whoami: {whoami}</pre>
<ide> </h1>
<ide> </div>
<ide> )
<ide><path>examples/with-carbon-components/next.config.js
<ide> const withSass = require('@zeit/next-sass')
<ide> const withImages = require('next-images')
<ide>
<del>module.exports = withImages(withSass({
<del> webpack (config) {
<del> config.module.rules.push({
<del> test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
<del> use: {
<del> loader: 'url-loader',
<del> options: {
<del> limit: 100000,
<del> publicPath: './',
<del> outputPath: 'static/',
<del> name: '[name].[ext]'
<add>module.exports = withImages(
<add> withSass({
<add> webpack (config) {
<add> config.module.rules.push({
<add> test: /\.(png|svg|eot|otf|ttf|woff|woff2)$/,
<add> use: {
<add> loader: 'url-loader',
<add> options: {
<add> limit: 100000,
<add> publicPath: './',
<add> outputPath: 'static/',
<add> name: '[name].[ext]'
<add> }
<ide> }
<del> }
<del> })
<add> })
<ide>
<del> return config
<del> }
<del>}))
<add> return config
<add> }
<add> })
<add>)
<ide><path>examples/with-carbon-components/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> return (
<ide> <html>
<ide> <Head>
<del> <link
<del> rel='stylesheet'
<del> href='/_next/static/style.css'
<del> />
<add> <link rel='stylesheet' href='/_next/static/style.css' />
<ide> </Head>
<ide> <body>
<ide> <Main />
<ide><path>examples/with-cerebral/components/Clock.js
<del>export default (props) => {
<add>export default props => {
<ide> return (
<ide> <div className={props.light ? 'light' : ''}>
<ide> {format(new Date(props.lastUpdate))}
<ide> <style jsx>{`
<ide> div {
<ide> padding: 15px;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> display: inline-block;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> export default (props) => {
<ide> )
<ide> }
<ide>
<del>const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<add>const format = t =>
<add> `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<ide>
<del>const pad = n => n < 10 ? `0${n}` : n
<add>const pad = n => (n < 10 ? `0${n}` : n)
<ide><path>examples/with-cerebral/components/Page.js
<ide> import { connect } from '@cerebral/react'
<ide> import { state, signal } from 'cerebral/tags'
<ide> import Clock from './Clock'
<ide>
<del>export default connect({
<del> lastUpdate: state`clock.lastUpdate`,
<del> light: state`clock.light`,
<del> mounted: signal`clock.mounted`,
<del> unMounted: signal`clock.unMounted`
<del>},
<del>class Page extends React.Component {
<del> componentDidMount () {
<del> this.props.mounted()
<del> }
<add>export default connect(
<add> {
<add> lastUpdate: state`clock.lastUpdate`,
<add> light: state`clock.light`,
<add> mounted: signal`clock.mounted`,
<add> unMounted: signal`clock.unMounted`
<add> },
<add> class Page extends React.Component {
<add> componentDidMount () {
<add> this.props.mounted()
<add> }
<ide>
<del> componentWillUnmount () {
<del> this.props.unMounted()
<del> }
<del> render () {
<del> return (
<del> <div>
<del> <h1>{this.props.title}</h1>
<del> <Clock lastUpdate={this.props.lastUpdate} light={this.props.light} />
<del> <nav>
<del> <Link href={this.props.linkTo}><a>Navigate</a></Link>
<del> </nav>
<del> </div>
<del> )
<add> componentWillUnmount () {
<add> this.props.unMounted()
<add> }
<add> render () {
<add> return (
<add> <div>
<add> <h1>{this.props.title}</h1>
<add> <Clock lastUpdate={this.props.lastUpdate} light={this.props.light} />
<add> <nav>
<add> <Link href={this.props.linkTo}>
<add> <a>Navigate</a>
<add> </Link>
<add> </nav>
<add> </div>
<add> )
<add> }
<ide> }
<del>}
<ide> )
<ide><path>examples/with-cerebral/modules/clock/actions.js
<del>export function startTimer ({clock}) {
<add>export function startTimer ({ clock }) {
<ide> clock.start('clock.secondTicked')
<ide> }
<ide>
<del>export function stopTimer ({clock}) {
<add>export function stopTimer ({ clock }) {
<ide> clock.stop()
<ide> }
<ide><path>examples/with-cerebral/modules/clock/index.js
<del>
<del>import {mounted, unMounted, secondTicked} from './signals'
<add>import { mounted, unMounted, secondTicked } from './signals'
<ide> import provider from './provider'
<ide>
<ide> export default {
<ide><path>examples/with-cerebral/modules/clock/provider.js
<ide> const SECOND = 1000
<ide> let timer = null
<ide>
<del>export default (context) => {
<add>export default context => {
<ide> context.clock = {
<ide> start (signalPath) {
<ide> const signal = context.controller.getSignal(signalPath)
<ide>
<ide> function tick () {
<ide> const now = Date.now()
<ide>
<del> signal({now})
<add> signal({ now })
<ide>
<ide> timer = setTimeout(tick, SECOND - (now % SECOND))
<ide> }
<ide><path>examples/with-cerebral/modules/clock/signals.js
<del>import {set} from 'cerebral/operators'
<del>import {state, props} from 'cerebral/tags'
<del>import {startTimer, stopTimer} from './actions'
<add>import { set } from 'cerebral/operators'
<add>import { state, props } from 'cerebral/tags'
<add>import { startTimer, stopTimer } from './actions'
<ide>
<del>export const mounted = [
<del> startTimer,
<del> set(state`clock.light`, true)
<del>]
<add>export const mounted = [startTimer, set(state`clock.light`, true)]
<ide> export const unMounted = stopTimer
<ide> export const secondTicked = set(state`clock.lastUpdate`, props`now`)
<ide><path>examples/with-cerebral/pages/index.js
<ide> import React from 'react'
<del>import {Controller, UniversalController} from 'cerebral'
<add>import { Controller, UniversalController } from 'cerebral'
<ide> import Devtools from 'cerebral/devtools'
<ide> import { Container } from '@cerebral/react'
<ide> import Page from '../components/Page'
<ide> import clock from '../modules/clock'
<ide>
<ide> export default class Counter extends React.Component {
<del> static getInitialProps ({req}) {
<add> static getInitialProps ({ req }) {
<ide> const isServer = Boolean(req)
<ide>
<ide> // On the server we prepare the state of the application. Since
<ide> // this is a synchronous state change we just use "setState", but
<ide> // you could do other async stuff here or even use "runSequence" to
<ide> // grab and set the initial state of the application using
<ide> if (isServer) {
<del> const controller = UniversalController({modules: {clock}})
<add> const controller = UniversalController({ modules: { clock } })
<ide> controller.setState('clock.lastUpdate', Date.now())
<ide>
<ide> return { stateChanges: controller.getChanges() }
<ide> export default class Counter extends React.Component {
<ide> // The controller will be instantiated for every page change and we only
<ide> // add the devtools if we indeed are running in the browser
<ide> this.controller = Controller({
<del> devtools: process.env.NODE_ENV === 'production' || typeof window === 'undefined' ? null : Devtools({host: 'localhost:8787'}),
<del> modules: {clock},
<add> devtools:
<add> process.env.NODE_ENV === 'production' || typeof window === 'undefined'
<add> ? null
<add> : Devtools({ host: 'localhost:8787' }),
<add> modules: { clock },
<ide> stateChanges: props.stateChanges
<ide> })
<ide> }
<ide><path>examples/with-cerebral/pages/other.js
<ide> import React from 'react'
<del>import {Controller, UniversalController} from 'cerebral'
<add>import { Controller, UniversalController } from 'cerebral'
<ide> import Devtools from 'cerebral/devtools'
<ide> import { Container } from '@cerebral/react'
<ide> import Page from '../components/Page'
<ide> import clock from '../modules/clock'
<ide>
<ide> export default class Counter extends React.Component {
<del> static getInitialProps ({req}) {
<add> static getInitialProps ({ req }) {
<ide> const isServer = Boolean(req)
<ide>
<ide> // On the server we prepare the state of the application. Since
<ide> // this is a synchronous state change we just use "setState", but
<ide> // you could do other async stuff here or even use "runSequence" to
<ide> // grab and set the initial state of the application using
<ide> if (isServer) {
<del> const controller = UniversalController({modules: {clock}})
<add> const controller = UniversalController({ modules: { clock } })
<ide> controller.setState('clock.lastUpdate', Date.now())
<ide>
<ide> return { stateChanges: controller.getChanges() }
<ide> export default class Counter extends React.Component {
<ide> // The controller will be instantiated for every page change and we only
<ide> // add the devtools if we indeed are running in the browser
<ide> this.controller = Controller({
<del> devtools: process.env.NODE_ENV === 'production' || typeof window === 'undefined' ? null : Devtools({host: 'localhost:8787'}),
<del> modules: {clock},
<add> devtools:
<add> process.env.NODE_ENV === 'production' || typeof window === 'undefined'
<add> ? null
<add> : Devtools({ host: 'localhost:8787' }),
<add> modules: { clock },
<ide> stateChanges: props.stateChanges
<ide> })
<ide> }
<ide><path>examples/with-configured-preset-env/pages/index.js
<del>import {Component} from 'react'
<add>import { Component } from 'react'
<ide>
<ide> function * generatorMethod () {
<ide> yield 1
<ide><path>examples/with-custom-babel-config/pages/index.js
<ide> export default class MyLuckNo extends React.Component {
<ide> const { randomNo } = this.state
<ide>
<ide> if (randomNo === null) {
<del> return (<p>Please wait..</p>)
<add> return <p>Please wait..</p>
<ide> }
<ide>
<ide> // This is an experimental JavaScript feature where we can get with
<ide> // using babel-preset-stage-0
<ide> const message = do {
<ide> if (randomNo < 30) {
<ide> // eslint-disable-next-line no-unused-expressions
<del> 'Do not give up. Try again.'
<add> ;('Do not give up. Try again.')
<ide> } else if (randomNo < 60) {
<ide> // eslint-disable-next-line no-unused-expressions
<del> 'You are a lucky guy'
<add> ;('You are a lucky guy')
<ide> } else {
<ide> // eslint-disable-next-line no-unused-expressions
<del> 'You are soooo lucky!'
<add> ;('You are soooo lucky!')
<ide> }
<ide> }
<ide>
<ide><path>examples/with-custom-reverse-proxy/pages/index.js
<ide> export default class extends React.Component {
<ide> return (
<ide> <content>
<ide> <p>
<del> /api/{this.props.queryString} routed to https://swapi.co/api/{this.props.queryString}
<add> /api/{this.props.queryString} routed to https://swapi.co/api/
<add> {this.props.queryString}
<ide> </p>
<ide> <p>
<ide> <a href='?people/2'>Try</a>
<ide>
<ide> <a href='/'>Reset</a>
<ide> </p>
<del> <pre>
<del> {this.state.response ? this.state.response : 'Loading...'}
<del> </pre>
<add> <pre>{this.state.response ? this.state.response : 'Loading...'}</pre>
<ide> </content>
<ide> )
<ide> }
<ide><path>examples/with-custom-reverse-proxy/server.js
<ide> const next = require('next')
<ide> const devProxy = {
<ide> '/api': {
<ide> target: 'https://swapi.co/api/',
<del> pathRewrite: {'^/api': '/'},
<add> pathRewrite: { '^/api': '/' },
<ide> changeOrigin: true
<ide> }
<ide> }
<ide><path>examples/with-cxs/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> return (
<ide> <html>
<ide> <Head>
<del> <style id='cxs-style' dangerouslySetInnerHTML={{ __html: this.props.style }} />
<add> <style
<add> id='cxs-style'
<add> dangerouslySetInnerHTML={{ __html: this.props.style }}
<add> />
<ide> </Head>
<ide> <body>
<ide> <Main />
<ide><path>examples/with-data-prefetch/components/link.js
<ide> import { execOnce, warn } from 'next/dist/lib/utils'
<ide> import exact from 'prop-types-exact'
<ide> import { format, resolve, parse } from 'url'
<ide>
<del>export const prefetch = async (href) => {
<add>export const prefetch = async href => {
<ide> // if we're running server side do nothing
<ide> if (typeof window === 'undefined') return
<ide>
<del> const url =
<del> typeof href !== 'string'
<del> ? format(href)
<del> : href
<add> const url = typeof href !== 'string' ? format(href) : href
<ide>
<ide> const { pathname } = window.location
<ide>
<ide> const parsedHref = resolve(pathname, url)
<ide>
<del> const { query } =
<del> typeof href !== 'string'
<del> ? href
<del> : parse(url, true)
<add> const { query } = typeof href !== 'string' ? href : parse(url, true)
<ide>
<ide> const Component = await Router.prefetch(parsedHref)
<ide>
<ide> export default class LinkWithData extends Link {
<ide> const value = props[propName]
<ide>
<ide> if (typeof value === 'string') {
<del> execOnce(warn)(`Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>`)
<add> execOnce(warn)(
<add> `Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>`
<add> )
<ide> }
<ide>
<ide> return null
<ide> }
<ide> ]).isRequired,
<ide> withData: PropTypes.bool // our custom prop
<del> });
<add> })
<ide>
<ide> // our custom prefetch method
<ide> async prefetch () {
<ide><path>examples/with-data-prefetch/pages/index.js
<ide> export default () => (
<ide> </Link>
<ide> </li>
<ide> <li>
<del> <Link href='/article?id=3' >
<del> <a onMouseOver={e => prefetch('/article?id=3')} >Article 3</a>
<add> <Link href='/article?id=3'>
<add> <a onMouseOver={e => prefetch('/article?id=3')}>Article 3</a>
<ide> </Link>
<ide> </li>
<ide> </ul>
<ide><path>examples/with-docker/next.config.js
<ide> // next.config.js
<ide> module.exports = {
<del> serverRuntimeConfig: { // Will only be available on the server side
<add> serverRuntimeConfig: {
<add> // Will only be available on the server side
<ide> mySecret: 'secret'
<ide> },
<del> publicRuntimeConfig: { // Will be available on both server and client
<add> publicRuntimeConfig: {
<add> // Will be available on both server and client
<ide> API_URL: process.env.API_URL
<ide> }
<ide> }
<ide><path>examples/with-docker/pages/index.js
<ide> export default class extends React.Component {
<ide> }
<ide>
<ide> render () {
<del> return <div>
<del> The API_URL is {API_URL}
<del> </div>
<add> return <div>The API_URL is {API_URL}</div>
<ide> }
<ide> }
<ide><path>examples/with-dotenv/next.config.js
<ide> const path = require('path')
<ide> const Dotenv = require('dotenv-webpack')
<ide>
<ide> module.exports = {
<del> webpack: (config) => {
<add> webpack: config => {
<ide> config.plugins = config.plugins || []
<ide>
<ide> config.plugins = [
<ide><path>examples/with-dotenv/pages/index.js
<del>export default () => (
<del> <div>{ process.env.TEST }</div>
<del>)
<add>export default () => <div>{process.env.TEST}</div>
<ide><path>examples/with-draft-js/pages/index.js
<ide> export default class App extends React.Component {
<ide> }
<ide>
<ide> this.focus = () => this.editor.focus()
<del> this.onChange = (editorState) => this.setState({editorState})
<add> this.onChange = editorState => this.setState({ editorState })
<ide> }
<ide>
<ide> onClickEditor = () => {
<ide> export default class App extends React.Component {
<ide>
<ide> // 2- Identify the selection coordinates
<ide> setSelectionXY = () => {
<del> var r = window.getSelection().getRangeAt(0).getBoundingClientRect()
<add> var r = window
<add> .getSelection()
<add> .getRangeAt(0)
<add> .getBoundingClientRect()
<ide> var relative = document.body.parentNode.getBoundingClientRect()
<ide> // 2-a Set the selection coordinates in the state
<del> this.setState({
<del> selectionCoordinates: r,
<del> windowWidth: relative.width,
<del> selectionMeasures: {
<del> w: r.width,
<del> h: r.height
<del> }
<del> }, () => this.showToolbar())
<add> this.setState(
<add> {
<add> selectionCoordinates: r,
<add> windowWidth: relative.width,
<add> selectionMeasures: {
<add> w: r.width,
<add> h: r.height
<add> }
<add> },
<add> () => this.showToolbar()
<add> )
<ide> }
<ide>
<ide> // 3- Show the toolbar
<ide> showToolbar = () => {
<del> this.setState({
<del> showToolbar: true
<del> }, () => this.measureToolbar())
<add> this.setState(
<add> {
<add> showToolbar: true
<add> },
<add> () => this.measureToolbar()
<add> )
<ide> }
<ide>
<ide> // 4- The toolbar was hidden until now
<ide> measureToolbar = () => {
<ide> // 4-a Define the toolbar width and height, as it is now visible
<del> this.setState({
<del> toolbarMeasures: {
<del> w: this.elemWidth,
<del> h: this.elemHeight
<del> }
<del> }, () => this.setToolbarXY())
<add> this.setState(
<add> {
<add> toolbarMeasures: {
<add> w: this.elemWidth,
<add> h: this.elemHeight
<add> }
<add> },
<add> () => this.setToolbarXY()
<add> )
<ide> }
<ide>
<ide> // 5- Now that we have all measures, define toolbar coordinates
<ide> setToolbarXY = () => {
<ide> let coordinates = {}
<ide>
<del> const { selectionMeasures, selectionCoordinates, toolbarMeasures, windowWidth } = this.state
<add> const {
<add> selectionMeasures,
<add> selectionCoordinates,
<add> toolbarMeasures,
<add> windowWidth
<add> } = this.state
<ide>
<ide> const hiddenTop = selectionCoordinates.y < toolbarMeasures.h
<del> const hiddenRight = windowWidth - selectionCoordinates.x < toolbarMeasures.w / 2
<add> const hiddenRight =
<add> windowWidth - selectionCoordinates.x < toolbarMeasures.w / 2
<ide> const hiddenLeft = selectionCoordinates.x < toolbarMeasures.w / 2
<ide>
<del> const normalX = selectionCoordinates.x - (toolbarMeasures.w / 2) + (selectionMeasures.w / 2)
<add> const normalX =
<add> selectionCoordinates.x - toolbarMeasures.w / 2 + selectionMeasures.w / 2
<ide> const normalY = selectionCoordinates.y - toolbarMeasures.h
<ide>
<ide> const invertedY = selectionCoordinates.y + selectionMeasures.h
<ide> export default class App extends React.Component {
<ide> })
<ide> }
<ide>
<del> handleKeyCommand = (command) => {
<del> const {editorState} = this.state
<add> handleKeyCommand = command => {
<add> const { editorState } = this.state
<ide> const newState = RichUtils.handleKeyCommand(editorState, command)
<ide> if (newState) {
<ide> this.onChange(newState)
<ide> export default class App extends React.Component {
<ide> return false
<ide> }
<ide>
<del> toggleToolbar = (inlineStyle) => {
<add> toggleToolbar = inlineStyle => {
<ide> this.onChange(
<del> RichUtils.toggleInlineStyle(
<del> this.state.editorState,
<del> inlineStyle
<del> )
<add> RichUtils.toggleInlineStyle(this.state.editorState, inlineStyle)
<ide> )
<ide> }
<ide>
<ide> render () {
<del> const {editorState} = this.state
<add> const { editorState } = this.state
<ide> // Make sure we're not on the ssr
<ide> if (typeof window !== 'undefined') {
<ide> // Let's stick the toolbar to the selection
<ide> export default class App extends React.Component {
<ide> return (
<ide> <div>
<ide> <div
<del> ref={(elem) => {
<add> ref={elem => {
<ide> this.elemWidth = elem ? elem.clientWidth : 0
<ide> this.elemHeight = elem ? elem.clientHeight : 0
<ide> }}
<ide> style={toolbarStyle}
<ide> >
<del> <ToolBar
<del> editorState={editorState}
<del> onToggle={this.toggleToolbar}
<del> />
<add> <ToolBar editorState={editorState} onToggle={this.toggleToolbar} />
<ide> </div>
<ide> <div onClick={this.onClickEditor} onBlur={this.checkSelectedText}>
<ide> <Editor
<ide> export default class App extends React.Component {
<ide> onChange={this.onChange}
<ide> placeholder='Tell a story...'
<ide> spellCheck={false}
<del> ref={(element) => { this.editor = element }}
<add> ref={element => {
<add> this.editor = element
<add> }}
<ide> />
<ide> </div>
<ide> <div style={{ marginTop: 40 }}>
<del> <button onClick={() => this.setState({showRawData: !this.state.showRawData})}>
<add> <button
<add> onClick={() =>
<add> this.setState({ showRawData: !this.state.showRawData })
<add> }
<add> >
<ide> {!this.state.showRawData ? 'Show' : 'Hide'} Raw Data
<del> </button><br />
<del> {this.state.showRawData && JSON.stringify(convertToRaw(editorState.getCurrentContent()))}
<add> </button>
<add> <br />
<add> {this.state.showRawData &&
<add> JSON.stringify(convertToRaw(editorState.getCurrentContent()))}
<ide> </div>
<ide> </div>
<ide> )
<ide> const styleMap = {
<ide> class ToolbarButton extends React.Component {
<ide> constructor () {
<ide> super()
<del> this.onToggle = (e) => {
<add> this.onToggle = e => {
<ide> e.preventDefault()
<ide> this.props.onToggle(this.props.style)
<ide> }
<ide> class ToolbarButton extends React.Component {
<ide> }
<ide> return (
<ide> <span onMouseDown={this.onToggle} style={buttonStyle}>
<del> { this.props.label }
<add> {this.props.label}
<ide> </span>
<ide> )
<ide> }
<ide> }
<ide>
<ide> var toolbarItems = [
<del> {label: 'Bold', style: 'BOLD'},
<del> {label: 'Italic', style: 'ITALIC'},
<del> {label: 'Underline', style: 'UNDERLINE'},
<del> {label: 'Code', style: 'CODE'},
<del> {label: 'Surprise', style: 'ANYCUSTOMSTYLE'}
<add> { label: 'Bold', style: 'BOLD' },
<add> { label: 'Italic', style: 'ITALIC' },
<add> { label: 'Underline', style: 'UNDERLINE' },
<add> { label: 'Code', style: 'CODE' },
<add> { label: 'Surprise', style: 'ANYCUSTOMSTYLE' }
<ide> ]
<ide>
<del>const ToolBar = (props) => {
<add>const ToolBar = props => {
<ide> var currentStyle = props.editorState.getCurrentInlineStyle()
<ide> return (
<ide> <div>
<del> {toolbarItems.map(toolbarItem =>
<add> {toolbarItems.map(toolbarItem => (
<ide> <ToolbarButton
<ide> key={toolbarItem.label}
<ide> active={currentStyle.has(toolbarItem.style)}
<ide> label={toolbarItem.label}
<ide> onToggle={props.onToggle}
<ide> style={toolbarItem.style}
<ide> />
<del> )}
<add> ))}
<ide> </div>
<ide> )
<ide> }
<ide>
<del>const initialData = {'blocks': [{'key': '16d0k', 'text': 'You can edit this text.', 'type': 'unstyled', 'depth': 0, 'inlineStyleRanges': [{'offset': 0, 'length': 23, 'style': 'BOLD'}], 'entityRanges': [], 'data': {}}, {'key': '98peq', 'text': '', 'type': 'unstyled', 'depth': 0, 'inlineStyleRanges': [], 'entityRanges': [], 'data': {}}, {'key': 'ecmnc', 'text': 'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.', 'type': 'unstyled', 'depth': 0, 'inlineStyleRanges': [{'offset': 0, 'length': 14, 'style': 'BOLD'}, {'offset': 133, 'length': 9, 'style': 'BOLD'}], 'entityRanges': [], 'data': {}}, {'key': 'fe2gn', 'text': '', 'type': 'unstyled', 'depth': 0, 'inlineStyleRanges': [], 'entityRanges': [], 'data': {}}, {'key': '4481k', 'text': 'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.', 'type': 'unstyled', 'depth': 0, 'inlineStyleRanges': [{'offset': 34, 'length': 19, 'style': 'BOLD'}, {'offset': 117, 'length': 4, 'style': 'BOLD'}, {'offset': 68, 'length': 10, 'style': 'ANYCUSTOMSTYLE'}], 'entityRanges': [], 'data': {}}], 'entityMap': {}}
<add>const initialData = {
<add> blocks: [
<add> {
<add> key: '16d0k',
<add> text: 'You can edit this text.',
<add> type: 'unstyled',
<add> depth: 0,
<add> inlineStyleRanges: [{ offset: 0, length: 23, style: 'BOLD' }],
<add> entityRanges: [],
<add> data: {}
<add> },
<add> {
<add> key: '98peq',
<add> text: '',
<add> type: 'unstyled',
<add> depth: 0,
<add> inlineStyleRanges: [],
<add> entityRanges: [],
<add> data: {}
<add> },
<add> {
<add> key: 'ecmnc',
<add> text:
<add> 'Luke Skywalker has vanished. In his absence, the sinister FIRST ORDER has risen from the ashes of the Empire and will not rest until Skywalker, the last Jedi, has been destroyed.',
<add> type: 'unstyled',
<add> depth: 0,
<add> inlineStyleRanges: [
<add> { offset: 0, length: 14, style: 'BOLD' },
<add> { offset: 133, length: 9, style: 'BOLD' }
<add> ],
<add> entityRanges: [],
<add> data: {}
<add> },
<add> {
<add> key: 'fe2gn',
<add> text: '',
<add> type: 'unstyled',
<add> depth: 0,
<add> inlineStyleRanges: [],
<add> entityRanges: [],
<add> data: {}
<add> },
<add> {
<add> key: '4481k',
<add> text:
<add> 'With the support of the REPUBLIC, General Leia Organa leads a brave RESISTANCE. She is desperate to find her brother Luke and gain his help in restoring peace and justice to the galaxy.',
<add> type: 'unstyled',
<add> depth: 0,
<add> inlineStyleRanges: [
<add> { offset: 34, length: 19, style: 'BOLD' },
<add> { offset: 117, length: 4, style: 'BOLD' },
<add> { offset: 68, length: 10, style: 'ANYCUSTOMSTYLE' }
<add> ],
<add> entityRanges: [],
<add> data: {}
<add> }
<add> ],
<add> entityMap: {}
<add>}
<ide><path>examples/with-dynamic-app-layout/layouts/BlueLayout.js
<ide> export default ({ children }) => {
<del> return <main style={{ border: '4px dashed blue' }}>
<del> {children}
<del> </main>
<add> return <main style={{ border: '4px dashed blue' }}>{children}</main>
<ide> }
<ide><path>examples/with-dynamic-app-layout/layouts/GreenLayout.js
<ide> export default ({ children }) => {
<del> return <main style={{ border: '4px dashed green' }}>
<del> {children}
<del> </main>
<add> return <main style={{ border: '4px dashed green' }}>{children}</main>
<ide> }
<ide><path>examples/with-dynamic-app-layout/layouts/RedLayout.js
<ide> export default ({ children }) => {
<del> return <main style={{ border: '4px dashed red' }}>
<del> {children}
<del> </main>
<add> return <main style={{ border: '4px dashed red' }}>{children}</main>
<ide> }
<ide><path>examples/with-dynamic-app-layout/pages/_app.js
<ide> import App, { Container } from 'next/app'
<ide> export default class MyApp extends App {
<ide> render () {
<ide> const { Component, pageProps } = this.props
<del> return <Container>
<del> <Component.Layout>
<del> <Component {...pageProps} />
<del> </Component.Layout>
<del> </Container>
<add> return (
<add> <Container>
<add> <Component.Layout>
<add> <Component {...pageProps} />
<add> </Component.Layout>
<add> </Container>
<add> )
<ide> }
<ide> }
<ide><path>examples/with-dynamic-app-layout/pages/green.js
<ide> import Link from 'next/link'
<ide> import GreenLayout from '../layouts/GreenLayout'
<ide>
<ide> const GreenPage = () => {
<del> return <p>
<del> This is the <strong style={{ color: 'green' }}>Green</strong> page, it's borders are green<br /><br />
<del> Go back to the <Link href='/'><a style={{ color: 'blue' }}>Blue Page</a></Link>
<del> </p>
<add> return (
<add> <p>
<add> This is the <strong style={{ color: 'green' }}>Green</strong> page, it's
<add> borders are green
<add> <br />
<add> <br />
<add> Go back to the{' '}
<add> <Link href='/'>
<add> <a style={{ color: 'blue' }}>Blue Page</a>
<add> </Link>
<add> </p>
<add> )
<ide> }
<ide>
<ide> GreenPage.Layout = GreenLayout
<ide><path>examples/with-dynamic-app-layout/pages/index.js
<ide> import Link from 'next/link'
<ide> import BlueLayout from '../layouts/BlueLayout'
<ide>
<ide> const BluePage = () => {
<del> return <p>
<del> This is the <strong style={{ color: 'blue' }}>Blue</strong> page, it's borders are blue<br /><br />
<del> Go to the <Link href='/red'><a style={{ color: 'red' }}>Red Page</a></Link><br /><br />
<del> Go to the <Link href='/green'><a style={{ color: 'green' }} >Green Page</a></Link>
<del> </p>
<add> return (
<add> <p>
<add> This is the <strong style={{ color: 'blue' }}>Blue</strong> page, it's
<add> borders are blue
<add> <br />
<add> <br />
<add> Go to the{' '}
<add> <Link href='/red'>
<add> <a style={{ color: 'red' }}>Red Page</a>
<add> </Link>
<add> <br />
<add> <br />
<add> Go to the{' '}
<add> <Link href='/green'>
<add> <a style={{ color: 'green' }}>Green Page</a>
<add> </Link>
<add> </p>
<add> )
<ide> }
<ide>
<ide> BluePage.Layout = BlueLayout
<ide><path>examples/with-dynamic-app-layout/pages/red.js
<ide> import Link from 'next/link'
<ide> import RedLayout from '../layouts/RedLayout'
<ide>
<ide> const RedPage = () => {
<del> return <p>
<del> This is the <strong style={{ color: 'red' }} >Red</strong> page, it's borders are red<br /><br />
<del> Go back to the <Link href='/'><a>Blue Page</a></Link>
<del> </p>
<add> return (
<add> <p>
<add> This is the <strong style={{ color: 'red' }}>Red</strong> page, it's
<add> borders are red
<add> <br />
<add> <br />
<add> Go back to the{' '}
<add> <Link href='/'>
<add> <a>Blue Page</a>
<add> </Link>
<add> </p>
<add> )
<ide> }
<ide>
<ide> RedPage.Layout = RedLayout
<ide><path>examples/with-dynamic-import/components/Header.js
<ide> import Link from 'next/link'
<ide> export default () => (
<ide> <div>
<ide> <Link href='/'>
<del> <a style={styles.a} >Home</a>
<add> <a style={styles.a}>Home</a>
<ide> </Link>
<ide>
<ide> <Link href='/about'>
<del> <a style={styles.a} >About</a>
<add> <a style={styles.a}>About</a>
<ide> </Link>
<ide> </div>
<ide> )
<ide><path>examples/with-dynamic-import/components/hello1.js
<del>export default () => (
<del> <p>Hello World 1 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 1 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/components/hello2.js
<del>export default () => (
<del> <p>Hello World 2 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 2 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/components/hello3.js
<del>export default () => (
<del> <p>Hello World 3 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 3 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/components/hello4.js
<del>export default () => (
<del> <p>Hello World 4 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 4 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/components/hello5.js
<del>export default () => (
<del> <p>Hello World 5 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 5 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/components/hello6.js
<del>export default () => (
<del> <p>Hello World 6 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 6 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/components/hello7.js
<del>export default () => (
<del> <p>Hello World 7 (imported dynamiclly) </p>
<del>)
<add>export default () => <p>Hello World 7 (imported dynamiclly) </p>
<ide><path>examples/with-dynamic-import/pages/index.js
<ide> const DynamicComponent1 = dynamic(import('../components/hello1'))
<ide>
<ide> const DynamicComponent2WithCustomLoading = dynamic({
<ide> loader: () => import('../components/hello2'),
<del> loading: () => (<p>Loading caused by client page transition ...</p>)
<add> loading: () => <p>Loading caused by client page transition ...</p>
<ide> })
<ide>
<ide> const DynamicComponent3WithNoSSR = dynamic({
<ide> loader: () => import('../components/hello3'),
<del> loading: () => (<p>Loading ...</p>),
<add> loading: () => <p>Loading ...</p>,
<ide> ssr: false
<ide> })
<ide>
<ide> const DynamicBundle = dynamic({
<ide> return components
<ide> },
<ide> render: (props, { Hello6, Hello7 }) => (
<del> <div style={{padding: 10, border: '1px solid #888'}}>
<add> <div style={{ padding: 10, border: '1px solid #888' }}>
<ide> <Hello6 />
<ide> <Hello7 />
<ide> </div>
<ide><path>examples/with-electron/renderer/pages/start.js
<ide> export default class extends Component {
<ide> <div>
<ide> <h1>Hello Electron!</h1>
<ide>
<del> {this.state.message &&
<del> <p>{this.state.message}</p>
<del> }
<add> {this.state.message && <p>{this.state.message}</p>}
<ide>
<ide> <form onSubmit={this.handleSubmit}>
<ide> <input type='text' onChange={this.handleChange} />
<ide><path>examples/with-emotion-fiber/features/home.component.js
<del>import {Basic, Combined, Animated, bounce} from '../shared/styles'
<add>import { Basic, Combined, Animated, bounce } from '../shared/styles'
<ide> const Home = () => (
<ide> <div>
<ide> <Basic>Cool Styles</Basic>
<ide><path>examples/with-emotion-fiber/hoc/withEmotion.component.js
<ide> const withEmotion = ComposedComponent => {
<ide> render () {
<ide> return <ComposedComponent />
<ide> }
<del> };
<add> }
<ide>
<ide> return HOC
<ide> }
<ide><path>examples/with-emotion-fiber/shared/styles.js
<ide> html, body {
<ide> `
<ide>
<ide> export const basicStyles = css`
<del>background-color: white;
<del>color: cornflowerblue;
<del>border: 1px solid lightgreen;
<del>border-right: none;
<del>border-bottom: none;
<del>box-shadow: 5px 5px 0 0 lightgreen, 10px 10px 0 0 lightyellow;
<del>transition: all 0.1s linear;
<del>margin: 3rem 0;
<del>padding: 1rem 0.5rem;
<add> background-color: white;
<add> color: cornflowerblue;
<add> border: 1px solid lightgreen;
<add> border-right: none;
<add> border-bottom: none;
<add> box-shadow: 5px 5px 0 0 lightgreen, 10px 10px 0 0 lightyellow;
<add> transition: all 0.1s linear;
<add> margin: 3rem 0;
<add> padding: 1rem 0.5rem;
<ide> `
<ide>
<ide> export const hoverStyles = css`
<del>&:hover {
<del>color: white;
<del>background-color: lightgray;
<del>border-color: aqua;
<del>box-shadow: -15px -15px 0 0 aqua, -30px -30px 0 0 cornflowerblue;
<del>}
<add> &:hover {
<add> color: white;
<add> background-color: lightgray;
<add> border-color: aqua;
<add> box-shadow: -15px -15px 0 0 aqua, -30px -30px 0 0 cornflowerblue;
<add> }
<ide> `
<ide> export const bounce = keyframes`
<ide> from {
<ide> transform: scale(0.99);
<ide> `
<ide>
<ide> export const Basic = styled('div')`
<del>${basicStyles};
<add> ${basicStyles};
<ide> `
<ide>
<ide> export const Combined = styled('div')`
<del>${basicStyles};
<del>${hoverStyles};
<del>& code {
<del> background-color: linen;
<del>}
<add> ${basicStyles};
<add> ${hoverStyles};
<add> & code {
<add> background-color: linen;
<add> }
<ide> `
<ide> export const Animated = styled('div')`
<del>${basicStyles};
<del>${hoverStyles};
<del>& code {
<del> background-color: linen;
<del>}
<del>animation: ${props => props.animation} 0.2s infinite ease-in-out alternate;
<add> ${basicStyles};
<add> ${hoverStyles};
<add> & code {
<add> background-color: linen;
<add> }
<add> animation: ${props => props.animation} 0.2s infinite ease-in-out alternate;
<ide> `
<ide><path>examples/with-external-styled-jsx-sass/pages/index.js
<ide> import styles from '../styles/style.scss'
<ide>
<del>export default () =>
<add>export default () => (
<ide> <div>
<ide> Hello World!
<ide> <style jsx>{styles}</style>
<ide> </div>
<add>)
<ide><path>examples/with-fela/FelaProvider.js
<ide> const clientRenderer = getFelaRenderer()
<ide> export default class FelaProvider extends Component {
<ide> static contextTypes = {
<ide> renderer: PropTypes.object
<del> };
<add> }
<ide>
<del> render () {
<add> render() {
<ide> if (this.context.renderer) {
<ide> return this.props.children
<ide> }
<ide>
<ide> const renderer = this.props.renderer || clientRenderer
<del> return (
<del> <Provider renderer={renderer}>
<del> {this.props.children}
<del> </Provider>
<del> )
<add> return <Provider renderer={renderer}>{this.props.children}</Provider>
<ide> }
<ide> }
<ide><path>examples/with-fela/getFelaRenderer.js
<ide> import webPreset from 'fela-preset-web'
<ide>
<ide> export default function getRenderer () {
<ide> return createRenderer({
<del> plugins: [
<del> ...webPreset
<del> ]
<add> plugins: [...webPreset]
<ide> })
<ide> }
<ide><path>examples/with-fela/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide>
<ide> return (
<ide> <html>
<del> <Head>
<del> {styleNodes}
<del> </Head>
<add> <Head>{styleNodes}</Head>
<ide> <body>
<ide> <Main />
<ide> <NextScript />
<ide><path>examples/with-firebase-authentication/pages/index.js
<ide> import 'isomorphic-unfetch'
<ide> import clientCredentials from '../credentials/client'
<ide>
<ide> export default class Index extends Component {
<del> static async getInitialProps ({req, query}) {
<add> static async getInitialProps ({ req, query }) {
<ide> const user = req && req.session ? req.session.decodedToken : null
<ide> // don't fetch anything from firebase if the user is not found
<ide> // const snap = user && await req.firebaseServer.database().ref('messages').once('value')
<ide> export default class Index extends Component {
<ide> firebase.auth().onAuthStateChanged(user => {
<ide> if (user) {
<ide> this.setState({ user: user })
<del> return user.getIdToken()
<del> .then((token) => {
<add> return user
<add> .getIdToken()
<add> .then(token => {
<ide> // eslint-disable-next-line no-undef
<ide> return fetch('/api/login', {
<ide> method: 'POST',
<ide> export default class Index extends Component {
<ide> credentials: 'same-origin',
<ide> body: JSON.stringify({ token })
<ide> })
<del> }).then((res) => this.addDbListener())
<add> })
<add> .then(res => this.addDbListener())
<ide> } else {
<ide> this.setState({ user: null })
<ide> // eslint-disable-next-line no-undef
<ide> export default class Index extends Component {
<ide> db.settings({
<ide> timestampsInSnapshots: true
<ide> })
<del> let unsubscribe = db.collection('messages').onSnapshot(querySnapshot => {
<del> var messages = {}
<del> querySnapshot.forEach(function (doc) {
<del> messages[doc.id] = doc.data()
<del> })
<del> if (messages) this.setState({ messages })
<del> }, (error) => {
<del> console.error(error)
<del> })
<add> let unsubscribe = db.collection('messages').onSnapshot(
<add> querySnapshot => {
<add> var messages = {}
<add> querySnapshot.forEach(function (doc) {
<add> messages[doc.id] = doc.data()
<add> })
<add> if (messages) this.setState({ messages })
<add> },
<add> error => {
<add> console.error(error)
<add> }
<add> )
<ide> this.setState({ unsubscribe })
<ide> }
<ide>
<ide> removeDbListener () {
<ide> // firebase.database().ref('messages').off()
<del> if (this.state.unsubscribe) { this.state.unsubscribe() }
<add> if (this.state.unsubscribe) {
<add> this.state.unsubscribe()
<add> }
<ide> }
<ide>
<ide> handleChange (event) {
<ide> export default class Index extends Component {
<ide> timestampsInSnapshots: true
<ide> })
<ide> const date = new Date().getTime()
<del> db.collection('messages').doc(`${date}`).set({
<del> id: date,
<del> text: this.state.value
<del> })
<add> db.collection('messages')
<add> .doc(`${date}`)
<add> .set({
<add> id: date,
<add> text: this.state.value
<add> })
<ide> this.setState({ value: '' })
<ide> }
<ide>
<ide> export default class Index extends Component {
<ide> render () {
<ide> const { user, value, messages } = this.state
<ide>
<del> return <div>
<del> {
<del> user
<del> ? <button onClick={this.handleLogout}>Logout</button>
<del> : <button onClick={this.handleLogin}>Login</button>
<del> }
<del> {
<del> user &&
<del> <div>
<del> <form onSubmit={this.handleSubmit}>
<del> <input
<del> type={'text'}
<del> onChange={this.handleChange}
<del> placeholder={'add message...'}
<del> value={value}
<del> />
<del> </form>
<del> <ul>
<del> {
<del> messages &&
<del> Object.keys(messages).map(key => <li key={key}>{messages[key].text}</li>)
<del> }
<del> </ul>
<del> </div>
<del> }
<del> </div>
<add> return (
<add> <div>
<add> {user ? (
<add> <button onClick={this.handleLogout}>Logout</button>
<add> ) : (
<add> <button onClick={this.handleLogin}>Login</button>
<add> )}
<add> {user && (
<add> <div>
<add> <form onSubmit={this.handleSubmit}>
<add> <input
<add> type={'text'}
<add> onChange={this.handleChange}
<add> placeholder={'add message...'}
<add> value={value}
<add> />
<add> </form>
<add> <ul>
<add> {messages &&
<add> Object.keys(messages).map(key => (
<add> <li key={key}>{messages[key].text}</li>
<add> ))}
<add> </ul>
<add> </div>
<add> )}
<add> </div>
<add> )
<ide> }
<ide> }
<ide><path>examples/with-firebase-authentication/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>const firebase = admin.initializeApp({
<del> credential: admin.credential.cert(require('./credentials/server')),
<del> databaseURL: '' // TODO database URL goes here
<del>}, 'server')
<add>const firebase = admin.initializeApp(
<add> {
<add> credential: admin.credential.cert(require('./credentials/server')),
<add> databaseURL: '' // TODO database URL goes here
<add> },
<add> 'server'
<add>)
<ide>
<del>app.prepare()
<del> .then(() => {
<del> const server = express()
<add>app.prepare().then(() => {
<add> const server = express()
<ide>
<del> server.use(bodyParser.json())
<del> server.use(session({
<add> server.use(bodyParser.json())
<add> server.use(
<add> session({
<ide> secret: 'geheimnis',
<ide> saveUninitialized: true,
<del> store: new FileStore({path: '/tmp/sessions', secret: 'geheimnis'}),
<add> store: new FileStore({ path: '/tmp/sessions', secret: 'geheimnis' }),
<ide> resave: false,
<ide> rolling: true,
<ide> httpOnly: true,
<ide> cookie: { maxAge: 604800000 } // week
<del> }))
<del>
<del> server.use((req, res, next) => {
<del> req.firebaseServer = firebase
<del> next()
<ide> })
<add> )
<ide>
<del> server.post('/api/login', (req, res) => {
<del> if (!req.body) return res.sendStatus(400)
<add> server.use((req, res, next) => {
<add> req.firebaseServer = firebase
<add> next()
<add> })
<ide>
<del> const token = req.body.token
<del> firebase.auth().verifyIdToken(token)
<del> .then((decodedToken) => {
<del> req.session.decodedToken = decodedToken
<del> return decodedToken
<del> })
<del> .then((decodedToken) => res.json({ status: true, decodedToken }))
<del> .catch((error) => res.json({ error }))
<del> })
<add> server.post('/api/login', (req, res) => {
<add> if (!req.body) return res.sendStatus(400)
<ide>
<del> server.post('/api/logout', (req, res) => {
<del> req.session.decodedToken = null
<del> res.json({ status: true })
<del> })
<add> const token = req.body.token
<add> firebase
<add> .auth()
<add> .verifyIdToken(token)
<add> .then(decodedToken => {
<add> req.session.decodedToken = decodedToken
<add> return decodedToken
<add> })
<add> .then(decodedToken => res.json({ status: true, decodedToken }))
<add> .catch(error => res.json({ error }))
<add> })
<ide>
<del> server.get('*', (req, res) => {
<del> return handle(req, res)
<del> })
<add> server.post('/api/logout', (req, res) => {
<add> req.session.decodedToken = null
<add> res.json({ status: true })
<add> })
<ide>
<del> server.listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add> server.get('*', (req, res) => {
<add> return handle(req, res)
<add> })
<add>
<add> server.listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/with-flow/pages/_app.js
<del>import App, {Container} from 'next/app'
<add>import App, { Container } from 'next/app'
<ide> import Link from 'next/link'
<ide> import React from 'react'
<ide>
<ide> export default class MyApp extends App {
<ide> pageProps = await Component.getInitialProps(ctx)
<ide> }
<ide>
<del> return {pageProps}
<add> return { pageProps }
<ide> }
<ide>
<ide> render () {
<del> const {Component, pageProps} = this.props
<add> const { Component, pageProps } = this.props
<ide> return (
<ide> <Container>
<ide> <header>
<ide> <nav>
<del> <Link href='/'><a>Home</a></Link>|
<del> <Link href='/about'><a>About</a></Link>|
<del> <Link href='/contact'><a>Contact</a></Link>
<add> <Link href='/'>
<add> <a>Home</a>
<add> </Link>
<add> |
<add> <Link href='/about'>
<add> <a>About</a>
<add> </Link>
<add> |
<add> <Link href='/contact'>
<add> <a>Contact</a>
<add> </Link>
<ide> </nav>
<ide> </header>
<ide>
<ide> <Component {...pageProps} />
<ide>
<del> <footer>
<del> I`m here to stay
<del> </footer>
<add> <footer>I`m here to stay</footer>
<ide> </Container>
<ide> )
<ide> }
<ide><path>examples/with-freactal/components/app.js
<ide> import React from 'react'
<ide> import { fetchUserRepos } from '../githubApi'
<ide> import provideStateFactory from '../provideState'
<ide>
<del>export default (Page) => {
<add>export default Page => {
<ide> const App = ({ serverState }) => {
<ide> const withState = provideStateFactory(serverState)
<ide> const PageWithState = withState(Page)
<ide><path>examples/with-freactal/githubApi.js
<ide> import 'isomorphic-unfetch'
<ide> const API_BASE_URL = 'https://api.github.com'
<ide>
<ide> export const fetchUserRepos = (username, page = 1) =>
<del> fetch(`${API_BASE_URL}/users/${username}/repos?page=${page}`)
<del> .then(response => response.json())
<add> fetch(`${API_BASE_URL}/users/${username}/repos?page=${page}`).then(response =>
<add> response.json()
<add> )
<ide><path>examples/with-freactal/pages/index.js
<ide> import React from 'react'
<ide> import { injectState } from 'freactal'
<ide> import app from '../components/app'
<ide>
<del>const Index = injectState(({ state: { ajaxStatus, githubReposList }, effects }) => {
<del> const fetchMore = () =>
<del> effects.fetchGithubReposList(githubReposList.username, githubReposList.page + 1)
<add>const Index = injectState(
<add> ({ state: { ajaxStatus, githubReposList }, effects }) => {
<add> const fetchMore = () =>
<add> effects.fetchGithubReposList(
<add> githubReposList.username,
<add> githubReposList.page + 1
<add> )
<ide>
<del> return (
<del> <div>
<del> <h1>{`List of @${githubReposList.username}'s repositories`}</h1>
<add> return (
<add> <div>
<add> <h1>{`List of @${githubReposList.username}'s repositories`}</h1>
<ide>
<del> <table>
<del> <thead>
<del> <tr>
<del> <th>name</th>
<del> <th>watchers</th>
<del> <th>stars</th>
<del> <th>forks</th>
<del> </tr>
<del> </thead>
<del> <tbody>
<del> {githubReposList.repos.map((repo) => (
<del> <tr key={repo.id}>
<del> <td>{repo.name}</td>
<del> <td>{repo.watchers_count}</td>
<del> <td>{repo.stargazers_count}</td>
<del> <td>{repo.forks_count}</td>
<add> <table>
<add> <thead>
<add> <tr>
<add> <th>name</th>
<add> <th>watchers</th>
<add> <th>stars</th>
<add> <th>forks</th>
<ide> </tr>
<del> ))}
<del> <tr>
<del> <td> </td>
<del> <td colSpan='3'>
<del> <button
<del> onClick={fetchMore}
<del> disabled={ajaxStatus}
<del> >{ajaxStatus ? 'loading' : 'fetch more'}</button>
<del> </td>
<del> </tr>
<del> </tbody>
<del> </table>
<del> </div>
<del> )
<del>})
<add> </thead>
<add> <tbody>
<add> {githubReposList.repos.map(repo => (
<add> <tr key={repo.id}>
<add> <td>{repo.name}</td>
<add> <td>{repo.watchers_count}</td>
<add> <td>{repo.stargazers_count}</td>
<add> <td>{repo.forks_count}</td>
<add> </tr>
<add> ))}
<add> <tr>
<add> <td> </td>
<add> <td colSpan='3'>
<add> <button onClick={fetchMore} disabled={ajaxStatus}>
<add> {ajaxStatus ? 'loading' : 'fetch more'}
<add> </button>
<add> </td>
<add> </tr>
<add> </tbody>
<add> </table>
<add> </div>
<add> )
<add> }
<add>)
<ide>
<ide> export default app(Index)
<ide><path>examples/with-freactal/provideState.js
<ide> import { provideState, update } from 'freactal'
<ide> import { fetchUserRepos } from './githubApi'
<ide>
<del>export default serverState => provideState({
<del> initialState: () => ({
<del> ...serverState,
<del> ajaxStatus: false
<del> }),
<add>export default serverState =>
<add> provideState({
<add> initialState: () => ({
<add> ...serverState,
<add> ajaxStatus: false
<add> }),
<ide>
<del> effects: {
<del> setAjaxLoader: update((state, ajaxStatus) => ({ ajaxStatus })),
<add> effects: {
<add> setAjaxLoader: update((state, ajaxStatus) => ({ ajaxStatus })),
<ide>
<del> fetchGithubReposList: (effects, username, page) =>
<del> effects.setAjaxLoader(true)
<del> .then(() => fetchUserRepos(username, page))
<del> .then((repos) => effects.setAjaxLoader(false).then(() => repos))
<del> .then((repos) => (state) => ({
<del> ...state,
<del> githubReposList: {
<del> username,
<del> page,
<del> repos: state.githubReposList.repos.concat(repos)
<del> }
<del> }))
<del> }
<del>})
<add> fetchGithubReposList: (effects, username, page) =>
<add> effects
<add> .setAjaxLoader(true)
<add> .then(() => fetchUserRepos(username, page))
<add> .then(repos => effects.setAjaxLoader(false).then(() => repos))
<add> .then(repos => state => ({
<add> ...state,
<add> githubReposList: {
<add> username,
<add> page,
<add> repos: state.githubReposList.repos.concat(repos)
<add> }
<add> }))
<add> }
<add> })
<ide><path>examples/with-glamorous/pages/index.js
<ide> if (typeof window !== 'undefined') {
<ide> }
<ide>
<ide> export default () => {
<del> css.global('html, body', { padding: '3rem 1rem', margin: 0, background: 'papayawhip', minHeight: '100%', fontFamily: 'Helvetica, Arial, sans-serif', fontSize: '24px' })
<add> css.global('html, body', {
<add> padding: '3rem 1rem',
<add> margin: 0,
<add> background: 'papayawhip',
<add> minHeight: '100%',
<add> fontFamily: 'Helvetica, Arial, sans-serif',
<add> fontSize: '24px'
<add> })
<ide>
<ide> const basicStyles = {
<ide> backgroundColor: 'white',
<ide> export default () => {
<ide>
<ide> return (
<ide> <div>
<del> <Basic>
<del> Cool Styles
<del> </Basic>
<add> <Basic>Cool Styles</Basic>
<ide> <Combined>
<ide> With <code>:hover</code>.
<ide> </Combined>
<del> <Animated>
<del> Let's bounce.
<del> </Animated>
<add> <Animated>Let's bounce.</Animated>
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/with-google-analytics/pages/_document.js
<ide> export default class extends Document {
<ide> gtag('js', new Date());
<ide>
<ide> gtag('config', '${GA_TRACKING_ID}');
<del> `}}
<add> `
<add> }}
<ide> />
<ide> </Head>
<ide> <body>
<ide><path>examples/with-immutable-redux-wrapper/components/AddCount.js
<ide> /* eslint-disable */
<del>import React, {Component} from 'react'
<add>import React, { Component } from 'react'
<ide> import { connect } from 'react-redux'
<ide> import { bindActionCreators } from 'redux'
<ide> import { addCount } from '../store'
<ide> class AddCount extends Component {
<ide> this.props.addCount()
<ide> }
<ide>
<del> render () {
<add> render() {
<ide> const { count } = this.props
<ide> return (
<ide> <div>
<ide> <style jsx>{`
<ide> div {
<ide> padding: 0 0 20px 0;
<ide> }
<del> `}</style>
<del> <h1>AddCount: <span>{count}</span></h1>
<add> `}</style>
<add> <h1>
<add> AddCount: <span>{count}</span>
<add> </h1>
<ide> <button onClick={this.add}>Add To Count</button>
<ide> </div>
<ide> )
<ide> }
<ide> }
<ide>
<del>const mapStateToProps = (state => ({ count: state.get('count') }))
<add>const mapStateToProps = state => ({ count: state.get('count') })
<ide>
<del>const mapDispatchToProps = (dispatch) => {
<add>const mapDispatchToProps = dispatch => {
<ide> return {
<ide> addCount: bindActionCreators(addCount, dispatch)
<ide> }
<ide> }
<ide>
<del>export default connect(mapStateToProps, mapDispatchToProps)(AddCount)
<add>export default connect(
<add> mapStateToProps,
<add> mapDispatchToProps
<add>)(AddCount)
<ide><path>examples/with-immutable-redux-wrapper/components/Clock.js
<ide> export default ({ lastUpdate, light }) => {
<ide> div {
<ide> padding: 15px;
<ide> display: inline-block;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> }
<ide> export default ({ lastUpdate, light }) => {
<ide> )
<ide> }
<ide>
<del>const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<add>const format = t =>
<add> `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<ide>
<del>const pad = n => n < 10 ? `0${n}` : n
<add>const pad = n => (n < 10 ? `0${n}` : n)
<ide><path>examples/with-immutable-redux-wrapper/components/Page.js
<ide> export default connect(state => ({
<ide> <Clock lastUpdate={lastUpdate} light={light} />
<ide> <AddCount />
<ide> <nav>
<del> <Link href={linkTo}><a>Navigate</a></Link>
<add> <Link href={linkTo}>
<add> <a>Navigate</a>
<add> </Link>
<ide> </nav>
<ide> </div>
<ide> )
<ide><path>examples/with-immutable-redux-wrapper/pages/index.js
<ide> class Counter extends React.Component {
<ide> }
<ide>
<ide> render () {
<del> return (
<del> <Page title='Index Page' linkTo='/other' />
<del> )
<add> return <Page title='Index Page' linkTo='/other' />
<ide> }
<ide> }
<ide>
<del>const mapDispatchToProps = (dispatch) => {
<add>const mapDispatchToProps = dispatch => {
<ide> return {
<ide> addCount: bindActionCreators(addCount, dispatch),
<ide> startClock: bindActionCreators(startClock, dispatch)
<ide> }
<ide> }
<ide>
<del>export default connect(null, mapDispatchToProps)(Counter)
<add>export default connect(
<add> null,
<add> mapDispatchToProps
<add>)(Counter)
<ide><path>examples/with-immutable-redux-wrapper/pages/other.js
<ide> class Counter extends React.Component {
<ide> }
<ide>
<ide> render () {
<del> return (
<del> <Page title='Other Page' linkTo='/' />
<del> )
<add> return <Page title='Other Page' linkTo='/' />
<ide> }
<ide> }
<ide>
<del>const mapDispatchToProps = (dispatch) => {
<add>const mapDispatchToProps = dispatch => {
<ide> return {
<ide> addCount: bindActionCreators(addCount, dispatch),
<ide> startClock: bindActionCreators(startClock, dispatch)
<ide> }
<ide> }
<ide>
<del>export default connect(null, mapDispatchToProps)(Counter)
<add>export default connect(
<add> null,
<add> mapDispatchToProps
<add>)(Counter)
<ide><path>examples/with-immutable-redux-wrapper/store.js
<ide> export const reducer = (state = exampleInitialState, action) => {
<ide> count: state.get('count') + 1
<ide> })
<ide>
<del> default: return state
<add> default:
<add> return state
<ide> }
<ide> }
<ide>
<ide> // ACTIONS
<del>export const serverRenderClock = (isServer) => dispatch => {
<add>export const serverRenderClock = isServer => dispatch => {
<ide> return dispatch({ type: actionTypes.TICK, light: !isServer, ts: Date.now() })
<ide> }
<ide>
<ide> export const startClock = () => dispatch => {
<del> return setInterval(() => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }), 1000)
<add> return setInterval(
<add> () => dispatch({ type: actionTypes.TICK, light: true, ts: Date.now() }),
<add> 1000
<add> )
<ide> }
<ide>
<ide> export const addCount = () => dispatch => {
<ide> return dispatch({ type: actionTypes.ADD })
<ide> }
<ide>
<ide> export const makeStore = (initialState = exampleInitialState) => {
<del> return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware)))
<add> return createStore(
<add> reducer,
<add> initialState,
<add> composeWithDevTools(applyMiddleware(thunkMiddleware))
<add> )
<ide> }
<ide><path>examples/with-ioc/__tests__/blog.page_with_provide.test.js
<ide> import App from '../pages/blog.js'
<ide>
<ide> describe('With Enzyme', () => {
<ide> it('Blog renders components', () => {
<del> const app = shallow(<App post={{title: 'Hi There!'}} />).dive()
<add> const app = shallow(<App post={{ title: 'Hi There!' }} />).dive()
<ide> expect(app.find('h1').text()).toEqual('Hi There!')
<ide> })
<ide> })
<ide>
<ide> describe('With Snapshot Testing', () => {
<ide> it('Blog renders components', () => {
<del> const component = renderer.create(<App post={{title: 'Hi There!'}} />)
<add> const component = renderer.create(<App post={{ title: 'Hi There!' }} />)
<ide> const tree = component.toJSON()
<ide> expect(tree).toMatchSnapshot()
<ide> })
<ide><path>examples/with-ioc/__tests__/endpoint.component_with_inject.test.js
<ide> describe('With Enzyme', () => {
<ide> const injected = shallow(<Component Link={() => {}} />)
<ide> const component = injected.dive()
<ide> expect(component.find('h3').text()).toEqual('Endpoint')
<del> expect(component.find('Link').first().find('a').text()).toEqual('About: foo baz')
<add> expect(
<add> component
<add> .find('Link')
<add> .first()
<add> .find('a')
<add> .text()
<add> ).toEqual('About: foo baz')
<ide> })
<ide> })
<ide>
<ide> describe('With Snapshot Testing', () => {
<ide> it('Blog renders components', () => {
<del> const component = renderer.create(<Component Link={(props) => <div comment={'mocked Link component'}>{props.children}</div>} />)
<add> const component = renderer.create(
<add> <Component
<add> Link={props => (
<add> <div comment={'mocked Link component'}>{props.children}</div>
<add> )}
<add> />
<add> )
<ide> const tree = component.toJSON()
<ide> expect(tree).toMatchSnapshot()
<ide> })
<ide><path>examples/with-ioc/__tests__/index.page_without_provide.test.js
<ide> import App from '../pages/index.js'
<ide> describe('With Enzyme', () => {
<ide> it('App shows "Menu"', () => {
<ide> const app = shallow(<App />)
<del> expect(app.find('li a').first().text()).toEqual('Blog: Hello world')
<add> expect(
<add> app
<add> .find('li a')
<add> .first()
<add> .text()
<add> ).toEqual('Blog: Hello world')
<ide> })
<ide> })
<ide>
<ide><path>examples/with-ioc/components/component1.js
<ide> import React from 'react'
<ide> import Component2 from './component2'
<ide>
<ide> export default () => (
<del> <div style={{ marginTop: '5px', border: '1px dotted #ff0000', padding: '10px' }}>
<add> <div
<add> style={{ marginTop: '5px', border: '1px dotted #ff0000', padding: '10px' }}
<add> >
<ide> <h3>Component1</h3>
<ide> Knows nothing about any custom `Link` or `Router` components or prop
<ide> <Component2 />
<ide><path>examples/with-ioc/components/component2.js
<ide> import Endpoint from './endpoint'
<ide> import EndButton from './endbutton'
<ide>
<ide> export default () => (
<del> <div style={{ marginTop: '5px', border: '1px dashed #0000ff', padding: '10px' }}>
<add> <div
<add> style={{ marginTop: '5px', border: '1px dashed #0000ff', padding: '10px' }}
<add> >
<ide> <h3>Component2</h3>
<ide> Knows nothing about any custom `Link` or `Router` components or prop
<ide> <Endpoint />
<ide><path>examples/with-ioc/components/endbutton.js
<ide> import PropTypes from 'prop-types'
<ide> Router: PropTypes.object
<ide> })
<ide> export default class extends React.Component {
<del> render () {
<add> render() {
<ide> const { Router } = this.props
<ide>
<ide> return (
<del> <div style={{ marginTop: '5px', border: '1px dashed #00ff00', padding: '10px' }}>
<add> <div
<add> style={{
<add> marginTop: '5px',
<add> border: '1px dashed #00ff00',
<add> padding: '10px'
<add> }}
<add> >
<ide> <h3>EndButton</h3>
<ide> Uses injected `Router` component without direct dependency on one
<ide> <br />
<del> <button onClick={() => Router.pushRoute('about', { foo: 'bar' })}>Route to About foo bar</button>
<add> <button onClick={() => Router.pushRoute('about', { foo: 'bar' })}>
<add> Route to About foo bar
<add> </button>
<ide> <br />
<ide> <button onClick={() => Router.pushRoute('/')}>go Home</button>
<ide> </div>
<ide><path>examples/with-ioc/components/endpoint.js
<ide> export default class extends React.Component {
<ide> Link: PropTypes.func.isRequired
<ide> }
<ide>
<del> render () {
<add> render() {
<ide> const { Link } = this.props
<ide>
<ide> return (
<del> <div style={{ marginTop: '5px', border: '1px dashed #00ff00', padding: '10px' }}>
<add> <div
<add> style={{
<add> marginTop: '5px',
<add> border: '1px dashed #00ff00',
<add> padding: '10px'
<add> }}
<add> >
<ide> <h3>Endpoint</h3>
<ide> Uses injected `Link` component without direct dependency on one
<ide> <br />
<del> <Link route='about' params={{ foo: 'baz' }}><a>About: foo baz</a></Link>
<add> <Link route="about" params={{ foo: 'baz' }}>
<add> <a>About: foo baz</a>
<add> </Link>
<ide> <br />
<del> <Link route='/'><a>go Home</a></Link>
<add> <Link route="/">
<add> <a>go Home</a>
<add> </Link>
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/with-ioc/pages/about.js
<del>export default props => <h1>About foo – no `Link` ({typeof props.Link}) available here</h1>
<add>export default props => (
<add> <h1>About foo – no `Link` ({typeof props.Link}) available here</h1>
<add>)
<ide><path>examples/with-ioc/pages/blog.js
<ide> const posts = [
<ide> Router
<ide> })
<ide> export default class extends React.Component {
<del> static async getInitialProps ({ query, res }) {
<add> static async getInitialProps({ query, res }) {
<ide> const post = posts.find(post => post.slug === query.slug)
<ide>
<ide> if (!post && res) {
<ide> export default class extends React.Component {
<ide> return { post }
<ide> }
<ide>
<del> render () {
<add> render() {
<ide> const { post } = this.props
<ide>
<ide> if (!post) return <h1>Post not found</h1>
<ide><path>examples/with-ioc/pages/index.js
<ide> import { Link, Router } from '../routes'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link route='blog' params={{ slug: 'hello-world' }}><a>Blog: Hello world</a></Link></li>
<del> <li><Link route='blog' params={{ slug: 'another-blog-post' }}><a>Blog: Another blog post</a></Link></li>
<del> <li><Link route='blog' params={{ slug: 'non-existant' }}><a>Blog: Not found</a></Link></li>
<del> <li><button onClick={() => Router.pushRoute('about', { foo: 'bar' })}>About foo bar</button></li>
<del> <li><button onClick={() => Router.pushRoute('about', { foo: 'baz' })}>About foo baz</button></li>
<add> <li>
<add> <Link route="blog" params={{ slug: 'hello-world' }}>
<add> <a>Blog: Hello world</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link route="blog" params={{ slug: 'another-blog-post' }}>
<add> <a>Blog: Another blog post</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link route="blog" params={{ slug: 'non-existant' }}>
<add> <a>Blog: Not found</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <button onClick={() => Router.pushRoute('about', { foo: 'bar' })}>
<add> About foo bar
<add> </button>
<add> </li>
<add> <li>
<add> <button onClick={() => Router.pushRoute('about', { foo: 'baz' })}>
<add> About foo baz
<add> </button>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/with-ioc/routes.js
<ide> const nextRoutes = require('next-routes')
<del>const routes = module.exports = nextRoutes()
<add>const routes = (module.exports = nextRoutes())
<ide>
<ide> routes.add('blog', '/blog/:slug')
<ide> routes.add('about', '/about-us/:foo(bar|baz)')
<ide><path>examples/with-ioc/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handler = routes.getRequestHandler(app)
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer(handler)
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer(handler).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/with-jest-typescript/jest.config.js
<ide> module.exports = {
<ide> transform: {
<ide> '^.+\\.tsx?$': 'babel-jest'
<ide> },
<del> testPathIgnorePatterns: [
<del> '<rootDir>/.next/', '<rootDir>/node_modules/'
<del> ],
<del> moduleFileExtensions: [
<del> 'ts', 'tsx', 'js', 'jsx'
<del> ],
<add> testPathIgnorePatterns: ['<rootDir>/.next/', '<rootDir>/node_modules/'],
<add> moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx'],
<ide> collectCoverage: true
<ide> }
<ide><path>examples/with-jest-typescript/jest.setup.js
<ide> const Enzyme = require('enzyme')
<ide> const Adapter = require('enzyme-adapter-react-16')
<ide>
<del>Enzyme.configure({adapter: new Adapter()})
<add>Enzyme.configure({ adapter: new Adapter() })
<ide><path>examples/with-kea/pages/_app.js
<ide> import { initStore } from '../store'
<ide>
<ide> @withRedux(initStore, { debug: process.env.NODE_ENV === 'development' })
<ide> export default class MyApp extends App {
<del> static async getInitialProps ({Component, ctx}) {
<del> const pageProps = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}
<add> static async getInitialProps({ Component, ctx }) {
<add> const pageProps = Component.getInitialProps
<add> ? await Component.getInitialProps(ctx)
<add> : {}
<ide> return { pageProps }
<ide> }
<ide>
<del> render () {
<add> render() {
<ide> const { Component, pageProps, store } = this.props
<ide> return (
<ide> <Container>
<ide><path>examples/with-kea/pages/index.js
<ide> import { kea } from 'kea'
<ide> ]
<ide> })
<ide> })
<del>
<ide> export default class App extends React.Component {
<del> render () {
<add> render() {
<ide> return (
<ide> <div>
<ide> <p>Double Counter: {this.props.doubleCounter}</p>
<del> <button type='button' onClick={() => this.actions.increment(1)}>Increment</button>
<del> <button type='button' onClick={() => this.actions.decrement(1)}>Decrement</button>
<add> <button type="button" onClick={() => this.actions.increment(1)}>
<add> Increment
<add> </button>
<add> <button type="button" onClick={() => this.actions.decrement(1)}>
<add> Decrement
<add> </button>
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/with-kea/store.js
<ide> const reduxDevTools =
<ide> : f => f
<ide>
<ide> export const initStore = () => {
<del> return createStore(
<del> reducers,
<del> compose(reduxDevTools)
<del> )
<add> return createStore(reducers, compose(reduxDevTools))
<ide> }
<ide><path>examples/with-loading/pages/_app.js
<ide> import React from 'react'
<del>import App, {Container} from 'next/app'
<add>import App, { Container } from 'next/app'
<ide> import Link from 'next/link'
<ide> import NProgress from 'nprogress'
<ide> import Router from 'next/router'
<ide> const linkStyle = {
<ide> margin: '0 10px 0 0'
<ide> }
<ide>
<del>Router.events.on('routeChangeStart', (url) => {
<add>Router.events.on('routeChangeStart', url => {
<ide> console.log(`Loading: ${url}`)
<ide> NProgress.start()
<ide> })
<ide> export default class MyApp extends App {
<ide> pageProps = await Component.getInitialProps(ctx)
<ide> }
<ide>
<del> return {pageProps}
<add> return { pageProps }
<ide> }
<ide>
<ide> render () {
<del> const {Component, pageProps} = this.props
<add> const { Component, pageProps } = this.props
<ide> return (
<ide> <Container>
<ide> <div style={{ marginBottom: 20 }}>
<del> <Link href='/'><a style={linkStyle}>Home</a></Link>
<del> <Link href='/about'><a style={linkStyle}>About</a></Link>
<del> <Link href='/forever'><a style={linkStyle}>Forever</a></Link>
<del> <Link href='/non-existing'><a style={linkStyle}>Non Existing Page</a></Link>
<add> <Link href='/'>
<add> <a style={linkStyle}>Home</a>
<add> </Link>
<add> <Link href='/about'>
<add> <a style={linkStyle}>About</a>
<add> </Link>
<add> <Link href='/forever'>
<add> <a style={linkStyle}>Forever</a>
<add> </Link>
<add> <Link href='/non-existing'>
<add> <a style={linkStyle}>Non Existing Page</a>
<add> </Link>
<ide> </div>
<ide>
<ide> <Component {...pageProps} />
<ide><path>examples/with-loading/pages/about.js
<ide> import React, { Component } from 'react'
<ide> export default class About extends Component {
<ide> // Add some delay
<ide> static async getInitialProps () {
<del> await new Promise((resolve) => {
<add> await new Promise(resolve => {
<ide> setTimeout(resolve, 500)
<ide> })
<ide> return {}
<ide><path>examples/with-loading/pages/forever.js
<ide> import React, { Component } from 'react'
<ide> export default class Forever extends Component {
<ide> // Add some delay
<ide> static async getInitialProps () {
<del> await new Promise((resolve) => {
<add> await new Promise(resolve => {
<ide> setTimeout(resolve, 3000)
<ide> })
<ide> return {}
<ide><path>examples/with-markdown/next.config.js
<ide> const emoji = require('remark-emoji')
<ide>
<ide> const withMDX = require('@zeit/next-mdx')({
<ide> options: {
<del> mdPlugins: [
<del> images,
<del> emoji
<del> ]
<add> mdPlugins: [images, emoji]
<ide> }
<ide> })
<ide>
<ide><path>examples/with-markdown/pages/index.js
<ide> import React from 'react'
<ide> import Document from '../md/markdown.mdx'
<ide>
<ide> const H1 = props => <h1 style={{ color: 'tomato' }} {...props} />
<del>const InlineCode = props => <code id='codes' style={{ color: 'purple' }} {...props} />
<add>const InlineCode = props => (
<add> <code id='codes' style={{ color: 'purple' }} {...props} />
<add>)
<ide> const Code = props => <code id='codes' style={{ fontWeight: 600 }} {...props} />
<ide> const Pre = props => <pre id='codes' style={{ color: 'red' }} {...props} />
<ide>
<del>export default () => <Document components={{ h1: H1, pre: Pre, code: Code, inlineCode: InlineCode }} />
<add>export default () => (
<add> <Document
<add> components={{ h1: H1, pre: Pre, code: Code, inlineCode: InlineCode }}
<add> />
<add>)
<ide><path>examples/with-mdx/components/button.js
<ide> export default ({ children }) => (
<del> <button style={{
<del> borderRadius: '3px',
<del> border: '1px solid black',
<del> color: 'black',
<del> padding: '0.5em 1em',
<del> cursor: 'pointer',
<del> fontSize: '1.1em'
<del> }}>
<add> <button
<add> style={{
<add> borderRadius: '3px',
<add> border: '1px solid black',
<add> color: 'black',
<add> padding: '0.5em 1em',
<add> cursor: 'pointer',
<add> fontSize: '1.1em'
<add> }}
<add> >
<ide> {children}
<ide> </button>
<ide> )
<ide><path>examples/with-mobx-state-tree/components/Clock.js
<del>export default (props) => {
<add>export default props => {
<ide> return (
<ide> <div className={props.light ? 'light' : ''}>
<ide> {format(new Date(props.lastUpdate))}
<ide> <style jsx>{`
<ide> div {
<ide> padding: 15px;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> display: inline-block;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> export default (props) => {
<ide> )
<ide> }
<ide>
<del>const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<add>const format = t =>
<add> `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<ide>
<del>const pad = n => n < 10 ? `0${n}` : n
<add>const pad = n => (n < 10 ? `0${n}` : n)
<ide><path>examples/with-mobx-state-tree/components/SampleComponent.js
<ide> class SampleComponent extends React.Component {
<ide> return (
<ide> <div>
<ide> <h1>{this.props.title}</h1>
<del> <Clock lastUpdate={this.props.store.lastUpdate} light={this.props.store.light} />
<add> <Clock
<add> lastUpdate={this.props.store.lastUpdate}
<add> light={this.props.store.light}
<add> />
<ide> <nav>
<del> <Link href={this.props.linkTo}><a>Navigate</a></Link>
<add> <Link href={this.props.linkTo}>
<add> <a>Navigate</a>
<add> </Link>
<ide> </nav>
<ide> </div>
<ide> )
<ide><path>examples/with-mobx-state-tree/pages/_app.js
<ide> export default class MyApp extends App {
<ide> // Use getInitialProps as a step in the lifecycle when
<ide> // we can initialize our store
<ide> //
<del> const isServer = (typeof window === 'undefined')
<add> const isServer = typeof window === 'undefined'
<ide> const store = initializeStore(isServer)
<ide> //
<ide> // Check whether the page being rendered by the App has a
<ide><path>examples/with-mobx-state-tree/pages/index.js
<ide> import React from 'react'
<ide> import SampleComponent from '../components/SampleComponent'
<ide>
<ide> export default () => {
<del> return (
<del> <SampleComponent title='Index Page' linkTo='/other' />
<del> )
<add> return <SampleComponent title='Index Page' linkTo='/other' />
<ide> }
<ide><path>examples/with-mobx-state-tree/pages/other.js
<ide> import React from 'react'
<ide> import SampleComponent from '../components/SampleComponent'
<ide>
<ide> export default () => {
<del> return (
<del> <SampleComponent title={'Other Page'} linkTo='/' />
<del> )
<add> return <SampleComponent title={'Other Page'} linkTo='/' />
<ide> }
<ide><path>examples/with-mobx-state-tree/stores/store.js
<ide> const Store = types
<ide> lastUpdate: types.Date,
<ide> light: false
<ide> })
<del> .actions((self) => {
<add> .actions(self => {
<ide> let timer
<ide> function start () {
<ide> timer = setInterval(() => {
<ide><path>examples/with-mobx/components/Clock.js
<del>export default (props) => {
<add>export default props => {
<ide> return (
<ide> <div className={props.light ? 'light' : ''}>
<ide> {format(new Date(props.lastUpdate))}
<ide> <style jsx>{`
<ide> div {
<ide> padding: 15px;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> display: inline-block;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> export default (props) => {
<ide> )
<ide> }
<ide>
<del>const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<add>const format = t =>
<add> `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<ide>
<del>const pad = n => n < 10 ? `0${n}` : n
<add>const pad = n => (n < 10 ? `0${n}` : n)
<ide><path>examples/with-mobx/components/Page.js
<ide> import Link from 'next/link'
<ide> import { inject, observer } from 'mobx-react'
<ide> import Clock from './Clock'
<ide>
<del>@inject('store') @observer
<add>@inject('store')
<add>@observer
<ide> class Page extends React.Component {
<del> componentDidMount () {
<add> componentDidMount() {
<ide> this.props.store.start()
<ide> }
<ide>
<del> componentWillUnmount () {
<add> componentWillUnmount() {
<ide> this.props.store.stop()
<ide> }
<ide>
<del> render () {
<add> render() {
<ide> return (
<ide> <div>
<ide> <h1>{this.props.title}</h1>
<del> <Clock lastUpdate={this.props.store.lastUpdate} light={this.props.store.light} />
<add> <Clock
<add> lastUpdate={this.props.store.lastUpdate}
<add> light={this.props.store.light}
<add> />
<ide> <nav>
<del> <Link href={this.props.linkTo}><a>Navigate</a></Link>
<add> <Link href={this.props.linkTo}>
<add> <a>Navigate</a>
<add> </Link>
<ide> </nav>
<ide> </div>
<ide> )
<ide><path>examples/with-mobx/pages/_app.js
<del>import App, {Container} from 'next/app'
<add>import App, { Container } from 'next/app'
<ide> import React from 'react'
<ide> import { initializeStore } from '../store'
<ide> import { Provider } from 'mobx-react'
<ide>
<ide> class MyMobxApp extends App {
<del> static async getInitialProps(appContext) {
<del> // Get or Create the store with `undefined` as initialState
<del> // This allows you to set a custom default initialState
<del> const mobxStore = initializeStore()
<del> // Provide the store to getInitialProps of pages
<del> appContext.ctx.mobxStore = mobxStore
<add> static async getInitialProps(appContext) {
<add> // Get or Create the store with `undefined` as initialState
<add> // This allows you to set a custom default initialState
<add> const mobxStore = initializeStore()
<add> // Provide the store to getInitialProps of pages
<add> appContext.ctx.mobxStore = mobxStore
<ide>
<del> let appProps = await App.getInitialProps(appContext)
<add> let appProps = await App.getInitialProps(appContext)
<ide>
<del> return {
<del> ...appProps,
<del> initialMobxState: mobxStore
<del> };
<add> return {
<add> ...appProps,
<add> initialMobxState: mobxStore
<ide> }
<add> }
<ide>
<del> constructor(props) {
<del> super(props)
<del> const isServer = typeof window === 'undefined'
<del> this.mobxStore = isServer ?
<del> props.initialMobxState:
<del> initializeStore(props.initialMobxState)
<del> }
<add> constructor(props) {
<add> super(props)
<add> const isServer = typeof window === 'undefined'
<add> this.mobxStore = isServer
<add> ? props.initialMobxState
<add> : initializeStore(props.initialMobxState)
<add> }
<ide>
<del> render() {
<del> const { Component, pageProps } = this.props
<del> return (
<del> <Container>
<del> <Provider store={this.mobxStore}>
<del> <Component {...pageProps} />
<del> </Provider>
<del> </Container>
<del> );
<del> }
<add> render() {
<add> const { Component, pageProps } = this.props
<add> return (
<add> <Container>
<add> <Provider store={this.mobxStore}>
<add> <Component {...pageProps} />
<add> </Provider>
<add> </Container>
<add> )
<add> }
<ide> }
<ide> export default MyMobxApp
<ide><path>examples/with-mobx/pages/index.js
<ide> import React from 'react'
<ide> import Page from '../components/Page'
<ide>
<ide> export default class Counter extends React.Component {
<del> render () {
<del> return (
<del> <Page title='Index Page' linkTo='/other' />
<del> )
<add> render() {
<add> return <Page title="Index Page" linkTo="/other" />
<ide> }
<ide> }
<ide><path>examples/with-mobx/pages/other.js
<ide> import React from 'react'
<ide> import Page from '../components/Page'
<ide>
<ide> export default class Counter extends React.Component {
<del> render () {
<del> return (
<del> <Page title='Other Page' linkTo='/' />
<del> )
<add> render() {
<add> return <Page title="Other Page" linkTo="/" />
<ide> }
<ide> }
<ide><path>examples/with-mobx/store.js
<ide> class Store {
<ide> @observable lastUpdate = 0
<ide> @observable light = false
<ide>
<del> constructor (isServer, initialData = {}) {
<del> this.lastUpdate = initialData.lastUpdate != null ? initialData.lastUpdate : Date.now()
<add> constructor(isServer, initialData = {}) {
<add> this.lastUpdate =
<add> initialData.lastUpdate != null ? initialData.lastUpdate : Date.now()
<ide> this.light = !!initialData.light
<ide> }
<ide>
<ide> class Store {
<ide> stop = () => clearInterval(this.timer)
<ide> }
<ide>
<del>
<ide> let store = null
<del>export function initializeStore (initialData) {
<add>export function initializeStore(initialData) {
<ide> // Always make a new store if server, otherwise state is shared between requests
<ide> if (isServer) {
<ide> return new Store(isServer, initialData)
<ide><path>examples/with-next-css/pages/index.js
<del>
<ide> /* Without CSS Modules, maybe with PostCSS */
<ide>
<ide> import '../style.css'
<ide><path>examples/with-next-routes/pages/about.js
<ide> import { withRouter } from 'next/router'
<ide>
<del>const About = ({router}) => <h1>About foo {router.query.foo}</h1>
<add>const About = ({ router }) => <h1>About foo {router.query.foo}</h1>
<ide>
<ide> export default withRouter(About)
<ide><path>examples/with-next-routes/pages/index.js
<ide> import { Link, Router } from '../routes'
<ide>
<ide> export default () => (
<ide> <ul>
<del> <li><Link route='blog' params={{ slug: 'hello-world' }}><a>Blog: Hello world</a></Link></li>
<del> <li><Link route='blog' params={{ slug: 'another-blog-post' }}><a>Blog: Another blog post</a></Link></li>
<del> <li><Link route='blog' params={{ slug: 'non-existant' }}><a>Blog: Not found</a></Link></li>
<del> <li><button onClick={() => Router.pushRoute('about', { foo: 'bar' })}>About foo bar</button></li>
<del> <li><button onClick={() => Router.pushRoute('about', { foo: 'baz' })}>About foo baz</button></li>
<add> <li>
<add> <Link route='blog' params={{ slug: 'hello-world' }}>
<add> <a>Blog: Hello world</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link route='blog' params={{ slug: 'another-blog-post' }}>
<add> <a>Blog: Another blog post</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <Link route='blog' params={{ slug: 'non-existant' }}>
<add> <a>Blog: Not found</a>
<add> </Link>
<add> </li>
<add> <li>
<add> <button onClick={() => Router.pushRoute('about', { foo: 'bar' })}>
<add> About foo bar
<add> </button>
<add> </li>
<add> <li>
<add> <button onClick={() => Router.pushRoute('about', { foo: 'baz' })}>
<add> About foo baz
<add> </button>
<add> </li>
<ide> </ul>
<ide> )
<ide><path>examples/with-next-routes/routes.js
<ide> const nextRoutes = require('next-routes')
<del>const routes = module.exports = nextRoutes()
<add>const routes = (module.exports = nextRoutes())
<ide>
<ide> routes.add('blog', '/blog/:slug')
<ide> routes.add('about', '/about-us/:foo(bar|baz)')
<ide><path>examples/with-next-routes/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handler = routes.getRequestHandler(app)
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer(handler)
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer(handler).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/with-next-sass/pages/index.js
<ide> import '../styles/style.scss'
<ide>
<del>export default () =>
<del> <div className='example'>
<del> Hello World!
<del> </div>
<add>export default () => <div className='example'>Hello World!</div>
<ide><path>examples/with-noscript/next.config.js
<ide> module.exports = {
<ide> webpack: (config, { dev }) => {
<ide> if (!dev) {
<ide> config.resolve.alias = {
<del> 'react-dom/server': require.resolve('react-dom/umd/react-dom-server.browser.production.min.js')
<add> 'react-dom/server': require.resolve(
<add> 'react-dom/umd/react-dom-server.browser.production.min.js'
<add> )
<ide> }
<ide> }
<ide> return config
<ide><path>examples/with-noscript/pages/index.js
<ide> class Index extends React.Component {
<ide> render () {
<ide> return (
<ide> <div style={{ textAlign: 'center' }}>
<del> {
<del> images.map((item, index) =>
<del> <div key={index}>
<del> <LazyLoad height={700} offset={100}>
<del> <img width={700} height={700} src={item} alt={`image_${index}`} />
<del> </LazyLoad>
<del> <Noscript>
<del> <img width={700} height={700} src={item} alt={`image_${index}`} />
<del> </Noscript>
<del> </div>
<del> )
<del> }
<add> {images.map((item, index) => (
<add> <div key={index}>
<add> <LazyLoad height={700} offset={100}>
<add> <img width={700} height={700} src={item} alt={`image_${index}`} />
<add> </LazyLoad>
<add> <Noscript>
<add> <img width={700} height={700} src={item} alt={`image_${index}`} />
<add> </Noscript>
<add> </div>
<add> ))}
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/with-pkg/pages/index.js
<del>export default () =>
<del> <h1>Home page</h1>
<add>export default () => <h1>Home page</h1>
<ide><path>examples/with-pkg/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev, dir: __dirname })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> createServer((req, res) => handle(req, res, parse(req.url, true).pathname))
<del> .listen(port, (err) => {
<del> if (err) throw err
<del> console.log(`> Ready on http://localhost:${port}`)
<del> })
<add>app.prepare().then(() => {
<add> createServer((req, res) =>
<add> handle(req, res, parse(req.url, true).pathname)
<add> ).listen(port, err => {
<add> if (err) throw err
<add> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<add>})
<ide><path>examples/with-polyfills/next.config.js
<ide> module.exports = {
<ide> cfg.entry = async () => {
<ide> const entries = await originalEntry()
<ide>
<del> if (entries['main.js'] && !entries['main.js'].includes('./client/polyfills.js')) {
<add> if (
<add> entries['main.js'] &&
<add> !entries['main.js'].includes('./client/polyfills.js')
<add> ) {
<ide> entries['main.js'].unshift('./client/polyfills.js')
<ide> }
<ide>
<ide><path>examples/with-polyfills/pages/index.js
<ide> console.log('Inside the /index.js page')
<ide>
<del>export default () => (
<del> <div>
<del> Hello World
<del> </div>
<del>)
<add>export default () => <div>Hello World</div>
<ide><path>examples/with-prefetching/components/Header.js
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <div>
<del> { /* Prefetch using the declarative API */ }
<add> {/* Prefetch using the declarative API */}
<ide> <Link prefetch href='/'>
<ide> <a>Home</a>
<ide> </Link>
<ide> export default () => (
<ide> <a>Features</a>
<ide> </Link>
<ide>
<del> { /* we imperatively prefetch on hover */ }
<add> {/* we imperatively prefetch on hover */}
<ide> <Link href='/about'>
<del> <a onMouseEnter={() => { Router.prefetch('/about'); console.log('prefetching /about!') }}>About</a>
<add> <a
<add> onMouseEnter={() => {
<add> Router.prefetch('/about')
<add> console.log('prefetching /about!')
<add> }}
<add> >
<add> About
<add> </a>
<ide> </Link>
<ide>
<ide> <Link href='/contact'>
<del> <a>Contact (<small>NO-PREFETCHING</small>)</a>
<add> <a>
<add> Contact (<small>NO-PREFETCHING</small>)
<add> </a>
<ide> </Link>
<ide>
<ide> <style jsx>{`
<ide><path>examples/with-prefetching/pages/_app.js
<del>import App, {Container} from 'next/app'
<add>import App, { Container } from 'next/app'
<ide> import React from 'react'
<ide> import Header from '../components/Header'
<ide>
<ide> export default class MyApp extends App {
<ide> pageProps = await Component.getInitialProps(ctx)
<ide> }
<ide>
<del> return {pageProps}
<add> return { pageProps }
<ide> }
<ide>
<ide> render () {
<del> const {Component, pageProps} = this.props
<add> const { Component, pageProps } = this.props
<ide> return (
<ide> <Container>
<ide> <Header />
<ide><path>examples/with-pretty-url-routing/pages/greeting.js
<ide> import React from 'react'
<ide> import PropTypes from 'prop-types'
<del>import {Link} from 'next-url-prettifier'
<del>import {Router} from '../routes'
<add>import { Link } from 'next-url-prettifier'
<add>import { Router } from '../routes'
<ide>
<ide> export default class GreetingPage extends React.Component {
<del> static getInitialProps ({query: {lang, name}}) {
<del> return {lang, name}
<add> static getInitialProps ({ query: { lang, name } }) {
<add> return { lang, name }
<ide> }
<ide>
<ide> renderSwitchLanguageLink () {
<del> const {lang, name} = this.props
<add> const { lang, name } = this.props
<ide> const switchLang = lang === 'fr' ? 'en' : 'fr'
<ide> return (
<del> <Link route={Router.linkPage('greeting', {name, lang: switchLang})}>
<add> <Link route={Router.linkPage('greeting', { name, lang: switchLang })}>
<ide> <a>{switchLang === 'fr' ? 'Français' : 'English'}</a>
<ide> </Link>
<ide> )
<ide> }
<ide>
<ide> render () {
<del> const {lang, name} = this.props
<add> const { lang, name } = this.props
<ide> return (
<ide> <div>
<del> <h1>{lang === 'fr' ? 'Bonjour' : 'Hello'} {name}</h1>
<add> <h1>
<add> {lang === 'fr' ? 'Bonjour' : 'Hello'} {name}
<add> </h1>
<ide> <div>{this.renderSwitchLanguageLink()}</div>
<ide> </div>
<ide> )
<ide><path>examples/with-pretty-url-routing/routes.js
<ide> const routes = [
<ide> },
<ide> {
<ide> page: 'greeting',
<del> prettyUrl: ({lang = '', name = ''}) =>
<del> (lang === 'fr' ? `/bonjour/${name}` : `/hello/${name}`),
<add> prettyUrl: ({ lang = '', name = '' }) =>
<add> lang === 'fr' ? `/bonjour/${name}` : `/hello/${name}`,
<ide> prettyUrlPatterns: [
<del> {pattern: '/hello/:name', defaultParams: {lang: 'en'}},
<del> {pattern: '/bonjour/:name', defaultParams: {lang: 'fr'}}
<add> { pattern: '/hello/:name', defaultParams: { lang: 'en' } },
<add> { pattern: '/bonjour/:name', defaultParams: { lang: 'fr' } }
<ide> ]
<ide> }
<ide> ]
<ide><path>examples/with-pretty-url-routing/server.js
<ide> const dev = process.env.NODE_ENV !== 'production'
<ide> const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<del>app.prepare()
<del> .then(() => {
<del> const server = express()
<add>app.prepare().then(() => {
<add> const server = express()
<ide>
<del> Router.forEachPattern((page, pattern, defaultParams) => server.get(pattern, (req, res) =>
<del> app.render(req, res, `/${page}`, Object.assign({}, defaultParams, req.query, req.params))
<del> ))
<add> Router.forEachPattern((page, pattern, defaultParams) =>
<add> server.get(pattern, (req, res) =>
<add> app.render(
<add> req,
<add> res,
<add> `/${page}`,
<add> Object.assign({}, defaultParams, req.query, req.params)
<add> )
<add> )
<add> )
<ide>
<del> server.get('*', (req, res) => handle(req, res))
<del> server.listen(port)
<del> })
<add> server.get('*', (req, res) => handle(req, res))
<add> server.listen(port)
<add>})
<ide><path>examples/with-react-ga/pages/about.js
<del>export default () => (
<del> <div>About us</div>
<del>)
<add>export default () => <div>About us</div>
<ide><path>examples/with-react-helmet/pages/_document.js
<ide> export default class extends Document {
<ide> }
<ide>
<ide> get helmetJsx () {
<del> return (<Helmet
<del> htmlAttributes={{lang: 'en'}}
<del> title='Hello next.js!'
<del> meta={[
<del> { name: 'viewport', content: 'width=device-width, initial-scale=1' },
<del> { property: 'og:title', content: 'Hello next.js!' }
<del> ]}
<del> />)
<add> return (
<add> <Helmet
<add> htmlAttributes={{ lang: 'en' }}
<add> title='Hello next.js!'
<add> meta={[
<add> { name: 'viewport', content: 'width=device-width, initial-scale=1' },
<add> { property: 'og:title', content: 'Hello next.js!' }
<add> ]}
<add> />
<add> )
<ide> }
<ide>
<ide> render () {
<del> return (<html {...this.helmetHtmlAttrComponents}>
<del> <Head>
<del> { this.helmetJsx }
<del> { this.helmetHeadComponents }
<del> </Head>
<del> <body {...this.helmetBodyAttrComponents}>
<del> <Main />
<del> <NextScript />
<del> </body>
<del> </html>)
<add> return (
<add> <html {...this.helmetHtmlAttrComponents}>
<add> <Head>
<add> {this.helmetJsx}
<add> {this.helmetHeadComponents}
<add> </Head>
<add> <body {...this.helmetBodyAttrComponents}>
<add> <Main />
<add> <NextScript />
<add> </body>
<add> </html>
<add> )
<ide> }
<ide> }
<ide><path>examples/with-react-helmet/pages/index.js
<del>export default () => (<div>
<del> Hello World!
<del></div>)
<add>export default () => <div>Hello World!</div>
<ide><path>examples/with-react-intl/components/Layout.js
<ide> import React from 'react'
<del>import {defineMessages, injectIntl} from 'react-intl'
<add>import { defineMessages, injectIntl } from 'react-intl'
<ide> import Head from 'next/head'
<ide> import Nav from './Nav'
<ide>
<ide> const messages = defineMessages({
<ide> }
<ide> })
<ide>
<del>export default injectIntl(({intl, title, children}) => (
<add>export default injectIntl(({ intl, title, children }) => (
<ide> <div>
<ide> <Head>
<ide> <meta name='viewport' content='width=device-width, initial-scale=1' />
<ide> export default injectIntl(({intl, title, children}) => (
<ide> </header>
<ide>
<ide> {children}
<del>
<ide> </div>
<ide> ))
<ide><path>examples/with-react-intl/components/Nav.js
<ide> import React from 'react'
<del>import {FormattedMessage} from 'react-intl'
<add>import { FormattedMessage } from 'react-intl'
<ide> import Link from 'next/link'
<ide>
<ide> export default () => (
<ide> <nav>
<ide> <li>
<ide> <Link href='/'>
<del> <a><FormattedMessage id='nav.home' defaultMessage='Home' /></a>
<add> <a>
<add> <FormattedMessage id='nav.home' defaultMessage='Home' />
<add> </a>
<ide> </Link>
<ide> </li>
<ide> <li>
<ide> <Link href='/about'>
<del> <a><FormattedMessage id='nav.about' defaultMessage='About' /></a>
<add> <a>
<add> <FormattedMessage id='nav.about' defaultMessage='About' />
<add> </a>
<ide> </Link>
<ide> </li>
<ide>
<ide><path>examples/with-react-intl/lib/withIntl.js
<ide> import hoistNonReactStatics from 'hoist-non-react-statics'
<ide> import { injectIntl } from 'react-intl'
<ide>
<del>export const hoistStatics = (higherOrderComponent) => (BaseComponent) => {
<add>export const hoistStatics = higherOrderComponent => BaseComponent => {
<ide> const NewComponent = higherOrderComponent(BaseComponent)
<ide> hoistNonReactStatics(NewComponent, BaseComponent)
<ide>
<ide><path>examples/with-react-intl/pages/_app.js
<ide> import { IntlProvider, addLocaleData } from 'react-intl'
<ide> // locale data was added to the page by `pages/_document.js`. This only happens
<ide> // once, on initial page load in the browser.
<ide> if (typeof window !== 'undefined' && window.ReactIntlLocaleData) {
<del> Object.keys(window.ReactIntlLocaleData).forEach((lang) => {
<add> Object.keys(window.ReactIntlLocaleData).forEach(lang => {
<ide> addLocaleData(window.ReactIntlLocaleData[lang])
<ide> })
<ide> }
<ide> export default class MyApp extends App {
<ide>
<ide> return (
<ide> <Container>
<del> <IntlProvider locale={locale} messages={messages} initialNow={initialNow}>
<add> <IntlProvider
<add> locale={locale}
<add> messages={messages}
<add> initialNow={initialNow}
<add> >
<ide> <Component {...pageProps} />
<ide> </IntlProvider>
<ide> </Container>
<ide><path>examples/with-react-intl/pages/_document.js
<del>import Document, {Head, Main, NextScript} from 'next/document'
<add>import Document, { Head, Main, NextScript } from 'next/document'
<ide>
<ide> // The document (which is SSR-only) needs to be customized to expose the locale
<ide> // data for the user's locale for React Intl to work in the browser.
<ide> export default class IntlDocument extends Document {
<ide> static async getInitialProps (context) {
<ide> const props = await super.getInitialProps(context)
<del> const {req: {locale, localeDataScript}} = context
<add> const {
<add> req: { locale, localeDataScript }
<add> } = context
<ide> return {
<ide> ...props,
<ide> locale,
<ide> export default class IntlDocument extends Document {
<ide>
<ide> render () {
<ide> // Polyfill Intl API for older browsers
<del> const polyfill = `https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.${this.props.locale}`
<add> const polyfill = `https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.${
<add> this.props.locale
<add> }`
<ide>
<ide> return (
<ide> <html>
<ide><path>examples/with-react-intl/pages/about.js
<del>import React, {Component} from 'react'
<del>import {FormattedRelative} from 'react-intl'
<add>import React, { Component } from 'react'
<add>import { FormattedRelative } from 'react-intl'
<ide> import Layout from '../components/Layout'
<ide>
<ide> class About extends Component {
<del> static async getInitialProps ({req}) {
<del> return {someDate: Date.now()}
<add> static async getInitialProps ({ req }) {
<add> return { someDate: Date.now() }
<ide> }
<ide>
<ide> render () {
<ide><path>examples/with-react-intl/scripts/default-lang.js
<del>const {readFileSync, writeFileSync} = require('fs')
<del>const {resolve} = require('path')
<add>const { readFileSync, writeFileSync } = require('fs')
<add>const { resolve } = require('path')
<ide> const glob = require('glob')
<ide>
<del>const defaultMessages = glob.sync('./lang/.messages/**/*.json')
<del> .map((filename) => readFileSync(filename, 'utf8'))
<del> .map((file) => JSON.parse(file))
<add>const defaultMessages = glob
<add> .sync('./lang/.messages/**/*.json')
<add> .map(filename => readFileSync(filename, 'utf8'))
<add> .map(file => JSON.parse(file))
<ide> .reduce((messages, descriptors) => {
<del> descriptors.forEach(({id, defaultMessage}) => {
<add> descriptors.forEach(({ id, defaultMessage }) => {
<ide> if (messages.hasOwnProperty(id)) {
<ide> throw new Error(`Duplicate message id: ${id}`)
<ide> }
<ide><path>examples/with-react-intl/server.js
<ide> const IntlPolyfill = require('intl')
<ide> Intl.NumberFormat = IntlPolyfill.NumberFormat
<ide> Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat
<ide>
<del>const {readFileSync} = require('fs')
<del>const {basename} = require('path')
<del>const {createServer} = require('http')
<add>const { readFileSync } = require('fs')
<add>const { basename } = require('path')
<add>const { createServer } = require('http')
<ide> const accepts = require('accepts')
<ide> const glob = require('glob')
<ide> const next = require('next')
<ide>
<ide> const port = parseInt(process.env.PORT, 10) || 3000
<ide> const dev = process.env.NODE_ENV !== 'production'
<del>const app = next({dev})
<add>const app = next({ dev })
<ide> const handle = app.getRequestHandler()
<ide>
<ide> // Get the supported languages by looking for translations in the `lang/` dir.
<del>const supportedLanguages = glob.sync('./lang/*.json').map((f) => basename(f, '.json'))
<add>const supportedLanguages = glob
<add> .sync('./lang/*.json')
<add> .map(f => basename(f, '.json'))
<ide>
<ide> // We need to expose React Intl's locale data on the request for the user's
<ide> // locale. This function will also cache the scripts by lang in memory.
<ide> const localeDataCache = new Map()
<del>const getLocaleDataScript = (locale) => {
<add>const getLocaleDataScript = locale => {
<ide> const lang = locale.split('-')[0]
<ide> if (!localeDataCache.has(lang)) {
<ide> const localeDataFile = require.resolve(`react-intl/locale-data/${lang}`)
<ide> const getLocaleDataScript = (locale) => {
<ide> // We need to load and expose the translations on the request for the user's
<ide> // locale. These will only be used in production, in dev the `defaultMessage` in
<ide> // each message description in the source code will be used.
<del>const getMessages = (locale) => {
<add>const getMessages = locale => {
<ide> return require(`./lang/${locale}.json`)
<ide> }
<ide>
<ide> app.prepare().then(() => {
<ide> req.localeDataScript = getLocaleDataScript(locale)
<ide> req.messages = dev ? {} : getMessages(locale)
<ide> handle(req, res)
<del> }).listen(port, (err) => {
<add> }).listen(port, err => {
<ide> if (err) throw err
<ide> console.log(`> Ready on http://localhost:${port}`)
<ide> })
<ide><path>examples/with-react-jss/pages/_document.js
<ide> import React from 'react'
<ide> import Document, { Head, Main, NextScript } from 'next/document'
<del>import {
<del> SheetsRegistry,
<del> JssProvider
<del>} from 'react-jss'
<add>import { SheetsRegistry, JssProvider } from 'react-jss'
<ide>
<ide> export default class JssDocument extends Document {
<ide> static getInitialProps (ctx) {
<ide><path>examples/with-react-md/pages/index.js
<ide> import ListItem from 'react-md/lib/Lists/ListItem'
<ide> import NavigationDrawer from 'react-md/lib/NavigationDrawers'
<ide> import SelectField from 'react-md/lib/SelectFields'
<ide>
<del>const avatarSrc = 'https://cloud.githubusercontent.com/assets/13041/19686250/971bf7f8-9ac0-11e6-975c-188defd82df1.png'
<add>const avatarSrc =
<add> 'https://cloud.githubusercontent.com/assets/13041/19686250/971bf7f8-9ac0-11e6-975c-188defd82df1.png'
<ide>
<ide> const drawerHeaderChildren = [
<ide> <Avatar
<ide> key={avatarSrc}
<ide> src={avatarSrc}
<ide> role='presentation'
<ide> iconSized
<del> style={{ alignSelf: 'center', marginLeft: 16, marginRight: 16, flexShrink: 0 }}
<add> style={{
<add> alignSelf: 'center',
<add> marginLeft: 16,
<add> marginRight: 16,
<add> flexShrink: 0
<add> }}
<ide> />,
<ide> <SelectField
<ide> id='account-switcher'
<ide> class NavigationLink extends PureComponent {
<ide> render () {
<ide> const { href, as, children, ..._props } = this.props
<ide> return (
<del> <div {..._props} style={{padding: 0}}>
<add> <div {..._props} style={{ padding: 0 }}>
<ide> <Link href={href} as={as}>
<del> <a className='md-list-tile md-list-tile--mini' style={{width: '100%', overflow: 'hidden'}}>
<add> <a
<add> className='md-list-tile md-list-tile--mini'
<add> style={{ width: '100%', overflow: 'hidden' }}
<add> >
<ide> {children}
<ide> </a>
<ide> </Link>
<ide> export default () => {
<ide> return (
<ide> <div>
<ide> <Head>
<del> <link rel='stylesheet' href='/static/react-md.light_blue-yellow.min.css' />
<del> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500' />
<del> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Material+Icons' />
<add> <link
<add> rel='stylesheet'
<add> href='/static/react-md.light_blue-yellow.min.css'
<add> />
<add> <link
<add> rel='stylesheet'
<add> href='https://fonts.googleapis.com/css?family=Roboto:300,400,500'
<add> />
<add> <link
<add> rel='stylesheet'
<add> href='https://fonts.googleapis.com/css?family=Material+Icons'
<add> />
<ide> </Head>
<ide> <NavigationDrawer
<ide> navItems={[
<ide><path>examples/with-react-native-web/next.config.js
<ide> const withTM = require('next-plugin-transpile-modules')
<ide>
<ide> module.exports = withTM({
<ide> transpileModules: ['react-native-web'],
<del> webpack: (config) => {
<add> webpack: config => {
<ide> // Alias all `react-native` imports to `react-native-web`
<ide> config.resolve.alias = {
<ide> 'react-native$': 'react-native-web'
<ide><path>examples/with-react-relay-network-modern/components/BlogPostPreview.js
<ide> import React from 'react'
<ide> import { createFragmentContainer, graphql } from 'react-relay'
<ide>
<ide> const BlogPostPreview = props => {
<del> return (
<del> <div key={props.post.id}>{props.post.title}</div>
<del> )
<add> return <div key={props.post.id}>{props.post.title}</div>
<ide> }
<ide>
<ide> export default createFragmentContainer(BlogPostPreview, {
<ide> post: graphql`
<del> fragment BlogPostPreview_post on BlogPost {
<del> id
<del> title
<del> }
<del> `
<add> fragment BlogPostPreview_post on BlogPost {
<add> id
<add> title
<add> }
<add> `
<ide> })
<ide><path>examples/with-react-relay-network-modern/components/BlogPosts.js
<ide> const BlogPosts = props => {
<ide> return (
<ide> <div>
<ide> <h1>Blog posts</h1>
<del> {props.viewer.allBlogPosts.edges.map(({ node }) =>
<del> <BlogPostPreview key={node.id}post={node} />
<del> )}
<add> {props.viewer.allBlogPosts.edges.map(({ node }) => (
<add> <BlogPostPreview key={node.id} post={node} />
<add> ))}
<ide> </div>
<ide> )
<ide> }
<ide>
<ide> export default createFragmentContainer(BlogPosts, {
<ide> viewer: graphql`
<del> fragment BlogPosts_viewer on Viewer {
<del> allBlogPosts(first: 10, orderBy: createdAt_DESC) {
<del> edges {
<del> node {
<del> ...BlogPostPreview_post
<del> id
<del> }
<del> }
<del> }
<add> fragment BlogPosts_viewer on Viewer {
<add> allBlogPosts(first: 10, orderBy: createdAt_DESC) {
<add> edges {
<add> node {
<add> ...BlogPostPreview_post
<add> id
<add> }
<ide> }
<del> `
<add> }
<add> }
<add> `
<ide> })
<ide><path>examples/with-react-relay-network-modern/lib/createEnvironment/server.js
<del>import { RelayNetworkLayer, urlMiddleware } from 'react-relay-network-modern/node8'
<add>import {
<add> RelayNetworkLayer,
<add> urlMiddleware
<add>} from 'react-relay-network-modern/node8'
<ide> import RelaySSR from 'react-relay-network-modern-ssr/node8/server'
<ide> import { Network, Environment, RecordSource, Store } from 'relay-runtime'
<ide>
<ide><path>examples/with-react-relay-network-modern/pages/_app.js
<ide> import React from 'react'
<ide> import { QueryRenderer, fetchQuery } from 'react-relay'
<ide> import NextApp, { Container } from 'next/app'
<ide>
<del>import {
<del> initEnvironment,
<del> createEnvironment
<del>} from '../lib/createEnvironment'
<add>import { initEnvironment, createEnvironment } from '../lib/createEnvironment'
<ide>
<ide> export default class App extends NextApp {
<ide> static getInitialProps = async ({ Component, router, ctx }) => {
<del> const { variables } = Component.getInitialProps ? await Component.getInitialProps(ctx) : {}
<add> const { variables } = Component.getInitialProps
<add> ? await Component.getInitialProps(ctx)
<add> : {}
<ide>
<ide> try {
<ide> if (initEnvironment) {
<ide> export default class App extends NextApp {
<ide> return {
<ide> variables
<ide> }
<del> };
<add> }
<ide>
<ide> render () {
<ide> const { Component, variables = {}, relayData } = this.props
<ide><path>examples/with-react-relay-network-modern/pages/index.js
<ide> export default class Index extends Component {
<ide> ...BlogPosts_viewer
<ide> }
<ide> }
<del> `;
<add> `
<ide>
<ide> render () {
<ide> return (
<ide><path>examples/with-react-toolbox/pages/index.js
<ide> export default () => (
<ide> <link href='/static/theme.css' rel='stylesheet' />
<ide> </Head>
<ide> <ThemeProvider theme={theme}>
<del> <Button raised primary>Hello</Button>
<add> <Button raised primary>
<add> Hello
<add> </Button>
<ide> </ThemeProvider>
<ide> </div>
<ide> )
<ide><path>examples/with-react-toolbox/static/theme.js
<del>module.exports = {'RTButton': {'button': '_2Agdx', 'rippleWrapper': '_3AVBi', 'squared': '_2GH_L', 'icon': '_3aBSX', 'solid': '_1ZxqC', 'raised': '_221ic _2Agdx _2GH_L _1ZxqC', 'flat': '_1jWAQ _2Agdx _2GH_L', 'floating': '_3IRMZ _2Agdx _1ZxqC', 'mini': '_2DCN-', 'toggle': 'hC5Z2 _2Agdx', 'primary': '_3tTAW', 'accent': '_2wp6F', 'neutral': '_2CPs4', 'inverse': '_2SPZr'}, 'RTRipple': {'rippleWrapper': '_16N7o', 'ripple': '_3SV_u', 'rippleRestarting': '_2OZWa', 'rippleActive': '_3O2Ue'}, 'RTDatePicker': {'input': '_2ISvI', 'disabled': 'Cf3yF', 'inputElement': 'x7MhN', 'header': '_2vLUd', 'year': '_1VWY-', 'date': '_3K2Ws', 'calendarWrapper': '_1t-4v', 'yearsDisplay': '_2OzvT', 'monthsDisplay': '_2DDdC', 'dialog': '_3fCV6', 'button': '_2hL6u', 'calendar': '_1X9ls', 'prev': 'Nv9Bc', 'next': '_3iPkS', 'title': '_2ESpD', 'years': 'zEdgW', 'active': '_1pjXb', 'week': 'PcByv', 'days': '_1qh3T', 'day': '_2qF_L', 'month': '_1hSm5', 'slideRightEnter': 'Rk89h', 'slideRightLeave': '_1nam4', 'slideRightEnterActive': 'm5B3T', 'slideRightLeaveActive': '_2bZap', 'slideLeftEnter': 'bGml_', 'slideLeftLeave': '_2WGqM', 'slideLeftEnterActive': '_3Ghls', 'slideLeftLeaveActive': '_2WLHG'}, 'RTInput': {'input': 'lFVgC', 'withIcon': '_1nKdf', 'icon': '_3ga1V', 'inputElement': '_4bZUj', 'bar': '_3FySS', 'label': '_34120', 'fixed': 'GRQEP', 'required': '_2G0aY', 'hint': 'bMyi_', 'filled': '_34NWn', 'error': '_2k5Jz', 'counter': '_1oTuT', 'disabled': '_3ZfJq', 'errored': '_2s74E', 'hidden': '_2gAMv'}, 'RTDialog': {'wrapper': '_3nrqp', 'dialog': '_3lw90', 'active': '_3ea_1', 'small': '_38VTT', 'normal': '_1K3iz', 'large': '_10LcP', 'fullscreen': '_3tLXQ', 'title': '_2J-aP', 'body': '_1Ivuq', 'navigation': 'wgwdj', 'button': '_22_c6'}, 'RTOverlay': {'overlay': '_2LA9x', 'active': '_1mb5R'}}
<add>module.exports = {
<add> RTButton: {
<add> button: '_2Agdx',
<add> rippleWrapper: '_3AVBi',
<add> squared: '_2GH_L',
<add> icon: '_3aBSX',
<add> solid: '_1ZxqC',
<add> raised: '_221ic _2Agdx _2GH_L _1ZxqC',
<add> flat: '_1jWAQ _2Agdx _2GH_L',
<add> floating: '_3IRMZ _2Agdx _1ZxqC',
<add> mini: '_2DCN-',
<add> toggle: 'hC5Z2 _2Agdx',
<add> primary: '_3tTAW',
<add> accent: '_2wp6F',
<add> neutral: '_2CPs4',
<add> inverse: '_2SPZr'
<add> },
<add> RTRipple: {
<add> rippleWrapper: '_16N7o',
<add> ripple: '_3SV_u',
<add> rippleRestarting: '_2OZWa',
<add> rippleActive: '_3O2Ue'
<add> },
<add> RTDatePicker: {
<add> input: '_2ISvI',
<add> disabled: 'Cf3yF',
<add> inputElement: 'x7MhN',
<add> header: '_2vLUd',
<add> year: '_1VWY-',
<add> date: '_3K2Ws',
<add> calendarWrapper: '_1t-4v',
<add> yearsDisplay: '_2OzvT',
<add> monthsDisplay: '_2DDdC',
<add> dialog: '_3fCV6',
<add> button: '_2hL6u',
<add> calendar: '_1X9ls',
<add> prev: 'Nv9Bc',
<add> next: '_3iPkS',
<add> title: '_2ESpD',
<add> years: 'zEdgW',
<add> active: '_1pjXb',
<add> week: 'PcByv',
<add> days: '_1qh3T',
<add> day: '_2qF_L',
<add> month: '_1hSm5',
<add> slideRightEnter: 'Rk89h',
<add> slideRightLeave: '_1nam4',
<add> slideRightEnterActive: 'm5B3T',
<add> slideRightLeaveActive: '_2bZap',
<add> slideLeftEnter: 'bGml_',
<add> slideLeftLeave: '_2WGqM',
<add> slideLeftEnterActive: '_3Ghls',
<add> slideLeftLeaveActive: '_2WLHG'
<add> },
<add> RTInput: {
<add> input: 'lFVgC',
<add> withIcon: '_1nKdf',
<add> icon: '_3ga1V',
<add> inputElement: '_4bZUj',
<add> bar: '_3FySS',
<add> label: '_34120',
<add> fixed: 'GRQEP',
<add> required: '_2G0aY',
<add> hint: 'bMyi_',
<add> filled: '_34NWn',
<add> error: '_2k5Jz',
<add> counter: '_1oTuT',
<add> disabled: '_3ZfJq',
<add> errored: '_2s74E',
<add> hidden: '_2gAMv'
<add> },
<add> RTDialog: {
<add> wrapper: '_3nrqp',
<add> dialog: '_3lw90',
<add> active: '_3ea_1',
<add> small: '_38VTT',
<add> normal: '_1K3iz',
<add> large: '_10LcP',
<add> fullscreen: '_3tLXQ',
<add> title: '_2J-aP',
<add> body: '_1Ivuq',
<add> navigation: 'wgwdj',
<add> button: '_22_c6'
<add> },
<add> RTOverlay: { overlay: '_2LA9x', active: '_1mb5R' }
<add>}
<ide><path>examples/with-react-useragent/pages/_app.js
<ide> import React from 'react'
<del>import App, {Container} from 'next/app'
<del>import {UserAgentProvider} from '@quentin-sommer/react-useragent'
<add>import App, { Container } from 'next/app'
<add>import { UserAgentProvider } from '@quentin-sommer/react-useragent'
<ide>
<ide> const PageWrapper = Comp =>
<ide> class extends React.Component {
<ide> const PageWrapper = Comp =>
<ide> }
<ide>
<ide> render () {
<del> const {ua, ...props} = this.props
<add> const { ua, ...props } = this.props
<ide> return (
<ide> <UserAgentProvider ua={ua}>
<ide> <Comp {...props} />
<ide> const PageWrapper = Comp =>
<ide>
<ide> class MyApp extends App {
<ide> render () {
<del> const {Component, pageProps} = this.props
<add> const { Component, pageProps } = this.props
<ide> return (
<ide> <Container>
<ide> <Component {...pageProps} />
<ide><path>examples/with-react-useragent/pages/index.js
<del>import React, {Component} from 'react'
<del>import {UserAgent} from '@quentin-sommer/react-useragent'
<add>import React, { Component } from 'react'
<add>import { UserAgent } from '@quentin-sommer/react-useragent'
<ide>
<ide> class Index extends Component {
<ide> render () {
<ide><path>examples/with-react-uwp/components/ThemeWrapper.js
<ide> export class ThemeWrapper extends Component {
<ide> render () {
<ide> const { children, style, ...props } = this.props
<ide> return (
<del> <Theme {...props} style={(props && props.theme) ? props.theme.prepareStyles(style) : void 0}>
<add> <Theme
<add> {...props}
<add> style={props && props.theme ? props.theme.prepareStyles(style) : void 0}
<add> >
<ide> {children}
<ide> </Theme>
<ide> )
<ide><path>examples/with-react-uwp/pages/_document.js
<ide> import Document, { Head, Main, NextScript } from 'next/document'
<ide>
<ide> export default class MyDocument extends Document {
<ide> static getInitialProps ({ renderPage }) {
<del> const {html, head, errorHtml, chunks} = renderPage()
<add> const { html, head, errorHtml, chunks } = renderPage()
<ide> return { html, head, errorHtml, chunks }
<ide> }
<ide>
<del> static contextTypes = { theme: PropTypes.object };
<add> static contextTypes = { theme: PropTypes.object }
<ide>
<ide> render () {
<ide> return (
<ide> <html lang='en'>
<ide> <Head>
<ide> <meta charSet='utf-8' />
<del> <meta name='viewport' content='user-scalable=0, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height' />
<add> <meta
<add> name='viewport'
<add> content='user-scalable=0, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height'
<add> />
<ide> <meta name='theme-color' content='yellowgreen' />
<del> <link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto:300,400,500' />
<add> <link
<add> rel='stylesheet'
<add> href='https://fonts.googleapis.com/css?family=Roboto:300,400,500'
<add> />
<ide> </Head>
<ide> <body>
<ide> <Main />
<ide><path>examples/with-react-uwp/pages/index.js
<ide> import PropTypes from 'prop-types'
<ide> import ThemeWrapper from '../components/ThemeWrapper'
<ide> import getTheme from 'react-uwp/styles/getTheme'
<ide>
<del>import {
<del> Button,
<del> ColorPicker,
<del> DatePicker,
<del> ProgressRing
<del>} from 'react-uwp'
<add>import { Button, ColorPicker, DatePicker, ProgressRing } from 'react-uwp'
<ide>
<ide> class Index extends Component {
<ide> static async getInitialProps ({ req }) {
<ide><path>examples/with-react-with-styles/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> return (
<ide> <html>
<ide> <Head>
<del> <style data-aphrodite dangerouslySetInnerHTML={{ __html: this.props.css.content }} />
<add> <style
<add> data-aphrodite
<add> dangerouslySetInnerHTML={{ __html: this.props.css.content }}
<add> />
<ide> </Head>
<ide> <body>
<ide> <Main />
<ide><path>examples/with-rebass/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide>
<ide> return (
<ide> <html>
<del> <Head>
<del> {styleTags}
<del> </Head>
<add> <Head>{styleTags}</Head>
<ide> <body>
<del> <div className='root'>
<del> {main}
<del> </div>
<add> <div className='root'>{main}</div>
<ide> <NextScript />
<ide> </body>
<ide> </html>
<ide><path>examples/with-rebass/pages/index.js
<ide> function HomePage () {
<ide>
<ide> <Container>
<ide> <Toolbar bg='black'>
<del> <NavLink href='https://github.com/zeit/next.js/' target='_blank'>Next.js</NavLink>
<add> <NavLink href='https://github.com/zeit/next.js/' target='_blank'>
<add> Next.js
<add> </NavLink>
<ide> <NavLink ml='auto' href='http://jxnblk.com/rebass/' target='_blank'>
<ide> REBASS
<ide> </NavLink>
<ide> function HomePage () {
<ide> <Flex justify='center'>
<ide> <Box width={1 / 2}>
<ide> <Blockquote center fontSize={3} py={4}>
<del> "Next.js is a minimalistic framework for server-rendered React applications."
<add> "Next.js is a minimalistic framework for server-rendered React
<add> applications."
<ide> </Blockquote>
<ide> </Box>
<ide> <Box width={6 / 12}>
<ide> <Blockquote center fontSize={3} py={4}>
<del> "Functional React UI component library, built with styled-components"
<add> "Functional React UI component library, built with
<add> styled-components"
<ide> </Blockquote>
<ide> </Box>
<ide> </Flex>
<ide><path>examples/with-recompose/pages/index.js
<ide> import { compose, withState, setStatic } from 'recompose'
<ide> // it needs to be at the top of the compose
<ide> const enhance = compose(
<ide> // set the static async method getInitialProps
<del> setStatic(
<del> 'getInitialProps',
<del> async ({ req }) => {
<del> const isServer = !!req
<del> // log if we're server or client side
<del> if (isServer) console.log('from server')
<del> else console.log('from client')
<del> // return a prop to know if we're server or client side
<del> return { isServer }
<del> }
<del> ),
<del> withState(
<del> 'counter',
<del> 'setCounter',
<del> 0
<del> )
<add> setStatic('getInitialProps', async ({ req }) => {
<add> const isServer = !!req
<add> // log if we're server or client side
<add> if (isServer) console.log('from server')
<add> else console.log('from client')
<add> // return a prop to know if we're server or client side
<add> return { isServer }
<add> }),
<add> withState('counter', 'setCounter', 0)
<ide> )
<ide>
<ide> // our enhanced page component
<ide><path>examples/with-redux-code-splitting/config/redux.js
<ide> import withRedux from 'next-redux-wrapper'
<ide> import { rootReducer } from 'fast-redux'
<ide>
<ide> export const initStore = (initialState = {}) => {
<del> return createStore(rootReducer, initialState,
<del> composeWithDevTools(applyMiddleware(thunkMiddleware)))
<add> return createStore(
<add> rootReducer,
<add> initialState,
<add> composeWithDevTools(applyMiddleware(thunkMiddleware))
<add> )
<ide> }
<ide>
<del>export const reduxPage = (comp) => withRedux(initStore)(comp)
<add>export const reduxPage = comp => withRedux(initStore)(comp)
<ide><path>examples/with-redux-code-splitting/containers/about.js
<ide> import React from 'react'
<del>import {bindActionCreators} from 'redux'
<del>import {connect} from 'react-redux'
<del>import {namespaceConfig} from 'fast-redux'
<add>import { bindActionCreators } from 'redux'
<add>import { connect } from 'react-redux'
<add>import { namespaceConfig } from 'fast-redux'
<ide> import Link from 'next/link'
<ide>
<del>const DEFAULT_STATE = {version: 1}
<add>const DEFAULT_STATE = { version: 1 }
<ide>
<del>const {actionCreator, getState: getAboutState} = namespaceConfig('about', DEFAULT_STATE)
<add>const { actionCreator, getState: getAboutState } = namespaceConfig(
<add> 'about',
<add> DEFAULT_STATE
<add>)
<ide>
<ide> const bumpVersion = actionCreator('bumpVersion', function (state, increment) {
<del> return {...state, version: state.version + increment}
<add> return { ...state, version: state.version + increment }
<ide> })
<ide>
<ide> const About = ({ version, bumpVersion }) => (
<ide> <div>
<ide> <h1>About us</h1>
<ide> <h3>Current version: {version}</h3>
<del> <p><button onClick={(e) => bumpVersion(1)}>Bump version!</button></p>
<del> <Link href='/'><a>Homepage</a></Link>
<add> <p>
<add> <button onClick={e => bumpVersion(1)}>Bump version!</button>
<add> </p>
<add> <Link href='/'>
<add> <a>Homepage</a>
<add> </Link>
<ide> </div>
<ide> )
<ide>
<ide> function mapDispatchToProps (dispatch) {
<ide> return bindActionCreators({ bumpVersion }, dispatch)
<ide> }
<ide>
<del>export default connect(mapStateToProps, mapDispatchToProps)(About)
<add>export default connect(
<add> mapStateToProps,
<add> mapDispatchToProps
<add>)(About)
<ide><path>examples/with-redux-code-splitting/containers/homepage.js
<ide> import React from 'react'
<del>import {bindActionCreators} from 'redux'
<del>import {connect} from 'react-redux'
<del>import {namespaceConfig} from 'fast-redux'
<add>import { bindActionCreators } from 'redux'
<add>import { connect } from 'react-redux'
<add>import { namespaceConfig } from 'fast-redux'
<ide> import Link from 'next/link'
<ide>
<del>const DEFAULT_STATE = {build: 1}
<add>const DEFAULT_STATE = { build: 1 }
<ide>
<del>const {actionCreator, getState: getHomepageState} = namespaceConfig('homepage', DEFAULT_STATE)
<add>const { actionCreator, getState: getHomepageState } = namespaceConfig(
<add> 'homepage',
<add> DEFAULT_STATE
<add>)
<ide>
<ide> const bumpBuild = actionCreator(function bumpBuild (state, increment) {
<del> return {...state, build: state.build + increment}
<add> return { ...state, build: state.build + increment }
<ide> })
<ide>
<ide> const Homepage = ({ build, bumpBuild }) => (
<ide> <div>
<ide> <h1>Homepage</h1>
<ide> <h3>Current build: {build}</h3>
<del> <p><button onClick={(e) => bumpBuild(1)}>Bump build!</button></p>
<del> <Link href='/about'><a>About Us</a></Link>
<add> <p>
<add> <button onClick={e => bumpBuild(1)}>Bump build!</button>
<add> </p>
<add> <Link href='/about'>
<add> <a>About Us</a>
<add> </Link>
<ide> </div>
<ide> )
<ide>
<ide> function mapDispatchToProps (dispatch) {
<ide> return bindActionCreators({ bumpBuild }, dispatch)
<ide> }
<ide>
<del>export default connect(mapStateToProps, mapDispatchToProps)(Homepage)
<add>export default connect(
<add> mapStateToProps,
<add> mapDispatchToProps
<add>)(Homepage)
<ide><path>examples/with-redux-code-splitting/pages/about.js
<del>import {reduxPage} from '../config/redux'
<add>import { reduxPage } from '../config/redux'
<ide> import About from '../containers/about'
<ide>
<ide> export default reduxPage(About)
<ide><path>examples/with-redux-code-splitting/pages/index.js
<del>import {reduxPage} from '../config/redux'
<add>import { reduxPage } from '../config/redux'
<ide> import Homepage from '../containers/homepage'
<ide>
<ide> export default reduxPage(Homepage)
<ide><path>examples/with-redux-observable/components/CharacterInfo.js
<ide> import React from 'react'
<ide> import { connect } from 'react-redux'
<ide>
<del>const CharacterInfo = ({ character, error, fetchCharacter, isFetchedOnServer = false }) => (
<add>const CharacterInfo = ({
<add> character,
<add> error,
<add> fetchCharacter,
<add> isFetchedOnServer = false
<add>}) => (
<ide> <div className='CharacterInfo'>
<del> {
<del> error ? <p>We encountered and error.</p>
<del> : <article>
<del> <h3>Character: {character.name}</h3>
<del> <p>birth year: {character.birth_year}</p>
<del> <p>gender: {character.gender}</p>
<del> <p>skin color: {character.skin_color}</p>
<del> <p>eye color: {character.eye_color}</p>
<del> </article>
<del>
<del> }
<add> {error ? (
<add> <p>We encountered and error.</p>
<add> ) : (
<add> <article>
<add> <h3>Character: {character.name}</h3>
<add> <p>birth year: {character.birth_year}</p>
<add> <p>gender: {character.gender}</p>
<add> <p>skin color: {character.skin_color}</p>
<add> <p>eye color: {character.eye_color}</p>
<add> </article>
<add> )}
<ide> <p>
<del> (was character fetched on server? -{' '}
<del> <b>{isFetchedOnServer.toString()})</b>
<add> (was character fetched on server? - <b>{isFetchedOnServer.toString()})</b>
<ide> </p>
<ide> <style jsx>{`
<ide> article {
<del> background-color: #528CE0;
<add> background-color: #528ce0;
<ide> border-radius: 15px;
<ide> padding: 15px;
<ide> width: 250px;
<ide> const CharacterInfo = ({ character, error, fetchCharacter, isFetchedOnServer = f
<ide> </div>
<ide> )
<ide>
<del>export default connect(
<del> state => ({
<del> character: state.character,
<del> error: state.error,
<del> isFetchedOnServer: state.isFetchedOnServer
<del> })
<del>)(CharacterInfo)
<add>export default connect(state => ({
<add> character: state.character,
<add> error: state.error,
<add> isFetchedOnServer: state.isFetchedOnServer
<add>}))(CharacterInfo)
<ide><path>examples/with-redux-observable/pages/index.js
<ide> class Counter extends React.Component {
<ide> <CharacterInfo />
<ide> <br />
<ide> <nav>
<del> <Link href='/other'><a>Navigate to "/other"</a></Link>
<add> <Link href='/other'>
<add> <a>Navigate to "/other"</a>
<add> </Link>
<ide> </nav>
<ide> </div>
<ide> )
<ide><path>examples/with-redux-observable/redux/epics.js
<ide> export const fetchUserEpic = (action$, state$) =>
<ide> mergeMap(action => {
<ide> return interval(3000).pipe(
<ide> map(x => actions.fetchCharacter()),
<del> takeUntil(action$.ofType(
<del> types.STOP_FETCHING_CHARACTERS,
<del> types.FETCH_CHARACTER_FAILURE
<del> ))
<add> takeUntil(
<add> action$.ofType(
<add> types.STOP_FETCHING_CHARACTERS,
<add> types.FETCH_CHARACTER_FAILURE
<add> )
<add> )
<ide> )
<ide> })
<ide> )
<ide> export const fetchCharacterEpic = (action$, state$) =>
<ide> )
<ide> )
<ide>
<del>export const rootEpic = combineEpics(
<del> fetchUserEpic,
<del> fetchCharacterEpic
<del>)
<add>export const rootEpic = combineEpics(fetchUserEpic, fetchCharacterEpic)
<ide><path>examples/with-redux-observable/redux/index.js
<ide> export default function initStore (initialState) {
<ide> epicMiddleware.run(rootEpic)
<ide>
<ide> return store
<del>};
<add>}
<ide><path>examples/with-redux-observable/redux/reducer.js
<ide> export default function reducer (state = INITIAL_STATE, { type, payload }) {
<ide> nextCharacterId: state.nextCharacterId + 1
<ide> }
<ide> case types.FETCH_CHARACTER_FAILURE:
<del> return { ...state, error: payload.error, isFetchedOnServer: payload.isServer }
<add> return {
<add> ...state,
<add> error: payload.error,
<add> isFetchedOnServer: payload.isServer
<add> }
<ide> default:
<ide> return state
<ide> }
<ide><path>examples/with-redux-reselect-recompose/actions/index.js
<ide> export const addCount = () => ({ type: ADD })
<ide>
<ide> export const setClock = (light, ts) => ({ type: TICK, light, ts })
<ide>
<del>export const serverRenderClock = isServer => dispatch => dispatch(setClock(!isServer, Date.now()))
<add>export const serverRenderClock = isServer => dispatch =>
<add> dispatch(setClock(!isServer, Date.now()))
<ide>
<del>export const startClock = () => dispatch => setInterval(() => dispatch(setClock(true, Date.now())), 800)
<add>export const startClock = () => dispatch =>
<add> setInterval(() => dispatch(setClock(true, Date.now())), 800)
<ide><path>examples/with-redux-reselect-recompose/components/addCount.js
<ide> import React from 'react'
<ide> import PropTypes from 'prop-types'
<ide> import { compose, setDisplayName, pure, setPropTypes } from 'recompose'
<ide>
<del>const AddCount = ({ count, addCount }) =>
<add>const AddCount = ({ count, addCount }) => (
<ide> <div>
<ide> <style jsx>{`
<ide> div {
<ide> padding: 0 0 20px 0;
<ide> }
<del> `}</style>
<del> <h1>AddCount: <span>{count}</span></h1>
<add> `}</style>
<add> <h1>
<add> AddCount: <span>{count}</span>
<add> </h1>
<ide> <button onClick={addCount}>Add To Count</button>
<ide> </div>
<add>)
<ide>
<ide> export default compose(
<ide> setDisplayName('AddCount'),
<ide><path>examples/with-redux-reselect-recompose/components/clock.js
<ide> import React from 'react'
<ide> import PropTypes from 'prop-types'
<ide> import { compose, pure, setDisplayName, setPropTypes } from 'recompose'
<ide>
<del>const format = t => `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<add>const format = t =>
<add> `${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}`
<ide>
<del>const pad = n => n < 10 ? `0${n}` : n
<add>const pad = n => (n < 10 ? `0${n}` : n)
<ide>
<del>const Clock = ({ lastUpdate, light }) =>
<add>const Clock = ({ lastUpdate, light }) => (
<ide> <div className={light ? 'light' : ''}>
<ide> {format(new Date(lastUpdate))}
<ide> <style jsx>{`
<ide> div {
<ide> padding: 15px;
<ide> display: inline-block;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> }
<ide> const Clock = ({ lastUpdate, light }) =>
<ide> }
<ide> `}</style>
<ide> </div>
<add>)
<ide>
<ide> export default compose(
<ide> setDisplayName('Clock'),
<ide><path>examples/with-redux-reselect-recompose/components/page.js
<ide> import { compose, setDisplayName, pure, setPropTypes } from 'recompose'
<ide> import Clock from './clock'
<ide> import AddCount from './addCount'
<ide>
<del>const Page = ({ title, linkTo, light, lastUpdate, count, addCount }) =>
<add>const Page = ({ title, linkTo, light, lastUpdate, count, addCount }) => (
<ide> <div>
<ide> <h1>{title}</h1>
<ide> <Clock lastUpdate={lastUpdate} light={light} />
<ide> <AddCount count={count} addCount={addCount} />
<ide> <nav>
<del> <Link href={linkTo}><a>Navigate</a></Link>
<add> <Link href={linkTo}>
<add> <a>Navigate</a>
<add> </Link>
<ide> </nav>
<ide> </div>
<add>)
<ide>
<ide> export default compose(
<ide> setDisplayName('Page'),
<ide><path>examples/with-redux-reselect-recompose/containers/page.js
<ide> import Page from 'components/page'
<ide>
<ide> export default compose(
<ide> setDisplayName('PageContainer'),
<del> connect(createSelector(
<del> selectLight(),
<del> selectLastUpdate(),
<del> selectCount(),
<del> (light, lastUpdate, count) => ({ light, lastUpdate, count })
<del> ), { addCount }),
<add> connect(
<add> createSelector(
<add> selectLight(),
<add> selectLastUpdate(),
<add> selectCount(),
<add> (light, lastUpdate, count) => ({ light, lastUpdate, count })
<add> ),
<add> { addCount }
<add> ),
<ide> pure
<ide> )(Page)
<ide><path>examples/with-redux-reselect-recompose/selectors/index.js
<ide> import { createSelector } from 'reselect'
<ide>
<ide> export const selectState = () => state => state.count
<ide>
<del>export const selectCount = () => createSelector(
<del> selectState(),
<del> count => count.count
<del>)
<add>export const selectCount = () =>
<add> createSelector(
<add> selectState(),
<add> count => count.count
<add> )
<ide>
<del>export const selectLight = () => createSelector(
<del> selectState(),
<del> count => count.light
<del>)
<add>export const selectLight = () =>
<add> createSelector(
<add> selectState(),
<add> count => count.light
<add> )
<ide>
<del>export const selectLastUpdate = () => createSelector(
<del> selectState(),
<del> count => count.lastUpdate
<del>)
<add>export const selectLastUpdate = () =>
<add> createSelector(
<add> selectState(),
<add> count => count.lastUpdate
<add> )
<ide><path>examples/with-redux-reselect-recompose/store.js
<ide> import reducer, { initialState } from 'reducers'
<ide>
<ide> export default (state = initialState) => {
<ide> const middlewares = [thunkMiddleware, createLogger()]
<del> return createStore(
<del> reducer,
<del> state,
<del> compose(applyMiddleware(...middlewares))
<del> )
<add> return createStore(reducer, state, compose(applyMiddleware(...middlewares)))
<ide> }
<ide><path>examples/with-redux-saga/actions.js
<ide> export function failure (error) {
<ide> }
<ide>
<ide> export function increment () {
<del> return {type: actionTypes.INCREMENT}
<add> return { type: actionTypes.INCREMENT }
<ide> }
<ide>
<ide> export function decrement () {
<del> return {type: actionTypes.DECREMENT}
<add> return { type: actionTypes.DECREMENT }
<ide> }
<ide>
<ide> export function reset () {
<del> return {type: actionTypes.RESET}
<add> return { type: actionTypes.RESET }
<ide> }
<ide>
<ide> export function loadData () {
<del> return {type: actionTypes.LOAD_DATA}
<add> return { type: actionTypes.LOAD_DATA }
<ide> }
<ide>
<ide> export function loadDataSuccess (data) {
<ide> export function loadDataSuccess (data) {
<ide> }
<ide>
<ide> export function startClock () {
<del> return {type: actionTypes.START_CLOCK}
<add> return { type: actionTypes.START_CLOCK }
<ide> }
<ide>
<ide> export function tickClock (isServer) {
<ide><path>examples/with-redux-saga/components/clock.js
<ide> const format = t => {
<ide> return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`
<ide> }
<ide>
<del>function Clock ({lastUpdate, light}) {
<add>function Clock ({ lastUpdate, light }) {
<ide> return (
<ide> <div className={light ? 'light' : ''}>
<ide> {format(new Date(lastUpdate))}
<ide> <style jsx>{`
<ide> div {
<ide> padding: 15px;
<ide> display: inline-block;
<del> color: #82FA58;
<add> color: #82fa58;
<ide> font: 50px menlo, monaco, monospace;
<ide> background-color: #000;
<ide> }
<ide><path>examples/with-redux-saga/components/counter.js
<del>import React, {Component} from 'react'
<del>import {connect} from 'react-redux'
<add>import React, { Component } from 'react'
<add>import { connect } from 'react-redux'
<ide>
<del>import {increment, decrement, reset} from '../actions'
<add>import { increment, decrement, reset } from '../actions'
<ide>
<ide> class Counter extends Component {
<ide> increment = () => {
<ide> class Counter extends Component {
<ide> }
<ide>
<ide> render () {
<del> const {count} = this.props
<add> const { count } = this.props
<ide> return (
<ide> <div>
<ide> <style jsx>{`
<ide> class Counter extends Component {
<ide> }
<ide> }
<ide>
<del>const mapStateToProps = ({count}) => ({count})
<add>const mapStateToProps = ({ count }) => ({ count })
<ide> export default connect(mapStateToProps)(Counter)
<ide><path>examples/with-redux-saga/components/page.js
<ide> import Link from 'next/link'
<del>import {connect} from 'react-redux'
<add>import { connect } from 'react-redux'
<ide>
<ide> import Counter from './counter'
<ide> import Clock from './clock'
<ide>
<del>function Page ({error, lastUpdate, light, linkTo, NavigateTo, placeholderData, title}) {
<add>function Page ({
<add> error,
<add> lastUpdate,
<add> light,
<add> linkTo,
<add> NavigateTo,
<add> placeholderData,
<add> title
<add>}) {
<ide> return (
<ide> <div>
<del> <h1>
<del> {title}
<del> </h1>
<add> <h1>{title}</h1>
<ide> <Clock lastUpdate={lastUpdate} light={light} />
<ide> <Counter />
<ide> <nav>
<ide> <Link href={linkTo}>
<ide> <a>Navigate: {NavigateTo}</a>
<ide> </Link>
<ide> </nav>
<del> {placeholderData &&
<add> {placeholderData && (
<ide> <pre>
<del> <code>
<del> {JSON.stringify(placeholderData, null, 2)}
<del> </code>
<del> </pre>}
<del> {error &&
<del> <p style={{color: 'red'}}>
<del> Error: {error.message}
<del> </p>}
<add> <code>{JSON.stringify(placeholderData, null, 2)}</code>
<add> </pre>
<add> )}
<add> {error && <p style={{ color: 'red' }}>Error: {error.message}</p>}
<ide> </div>
<ide> )
<ide> }
<ide><path>examples/with-redux-saga/pages/index.js
<ide> import React from 'react'
<del>import {connect} from 'react-redux'
<add>import { connect } from 'react-redux'
<ide>
<del>import {loadData, startClock, tickClock} from '../actions'
<add>import { loadData, startClock, tickClock } from '../actions'
<ide> import Page from '../components/page'
<ide>
<ide> class Index extends React.Component { | 300 |
Javascript | Javascript | fix typos and redundant words | ba8c987391a56c68cf1b0d8decd74e19092069c7 | <ide><path>src/renderers/dom/client/ReactReconcileTransaction.js
<ide> var EVENT_SUPPRESSION = {
<ide>
<ide> /**
<ide> * Provides a queue for collecting `componentDidMount` and
<del> * `componentDidUpdate` callbacks during the the transaction.
<add> * `componentDidUpdate` callbacks during the transaction.
<ide> */
<ide> var ON_DOM_READY_QUEUEING = {
<ide> /**
<ide><path>src/renderers/dom/shared/HTMLDOMPropertyConfig.js
<ide> var HTMLDOMPropertyConfig = {
<ide> itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
<ide> itemType: MUST_USE_ATTRIBUTE,
<ide> // itemID and itemRef are for Microdata support as well but
<del> // only specified in the the WHATWG spec document. See
<add> // only specified in the WHATWG spec document. See
<ide> // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
<ide> itemID: MUST_USE_ATTRIBUTE,
<ide> itemRef: MUST_USE_ATTRIBUTE,
<ide><path>src/renderers/shared/event/eventPlugins/ResponderEventPlugin.js
<ide> var eventTypes = {
<ide> * immediately to indicate so, either by highlighting or moving accordingly.
<ide> * - To be the responder means, that touches are exclusively important to that
<ide> * responder view, and no other view.
<del> * - While touches are still occuring, the responder lock can be transfered to
<add> * - While touches are still occurring, the responder lock can be transferred to
<ide> * a new view, but only to increasingly "higher" views (meaning ancestors of
<ide> * the current responder).
<ide> *
<ide> function setResponderAndExtractTransfer(
<ide> eventTypes.selectionChangeShouldSetResponder :
<ide> eventTypes.scrollShouldSetResponder;
<ide>
<del> // TODO: stop one short of the the current responder.
<add> // TODO: stop one short of the current responder.
<ide> var bubbleShouldSetFrom = !responderInst ?
<ide> targetInst :
<ide> EventPluginUtils.getLowestCommonAncestor(responderInst, targetInst);
<ide> var ResponderEventPlugin = {
<ide> nativeEvent,
<ide> nativeEventTarget) :
<ide> null;
<del> // Responder may or may not have transfered on a new touch start/move.
<add> // Responder may or may not have transferred on a new touch start/move.
<ide> // Regardless, whoever is the responder after any potential transfer, we
<ide> // direct all touch start/move/ends to them in the form of
<ide> // `onResponderMove/Start/End`. These will be called for *every* additional
<ide><path>src/renderers/shared/event/eventPlugins/__tests__/ResponderEventPlugin-test.js
<ide> describe('ResponderEventPlugin', function() {
<ide>
<ide> config = oneEventLoopTestConfig(three);
<ide>
<del> // Parent is responder, and responder is transfered by a second touch start
<add> // Parent is responder, and responder is transferred by a second touch start
<ide> config.startShouldSetResponder.captured.grandParent = {order: 0, returnVal: true};
<ide> config.responderTerminationRequest.parent = {order: 1, returnVal: true};
<ide> config.responderGrant.grandParent = {order: 2}; | 4 |
Ruby | Ruby | call tap not formula | 478e4f112c5482a0424c0a27c6d9d10fea3d2c07 | <ide><path>Library/Homebrew/formulary.rb
<ide> def get_formula(spec, alias_path: nil)
<ide> def load_file
<ide> super
<ide> rescue MethodDeprecatedError => e
<del> e.issues_url = formula.tap.issues_url || formula.tap.to_s
<add> e.issues_url = tap.issues_url || tap.to_s
<ide> raise
<ide> end
<ide> end | 1 |
PHP | PHP | use null coalescing operator where possible | f4ea4574c83eb80da1aa4f40b6117fd1488afef7 | <ide><path>src/Auth/BaseAuthenticate.php
<ide> protected function _query(string $username): Query
<ide> $finder = key($finder);
<ide> }
<ide>
<del> if (!isset($options['username'])) {
<del> $options['username'] = $username;
<del> }
<add> $options['username'] = $options['username'] ?? $username;
<ide>
<ide> return $table->find($finder, $options);
<ide> }
<ide><path>src/Command/I18nExtractCommand.php
<ide> protected function _buildFiles(Arguments $args): void
<ide> */
<ide> protected function _store(string $domain, string $header, string $sentence): void
<ide> {
<del> if (!isset($this->_storage[$domain])) {
<del> $this->_storage[$domain] = [];
<del> }
<add> $this->_storage[$domain] = $this->_storage[$domain] ?? [];
<add>
<ide> if (!isset($this->_storage[$domain][$sentence])) {
<ide> $this->_storage[$domain][$sentence] = $header;
<ide> } else {
<ide><path>src/Console/Arguments.php
<ide> public function getOptions(): array
<ide> */
<ide> public function getOption(string $name)
<ide> {
<del> if (isset($this->options[$name])) {
<del> return $this->options[$name];
<del> }
<del>
<del> return null;
<add> return $this->options[$name] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/Console/CommandRunner.php
<ide> protected function resolveName(CommandCollection $commands, ConsoleIo $io, ?stri
<ide> $io->err('<error>No command provided. Choose one of the available commands.</error>', 2);
<ide> $name = 'help';
<ide> }
<del> if (isset($this->aliases[$name])) {
<del> $name = $this->aliases[$name];
<del> }
<add> $name = $this->aliases[$name] ?? $name;
<ide> if (!$commands->has($name)) {
<ide> $name = Inflector::underscore($name);
<ide> }
<ide><path>src/Console/Shell.php
<ide> public function dispatchShell(): int
<ide> {
<ide> [$args, $extra] = $this->parseDispatchArguments(func_get_args());
<ide>
<del> if (!isset($extra['requested'])) {
<del> $extra['requested'] = true;
<del> }
<add> $extra['requested'] = $extra['requested'] ?? true;
<ide> /** @psalm-suppress DeprecatedClass */
<ide> $dispatcher = new ShellDispatcher($args, false);
<ide>
<ide> public function __get(string $name)
<ide> */
<ide> public function param(string $name)
<ide> {
<del> if (!isset($this->params[$name])) {
<del> return null;
<del> }
<del>
<del> return $this->params[$name];
<add> return $this->params[$name] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/Controller/Component.php
<ide> public function __get(string $name)
<ide> $config = (array)$this->_componentMap[$name]['config'] + ['enabled' => false];
<ide> $this->{$name} = $this->_registry->load($this->_componentMap[$name]['class'], $config);
<ide> }
<del> if (!isset($this->{$name})) {
<del> return null;
<del> }
<ide>
<del> return $this->{$name};
<add> return $this->{$name} ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function respondAs($type, array $options = []): bool
<ide> $cType = $response->getMimeType($type);
<ide> }
<ide> if (is_array($cType)) {
<del> if (isset($cType[$options['index']])) {
<del> $cType = $cType[$options['index']];
<del> }
<add> $cType = $cType[$options['index']] ?? $cType;
<ide>
<ide> if ($this->prefers($cType)) {
<ide> $cType = $this->prefers($cType);
<ide><path>src/Core/ClassLoader.php
<ide> public function addNamespace(string $prefix, string $baseDir, bool $prepend = fa
<ide> $baseDir = rtrim($baseDir, '/') . DIRECTORY_SEPARATOR;
<ide> $baseDir = rtrim($baseDir, DIRECTORY_SEPARATOR) . '/';
<ide>
<del> if (!isset($this->_prefixes[$prefix])) {
<del> $this->_prefixes[$prefix] = [];
<del> }
<add> $this->_prefixes[$prefix] = $this->_prefixes[$prefix] ?? [];
<ide>
<ide> if ($prepend) {
<ide> array_unshift($this->_prefixes[$prefix], $baseDir);
<ide><path>src/Core/InstanceConfigTrait.php
<ide> protected function _configWrite($key, $value, $merge = false): void
<ide> throw new CakeException(sprintf('Cannot set %s value', $key));
<ide> }
<ide>
<del> if (!isset($update[$k])) {
<del> $update[$k] = [];
<del> }
<add> $update[$k] = $update[$k] ?? [];
<ide>
<ide> $update = &$update[$k];
<ide> }
<ide><path>src/Core/functions.php
<ide> function env(string $key, $default = null)
<ide> $key = 'SCRIPT_URL';
<ide> }
<ide>
<del> $val = null;
<del> if (isset($_SERVER[$key])) {
<del> $val = $_SERVER[$key];
<del> } elseif (isset($_ENV[$key])) {
<del> $val = $_ENV[$key];
<del> } elseif (getenv($key) !== false) {
<add> $val = $_SERVER[$key] ?? $_ENV[$key] ?? null;
<add> if ($val == null && getenv($key) !== false) {
<ide> $val = getenv($key);
<ide> }
<ide>
<ide><path>src/Database/Schema/TableSchema.php
<ide> public function constraints(): array
<ide> */
<ide> public function getConstraint(string $name): ?array
<ide> {
<del> if (!isset($this->_constraints[$name])) {
<del> return null;
<del> }
<del>
<del> return $this->_constraints[$name];
<add> return $this->_constraints[$name] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/Database/Statement/StatementDecorator.php
<ide> public function bind(array $params, array $types): void
<ide> $anonymousParams = is_int(key($params)) ? true : false;
<ide> $offset = 1;
<ide> foreach ($params as $index => $value) {
<del> $type = null;
<del> if (isset($types[$index])) {
<del> $type = $types[$index];
<del> }
<add> $type = $types[$index] ?? null;
<ide> if ($anonymousParams) {
<ide> /** @psalm-suppress InvalidOperand */
<ide> $index += $offset;
<ide><path>src/Database/TypeMap.php
<ide> public function getTypes(): array
<ide> */
<ide> public function type($column): ?string
<ide> {
<del> if (isset($this->_types[$column])) {
<del> return $this->_types[$column];
<del> }
<del> if (isset($this->_defaults[$column])) {
<del> return $this->_defaults[$column];
<del> }
<del>
<del> return null;
<add> return $this->_types[$column] ?? $this->_defaults[$column] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/Datasource/ConnectionManager.php
<ide> public static function get(string $name, bool $useAliases = true)
<ide> if (empty(static::$_registry)) {
<ide> static::$_registry = new ConnectionRegistry();
<ide> }
<del> if (isset(static::$_registry->{$name})) {
<del> return static::$_registry->{$name};
<del> }
<ide>
<del> return static::$_registry->load($name, static::$_config[$name]);
<add> return static::$_registry->{$name}
<add> ?? static::$_registry->load($name, static::$_config[$name]);
<ide> }
<ide> }
<ide><path>src/Datasource/RuleInvoker.php
<ide> public function __invoke(EntityInterface $entity, array $scope): bool
<ide> return $pass === true;
<ide> }
<ide>
<del> $message = 'invalid';
<del> if (isset($this->options['message'])) {
<del> $message = $this->options['message'];
<del> }
<add> $message = $this->options['message'] ?? 'invalid';
<ide> if (is_string($pass)) {
<ide> $message = $pass;
<ide> }
<ide><path>src/Error/BaseErrorHandler.php
<ide> abstract protected function _displayException(Throwable $exception): void;
<ide> */
<ide> public function register(): void
<ide> {
<del> $level = -1;
<del> if (isset($this->_config['errorLevel'])) {
<del> $level = $this->_config['errorLevel'];
<del> }
<add> $level = $this->_config['errorLevel'] ?? -1;
<ide> error_reporting($level);
<ide> set_error_handler([$this, 'handleError'], $level);
<ide> set_exception_handler([$this, 'handleException']);
<ide><path>src/Filesystem/File.php
<ide> public function info(): array
<ide> if (!$this->info) {
<ide> $this->info = pathinfo($this->path);
<ide> }
<del> if (!isset($this->info['filename'])) {
<del> $this->info['filename'] = $this->name();
<del> }
<del> if (!isset($this->info['filesize'])) {
<del> $this->info['filesize'] = $this->size();
<del> }
<del> if (!isset($this->info['mime'])) {
<del> $this->info['mime'] = $this->mime();
<del> }
<add>
<add> $this->info['filename'] = $this->info['filename'] ?? $this->name();
<add> $this->info['filesize'] = $this->info['filesize'] ?? $this->size();
<add> $this->info['mime'] = $this->info['mime'] ?? $this->mime();
<ide>
<ide> return $this->info;
<ide> }
<ide> public function ext()
<ide> if (!$this->info) {
<ide> $this->info();
<ide> }
<del> if (isset($this->info['extension'])) {
<del> return $this->info['extension'];
<del> }
<ide>
<del> return false;
<add> return $this->info['extension'] ?? false;
<ide> }
<ide>
<ide> /**
<ide><path>src/Form/Schema.php
<ide> public function fields(): array
<ide> */
<ide> public function field(string $name): ?array
<ide> {
<del> if (!isset($this->_fields[$name])) {
<del> return null;
<del> }
<del>
<del> return $this->_fields[$name];
<add> return $this->_fields[$name] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/Http/FlashMessage.php
<ide> public function set($message, array $options = []): void
<ide> */
<ide> public function setExceptionMessage(Throwable $exception, array $options = []): void
<ide> {
<del> if (!isset($options['element'])) {
<del> $options['element'] = 'error';
<del> }
<del> if (!isset($options['params']['code'])) {
<del> $options['params']['code'] = $exception->getCode();
<del> }
<add> $options['element'] = $options['element'] ?? 'error';
<add> $options['params']['code'] = $options['params']['code'] ?? $exception->getCode();
<ide>
<ide> $message = $exception->getMessage();
<ide> $this->set($message, $options);
<ide><path>src/Http/Response.php
<ide> class Response implements ResponseInterface
<ide> */
<ide> public function __construct(array $options = [])
<ide> {
<del> if (isset($options['streamTarget'])) {
<del> $this->_streamTarget = $options['streamTarget'];
<del> }
<del> if (isset($options['streamMode'])) {
<del> $this->_streamMode = $options['streamMode'];
<del> }
<add> $this->_streamTarget = $options['streamTarget'] ?? $this->_streamTarget;
<add> $this->_streamMode = $options['streamMode'] ?? $this->_streamMode;
<ide> if (isset($options['stream'])) {
<ide> if (!$options['stream'] instanceof StreamInterface) {
<ide> throw new InvalidArgumentException('Stream option must be an object that implements StreamInterface');
<ide> protected function resolveType(string $contentType): string
<ide> */
<ide> public function getMimeType(string $alias)
<ide> {
<del> if (isset($this->_mimeTypes[$alias])) {
<del> return $this->_mimeTypes[$alias];
<del> }
<del>
<del> return false;
<add> return $this->_mimeTypes[$alias] ?? false;
<ide> }
<ide>
<ide> /**
<ide><path>src/Http/ServerRequest.php
<ide> public function is($type, ...$args): bool
<ide> if ($args) {
<ide> return $this->_is($type, $args);
<ide> }
<del> if (!isset($this->_detectorCache[$type])) {
<del> $this->_detectorCache[$type] = $this->_is($type, $args);
<del> }
<ide>
<del> return $this->_detectorCache[$type];
<add> return $this->_detectorCache[$type] = $this->_detectorCache[$type] ?? $this->_is($type, $args);
<ide> }
<ide>
<ide> /**
<ide><path>src/I18n/Package.php
<ide> public function getMessages(): array
<ide> */
<ide> public function getMessage(string $key)
<ide> {
<del> if (isset($this->messages[$key])) {
<del> return $this->messages[$key];
<del> }
<del>
<del> return false;
<add> return $this->messages[$key] ?? false;
<ide> }
<ide>
<ide> /**
<ide><path>src/ORM/Association/BelongsToMany.php
<ide> public function attachTo(Query $query, array $options = []): void
<ide> $cond = $belongsTo->_joinCondition(['foreignKey' => $belongsTo->getForeignKey()]);
<ide> $cond += $this->junctionConditions();
<ide>
<del> $includeFields = null;
<del> if (isset($options['includeFields'])) {
<del> $includeFields = $options['includeFields'];
<del> }
<add> $includeFields = $options['includeFields'] ?? null;
<ide>
<ide> // Attach the junction table as well we need it to populate _joinData.
<ide> $assoc = $this->_targetTable->getAssociation($junction->getAlias());
<ide> protected function _appendNotMatching(Query $query, array $options): void
<ide> if (empty($options['negateMatch'])) {
<ide> return;
<ide> }
<del> if (!isset($options['conditions'])) {
<del> $options['conditions'] = [];
<del> }
<add> $options['conditions'] = $options['conditions'] ?? [];
<ide> $junction = $this->junction();
<ide> $belongsTo = $junction->getAssociation($this->getSource()->getAlias());
<ide> $conds = $belongsTo->_joinCondition(['foreignKey' => $belongsTo->getForeignKey()]);
<ide><path>src/ORM/Association/Loader/SelectLoader.php
<ide> protected function _buildQuery(array $options): Query
<ide> $filter = $options['keys'];
<ide> $useSubquery = $options['strategy'] === Association::STRATEGY_SUBQUERY;
<ide> $finder = $this->finder;
<del>
<del> if (!isset($options['fields'])) {
<del> $options['fields'] = [];
<del> }
<add> $options['fields'] = $options['fields'] ?? [];
<ide>
<ide> /** @var \Cake\ORM\Query $query */
<ide> $query = $finder();
<ide><path>src/ORM/AssociationCollection.php
<ide> public function load(string $className, string $associated, array $options = [])
<ide> */
<ide> public function get(string $alias): ?Association
<ide> {
<del> if (isset($this->_items[$alias])) {
<del> return $this->_items[$alias];
<del> }
<del>
<del> return null;
<add> return $this->_items[$alias] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/ORM/Behavior/CounterCacheBehavior.php
<ide> protected function _getCount(array $config, array $conditions): int
<ide> unset($config['finder']);
<ide> }
<ide>
<del> if (!isset($config['conditions'])) {
<del> $config['conditions'] = [];
<del> }
<del> $config['conditions'] = array_merge($conditions, $config['conditions']);
<add> $config['conditions'] = array_merge($conditions, $config['conditions'] ?? []);
<ide> $query = $this->_table->find($finder, $config);
<ide>
<ide> return $query->count();
<ide><path>src/ORM/Marshaller.php
<ide> protected function _buildPropertyMap(array $data, array $options): array
<ide> }
<ide>
<ide> // Map associations
<del> if (!isset($options['associated'])) {
<del> $options['associated'] = [];
<del> }
<add> $options['associated'] = $options['associated'] ?? [];
<ide> $include = $this->_normalizeAssociations($options['associated']);
<ide> foreach ($include as $key => $nested) {
<ide> if (is_int($key) && is_scalar($nested)) {
<ide><path>src/ORM/ResultSet.php
<ide> protected function _groupResult(array $row)
<ide> // If the default table is not in the results, set
<ide> // it to an empty array so that any contained
<ide> // associations hydrate correctly.
<del> if (!isset($results[$defaultAlias])) {
<del> $results[$defaultAlias] = [];
<del> }
<add> $results[$defaultAlias] = $results[$defaultAlias] ?? [];
<ide>
<ide> unset($presentAliases[$defaultAlias]);
<ide>
<ide><path>src/ORM/Table.php
<ide> public function newEmptyEntity(): EntityInterface
<ide> */
<ide> public function newEntity(array $data, array $options = []): EntityInterface
<ide> {
<del> if (!isset($options['associated'])) {
<del> $options['associated'] = $this->_associations->keys();
<del> }
<add> $options['associated'] = $options['associated'] ?? $this->_associations->keys();
<ide> $marshaller = $this->marshaller();
<ide>
<ide> return $marshaller->one($data, $options);
<ide> public function newEntity(array $data, array $options = []): EntityInterface
<ide> */
<ide> public function newEntities(array $data, array $options = []): array
<ide> {
<del> if (!isset($options['associated'])) {
<del> $options['associated'] = $this->_associations->keys();
<del> }
<add> $options['associated'] = $options['associated'] ?? $this->_associations->keys();
<ide> $marshaller = $this->marshaller();
<ide>
<ide> return $marshaller->many($data, $options);
<ide> public function newEntities(array $data, array $options = []): array
<ide> */
<ide> public function patchEntity(EntityInterface $entity, array $data, array $options = []): EntityInterface
<ide> {
<del> if (!isset($options['associated'])) {
<del> $options['associated'] = $this->_associations->keys();
<del> }
<add> $options['associated'] = $options['associated'] ?? $this->_associations->keys();
<ide> $marshaller = $this->marshaller();
<ide>
<ide> return $marshaller->merge($entity, $data, $options);
<ide> public function patchEntity(EntityInterface $entity, array $data, array $options
<ide> */
<ide> public function patchEntities(iterable $entities, array $data, array $options = []): array
<ide> {
<del> if (!isset($options['associated'])) {
<del> $options['associated'] = $this->_associations->keys();
<del> }
<add> $options['associated'] = $options['associated'] ?? $this->_associations->keys();
<ide> $marshaller = $this->marshaller();
<ide>
<ide> return $marshaller->mergeMany($entities, $data, $options);
<ide><path>src/Routing/Route/Route.php
<ide> public function match(array $url, array $context = []): ?string
<ide> if (!isset($hostOptions['_host']) && strpos($this->options['_host'], '*') === false) {
<ide> $hostOptions['_host'] = $this->options['_host'];
<ide> }
<del> if (!isset($hostOptions['_host'])) {
<del> $hostOptions['_host'] = $context['_host'];
<del> }
<add> $hostOptions['_host'] = $hostOptions['_host'] ?? $context['_host'];
<ide>
<ide> // The host did not match the route preferences
<ide> if (!$this->hostMatches((string)$hostOptions['_host'])) {
<ide><path>src/Routing/RouteBuilder.php
<ide> public function resources(string $name, $options = [], $callback = null)
<ide> continue;
<ide> }
<ide>
<del> $action = $params['action'];
<del> if (isset($options['actions'][$method])) {
<del> $action = $options['actions'][$method];
<del> }
<add> $action = $options['actions'][$method] ?? $params['action'];
<ide>
<ide> $url = '/' . implode('/', array_filter([$options['path'], $params['path']]));
<ide> $params = [
<ide> protected function _makeRoute($route, $defaults, $options): Route
<ide> */
<ide> public function redirect(string $route, $url, array $options = []): Route
<ide> {
<del> if (!isset($options['routeClass'])) {
<del> $options['routeClass'] = RedirectRoute::class;
<del> }
<add> $options['routeClass'] = $options['routeClass'] ?? RedirectRoute::class;
<ide> if (is_string($url)) {
<ide> $url = ['redirect' => $url];
<ide> }
<ide><path>src/Routing/RouteCollection.php
<ide> public function add(Route $route, array $options = []): void
<ide>
<ide> // Generated names.
<ide> $name = $route->getName();
<del> if (!isset($this->_routeTable[$name])) {
<del> $this->_routeTable[$name] = [];
<del> }
<add> $this->_routeTable[$name] = $this->_routeTable[$name] ?? [];
<ide> $this->_routeTable[$name][] = $route;
<ide>
<ide> // Index path prefixes (for parsing)
<ide><path>src/Routing/Router.php
<ide> public static function url($url = null, bool $full = false): string
<ide> $context = static::$_requestContext;
<ide> $request = static::getRequest();
<ide>
<del> if (!isset($context['_base'])) {
<del> $context['_base'] = Configure::read('App.base') ?: '';
<del> }
<add> $context['_base'] = $context['_base'] ?? Configure::read('App.base') ?: '';
<ide>
<ide> if (empty($url)) {
<ide> $here = $request ? $request->getRequestTarget() : '/';
<ide><path>src/Shell/Task/CommandTask.php
<ide> protected function _findShells(array $shellList, string $path, string $key, arra
<ide> */
<ide> protected function _appendShells(string $type, array $shells, array $shellList, array $skip): array
<ide> {
<del> if (!isset($shellList[$type])) {
<del> $shellList[$type] = [];
<del> }
<add> $shellList[$type] = $shellList[$type] ?? [];
<ide>
<ide> foreach ($shells as $shell) {
<ide> $name = Inflector::underscore(preg_replace('/(Shell|Command)$/', '', $shell));
<ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function load(TestCase $test): void
<ide> /** @var \Cake\Datasource\FixtureInterface[] $fixtures */
<ide> $tables = $db->getSchemaCollection()->listTables();
<ide> $configName = $db->configName();
<del> if (!isset($this->_insertionMap[$configName])) {
<del> $this->_insertionMap[$configName] = [];
<del> }
<add> $this->_insertionMap[$configName] = $this->_insertionMap[$configName] ?? [];
<ide>
<ide> foreach ($fixtures as $fixture) {
<ide> if (!$fixture instanceof ConstraintsInterface) {
<ide><path>src/TestSuite/Fixture/TestFixture.php
<ide> protected function _tableFromClass(): string
<ide> {
<ide> [, $class] = namespaceSplit(static::class);
<ide> preg_match('/^(.*)Fixture$/', $class, $matches);
<del> $table = $class;
<del>
<del> if (isset($matches[1])) {
<del> $table = $matches[1];
<del> }
<add> $table = $matches[1] ?? $class;
<ide>
<ide> return Inflector::tableize($table);
<ide> }
<ide><path>src/TestSuite/IntegrationTestTrait.php
<ide> public function cookie(string $name, $value): void
<ide> */
<ide> protected function _getCookieEncryptionKey(): string
<ide> {
<del> if (isset($this->_cookieEncryptionKey)) {
<del> return $this->_cookieEncryptionKey;
<del> }
<del>
<del> return Security::getSalt();
<add> return $this->_cookieEncryptionKey ?? Security::getSalt();
<ide> }
<ide>
<ide> /**
<ide><path>src/Utility/Hash.php
<ide> protected static function _matches($data, string $selector): bool
<ide> return false;
<ide> }
<ide>
<del> $prop = '';
<del> if (isset($data[$attr])) {
<del> $prop = $data[$attr];
<del> }
<add> $prop = $data[$attr] ?? '';
<ide> $isBool = is_bool($prop);
<ide> if ($isBool && is_numeric($val)) {
<ide> $prop = $prop ? '1' : '0';
<ide> protected static function _simpleOp(string $op, array $data, array $path, $value
<ide>
<ide> return $data;
<ide> }
<del> if (!isset($_list[$key])) {
<del> $_list[$key] = [];
<del> }
<add> $_list[$key] = $_list[$key] ?? [];
<ide> $_list = &$_list[$key];
<ide> if (!is_array($_list)) {
<ide> $_list = [];
<ide> public static function combine(array $data, $keyPath, $valuePath = null, ?string
<ide> $c = is_array($keys) ? count($keys) : count($vals);
<ide> $out = [];
<ide> for ($i = 0; $i < $c; $i++) {
<del> if (!isset($group[$i])) {
<del> $group[$i] = 0;
<del> }
<del> if (!isset($out[$group[$i]])) {
<del> $out[$group[$i]] = [];
<del> }
<add> $group[$i] = $group[$i] ?? 0;
<add> $out[$group[$i]] = $out[$group[$i]] ?? [];
<ide> if ($keys === null) {
<ide> $out[$group[$i]][] = $vals[$i];
<ide> } else {
<ide><path>src/Validation/ValidationRule.php
<ide> protected function _addValidatorProps(array $validator = []): void
<ide> public function get(string $property)
<ide> {
<ide> $property = '_' . $property;
<del> if (isset($this->{$property})) {
<del> return $this->{$property};
<del> }
<add>
<add> return $this->{$property} ?? null;
<ide> }
<ide> }
<ide><path>src/Validation/Validator.php
<ide> public function getProvider(string $name)
<ide> */
<ide> public static function getDefaultProvider(string $name)
<ide> {
<del> if (!isset(self::$_defaultProviders[$name])) {
<del> return null;
<del> }
<del>
<del> return self::$_defaultProviders[$name];
<add> return self::$_defaultProviders[$name] ?? null;
<ide> }
<ide>
<ide> /**
<ide><path>src/View/Helper/FormHelper.php
<ide> public function controls(array $fields, array $options = []): string
<ide> */
<ide> public function fieldset(string $fields = '', array $options = []): string
<ide> {
<del> $fieldset = $legend = true;
<add> $legend = $options['legend'] ?? true;
<add> $fieldset = $options['fieldset'] ?? true;
<ide> $context = $this->_getContext();
<ide> $out = $fields;
<ide>
<del> if (isset($options['legend'])) {
<del> $legend = $options['legend'];
<del> }
<del> if (isset($options['fieldset'])) {
<del> $fieldset = $options['fieldset'];
<del> }
<del>
<ide> if ($legend === true) {
<ide> $isCreate = $context->isCreate();
<ide> $modelName = Inflector::humanize(
<ide> protected function _getLabel(string $fieldName, array $options)
<ide> return false;
<ide> }
<ide>
<del> $label = null;
<del> if (isset($options['label'])) {
<del> $label = $options['label'];
<del> }
<add> $label = $options['label'] ?? null;
<ide>
<ide> if ($label === false && $options['type'] === 'checkbox') {
<ide> return $options['input'];
<ide> public function radio(string $fieldName, iterable $options = [], array $attribut
<ide> */
<ide> public function __call(string $method, array $params)
<ide> {
<del> $options = [];
<ide> if (empty($params)) {
<ide> throw new CakeException(sprintf('Missing field name for FormHelper::%s', $method));
<ide> }
<del> if (isset($params[1])) {
<del> $options = $params[1];
<del> }
<del> if (!isset($options['type'])) {
<del> $options['type'] = $method;
<del> }
<add> $options = $params[1] ?? [];
<add> $options['type'] = $options['type'] ?? $method;
<ide> $options = $this->_initInputField($params[0], $options);
<ide>
<ide> return $this->widget($options['type'], $options);
<ide><path>src/View/Helper/PaginatorHelper.php
<ide> public function params(?string $model = null): array
<ide> public function param(string $key, ?string $model = null)
<ide> {
<ide> $params = $this->params($model);
<del> if (!isset($params[$key])) {
<del> return null;
<del> }
<ide>
<del> return $params[$key];
<add> return $params[$key] ?? null;
<ide> }
<ide>
<ide> /**
<ide> public function current(?string $model = null): int
<ide> {
<ide> $params = $this->params($model);
<ide>
<del> if (isset($params['page'])) {
<del> return $params['page'];
<del> }
<del>
<del> return 1;
<add> return $params['page'] ?? 1;
<ide> }
<ide>
<ide> /**
<ide> public function total(?string $model = null): int
<ide> {
<ide> $params = $this->params($model);
<ide>
<del> if (isset($params['pageCount'])) {
<del> return $params['pageCount'];
<del> }
<del>
<del> return 0;
<add> return $params['pageCount'] ?? 0;
<ide> }
<ide>
<ide> /**
<ide> public function generateUrlParams(array $options = [], ?string $model = null, ar
<ide> $url = Hash::merge($url, Hash::get($this->_config, $key, []));
<ide> }
<ide>
<del> if (!isset($url['?'])) {
<del> $url['?'] = [];
<del> }
<add> $url['?'] = $url['?'] ?? [];
<ide>
<ide> if (!empty($this->_config['options']['routePlaceholders'])) {
<ide> $placeholders = array_flip($this->_config['options']['routePlaceholders']);
<ide><path>src/View/View.php
<ide> public function getVars(): array
<ide> */
<ide> public function get(string $var, $default = null)
<ide> {
<del> if (!isset($this->viewVars[$var])) {
<del> return $default;
<del> }
<del>
<del> return $this->viewVars[$var];
<add> return $this->viewVars[$var] ?? $default;
<ide> }
<ide>
<ide> /**
<ide><path>src/View/ViewBlock.php
<ide> public function set(string $name, $value): void
<ide> */
<ide> public function get(string $name, string $default = ''): string
<ide> {
<del> if (!isset($this->_blocks[$name])) {
<del> return $default;
<del> }
<del>
<del> return $this->_blocks[$name];
<add> return $this->_blocks[$name] ?? $default;
<ide> }
<ide>
<ide> /**
<ide><path>src/View/Widget/RadioWidget.php
<ide> protected function _renderInput($val, $text, $data, $context): string
<ide> }
<ide> $radio['name'] = $data['name'];
<ide>
<del> if (!isset($radio['templateVars'])) {
<del> $radio['templateVars'] = [];
<del> }
<add> $radio['templateVars'] = $radio['templateVars'] ?? [];
<ide> if (!empty($data['templateVars'])) {
<ide> $radio['templateVars'] = array_merge($data['templateVars'], $radio['templateVars']);
<ide> }
<ide><path>src/View/Widget/SelectBoxWidget.php
<ide> protected function _renderOptions(iterable $options, ?array $disabled, $selected
<ide> $optAttrs = $val;
<ide> $key = $optAttrs['value'];
<ide> }
<del> if (!isset($optAttrs['templateVars'])) {
<del> $optAttrs['templateVars'] = [];
<del> }
<add> $optAttrs['templateVars'] = $optAttrs['templateVars'] ?? [];
<ide> if ($this->_isSelected((string)$key, $selected)) {
<ide> $optAttrs['selected'] = true;
<ide> } | 46 |
Text | Text | add v3.14.0-beta.4 to changelog | 72553a0a51b24b392d5619d445cc3f1c3bab1448 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v3.14.0-beta.4 (October 7, 2019)
<add>
<add>- [#18462](https://github.com/emberjs/ember.js/pull/18462) [BUGFIX] Prevents observer re-entry
<add>
<ide> ### v3.14.0-beta.3 (October 1, 2019)
<ide>
<ide> - [#18429](https://github.com/emberjs/ember.js/pull/18429) [BUGFIX] Fix incorrect error message for octane features. | 1 |
Ruby | Ruby | remove unnecessary mocking in actioncable tests | 78288f75e127182751938353ef3005a29d9c3bc1 | <ide><path>actioncable/test/channel/stream_test.rb
<ide> class StreamTest < ActionCable::TestCase
<ide> test "streaming start and stop" do
<ide> run_in_eventmachine do
<ide> connection = TestConnection.new
<del> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("test_room_1", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) }
<add> connection.pubsub.expects(:subscribe).with("test_room_1", kind_of(Proc), kind_of(Proc))
<ide> channel = ChatChannel.new connection, "{id: 1}", id: 1
<ide> channel.subscribe_to_channel
<ide>
<ide> wait_for_async
<ide>
<del> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) }
<add> connection.pubsub.expects(:unsubscribe)
<ide> channel.unsubscribe_from_channel
<ide> end
<ide> end
<ide>
<ide> test "stream from non-string channel" do
<ide> run_in_eventmachine do
<ide> connection = TestConnection.new
<del> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("channel", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) }
<add> connection.pubsub.expects(:subscribe).with("channel", kind_of(Proc), kind_of(Proc))
<add>
<ide> channel = SymbolChannel.new connection, ""
<ide> channel.subscribe_to_channel
<ide>
<ide> wait_for_async
<ide>
<del> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:unsubscribe) }
<add> connection.pubsub.expects(:unsubscribe)
<ide> channel.unsubscribe_from_channel
<ide> end
<ide> end
<ide>
<ide> test "stream_for" do
<ide> run_in_eventmachine do
<ide> connection = TestConnection.new
<del> connection.expects(:pubsub).returns mock().tap { |m| m.expects(:subscribe).with("action_cable:stream_tests:chat:Room#1-Campfire", kind_of(Proc), kind_of(Proc)).returns stub_everything(:pubsub) }
<add> connection.pubsub.expects(:subscribe).with("action_cable:stream_tests:chat:Room#1-Campfire", kind_of(Proc), kind_of(Proc))
<ide>
<ide> channel = ChatChannel.new connection, ""
<ide> channel.subscribe_to_channel
<ide><path>actioncable/test/connection/base_test.rb
<ide> def send_async(method, *args)
<ide> connection.process
<ide>
<ide> # Setup the connection
<del> connection.server.stubs(:timer).returns(true)
<ide> connection.send :handle_open
<ide> assert connection.connected
<ide>
<ide><path>actioncable/test/connection/identifier_test.rb
<ide> def connect
<ide>
<ide> test "connection identifier" do
<ide> run_in_eventmachine do
<del> open_connection_with_stubbed_pubsub
<add> open_connection
<ide> assert_equal "User#lifo", @connection.connection_identifier
<ide> end
<ide> end
<ide>
<ide> test "should subscribe to internal channel on open and unsubscribe on close" do
<ide> run_in_eventmachine do
<del> pubsub = mock("pubsub_adapter")
<del> pubsub.expects(:subscribe).with("action_cable/User#lifo", kind_of(Proc))
<del> pubsub.expects(:unsubscribe).with("action_cable/User#lifo", kind_of(Proc))
<del>
<ide> server = TestServer.new
<del> server.stubs(:pubsub).returns(pubsub)
<ide>
<del> open_connection server: server
<add> server.pubsub.expects(:subscribe)
<add> .with("action_cable/User#lifo", kind_of(Proc))
<add> server.pubsub.expects(:unsubscribe)
<add> .with("action_cable/User#lifo", kind_of(Proc))
<add>
<add> open_connection(server)
<ide> close_connection
<ide> end
<ide> end
<ide>
<ide> test "processing disconnect message" do
<ide> run_in_eventmachine do
<del> open_connection_with_stubbed_pubsub
<add> open_connection
<ide>
<ide> assert_called(@connection.websocket, :close) do
<ide> @connection.process_internal_message "type" => "disconnect"
<ide> def connect
<ide>
<ide> test "processing invalid message" do
<ide> run_in_eventmachine do
<del> open_connection_with_stubbed_pubsub
<add> open_connection
<ide>
<ide> assert_not_called(@connection.websocket, :close) do
<ide> @connection.process_internal_message "type" => "unknown"
<ide> def connect
<ide> end
<ide>
<ide> private
<del> def open_connection_with_stubbed_pubsub
<del> server = TestServer.new
<del> server.stubs(:adapter).returns(stub_everything("adapter"))
<del>
<del> open_connection server: server
<del> end
<add> def open_connection(server = nil)
<add> server ||= TestServer.new
<ide>
<del> def open_connection(server:)
<ide> env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket"
<ide> @connection = Connection.new(server, env)
<ide>
<ide><path>actioncable/test/connection/multiple_identifiers_test.rb
<ide> def connect
<ide>
<ide> test "multiple connection identifiers" do
<ide> run_in_eventmachine do
<del> open_connection_with_stubbed_pubsub
<add> open_connection
<add>
<ide> assert_equal "Room#my-room:User#lifo", @connection.connection_identifier
<ide> end
<ide> end
<ide>
<ide> private
<del> def open_connection_with_stubbed_pubsub
<add> def open_connection
<ide> server = TestServer.new
<del> server.stubs(:pubsub).returns(stub_everything("pubsub"))
<del>
<del> open_connection server: server
<del> end
<del>
<del> def open_connection(server:)
<ide> env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket"
<ide> @connection = Connection.new(server, env)
<ide>
<ide><path>actioncable/test/connection/string_identifier_test.rb
<ide> def send_async(method, *args)
<ide>
<ide> test "connection identifier" do
<ide> run_in_eventmachine do
<del> open_connection_with_stubbed_pubsub
<add> open_connection
<add>
<ide> assert_equal "random-string", @connection.connection_identifier
<ide> end
<ide> end
<ide>
<ide> private
<del> def open_connection_with_stubbed_pubsub
<del> @server = TestServer.new
<del> @server.stubs(:pubsub).returns(stub_everything("pubsub"))
<del>
<del> open_connection
<del> end
<del>
<ide> def open_connection
<add> server = TestServer.new
<ide> env = Rack::MockRequest.env_for "/test", "HTTP_HOST" => "localhost", "HTTP_CONNECTION" => "upgrade", "HTTP_UPGRADE" => "websocket"
<del> @connection = Connection.new(@server, env)
<add> @connection = Connection.new(server, env)
<ide>
<ide> @connection.process
<ide> @connection.send :on_open | 5 |
Mixed | Ruby | reduce memory usage when loading types in pg | 445c12f7dfa345b86e05dc610d665f9afde14c26 | <ide><path>activerecord/CHANGELOG.md
<add>* Reduce memory usage from loading types on pg.
<add>
<add> Fixes #19578.
<add>
<add> *Sean Griffin*
<add>
<ide> * Add `config.active_record.warn_on_records_fetched_greater_than` option
<ide>
<ide> When set to an integer, a warning will be logged whenever a result set
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/oid/type_map_initializer.rb
<ide> def initialize(store)
<ide> def run(records)
<ide> nodes = records.reject { |row| @store.key? row['oid'].to_i }
<ide> mapped, nodes = nodes.partition { |row| @store.key? row['typname'] }
<del> ranges, nodes = nodes.partition { |row| row['typtype'] == 'r' }
<del> enums, nodes = nodes.partition { |row| row['typtype'] == 'e' }
<del> domains, nodes = nodes.partition { |row| row['typtype'] == 'd' }
<del> arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in' }
<add> ranges, nodes = nodes.partition { |row| row['typtype'] == 'r'.freeze }
<add> enums, nodes = nodes.partition { |row| row['typtype'] == 'e'.freeze }
<add> domains, nodes = nodes.partition { |row| row['typtype'] == 'd'.freeze }
<add> arrays, nodes = nodes.partition { |row| row['typinput'] == 'array_in'.freeze }
<ide> composites, nodes = nodes.partition { |row| row['typelem'].to_i != 0 }
<ide>
<ide> mapped.each { |row| register_mapped_type(row) }
<ide> def run(records)
<ide> composites.each { |row| register_composite_type(row) }
<ide> end
<ide>
<add> def query_conditions_for_initial_load(type_map)
<add> known_type_names = type_map.keys.map { |n| "'#{n}'" }
<add> known_type_types = %w('r' 'e' 'd')
<add> <<-SQL % [known_type_names.join(", "), known_type_types.join(", ")]
<add> WHERE
<add> t.typname IN (%s)
<add> OR t.typtype IN (%s)
<add> OR t.typinput::varchar = 'array_in'
<add> OR t.typelem != 0
<add> SQL
<add> end
<add>
<ide> private
<ide> def register_mapped_type(row)
<ide> alias_type row['oid'], row['typname']
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb
<ide> def has_default_function?(default_value, default) # :nodoc:
<ide> end
<ide>
<ide> def load_additional_types(type_map, oids = nil) # :nodoc:
<add> initializer = OID::TypeMapInitializer.new(type_map)
<add>
<ide> if supports_ranges?
<ide> query = <<-SQL
<ide> SELECT t.oid, t.typname, t.typelem, t.typdelim, t.typinput, r.rngsubtype, t.typtype, t.typbasetype
<ide> def load_additional_types(type_map, oids = nil) # :nodoc:
<ide>
<ide> if oids
<ide> query += "WHERE t.oid::integer IN (%s)" % oids.join(", ")
<add> else
<add> query += initializer.query_conditions_for_initial_load(type_map)
<ide> end
<ide>
<del> initializer = OID::TypeMapInitializer.new(type_map)
<del> records = execute(query, 'SCHEMA')
<del> initializer.run(records)
<add> execute_and_clear(query, 'SCHEMA', []) do |records|
<add> initializer.run(records)
<add> end
<ide> end
<ide>
<ide> FEATURE_NOT_SUPPORTED = "0A000" #:nodoc:
<ide> def add_pg_decoders
<ide> 'float8' => PG::TextDecoder::Float,
<ide> 'bool' => PG::TextDecoder::Boolean,
<ide> }
<del> query = <<-SQL
<add> known_coder_types = coders_by_name.keys.map { |n| quote(n) }
<add> query = <<-SQL % known_coder_types.join(", ")
<ide> SELECT t.oid, t.typname
<ide> FROM pg_type as t
<add> WHERE t.typname IN (%s)
<ide> SQL
<ide> coders = execute_and_clear(query, "SCHEMA", []) do |result|
<ide> result
<ide><path>activerecord/lib/active_record/type/hash_lookup_type_map.rb
<ide> module ActiveRecord
<ide> module Type
<ide> class HashLookupTypeMap < TypeMap # :nodoc:
<del> delegate :key?, to: :@mapping
<del>
<ide> def alias_type(type, alias_type)
<ide> register_type(type) { |_, *args| lookup(alias_type, *args) }
<ide> end
<ide>
<add> def key?(key)
<add> @mapping.key?(key)
<add> end
<add>
<add> def keys
<add> @mapping.keys
<add> end
<add>
<ide> private
<ide>
<ide> def perform_fetch(type, *args, &block) | 4 |
Java | Java | fix checkstyle violation | 2899652d8ea1b68b92f94ba1f13e028f76c251cb | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultWebClient.java
<ide> private static class DefaultResponseSpec implements ResponseSpec {
<ide> this.statusHandlers.add(DEFAULT_STATUS_HANDLER);
<ide> }
<ide>
<del>
<add>
<ide> @Override
<ide> public ResponseSpec onStatus(Predicate<HttpStatus> statusPredicate,
<ide> Function<ClientResponse, Mono<? extends Throwable>> exceptionFunction) { | 1 |
Python | Python | fix trainer and args to mention adamw, not adam. | 538245b0c2199a7546bb92eed566965609acb5bb | <ide><path>src/transformers/training_args.py
<ide> class TrainingArguments:
<ide> left unset, the whole predictions are accumulated on GPU/TPU before being moved to the CPU (faster but
<ide> requires more memory).
<ide> learning_rate (:obj:`float`, `optional`, defaults to 5e-5):
<del> The initial learning rate for Adam.
<add> The initial learning rate for :class:`~transformers.AdamW` optimizer.
<ide> weight_decay (:obj:`float`, `optional`, defaults to 0):
<del> The weight decay to apply (if not zero).
<add> The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in
<add> :class:`~transformers.AdamW` optimizer.
<ide> adam_beta1 (:obj:`float`, `optional`, defaults to 0.9):
<del> The beta1 hyperparameter for the Adam optimizer.
<add> The beta1 hyperparameter for the :class:`~transformers.AdamW` optimizer.
<ide> adam_beta2 (:obj:`float`, `optional`, defaults to 0.999):
<del> The beta2 hyperparameter for the Adam optimizer.
<add> The beta2 hyperparameter for the :class:`~transformers.AdamW` optimizer.
<ide> adam_epsilon (:obj:`float`, `optional`, defaults to 1e-8):
<del> The epsilon hyperparameter for the Adam optimizer.
<add> The epsilon hyperparameter for the :class:`~transformers.AdamW` optimizer.
<ide> max_grad_norm (:obj:`float`, `optional`, defaults to 1.0):
<ide> Maximum gradient norm (for gradient clipping).
<ide> num_train_epochs(:obj:`float`, `optional`, defaults to 3.0):
<ide> class TrainingArguments:
<ide> metadata={"help": "Number of predictions steps to accumulate before moving the tensors to the CPU."},
<ide> )
<ide>
<del> learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for Adam."})
<del> weight_decay: float = field(default=0.0, metadata={"help": "Weight decay if we apply some."})
<del> adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for Adam optimizer"})
<del> adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for Adam optimizer"})
<del> adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for Adam optimizer."})
<add> learning_rate: float = field(default=5e-5, metadata={"help": "The initial learning rate for AdamW."})
<add> weight_decay: float = field(default=0.0, metadata={"help": "Weight decay for AdamW if we apply some."})
<add> adam_beta1: float = field(default=0.9, metadata={"help": "Beta1 for AdamW optimizer"})
<add> adam_beta2: float = field(default=0.999, metadata={"help": "Beta2 for AdamW optimizer"})
<add> adam_epsilon: float = field(default=1e-8, metadata={"help": "Epsilon for AdamW optimizer."})
<ide> max_grad_norm: float = field(default=1.0, metadata={"help": "Max gradient norm."})
<ide>
<ide> num_train_epochs: float = field(default=3.0, metadata={"help": "Total number of training epochs to perform."})
<ide> class TrainingArguments:
<ide> label_smoothing_factor: float = field(
<ide> default=0.0, metadata={"help": "The label smoothing epsilon to apply (zero means no label smoothing)."}
<ide> )
<del> adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace Adam by Adafactor."})
<add> adafactor: bool = field(default=False, metadata={"help": "Whether or not to replace AdamW by Adafactor."})
<ide> group_by_length: bool = field(
<ide> default=False,
<ide> metadata={"help": "Whether or not to group samples of roughly the same length together when batching."}, | 1 |
PHP | PHP | add docs for return false case | f843df1831342167c371afe72e63509f0a8bf97b | <ide><path>src/ORM/Behavior/CounterCacheBehavior.php
<ide> *
<ide> * Counter cache using lambda function returning the count
<ide> * This is equivalent to example #2
<add> *
<ide> * ```
<ide> * [
<ide> * 'Users' => [
<ide> * ]
<ide> * ```
<ide> *
<add> * When using a lambda function you can return `false` to disable updating the counter value
<add> * for the current operation.
<add> *
<ide> * Ignore updating the field if it is dirty
<ide> * ```
<ide> * [ | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.