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
PHP
PHP
refactor some code
5f8062c0dab1cfcd3959c7661fd778ed85cc9b2d
<ide><path>src/Illuminate/Pagination/Paginator.php <ide> public function appends($key, $value) <ide> return $this->addQuery($key, $value); <ide> } <ide> <del> /** <del> * The pagination environment. <del> * <del> * @var \Illuminate\Pagination\Environment <del> */ <del> public function getEnvironment() <del> { <del> return $this->env; <del> } <del> <ide> /** <ide> * Add a query string value to the paginator. <ide> * <ide> public function getTotal() <ide> return $this->total; <ide> } <ide> <add> /** <add> * Get the pagination environment. <add> * <add> * @var \Illuminate\Pagination\Environment <add> */ <add> public function getEnvironment() <add> { <add> return $this->env; <add> } <add> <ide> /** <ide> * Get an iterator for the items. <ide> *
1
Javascript
Javascript
define jquery.uniquesort in selector-native too
bf591fb597a056bf2fc9bc474010374695b18d1a
<ide><path>src/selector-native.js <ide> var hasDuplicate, <ide> <ide> // Not directly comparable, sort on existence of method <ide> return a.compareDocumentPosition ? -1 : 1; <add> }, <add> uniqueSort = function( results ) { <add> var elem, <add> duplicates = [], <add> i = 0, <add> j = 0; <add> <add> hasDuplicate = false; <add> results.sort( sortOrder ); <add> <add> if ( hasDuplicate ) { <add> while ( (elem = results[i++]) ) { <add> if ( elem === results[ i ] ) { <add> j = duplicates.push( i ); <add> } <add> } <add> while ( j-- ) { <add> results.splice( duplicates[ j ], 1 ); <add> } <add> } <add> <add> return results; <ide> }; <ide> <ide> jQuery.extend({ <ide> jQuery.extend({ <ide> <ide> return results; <ide> }, <del> unique: function( results ) { <del> var elem, <del> duplicates = [], <del> i = 0, <del> j = 0; <del> <del> hasDuplicate = false; <del> results.sort( sortOrder ); <del> <del> if ( hasDuplicate ) { <del> while ( (elem = results[i++]) ) { <del> if ( elem === results[ i ] ) { <del> j = duplicates.push( i ); <del> } <del> } <del> while ( j-- ) { <del> results.splice( duplicates[ j ], 1 ); <del> } <del> } <del> <del> return results; <del> }, <add> uniqueSort: uniqueSort, <add> unique: uniqueSort, <ide> text: function( elem ) { <ide> var node, <ide> ret = "",
1
Python
Python
add reporting of stats and turn off dist_strat
1b3c9ba6a68c1e9ec2f9d570113ffbb3eae681f5
<ide><path>official/resnet/keras/keras_cifar_main.py <ide> def __init__(self, batch_size): <ide> <ide> """ <ide> self._batch_size = batch_size <add> self.last_exp_per_sec = 0 <ide> super(TimeHistory, self).__init__() <ide> <ide> def on_train_begin(self, logs=None): <ide> def on_batch_end(self, batch, logs=None): <ide> last_n_batches = time.time() - self.batch_time_start <ide> examples_per_second = (self._batch_size * n) / last_n_batches <ide> self.batch_times_secs.append(last_n_batches) <add> self.last_exp_per_sec = examples_per_second <ide> self.record_batch = True <ide> # TODO(anjalisridhar): add timestamp as well. <ide> if batch != 0: <ide> def run_cifar_with_keras(flags_obj): <ide> <ide> else: <ide> train_input_dataset = cifar_main.input_fn( <del> True, <del> flags_obj.data_dir, <del> batch_size=per_device_batch_size, <del> num_epochs=flags_obj.train_epochs, <del> parse_record_fn=parse_record_keras) <add> True, <add> flags_obj.data_dir, <add> batch_size=per_device_batch_size, <add> num_epochs=flags_obj.train_epochs, <add> parse_record_fn=parse_record_keras) <ide> <ide> eval_input_dataset = cifar_main.input_fn( <del> False, <del> flags_obj.data_dir, <del> batch_size=per_device_batch_size, <del> num_epochs=flags_obj.train_epochs, <del> parse_record_fn=parse_record_keras) <del> <add> False, <add> flags_obj.data_dir, <add> batch_size=per_device_batch_size, <add> num_epochs=flags_obj.train_epochs, <add> parse_record_fn=parse_record_keras) <ide> <ide> # Use Keras ResNet50 applications model and native keras APIs <ide> # initialize RMSprop optimizer <ide> def run_cifar_with_keras(flags_obj): <ide> <ide> # TF Optimizer: <ide> # opt = tf.train.MomentumOptimizer(learning_rate=0.1, momentum=0.9) <del> <add> <ide> strategy = distribution_utils.get_distribution_strategy( <ide> num_gpus=flags_obj.num_gpus) <ide> <ide> model = keras_resnet_model.ResNet56(input_shape=(32, 32, 3), <del> include_top=True, <del> classes=cifar_main._NUM_CLASSES, <del> weights=None) <del> <add> include_top=True, <add> classes=cifar_main._NUM_CLASSES, <add> weights=None) <ide> <ide> loss = 'categorical_crossentropy' <ide> accuracy = 'categorical_accuracy' <ide> <del> if flags_obj.num_gpus == 1: <add> if flags_obj.num_gpus == 1 and flags_obj.dist_strat_off: <add> print('Not using distribution strategies.') <ide> model.compile(loss=loss, <ide> optimizer=opt, <ide> metrics=[accuracy]) <ide> def run_cifar_with_keras(flags_obj): <ide> time_callback = TimeHistory(flags_obj.batch_size) <ide> <ide> tesorboard_callback = tf.keras.callbacks.TensorBoard( <del> log_dir=flags_obj.model_dir) <del> #update_freq="batch") # Add this if want per batch logging. <add> log_dir=flags_obj.model_dir) <add> # update_freq="batch") # Add this if want per batch logging. <ide> <ide> lr_callback = LearningRateBatchScheduler( <del> learning_rate_schedule, <del> batch_size=flags_obj.batch_size, <del> num_images=cifar_main._NUM_IMAGES['train']) <del> <add> learning_rate_schedule, <add> batch_size=flags_obj.batch_size, <add> num_images=cifar_main._NUM_IMAGES['train']) <add> <ide> num_eval_steps = (cifar_main._NUM_IMAGES['validation'] // <del> flags_obj.batch_size) <del> <del> print("Executing eagerly?:", tf.executing_eagerly()) <del> model.fit(train_input_dataset, <del> epochs=flags_obj.train_epochs, <del> steps_per_epoch=steps_per_epoch, <del> callbacks=[ <del> time_callback, <del> lr_callback, <del> tesorboard_callback <del> ], <del> verbose=1) <del> <add> flags_obj.batch_size) <add> <add> print('Executing eagerly?:', tf.executing_eagerly()) <add> history = model.fit(train_input_dataset, <add> epochs=flags_obj.train_epochs, <add> steps_per_epoch=steps_per_epoch, <add> callbacks=[ <add> time_callback, <add> lr_callback, <add> tesorboard_callback <add> ], <add> verbose=1) <add> <ide> eval_output = model.evaluate(eval_input_dataset, <ide> steps=num_eval_steps, <ide> verbose=1) <del> print('Test loss:', eval_output[0]) <ide> <del>def main(_): <add> stats = {} <add> stats['accuracy_top_1'] = eval_output[1] <add> stats['eval_loss'] = eval_output[0] <add> stats['training_loss'] = history.history['loss'][-1] <add> stats['training_accuracy_top_1'] = history.history['categorical_accuracy'][-1] <add> <add> print('top_1 accuracy:{}'.format(stats['accuracy_top_1'])) <add> print('top_1_training_accuracy:{}'.format(stats['training_accuracy_top_1'])) <add> return stats <ide> <add> <add>def define_keras_cifar_flags(): <add> flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?') <add> <add> <add>def main(_): <ide> with logger.benchmark_context(flags.FLAGS): <ide> run_cifar_with_keras(flags.FLAGS) <ide> <ide> <ide> if __name__ == '__main__': <ide> tf.logging.set_verbosity(tf.logging.DEBUG) <add> define_keras_cifar_flags() <ide> cifar_main.define_cifar_flags() <del> flags.DEFINE_boolean(name='enable_eager', default=False, help='Enable eager?') <ide> absl_app.run(main)
1
Ruby
Ruby
pull no args check into a method
7535ba3be475674748f588cf21d2feea2951dff4
<ide><path>Library/Contributions/cmd/brew-test-bot.rb <ide> def initialize argument <ide> FileUtils.mkdir_p @brewbot_root <ide> end <ide> <add> def no_args? <add> @hash == 'HEAD' <add> end <add> <ide> def git arguments <ide> Dir.chdir HOMEBREW_REPOSITORY do <ide> `git #{arguments}` <ide> def single_commit? start_revision, end_revision <ide> end <ide> end <ide> <del> if @hash == 'HEAD' <add> if no_args? <ide> if diff_start_sha1 == diff_end_sha1 or \ <ide> single_commit?(diff_start_sha1, diff_end_sha1) <ide> @name = diff_end_sha1
1
Text
Text
fix older release notes
df1d222dd0b4ed00e241a4b0709d2d5c0397b063
<ide><path>CHANGELOG.md <ide> with the `$route` service <ide> (e.g. `ng:init="$location = $service('$location'), ...`) in the view or more correctly create <ide> a service like this: <ide> <del> angular.service('published-svc-shim', function() { <del> this.$location = this.$service('$location'); <del> this.$route = this.$service('$route'); <del> this.$cookies = this.$service('$cookies'); <del> this.$window = this.$service('$window'); <del> this.$document = this.$service('$document'); <del> this.$exceptionHandler = this.$service('$exceptionHandler'); <del> this.$invalidWidgets = this.$service('$invalidWidgets'); <del> }, {$eager: true}); <add> angular.service('published-svc-shim', function($location, $route, $cookies, $window, <add> $document, $exceptionHandler, $invalidWidgets) { <add> this.$location = $location; <add> this.$route = $route; <add> this.$cookies = $cookies; <add> this.$window = $window; <add> this.$document = $document; <add> this.$exceptionHandler = $exceptionHandler; <add> this.$invalidWidgets = $invalidWidgets; <add> }, {$inject: ['$location', '$route', '$cookies', '$window', '$document', '$exceptionHandler', <add> '$invalidWidgets'], <add> $eager: true}); <ide> <ide> - In the light of the `eager-published` change, to complete the cleanup we renamed `$creation` <del> property of services to `eager` with its value being a boolean. <add> property of services to `$eager` with its value being a boolean. <ide> To transition, please rename all `$creation: 'eager'` declarations to `$eager: true`. <ide> (commit 1430c6d6) <ide>
1
Ruby
Ruby
remove check for present? from delete_all
2512bd717bbf60364935afdbacb422d9248a1ba8
<ide><path>activerecord/lib/active_record/associations/collection_association.rb <ide> def transaction(*args) <ide> # <ide> # See delete for more info. <ide> def delete_all(dependent = nil) <del> if dependent.present? && ![:nullify, :delete_all].include?(dependent) <add> if dependent && ![:nullify, :delete_all].include?(dependent) <ide> raise ArgumentError, "Valid values are :nullify or :delete_all" <ide> end <ide> <del> dependent = if dependent.present? <add> dependent = if dependent <ide> dependent <ide> elsif options[:dependent] == :destroy <ide> :delete_all
1
Ruby
Ruby
use gcc instead of gfortran
326d3e07e913cdcaab2191c71a49ecdbee8a6973
<ide><path>Library/Homebrew/requirements/fortran_dependency.rb <ide> class FortranDependency < Requirement <ide> fatal true <ide> <del> default_formula 'gfortran' <add> default_formula 'gcc' <ide> <ide> env { ENV.fortran } <ide>
1
Python
Python
implement mapped value unpacking
46a337c8cda6fcc515fffe9a4e4cc324edaefa0a
<ide><path>airflow/cli/commands/task_command.py <ide> def _run_task_by_local_task_job(args, ti): <ide> <ide> def _run_raw_task(args, ti: TaskInstance) -> None: <ide> """Runs the main task handling code""" <del> ti.task = ti.task.unmap() <ide> ti._run_raw_task( <ide> mark_success=args.mark_success, <ide> job_id=args.job_id, <ide> def task_render(args): <ide> dag = get_dag(args.subdir, args.dag_id) <ide> task = dag.get_task(task_id=args.task_id) <ide> ti = _get_ti(task, args.execution_date_or_run_id, args.map_index, create_if_necessary=True) <del> ti.task = ti.task.unmap() <ide> ti.render_templates() <ide> for attr in task.__class__.template_fields: <ide> print( <ide><path>airflow/decorators/base.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> <add>import collections.abc <ide> import functools <ide> import inspect <del>import itertools <ide> import re <ide> import sys <ide> from typing import ( <add> TYPE_CHECKING, <ide> Any, <ide> Callable, <ide> Collection, <ide> <ide> import attr <ide> import typing_extensions <add>from sqlalchemy.orm import Session <ide> <ide> from airflow.compat.functools import cache, cached_property <ide> from airflow.exceptions import AirflowException <ide> from airflow.models.abstractoperator import DEFAULT_RETRIES, DEFAULT_RETRY_DELAY <ide> from airflow.models.baseoperator import BaseOperator, coerce_resources, coerce_retry_delay, parse_retries <ide> from airflow.models.dag import DAG, DagContext <del>from airflow.models.mappedoperator import MappedOperator <add>from airflow.models.mappedoperator import ( <add> MappedOperator, <add> ValidationSource, <add> create_mocked_kwargs, <add> get_mappable_types, <add>) <ide> from airflow.models.pool import Pool <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.typing_compat import Protocol <ide> from airflow.utils import timezone <ide> from airflow.utils.context import Context <ide> from airflow.utils.task_group import TaskGroup, TaskGroupContext <add>from airflow.utils.types import NOTSET <add> <add>if TYPE_CHECKING: <add> from airflow.models.mappedoperator import MapArgument <ide> <ide> <ide> def validate_python_callable(python_callable: Any) -> None: <ide> def __call__(self, *args, **kwargs) -> XComArg: <ide> op.doc_md = self.function.__doc__ <ide> return XComArg(op) <ide> <del> def _validate_arg_names(self, funcname: str, kwargs: Dict[str, Any], valid_names: Set[str] = set()): <del> unknown_args = kwargs.copy() <del> for name in itertools.chain(self.function_arg_names, valid_names): <del> unknown_args.pop(name, None) <del> <del> if not unknown_args: <del> # If we have no args left ot check, we are valid <del> return <add> def _validate_arg_names(self, func: ValidationSource, kwargs: Dict[str, Any]): <add> kwargs_left = kwargs.copy() <add> for arg_name in self.function_arg_names: <add> value = kwargs_left.pop(arg_name, NOTSET) <add> if func != "map" or value is NOTSET or isinstance(value, get_mappable_types()): <add> continue <add> raise ValueError(f"{func} got unexpected value{type(value)!r} for keyword argument {arg_name!r}") <ide> <del> if len(unknown_args) == 1: <del> raise TypeError(f'{funcname} got unexpected keyword argument {next(iter(unknown_args))!r}') <del> else: <del> names = ", ".join(repr(n) for n in unknown_args) <del> raise TypeError(f'{funcname} got unexpected keyword arguments {names}') <add> if len(kwargs_left) == 1: <add> raise TypeError(f"{func} got unexpected keyword argument {next(iter(kwargs_left))!r}") <add> elif kwargs_left: <add> names = ", ".join(repr(n) for n in kwargs_left) <add> raise TypeError(f"{func} got unexpected keyword arguments {names}") <ide> <del> def map(self, **kwargs) -> XComArg: <add> def map(self, **kwargs: "MapArgument") -> XComArg: <ide> self._validate_arg_names("map", kwargs) <ide> <ide> partial_kwargs = self.kwargs.copy() <ide> def map(self, **kwargs) -> XComArg: <ide> task_group = partial_kwargs.pop("task_group", TaskGroupContext.get_current_task_group(dag)) <ide> task_id = get_unique_task_id(partial_kwargs.pop("task_id"), dag, task_group) <ide> params = partial_kwargs.pop("params", None) <del> partial_op_kwargs = partial_kwargs.pop("op_kwargs", {}) <ide> <ide> # Logic here should be kept in sync with BaseOperatorMeta.partial(). <ide> if "task_concurrency" in partial_kwargs: <ide> def map(self, **kwargs) -> XComArg: <ide> ) <ide> partial_kwargs["resources"] = coerce_resources(partial_kwargs.get("resources")) <ide> partial_kwargs.setdefault("executor_config", {}) <add> partial_kwargs.setdefault("op_args", []) <add> partial_kwargs.setdefault("op_kwargs", {}) <ide> <ide> # Mypy does not work well with a subclassed attrs class :( <ide> _MappedOperator = cast(Any, DecoratedMappedOperator) <ide> operator = _MappedOperator( <ide> operator_class=self.operator_class, <del> mapped_kwargs={"op_args": [], "op_kwargs": kwargs}, <add> mapped_kwargs={}, <ide> partial_kwargs=partial_kwargs, <ide> task_id=task_id, <ide> params=params, <ide> def map(self, **kwargs) -> XComArg: <ide> end_date=end_date, <ide> multiple_outputs=self.multiple_outputs, <ide> python_callable=self.function, <del> partial_op_kwargs=partial_op_kwargs, <add> mapped_op_kwargs=kwargs, <ide> ) <ide> return XComArg(operator=operator) <ide> <ide> def partial(self, **kwargs) -> "_TaskDecorator[Function, OperatorSubclass]": <ide> return attr.evolve(self, kwargs={**self.kwargs, "op_kwargs": op_kwargs}) <ide> <ide> <del>def _merge_kwargs( <del> kwargs1: Dict[str, XComArg], <del> kwargs2: Dict[str, XComArg], <del> *, <del> fail_reason: str, <del>) -> Dict[str, XComArg]: <add>def _merge_kwargs(kwargs1: Dict[str, Any], kwargs2: Dict[str, Any], *, fail_reason: str) -> Dict[str, Any]: <ide> duplicated_keys = set(kwargs1).intersection(kwargs2) <ide> if len(duplicated_keys) == 1: <ide> raise TypeError(f"{fail_reason} argument: {duplicated_keys.pop()}") <ide> class DecoratedMappedOperator(MappedOperator): <ide> multiple_outputs: bool <ide> python_callable: Callable <ide> <del> # We can't save these in partial_kwargs because op_args and op_kwargs need <del> # to be present in mapped_kwargs, and MappedOperator prevents duplication. <del> partial_op_kwargs: Dict[str, Any] <add> # We can't save these in mapped_kwargs because op_kwargs need to be present <add> # in partial_kwargs, and MappedOperator prevents duplication. <add> mapped_op_kwargs: Dict[str, "MapArgument"] <ide> <ide> @classmethod <ide> @cache <ide> def get_serialized_fields(cls): <del> # The magic argument-less super() does not work well with @cache <del> # (actually lru_cache in general), so we use the explicit form instead. <add> # The magic super() doesn't work here, so we use the explicit form. <add> # Not using super(..., cls) to work around pyupgrade bug. <ide> sup = super(DecoratedMappedOperator, DecoratedMappedOperator) <del> return sup.get_serialized_fields() | {"partial_op_kwargs"} <add> return sup.get_serialized_fields() | {"mapped_op_kwargs"} <ide> <del> def _create_unmapped_operator( <del> self, <del> *, <del> mapped_kwargs: Dict[str, Any], <del> partial_kwargs: Dict[str, Any], <del> real: bool, <del> ) -> "BaseOperator": <add> def __attrs_post_init__(self): <add> # The magic super() doesn't work here, so we use the explicit form. <add> # Not using super(..., self) to work around pyupgrade bug. <add> super(DecoratedMappedOperator, DecoratedMappedOperator).__attrs_post_init__(self) <add> XComArg.apply_upstream_relationship(self, self.mapped_op_kwargs) <add> <add> def _get_expansion_kwargs(self) -> Dict[str, "MapArgument"]: <add> """The kwargs to calculate expansion length against. <add> <add> Different from classic operators, a decorated (taskflow) operator's <add> ``map()`` contributes to the ``op_kwargs`` operator argument (not the <add> operator arguments themselves), and should therefore expand against it. <add> """ <add> return self.mapped_op_kwargs <add> <add> def _create_unmapped_operator(self, *, mapped_kwargs: Dict[str, Any], real: bool) -> "BaseOperator": <ide> assert not isinstance(self.operator_class, str) <del> mapped_kwargs = mapped_kwargs.copy() <del> del mapped_kwargs["op_kwargs"] <add> partial_kwargs = self.partial_kwargs.copy() <add> if real: <add> mapped_op_kwargs: Dict[str, Any] = self.mapped_op_kwargs <add> else: <add> mapped_op_kwargs = create_mocked_kwargs(self.mapped_op_kwargs) <ide> op_kwargs = _merge_kwargs( <del> self.partial_op_kwargs, <del> self.mapped_kwargs["op_kwargs"], # We want to "original" op_kwargs. <add> partial_kwargs.pop("op_kwargs"), <add> mapped_op_kwargs, <ide> fail_reason="mapping already partial", <ide> ) <ide> return self.operator_class( <ide> def _create_unmapped_operator( <ide> **mapped_kwargs, <ide> ) <ide> <add> def _expand_mapped_field(self, key: str, content: Any, context: Context, *, session: Session) -> Any: <add> if key != "op_kwargs" or not isinstance(content, collections.abc.Mapping): <add> return content <add> # The magic super() doesn't work here, so we use the explicit form. <add> # Not using super(..., self) to work around pyupgrade bug. <add> sup: Any = super(DecoratedMappedOperator, DecoratedMappedOperator) <add> return {k: sup._expand_mapped_field(self, k, v, context, session=session) for k, v in content.items()} <add> <ide> <ide> class Task(Generic[Function]): <ide> """Declaration of a @task-decorated callable for type-checking. <ide> class Task(Generic[Function]): <ide> <ide> function: Function <ide> <del> def map(self, **kwargs: Any) -> XComArg: <add> def map(self, **kwargs: "MapArgument") -> XComArg: <ide> ... <ide> <ide> def partial(self, **kwargs: Any) -> "Task[Function]": <ide><path>airflow/executors/debug_executor.py <ide> def _run_task(self, ti: TaskInstance) -> bool: <ide> key = ti.key <ide> try: <ide> params = self.tasks_params.pop(ti.key, {}) <del> ti.task = ti.task.unmap() <ide> ti._run_raw_task(job_id=ti.job_id, **params) <ide> self.change_state(key, State.SUCCESS) <ide> ti._run_finished_callback() <ide><path>airflow/jobs/backfill_job.py <ide> def _manage_executor_state( <ide> if ti.state not in self.STATES_COUNT_AS_RUNNING: <ide> for node in ti.task.mapped_dependants(): <ide> assert isinstance(node, MappedOperator) <del> yield node, ti.run_id, node.expand_mapped_task(ti, session) <add> yield node, ti.run_id, node.expand_mapped_task(ti.run_id, session=session) <ide> <ide> @provide_session <ide> def _get_dag_run(self, dagrun_info: DagRunInfo, dag: DAG, session: Session = None): <ide><path>airflow/models/abstractoperator.py <ide> # under the License. <ide> <ide> import datetime <del>from typing import TYPE_CHECKING, Any, Callable, Collection, Dict, List, Optional, Set, Type, Union <add>from typing import TYPE_CHECKING, Any, Callable, Collection, Dict, Iterable, List, Optional, Set, Type, Union <add> <add>from sqlalchemy.orm import Session <ide> <ide> from airflow.compat.functools import cached_property <ide> from airflow.configuration import conf <ide> from airflow.exceptions import AirflowException <ide> from airflow.models.taskmixin import DAGNode <ide> from airflow.utils.context import Context <add>from airflow.utils.helpers import render_template_as_native, render_template_to_string <ide> from airflow.utils.log.logging_mixin import LoggingMixin <add>from airflow.utils.session import NEW_SESSION, provide_session <ide> from airflow.utils.trigger_rule import TriggerRule <ide> from airflow.utils.weight_rule import WeightRule <ide> <ide> def get_extra_links(self, dttm: datetime.datetime, link_name: str) -> Optional[D <ide> elif link_name in self.global_operator_extra_link_dict: <ide> return self.global_operator_extra_link_dict[link_name].get_link(self, dttm) <ide> return None <add> <add> def render_template_fields( <add> self, <add> context: Context, <add> jinja_env: Optional["jinja2.Environment"] = None, <add> ) -> Optional["BaseOperator"]: <add> """Template all attributes listed in template_fields. <add> <add> If the operator is mapped, this should return the unmapped, fully <add> rendered, and map-expanded operator. The mapped operator should not be <add> modified. <add> <add> If the operator is not mapped, this should modify the operator in-place <add> and return either *None* (for backwards compatibility) or *self*. <add> """ <add> raise NotImplementedError() <add> <add> @provide_session <add> def _do_render_template_fields( <add> self, <add> parent: Any, <add> template_fields: Iterable[str], <add> context: Context, <add> jinja_env: "jinja2.Environment", <add> seen_oids: Set, <add> *, <add> session: Session = NEW_SESSION, <add> ) -> None: <add> for attr_name in template_fields: <add> try: <add> value = getattr(parent, attr_name) <add> except AttributeError: <add> raise AttributeError( <add> f"{attr_name!r} is configured as a template field " <add> f"but {parent.task_type} does not have this attribute." <add> ) <add> if not value: <add> continue <add> rendered_content = self._render_template_field( <add> attr_name, <add> value, <add> context, <add> jinja_env, <add> seen_oids, <add> session=session, <add> ) <add> setattr(parent, attr_name, rendered_content) <add> <add> def _render_template_field( <add> self, <add> key: str, <add> value: Any, <add> context: Context, <add> jinja_env: Optional["jinja2.Environment"] = None, <add> seen_oids: Optional[Set] = None, <add> *, <add> session: Session, <add> ) -> Any: <add> """Override point for MappedOperator to perform further resolution.""" <add> return self.render_template(value, context, jinja_env, seen_oids) <add> <add> def render_template( <add> self, <add> content: Any, <add> context: Context, <add> jinja_env: Optional["jinja2.Environment"] = None, <add> seen_oids: Optional[Set] = None, <add> ) -> Any: <add> """Render a templated string. <add> <add> If *content* is a collection holding multiple templated strings, strings <add> in the collection will be templated recursively. <add> <add> :param content: Content to template. Only strings can be templated (may <add> be inside a collection). <add> :param context: Dict with values to apply on templated content <add> :param jinja_env: Jinja environment. Can be provided to avoid <add> re-creating Jinja environments during recursion. <add> :param seen_oids: template fields already rendered (to avoid <add> *RecursionError* on circular dependencies) <add> :return: Templated content <add> """ <add> # "content" is a bad name, but we're stuck to it being public API. <add> value = content <add> del content <add> <add> if not jinja_env: <add> jinja_env = self.get_template_env() <add> <add> from airflow.models.param import DagParam <add> from airflow.models.xcom_arg import XComArg <add> <add> if isinstance(value, str): <add> if any(value.endswith(ext) for ext in self.template_ext): # A filepath. <add> template = jinja_env.get_template(value) <add> else: <add> template = jinja_env.from_string(value) <add> dag = self.get_dag() <add> if dag and dag.render_template_as_native_obj: <add> return render_template_as_native(template, context) <add> return render_template_to_string(template, context) <add> <add> if isinstance(value, (DagParam, XComArg)): <add> return value.resolve(context) <add> <add> # Fast path for common built-in collections. <add> if value.__class__ is tuple: <add> return tuple(self.render_template(element, context, jinja_env) for element in value) <add> elif isinstance(value, tuple): # Special case for named tuples. <add> return value.__class__(*(self.render_template(el, context, jinja_env) for el in value)) <add> elif isinstance(value, list): <add> return [self.render_template(element, context, jinja_env) for element in value] <add> elif isinstance(value, dict): <add> return {key: self.render_template(value, context, jinja_env) for key, value in value.items()} <add> elif isinstance(value, set): <add> return {self.render_template(element, context, jinja_env) for element in value} <add> <add> # More complex collections. <add> if seen_oids is None: <add> oids = set() <add> else: <add> oids = seen_oids <add> self._render_nested_template_fields(value, context, jinja_env, oids) <add> return value <add> <add> def _render_nested_template_fields( <add> self, <add> value: Any, <add> context: Context, <add> jinja_env: "jinja2.Environment", <add> seen_oids: Set[int], <add> ) -> None: <add> if id(value) in seen_oids: <add> return <add> seen_oids.add(id(value)) <add> try: <add> nested_template_fields = value.template_fields <add> except AttributeError: <add> # content has no inner template fields <add> return <add> self._do_render_template_fields(value, nested_template_fields, context, jinja_env, seen_oids) <ide><path>airflow/models/baseoperator.py <ide> from airflow.triggers.base import BaseTrigger <ide> from airflow.utils import timezone <ide> from airflow.utils.context import Context <del>from airflow.utils.helpers import render_template_as_native, render_template_to_string, validate_key <add>from airflow.utils.helpers import validate_key <ide> from airflow.utils.operator_resources import Resources <ide> from airflow.utils.session import NEW_SESSION, provide_session <ide> from airflow.utils.trigger_rule import TriggerRule <ide> def __setstate__(self, state): <ide> self._log = logging.getLogger("airflow.task.operators") <ide> <ide> def render_template_fields( <del> self, context: Context, jinja_env: Optional["jinja2.Environment"] = None <del> ) -> None: <del> """ <del> Template all attributes listed in template_fields. Note this operation is irreversible. <del> <del> :param context: Dict with values to apply on content <del> :param jinja_env: Jinja environment <del> """ <del> if not jinja_env: <del> jinja_env = self.get_template_env() <del> <del> self._do_render_template_fields(self, self.template_fields, context, jinja_env, set()) <del> <del> def _do_render_template_fields( <ide> self, <del> parent: Any, <del> template_fields: Iterable[str], <ide> context: Context, <del> jinja_env: "jinja2.Environment", <del> seen_oids: Set, <del> ) -> None: <del> for attr_name in template_fields: <del> try: <del> content = getattr(parent, attr_name) <del> except AttributeError: <del> raise AttributeError( <del> f"{attr_name!r} is configured as a template field " <del> f"but {parent.task_type} does not have this attribute." <del> ) <add> jinja_env: Optional["jinja2.Environment"] = None, <add> ) -> Optional["BaseOperator"]: <add> """Template all attributes listed in template_fields. <ide> <del> if content: <del> rendered_content = self.render_template(content, context, jinja_env, seen_oids) <del> setattr(parent, attr_name, rendered_content) <add> This mutates the attributes in-place and is irreversible. <ide> <del> def render_template( <del> self, <del> content: Any, <del> context: Context, <del> jinja_env: Optional["jinja2.Environment"] = None, <del> seen_oids: Optional[Set] = None, <del> ) -> Any: <del> """ <del> Render a templated string. The content can be a collection holding multiple templated strings and will <del> be templated recursively. <del> <del> :param content: Content to template. Only strings can be templated (may be inside collection). <del> :param context: Dict with values to apply on templated content <del> :param jinja_env: Jinja environment. Can be provided to avoid re-creating Jinja environments during <del> recursion. <del> :param seen_oids: template fields already rendered (to avoid RecursionError on circular dependencies) <del> :return: Templated content <add> :param context: Dict with values to apply on content <add> :param jinja_env: Jinja environment <ide> """ <ide> if not jinja_env: <ide> jinja_env = self.get_template_env() <del> <del> # Imported here to avoid circular dependency <del> from airflow.models.param import DagParam <del> from airflow.models.xcom_arg import XComArg <del> <del> if isinstance(content, str): <del> if any(content.endswith(ext) for ext in self.template_ext): # Content contains a filepath. <del> template = jinja_env.get_template(content) <del> else: <del> template = jinja_env.from_string(content) <del> if self.has_dag() and self.dag.render_template_as_native_obj: <del> return render_template_as_native(template, context) <del> return render_template_to_string(template, context) <del> <del> elif isinstance(content, (XComArg, DagParam)): <del> return content.resolve(context) <del> <del> if isinstance(content, tuple): <del> if type(content) is not tuple: <del> # Special case for named tuples <del> return content.__class__( <del> *(self.render_template(element, context, jinja_env) for element in content) <del> ) <del> else: <del> return tuple(self.render_template(element, context, jinja_env) for element in content) <del> <del> elif isinstance(content, list): <del> return [self.render_template(element, context, jinja_env) for element in content] <del> <del> elif isinstance(content, dict): <del> return {key: self.render_template(value, context, jinja_env) for key, value in content.items()} <del> <del> elif isinstance(content, set): <del> return {self.render_template(element, context, jinja_env) for element in content} <del> <del> else: <del> if seen_oids is None: <del> seen_oids = set() <del> self._render_nested_template_fields(content, context, jinja_env, seen_oids) <del> return content <del> <del> def _render_nested_template_fields( <del> self, content: Any, context: Context, jinja_env: "jinja2.Environment", seen_oids: Set <del> ) -> None: <del> if id(content) not in seen_oids: <del> seen_oids.add(id(content)) <del> try: <del> nested_template_fields = content.template_fields <del> except AttributeError: <del> # content has no inner template fields <del> return <del> <del> self._do_render_template_fields(content, nested_template_fields, context, jinja_env, seen_oids) <add> self._do_render_template_fields(self, self.template_fields, context, jinja_env, set()) <add> return self <ide> <ide> @provide_session <ide> def clear( <ide><path>airflow/models/mappedoperator.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> <add>import collections <add>import collections.abc <ide> import datetime <add>import functools <add>import operator <ide> import unittest.mock <ide> import warnings <ide> from typing import ( <ide> TaskStateChangeCallback, <ide> ) <ide> from airflow.models.pool import Pool <del>from airflow.models.xcom_arg import XComArg <ide> from airflow.serialization.enums import DagAttributeTypes <ide> from airflow.ti_deps.deps.base_ti_dep import BaseTIDep <ide> from airflow.ti_deps.deps.mapped_task_expanded import MappedTaskIsExpanded <add>from airflow.typing_compat import Literal <add>from airflow.utils.context import Context <ide> from airflow.utils.operator_resources import Resources <del>from airflow.utils.session import NEW_SESSION <ide> from airflow.utils.state import State, TaskInstanceState <ide> from airflow.utils.task_group import TaskGroup <ide> from airflow.utils.trigger_rule import TriggerRule <add>from airflow.utils.types import NOTSET <ide> <ide> if TYPE_CHECKING: <add> import jinja2 # Slow import. <add> <ide> from airflow.models.baseoperator import BaseOperator, BaseOperatorLink <ide> from airflow.models.dag import DAG <ide> from airflow.models.taskinstance import TaskInstance <add> from airflow.models.xcom_arg import XComArg <add> <add> # BaseOperator.map() can be called on an XComArg, sequence, or dict (not any <add> # mapping since we need the value to be ordered). <add> MapArgument = Union[XComArg, Sequence, dict] <add> <add>ValidationSource = Union[Literal["map"], Literal["partial"]] <add> <add> <add># For isinstance() check. <add>@cache <add>def get_mappable_types() -> Tuple[type, ...]: <add> from airflow.models.xcom_arg import XComArg <add> <add> return (XComArg, dict, list) <ide> <ide> <del>def validate_mapping_kwargs(op: Type["BaseOperator"], func: str, value: Dict[str, Any]) -> None: <add>def validate_mapping_kwargs(op: Type["BaseOperator"], func: ValidationSource, value: Dict[str, Any]) -> None: <ide> # use a dict so order of args is same as code order <ide> unknown_args = value.copy() <ide> for klass in op.mro(): <del> init = klass.__init__ # type: ignore <add> init = klass.__init__ # type: ignore[misc] <ide> try: <ide> param_names = init._BaseOperatorMeta__param_names <ide> except AttributeError: <ide> continue <ide> for name in param_names: <del> unknown_args.pop(name, None) <add> value = unknown_args.pop(name, NOTSET) <add> if func != "map": <add> continue <add> if value is NOTSET: <add> continue <add> if isinstance(value, get_mappable_types()): <add> continue <add> type_name = type(value).__name__ <add> error = f"{op.__name__}.map() got unexpected type {type_name!r} for keyword argument {name}" <add> raise ValueError(error) <ide> if not unknown_args: <ide> return # If we have no args left ot check: stop looking at the MRO chian. <ide> <ide> if len(unknown_args) == 1: <del> error = f"unexpected keyword argument {unknown_args.popitem()[0]!r}" <add> error = f"an unexpected keyword argument {unknown_args.popitem()[0]!r}" <ide> else: <ide> names = ", ".join(repr(n) for n in unknown_args) <ide> error = f"unexpected keyword arguments {names}" <ide> def prevent_duplicates(kwargs1: Dict[str, Any], kwargs2: Dict[str, Any], *, fail <ide> raise TypeError(f"{fail_reason} arguments: {duplicated_keys_display}") <ide> <ide> <add>def create_mocked_kwargs(kwargs: Dict[str, "MapArgument"]) -> Dict[str, unittest.mock.MagicMock]: <add> """Create a mapping of mocks for given map arguments. <add> <add> When a mapped operator is created, we want to perform basic validation on <add> the map arguments, especially the count of arguments. However, most of this <add> kind of logic lives directly on an operator class's ``__init__``, and <add> there's no good way to validate the arguments except to actually try to <add> create an operator instance. <add> <add> Since the map arguments are yet to be populated when the mapped operator is <add> being parsed, we need to "invent" some mocked values for this validation <add> purpose. The :class:`~unittest.mock.MagicMock` class is a good fit for this <add> since it not only provide good run-time properties, but also enjoy special <add> treatments in Mypy. <add> """ <add> return {k: unittest.mock.MagicMock(name=k) for k in kwargs} <add> <add> <ide> @attr.define(kw_only=True, repr=False) <ide> class OperatorPartial: <ide> """An "intermediate state" returned by ``BaseOperator.partial()``. <ide> def __del__(self): <ide> if not self._map_called: <ide> warnings.warn(f"{self!r} was never mapped!") <ide> <del> def map(self, **mapped_kwargs) -> "MappedOperator": <add> def map(self, **mapped_kwargs: "MapArgument") -> "MappedOperator": <ide> from airflow.operators.dummy import DummyOperator <ide> <ide> validate_mapping_kwargs(self.operator_class, "map", mapped_kwargs) <ide> def map(self, **mapped_kwargs) -> "MappedOperator": <ide> start_date = partial_kwargs.pop("start_date") <ide> end_date = partial_kwargs.pop("end_date") <ide> <del> operator = MappedOperator( <add> op = MappedOperator( <ide> operator_class=self.operator_class, <ide> mapped_kwargs=mapped_kwargs, <ide> partial_kwargs=partial_kwargs, <ide> def map(self, **mapped_kwargs) -> "MappedOperator": <ide> end_date=end_date, <ide> ) <ide> self._map_called = True <del> return operator <add> return op <ide> <ide> <ide> @attr.define(kw_only=True) <ide> class MappedOperator(AbstractOperator): <ide> """Object representing a mapped operator in a DAG.""" <ide> <ide> operator_class: Union[Type["BaseOperator"], str] <del> mapped_kwargs: Dict[str, Any] <add> mapped_kwargs: Dict[str, "MapArgument"] <ide> partial_kwargs: Dict[str, Any] <ide> <ide> # Needed for serialization. <ide> def __repr__(self): <ide> return f"<Mapped({self._task_type}): {self.task_id}>" <ide> <ide> def __attrs_post_init__(self): <add> from airflow.models.xcom_arg import XComArg <add> <ide> prevent_duplicates(self.partial_kwargs, self.mapped_kwargs, fail_reason="mapping already partial") <ide> self._validate_argument_count() <ide> if self.task_group: <ide> def _validate_argument_count(self) -> None: <ide> """ <ide> if isinstance(self.operator_class, str): <ide> return # No need to validate deserialized operator. <del> operator = self._create_unmapped_operator( <del> mapped_kwargs={k: unittest.mock.MagicMock(name=k) for k in self.mapped_kwargs}, <del> partial_kwargs=self.partial_kwargs, <del> real=False, <del> ) <del> if operator.task_group: <del> operator.task_group._remove(operator) <del> dag = operator.get_dag() <add> mocked_mapped_kwargs = create_mocked_kwargs(self.mapped_kwargs) <add> op = self._create_unmapped_operator(mapped_kwargs=mocked_mapped_kwargs, real=False) <add> dag = op.get_dag() <ide> if dag: <del> dag._remove_task(operator.task_id) <add> dag._remove_task(op.task_id) <ide> <ide> @property <ide> def task_type(self) -> str: <ide> def serialize_for_task_group(self) -> Tuple[DagAttributeTypes, Any]: <ide> """Implementing DAGNode.""" <ide> return DagAttributeTypes.OP, self.task_id <ide> <del> def _create_unmapped_operator( <del> self, <del> *, <del> mapped_kwargs: Dict[str, Any], <del> partial_kwargs: Dict[str, Any], <del> real: bool, <del> ) -> "BaseOperator": <add> def _create_unmapped_operator(self, *, mapped_kwargs: Dict[str, Any], real: bool) -> "BaseOperator": <add> """Create a task of the underlying class based on this mapped operator. <add> <add> :param mapped_kwargs: Mapped keyword arguments to be used to create the <add> task. Do not use ``self.mapped_kwargs``. <add> :param real: Whether the task should be created "for real" (i.e. *False* <add> means the operator is only created for validation purposes and not <add> going to be added to the actual DAG). This is simply forwarded to <add> the operator's ``_airflow_map_validation`` argument. <add> """ <ide> assert not isinstance(self.operator_class, str) <ide> return self.operator_class( <ide> task_id=self.task_id, <ide> def _create_unmapped_operator( <ide> start_date=self.start_date, <ide> end_date=self.end_date, <ide> _airflow_map_validation=not real, <add> **self.partial_kwargs, <ide> **mapped_kwargs, <del> **partial_kwargs, <ide> ) <ide> <ide> def unmap(self) -> "BaseOperator": <ide> def unmap(self) -> "BaseOperator": <ide> if not dag: <ide> raise RuntimeError("Cannot unmap a task without a DAG") <ide> dag._remove_task(self.task_id) <del> return self._create_unmapped_operator( <del> mapped_kwargs=self.mapped_kwargs, <del> partial_kwargs=self.partial_kwargs, <del> real=True, <add> return self._create_unmapped_operator(mapped_kwargs=self.mapped_kwargs, real=True) <add> <add> def _get_expansion_kwargs(self) -> Dict[str, "MapArgument"]: <add> """The kwargs to calculate expansion length against. <add> <add> This is ``self.mapped_kwargs`` for classic operators because kwargs to <add> ``BaseOperator.map()`` contribute to operator arguments. <add> """ <add> return self.mapped_kwargs <add> <add> def _get_map_lengths(self, run_id: str, *, session: Session) -> Dict[str, int]: <add> # TODO: Find a way to cache this. <add> from airflow.models.taskmap import TaskMap <add> from airflow.models.xcom_arg import XComArg <add> <add> expansion_kwargs = self._get_expansion_kwargs() <add> <add> # Populate literal mapped arguments first. <add> map_lengths: Dict[str, int] = collections.defaultdict(int) <add> map_lengths.update((k, len(v)) for k, v in expansion_kwargs.items() if not isinstance(v, XComArg)) <add> <add> # Build a reverse mapping of what arguments each task contributes to. <add> dep_keys: Dict[str, Set[str]] = collections.defaultdict(set) <add> for k, v in expansion_kwargs.items(): <add> if not isinstance(v, XComArg): <add> continue <add> dep_keys[v.operator.task_id].add(k) <add> <add> taskmap_query = session.query(TaskMap.task_id, TaskMap.length).filter( <add> TaskMap.dag_id == self.dag_id, <add> TaskMap.run_id == run_id, <add> TaskMap.task_id.in_(list(dep_keys)), <ide> ) <add> for task_id, length in taskmap_query: <add> for mapped_arg_name in dep_keys[task_id]: <add> map_lengths[mapped_arg_name] += length <ide> <del> def expand_mapped_task( <del> self, <del> upstream_ti: "TaskInstance", <del> session: Session = NEW_SESSION, <del> ) -> Sequence["TaskInstance"]: <add> if len(map_lengths) < len(expansion_kwargs): <add> keys = ", ".join(repr(k) for k in sorted(set(expansion_kwargs).difference(map_lengths))) <add> raise RuntimeError(f"Failed to populate all mapping metadata; missing: {keys}") <add> <add> return map_lengths <add> <add> def expand_mapped_task(self, run_id: str, *, session: Session) -> Sequence["TaskInstance"]: <ide> """Create the mapped task instances for mapped task. <ide> <ide> :return: The mapped task instances, in ascending order by map index. <ide> """ <del> # TODO: support having multiuple mapped upstreams? <ide> from airflow.models.taskinstance import TaskInstance <del> from airflow.models.taskmap import TaskMap <ide> from airflow.settings import task_instance_mutation_hook <ide> <del> task_map_info_length: Optional[int] = ( <del> session.query(TaskMap.length) <del> .filter_by( <del> dag_id=upstream_ti.dag_id, <del> task_id=upstream_ti.task_id, <del> run_id=upstream_ti.run_id, <del> map_index=upstream_ti.map_index, <del> ) <del> .scalar() <del> ) <del> if task_map_info_length is None: <del> # TODO: What would lead to this? How can this be better handled? <del> raise RuntimeError("mapped operator cannot be expanded; upstream not found") <add> total_length = functools.reduce(operator.mul, self._get_map_lengths(run_id, session=session).values()) <ide> <del> state = None <add> state: Optional[TaskInstanceState] = None <ide> unmapped_ti: Optional[TaskInstance] = ( <ide> session.query(TaskInstance) <ide> .filter( <del> TaskInstance.dag_id == upstream_ti.dag_id, <del> TaskInstance.run_id == upstream_ti.run_id, <add> TaskInstance.dag_id == self.dag_id, <ide> TaskInstance.task_id == self.task_id, <add> TaskInstance.run_id == run_id, <ide> TaskInstance.map_index == -1, <ide> or_(TaskInstance.state.in_(State.unfinished), TaskInstance.state.is_(None)), <ide> ) <ide> def expand_mapped_task( <ide> if unmapped_ti: <ide> # The unmapped task instance still exists and is unfinished, i.e. we <ide> # haven't tried to run it before. <del> if task_map_info_length < 1: <add> if total_length < 1: <ide> # If the upstream maps this to a zero-length value, simply marked the <ide> # unmapped task instance as SKIPPED (if needed). <del> self.log.info("Marking %s as SKIPPED since the map has 0 values to expand", unmapped_ti) <add> self.log.info( <add> "Marking %s as SKIPPED since the map has %d values to expand", <add> unmapped_ti, <add> total_length, <add> ) <ide> unmapped_ti.state = TaskInstanceState.SKIPPED <ide> session.flush() <ide> return ret <ide> def expand_mapped_task( <ide> state = unmapped_ti.state <ide> self.log.debug("Updated in place to become %s", unmapped_ti) <ide> ret.append(unmapped_ti) <del> indexes_to_map = range(1, task_map_info_length) <add> indexes_to_map = range(1, total_length) <ide> else: <ide> # Only create "missing" ones. <ide> current_max_mapping = ( <ide> session.query(func.max(TaskInstance.map_index)) <ide> .filter( <del> TaskInstance.dag_id == upstream_ti.dag_id, <add> TaskInstance.dag_id == self.dag_id, <ide> TaskInstance.task_id == self.task_id, <del> TaskInstance.run_id == upstream_ti.run_id, <add> TaskInstance.run_id == run_id, <ide> ) <ide> .scalar() <ide> ) <del> indexes_to_map = range(current_max_mapping + 1, task_map_info_length) <add> indexes_to_map = range(current_max_mapping + 1, total_length) <ide> <ide> for index in indexes_to_map: <ide> # TODO: Make more efficient with bulk_insert_mappings/bulk_save_mappings. <ide> # TODO: Change `TaskInstance` ctor to take Operator, not BaseOperator <del> ti = TaskInstance(self, run_id=upstream_ti.run_id, map_index=index, state=state) # type: ignore <add> ti = TaskInstance(self, run_id=run_id, map_index=index, state=state) # type: ignore <ide> self.log.debug("Expanding TIs upserted %s", ti) <ide> task_instance_mutation_hook(ti) <ide> ti = session.merge(ti) <ide> def expand_mapped_task( <ide> # Set to "REMOVED" any (old) TaskInstances with map indices greater <ide> # than the current map value <ide> session.query(TaskInstance).filter( <del> TaskInstance.dag_id == upstream_ti.dag_id, <add> TaskInstance.dag_id == self.dag_id, <ide> TaskInstance.task_id == self.task_id, <del> TaskInstance.run_id == upstream_ti.run_id, <del> TaskInstance.map_index >= task_map_info_length, <add> TaskInstance.run_id == run_id, <add> TaskInstance.map_index >= total_length, <ide> ).update({TaskInstance.state: TaskInstanceState.REMOVED}) <ide> <ide> session.flush() <ide> <ide> return ret <add> <add> def prepare_for_execution(self) -> "MappedOperator": <add> # Since a mapped operator cannot be used for execution, and an unmapped <add> # BaseOperator needs to be created later (see render_template_fields), <add> # we don't need to create a copy of the MappedOperator here. <add> return self <add> <add> def render_template_fields( <add> self, <add> context: Context, <add> jinja_env: Optional["jinja2.Environment"] = None, <add> ) -> Optional["BaseOperator"]: <add> """Template all attributes listed in template_fields. <add> <add> Different from the BaseOperator implementation, this renders the <add> template fields on the *unmapped* BaseOperator. <add> <add> :param context: Dict with values to apply on content <add> :param jinja_env: Jinja environment <add> :return: The unmapped, populated BaseOperator <add> """ <add> if not jinja_env: <add> jinja_env = self.get_template_env() <add> unmapped_task = self.unmap() <add> self._do_render_template_fields( <add> parent=unmapped_task, <add> template_fields=unmapped_task.template_fields, <add> context=context, <add> jinja_env=jinja_env, <add> seen_oids=set(), <add> ) <add> return unmapped_task <add> <add> def _render_template_field( <add> self, <add> key: str, <add> value: Any, <add> context: Context, <add> jinja_env: Optional["jinja2.Environment"] = None, <add> seen_oids: Optional[Set] = None, <add> *, <add> session: Session, <add> ) -> Any: <add> """Override the ordinary template rendering to add more logic. <add> <add> Specifically, if we're rendering a mapped argument, we need to "unmap" <add> the value as well to assign it to the unmapped operator. <add> """ <add> value = super()._render_template_field(key, value, context, jinja_env, seen_oids, session=session) <add> return self._expand_mapped_field(key, value, context, session=session) <add> <add> def _expand_mapped_field(self, key: str, value: Any, context: Context, *, session: Session) -> Any: <add> map_index = context["ti"].map_index <add> if map_index < 0: <add> return value <add> expansion_kwargs = self._get_expansion_kwargs() <add> all_lengths = self._get_map_lengths(context["run_id"], session=session) <add> <add> def _find_index_for_this_field(index: int) -> int: <add> # Need to use self.mapped_kwargs for the original argument order. <add> for mapped_key in reversed(list(expansion_kwargs)): <add> mapped_length = all_lengths[mapped_key] <add> if mapped_length < 1: <add> raise RuntimeError(f"cannot expand field mapped to length {mapped_length!r}") <add> if mapped_key == key: <add> return index % mapped_length <add> index //= mapped_length <add> return -1 <add> <add> found_index = _find_index_for_this_field(map_index) <add> if found_index < 0: <add> return value <add> if isinstance(value, collections.abc.Sequence): <add> return value[found_index] <add> if not isinstance(value, dict): <add> raise TypeError(f"can't map over value of type {type(value)}") <add> for i, (k, v) in enumerate(value.items()): <add> if i == found_index: <add> return k, v <add> raise IndexError(f"index {map_index} is over mapped length") <ide><path>airflow/models/renderedtifields.py <ide> class RenderedTaskInstanceFields(Base): <ide> def __init__(self, ti: TaskInstance, render_templates=True): <ide> self.dag_id = ti.dag_id <ide> self.task_id = ti.task_id <del> self.task = ti.task <ide> self.execution_date = ti.execution_date <ide> self.ti = ti <ide> if render_templates: <ide> ti.render_templates() <add> self.task = ti.task <ide> if os.environ.get("AIRFLOW_IS_K8S_EXECUTOR_POD", None): <ide> self.k8s_pod_yaml = ti.render_k8s_pod_yaml() <ide> self.rendered_fields = { <ide><path>airflow/models/taskinstance.py <ide> def _run_raw_task( <ide> :param pool: specifies the pool to use to run the task instance <ide> :param session: SQLAlchemy ORM Session <ide> """ <del> if self.task.is_mapped: <del> raise RuntimeError( <del> f'task property of {self.task_id!r} was still a MappedOperator -- it should have been ' <del> 'expanded already!' <del> ) <del> task = self.task.unmap() <ide> self.test_mode = test_mode <del> self.refresh_from_task(task, pool_override=pool) <add> self.refresh_from_task(self.task, pool_override=pool) <ide> self.refresh_from_db(session=session) <ide> self.job_id = job_id <ide> self.hostname = get_hostname() <ide> def _run_raw_task( <ide> Stats.incr(f'ti.start.{self.task.dag_id}.{self.task.task_id}') <ide> try: <ide> if not mark_success: <del> self.task = task.prepare_for_execution() <add> self.task = self.task.prepare_for_execution() <ide> context = self.get_template_context(ignore_param_exceptions=False) <ide> self._execute_task_with_callbacks(context) <ide> if not test_mode: <ide> def _run_raw_task( <ide> session.commit() <ide> raise <ide> finally: <del> Stats.incr(f'ti.finish.{task.dag_id}.{task.task_id}.{self.state}') <add> Stats.incr(f'ti.finish.{self.dag_id}.{self.task_id}.{self.state}') <ide> <ide> # Recording SKIPPED or SUCCESS <ide> self.clear_next_method_args() <ide> def run( <ide> <ide> def dry_run(self): <ide> """Only Renders Templates for the TI""" <del> task_copy = self.task.unmap().prepare_for_execution() <del> self.task = task_copy <add> from airflow.models.baseoperator import BaseOperator <ide> <add> self.task = self.task.prepare_for_execution() <ide> self.render_templates() <del> task_copy.dry_run() <add> assert isinstance(self.task, BaseOperator) # For Mypy. <add> self.task.dry_run() <ide> <ide> @provide_session <ide> def _handle_reschedule( <ide> def get_prev_ds_nodash() -> Optional[str]: <ide> return Context(context) # type: ignore <ide> <ide> @provide_session <del> def get_rendered_template_fields(self, session=NEW_SESSION): <add> def get_rendered_template_fields(self, session: Session = NEW_SESSION) -> None: <ide> """Fetch rendered template fields from DB""" <ide> from airflow.models.renderedtifields import RenderedTaskInstanceFields <ide> <ide> rendered_task_instance_fields = RenderedTaskInstanceFields.get_templated_fields(self, session=session) <ide> if rendered_task_instance_fields: <add> task = self.task.unmap() <ide> for field_name, rendered_value in rendered_task_instance_fields.items(): <ide> setattr(self.task, field_name, rendered_value) <del> else: <del> try: <del> self.render_templates() <del> except (TemplateAssertionError, UndefinedError) as e: <del> raise AirflowException( <del> "Webserver does not have access to User-defined Macros or Filters " <del> "when Dag Serialization is enabled. Hence for the task that have not yet " <del> "started running, please use 'airflow tasks render' for debugging the " <del> "rendering of template_fields." <del> ) from e <add> self.task = task <add> try: <add> self.render_templates() <add> except (TemplateAssertionError, UndefinedError) as e: <add> raise AirflowException( <add> "Webserver does not have access to User-defined Macros or Filters " <add> "when Dag Serialization is enabled. Hence for the task that have not yet " <add> "started running, please use 'airflow tasks render' for debugging the " <add> "rendering of template_fields." <add> ) from e <ide> <ide> @provide_session <ide> def get_rendered_k8s_spec(self, session=NEW_SESSION): <ide> def overwrite_params_with_dag_run_conf(self, params, dag_run): <ide> params.update(dag_run.conf) <ide> <ide> def render_templates(self, context: Optional[Context] = None) -> None: <del> """Render templates in the operator fields.""" <del> if self.task.is_mapped: <del> raise RuntimeError( <del> f'task property of {self.task_id!r} was still a MappedOperator -- it should have been ' <del> 'expanded already!' <del> ) <add> """Render templates in the operator fields. <add> <add> If the task was originally mapped, this may replace ``self.task`` with <add> the unmapped, fully rendered BaseOperator. <add> """ <ide> if not context: <ide> context = self.get_template_context() <del> self.task.unmap().render_template_fields(context) <add> task = self.task.render_template_fields(context) <add> if task is not None: <add> self.task = task <ide> <ide> def render_k8s_pod_yaml(self) -> Optional[dict]: <ide> """Render k8s pod yaml""" <ide><path>airflow/serialization/serialized_objects.py <ide> def serialize_mapped_operator(cls, op: MappedOperator) -> Dict[str, Any]: <ide> assert op_kwargs[Encoding.TYPE] == DAT.DICT <ide> serialized_op["partial_kwargs"]["op_kwargs"] = op_kwargs[Encoding.VAR] <ide> with contextlib.suppress(KeyError): <del> op_kwargs = serialized_op["partial_op_kwargs"] <add> op_kwargs = serialized_op["mapped_op_kwargs"] <ide> assert op_kwargs[Encoding.TYPE] == DAT.DICT <del> serialized_op["partial_op_kwargs"] = op_kwargs[Encoding.VAR] <add> serialized_op["mapped_op_kwargs"] = op_kwargs[Encoding.VAR] <ide> <ide> serialized_op["_is_mapped"] = True <ide> return serialized_op <ide> def deserialize_operator(cls, encoded_op: Dict[str, Any]) -> Union[BaseOperator, <ide> v = {arg: cls._deserialize(value) for arg, value in v.items()} <ide> if op_kwargs is not None: <ide> v["op_kwargs"] = op_kwargs <del> elif k == "partial_op_kwargs": <add> elif k == "mapped_op_kwargs": <ide> v = {arg: cls._deserialize(value) for arg, value in v.items()} <ide> elif k in cls._decorated_fields or k not in op.get_serialized_fields(): <ide> v = cls._deserialize(v) <ide><path>airflow/www/views.py <ide> def rendered_templates(self, session): <ide> logging.info("Retrieving rendered templates.") <ide> dag: DAG = current_app.dag_bag.get_dag(dag_id) <ide> dag_run = dag.get_dagrun(execution_date=dttm, session=session) <del> task = copy.copy(dag.get_task(task_id).unmap()) <add> task = dag.get_task(task_id).prepare_for_execution() <ide> <ide> if dag_run is None: <ide> # No DAG run matching given logical date. This usually means this <ide> def rendered_templates(self, session): <ide> flash(msg, "error") <ide> except Exception as e: <ide> flash("Error rendering template: " + str(e), "error") <add> else: <add> task = ti.task <ide> <ide> title = "Rendered Template" <ide> html_dict = {} <ide><path>tests/dags/test_mapped_classic.py <ide> <ide> <ide> @task <del>def make_list(): <del> return [1, 2, {'a': 'b'}] <add>def make_arg_lists(): <add> return [[1], [2], [{'a': 'b'}]] <ide> <ide> <del>def consumer(*args): <del> print(repr(args)) <add>def consumer(value): <add> print(repr(value)) <ide> <ide> <ide> with DAG(dag_id='test_mapped_classic', start_date=days_ago(2)) as dag: <del> PythonOperator.partial(task_id='consumer', python_callable=consumer).map(op_args=make_list()) <add> PythonOperator.partial(task_id='consumer', python_callable=consumer).map(op_args=make_arg_lists()) <ide><path>tests/decorators/test_python.py <ide> from airflow.decorators.base import DecoratedMappedOperator <ide> from airflow.exceptions import AirflowException <ide> from airflow.models import DAG <del>from airflow.models.mappedoperator import MappedOperator <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.utils import timezone <ide> from airflow.utils.state import State <ide> def double(number: int): <ide> doubled_1 = double.map(number=literal) <ide> <ide> assert isinstance(doubled_0, XComArg) <del> assert isinstance(doubled_0.operator, MappedOperator) <add> assert isinstance(doubled_0.operator, DecoratedMappedOperator) <ide> assert doubled_0.operator.task_id == "double" <del> assert doubled_0.operator.mapped_kwargs == {"op_args": [], "op_kwargs": {"number": literal}} <add> assert doubled_0.operator.mapped_op_kwargs == {"number": literal} <ide> <ide> assert doubled_1.operator.task_id == "double__1" <ide> <ide> def test_mapped_decorator_invalid_args() -> None: <ide> def double(number: int): <ide> return number * 2 <ide> <del> with DAG('test_dag', start_date=DEFAULT_DATE): <del> literal = [1, 2, 3] <add> literal = [1, 2, 3] <ide> <del> with pytest.raises(TypeError, match="arguments 'other', 'b'"): <del> double.partial(other=1, b='a') <del> with pytest.raises(TypeError, match="argument 'other'"): <del> double.map(number=literal, other=1) <add> with pytest.raises(TypeError, match="arguments 'other', 'b'"): <add> double.partial(other=[1], b=['a']) <add> with pytest.raises(TypeError, match="argument 'other'"): <add> double.map(number=literal, other=[1]) <add> with pytest.raises(ValueError, match="argument 'number'"): <add> double.map(number=1) # type: ignore[arg-type] <ide> <ide> <ide> def test_partial_mapped_decorator() -> None: <ide> def product(number: int, multiple: int): <ide> <ide> assert isinstance(doubled, XComArg) <ide> assert isinstance(doubled.operator, DecoratedMappedOperator) <del> assert doubled.operator.mapped_kwargs == {"op_args": [], "op_kwargs": {"number": literal}} <del> assert doubled.operator.partial_op_kwargs == {"multiple": 2} <add> assert doubled.operator.mapped_op_kwargs == {"number": literal} <add> assert doubled.operator.partial_kwargs["op_kwargs"] == {"multiple": 2} <ide> <ide> assert isinstance(trippled.operator, DecoratedMappedOperator) # For type-checking on partial_kwargs. <del> assert trippled.operator.partial_op_kwargs == {"multiple": 3} <add> assert trippled.operator.partial_kwargs["op_kwargs"] == {"multiple": 3} <ide> <ide> assert doubled.operator is not trippled.operator <ide> <ide><path>tests/models/test_baseoperator.py <ide> from airflow.models.mappedoperator import MappedOperator <ide> from airflow.models.taskinstance import TaskInstance <ide> from airflow.models.taskmap import TaskMap <add>from airflow.models.xcom import XCOM_RETURN_KEY <ide> from airflow.models.xcom_arg import XComArg <ide> from airflow.utils.context import Context <ide> from airflow.utils.edgemodifier import Label <ide> def test_expand_mapped_task_instance(dag_maker, session, num_existing_tis, expec <ide> session.add(ti) <ide> session.flush() <ide> <del> mapped.expand_mapped_task(upstream_ti=dr.get_task_instance(task1.task_id), session=session) <add> mapped.expand_mapped_task(dr.run_id, session=session) <ide> <ide> indices = ( <ide> session.query(TaskInstance.map_index, TaskInstance.state) <ide> def test_expand_mapped_task_instance(dag_maker, session, num_existing_tis, expec <ide> def test_expand_mapped_task_instance_skipped_on_zero(dag_maker, session): <ide> with dag_maker(session=session): <ide> task1 = BaseOperator(task_id="op1") <del> xcomarg = XComArg(task1, "test_key") <del> mapped = MockOperator.partial(task_id='task_2').map(arg2=xcomarg) <add> mapped = MockOperator.partial(task_id='task_2').map(arg2=XComArg(task1, XCOM_RETURN_KEY)) <ide> <ide> dr = dag_maker.create_dagrun() <ide> <ide> session.add( <ide> TaskMap(dag_id=dr.dag_id, task_id=task1.task_id, run_id=dr.run_id, map_index=-1, length=0, keys=None) <ide> ) <add> session.flush() <ide> <del> mapped.expand_mapped_task(upstream_ti=dr.get_task_instance(task1.task_id), session=session) <add> mapped.expand_mapped_task(dr.run_id, session=session) <ide> <ide> indices = ( <ide> session.query(TaskInstance.map_index, TaskInstance.state) <ide><path>tests/models/test_taskinstance.py <ide> # under the License. <ide> <ide> import datetime <add>import operator <ide> import os <ide> import signal <ide> import urllib <ide> def pull_something(value): <ide> assert task_map.map_index == -1 <ide> assert task_map.length == expected_length <ide> assert task_map.keys == expected_keys <add> <add> <add>class TestMappedTaskInstanceReceiveValue: <add> @pytest.mark.parametrize( <add> "literal, expected_outputs", <add> [ <add> pytest.param([1, 2, 3], [1, 2, 3], id="list"), <add> pytest.param({"a": 1, "b": 2}, [("a", 1), ("b", 2)], id="dict"), <add> ], <add> ) <add> def test_map_literal(self, literal, expected_outputs, dag_maker, session): <add> outputs = [] <add> <add> with dag_maker(dag_id="literal", session=session) as dag: <add> <add> @dag.task <add> def show(value): <add> outputs.append(value) <add> <add> show.map(value=literal) <add> <add> dag_run = dag_maker.create_dagrun() <add> show_task = dag.get_task("show") <add> mapped_tis = show_task.expand_mapped_task(dag_run.run_id, session=session) <add> assert len(mapped_tis) == len(literal) <add> <add> for ti in sorted(mapped_tis, key=operator.attrgetter("map_index")): <add> ti.refresh_from_task(show_task) <add> ti.run() <add> assert outputs == expected_outputs <add> <add> @pytest.mark.parametrize( <add> "upstream_return, expected_outputs", <add> [ <add> pytest.param([1, 2, 3], [1, 2, 3], id="list"), <add> pytest.param({"a": 1, "b": 2}, [("a", 1), ("b", 2)], id="dict"), <add> ], <add> ) <add> def test_map_xcom(self, upstream_return, expected_outputs, dag_maker, session): <add> outputs = [] <add> <add> with dag_maker(dag_id="xcom", session=session) as dag: <add> <add> @dag.task <add> def emit(): <add> return upstream_return <add> <add> @dag.task <add> def show(value): <add> outputs.append(value) <add> <add> show.map(value=emit()) <add> <add> dag_run = dag_maker.create_dagrun() <add> emit_ti = dag_run.get_task_instance("emit", session=session) <add> emit_ti.refresh_from_task(dag.get_task("emit")) <add> emit_ti.run() <add> <add> show_task = dag.get_task("show") <add> mapped_tis = show_task.expand_mapped_task(dag_run.run_id, session=session) <add> assert len(mapped_tis) == len(upstream_return) <add> <add> for ti in sorted(mapped_tis, key=operator.attrgetter("map_index")): <add> ti.refresh_from_task(show_task) <add> ti.run() <add> assert outputs == expected_outputs <add> <add> def test_map_product(self, dag_maker, session): <add> outputs = [] <add> <add> with dag_maker(dag_id="product", session=session) as dag: <add> <add> @dag.task <add> def emit_numbers(): <add> return [1, 2] <add> <add> @dag.task <add> def emit_letters(): <add> return {"a": "x", "b": "y", "c": "z"} <add> <add> @dag.task <add> def show(number, letter): <add> outputs.append((number, letter)) <add> <add> show.map(number=emit_numbers(), letter=emit_letters()) <add> <add> dag_run = dag_maker.create_dagrun() <add> for task_id in ["emit_numbers", "emit_letters"]: <add> ti = dag_run.get_task_instance(task_id, session=session) <add> ti.refresh_from_task(dag.get_task(task_id)) <add> ti.run() <add> <add> show_task = dag.get_task("show") <add> mapped_tis = show_task.expand_mapped_task(dag_run.run_id, session=session) <add> assert len(mapped_tis) == 6 <add> <add> for ti in sorted(mapped_tis, key=operator.attrgetter("map_index")): <add> ti.refresh_from_task(show_task) <add> ti.run() <add> assert outputs == [ <add> (1, ("a", "x")), <add> (1, ("b", "y")), <add> (1, ("c", "z")), <add> (2, ("a", "x")), <add> (2, ("b", "y")), <add> (2, ("c", "z")), <add> ] <add> <add> def test_map_product_same(self, dag_maker, session): <add> """Test a mapped task can refer to the same source multiple times.""" <add> outputs = [] <add> <add> with dag_maker(dag_id="product_same", session=session) as dag: <add> <add> @dag.task <add> def emit_numbers(): <add> return [1, 2] <add> <add> @dag.task <add> def show(a, b): <add> outputs.append((a, b)) <add> <add> emit_task = emit_numbers() <add> show.map(a=emit_task, b=emit_task) <add> <add> dag_run = dag_maker.create_dagrun() <add> ti = dag_run.get_task_instance("emit_numbers", session=session) <add> ti.refresh_from_task(dag.get_task("emit_numbers")) <add> ti.run() <add> <add> show_task = dag.get_task("show") <add> mapped_tis = show_task.expand_mapped_task(dag_run.run_id, session=session) <add> assert len(mapped_tis) == 4 <add> <add> for ti in sorted(mapped_tis, key=operator.attrgetter("map_index")): <add> ti.refresh_from_task(show_task) <add> ti.run() <add> assert outputs == [(1, 1), (1, 2), (2, 1), (2, 2)] <ide><path>tests/providers/snowflake/transfers/test_snowflake_to_slack.py <ide> # specific language governing permissions and limitations <ide> # under the License. <ide> <del>import unittest <ide> from unittest import mock <ide> <ide> from airflow.models import DAG <ide> from airflow.providers.snowflake.transfers.snowflake_to_slack import SnowflakeToSlackOperator <ide> from airflow.utils import timezone <add>from tests.test_utils.db import clear_db_runs <ide> <ide> TEST_DAG_ID = 'snowflake_to_slack_unit_test' <ide> DEFAULT_DATE = timezone.datetime(2017, 1, 1) <ide> <ide> <del>class TestSnowflakeToSlackOperator(unittest.TestCase): <del> def setUp(self): <add>class TestSnowflakeToSlackOperator: <add> def setup_class(self): <add> clear_db_runs() <add> <add> def setup_method(self): <ide> self.example_dag = DAG('unit_test_dag_snowflake_to_slack', start_date=DEFAULT_DATE) <ide> <add> def teardown_method(self): <add> clear_db_runs() <add> <ide> @staticmethod <ide> def _construct_operator(**kwargs): <ide> operator = SnowflakeToSlackOperator(task_id=TEST_DAG_ID, **kwargs) <ide><path>tests/serialization/test_dag_serialization.py <ide> def x(arg1, arg2, arg3): <ide> '_task_module': 'airflow.decorators.python', <ide> '_task_type': '_PythonDecoratedOperator', <ide> 'downstream_task_ids': [], <del> 'partial_op_kwargs': {'arg1': [1, 2, {"__type": "dict", "__var": {'a': 'b'}}]}, <del> 'partial_kwargs': {'retry_delay': {'__type': 'timedelta', '__var': 30.0}}, <del> 'mapped_kwargs': { <add> 'partial_kwargs': { <ide> 'op_args': [], <del> 'op_kwargs': { <del> 'arg2': {"__type": "dict", "__var": {'a': 1, 'b': 2}}, <del> 'arg3': {'__type': 'xcomref', '__var': {'task_id': 'op1', 'key': 'my_key'}}, <del> }, <add> 'op_kwargs': {'arg1': [1, 2, {"__type": "dict", "__var": {'a': 'b'}}]}, <add> 'retry_delay': {'__type': 'timedelta', '__var': 30.0}, <add> }, <add> 'mapped_kwargs': {}, <add> 'mapped_op_kwargs': { <add> 'arg2': {"__type": "dict", "__var": {'a': 1, 'b': 2}}, <add> 'arg3': {'__type': 'xcomref', '__var': {'task_id': 'op1', 'key': 'my_key'}}, <ide> }, <ide> 'operator_extra_links': [], <ide> 'ui_color': '#ffefeb', <ide> def x(arg1, arg2, arg3): <ide> assert deserialized.upstream_task_ids == set() <ide> assert deserialized.downstream_task_ids == set() <ide> <del> assert deserialized.mapped_kwargs["op_kwargs"] == { <add> assert deserialized.mapped_op_kwargs == { <ide> "arg2": {"a": 1, "b": 2}, <ide> "arg3": _XComRef("op1", "my_key"), <ide> } <del> assert deserialized.partial_kwargs == {"retry_delay": timedelta(seconds=30)} <del> assert deserialized.partial_op_kwargs == {"arg1": [1, 2, {"a": "b"}]} <add> assert deserialized.partial_kwargs == { <add> "op_args": [], <add> "op_kwargs": {"arg1": [1, 2, {"a": "b"}]}, <add> "retry_delay": timedelta(seconds=30), <add> } <ide> <ide> <ide> def test_mapped_task_group_serde():
17
Text
Text
move trevnorris to tsc emeritus
636bac712508725b218e6ba112872470f5a23def
<ide><path>README.md <ide> For more information about the governance of the Node.js project, see <ide> **Michaël Zasso** &lt;targos@protonmail.com&gt; (he/him) <ide> * [thefourtheye](https://github.com/thefourtheye) - <ide> **Sakthipriyan Vairamani** &lt;thechargingvolcano@gmail.com&gt; (he/him) <del>* [trevnorris](https://github.com/trevnorris) - <del>**Trevor Norris** &lt;trev.norris@gmail.com&gt; <ide> * [Trott](https://github.com/Trott) - <ide> **Rich Trott** &lt;rtrott@gmail.com&gt; (he/him) <ide> <ide> For more information about the governance of the Node.js project, see <ide> **Bert Belder** &lt;bertbelder@gmail.com&gt; <ide> * [shigeki](https://github.com/shigeki) - <ide> **Shigeki Ohtsu** &lt;ohtsu@ohtsu.org&gt; (he/him) <add>* [trevnorris](https://github.com/trevnorris) - <add>**Trevor Norris** &lt;trev.norris@gmail.com&gt; <ide> <ide> ### Collaborators <ide>
1
Ruby
Ruby
fix the tests to test what they should be testing
825447130d1a34557d7ba6d8985d2e0715fcbf8e
<ide><path>railties/test/application/middleware/cache_test.rb <ide> def test_cache_works_with_etags <ide> assert_equal "miss, store", last_response.headers["X-Rack-Cache"] <ide> assert_equal "public", last_response.headers["Cache-Control"] <ide> <del> body = last_response.body <ide> etag = last_response.headers["ETag"] <ide> <del> get "/expires/expires_etag", {}, "If-None-Match" => etag <add> get "/expires/expires_etag", {}, "HTTP_IF_NONE_MATCH" => etag <ide> assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"] <del> assert_equal body, last_response.body <add> assert_equal 304, last_response.status <add> assert_equal "", last_response.body <ide> end <ide> <ide> def test_cache_works_with_etags_private <ide> def test_cache_works_with_etags_private <ide> body = last_response.body <ide> etag = last_response.headers["ETag"] <ide> <del> get "/expires/expires_etag", { private: true }, "If-None-Match" => etag <add> get "/expires/expires_etag", { private: true }, "HTTP_IF_NONE_MATCH" => etag <ide> assert_equal "miss", last_response.headers["X-Rack-Cache"] <ide> assert_not_equal body, last_response.body <ide> end <ide> def test_cache_works_with_last_modified <ide> assert_equal "miss, store", last_response.headers["X-Rack-Cache"] <ide> assert_equal "public", last_response.headers["Cache-Control"] <ide> <del> body = last_response.body <ide> last = last_response.headers["Last-Modified"] <ide> <del> get "/expires/expires_last_modified", {}, "If-Modified-Since" => last <add> get "/expires/expires_last_modified", {}, "HTTP_IF_MODIFIED_SINCE" => last <ide> assert_equal "stale, valid, store", last_response.headers["X-Rack-Cache"] <del> assert_equal body, last_response.body <add> assert_equal 304, last_response.status <add> assert_equal "", last_response.body <ide> end <ide> <ide> def test_cache_works_with_last_modified_private <ide> def test_cache_works_with_last_modified_private <ide> body = last_response.body <ide> last = last_response.headers["Last-Modified"] <ide> <del> get "/expires/expires_last_modified", { private: true }, "If-Modified-Since" => last <add> get "/expires/expires_last_modified", { private: true }, "HTTP_IF_MODIFIED_SINCE" => last <ide> assert_equal "miss", last_response.headers["X-Rack-Cache"] <ide> assert_not_equal body, last_response.body <ide> end
1
Java
Java
implement elementat as operator
f0fea5fa67bc9ed770ddfa55845e276d4a766e69
<ide><path>rxjava-core/src/main/java/rx/Observable.java <ide> public final void onNext(T args) { <ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementat">RxJava Wiki: elementAt()</a> <ide> */ <ide> public final Observable<T> elementAt(int index) { <del> return create(new OperatorElementAt<T>(this, index)); <add> return lift(new OperatorElementAt<T>(index)); <ide> } <ide> <ide> /** <ide> public final Observable<T> elementAt(int index) { <ide> * @see <a href="https://github.com/Netflix/RxJava/wiki/Filtering-Observables#wiki-elementatordefault">RxJava Wiki: elementAtOrDefault()</a> <ide> */ <ide> public final Observable<T> elementAtOrDefault(int index, T defaultValue) { <del> return create(new OperatorElementAt<T>(this, index, defaultValue)); <add> return lift(new OperatorElementAt<T>(index, defaultValue)); <ide> } <ide> <ide> /** <ide><path>rxjava-core/src/main/java/rx/operators/OperatorElementAt.java <ide> */ <ide> package rx.operators; <ide> <del>import rx.Observable; <del>import rx.Observable.OnSubscribe; <add>import rx.Observable.Operator; <ide> import rx.Subscriber; <ide> <ide> /** <ide> * Returns the element at a specified index in a sequence. <ide> */ <del>public final class OperatorElementAt<T> implements OnSubscribe<T> { <add>public final class OperatorElementAt<T> implements Operator<T, T> { <ide> <del> private final Observable<? extends T> source; <ide> private final int index; <ide> private final boolean hasDefault; <ide> private final T defaultValue; <ide> <del> public OperatorElementAt(Observable<? extends T> source, int index) { <del> this(source, index, null, false); <add> public OperatorElementAt(int index) { <add> this(index, null, false); <ide> } <ide> <del> public OperatorElementAt(Observable<? extends T> source, int index, T defaultValue) { <del> this(source, index, defaultValue, true); <add> public OperatorElementAt(int index, T defaultValue) { <add> this(index, defaultValue, true); <ide> } <ide> <del> private OperatorElementAt(Observable<? extends T> source, int index, T defaultValue, boolean hasDefault) { <add> private OperatorElementAt(int index, T defaultValue, boolean hasDefault) { <ide> if (index < 0) { <ide> throw new IndexOutOfBoundsException(index + " is out of bounds"); <ide> } <del> this.source = source; <ide> this.index = index; <ide> this.defaultValue = defaultValue; <ide> this.hasDefault = hasDefault; <ide> } <ide> <ide> @Override <del> public void call(final Subscriber<? super T> subscriber) { <del> source.subscribe(new Subscriber<T>(subscriber) { <add> public Subscriber<? super T> call(final Subscriber<? super T> subscriber) { <add> return new Subscriber<T>(subscriber) { <ide> <ide> private int currentIndex = 0; <ide> <ide> public void onCompleted() { <ide> } <ide> } <ide> } <del> }); <add> }; <ide> } <add> <ide> }
2
Javascript
Javascript
allocate iteration structures lazily (pt. 2)
797446a228e34c9d0649518a50887c542f145b4a
<ide><path>packages/ember-metal/lib/meta.js <ide> export class Meta { <ide> while (pointer !== undefined) { <ide> let map = pointer[key]; <ide> if (map) { <del> seen = seen || Object.create(null); <ide> let innerMap = map[subkey]; <ide> if (innerMap) { <ide> for (let innerKey in innerMap) { <add> seen = seen || Object.create(null); <ide> if (!seen[innerKey]) { <ide> seen[innerKey] = true; <ide> calls = calls || []; <ide> function inheritedMap(name, Meta) { <ide> <ide> Meta.prototype[`forEach${capitalized}`] = function(fn) { <ide> let pointer = this; <del> let seen = Object.create(null); <add> let seen; <ide> while (pointer !== undefined) { <ide> let map = pointer[key]; <ide> if (map) { <ide> for (let key in map) { <add> seen = seen || Object.create(null); <ide> if (!seen[key]) { <ide> seen[key] = true; <ide> fn(key, map[key]);
1
PHP
PHP
correct more docs and add an assertion
9da7e9d44664b02f55d2f69e240be23a29c498a1
<ide><path>src/ORM/Table.php <ide> public function rulesChecker() { <ide> } <ide> <ide> /** <del> * Returns rules chaker object after modifying the one that was passed. Subclasses <add> * Returns rules checker object after modifying the one that was passed. Subclasses <ide> * can override this method in order to initialize the rules to be applied to <ide> * entities saved by this table. <ide> * <ide><path>tests/TestCase/ORM/RulesCheckerIntegrationTest.php <ide> public function testsSaveBelongsToWithValidationError() { <ide> $this->assertTrue($entity->author->isNew()); <ide> $this->assertNull($entity->get('author_id')); <ide> $this->assertNotEmpty($entity->author->errors('name')); <add> $this->assertEquals(['This is an error'], $entity->author->errors('name')); <ide> } <ide> <ide> /**
2
Python
Python
remove detection generator
a4b2ed32c01c9666456d739763e6e1c2aca49cf3
<ide><path>official/vision/beta/projects/yolo/modeling/layers/detection_generator.py <del>"""Contains common building blocks for yolo neural networks.""" <del>import tensorflow as tf <del>import tensorflow.keras as ks <del>import tensorflow.keras.backend as K <del> <del># from official.vision.beta.projects.yolo.ops import loss_utils <del>from official.vision.beta.projects.yolo.ops import box_ops <del># from official.vision.beta.projects.yolo.losses import yolo_loss <del># from official.vision.beta.projects.yolo.ops import nms_ops <del> <del> <del>@ks.utils.register_keras_serializable(package='yolo') <del>class YoloLayer(ks.Model): <del> <del> def __init__(self, <del> masks, <del> anchors, <del> classes, <del> iou_thresh=0.0, <del> ignore_thresh=0.7, <del> truth_thresh=1.0, <del> nms_thresh=0.6, <del> max_delta=10.0, <del> loss_type='ciou', <del> use_tie_breaker=True, <del> iou_normalizer=1.0, <del> cls_normalizer=1.0, <del> obj_normalizer=1.0, <del> use_scaled_loss=False, <del> darknet = None, <del> pre_nms_points=5000, <del> label_smoothing=0.0, <del> max_boxes=200, <del> new_cords=False, <del> path_scale=None, <del> scale_xy=None, <del> nms_type='greedy', <del> objectness_smooth=False, <del> **kwargs): <del> """ <del> parameters for the loss functions used at each detection head output <del> <del> Args: <del> classes: `int` for the number of classes <del> mask: `List[int]` for the output level that this specific model output <del> level <del> anchors: `List[List[int]]` for the anchor boxes that are used in the model <del> at all levels <del> scale_anchors: `int` for how much to scale this level to get the orginal <del> input shape <del> ignore_thresh: `float` for the IOU value over which the loss is not <del> propagated, and a detection is assumed to have been made <del> truth_thresh: `float` for the IOU value over which the loss is propagated <del> despite a detection being made <del> loss_type: `str` for the typeof iou loss to use with in {ciou, diou, <del> giou, iou} <del> iou_normalizer: `float` for how much to scale the loss on the IOU or the <del> boxes <del> cls_normalizer: `float` for how much to scale the loss on the classes <del> obj_normalizer: `float` for how much to scale loss on the detection map <del> objectness_smooth: `float` for how much to smooth the loss on the <del> detection map <del> use_scaled_loss: `bool` for whether to use the scaled loss <del> or the traditional loss <del> label_smoothing: `float` for how much to smooth the loss on the classes <del> new_cords: `bool` for which scaling type to use <del> scale_xy: dictionary `float` values inidcating how far each pixel can see <del> outside of its containment of 1.0. a value of 1.2 indicates there is a <del> 20% extended radius around each pixel that this specific pixel can <del> predict values for a center at. the center can range from 0 - value/2 <del> to 1 + value/2, this value is set in the yolo filter, and resused here. <del> there should be one value for scale_xy for each level from min_level to <del> max_level <del> max_delta: gradient clipping to apply to the box loss <del> nms_type: "greedy", <del> nms_thresh: 0.6, <del> iou_thresh: 0.213, <del> name=None, <del> <del> <del> Return: <del> loss: `float` for the actual loss <del> box_loss: `float` loss on the boxes used for metrics <del> conf_loss: `float` loss on the confidence used for metrics <del> class_loss: `float` loss on the classes used for metrics <del> avg_iou: `float` metric for the average iou between predictions <del> and ground truth <del> avg_obj: `float` metric for the average confidence of the model <del> for predictions <del> recall50: `float` metric for how accurate the model is <del> precision50: `float` metric for how precise the model is <del> """ <del> super().__init__(**kwargs) <del> self._masks = masks <del> self._anchors = anchors <del> self._thresh = iou_thresh <del> self._ignore_thresh = ignore_thresh <del> self._truth_thresh = truth_thresh <del> self._iou_normalizer = iou_normalizer <del> self._cls_normalizer = cls_normalizer <del> self._obj_normalizer = obj_normalizer <del> self._objectness_smooth = objectness_smooth <del> self._nms_thresh = nms_thresh <del> self._max_boxes = max_boxes <del> self._max_delta = max_delta <del> self._classes = classes <del> self._loss_type = loss_type <del> self._use_tie_breaker = use_tie_breaker <del> <del> self._use_scaled_loss = use_scaled_loss <del> self._darknet = darknet <del> <del> self._pre_nms_points = pre_nms_points <del> self._label_smoothing = label_smoothing <del> self._keys = list(masks.keys()) <del> self._len_keys = len(self._keys) <del> self._new_cords = new_cords <del> self._path_scale = path_scale or { <del> key: 2**int(key) for key, _ in masks.items() <del> } <del> <del> self._nms_types = { <del> 'greedy': 1, <del> 'iou': 2, <del> 'giou': 3, <del> 'ciou': 4, <del> 'diou': 5, <del> 'class_independent': 6, <del> 'weighted_diou': 7 <del> } <del> <del> self._nms_type = self._nms_types[nms_type] <del> <del> if self._nms_type >= 2 and self._nms_type <= 5: <del> self._nms = nms_ops.TiledNMS(iou_type=nms_type) <del> <del> self._scale_xy = scale_xy or {key: 1.0 for key, _ in masks.items()} <del> <del> self._generator = {} <del> self._len_mask = {} <del> for key in self._keys: <del> anchors = [self._anchors[mask] for mask in self._masks[key]] <del> self._generator[key] = self.get_generators(anchors, self._path_scale[key], <del> key) <del> self._len_mask[key] = len(self._masks[key]) <del> return <del> <del> def get_generators(self, anchors, path_scale, path_key): <del> # anchor_generator = loss_utils.GridGenerator( <del> # anchors, scale_anchors=path_scale) <del> # return anchor_generator <del> return None <del> <del> def rm_nan_inf(self, x, val=0.0): <del> x = tf.where(tf.math.is_nan(x), tf.cast(val, dtype=x.dtype), x) <del> x = tf.where(tf.math.is_inf(x), tf.cast(val, dtype=x.dtype), x) <del> return x <del> <del> def parse_prediction_path(self, key, inputs): <del> shape_ = tf.shape(inputs) <del> shape = inputs.get_shape().as_list() <del> batchsize, height, width = shape_[0], shape[1], shape[2] <del> <del> generator = self._generator[key] <del> len_mask = self._len_mask[key] <del> scale_xy = self._scale_xy[key] <del> <del> # reshape the yolo output to (batchsize, <del> # width, <del> # height, <del> # number_anchors, <del> # remaining_points) <del> <del> data = tf.reshape(inputs, [-1, height, width, len_mask, self._classes + 5]) <del> <del> # use the grid generator to get the formatted anchor boxes and grid points <del> # in shape [1, height, width, 2] <del> centers, anchors = generator(height, width, batchsize, dtype=data.dtype) <del> <del> # # tempcode <del> # centers /= tf.cast([width, height], centers.dtype) <del> # anchors /= tf.cast([width, height], anchors.dtype) <del> <del> # split the yolo detections into boxes, object score map, classes <del> boxes, obns_scores, class_scores = tf.split( <del> data, [4, 1, self._classes], axis=-1) <del> <del> # determine the number of classes <del> classes = class_scores.get_shape().as_list()[ <del> -1] #tf.shape(class_scores)[-1] <del> <del> # # configurable to use the new coordinates in scaled Yolo v4 or not <del> # if not self._new_cords[key]: <del> # # coordinates from scaled yolov4 <del> # _, _, boxes = yolo_loss.get_predicted_box( <del> # tf.cast(height, data.dtype), tf.cast(width, data.dtype), boxes, <del> # anchors, centers, scale_xy) <del> # else: <del> # # coordinates from regular yolov3 - v4 <del> # _, _, boxes = yolo_loss.get_predicted_box_newcords( <del> # tf.cast(height, data.dtype), tf.cast(width, data.dtype), boxes, <del> # anchors, centers, scale_xy) <del> boxes = None <del> <del> # convert boxes from yolo(x, y, w. h) to tensorflow(ymin, xmin, ymax, xmax) <del> boxes = box_ops.xcycwh_to_yxyx(boxes) <del> <del> # activate and detection map <del> obns_scores = tf.math.sigmoid(obns_scores) <del> <del> # threshold the detection map <del> obns_mask = tf.cast(obns_scores > self._thresh, obns_scores.dtype) <del> <del> # convert detection map to class detection probabailities <del> class_scores = tf.math.sigmoid(class_scores) * obns_mask * obns_scores <del> class_scores *= tf.cast(class_scores > self._thresh, class_scores.dtype) <del> <del> fill = height * width * len_mask <del> # platten predictions to [batchsize, N, -1] for non max supression <del> boxes = tf.reshape(boxes, [-1, fill, 4]) <del> class_scores = tf.reshape(class_scores, [-1, fill, classes]) <del> obns_scores = tf.reshape(obns_scores, [-1, fill]) <del> <del> return obns_scores, boxes, class_scores <del> <del> def call(self, inputs): <del> boxes = [] <del> class_scores = [] <del> object_scores = [] <del> levels = list(inputs.keys()) <del> min_level = int(min(levels)) <del> max_level = int(max(levels)) <del> <del> # aggregare boxes over each scale <del> for i in range(min_level, max_level + 1): <del> key = str(i) <del> object_scores_, boxes_, class_scores_ = self.parse_prediction_path( <del> key, inputs[key]) <del> boxes.append(boxes_) <del> class_scores.append(class_scores_) <del> object_scores.append(object_scores_) <del> <del> # colate all predicitons <del> boxes = tf.concat(boxes, axis=1) <del> object_scores = K.concatenate(object_scores, axis=1) <del> class_scores = K.concatenate(class_scores, axis=1) <del> <del> # # apply nms <del> # if self._nms_type == 7: <del> # boxes, class_scores, object_scores = nms_ops.non_max_suppression2( <del> # boxes, <del> # class_scores, <del> # object_scores, <del> # self._max_boxes, <del> # pre_nms_thresh = self._thresh, <del> # nms_thresh = self._nms_thresh, <del> # prenms_top_k=self._pre_nms_points) <del> # elif self._nms_type == 6: <del> # boxes, class_scores, object_scores = nms_ops.nms( <del> # boxes, <del> # class_scores, <del> # object_scores, <del> # self._max_boxes, <del> # self._thresh, <del> # self._nms_thresh, <del> # prenms_top_k=self._pre_nms_points) <del> # elif self._nms_type == 1: <del> # # greedy NMS <del> # boxes = tf.cast(boxes, dtype=tf.float32) <del> # class_scores = tf.cast(class_scores, dtype=tf.float32) <del> # nms_items = tf.image.combined_non_max_suppression( <del> # tf.expand_dims(boxes, axis=-2), <del> # class_scores, <del> # self._pre_nms_points, <del> # self._max_boxes, <del> # iou_threshold=self._nms_thresh, <del> # score_threshold=self._thresh) <del> # # cast the boxes and predicitons abck to original datatype <del> # boxes = tf.cast(nms_items.nmsed_boxes, object_scores.dtype) <del> # class_scores = tf.cast(nms_items.nmsed_classes, object_scores.dtype) <del> # object_scores = tf.cast(nms_items.nmsed_scores, object_scores.dtype) <del> # <del> # else: <del> # boxes = tf.cast(boxes, dtype=tf.float32) <del> # class_scores = tf.cast(class_scores, dtype=tf.float32) <del> # boxes, confidence, classes, valid = self._nms.complete_nms( <del> # tf.expand_dims(boxes, axis=-2), <del> # class_scores, <del> # pre_nms_top_k=self._pre_nms_points, <del> # max_num_detections=self._max_boxes, <del> # nms_iou_threshold=self._nms_thresh, <del> # pre_nms_score_threshold=self._thresh) <del> # boxes = tf.cast(boxes, object_scores.dtype) <del> # class_scores = tf.cast(classes, object_scores.dtype) <del> # object_scores = tf.cast(confidence, object_scores.dtype) <del> <del> # compute the number of valid detections <del> num_detections = tf.math.reduce_sum(tf.math.ceil(object_scores), axis=-1) <del> <del> # format and return <del> return { <del> 'bbox': boxes, <del> 'classes': class_scores, <del> 'confidence': object_scores, <del> 'num_detections': num_detections, <del> } <del> <del> @property <del> def losses(self): <del> """ Generates a dictionary of losses to apply to each path <del> <del> Done in the detection generator because all parameters are the same <del> across both loss and detection generator <del> """ <del> # loss_dict = {} <del> # for key in self._keys: <del> # loss_dict[key] = yolo_loss.Yolo_Loss( <del> # classes=self._classes, <del> # anchors=self._anchors, <del> # darknet=self._darknet, <del> # truth_thresh=self._truth_thresh[key], <del> # ignore_thresh=self._ignore_thresh[key], <del> # loss_type=self._loss_type[key], <del> # iou_normalizer=self._iou_normalizer[key], <del> # cls_normalizer=self._cls_normalizer[key], <del> # obj_normalizer=self._obj_normalizer[key], <del> # new_cords=self._new_cords[key], <del> # objectness_smooth=self._objectness_smooth[key], <del> # use_scaled_loss=self._use_scaled_loss, <del> # label_smoothing=self._label_smoothing, <del> # mask=self._masks[key], <del> # max_delta=self._max_delta[key], <del> # scale_anchors=self._path_scale[key], <del> # scale_x_y=self._scale_xy[key]) <del> # return loss_dict <del> return None <del> <del> def get_config(self): <del> return { <del> 'masks': dict(self._masks), <del> 'anchors': [list(a) for a in self._anchors], <del> 'thresh': self._thresh, <del> 'max_boxes': self._max_boxes, <del> } <ide><path>official/vision/beta/projects/yolo/modeling/yolo_model.py <del>from official.core import registry <add>from official.core import registry # pylint: disable=unused-import <ide> import tensorflow as tf <ide> import tensorflow.keras as ks <ide> from typing import * <ide> <del>from yolo.configs import yolo <del> <del>from official.vision.beta.modeling.backbones import factory <del>from yolo.modeling.backbones.darknet import build_darknet <del>from yolo.modeling.backbones.darknet import Darknet <del>from yolo.modeling.decoders.yolo_decoder import YoloDecoder <del>from yolo.modeling.heads.yolo_head import YoloHead <del>from yolo.modeling.layers.detection_generator import YoloLayer <add>from official.vision.beta.projects.yolo.modeling.backbones.darknet import \ <add> Darknet <add>from official.vision.beta.projects.yolo.modeling.decoders.yolo_decoder import \ <add> YoloDecoder <add>from official.vision.beta.projects.yolo.modeling.heads.yolo_head import YoloHead <ide> <ide> # static base Yolo Models that do not require configuration <ide> # similar to a backbone model id. <ide> # the structure is as follows. model version, {v3, v4, v#, ... etc} <ide> # the model config type {regular, tiny, small, large, ... etc} <ide> YOLO_MODELS = { <del> "v4": <del> dict( <del> regular=dict( <del> embed_spp=False, <del> use_fpn=True, <del> max_level_process_len=None, <del> path_process_len=6), <del> tiny=dict( <del> embed_spp=False, <del> use_fpn=False, <del> max_level_process_len=2, <del> path_process_len=1), <del> csp=dict( <del> embed_spp=False, <del> use_fpn=True, <del> max_level_process_len=None, <del> csp_stack=5, <del> fpn_depth=5, <del> path_process_len=6), <del> csp_large=dict( <del> embed_spp=False, <del> use_fpn=True, <del> max_level_process_len=None, <del> csp_stack=7, <del> fpn_depth=7, <del> path_process_len=8, <del> fpn_filter_scale=2), <del> ), <del> "v3": <del> dict( <del> regular=dict( <del> embed_spp=False, <del> use_fpn=False, <del> max_level_process_len=None, <del> path_process_len=6), <del> tiny=dict( <del> embed_spp=False, <del> use_fpn=False, <del> max_level_process_len=2, <del> path_process_len=1), <del> spp=dict( <del> embed_spp=True, <del> use_fpn=False, <del> max_level_process_len=2, <del> path_process_len=1), <del> ), <add> "v4" : dict( <add> regular = dict( <add> embed_spp=False, <add> use_fpn=True, <add> max_level_process_len=None, <add> path_process_len=6), <add> tiny = dict( <add> embed_spp=False, <add> use_fpn=False, <add> max_level_process_len=2, <add> path_process_len=1), <add> csp = dict( <add> embed_spp=False, <add> use_fpn=True, <add> max_level_process_len=None, <add> csp_stack=5, <add> fpn_depth=5, <add> path_process_len=6), <add> csp_large=dict( <add> embed_spp=False, <add> use_fpn=True, <add> max_level_process_len=None, <add> csp_stack=7, <add> fpn_depth=7, <add> path_process_len=8, <add> fpn_filter_scale=2), <add> ), <add> "v3" : dict( <add> regular = dict( <add> embed_spp=False, <add> use_fpn=False, <add> max_level_process_len=None, <add> path_process_len=6), <add> tiny = dict( <add> embed_spp=False, <add> use_fpn=False, <add> max_level_process_len=2, <add> path_process_len=1), <add> spp = dict( <add> embed_spp=True, <add> use_fpn=False, <add> max_level_process_len=2, <add> path_process_len=1), <add> ), <ide> } <ide> <ide> <ide> def get_config(self): <ide> <ide> @classmethod <ide> def from_config(cls, config): <del> return cls(**config) <ide>\ No newline at end of file <add> return cls(**config)
2
Go
Go
fix flaky testeventscontainerfilterbeforecreate
e372883fcd38aab4d18c11be41e38574250c4c25
<ide><path>integration-cli/docker_cli_events_unix_test.go <ide> package main <ide> <ide> import ( <ide> "bufio" <add> "bytes" <ide> "fmt" <ide> "io/ioutil" <ide> "os" <ide> func (s *DockerSuite) TestEventsContainerFilterByName(c *check.C) { <ide> // #18453 <ide> func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) { <ide> testRequires(c, DaemonIsLinux) <del> var ( <del> out string <del> ch chan struct{} <del> ) <del> ch = make(chan struct{}) <del> <del> // calculate the time it takes to create and start a container and sleep 2 seconds <del> // this is to make sure the docker event will recevie the event of container <del> since := daemonTime(c) <del> id, _ := dockerCmd(c, "run", "-d", "busybox", "top") <add> buf := &bytes.Buffer{} <add> cmd := exec.Command(dockerBinary, "events", "-f", "container=foo", "--since=0") <add> cmd.Stdout = buf <add> c.Assert(cmd.Start(), check.IsNil) <add> defer cmd.Wait() <add> defer cmd.Process.Kill() <add> <add> // Sleep for a second to make sure we are testing the case where events are listened before container starts. <add> time.Sleep(time.Second) <add> id, _ := dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top") <ide> cID := strings.TrimSpace(id) <del> waitRun(cID) <del> time.Sleep(2 * time.Second) <del> duration := daemonTime(c).Sub(since) <del> <del> go func() { <del> // start events and wait for future events to <del> // make sure the new container shows up even when <del> // the event stream was created before the container. <del> t := daemonTime(c).Add(2 * duration) <del> out, _ = dockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", parseEventTime(t)) <del> close(ch) <del> }() <del> // Sleep 2 second to wait docker event to start <del> time.Sleep(2 * time.Second) <del> id, _ = dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top") <del> cID = strings.TrimSpace(id) <del> waitRun(cID) <del> <-ch <del> c.Assert(out, checker.Contains, cID, check.Commentf("Missing event of container (foo)")) <add> for i := 0; ; i++ { <add> out := buf.String() <add> if strings.Contains(out, cID) { <add> break <add> } <add> if i > 30 { <add> c.Fatalf("Missing event of container (foo, %v), got %q", cID, out) <add> } <add> time.Sleep(500 * time.Millisecond) <add> } <ide> } <ide> <ide> func (s *DockerSuite) TestVolumeEvents(c *check.C) {
1
Javascript
Javascript
fix a bug with zero-duration transitions
bbcf25ef7d188d8e1fcf56ad4e6becffa0756398
<ide><path>d3.js <del>d3 = {version: "0.26.0"}; // semver <add>d3 = {version: "0.26.1"}; // semver <ide> if (!Date.now) Date.now = function() { <ide> return +new Date(); <ide> }; <ide> function d3_transition(groups) { <ide> te, // ease(t) <ide> tk, // tween key <ide> ik = interpolators[k]; <add> <add> // Check if the (un-eased) time is outside the range [0,1]. <ide> if (t < 1) { <ide> clear = false; <ide> if (t < 0) return; <del> if (stage[k]) { <del> if (tx.active != transitionId) { <del> stage[k] = 2; <del> return; <del> } <del> } else if (!tx || tx.active > transitionId) { <add> } else { <add> t = 1; <add> } <add> <add> // Determine the stage of this transition. <add> // 0 - Not yet started. <add> // 1 - In progress. <add> // 2 - Ended. <add> if (stage[k]) { <add> if (tx.active != transitionId) { <ide> stage[k] = 2; <ide> return; <del> } else { <del> stage[k] = 1; <del> event.start.dispatch.apply(this, arguments); <del> ik = interpolators[k] = {}; <del> tx.active = transitionId; <del> for (tk in tweens) ik[tk] = tweens[tk].apply(this, arguments); <ide> } <del> te = ease(t); <del> for (tk in tweens) ik[tk].call(this, te); <add> } else if (!tx || tx.active > transitionId) { <add> stage[k] = 2; <add> return; <ide> } else { <add> stage[k] = 1; <add> event.start.dispatch.apply(this, arguments); <add> ik = interpolators[k] = {}; <add> tx.active = transitionId; <add> for (tk in tweens) ik[tk] = tweens[tk].apply(this, arguments); <add> } <add> <add> // Apply the interpolators! <add> te = ease(t); <add> for (tk in tweens) ik[tk].call(this, te); <add> <add> // Handle ending transitions. <add> if (t == 1) { <ide> stage[k] = 2; <ide> if (tx.active == transitionId) { <ide> var owner = tx.owner; <del> for (tk in tweens) ik[tk].call(this, 1); <ide> if (owner == transitionId) { <ide> delete this.__transition__; <ide> if (remove) this.parentNode.removeChild(this); <ide><path>d3.layout.js <ide> d3["layout"]["chord"] = function() { <ide> x += padding; <ide> } <ide> <del> // Generate chords for each subgroup-subgroup link. <add> // Generate chords for each (non-empty) subgroup-subgroup link. <ide> i = -1; while (++i < n) { <ide> j = i - 1; while (++j < n) { <del> chords.push({ <del> "source": subgroups[i + "-" + j], <del> "target": subgroups[j + "-" + i] <del> }) <add> var source = subgroups[i + "-" + j], <add> target = subgroups[j + "-" + i]; <add> if (source["value"] || target["value"]) { <add> chords.push({ <add> "source": source, <add> "target": target <add> }) <add> } <ide> } <ide> } <ide> <ide><path>d3.layout.min.js <ide> (function(){d3.layout={}; <del>d3.layout.chord=function(){function u(){var a={},h=[],v=d3.range(f),r=[],k,d,s,c,e;g=[];i=[];k=0;for(c=-1;++c<f;){d=0;for(e=-1;++e<f;)d+=j[c][e];h.push(d);r.push(d3.range(f));k+=d}l&&v.sort(function(t,m){return l(h[t],h[m])});n&&r.forEach(function(t,m){t.sort(function(z,A){return n(j[m][z],j[m][A])})});k=(2*Math.PI-o*f)/k;d=0;for(c=-1;++c<f;){s=d;for(e=-1;++e<f;){var p=v[c],w=r[p][e],x=j[p][w];a[c+"-"+e]={index:p,subindex:w,startAngle:d,endAngle:d+=x*k,value:x}}i.push({index:p,startAngle:s,endAngle:d, <del>value:(d-s)/k});d+=o}for(c=-1;++c<f;)for(e=c-1;++e<f;)g.push({source:a[c+"-"+e],target:a[e+"-"+c]});q&&y()}function y(){g.sort(function(a,h){a=Math.min(a.source.value,a.target.value);h=Math.min(h.source.value,h.target.value);return q(a,h)})}var b={},g,i,j,f,o=0,l,n,q;b.matrix=function(a){if(!arguments.length)return j;f=(j=a)&&j.length;g=i=null;return b};b.padding=function(a){if(!arguments.length)return o;o=a;g=i=null;return b};b.sortGroups=function(a){if(!arguments.length)return l;l=a;g=i=null;return b}; <del>b.sortSubgroups=function(a){if(!arguments.length)return n;n=a;g=null;return b};b.sortChords=function(a){if(!arguments.length)return q;q=a;g&&y();return b};b.chords=function(){g||u();return g};b.groups=function(){i||u();return i};return b};})() <add>d3.layout.chord=function(){function v(){var a={},h=[],m=d3.range(f),k=[],l,d,t,c,e;g=[];i=[];l=0;for(c=-1;++c<f;){d=0;for(e=-1;++e<f;)d+=j[c][e];h.push(d);k.push(d3.range(f));l+=d}n&&m.sort(function(u,o){return n(h[u],h[o])});p&&k.forEach(function(u,o){u.sort(function(z,A){return p(j[o][z],j[o][A])})});l=(2*Math.PI-q*f)/l;d=0;for(c=-1;++c<f;){t=d;for(e=-1;++e<f;){var r=m[c],w=k[r][e],x=j[r][w];a[c+"-"+e]={index:r,subindex:w,startAngle:d,endAngle:d+=x*l,value:x}}i.push({index:r,startAngle:t,endAngle:d, <add>value:(d-t)/l});d+=q}for(c=-1;++c<f;)for(e=c-1;++e<f;){m=a[c+"-"+e];k=a[e+"-"+c];if(m.value||k.value)g.push({source:m,target:k})}s&&y()}function y(){g.sort(function(a,h){a=Math.min(a.source.value,a.target.value);h=Math.min(h.source.value,h.target.value);return s(a,h)})}var b={},g,i,j,f,q=0,n,p,s;b.matrix=function(a){if(!arguments.length)return j;f=(j=a)&&j.length;g=i=null;return b};b.padding=function(a){if(!arguments.length)return q;q=a;g=i=null;return b};b.sortGroups=function(a){if(!arguments.length)return n; <add>n=a;g=i=null;return b};b.sortSubgroups=function(a){if(!arguments.length)return p;p=a;g=null;return b};b.sortChords=function(a){if(!arguments.length)return s;s=a;g&&y();return b};b.chords=function(){g||v();return g};b.groups=function(){i||v();return i};return b};})() <ide><path>d3.min.js <del>(function(){var o=null;d3={version:"0.26.0"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function w(a){return Array.prototype.slice.call(a)}function x(a){return typeof a=="function"?a:function(){return a}}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.merge=function(a){return Array.prototype.concat.apply([],a)}; <del>d3.split=function(a,b){var e=[],f=[],c,d=-1,h=a.length;if(arguments.length<2)b=aa;for(;++d<h;)if(b.call(f,c=a[d],d)){e.push(f);f=[]}else f.push(c);e.push(f);return e};function aa(a){return a==o}function E(a,b){b=w(arguments);b[0]=this;a.apply(this,b);return this}d3.range=function(a,b,e){if(arguments.length==1){b=a;a=0}if(e==o)e=1;if((b-a)/e==Infinity)throw Error("infinite range");var f=[],c=-1,d;if(e<0)for(;(d=a+e*++c)>b;)f.push(d);else for(;(d=a+e*++c)<b;)f.push(d);return f}; <add>(function(){var o=null;d3={version:"0.26.1"};if(!Date.now)Date.now=function(){return+new Date};if(!Object.create)Object.create=function(a){function b(){}b.prototype=a;return new b};function x(a){return Array.prototype.slice.call(a)}function y(a){return typeof a=="function"?a:function(){return a}}d3.ascending=function(a,b){return a<b?-1:a>b?1:0};d3.descending=function(a,b){return b<a?-1:b>a?1:0};d3.merge=function(a){return Array.prototype.concat.apply([],a)}; <add>d3.split=function(a,b){var e=[],f=[],c,d=-1,h=a.length;if(arguments.length<2)b=aa;for(;++d<h;)if(b.call(f,c=a[d],d)){e.push(f);f=[]}else f.push(c);e.push(f);return e};function aa(a){return a==o}function E(a,b){b=x(arguments);b[0]=this;a.apply(this,b);return this}d3.range=function(a,b,e){if(arguments.length==1){b=a;a=0}if(e==o)e=1;if((b-a)/e==Infinity)throw Error("infinite range");var f=[],c=-1,d;if(e<0)for(;(d=a+e*++c)>b;)f.push(d);else for(;(d=a+e*++c)<b;)f.push(d);return f}; <ide> d3.text=function(a,b,e){var f=new XMLHttpRequest;if(arguments.length==3)f.overrideMimeType(b);else e=b;f.open("GET",a,true);f.onreadystatechange=function(){if(f.readyState==4)e(f.status<300&&f.responseText?f.responseText:o)};f.send(o)};d3.json=function(a,b){return d3.text(a,"application/json",function(e){b(e&&JSON.parse(e))})}; <ide> d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}};d3.dispatch=function(){for(var a={},b,e=0,f=arguments.length;e<f;e++){b=arguments[e];a[b]=ba(b)}return a}; <ide> function ba(){var a={},b=[];a.add=function(e){for(var f=0;f<b.length;f++)if(b[f].i==e)return a;b.push({i:e,on:true});return a};a.remove=function(e){for(var f=0;f<b.length;f++){var c=b[f];if(c.i==e){c.on=false;b=b.slice(0,f).concat(b.slice(f+1));break}}return a};a.dispatch=function(){for(var e=b,f=0,c=e.length;f<c;f++){var d=e[f];d.on&&d.i.apply(this,arguments)}};return a} <ide> lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsla <ide> moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57", <ide> seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"},N;for(N in G)G[N]=I(G[N],J,ra);d3.hsl=function(a,b,e){return arguments.length==1?I(""+a,ta,M):M(+a,+b,+e)}; <ide> function M(a,b,e){return{h:a,s:b,l:e,toString:ua}}function ua(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"}function ra(a,b,e){function f(h){if(h>360)h-=360;else if(h<0)h+=360;if(h<60)return c+(d-c)*h/60;if(h<180)return d;if(h<240)return c+(d-c)*(240-h)/60;return c}var c,d;a%=360;if(a<0)a+=360;b=b<0?0:b>1?1:b;e=e<0?0:e>1?1:e;d=e<=0.5?e*(1+b):e+b-e*b;c=2*e-d;return J(Math.round(f(a+120)*255),Math.round(f(a)*255),Math.round(f(a-120)*255))}var P=O([[document]]);P[0].parentNode=document.documentElement; <del>d3.select=function(a){return typeof a=="string"?P.select(a):O([[a]])};d3.selectAll=function(a){return typeof a=="string"?P.selectAll(a):O([w(a)])}; <add>d3.select=function(a){return typeof a=="string"?P.select(a):O([[a]])};d3.selectAll=function(a){return typeof a=="string"?P.selectAll(a):O([x(a)])}; <ide> function O(a){function b(c){for(var d=[],h,g,i,j,m=0,p=a.length;m<p;m++){i=a[m];d.push(h=[]);h.parentNode=i.parentNode;h.parentData=i.parentData;for(var r=0,k=i.length;r<k;r++)if(j=i[r]){h.push(g=c(j));if(g&&"__data__"in j)g.__data__=j.__data__}else h.push(o)}return O(d)}function e(c){for(var d=[],h,g,i,j=0,m=a.length;j<m;j++){g=a[j];for(var p=0,r=g.length;p<r;p++)if(i=g[p]){d.push(h=c(i));h.parentNode=i;h.parentData=i.__data__}}return O(d)}function f(c){for(var d=0,h=a.length;d<h;d++)for(var g=a[d], <del>i=0,j=g.length;i<j;i++){var m=g[i];if(m)return c.call(m,m.__data__,i)}return o}a.select=function(c){return b(function(d){return d.querySelector(c)})};a.selectAll=function(c){return e(function(d){return w(d.querySelectorAll(c))})};a.filter=function(c){for(var d=[],h,g,i,j=0,m=a.length;j<m;j++){g=a[j];d.push(h=[]);h.parentNode=g.parentNode;h.parentData=g.parentData;for(var p=0,r=g.length;p<r;p++)if((i=g[p])&&c.call(i,i.__data__,p))h.push(i)}return O(d)};a.data=function(c,d){function h(k,n){function q(Ea){return k.parentNode.appendChild(Ea)} <del>var l=0,s=k.length,t=n.length,u=Math.min(s,t),B=Math.max(s,t),y=[],z=[],v=[],A,C;if(d){u={};B=[];var D;C=n.length;for(l=0;l<s;l++){D=d.nodeKey(A=k[l]);if(D in u)v[C++]=k[l];else{u[D]=A;B.push(D)}}for(l=0;l<t;l++){if(A=u[D=d.dataKey(C=n[l])]){A.__data__=C;y[l]=A;z[l]=v[l]=o}else{z[l]={appendChild:q,__data__:C};y[l]=v[l]=o}delete u[D]}for(l=0;l<s;l++)if(B[l]in u)v[l]=k[l]}else{for(;l<u;l++){A=k[l];C=n[l];if(A){A.__data__=C;y[l]=A;z[l]=v[l]=o}else{z[l]={appendChild:q,__data__:C};y[l]=v[l]=o}}for(;l< <del>t;l++){z[l]={appendChild:q,__data__:n[l]};y[l]=v[l]=o}for(;l<B;l++){v[l]=k[l];z[l]=y[l]=o}}z.parentNode=y.parentNode=v.parentNode=k.parentNode;z.parentData=y.parentData=v.parentData=k.parentData;m.push(z);p.push(y);r.push(v)}var g=-1,i=a.length,j,m=[],p=[],r=[];if(typeof d=="string")d=va(d);if(typeof c=="function")for(;++g<i;)h(j=a[g],c.call(j,j.parentData,g));else for(;++g<i;)h(j=a[g],c);g=O(p);g.enter=function(k){return O(m).append(k)};g.exit=function(){return O(r)};return g};a.each=function(c){for(var d= <add>i=0,j=g.length;i<j;i++){var m=g[i];if(m)return c.call(m,m.__data__,i)}return o}a.select=function(c){return b(function(d){return d.querySelector(c)})};a.selectAll=function(c){return e(function(d){return x(d.querySelectorAll(c))})};a.filter=function(c){for(var d=[],h,g,i,j=0,m=a.length;j<m;j++){g=a[j];d.push(h=[]);h.parentNode=g.parentNode;h.parentData=g.parentData;for(var p=0,r=g.length;p<r;p++)if((i=g[p])&&c.call(i,i.__data__,p))h.push(i)}return O(d)};a.data=function(c,d){function h(k,n){function q(Ea){return k.parentNode.appendChild(Ea)} <add>var l=0,t=k.length,u=n.length,s=Math.min(t,u),v=Math.max(t,u),z=[],A=[],w=[],B,C;if(d){s={};v=[];var D;C=n.length;for(l=0;l<t;l++){D=d.nodeKey(B=k[l]);if(D in s)w[C++]=k[l];else{s[D]=B;v.push(D)}}for(l=0;l<u;l++){if(B=s[D=d.dataKey(C=n[l])]){B.__data__=C;z[l]=B;A[l]=w[l]=o}else{A[l]={appendChild:q,__data__:C};z[l]=w[l]=o}delete s[D]}for(l=0;l<t;l++)if(v[l]in s)w[l]=k[l]}else{for(;l<s;l++){B=k[l];C=n[l];if(B){B.__data__=C;z[l]=B;A[l]=w[l]=o}else{A[l]={appendChild:q,__data__:C};z[l]=w[l]=o}}for(;l< <add>u;l++){A[l]={appendChild:q,__data__:n[l]};z[l]=w[l]=o}for(;l<v;l++){w[l]=k[l];A[l]=z[l]=o}}A.parentNode=z.parentNode=w.parentNode=k.parentNode;A.parentData=z.parentData=w.parentData=k.parentData;m.push(A);p.push(z);r.push(w)}var g=-1,i=a.length,j,m=[],p=[],r=[];if(typeof d=="string")d=va(d);if(typeof c=="function")for(;++g<i;)h(j=a[g],c.call(j,j.parentData,g));else for(;++g<i;)h(j=a[g],c);g=O(p);g.enter=function(k){return O(m).append(k)};g.exit=function(){return O(r)};return g};a.each=function(c){for(var d= <ide> 0,h=a.length;d<h;d++)for(var g=a[d],i=0,j=g.length;i<j;i++){var m=g[i];m&&c.call(m,m.__data__,i)}return a};a.node=function(){return f(function(){return this})};a.attr=function(c,d){function h(){this.removeAttribute(c)}function g(){this.removeAttributeNS(c.space,c.local)}function i(){this.setAttribute(c,d)}function j(){this.setAttributeNS(c.space,c.local,d)}function m(){var r=d.apply(this,arguments);r==o?this.removeAttribute(c):this.setAttribute(c,r)}function p(){var r=d.apply(this,arguments);r==o? <ide> this.removeAttributeNS(c.space,c.local):this.setAttributeNS(c.space,c.local,r)}c=d3.ns.qualify(c);if(arguments.length<2)return f(c.local?function(){return this.getAttributeNS(c.space,c.local)}:function(){return this.getAttribute(c)});return a.each(d==o?c.local?g:h:typeof d=="function"?c.local?p:m:c.local?j:i)};a.style=function(c,d,h){function g(){this.style.removeProperty(c)}function i(){this.style.setProperty(c,d,h)}function j(){var m=d.apply(this,arguments);m==o?this.style.removeProperty(c):this.style.setProperty(c, <ide> m,h)}if(arguments.length<3)h=o;if(arguments.length<2)return f(function(){return window.getComputedStyle(this,o).getPropertyValue(c)});return a.each(d==o?g:typeof d=="function"?j:i)};a.property=function(c,d){function h(){delete this[c]}function g(){this[c]=d}function i(){var j=d.apply(this,arguments);if(j==o)delete this[c];else this[c]=j}c=d3.ns.qualify(c);if(arguments.length<2)return f(function(){return this[c]});return a.each(d==o?h:typeof d=="function"?i:g)};a.text=function(c){function d(){this.appendChild(document.createTextNode(c))} <ide> function h(){var g=c.apply(this,arguments);g!=o&&this.appendChild(document.createTextNode(g))}if(arguments.length<1)return f(function(){return this.textContent});a.each(function(){for(;this.lastChild;)this.removeChild(this.lastChild)});return c==o?a:a.each(typeof c=="function"?h:d)};a.html=function(c){function d(){this.innerHTML=c}function h(){this.innerHTML=c.apply(this,arguments)}if(arguments.length<1)return f(function(){return this.innerHTML});return a.each(typeof c=="function"?h:d)};a.append= <ide> function(c){function d(g){return g.appendChild(document.createElement(c))}function h(g){return g.appendChild(document.createElementNS(c.space,c.local))}c=d3.ns.qualify(c);return b(c.local?h:d)};a.remove=function(){return b(function(c){var d=c.parentNode;d.removeChild(c);return d})};a.sort=function(c){c=wa.apply(this,arguments);for(var d=0,h=a.length;d<h;d++){var g=a[d];g.sort(c);for(var i=1,j=g.length,m=g[0];i<j;i++){var p=g[i];if(p){m&&m.parentNode.insertBefore(p,m.nextSibling);m=p}}}return a};a.on= <ide> function(c,d){c="on"+c;return a.each(function(h,g){this[c]=function(i){var j=d3.event;d3.event=i;try{d.call(this,h,g)}finally{d3.event=j}}})};a.transition=function(){return Q(a)};a.call=E;return a}function va(a){return{nodeKey:function(b){return b.getAttribute(a)},dataKey:function(b){return b[a]}}}function wa(a){arguments.length||(a=xa);return function(b,e){return a(b&&b.__data__,e&&e.__data__)}}function xa(a,b){return a<b?-1:a>b?1:0}d3.transition=P.transition;var ya=0,R=0; <del>function Q(a){function b(k){var n=true,q=-1;a.each(function(){if(i[++q]!=2){var l=(k-j[q])/m[q],s=this.__transition__,t,u=d[q];if(l<1){n=false;if(!(l<0)){if(i[q]){if(s.d!=f){i[q]=2;return}}else if(!s||s.d>f){i[q]=2;return}else{i[q]=1;g.start.dispatch.apply(this,arguments);u=d[q]={};s.d=f;for(t in c)u[t]=c[t].apply(this,arguments)}s=r(l);for(t in c)u[t].call(this,s)}}else{i[q]=2;if(s.d==f){l=s.o;for(t in c)u[t].call(this,1);if(l==f){delete this.__transition__;h&&this.parentNode.removeChild(this)}R= <del>f;g.end.dispatch.apply(this,arguments);R=0;s.o=l}}}});return n}var e={},f=R||++ya,c={},d=[],h=false,g=d3.dispatch("start","end"),i=[],j=[],m=[],p,r=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).o=f});e.delay=function(k){var n=Infinity,q=-1;if(typeof k=="function")a.each(function(){var l=j[++q]=+k.apply(this,arguments);if(l<n)n=l});else{n=+k;a.each(function(){j[++q]=n})}za(b,n);return e};e.duration=function(k){var n=-1;if(typeof k=="function"){p=0;a.each(function(){var q= <del>m[++n]=+k.apply(this,arguments);if(q>p)p=q})}else{p=+k;a.each(function(){m[++n]=p})}return e};e.ease=function(k){r=typeof k=="string"?d3.ease(k):k;return e};e.attrTween=function(k,n){function q(s,t){var u=n.call(this,s,t,this.getAttribute(k));return function(B){this.setAttribute(k,u(B))}}function l(s,t){var u=n.call(this,s,t,this.getAttributeNS(k.space,k.local));return function(B){this.setAttributeNS(k.space,k.local,u(B))}}c["attr."+k]=k.local?l:q;return e};e.attr=function(k,n){return e.attrTween(k, <del>Aa(n))};e.styleTween=function(k,n,q){c["style."+k]=function(l,s){var t=n.call(this,l,s,window.getComputedStyle(this,o).getPropertyValue(k));return function(u){this.style.setProperty(k,t(u),q)}};return e};e.style=function(k,n,q){return e.styleTween(k,Aa(n),q)};e.select=function(k){var n;k=Q(a.select(k)).ease(r);n=-1;k.delay(function(){return j[++n]});n=-1;k.duration(function(){return m[++n]});return k};e.selectAll=function(k){var n;k=Q(a.selectAll(k)).ease(r);n=-1;k.delay(function(q,l){return j[l? <del>n:++n]});n=-1;k.duration(function(q,l){return m[l?n:++n]});return k};e.remove=function(){h=true;return e};e.each=function(k,n){g[k].add(n);return e};e.call=E;return e.delay(0).duration(250)}var S=o,T=0,U;function za(a,b){var e=Date.now(),f=false,c=e+b,d=S;if(isFinite(b)){for(;d;){if(d.n==a){d.j=e;d.delay=b;f=true}else{var h=d.j+d.delay;if(h<c)c=h}d=d.next}f||(S={n:a,j:e,delay:b,next:S});if(!U){clearTimeout(T);T=setTimeout(Ba,Math.max(24,c-e))}}}function Ba(){U=setInterval(Ca,24);T=0} <add>function Q(a){function b(k){var n=true,q=-1;a.each(function(){if(i[++q]!=2){var l=(k-j[q])/m[q],t=this.__transition__,u,s,v=d[q];if(l<1){n=false;if(l<0)return}else l=1;if(i[q]){if(t.d!=f){i[q]=2;return}}else if(!t||t.d>f){i[q]=2;return}else{i[q]=1;g.start.dispatch.apply(this,arguments);v=d[q]={};t.d=f;for(s in c)v[s]=c[s].apply(this,arguments)}u=r(l);for(s in c)v[s].call(this,u);if(l==1){i[q]=2;if(t.d==f){l=t.o;if(l==f){delete this.__transition__;h&&this.parentNode.removeChild(this)}R=f;g.end.dispatch.apply(this, <add>arguments);R=0;t.o=l}}}});return n}var e={},f=R||++ya,c={},d=[],h=false,g=d3.dispatch("start","end"),i=[],j=[],m=[],p,r=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).o=f});e.delay=function(k){var n=Infinity,q=-1;if(typeof k=="function")a.each(function(){var l=j[++q]=+k.apply(this,arguments);if(l<n)n=l});else{n=+k;a.each(function(){j[++q]=n})}za(b,n);return e};e.duration=function(k){var n=-1;if(typeof k=="function"){p=0;a.each(function(){var q=m[++n]=+k.apply(this, <add>arguments);if(q>p)p=q})}else{p=+k;a.each(function(){m[++n]=p})}return e};e.ease=function(k){r=typeof k=="string"?d3.ease(k):k;return e};e.attrTween=function(k,n){function q(t,u){var s=n.call(this,t,u,this.getAttribute(k));return function(v){this.setAttribute(k,s(v))}}function l(t,u){var s=n.call(this,t,u,this.getAttributeNS(k.space,k.local));return function(v){this.setAttributeNS(k.space,k.local,s(v))}}c["attr."+k]=k.local?l:q;return e};e.attr=function(k,n){return e.attrTween(k,Aa(n))};e.styleTween= <add>function(k,n,q){c["style."+k]=function(l,t){var u=n.call(this,l,t,window.getComputedStyle(this,o).getPropertyValue(k));return function(s){this.style.setProperty(k,u(s),q)}};return e};e.style=function(k,n,q){return e.styleTween(k,Aa(n),q)};e.select=function(k){var n;k=Q(a.select(k)).ease(r);n=-1;k.delay(function(){return j[++n]});n=-1;k.duration(function(){return m[++n]});return k};e.selectAll=function(k){var n;k=Q(a.selectAll(k)).ease(r);n=-1;k.delay(function(q,l){return j[l?n:++n]});n=-1;k.duration(function(q, <add>l){return m[l?n:++n]});return k};e.remove=function(){h=true;return e};e.each=function(k,n){g[k].add(n);return e};e.call=E;return e.delay(0).duration(250)}var S=o,T=0,U;function za(a,b){var e=Date.now(),f=false,c=e+b,d=S;if(isFinite(b)){for(;d;){if(d.n==a){d.j=e;d.delay=b;f=true}else{var h=d.j+d.delay;if(h<c)c=h}d=d.next}f||(S={n:a,j:e,delay:b,next:S});if(!U){clearTimeout(T);T=setTimeout(Ba,Math.max(24,c-e))}}}function Ba(){U=setInterval(Ca,24);T=0} <ide> function Ca(){for(var a,b=Date.now(),e=S;e;){a=b-e.j;if(a>e.delay)e.t=e.n(a);e=e.next}a=o;for(b=S;b;)b=b.t?a?a.next=b.next:S=b.next:(a=b).next;a||(U=clearInterval(U))}function Aa(a){return typeof a=="function"?function(b,e,f){return d3.interpolate(f,a.call(this,b,e))}:function(b,e,f){return d3.interpolate(f,a)}}d3.scale={}; <ide> d3.scale.linear=function(){function a(j){return i((j-e)*h)}function b(j){var m=Math.min(e,f),p=Math.max(e,f),r=p-m,k=Math.pow(10,Math.floor(Math.log(r/j)/Math.LN10));j=j/(r/k);if(j<=0.15)k*=10;else if(j<=0.35)k*=5;else if(j<=0.75)k*=2;return{start:Math.ceil(m/k)*k,stop:Math.floor(p/k)*k+k*0.5,q:k}}var e=0,f=1,c=0,d=1,h=1/(f-e),g=(f-e)/(d-c),i=d3.interpolate(c,d);a.invert=function(j){return(j-c)*g+e};a.domain=function(j){if(!arguments.length)return[e,f];e=j[0];f=j[1];h=1/(f-e);g=(f-e)/(d-c);return a}; <ide> a.range=function(j){if(!arguments.length)return[c,d];c=j[0];d=j[1];g=(f-e)/(d-c);i=d3.interpolate(c,d);return a};a.ticks=function(j){j=b(j);return d3.range(j.start,j.stop,j.q)};a.tickFormat=function(j){return d3.format(",."+Math.max(0,-Math.floor(Math.log(b(j).q)/Math.LN10+0.01))+"f")};return a}; <ide> d3.scale.ordinal=function(){function a(d){d=d in e?e[d]:e[d]=b.push(d)-1;return <ide> 2)h=0;var g=d[0],i=d[1],j=(i-g)/(b.length+h);f=d3.range(g+j*h,i,j);c=j*(1-h);return a};a.rangeBand=function(){return c};return a};d3.scale.category10=function(){return d3.scale.ordinal().range(Da)};d3.scale.category20=function(){return d3.scale.ordinal().range(Fa)};d3.scale.category20b=function(){return d3.scale.ordinal().range(Ga)};d3.scale.category20c=function(){return d3.scale.ordinal().range(Ha)}; <ide> var Da=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],Fa=["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],Ga=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd", <ide> "#de9ed6"],Ha=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.svg={}; <del>d3.svg.arc=function(){function a(d,h){var g=b.call(this,d,h),i=e.call(this,d,h),j=f.call(this,d,h)+V,m=c.call(this,d,h)+V,p=m-j,r=Math.cos(j);j=Math.sin(j);var k=Math.cos(m);m=Math.sin(m);return"M"+i*r+","+i*j+"A"+i+","+i+" 0 "+(p<Math.PI?"0":"1")+",1 "+i*k+","+i*m+"L"+g*k+","+g*m+"A"+g+","+g+" 0 "+(p<Math.PI?"0":"1")+",0 "+g*r+","+g*j+"Z"}var b=Ia,e=Ja,f=Ka,c=La;a.innerRadius=function(d){if(!arguments.length)return b;b=x(d);return a};a.outerRadius=function(d){if(!arguments.length)return e;e=x(d); <del>return a};a.startAngle=function(d){if(!arguments.length)return f;f=x(d);return a};a.endAngle=function(d){if(!arguments.length)return c;c=x(d);return a};return a};var V=-Math.PI/2;function Ia(a){return a.innerRadius}function Ja(a){return a.outerRadius}function Ka(a){return a.startAngle}function La(a){return a.endAngle} <add>d3.svg.arc=function(){function a(d,h){var g=b.call(this,d,h),i=e.call(this,d,h),j=f.call(this,d,h)+V,m=c.call(this,d,h)+V,p=m-j,r=Math.cos(j);j=Math.sin(j);var k=Math.cos(m);m=Math.sin(m);return"M"+i*r+","+i*j+"A"+i+","+i+" 0 "+(p<Math.PI?"0":"1")+",1 "+i*k+","+i*m+"L"+g*k+","+g*m+"A"+g+","+g+" 0 "+(p<Math.PI?"0":"1")+",0 "+g*r+","+g*j+"Z"}var b=Ia,e=Ja,f=Ka,c=La;a.innerRadius=function(d){if(!arguments.length)return b;b=y(d);return a};a.outerRadius=function(d){if(!arguments.length)return e;e=y(d); <add>return a};a.startAngle=function(d){if(!arguments.length)return f;f=y(d);return a};a.endAngle=function(d){if(!arguments.length)return c;c=y(d);return a};return a};var V=-Math.PI/2;function Ia(a){return a.innerRadius}function Ja(a){return a.outerRadius}function Ka(a){return a.startAngle}function La(a){return a.endAngle} <ide> d3.svg.line=function(){function a(d){return d.length<1?o:"M"+c(W(this,d,b,e))}var b=Ma,e=Na,f="linear",c=X[f];a.x=function(d){if(!arguments.length)return b;b=d;return a};a.y=function(d){if(!arguments.length)return e;e=d;return a};a.interpolate=function(d){if(!arguments.length)return f;c=X[f=d];return a};return a}; <ide> function W(a,b,e,f){var c=[],d=-1,h=b.length,g=typeof e=="function",i=typeof f=="function",j;if(g&&i)for(;++d<h;)c.push([e.call(a,j=b[d],d),f.call(a,j,d)]);else if(g)for(;++d<h;)c.push([e.call(a,b[d],d),f]);else if(i)for(;++d<h;)c.push([e,f.call(a,b[d],d)]);else for(;++d<h;)c.push([e,f]);return c}function Ma(a){return a.x}function Na(a){return a.y}var X={linear:Oa,basis:Pa}; <ide> function Oa(a){if(a.length<1)return o;var b=[],e=0,f=a.length,c=a[0];for(b.push(c[0],",",c[1]);++e<f;)b.push("L",(c=a[e])[0],",",c[1]);return b.join("")}function Pa(a){if(a.length<3)return Oa(a);var b=[],e=1,f=a.length,c=a[0],d=c[0],h=c[1],g=[d,d,d,(c=a[1])[0]],i=[h,h,h,c[1]];b.push(d,",",h);for(Y(b,g,i);++e<f;){c=a[e];g.shift();g.push(c[0]);i.shift();i.push(c[1]);Y(b,g,i)}for(e=-1;++e<2;){g.shift();g.push(c[0]);i.shift();i.push(c[1]);Y(b,g,i)}return b.join("")} <ide> function Z(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}var Qa=[0,2/3,1/3,0],Ra=[0,1/3,2/3,0],Sa=[0,1/6,2/3,1/6];function Y(a,b,e){a.push("C",Z(Qa,b),",",Z(Qa,e),",",Z(Ra,b),",",Z(Ra,e),",",Z(Sa,b),",",Z(Sa,e))} <ide> d3.svg.area=function(){function a(h){return h.length<1?o:"M"+d(W(this,h,b,f))+"L"+d(W(this,h,b,e).reverse())+"Z"}var b=Ma,e=Ta,f=Na,c="linear",d=X[c];a.x=function(h){if(!arguments.length)return b;b=h;return a};a.y0=function(h){if(!arguments.length)return e;e=h;return a};a.y1=function(h){if(!arguments.length)return f;f=h;return a};a.interpolate=function(h){if(!arguments.length)return c;d=X[c=h];return a};return a};function Ta(){return 0} <del>d3.svg.chord=function(){function a(g,i){var j=b(this,e,g,i),m=b(this,f,g,i);return"M"+j.c+("A"+j.r+","+j.r+" 0 0,1 "+j.p)+(j.k==m.k&&j.m==m.m?"Q 0,0 "+j.c:"Q 0,0 "+m.c+("A"+m.r+","+m.r+" 0 0,1 "+m.p)+("Q 0,0 "+j.c))+"Z"}function b(g,i,j,m){var p=i.call(g,j,m);i=c.call(g,p,m);j=d.call(g,p,m)+V;g=h.call(g,p,m)+V;return{r:i,k:j,m:g,c:[i*Math.cos(j),i*Math.sin(j)],p:[i*Math.cos(g),i*Math.sin(g)]}}var e=Ua,f=Va,c=Wa,d=Ka,h=La;a.radius=function(g){if(!arguments.length)return c;c=x(g);return a};a.source= <del>function(g){if(!arguments.length)return e;e=x(g);return a};a.target=function(g){if(!arguments.length)return f;f=x(g);return a};a.startAngle=function(g){if(!arguments.length)return d;d=x(g);return a};a.endAngle=function(g){if(!arguments.length)return h;h=x(g);return a};return a};function Ua(a){return a.source}function Va(a){return a.target}function Wa(a){return a.radius} <add>d3.svg.chord=function(){function a(g,i){var j=b(this,e,g,i),m=b(this,f,g,i);return"M"+j.c+("A"+j.r+","+j.r+" 0 0,1 "+j.p)+(j.k==m.k&&j.m==m.m?"Q 0,0 "+j.c:"Q 0,0 "+m.c+("A"+m.r+","+m.r+" 0 0,1 "+m.p)+("Q 0,0 "+j.c))+"Z"}function b(g,i,j,m){var p=i.call(g,j,m);i=c.call(g,p,m);j=d.call(g,p,m)+V;g=h.call(g,p,m)+V;return{r:i,k:j,m:g,c:[i*Math.cos(j),i*Math.sin(j)],p:[i*Math.cos(g),i*Math.sin(g)]}}var e=Ua,f=Va,c=Wa,d=Ka,h=La;a.radius=function(g){if(!arguments.length)return c;c=y(g);return a};a.source= <add>function(g){if(!arguments.length)return e;e=y(g);return a};a.target=function(g){if(!arguments.length)return f;f=y(g);return a};a.startAngle=function(g){if(!arguments.length)return d;d=y(g);return a};a.endAngle=function(g){if(!arguments.length)return h;h=y(g);return a};return a};function Ua(a){return a.source}function Va(a){return a.target}function Wa(a){return a.radius} <ide> d3.svg.mouse=function(a){var b=(a.ownerSVGElement||a).createSVGPoint();if($<0&&(window.scrollX||window.scrollY)){var e=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),f=e[0][0].getScreenCTM();$=!(f.f||f.e);e.remove()}if($){b.x=d3.event.pageX;b.y=d3.event.pageY}else{b.x=d3.event.clientX;b.y=d3.event.clientY}b=b.matrixTransform(a.getScreenCTM().inverse());return[b.x,b.y]};var $=/WebKit/.test(navigator.userAgent)?-1:0;})() <ide><path>src/core/core.js <del>d3 = {version: "0.26.0"}; // semver <add>d3 = {version: "0.26.1"}; // semver <ide><path>src/core/transition.js <ide> function d3_transition(groups) { <ide> te, // ease(t) <ide> tk, // tween key <ide> ik = interpolators[k]; <add> <add> // Check if the (un-eased) time is outside the range [0,1]. <ide> if (t < 1) { <ide> clear = false; <ide> if (t < 0) return; <del> if (stage[k]) { <del> if (tx.active != transitionId) { <del> stage[k] = 2; <del> return; <del> } <del> } else if (!tx || tx.active > transitionId) { <add> } else { <add> t = 1; <add> } <add> <add> // Determine the stage of this transition. <add> // 0 - Not yet started. <add> // 1 - In progress. <add> // 2 - Ended. <add> if (stage[k]) { <add> if (tx.active != transitionId) { <ide> stage[k] = 2; <ide> return; <del> } else { <del> stage[k] = 1; <del> event.start.dispatch.apply(this, arguments); <del> ik = interpolators[k] = {}; <del> tx.active = transitionId; <del> for (tk in tweens) ik[tk] = tweens[tk].apply(this, arguments); <ide> } <del> te = ease(t); <del> for (tk in tweens) ik[tk].call(this, te); <add> } else if (!tx || tx.active > transitionId) { <add> stage[k] = 2; <add> return; <ide> } else { <add> stage[k] = 1; <add> event.start.dispatch.apply(this, arguments); <add> ik = interpolators[k] = {}; <add> tx.active = transitionId; <add> for (tk in tweens) ik[tk] = tweens[tk].apply(this, arguments); <add> } <add> <add> // Apply the interpolators! <add> te = ease(t); <add> for (tk in tweens) ik[tk].call(this, te); <add> <add> // Handle ending transitions. <add> if (t == 1) { <ide> stage[k] = 2; <ide> if (tx.active == transitionId) { <ide> var owner = tx.owner; <del> for (tk in tweens) ik[tk].call(this, 1); <ide> if (owner == transitionId) { <ide> delete this.__transition__; <ide> if (remove) this.parentNode.removeChild(this); <ide><path>src/layout/chord.js <ide> d3["layout"]["chord"] = function() { <ide> x += padding; <ide> } <ide> <del> // Generate chords for each subgroup-subgroup link. <add> // Generate chords for each (non-empty) subgroup-subgroup link. <ide> i = -1; while (++i < n) { <ide> j = i - 1; while (++j < n) { <del> chords.push({ <del> "source": subgroups[i + "-" + j], <del> "target": subgroups[j + "-" + i] <del> }) <add> var source = subgroups[i + "-" + j], <add> target = subgroups[j + "-" + i]; <add> if (source["value"] || target["value"]) { <add> chords.push({ <add> "source": source, <add> "target": target <add> }) <add> } <ide> } <ide> } <ide>
7
Ruby
Ruby
define word boundary for unanchored path regexp
c94754e2f0bc488907157382ece309baf4ddb1b0
<ide><path>actionpack/lib/action_dispatch/journey/path/pattern.rb <ide> def visit_OR(node) <ide> <ide> class UnanchoredRegexp < AnchoredRegexp # :nodoc: <ide> def accept(node) <del> %r{\A#{visit node}} <add> %r{\A#{visit node}\b} <ide> end <ide> end <ide> <ide><path>actionpack/test/dispatch/mount_test.rb <ide> def test_mounting_with_shorthand <ide> assert_equal "/shorthand -- /omg", response.body <ide> end <ide> <add> def test_mounting_does_not_match_similar_paths <add> get "/shorthandomg" <add> assert_not_equal "/shorthand -- /omg", response.body <add> assert_equal " -- /shorthandomg", response.body <add> end <add> <ide> def test_mounting_works_with_via <ide> get "/getfake" <ide> assert_equal "OK", response.body <ide><path>actionpack/test/journey/path/pattern_test.rb <ide> class TestPattern < ActiveSupport::TestCase <ide> end <ide> <ide> { <del> "/:controller(/:action)" => %r{\A/(#{x})(?:/([^/.?]+))?}, <del> "/:controller/foo" => %r{\A/(#{x})/foo}, <del> "/:controller/:action" => %r{\A/(#{x})/([^/.?]+)}, <del> "/:controller" => %r{\A/(#{x})}, <del> "/:controller(/:action(/:id))" => %r{\A/(#{x})(?:/([^/.?]+)(?:/([^/.?]+))?)?}, <del> "/:controller/:action.xml" => %r{\A/(#{x})/([^/.?]+)\.xml}, <del> "/:controller.:format" => %r{\A/(#{x})\.([^/.?]+)}, <del> "/:controller(.:format)" => %r{\A/(#{x})(?:\.([^/.?]+))?}, <del> "/:controller/*foo" => %r{\A/(#{x})/(.+)}, <del> "/:controller/*foo/bar" => %r{\A/(#{x})/(.+)/bar}, <del> "/:foo|*bar" => %r{\A/(?:([^/.?]+)|(.+))}, <add> "/:controller(/:action)" => %r{\A/(#{x})(?:/([^/.?]+))?\b}, <add> "/:controller/foo" => %r{\A/(#{x})/foo\b}, <add> "/:controller/:action" => %r{\A/(#{x})/([^/.?]+)\b}, <add> "/:controller" => %r{\A/(#{x})\b}, <add> "/:controller(/:action(/:id))" => %r{\A/(#{x})(?:/([^/.?]+)(?:/([^/.?]+))?)?\b}, <add> "/:controller/:action.xml" => %r{\A/(#{x})/([^/.?]+)\.xml\b}, <add> "/:controller.:format" => %r{\A/(#{x})\.([^/.?]+)\b}, <add> "/:controller(.:format)" => %r{\A/(#{x})(?:\.([^/.?]+))?\b}, <add> "/:controller/*foo" => %r{\A/(#{x})/(.+)\b}, <add> "/:controller/*foo/bar" => %r{\A/(#{x})/(.+)/bar\b}, <add> "/:foo|*bar" => %r{\A/(?:([^/.?]+)|(.+))\b}, <ide> }.each do |path, expected| <ide> define_method(:"test_to_non_anchored_regexp_#{Regexp.escape(path)}") do <ide> path = Pattern.build(
3
Javascript
Javascript
flow strict in viewpagerandroid.android.js
636e146c4a27990547c81c2d36411d36b2c8e788
<ide><path>Libraries/Components/ViewPager/ViewPagerAndroid.android.js <ide> * LICENSE file in the root directory of this source tree. <ide> * <ide> * @format <del> * @flow <add> * @flow strict-local <ide> */ <ide> <ide> 'use strict'; <ide> const requireNativeComponent = require('requireNativeComponent'); <ide> <ide> const NativeAndroidViewPager = requireNativeComponent('AndroidViewPager'); <ide> <add>import type {SyntheticEvent} from 'CoreEventTypes'; <ide> import type {ViewStyleProp} from 'StyleSheet'; <ide> <ide> const VIEWPAGER_REF = 'viewPager'; <ide> <del>type Event = Object; <add>type PageScrollState = 'idle' | 'dragging' | 'settling'; <add> <add>type PageScrollEvent = SyntheticEvent< <add> $ReadOnly<{| <add> position: number, <add> offset: number, <add> |}>, <add>>; <add> <add>type PageScrollStateChangedEvent = SyntheticEvent< <add> $ReadOnly<{| <add> pageScrollState: PageScrollState, <add> |}>, <add>>; <add> <add>type PageSelectedEvent = SyntheticEvent< <add> $ReadOnly<{| <add> position: number, <add> |}>, <add>>; <ide> <ide> export type ViewPagerScrollState = $Enum<{ <ide> idle: string, <ide> type Props = $ReadOnly<{| <ide> * Value x means that (1 - x) fraction of the page at "position" index is <ide> * visible, and x fraction of the next page is visible. <ide> */ <del> onPageScroll?: ?Function, <add> onPageScroll?: ?(e: PageScrollEvent) => void, <ide> <ide> /** <ide> * Function called when the page scrolling state has changed. <ide> type Props = $ReadOnly<{| <ide> * - settling, meaning that there was an interaction with the page scroller, and the <ide> * page scroller is now finishing it's closing or opening animation <ide> */ <del> onPageScrollStateChanged?: ?Function, <add> onPageScrollStateChanged?: ?(e: PageScrollState) => void, <ide> <ide> /** <ide> * This callback will be called once ViewPager finish navigating to selected page <ide> * (when user swipes between pages). The `event.nativeEvent` object passed to this <ide> * callback will have following fields: <ide> * - position - index of page that has been selected <ide> */ <del> onPageSelected?: ?Function, <add> onPageSelected?: ?(e: PageSelectedEvent) => void, <ide> <ide> /** <ide> * Blank space to show between pages. This is only visible while scrolling, pages are still <ide> class ViewPagerAndroid extends React.Component<Props> { <ide> }); <ide> }; <ide> <del> _onPageScroll = (e: Event) => { <add> _onPageScroll = (e: PageScrollEvent) => { <ide> if (this.props.onPageScroll) { <ide> this.props.onPageScroll(e); <ide> } <ide> class ViewPagerAndroid extends React.Component<Props> { <ide> } <ide> }; <ide> <del> _onPageScrollStateChanged = (e: Event) => { <add> _onPageScrollStateChanged = (e: PageScrollStateChangedEvent) => { <ide> if (this.props.onPageScrollStateChanged) { <ide> this.props.onPageScrollStateChanged(e.nativeEvent.pageScrollState); <ide> } <ide> }; <ide> <del> _onPageSelected = (e: Event) => { <add> _onPageSelected = (e: PageSelectedEvent) => { <ide> if (this.props.onPageSelected) { <ide> this.props.onPageSelected(e); <ide> }
1
Java
Java
add fb4a native modules to snapshot tests
dc22bd638fcc68ecab55d1175318822cf8972967
<ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactAppTestActivity.java <ide> <ide> package com.facebook.react.testing; <ide> <del>import javax.annotation.Nullable; <del> <del>import java.util.concurrent.CountDownLatch; <del>import java.util.concurrent.TimeUnit; <del> <ide> import android.graphics.Bitmap; <ide> import android.os.Bundle; <ide> import android.support.v4.app.FragmentActivity; <ide> import android.view.View; <ide> import android.view.ViewTreeObserver; <ide> import android.widget.FrameLayout; <del> <ide> import com.facebook.infer.annotation.Assertions; <ide> import com.facebook.react.ReactInstanceManager; <ide> import com.facebook.react.ReactInstanceManagerBuilder; <ide> import com.facebook.react.testing.idledetection.ReactBridgeIdleSignaler; <ide> import com.facebook.react.testing.idledetection.ReactIdleDetectionUtil; <ide> import com.facebook.react.uimanager.UIImplementationProvider; <add>import java.util.concurrent.CountDownLatch; <add>import java.util.concurrent.TimeUnit; <add>import javax.annotation.Nullable; <ide> <ide> public class ReactAppTestActivity extends FragmentActivity implements <ide> DefaultHardwareBackBtnHandler <ide> public class ReactAppTestActivity extends FragmentActivity implements <ide> private static final String DEFAULT_BUNDLE_NAME = "AndroidTestBundle.js"; <ide> private static final int ROOT_VIEW_ID = 8675309; <ide> // we need a bigger timeout for CI builds because they run on a slow emulator <del> private static final long IDLE_TIMEOUT_MS = 60000; <add> private static final long IDLE_TIMEOUT_MS = 120000; <ide> <ide> private CountDownLatch mLayoutEvent = new CountDownLatch(1); <ide> private @Nullable ReactBridgeIdleSignaler mBridgeIdleSignaler; <ide> public void loadApp( <ide> mBridgeIdleSignaler = new ReactBridgeIdleSignaler(); <ide> <ide> ReactInstanceManagerBuilder builder = <del> ReactTestHelper.getReactTestFactory().getReactInstanceManagerBuilder() <del> .setApplication(getApplication()) <del> .setBundleAssetName(bundleName) <add> ReactTestHelper.getReactTestFactory() <add> .getReactInstanceManagerBuilder() <add> .setApplication(getApplication()) <add> .setBundleAssetName(bundleName); <add> if (!spec.getAlternativeReactPackagesForTest().isEmpty()) { <add> builder.addPackages(spec.getAlternativeReactPackagesForTest()); <add> } else { <add> builder.addPackage(new MainReactPackage()); <add> } <add> builder <add> .addPackage(new InstanceSpecForTestPackage(spec)) <ide> // By not setting a JS module name, we force the bundle to be always loaded from <ide> // assets, not the devserver, even if dev mode is enabled (such as when testing redboxes). <ide> // This makes sense because we never run the devserver in tests. <ide> //.setJSMainModuleName() <del> .addPackage(spec.getAlternativeReactPackageForTest() != null ? <del> spec.getAlternativeReactPackageForTest() : new MainReactPackage()) <del> .addPackage(new InstanceSpecForTestPackage(spec)) <ide> .setUseDeveloperSupport(useDevSupport) <ide> .setBridgeIdleDebugListener(mBridgeIdleSignaler) <ide> .setInitialLifecycleState(mLifecycleState) <ide><path>ReactAndroid/src/androidTest/java/com/facebook/react/testing/ReactInstanceSpecForTest.java <ide> <ide> package com.facebook.react.testing; <ide> <del>import java.util.ArrayList; <del>import java.util.Arrays; <del>import java.util.List; <del> <ide> import android.annotation.SuppressLint; <del> <del>import com.facebook.react.bridge.NativeModule; <add>import com.facebook.react.ReactPackage; <ide> import com.facebook.react.bridge.JavaScriptModule; <add>import com.facebook.react.bridge.NativeModule; <ide> import com.facebook.react.uimanager.ViewManager; <del>import com.facebook.react.ReactPackage; <add>import java.util.ArrayList; <add>import java.util.Arrays; <add>import java.util.List; <ide> <ide> /** <ide> * A spec that allows a test to add additional NativeModules/JS modules to the ReactInstance. This <ide> public class ReactInstanceSpecForTest { <ide> new ArrayList<NativeModule>(Arrays.asList(new FakeWebSocketModule())); <ide> private final List<Class<? extends JavaScriptModule>> mJSModuleSpecs = new ArrayList<>(); <ide> private final List<ViewManager> mViewManagers = new ArrayList<>(); <del> private ReactPackage mReactPackage = null; <add> private final ArrayList<ReactPackage> mReactPackages = new ArrayList<>(); <ide> <ide> public ReactInstanceSpecForTest addNativeModule(NativeModule module) { <ide> mNativeModules.add(module); <ide> return this; <ide> } <ide> <ide> public ReactInstanceSpecForTest setPackage(ReactPackage reactPackage) { <del> mReactPackage = reactPackage; <add> if (!mReactPackages.isEmpty()) { <add> throw new IllegalStateException( <add> "setPackage is not allowed after addPackages. " + reactPackage); <add> } <add> mReactPackages.add(reactPackage); <add> return this; <add> } <add> <add> public ReactInstanceSpecForTest addPackages(List<ReactPackage> reactPackages) { <add> mReactPackages.addAll(reactPackages); <ide> return this; <ide> } <ide> <ide> public List<NativeModule> getExtraNativeModulesForTest() { <ide> } <ide> <ide> public ReactPackage getAlternativeReactPackageForTest() { <del> return mReactPackage; <add> if (mReactPackages.size() > 1) { <add> throw new IllegalStateException( <add> "Multiple packages were added - use getAlternativeReactPackagesForTest instead."); <add> } <add> return mReactPackages.get(0); <add> } <add> <add> public List<ReactPackage> getAlternativeReactPackagesForTest() { <add> return mReactPackages; <ide> } <ide> <ide> public List<ViewManager> getExtraViewManagers() { <ide><path>ReactAndroid/src/main/java/com/facebook/react/ReactInstanceManagerBuilder.java <ide> import android.app.Activity; <ide> import android.app.Application; <ide> import com.facebook.infer.annotation.Assertions; <del>import com.facebook.react.bridge.JavaScriptExecutorFactory; <ide> import com.facebook.react.bridge.JSBundleLoader; <ide> import com.facebook.react.bridge.JSCJavaScriptExecutorFactory; <add>import com.facebook.react.bridge.JavaScriptExecutorFactory; <ide> import com.facebook.react.bridge.NativeModuleCallExceptionHandler; <ide> import com.facebook.react.bridge.NotThreadSafeBridgeIdleDebugListener; <ide> import com.facebook.react.common.LifecycleState; <ide> public ReactInstanceManagerBuilder addPackage(ReactPackage reactPackage) { <ide> return this; <ide> } <ide> <add> public ReactInstanceManagerBuilder addPackages(List<ReactPackage> reactPackages) { <add> mPackages.addAll(reactPackages); <add> return this; <add> } <add> <ide> public ReactInstanceManagerBuilder setBridgeIdleDebugListener( <ide> NotThreadSafeBridgeIdleDebugListener bridgeIdleDebugListener) { <ide> mBridgeIdleDebugListener = bridgeIdleDebugListener;
3
Python
Python
fix two bugs with assignment in linode dns driver
ab047b952aea70ee27114478140d848642f9819f
<ide><path>libcloud/dns/drivers/linode.py <ide> def create_record(self, name, zone, type, data, extra=None): <ide> valid_keys=VALID_RECORD_EXTRA_PARAMS, <ide> extra=extra) <ide> <del> data = self.connection.request(API_ROOT, params=params).objects[0] <del> record = Record(id=data['ResourceID'], name=name, type=type, <add> result = self.connection.request(API_ROOT, params=params).objects[0] <add> record = Record(id=result['ResourceID'], name=name, type=type, <ide> data=data, extra=merged, zone=zone, driver=self) <ide> return record <ide> <del> def update_record(self, record, name, type, data, extra): <add> def update_record(self, record, name, type, data, extra=None): <ide> """ <ide> Update an existing record. <ide> <ide> def update_record(self, record, name, type, data, extra): <ide> valid_keys=VALID_RECORD_EXTRA_PARAMS, <ide> extra=extra) <ide> <del> data = self.connection.request(API_ROOT, params=params).objects[0] <del> record = Record(id=data['ResourceID'], name=name, type=type, <add> result = self.connection.request(API_ROOT, params=params).objects[0] <add> record = Record(id=result['ResourceID'], name=name, type=type, <ide> data=data, extra=merged, zone=record.zone, driver=self) <ide> return record <ide>
1
PHP
PHP
fix php-cs (missing spaces)
91dcfdf38733581321c268da3ccc3f1cd6974835
<ide><path>src/View/ViewBlock.php <ide> public function end() <ide> $mode = end($this->_active); <ide> $active = key($this->_active); <ide> $content = ob_get_clean(); <del> if($mode === ViewBlock::OVERRIDE) { <add> if ($mode === ViewBlock::OVERRIDE) { <ide> $this->_blocks[$active] = $content; <ide> } else { <ide> $this->concat($active, $content, $mode); <ide> public function end() <ide> */ <ide> public function concat($name, $value = null, $mode = ViewBlock::APPEND) <ide> { <del> if($value === null) { <add> if ($value === null) { <ide> $this->start($name, $mode); <ide> return; <ide> }
1
Text
Text
add quotes to api
636d3aeda753301657cf9f2e9faa8e947392bfe2
<ide><path>docs/advanced-features/react-18.md <ide> Ensure you have the `rc` npm tag of React installed: <ide> npm install next@latest react@rc react-dom@rc <ide> ``` <ide> <del>That's all! You can now start using React 18's new APIs like `startTransition` and Suspense in Next.js. <add>That's all! You can now start using React 18's new APIs like `startTransition` and `Suspense` in Next.js. <ide> <ide> ### Enable SSR Streaming (Alpha) <ide>
1
Javascript
Javascript
pass session object directly into connect-mongo
093bbfd679f3cc75a214e6270527646cee853d34
<ide><path>app.js <ide> var csrf = require('lusca').csrf(); <ide> var methodOverride = require('method-override'); <ide> <ide> var _ = require('lodash'); <del>var MongoStore = require('connect-mongo')({ session: session }); <add>var MongoStore = require('connect-mongo')(session); <ide> var flash = require('express-flash'); <ide> var path = require('path'); <ide> var mongoose = require('mongoose');
1
Ruby
Ruby
correct the parameter name for deserialize
6852a53821a4da20943592601582d488e384810d
<ide><path>activejob/lib/active_job/serializers/object_serializer.rb <ide> def serialize(hash) <ide> end <ide> <ide> # Deserializes an argument from a JSON primitive type. <del> def deserialize(_argument) <add> def deserialize(json) <ide> raise NotImplementedError <ide> end <ide>
1
Python
Python
describe memory considerations in in1d/isin
7cb937c37f2cb33c096055b3783a006f71c938df
<ide><path>numpy/lib/arraysetops.py <ide> def in1d(ar1, ar2, assume_unique=False, invert=False, method='auto'): <ide> The algorithm to use. This will not affect the final result, <ide> but will affect the speed. Default is 'auto'. <ide> <del> - If 'sort', will use a sort-based approach. <add> - If 'sort', will use a mergesort-based approach. This will have <add> a memory usage of roughly 6 times the sum of the sizes of <add> `ar1` and `ar2`, not accounting for size of dtypes. <ide> - If 'dictionary', will use a key-dictionary approach similar <ide> to a counting sort. This is only available for boolean and <del> integer arrays. <add> integer arrays. This will have a memory usage of the <add> size of `ar1` plus the max-min value of `ar2`. This tends <add> to be the faster method if the following formula is true: <add> `log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927`, <add> but may use greater memory. <ide> - If 'auto', will automatically choose the method which is <del> expected to perform the fastest, which depends <del> on the size and range of `ar2`. For larger sizes or <del> smaller range, 'dictionary' is chosen. <del> For larger range or smaller sizes, 'sort' is chosen. <add> expected to perform the fastest, using the above <add> formula. For larger sizes or smaller range, <add> 'dictionary' is chosen. For larger range or smaller <add> sizes, 'sort' is chosen. <ide> <ide> .. versionadded:: 1.8.0 <ide> <ide> def isin(element, test_elements, assume_unique=False, invert=False, <ide> The algorithm to use. This will not affect the final result, <ide> but will affect the speed. Default is 'auto'. <ide> <del> - If 'sort', will use a sort-based approach. <add> - If 'sort', will use a mergesort-based approach. This will have <add> a memory usage of roughly 6 times the sum of the sizes of <add> `ar1` and `ar2`, not accounting for size of dtypes. <ide> - If 'dictionary', will use a key-dictionary approach similar <ide> to a counting sort. This is only available for boolean and <del> integer arrays. <add> integer arrays. This will have a memory usage of the <add> size of `ar1` plus the max-min value of `ar2`. This tends <add> to be the faster method if the following formula is true: <add> `log10(len(ar2)) > (log10(max(ar2)-min(ar2)) - 2.27) / 0.927`, <add> but may use greater memory. <ide> - If 'auto', will automatically choose the method which is <del> expected to perform the fastest, which depends <del> on the size and range of `ar2`. For larger sizes, <add> expected to perform the fastest, using the above <add> formula. For larger sizes or smaller range, <ide> 'dictionary' is chosen. For larger range or smaller <ide> sizes, 'sort' is chosen. <ide>
1
Mixed
Text
remove old documentation
df1d146ee784868b44ddba802edfcc30c6ad9795
<ide><path>docs/api-guide/filtering.md <ide> By default, the search parameter is named `'search`', but this may be overridden <ide> To dynamically change search fields based on request content, it's possible to subclass the `SearchFilter` and override the `get_search_fields()` function. For example, the following subclass will only search on `title` if the query parameter `title_only` is in the request: <ide> <ide> from rest_framework import filters <del> <add> <ide> class CustomSearchFilter(filters.SearchFilter): <ide> def get_search_fields(self, view, request): <ide> if request.query_params.get('title_only'): <ide> The `ordering` attribute may be either a string or a list/tuple of strings. <ide> <ide> --- <ide> <del>## DjangoObjectPermissionsFilter <del> <del>The `DjangoObjectPermissionsFilter` is intended to be used together with the [`django-guardian`][guardian] package, with custom `'view'` permissions added. The filter will ensure that querysets only returns objects for which the user has the appropriate view permission. <del> <del>--- <del> <del>**Note:** This filter has been deprecated as of version 3.9 and moved to the 3rd-party [`djangorestframework-guardian` package][django-rest-framework-guardian]. <del> <del>--- <del> <del>If you're using `DjangoObjectPermissionsFilter`, you'll probably also want to add an appropriate object permissions class, to ensure that users can only operate on instances if they have the appropriate object permissions. The easiest way to do this is to subclass `DjangoObjectPermissions` and add `'view'` permissions to the `perms_map` attribute. <del> <del>A complete example using both `DjangoObjectPermissionsFilter` and `DjangoObjectPermissions` might look something like this. <del> <del>**permissions.py**: <del> <del> class CustomObjectPermissions(permissions.DjangoObjectPermissions): <del> """ <del> Similar to `DjangoObjectPermissions`, but adding 'view' permissions. <del> """ <del> perms_map = { <del> 'GET': ['%(app_label)s.view_%(model_name)s'], <del> 'OPTIONS': ['%(app_label)s.view_%(model_name)s'], <del> 'HEAD': ['%(app_label)s.view_%(model_name)s'], <del> 'POST': ['%(app_label)s.add_%(model_name)s'], <del> 'PUT': ['%(app_label)s.change_%(model_name)s'], <del> 'PATCH': ['%(app_label)s.change_%(model_name)s'], <del> 'DELETE': ['%(app_label)s.delete_%(model_name)s'], <del> } <del> <del>**views.py**: <del> <del> class EventViewSet(viewsets.ModelViewSet): <del> """ <del> Viewset that only lists events if user has 'view' permissions, and only <del> allows operations on individual events if user has appropriate 'view', 'add', <del> 'change' or 'delete' permissions. <del> """ <del> queryset = Event.objects.all() <del> serializer_class = EventSerializer <del> filter_backends = (filters.DjangoObjectPermissionsFilter,) <del> permission_classes = (myapp.permissions.CustomObjectPermissions,) <del> <del>For more information on adding `'view'` permissions for models, see the [relevant section][view-permissions] of the `django-guardian` documentation, and [this blogpost][view-permissions-blogpost]. <del> <del>--- <del> <ide> # Custom generic filtering <ide> <ide> You can also provide your own generic filtering backend, or write an installable app for other developers to use. <ide> The [djangorestframework-word-filter][django-rest-framework-word-search-filter] <ide> [cite]: https://docs.djangoproject.com/en/stable/topics/db/queries/#retrieving-specific-objects-with-filters <ide> [django-filter-docs]: https://django-filter.readthedocs.io/en/latest/index.html <ide> [django-filter-drf-docs]: https://django-filter.readthedocs.io/en/latest/guide/rest_framework.html <del>[guardian]: https://django-guardian.readthedocs.io/ <del>[view-permissions]: https://django-guardian.readthedocs.io/en/latest/userguide/assign.html <del>[view-permissions-blogpost]: https://blog.nyaruka.com/adding-a-view-permission-to-django-models <ide> [search-django-admin]: https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields <ide> [django-rest-framework-filters]: https://github.com/philipn/django-rest-framework-filters <del>[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian <ide> [django-rest-framework-word-search-filter]: https://github.com/trollknurr/django-rest-framework-word-search-filter <ide> [django-url-filter]: https://github.com/miki725/django-url-filter <ide> [drf-url-filter]: https://github.com/manjitkumar/drf-url-filters <ide><path>docs/community/third-party-packages.md <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> * [djangorestframework-chain][djangorestframework-chain] - Allows arbitrary chaining of both relations and lookup filters. <ide> * [django-url-filter][django-url-filter] - Allows a safe way to filter data via human-friendly URLs. It is a generic library which is not tied to DRF but it provides easy integration with DRF. <ide> * [drf-url-filter][drf-url-filter] is a simple Django app to apply filters on drf `ModelViewSet`'s `Queryset` in a clean, simple and configurable way. It also supports validations on incoming query params and their values. <add>* [django-rest-framework-guardian][django-rest-framework-guardian] - Provides integration with django-guardian, including the `DjangoObjectPermissionsFilter` previously found in DRF. <ide> <ide> ### Misc <ide> <ide> To submit new content, [open an issue][drf-create-issue] or [create a pull reque <ide> [drf-access-policy]: https://github.com/rsinger86/drf-access-policy <ide> [drf-flex-fields]: https://github.com/rsinger86/drf-flex-fields <ide> [djangorestframework-mvt]: https://github.com/corteva/djangorestframework-mvt <add>[django-rest-framework-guardian]: https://github.com/rpkilby/django-rest-framework-guardian <ide><path>rest_framework/decorators.py <ide> for writing function-based views with REST framework. <ide> <ide> There are also various decorators for setting the API policies on function <del>based views, as well as the `@detail_route` and `@list_route` decorators, which are <del>used to annotate methods on viewsets that should be included by routers. <add>based views, as well as the `@action` decorator, which is used to annotate <add>methods on viewsets that should be included by routers. <ide> """ <ide> import types <ide>
3
Javascript
Javascript
use the functions
5d87002b3f07687f71186baec75b5acc98bc7cc1
<ide><path>src/git-repository-async.js <ide> export default class GitRepositoryAsync { <ide> }) <ide> .then(statuses => { <ide> return Promise.all(statuses.map(s => s.statusBit())).then(bits => { <del> let directoryStatus = 0 <del> const filteredBits = bits.filter(b => b > 0) <del> if (filteredBits.length > 0) { <del> filteredBits.forEach(bit => directoryStatus |= bit) <del> } <del> <del> return directoryStatus <add> return bits <add> .filter(b => b > 0) <add> .reduce((status, bit) => status | bit, 0) <ide> }) <ide> }) <ide> }
1
Text
Text
add some tutorials
a9aaebb70c45e3913d0c6430bfb3739e6ad42e94
<ide><path>docs/introduction/Ecosystem.md <ide> On this page we will only feature a few of them that the Redux maintainers have <ide> <ide> * [redux-devtools](http://github.com/gaearon/redux-devtools) — An action logger with time travel UI, hot reloading and error handling for the reducers, [first demoed at React Europe](https://www.youtube.com/watch?v=xsSnOQynTHs) <ide> <add>## Tutorials and Articles <add> <add>* [redux-tutorial](https://github.com/happypoulp/redux-tutorial) — Learn how to use redux step by step <add>* [What the Flux?! Let’s Redux.](https://blog.andyet.com/2015/08/06/what-the-flux-lets-redux) <add>* [Handcrafting an Isomorphic Redux Application (With Love)](https://medium.com/@bananaoomarang/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4) <add> <ide> ## More <ide> <ide> [Awesome Redux](https://github.com/xgrommx/awesome-redux) is an extensive list of Redux-related repositories.
1
PHP
PHP
throw error when psy/psysh is not loaded
01d03b7dcb8807474402f36c0cb474fcfa92301a
<ide><path>src/basics.php <ide> function breakpoint() <ide> if (PHP_SAPI === 'cli' && class_exists('\Psy\Shell')) { <ide> return 'extract(\Psy\Shell::debug(get_defined_vars(), isset($this) ? $this : null));'; <ide> } <add> trigger_error( <add> "psy/psysh must be loaded and you should be in CLI to use the breakpoint method", <add> E_USER_WARNING <add> ); <ide> } <ide> }
1
PHP
PHP
fix deprecationwarning message
1a684f97c337234c67297878cf34af4a486403b6
<ide><path>src/Database/Schema/TableSchema.php <ide> public function temporary($temporary = null) <ide> { <ide> deprecationWarning( <ide> 'TableSchema::temporary() is deprecated. ' . <del> 'Use TableSchema::setTemporary()/getTemporary() instead.' <add> 'Use TableSchema::setTemporary()/isTemporary() instead.' <ide> ); <ide> if ($temporary !== null) { <ide> return $this->setTemporary($temporary);
1
Ruby
Ruby
pass explicit sort to handle apfs
ac799d9f2d8cff87d01b69174056f65552517721
<ide><path>Library/Homebrew/cmd/list.rb <ide> def filtered_list <ide> end <ide> if ARGV.include? "--pinned" <ide> pinned_versions = {} <del> names.each do |d| <add> names.sort.each do |d| <ide> keg_pin = (HOMEBREW_PINNED_KEGS/d.basename.to_s) <ide> if keg_pin.exist? || keg_pin.symlink? <ide> pinned_versions[d] = keg_pin.readlink.basename.to_s
1
Javascript
Javascript
read color info from jpx stream
1ccc8a64b7beeb79f5dc4aee1a03ef04f23997ee
<ide><path>src/core/image.js <ide> * See the License for the specific language governing permissions and <ide> * limitations under the License. <ide> */ <del>/* globals ColorSpace, DecodeStream, error, isArray, ImageKind, isStream, <del> JpegStream, Name, Promise, Stream, warn, LegacyPromise */ <add>/* globals ColorSpace, DecodeStream, error, info, isArray, ImageKind, isStream, <add> JpegStream, JpxImage, Name, Promise, Stream, warn, LegacyPromise */ <ide> <ide> 'use strict'; <ide> <ide> var PDFImage = (function PDFImageClosure() { <ide> } <ide> function PDFImage(xref, res, image, inline, smask, mask, isMask) { <ide> this.image = image; <del> if (image.getParams) { <del> // JPX/JPEG2000 streams directly contain bits per component <del> // and color space mode information. <del> warn('get params from actual stream'); <del> // var bits = ... <del> // var colorspace = ... <add> var dict = image.dict; <add> if (dict.get('Filter').name === 'JPXDecode') { <add> info('get image params from JPX stream'); <add> var jpxImage = new JpxImage(); <add> var data = image.stream.bytes; <add> jpxImage.parseImageProperties(data, 0, data.length); <add> image.bitsPerComponent = jpxImage.bitsPerComponent; <add> image.numComps = jpxImage.componentsCount; <add> } <add> if (dict.get('Filter').name === 'JBIG2Decode') { <add> image.bitsPerComponent = 1; <add> image.numComps = 1; <ide> } <ide> // TODO cache rendered images? <ide> <del> var dict = image.dict; <ide> this.width = dict.get('Width', 'W'); <ide> this.height = dict.get('Height', 'H'); <ide> <ide> var PDFImage = (function PDFImageClosure() { <ide> if (!this.imageMask) { <ide> var colorSpace = dict.get('ColorSpace', 'CS'); <ide> if (!colorSpace) { <del> warn('JPX images (which do not require color spaces)'); <del> colorSpace = Name.get('DeviceRGB'); <add> info('JPX images (which do not require color spaces)'); <add> switch (image.numComps) { <add> case 1: <add> colorSpace = Name.get('DeviceGray'); <add> break; <add> case 3: <add> colorSpace = Name.get('DeviceRGB'); <add> break; <add> default: <add> // TODO: Find out how four color channels are handled. CMYK? Alpha? <add> error('JPX images with ' + this.numComps + <add> ' color components not supported.'); <add> } <ide> } <ide> this.colorSpace = ColorSpace.parse(colorSpace, xref, res); <ide> this.numComps = this.colorSpace.numComps; <ide><path>src/core/jpx.js <ide> var JpxImage = (function JpxImageClosure() { <ide> 'HL': 1, <ide> 'HH': 2 <ide> }; <del> var TransformType = { <del> IRREVERSIBLE: 0, <del> REVERSIBLE: 1 <del> }; <ide> function JpxImage() { <ide> this.failOnCorruptedImage = false; <ide> } <ide> var JpxImage = (function JpxImageClosure() { <ide> } <ide> } <ide> }, <add> parseImageProperties: function JpxImage_parseImageProperties(data, start, <add> end) { <add> try { <add> var position = start; <add> while (position + 40 < end) { <add> var code = readUint16(data, position); <add> // Image and tile size (SIZ) <add> if (code == 0xFF51) { <add> var Xsiz = readUint32(data, position + 6); <add> var Ysiz = readUint32(data, position + 10); <add> var XOsiz = readUint32(data, position + 14); <add> var YOsiz = readUint32(data, position + 18); <add> var Csiz = readUint16(data, position + 38); <add> this.width = Xsiz - XOsiz; <add> this.height = Ysiz - YOsiz; <add> this.componentsCount = Csiz; <add> // Results are always returned as UInt8Arrays <add> this.bitsPerComponent = 8; <add> return; <add> } <add> position += 1; <add> } <add> throw 'No size marker found in JPX stream'; <add> } catch (e) { <add> if (this.failOnCorruptedImage) { <add> error('JPX error: ' + e); <add> } else { <add> warn('JPX error: ' + e + '. Trying to recover'); <add> } <add> } <add> }, <ide> parseCodestream: function JpxImage_parseCodestream(data, start, end) { <ide> var context = {}; <ide> try { <ide> var JpxImage = (function JpxImageClosure() { <ide> cod.verticalyStripe = !!(blockStyle & 8); <ide> cod.predictableTermination = !!(blockStyle & 16); <ide> cod.segmentationSymbolUsed = !!(blockStyle & 32); <del> cod.transformation = data[j++]; <add> cod.reversibleTransformation = data[j++]; <ide> if (cod.entropyCoderWithCustomPrecincts) { <ide> var precinctsSizes = []; <ide> while (j < length + position) { <ide> var JpxImage = (function JpxImageClosure() { <ide> length = readUint16(data, position); <ide> // skipping content <ide> break; <add> case 0xFF53: // Coding style component (COC) <add> throw 'Codestream code 0xFF53 (COC) is not implemented'; <ide> default: <ide> throw 'Unknown codestream code: ' + code.toString(16); <ide> } <ide> var JpxImage = (function JpxImageClosure() { <ide> return position; <ide> } <ide> function copyCoefficients(coefficients, x0, y0, width, height, <del> delta, mb, codeblocks, transformation, <add> delta, mb, codeblocks, reversible, <ide> segmentationSymbolUsed) { <ide> for (var i = 0, ii = codeblocks.length; i < ii; ++i) { <ide> var codeblock = codeblocks[i]; <ide> var JpxImage = (function JpxImageClosure() { <ide> <ide> var offset = (codeblock.tbx0_ - x0) + (codeblock.tby0_ - y0) * width; <ide> var n, nb, correction, position = 0; <del> var irreversible = (transformation === TransformType.IRREVERSIBLE); <add> var irreversible = !reversible; <ide> var sign = bitModel.coefficentsSign; <ide> var magnitude = bitModel.coefficentsMagnitude; <ide> var bitsDecoded = bitModel.bitsDecoded; <add> var magnitudeCorrection = reversible ? 0 : 0.5; <ide> for (var j = 0; j < blockHeight; j++) { <ide> for (var k = 0; k < blockWidth; k++) { <del> n = (sign[position] ? -1 : 1) * magnitude[position]; <del> nb = bitsDecoded[position]; <del> correction = (irreversible || mb > nb) ? 1 << (mb - nb) : 1; <del> coefficients[offset++] = n * correction * delta; <add> var mag = magnitude[position]; <add> if (mag !== 0) { <add> n = sign[position] ? -(mag + magnitudeCorrection) : <add> (mag + magnitudeCorrection); <add> nb = bitsDecoded[position]; <add> correction = (irreversible || mb > nb) ? 1 << (mb - nb) : 1; <add> coefficients[offset] = n * correction * delta; <add> } <add> offset++; <ide> position++; <ide> } <ide> offset += width - blockWidth; <ide> var JpxImage = (function JpxImageClosure() { <ide> var spqcds = quantizationParameters.SPqcds; <ide> var scalarExpounded = quantizationParameters.scalarExpounded; <ide> var guardBits = quantizationParameters.guardBits; <del> var transformation = codingStyleParameters.transformation; <ide> var segmentationSymbolUsed = codingStyleParameters.segmentationSymbolUsed; <ide> var precision = context.components[c].precision; <ide> <del> var transformation = codingStyleParameters.transformation; <del> var transform = (transformation === TransformType.IRREVERSIBLE ? <del> new IrreversibleTransform() : new ReversibleTransform()); <add> var reversible = codingStyleParameters.reversibleTransformation; <add> var transform = (reversible ? new ReversibleTransform() : <add> new IrreversibleTransform()); <ide> <ide> var subbandCoefficients = []; <del> var k = 0, b = 0; <add> var b = 0; <ide> for (var i = 0; i <= decompositionLevelsCount; i++) { <ide> var resolution = component.resolutions[i]; <ide> <ide> var JpxImage = (function JpxImageClosure() { <ide> var gainLog2 = SubbandsGainLog2[subband.type]; <ide> <ide> // calulate quantization coefficient (Section E.1.1.1) <del> var delta = (transformation === TransformType.IRREVERSIBLE ? <del> Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048) : 1); <add> var delta = (reversible ? 1 : <add> Math.pow(2, precision + gainLog2 - epsilon) * (1 + mu / 2048)); <ide> var mb = (guardBits + epsilon - 1); <ide> <ide> var coefficients = new Float32Array(width * height); <ide> copyCoefficients(coefficients, subband.tbx0, subband.tby0, <del> width, height, delta, mb, subband.codeblocks, transformation, <add> width, height, delta, mb, subband.codeblocks, reversible, <ide> segmentationSymbolUsed); <ide> <ide> subbandCoefficients.push({ <ide> var JpxImage = (function JpxImageClosure() { <ide> // Section G.2.2 Inverse multi component transform <ide> if (tile.codingStyleDefaultParameters.multipleComponentTransform) { <ide> var component0 = tile.components[0]; <del> var transformation = component0.codingStyleParameters.transformation; <del> if (transformation === TransformType.IRREVERSIBLE) { <add> if (!component0.codingStyleParameters.reversibleTransformation) { <ide> // inverse irreversible multiple component transform <ide> var y0items = result[0].items; <ide> var y1items = result[1].items; <ide> var JpxImage = (function JpxImageClosure() { <ide> var items = new Float32Array(width * height); <ide> var i, j, k, l; <ide> <del> for (i = 0; i < llHeight; i++) { <del> var k = i * llWidth, l = i * 2 * width; <add> for (i = 0, k = 0; i < llHeight; i++) { <add> l = i * 2 * width; <ide> for (var j = 0; j < llWidth; j++, k++, l += 2) { <ide> items[l] = llItems[k]; <ide> } <ide> } <del> for (i = 0; i < hlHeight; i++) { <del> k = i * hlWidth; l = i * 2 * width + 1; <add> for (i = 0, k = 0; i < hlHeight; i++) { <add> l = i * 2 * width + 1; <ide> for (j = 0; j < hlWidth; j++, k++, l += 2) { <ide> items[l] = hlItems[k]; <ide> } <ide> } <del> for (i = 0; i < lhHeight; i++) { <del> k = i * lhWidth; l = (i * 2 + 1) * width; <add> for (i = 0, k = 0; i < lhHeight; i++) { <add> l = (i * 2 + 1) * width; <ide> for (j = 0; j < lhWidth; j++, k++, l += 2) { <ide> items[l] = lhItems[k]; <ide> } <ide> } <del> for (i = 0; i < hhHeight; i++) { <del> k = i * hhWidth; l = (i * 2 + 1) * width + 1; <add> for (i = 0, k = 0; i < hhHeight; i++) { <add> l = (i * 2 + 1) * width + 1; <ide> for (j = 0; j < hhWidth; j++, k++, l += 2) { <ide> items[l] = hhItems[k]; <ide> }
2
Mixed
Javascript
remove unused vars from the test execution scope
63d0a2682fc7ac473ed6340f68e6f05273bc7c5e
<ide><path>client/src/client/frame-runner.js <ide> if (window.frameElement && window.frameElement.id === testId) { <ide> } <ide> <ide> function initTestFrame() { <del> const frameReady = document.__frameReady; <del> const source = document.__source; <del> const __getUserInput = document.__getUserInput || (x => x); <add> const code = (document.__source || '').slice(0); <add> if (!document.__getUserInput) { <add> document.__getUserInput = () => code; <add> } <ide> <del> // Fake Deep Equal dependency <ide> /* eslint-disable no-unused-vars */ <add> // Fake Deep Equal dependency <ide> const DeepEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b); <ide> <ide> // Hardcode Deep Freeze dependency <ide> function initTestFrame() { <ide> }; <ide> <ide> const assert = chai.assert; <del> const getUserInput = __getUserInput; <add> /* eslint-enable no-unused-vars */ <ide> <ide> if (document.Enzyme) { <ide> window.Enzyme = document.Enzyme; <ide> } <ide> <ide> document.__runTest = async function runTests(testString) { <del> /* eslint-disable no-unused-vars */ <del> const code = source.slice(0); <del> const editor = { <del> getValue() { <del> return source; <del> } <del> }; <del> /* eslint-disable no-unused-vars */ <ide> // uncomment the following line to inspect <ide> // the frame-runner as it runs tests <ide> // make sure the dev tools console is open <ide> // debugger; <ide> try { <del> /* eslint-disable no-eval */ <ide> // eval test string to actual JavaScript <ide> // This return can be a function <ide> // i.e. function() { assert(true, 'happy coding'); } <add> // eslint-disable-next-line no-eval <ide> const test = eval(testString); <del> /* eslint-enable no-eval */ <ide> if (typeof test === 'function') { <del> await test(getUserInput); <add> await test(document.__getUserInput); <ide> } <ide> return { pass: true }; <ide> } catch (err) { <ide> function initTestFrame() { <ide> }; <ide> <ide> // notify that the window methods are ready to run <del> frameReady(); <add> document.__frameReady(); <ide> } <ide><path>curriculum/challenges/english/03-front-end-libraries/react-and-redux/moving-forward-from-here.english.md <ide> Log the message <code>'Now I know React and Redux!'</code> to the console. <ide> ```yml <ide> tests: <ide> - text: The message <code>Now I know React and Redux!</code> should be logged to the console. <del> testString: assert(editor.getValue().includes('console.log("Now I know React and Redux!")') || editor.getValue().includes('console.log(\'Now I know React and Redux!\')'), 'The message <code>Now I know React and Redux!</code> should be logged to the console.'); <add> testString: getUserInput => assert(/console.log\(("|')Now I know React and Redux!\1\)/.test(getUserInput('index')), 'The message <code>Now I know React and Redux!</code> should be logged to the console.'); <ide> <ide> ``` <ide>
2
Java
Java
fix classcastexception when setting media types
9f9f1ed2533110081c4a62b20d2b5658c8a68496
<ide><path>spring-web/src/main/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBean.java <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.Map.Entry; <ide> import java.util.Properties; <ide> <ide> import javax.servlet.ServletContext; <ide> <ide> private boolean ignoreAcceptHeader = false; <ide> <del> private Properties mediaTypes = new Properties(); <add> private Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); <ide> <ide> private Boolean useJaf; <ide> <ide> <ide> private ServletContext servletContext; <ide> <del> <ide> /** <ide> * Indicate whether the extension of the request path should be used to determine <ide> * the requested media type with the <em>highest priority</em>. <ide> public void setFavorPathExtension(boolean favorPathExtension) { <ide> } <ide> <ide> /** <del> * Add mappings from file extensions to media types. <del> * <p>If this property is not set, the Java Action Framework, if available, may <del> * still be used in conjunction with {@link #setFavorPathExtension(boolean)}. <add> * Add mappings from file extensions to media types represented as strings. <add> * <p>When this mapping is not set or when an extension is not found, the Java <add> * Action Framework, if available, may be used if enabled via <add> * {@link #setFavorPathExtension(boolean)}. <add> * <add> * @see #addMediaType(String, MediaType) <add> * @see #addMediaTypes(Map) <ide> */ <ide> public void setMediaTypes(Properties mediaTypes) { <ide> if (!CollectionUtils.isEmpty(mediaTypes)) { <del> for (Map.Entry<Object, Object> entry : mediaTypes.entrySet()) { <del> String extension = ((String) entry.getKey()).toLowerCase(Locale.ENGLISH); <add> for (Entry<Object, Object> entry : mediaTypes.entrySet()) { <add> String extension = ((String)entry.getKey()).toLowerCase(Locale.ENGLISH); <ide> this.mediaTypes.put(extension, MediaType.valueOf((String) entry.getValue())); <ide> } <ide> } <ide> } <ide> <del> public Properties getMediaTypes() { <del> return this.mediaTypes; <add> /** <add> * Add a mapping from a file extension to a media type. <add> * <p>If no mapping is added or when an extension is not found, the Java <add> * Action Framework, if available, may be used if enabled via <add> * {@link #setFavorPathExtension(boolean)}. <add> */ <add> public void addMediaType(String fileExtension, MediaType mediaType) { <add> this.mediaTypes.put(fileExtension, mediaType); <add> } <add> <add> /** <add> * Add mappings from file extensions to media types. <add> * <p>If no mappings are added or when an extension is not found, the Java <add> * Action Framework, if available, may be used if enabled via <add> * {@link #setFavorPathExtension(boolean)}. <add> */ <add> public void addMediaTypes(Map<String, MediaType> mediaTypes) { <add> if (mediaTypes != null) { <add> this.mediaTypes.putAll(mediaTypes); <add> } <ide> } <ide> <ide> /** <ide> * Indicate whether to use the Java Activation Framework as a fallback option <ide> * to map from file extensions to media types. This is used only when <ide> * {@link #setFavorPathExtension(boolean)} is set to {@code true}. <ide> * <p>The default value is {@code true}. <add> * <ide> * @see #parameterName <ide> * @see #setMediaTypes(Properties) <ide> */ <ide> public void setUseJaf(boolean useJaf) { <ide> * {@code "application/pdf"} regardless of the {@code Accept} header. <ide> * <p>To use this option effectively you must also configure the MediaType <ide> * type mappings via {@link #setMediaTypes(Properties)}. <add> * <ide> * @see #setParameterName(String) <ide> */ <ide> public void setFavorParameter(boolean favorParameter) { <ide> public void setIgnoreAcceptHeader(boolean ignoreAcceptHeader) { <ide> /** <ide> * Set the default content type. <ide> * <p>This content type will be used when neither the request path extension, <del> * nor a request parameter, nor the {@code Accept} header could help determine <del> * the requested content type. <add> * nor a request parameter, nor the {@code Accept} header could help <add> * determine the requested content type. <ide> */ <ide> public void setDefaultContentType(MediaType defaultContentType) { <ide> this.defaultContentType = defaultContentType; <ide> public void setServletContext(ServletContext servletContext) { <ide> public void afterPropertiesSet() throws Exception { <ide> List<ContentNegotiationStrategy> strategies = new ArrayList<ContentNegotiationStrategy>(); <ide> <del> Map<String, MediaType> mediaTypesMap = new HashMap<String, MediaType>(); <del> CollectionUtils.mergePropertiesIntoMap(this.mediaTypes, mediaTypesMap); <del> <ide> if (this.favorPathExtension) { <ide> PathExtensionContentNegotiationStrategy strategy; <ide> if (this.servletContext != null) { <del> strategy = new ServletPathExtensionContentNegotiationStrategy(this.servletContext, mediaTypesMap); <del> } <del> else { <del> strategy = new PathExtensionContentNegotiationStrategy(mediaTypesMap); <add> strategy = new ServletPathExtensionContentNegotiationStrategy(this.servletContext, this.mediaTypes); <add> } else { <add> strategy = new PathExtensionContentNegotiationStrategy(this.mediaTypes); <ide> } <ide> if (this.useJaf != null) { <ide> strategy.setUseJaf(this.useJaf); <ide> public void afterPropertiesSet() throws Exception { <ide> } <ide> <ide> if (this.favorParameter) { <del> ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(mediaTypesMap); <add> ParameterContentNegotiationStrategy strategy = new ParameterContentNegotiationStrategy(this.mediaTypes); <ide> strategy.setParameterName(this.parameterName); <ide> strategies.add(strategy); <ide> } <ide><path>spring-web/src/test/java/org/springframework/web/accept/ContentNegotiationManagerFactoryBeanTests.java <ide> <ide> import java.util.Arrays; <ide> import java.util.Collections; <del>import java.util.Properties; <add>import java.util.HashMap; <add>import java.util.Map; <ide> <ide> import org.junit.Before; <ide> import org.junit.Test; <ide> public void defaultSettings() throws Exception { <ide> <ide> @Test <ide> public void addMediaTypes() throws Exception { <del> Properties mediaTypes = new Properties(); <del> mediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE); <del> this.factoryBean.setMediaTypes(mediaTypes); <add> Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); <add> mediaTypes.put("json", MediaType.APPLICATION_JSON); <add> this.factoryBean.addMediaTypes(mediaTypes); <ide> <ide> this.factoryBean.afterPropertiesSet(); <ide> ContentNegotiationManager manager = this.factoryBean.getObject(); <ide> public void addMediaTypes() throws Exception { <ide> public void favorParameter() throws Exception { <ide> this.factoryBean.setFavorParameter(true); <ide> <del> Properties mediaTypes = new Properties(); <del> mediaTypes.put("json", MediaType.APPLICATION_JSON_VALUE); <del> this.factoryBean.setMediaTypes(mediaTypes); <add> Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); <add> mediaTypes.put("json", MediaType.APPLICATION_JSON); <add> this.factoryBean.addMediaTypes(mediaTypes); <ide> <ide> this.factoryBean.afterPropertiesSet(); <ide> ContentNegotiationManager manager = this.factoryBean.getObject(); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ContentNegotiationConfigurer.java <ide> */ <ide> package org.springframework.web.servlet.config.annotation; <ide> <add>import java.util.HashMap; <ide> import java.util.Map; <ide> <ide> import javax.servlet.ServletContext; <ide> */ <ide> public class ContentNegotiationConfigurer { <ide> <del> private ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean(); <add> private final ContentNegotiationManagerFactoryBean factoryBean = new ContentNegotiationManagerFactoryBean(); <add> <add> private final Map<String, MediaType> mediaTypes = new HashMap<String, MediaType>(); <ide> <ide> <ide> /** <ide> public ContentNegotiationConfigurer favorPathExtension(boolean favorPathExtensio <ide> * still be used in conjunction with {@link #favorPathExtension(boolean)}. <ide> */ <ide> public ContentNegotiationConfigurer mediaType(String extension, MediaType mediaType) { <del> this.factoryBean.getMediaTypes().put(extension, mediaType); <add> this.mediaTypes.put(extension, mediaType); <ide> return this; <ide> } <ide> <ide> public ContentNegotiationConfigurer mediaType(String extension, MediaType mediaT <ide> */ <ide> public ContentNegotiationConfigurer mediaTypes(Map<String, MediaType> mediaTypes) { <ide> if (mediaTypes != null) { <del> this.factoryBean.getMediaTypes().putAll(mediaTypes); <add> this.mediaTypes.putAll(mediaTypes); <ide> } <ide> return this; <ide> } <ide> public ContentNegotiationConfigurer mediaTypes(Map<String, MediaType> mediaTypes <ide> * still be used in conjunction with {@link #favorPathExtension(boolean)}. <ide> */ <ide> public ContentNegotiationConfigurer replaceMediaTypes(Map<String, MediaType> mediaTypes) { <del> this.factoryBean.getMediaTypes().clear(); <add> this.mediaTypes.clear(); <ide> mediaTypes(mediaTypes); <ide> return this; <ide> } <ide> public ContentNegotiationConfigurer defaultContentType(MediaType defaultContentT <ide> * Return the configured {@link ContentNegotiationManager} instance <ide> */ <ide> protected ContentNegotiationManager getContentNegotiationManager() throws Exception { <add> if (!this.mediaTypes.isEmpty()) { <add> this.factoryBean.addMediaTypes(mediaTypes); <add> } <ide> this.factoryBean.afterPropertiesSet(); <ide> return this.factoryBean.getObject(); <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/ContentNegotiatingViewResolver.java <ide> import java.util.List; <ide> import java.util.Locale; <ide> import java.util.Map; <add>import java.util.Properties; <ide> import java.util.Set; <ide> <ide> import javax.activation.FileTypeMap; <ide> public void setIgnoreAcceptHeader(boolean ignoreAcceptHeader) { <ide> @Deprecated <ide> public void setMediaTypes(Map<String, String> mediaTypes) { <ide> if (mediaTypes != null) { <del> this.cnManagerFactoryBean.getMediaTypes().putAll(mediaTypes); <add> Properties props = new Properties(); <add> props.putAll(mediaTypes); <add> this.cnManagerFactoryBean.setMediaTypes(props); <ide> } <ide> } <ide>
4
Python
Python
add unpack_inputs decorator to mbart
9042dfe35caa2b6ff0e51d554fa50c795558e488
<ide><path>src/transformers/models/mbart/modeling_tf_mbart.py <ide> TFPreTrainedModel, <ide> TFSharedEmbeddings, <ide> TFWrappedEmbeddings, <del> input_processing, <ide> keras_serializable, <add> unpack_inputs, <ide> ) <ide> from ...tf_utils import shape_list <ide> from ...utils import logging <ide> def get_embed_tokens(self): <ide> def set_embed_tokens(self, embed_tokens): <ide> self.embed_tokens = embed_tokens <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> input_ids=None, <ide> def call( <ide> Whether or not to use the model in training mode (some modules like dropout modules have different <ide> behaviors between training and evaluation). <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <del> attention_mask=attention_mask, <del> head_mask=head_mask, <del> inputs_embeds=inputs_embeds, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if inputs["input_ids"] is not None and inputs["inputs_embeds"] is not None: <add> if input_ids is not None and inputs_embeds is not None: <ide> raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") <del> elif inputs["input_ids"] is not None: <del> input_shape = shape_list(inputs["input_ids"]) <del> elif inputs["inputs_embeds"] is not None: <del> input_shape = shape_list(inputs["inputs_embeds"])[:-1] <add> elif input_ids is not None: <add> input_shape = shape_list(input_ids) <add> elif inputs_embeds is not None: <add> input_shape = shape_list(inputs_embeds)[:-1] <ide> else: <ide> raise ValueError("You have to specify either input_ids or inputs_embeds") <ide> <del> if inputs["inputs_embeds"] is None: <del> inputs["inputs_embeds"] = self.embed_tokens(inputs["input_ids"]) * self.embed_scale <add> if inputs_embeds is None: <add> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <ide> <ide> embed_pos = self.embed_positions(input_shape) <del> hidden_states = inputs["inputs_embeds"] + embed_pos <add> hidden_states = inputs_embeds + embed_pos <ide> hidden_states = self.layernorm_embedding(hidden_states) <del> hidden_states = self.dropout(hidden_states, training=inputs["training"]) <add> hidden_states = self.dropout(hidden_states, training=training) <ide> <ide> # check attention mask and invert <del> if inputs["attention_mask"] is not None: <add> if attention_mask is not None: <ide> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] <del> attention_mask = _expand_mask(inputs["attention_mask"]) <add> attention_mask = _expand_mask(attention_mask) <ide> else: <ide> attention_mask = None <ide> <del> encoder_states = () if inputs["output_hidden_states"] else None <del> all_attentions = () if inputs["output_attentions"] else None <add> encoder_states = () if output_hidden_states else None <add> all_attentions = () if output_attentions else None <ide> <ide> # check if head_mask has a correct number of layers specified if desired <ide> # The tf.debugging asserts are not compliant with XLA then they <ide> # have to be disabled in other modes than eager. <del> if inputs["head_mask"] is not None and tf.executing_eagerly(): <add> if head_mask is not None and tf.executing_eagerly(): <ide> tf.debugging.assert_equal( <del> shape_list(inputs["head_mask"])[0], <add> shape_list(head_mask)[0], <ide> len(self.layers), <del> message=f"The head_mask should be specified for {len(self.layers)} layers, but it is for {shape_list(inputs['head_mask'])[0]}.", <add> message=f"The head_mask should be specified for {len(self.layers)} layers, but it is for {shape_list(head_mask)[0]}.", <ide> ) <ide> <ide> # encoder layers <ide> for idx, encoder_layer in enumerate(self.layers): <ide> <del> if inputs["output_hidden_states"]: <add> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <ide> dropout_probability = random.uniform(0, 1) <del> if inputs["training"] and (dropout_probability < self.layerdrop): # skip the layer <add> if training and (dropout_probability < self.layerdrop): # skip the layer <ide> continue <ide> <ide> hidden_states, attn = encoder_layer( <ide> hidden_states, <ide> attention_mask, <del> inputs["head_mask"][idx] if inputs["head_mask"] is not None else None, <add> head_mask[idx] if head_mask is not None else None, <ide> ) <ide> <del> if inputs["output_attentions"]: <add> if output_attentions: <ide> all_attentions += (attn,) <ide> <ide> hidden_states = self.layer_norm(hidden_states) <ide> <del> if inputs["output_hidden_states"]: <add> if output_hidden_states: <ide> encoder_states = encoder_states + (hidden_states,) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None) <ide> return TFBaseModelOutput( <ide> last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions <ide> def get_embed_tokens(self): <ide> def set_embed_tokens(self, embed_tokens): <ide> self.embed_tokens = embed_tokens <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> input_ids=None, <ide> def call( <ide> Whether or not to use the model in training mode (some modules like dropout modules have different <ide> behaviors between training and evaluation). <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <del> attention_mask=attention_mask, <del> encoder_hidden_states=encoder_hidden_states, <del> encoder_attention_mask=encoder_attention_mask, <del> head_mask=head_mask, <del> cross_attn_head_mask=cross_attn_head_mask, <del> inputs_embeds=inputs_embeds, <del> past_key_values=past_key_values, <del> use_cache=use_cache, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if inputs["input_ids"] is not None and inputs["inputs_embeds"] is not None: <add> if input_ids is not None and inputs_embeds is not None: <ide> raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") <del> elif inputs["input_ids"] is not None: <del> input_shape = shape_list(inputs["input_ids"]) <del> elif inputs["inputs_embeds"] is not None: <del> input_shape = shape_list(inputs["inputs_embeds"])[:-1] <add> elif input_ids is not None: <add> input_shape = shape_list(input_ids) <add> elif inputs_embeds is not None: <add> input_shape = shape_list(inputs_embeds)[:-1] <ide> else: <ide> raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") <ide> <del> past_key_values_length = ( <del> shape_list(inputs["past_key_values"][0][0])[2] if inputs["past_key_values"] is not None else 0 <del> ) <add> past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0 <ide> <ide> # embed positions <ide> positions = self.embed_positions(input_shape, past_key_values_length) <ide> <del> if inputs["inputs_embeds"] is None: <del> inputs["inputs_embeds"] = self.embed_tokens(inputs["input_ids"]) * self.embed_scale <add> if inputs_embeds is None: <add> inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale <ide> <del> hidden_states = inputs["inputs_embeds"] <add> hidden_states = inputs_embeds <ide> <ide> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] <ide> if input_shape[-1] > 1: <ide> def call( <ide> tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1] <ide> ) <ide> <del> if inputs["attention_mask"] is not None: <del> combined_attention_mask = combined_attention_mask + _expand_mask( <del> inputs["attention_mask"], tgt_len=input_shape[-1] <del> ) <add> if attention_mask is not None: <add> combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1]) <ide> <del> if inputs["encoder_hidden_states"] is not None and inputs["encoder_attention_mask"] is not None: <add> if encoder_hidden_states is not None and encoder_attention_mask is not None: <ide> # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] <del> inputs["encoder_attention_mask"] = _expand_mask(inputs["encoder_attention_mask"], tgt_len=input_shape[-1]) <add> encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1]) <ide> <ide> hidden_states = self.layernorm_embedding(hidden_states + positions) <del> hidden_states = self.dropout(hidden_states, training=inputs["training"]) <add> hidden_states = self.dropout(hidden_states, training=training) <ide> <ide> # decoder layers <del> all_hidden_states = () if inputs["output_hidden_states"] else None <del> all_self_attns = () if inputs["output_attentions"] else None <del> all_cross_attns = () if (inputs["output_attentions"] and inputs["encoder_hidden_states"] is not None) else None <del> present_key_values = () if inputs["use_cache"] else None <add> all_hidden_states = () if output_hidden_states else None <add> all_self_attns = () if output_attentions else None <add> all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None <add> present_key_values = () if use_cache else None <ide> <ide> # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired <ide> # The tf.debugging asserts are not compliant with XLA then they <ide> # have to be disabled in other modes than eager. <del> for attn_mask in ["head_mask", "cross_attn_head_mask"]: <del> if inputs[attn_mask] is not None and tf.executing_eagerly(): <add> for attn_mask in [head_mask, cross_attn_head_mask]: <add> if attn_mask is not None and tf.executing_eagerly(): <ide> tf.debugging.assert_equal( <del> shape_list(inputs[attn_mask])[0], <add> shape_list(attn_mask)[0], <ide> len(self.layers), <del> message=f"The {attn_mask} should be specified for {len(self.layers)} layers, but it is for {shape_list(inputs[attn_mask])[0]}.", <add> message=f"The {attn_mask} should be specified for {len(self.layers)} layers, but it is for {shape_list(attn_mask)[0]}.", <ide> ) <ide> <ide> for idx, decoder_layer in enumerate(self.layers): <ide> # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) <del> if inputs["output_hidden_states"]: <add> if output_hidden_states: <ide> all_hidden_states += (hidden_states,) <ide> dropout_probability = random.uniform(0, 1) <ide> <del> if inputs["training"] and (dropout_probability < self.layerdrop): <add> if training and (dropout_probability < self.layerdrop): <ide> continue <ide> <del> past_key_value = inputs["past_key_values"][idx] if inputs["past_key_values"] is not None else None <add> past_key_value = past_key_values[idx] if past_key_values is not None else None <ide> <ide> hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer( <ide> hidden_states, <ide> attention_mask=combined_attention_mask, <del> encoder_hidden_states=inputs["encoder_hidden_states"], <del> encoder_attention_mask=inputs["encoder_attention_mask"], <del> layer_head_mask=inputs["head_mask"][idx] if inputs["head_mask"] is not None else None, <del> cross_attn_layer_head_mask=inputs["cross_attn_head_mask"][idx] <del> if inputs["cross_attn_head_mask"] is not None <del> else None, <add> encoder_hidden_states=encoder_hidden_states, <add> encoder_attention_mask=encoder_attention_mask, <add> layer_head_mask=head_mask[idx] if head_mask is not None else None, <add> cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None, <ide> past_key_value=past_key_value, <ide> ) <ide> <del> if inputs["use_cache"]: <add> if use_cache: <ide> present_key_values += (present_key_value,) <ide> <del> if inputs["output_attentions"]: <add> if output_attentions: <ide> all_self_attns += (layer_self_attn,) <ide> <del> if inputs["encoder_hidden_states"] is not None: <add> if encoder_hidden_states is not None: <ide> all_cross_attns += (layer_cross_attn,) <ide> <ide> hidden_states = self.layer_norm(hidden_states) <ide> <del> if inputs["output_hidden_states"]: <add> if output_hidden_states: <ide> all_hidden_states += (hidden_states,) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns <ide> else: <ide> return TFBaseModelOutputWithPastAndCrossAttentions( <ide> def set_input_embeddings(self, new_embeddings): <ide> self.encoder.set_embed_tokens(embed_tokens) <ide> self.decoder.set_embed_tokens(embed_tokens) <ide> <add> @unpack_inputs <ide> def call( <ide> self, <ide> input_ids=None, <ide> def call( <ide> training=False, <ide> **kwargs <ide> ): <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <del> attention_mask=attention_mask, <del> decoder_input_ids=decoder_input_ids, <del> decoder_attention_mask=decoder_attention_mask, <del> head_mask=head_mask, <del> decoder_head_mask=decoder_head_mask, <del> cross_attn_head_mask=cross_attn_head_mask, <del> encoder_outputs=encoder_outputs, <del> past_key_values=past_key_values, <del> inputs_embeds=inputs_embeds, <del> decoder_inputs_embeds=decoder_inputs_embeds, <del> use_cache=use_cache, <del> output_attentions=output_attentions, <del> output_hidden_states=output_hidden_states, <del> return_dict=return_dict, <del> training=training, <del> kwargs_call=kwargs, <del> ) <ide> <del> if inputs["decoder_input_ids"] is None and inputs["decoder_inputs_embeds"] is None: <del> inputs["use_cache"] = False <add> if decoder_input_ids is None and decoder_inputs_embeds is None: <add> use_cache = False <ide> <del> inputs["output_hidden_states"] = ( <del> inputs["output_hidden_states"] <del> if inputs["output_hidden_states"] is not None <del> else self.config.output_hidden_states <add> output_hidden_states = ( <add> output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states <ide> ) <ide> <del> if inputs["decoder_input_ids"] is None and inputs["input_ids"] is not None: <del> inputs["decoder_input_ids"] = shift_tokens_right(inputs["input_ids"], self.config.pad_token_id) <del> <del> if inputs["encoder_outputs"] is None: <del> inputs["encoder_outputs"] = self.encoder( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> head_mask=inputs["head_mask"], <del> inputs_embeds=inputs["inputs_embeds"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> if decoder_input_ids is None and input_ids is not None: <add> decoder_input_ids = shift_tokens_right(input_ids, self.config.pad_token_id) <add> <add> if encoder_outputs is None: <add> encoder_outputs = self.encoder( <add> input_ids=input_ids, <add> attention_mask=attention_mask, <add> head_mask=head_mask, <add> inputs_embeds=inputs_embeds, <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True <del> elif inputs["return_dict"] and not isinstance(inputs["encoder_outputs"], TFBaseModelOutput): <del> inputs["encoder_outputs"] = TFBaseModelOutput( <del> last_hidden_state=inputs["encoder_outputs"][0], <del> hidden_states=inputs["encoder_outputs"][1] if len(inputs["encoder_outputs"]) > 1 else None, <del> attentions=inputs["encoder_outputs"][2] if len(inputs["encoder_outputs"]) > 2 else None, <add> elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput): <add> encoder_outputs = TFBaseModelOutput( <add> last_hidden_state=encoder_outputs[0], <add> hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None, <add> attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None, <ide> ) <ide> # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False <del> elif not inputs["return_dict"] and not isinstance(inputs["encoder_outputs"], tuple): <del> inputs["encoder_outputs"] = inputs["encoder_outputs"].to_tuple() <add> elif not return_dict and not isinstance(encoder_outputs, tuple): <add> encoder_outputs = encoder_outputs.to_tuple() <ide> <ide> decoder_outputs = self.decoder( <del> inputs["decoder_input_ids"], <del> attention_mask=inputs["decoder_attention_mask"], <del> encoder_hidden_states=inputs["encoder_outputs"][0], <del> encoder_attention_mask=inputs["attention_mask"], <del> head_mask=inputs["decoder_head_mask"], <del> cross_attn_head_mask=inputs["cross_attn_head_mask"], <del> past_key_values=inputs["past_key_values"], <del> inputs_embeds=inputs["decoder_inputs_embeds"], <del> use_cache=inputs["use_cache"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <add> decoder_input_ids, <add> attention_mask=decoder_attention_mask, <add> encoder_hidden_states=encoder_outputs[0], <add> encoder_attention_mask=attention_mask, <add> head_mask=decoder_head_mask, <add> cross_attn_head_mask=cross_attn_head_mask, <add> past_key_values=past_key_values, <add> inputs_embeds=decoder_inputs_embeds, <add> use_cache=use_cache, <add> output_attentions=output_attentions, <add> output_hidden_states=output_hidden_states, <add> return_dict=return_dict, <add> training=training, <ide> ) <ide> <del> if not inputs["return_dict"]: <del> return decoder_outputs + inputs["encoder_outputs"] <add> if not return_dict: <add> return decoder_outputs + encoder_outputs <ide> <ide> return TFSeq2SeqModelOutput( <ide> last_hidden_state=decoder_outputs.last_hidden_state, <ide> past_key_values=decoder_outputs.past_key_values, <ide> decoder_hidden_states=decoder_outputs.hidden_states, <ide> decoder_attentions=decoder_outputs.attentions, <ide> cross_attentions=decoder_outputs.cross_attentions, <del> encoder_last_hidden_state=inputs["encoder_outputs"].last_hidden_state, <del> encoder_hidden_states=inputs["encoder_outputs"].hidden_states, <del> encoder_attentions=inputs["encoder_outputs"].attentions, <add> encoder_last_hidden_state=encoder_outputs.last_hidden_state, <add> encoder_hidden_states=encoder_outputs.hidden_states, <add> encoder_attentions=encoder_outputs.attentions, <ide> ) <ide> <ide> <ide> def get_encoder(self): <ide> def get_decoder(self): <ide> return self.model.decoder <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING.format("batch_size, sequence_length")) <ide> @add_code_sample_docstrings( <ide> processor_class=_TOKENIZER_FOR_DOC, <ide> def call( <ide> training=False, <ide> **kwargs <ide> ): <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <add> <add> outputs = self.model( <ide> input_ids=input_ids, <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <ide> def call( <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> outputs = self.model( <del> input_ids=inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> decoder_input_ids=inputs["decoder_input_ids"], <del> decoder_attention_mask=inputs["decoder_attention_mask"], <del> head_mask=inputs["head_mask"], <del> decoder_head_mask=inputs["decoder_head_mask"], <del> cross_attn_head_mask=inputs["cross_attn_head_mask"], <del> encoder_outputs=inputs["encoder_outputs"], <del> past_key_values=inputs["past_key_values"], <del> inputs_embeds=inputs["inputs_embeds"], <del> decoder_inputs_embeds=inputs["decoder_inputs_embeds"], <del> use_cache=inputs["use_cache"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> <ide> return outputs <ide> def get_bias(self): <ide> def set_bias(self, value): <ide> self.final_logits_bias = value["final_logits_bias"] <ide> <add> @unpack_inputs <ide> @add_start_docstrings_to_model_forward(MBART_INPUTS_DOCSTRING) <ide> @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC) <ide> @add_end_docstrings(MBART_GENERATION_EXAMPLE) <ide> def call( <ide> Returns: <ide> <ide> """ <del> inputs = input_processing( <del> func=self.call, <del> config=self.config, <del> input_ids=input_ids, <add> <add> if labels is not None: <add> labels = tf.where( <add> labels == self.config.pad_token_id, <add> tf.fill(shape_list(labels), -100), <add> labels, <add> ) <add> use_cache = False <add> if decoder_input_ids is None: <add> decoder_input_ids = shift_tokens_right(labels, self.config.pad_token_id) <add> <add> outputs = self.model( <add> input_ids, <ide> attention_mask=attention_mask, <ide> decoder_input_ids=decoder_input_ids, <add> encoder_outputs=encoder_outputs, <ide> decoder_attention_mask=decoder_attention_mask, <ide> head_mask=head_mask, <ide> decoder_head_mask=decoder_head_mask, <ide> cross_attn_head_mask=cross_attn_head_mask, <del> encoder_outputs=encoder_outputs, <ide> past_key_values=past_key_values, <ide> inputs_embeds=inputs_embeds, <ide> decoder_inputs_embeds=decoder_inputs_embeds, <ide> use_cache=use_cache, <ide> output_attentions=output_attentions, <ide> output_hidden_states=output_hidden_states, <ide> return_dict=return_dict, <del> labels=labels, <ide> training=training, <del> kwargs_call=kwargs, <del> ) <del> <del> if inputs["labels"] is not None: <del> inputs["labels"] = tf.where( <del> inputs["labels"] == self.config.pad_token_id, <del> tf.fill(shape_list(inputs["labels"]), -100), <del> inputs["labels"], <del> ) <del> inputs["use_cache"] = False <del> if inputs["decoder_input_ids"] is None: <del> inputs["decoder_input_ids"] = shift_tokens_right(inputs["labels"], self.config.pad_token_id) <del> <del> outputs = self.model( <del> inputs["input_ids"], <del> attention_mask=inputs["attention_mask"], <del> decoder_input_ids=inputs["decoder_input_ids"], <del> encoder_outputs=inputs["encoder_outputs"], <del> decoder_attention_mask=inputs["decoder_attention_mask"], <del> head_mask=inputs["head_mask"], <del> decoder_head_mask=inputs["decoder_head_mask"], <del> cross_attn_head_mask=inputs["cross_attn_head_mask"], <del> past_key_values=inputs["past_key_values"], <del> inputs_embeds=inputs["inputs_embeds"], <del> decoder_inputs_embeds=inputs["decoder_inputs_embeds"], <del> use_cache=inputs["use_cache"], <del> output_attentions=inputs["output_attentions"], <del> output_hidden_states=inputs["output_hidden_states"], <del> return_dict=inputs["return_dict"], <del> training=inputs["training"], <ide> ) <ide> lm_logits = self.model.shared(outputs[0], mode="linear") <ide> lm_logits = lm_logits + self.final_logits_bias <del> masked_lm_loss = None if inputs["labels"] is None else self.hf_compute_loss(inputs["labels"], lm_logits) <add> masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits) <ide> <del> if not inputs["return_dict"]: <add> if not return_dict: <ide> output = (lm_logits,) + outputs[1:] <ide> return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output <ide> return TFSeq2SeqLMOutput(
1
Ruby
Ruby
use travel_to convention in existing test
59cb9e31fd9a2671697fb8d4b652b7a1b2a02a32
<ide><path>activesupport/test/time_zone_test.rb <ide> def test_unknown_timezones_delegation_to_tzinfo <ide> end <ide> <ide> def test_today <del> Time.stubs(:now).returns(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST <add> travel_to(Time.utc(2000, 1, 1, 4, 59, 59)) # 1 sec before midnight Jan 1 EST <ide> assert_equal Date.new(1999, 12, 31), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today <del> Time.stubs(:now).returns(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST <add> travel_to(Time.utc(2000, 1, 1, 5)) # midnight Jan 1 EST <ide> assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today <del> Time.stubs(:now).returns(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST <add> travel_to(Time.utc(2000, 1, 2, 4, 59, 59)) # 1 sec before midnight Jan 2 EST <ide> assert_equal Date.new(2000, 1, 1), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today <del> Time.stubs(:now).returns(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST <add> travel_to(Time.utc(2000, 1, 2, 5)) # midnight Jan 2 EST <ide> assert_equal Date.new(2000, 1, 2), ActiveSupport::TimeZone['Eastern Time (US & Canada)'].today <ide> end <ide>
1
Python
Python
fix flake8 styling
cb21d010dddaf482200c3f8b6fef482b938a53ac
<ide><path>libcloud/compute/drivers/softlayer.py <ide> crypto = False <ide> <ide> from libcloud.common.softlayer import SoftLayerConnection, SoftLayerException <del>from libcloud.common.types import LibcloudError <ide> from libcloud.compute.types import Provider, NodeState <ide> from libcloud.compute.base import NodeDriver, Node, NodeLocation, NodeSize, \ <ide> NodeImage, KeyPair <ide> def get_image(self, image_id): <ide> images = self.list_images() <ide> images = [image for image in images if image.id == image_id] <ide> if len(images) < 1: <del> raise SoftLayerException('could not find the image with id %s'\ <del> % image_id) <add> raise SoftLayerException('could not find the image with id %s' <add> % image_id) <ide> image = images[0] <ide> return image <ide>
1
Javascript
Javascript
use nonce attribute for inline script if provided
f1f83507dbf655ceb67a07b41a2765e00499add3
<ide><path>server/document.js <ide> export class Main extends Component { <ide> } <ide> <ide> export class NextScript extends Component { <add> static propTypes = { <add> nonce: PropTypes.string <add> } <add> <ide> static contextTypes = { <ide> _documentProps: PropTypes.any <ide> } <ide> export class NextScript extends Component { <ide> __NEXT_DATA__.chunks = chunks <ide> <ide> return <div> <del> {staticMarkup ? null : <script dangerouslySetInnerHTML={{ <add> {staticMarkup ? null : <script nonce={this.props.nonce} dangerouslySetInnerHTML={{ <ide> __html: ` <ide> __NEXT_DATA__ = ${htmlescape(__NEXT_DATA__)} <ide> module={}
1
Ruby
Ruby
eliminate key_generator ivar
197141a8c7461b79074e1f9ebaddc2990eea6bf8
<ide><path>actionpack/lib/action_dispatch/middleware/cookies.rb <ide> module ChainedCookieJars <ide> # cookies.permanent.signed[:remember_me] = current_user.id <ide> # # => Set-Cookie: remember_me=BAhU--848956038e692d7046deab32b7131856ab20e14e; path=/; expires=Sun, 16-Dec-2029 03:24:16 GMT <ide> def permanent <del> @permanent ||= PermanentCookieJar.new(self, @key_generator, @request) <add> @permanent ||= PermanentCookieJar.new(self, @request) <ide> end <ide> <ide> # Returns a jar that'll automatically generate a signed representation of cookie value and verify it when reading from <ide> def permanent <ide> def signed <ide> @signed ||= <ide> if upgrade_legacy_signed_cookies? <del> UpgradeLegacySignedCookieJar.new(self, @key_generator, @request) <add> UpgradeLegacySignedCookieJar.new(self, @request) <ide> else <del> SignedCookieJar.new(self, @key_generator, @request) <add> SignedCookieJar.new(self, @request) <ide> end <ide> end <ide> <ide> def signed <ide> def encrypted <ide> @encrypted ||= <ide> if upgrade_legacy_signed_cookies? <del> UpgradeLegacyEncryptedCookieJar.new(self, @key_generator, @request) <add> UpgradeLegacyEncryptedCookieJar.new(self, @request) <ide> else <del> EncryptedCookieJar.new(self, @key_generator, @request) <add> EncryptedCookieJar.new(self, @request) <ide> end <ide> end <ide> <ide> def signed_or_encrypted <ide> def upgrade_legacy_signed_cookies? <ide> @request.secret_token.present? && @request.secret_key_base.present? <ide> end <add> <add> def key_generator <add> @request.key_generator <add> end <ide> end <ide> <ide> # Passing the ActiveSupport::MessageEncryptor::NullSerializer downstream <ide> def self.build(req, cookies) <ide> end <ide> <ide> def initialize(key_generator, host = nil, secure = false, request) <del> @key_generator = key_generator <ide> @set_cookies = {} <ide> @delete_cookies = {} <ide> @host = host <ide> def write_cookie?(cookie) <ide> class PermanentCookieJar #:nodoc: <ide> include ChainedCookieJars <ide> <del> def initialize(parent_jar, key_generator, request) <add> def initialize(parent_jar, request) <ide> @parent_jar = parent_jar <del> @key_generator = key_generator <ide> @request = request <ide> end <ide> <ide> class SignedCookieJar #:nodoc: <ide> include ChainedCookieJars <ide> include SerializedCookieJars <ide> <del> def initialize(parent_jar, key_generator, request) <add> def initialize(parent_jar, request) <ide> @parent_jar = parent_jar <ide> @request = request <ide> secret = key_generator.generate_key(request.signed_cookie_salt) <ide> class EncryptedCookieJar #:nodoc: <ide> include ChainedCookieJars <ide> include SerializedCookieJars <ide> <del> def initialize(parent_jar, key_generator, request) <add> def initialize(parent_jar, request) <add> @request = request <add> <ide> if ActiveSupport::LegacyKeyGenerator === key_generator <ide> raise "You didn't set secrets.secret_key_base, which is required for this cookie jar. " + <ide> "Read the upgrade documentation to learn more about this new config option." <ide> end <ide> <ide> @parent_jar = parent_jar <del> @request = request <ide> secret = key_generator.generate_key(request.encrypted_cookie_salt || '') <ide> sign_secret = key_generator.generate_key(request.encrypted_signed_cookie_salt || '') <ide> @encryptor = ActiveSupport::MessageEncryptor.new(secret, sign_secret, digest: digest, serializer: ActiveSupport::MessageEncryptor::NullSerializer)
1
Javascript
Javascript
avoid allocations in executecommand()
6c698519cdb6d3fdcb561828f0ad52b3e45b114b
<ide><path>src/core/fonts.js <ide> var Type1CharString = (function Type1CharStringClosure() { <ide> if (keepStack) { <ide> this.stack.splice(start, howManyArgs); <ide> } else { <del> this.stack = []; <add> this.stack.length = 0; <ide> } <ide> return false; <ide> }
1
Text
Text
fix typo in fs.md
36bc8b905c78c57195aad13dc4f1012fbe3e5a06
<ide><path>doc/api/fs.md <ide> changes: <ide> * `bytesRead` {integer} <ide> * `buffer` {Buffer} <ide> <del>Similar to the `fs.read90` function, this version takes an optional `options` <del>object. If no `options` object is specified, it will default with the above <del>values. <add>Similar to the [`fs.read()`][] function, this version takes an optional <add>`options` object. If no `options` object is specified, it will default with the <add>above values. <ide> <ide> ### `fs.readdir(path[, options], callback)` <ide> <!-- YAML
1
Python
Python
remove unittest.main() in test modules
7e98e211f0e86e414b22946bd89391e49d2ea900
<ide><path>examples/summarization/test_utils_summarization.py <ide> def test_compute_token_type_ids(self): <ide> <ide> result = compute_token_type_ids(batch, separator) <ide> np.testing.assert_array_equal(result, expected) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>examples/test_examples.py <ide> def test_generation(self): <ide> with patch.object(sys, "argv", testargs + [model_type, model_name]): <ide> result = run_generation.main() <ide> self.assertGreaterEqual(len(result), 10) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>templates/adding_a_new_model/tests/test_modeling_tf_xxx.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import XxxConfig, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in ["xxx-base-uncased"]: <ide> model = TFXxxModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>templates/adding_a_new_model/tests/test_modeling_xxx.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(XXX_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = XxxModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>templates/adding_a_new_model/tests/test_tokenization_xxx.py <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <ide> import os <del>import unittest <ide> from io import open <ide> <ide> from transformers.tokenization_bert import VOCAB_FILES_NAMES, XxxTokenizer <ide> def test_full_tokenizer(self): <ide> tokens = tokenizer.tokenize("UNwant\u00E9d,running") <ide> self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"]) <ide> self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9]) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_configuration_common.py <ide> <ide> import json <ide> import os <del>import unittest <ide> <ide> from .tokenization_tests_commons import TemporaryDirectory <ide> <ide> def run_common_tests(self): <ide> self.create_and_test_config_to_json_string() <ide> self.create_and_test_config_to_json_file() <ide> self.create_and_test_config_from_and_save_pretrained() <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_hf_api.py <ide> def test_token_workflow(self): <ide> # ^^ not an error, we test that the <ide> # second call does not fail. <ide> self.assertEqual(HfFolder.get_token(), None) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_model_card.py <ide> def test_model_card_from_and_save_pretrained(self): <ide> model_card_second = ModelCard.from_pretrained(tmpdirname) <ide> <ide> self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_albert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = AlbertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_auto.py <ide> def test_from_pretrained_identifier(self): <ide> logging.basicConfig(level=logging.INFO) <ide> model = AutoModelWithLMHead.from_pretrained(SMALL_MODEL_IDENTIFIER) <ide> self.assertIsInstance(model, BertForMaskedLM) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_bert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(BERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = BertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_common.py <ide> def test_model_from_pretrained(self): <ide> self.assertEqual(model.config.output_attentions, True) <ide> self.assertEqual(model.config.output_hidden_states, True) <ide> self.assertEqual(model.config, config) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_ctrl.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(CTRL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = CTRLModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_distilbert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_for_token_classification(self): <ide> # for model_name in list(DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> # model = DistilBertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> # self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_encoder_decoder.py <ide> def test_model2model_from_pretrained_not_bert(self): <ide> <ide> with self.assertRaises(ValueError): <ide> _ = Model2Model.from_pretrained("does-not-exist") <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_gpt2.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(GPT2_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = GPT2Model.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_openai.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = OpenAIGPTModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_roberta.py <ide> def test_inference_classification_head(self): <ide> self.assertEqual(output.shape, expected_shape) <ide> expected_tensor = torch.Tensor([[-0.9469, 0.3913, 0.5118]]) <ide> self.assertTrue(torch.allclose(output, expected_tensor, atol=1e-3)) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_t5.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(T5_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = T5Model.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_albert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import AlbertConfig, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFAlbertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_auto.py <ide> def test_from_pretrained_identifier(self): <ide> logging.basicConfig(level=logging.INFO) <ide> model = TFAutoModelWithLMHead.from_pretrained(SMALL_MODEL_IDENTIFIER) <ide> self.assertIsInstance(model, TFBertForMaskedLM) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_bert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import BertConfig, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in ["bert-base-uncased"]: <ide> model = TFBertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_common.py <ide> def ids_tensor(shape, vocab_size, rng=None, name=None, dtype=None): <ide> output = tf.constant(values, shape=shape, dtype=dtype if dtype is not None else tf.int32) <ide> <ide> return output <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_ctrl.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import CTRLConfig, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_CTRL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFCTRLModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_distilbert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import DistilBertConfig, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_for_sequence_classification(self): <ide> # for model_name in list(DISTILBERT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> # model = DistilBertModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> # self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_gpt2.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import GPT2Config, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_GPT2_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFGPT2Model.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_openai_gpt.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import OpenAIGPTConfig, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFOpenAIGPTModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_roberta.py <ide> def test_inference_classification_head(self): <ide> self.assertEqual(list(output.numpy().shape), expected_shape) <ide> expected_tensor = tf.constant([[-0.9469, 0.3913, 0.5118]]) <ide> self.assertTrue(numpy.allclose(output.numpy(), expected_tensor.numpy(), atol=1e-3)) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_t5.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import T5Config, is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in ["t5-small"]: <ide> model = TFT5Model.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_transfo_xl.py <ide> from __future__ import absolute_import, division, print_function <ide> <ide> import random <del>import unittest <ide> <ide> from transformers import TransfoXLConfig, is_tf_available <ide> <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFTransfoXLModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_xlm.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_tf_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_XLM_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFXLMModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_tf_xlnet.py <ide> from __future__ import absolute_import, division, print_function <ide> <ide> import random <del>import unittest <ide> <ide> from transformers import XLNetConfig, is_tf_available <ide> <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TF_XLNET_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TFXLNetModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_transfo_xl.py <ide> from __future__ import absolute_import, division, print_function <ide> <ide> import random <del>import unittest <ide> <ide> from transformers import is_torch_available <ide> <ide> def test_model_from_pretrained(self): <ide> for model_name in list(TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = TransfoXLModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_xlm.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function <ide> <del>import unittest <del> <ide> from transformers import is_torch_available <ide> <ide> from .test_configuration_common import ConfigTester <ide> def test_model_from_pretrained(self): <ide> for model_name in list(XLM_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = XLMModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_modeling_xlnet.py <ide> from __future__ import absolute_import, division, print_function <ide> <ide> import random <del>import unittest <ide> <ide> from transformers import is_torch_available <ide> <ide> def test_model_from_pretrained(self): <ide> for model_name in list(XLNET_PRETRAINED_MODEL_ARCHIVE_MAP.keys())[:1]: <ide> model = XLNetModel.from_pretrained(model_name, cache_dir=CACHE_DIR) <ide> self.assertIsNotNone(model) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_optimization.py <ide> def test_warmup_cosine_hard_restart_scheduler(self): <ide> ) <ide> lrs_2 = unwrap_and_save_reload_schedule(scheduler, self.num_steps) <ide> self.assertListEqual([l[0] for l in lrs], [l[0] for l in lrs_2]) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_optimization_tf.py <ide> def apply_grad(): <ide> self.assertEqual(accumulator.step, 0) <ide> self.assertListAlmostEqual(accumulator._gradients[0].values[0].value().numpy().tolist(), [0.0, 0.0], tol=1e-2) <ide> self.assertListAlmostEqual(accumulator._gradients[0].values[1].value().numpy().tolist(), [0.0, 0.0], tol=1e-2) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_pipelines.py <ide> def test_tf_question_answering(self): <ide> for tokenizer, model, config in TF_QA_FINETUNED_MODELS: <ide> nlp = pipeline(task="question-answering", model=model, config=config, tokenizer=tokenizer) <ide> self._test_multicolumn_pipeline(nlp, valid_samples, invalid_samples, mandatory_output_keys) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_albert.py <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <ide> import os <del>import unittest <ide> <ide> from transformers.tokenization_albert import AlbertTokenizer <ide> <ide> def test_sequence_builders(self): <ide> assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [ <ide> tokenizer.sep_token_id <ide> ] <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_auto.py <ide> def test_tokenizer_from_pretrained_identifier(self): <ide> tokenizer = AutoTokenizer.from_pretrained(SMALL_MODEL_IDENTIFIER) <ide> self.assertIsInstance(tokenizer, BertTokenizer) <ide> self.assertEqual(len(tokenizer), 12) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_bert.py <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <ide> import os <del>import unittest <ide> from io import open <ide> <ide> from transformers.tokenization_bert import ( <ide> def test_sequence_builders(self): <ide> <ide> assert encoded_sentence == [101] + text + [102] <ide> assert encoded_pair == [101] + text + [102] + text_2 + [102] <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_ctrl.py <ide> <ide> import json <ide> import os <del>import unittest <ide> from io import open <ide> <ide> from transformers.tokenization_ctrl import VOCAB_FILES_NAMES, CTRLTokenizer <ide> def test_full_tokenizer(self): <ide> <ide> input_bpe_tokens = [0, 1, 2, 4, 5, 1, 0, 3, 6] <ide> self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_distilbert.py <ide> # limitations under the License. <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <del>import unittest <del> <ide> from transformers.tokenization_distilbert import DistilBertTokenizer <ide> <ide> from .test_tokenization_bert import BertTokenizationTest <ide> def test_sequence_builders(self): <ide> assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_2 + [ <ide> tokenizer.sep_token_id <ide> ] <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_gpt2.py <ide> <ide> import json <ide> import os <del>import unittest <ide> from io import open <ide> <ide> from transformers.tokenization_gpt2 import VOCAB_FILES_NAMES, GPT2Tokenizer <ide> def test_full_tokenizer(self): <ide> input_tokens = tokens + [tokenizer.unk_token] <ide> input_bpe_tokens = [14, 15, 10, 9, 3, 2, 15, 19] <ide> self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_openai.py <ide> <ide> import json <ide> import os <del>import unittest <ide> <ide> from transformers.tokenization_openai import VOCAB_FILES_NAMES, OpenAIGPTTokenizer <ide> <ide> def test_full_tokenizer(self): <ide> input_tokens = tokens + ["<unk>"] <ide> input_bpe_tokens = [14, 15, 20] <ide> self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_roberta.py <ide> <ide> import json <ide> import os <del>import unittest <ide> from io import open <ide> <ide> from transformers.tokenization_roberta import VOCAB_FILES_NAMES, RobertaTokenizer <ide> def test_sequence_builders(self): <ide> <ide> assert encoded_sentence == encoded_text_from_decode <ide> assert encoded_pair == encoded_pair_from_decode <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_t5.py <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <ide> import os <del>import unittest <ide> <ide> from transformers.tokenization_t5 import T5Tokenizer <ide> from transformers.tokenization_xlnet import SPIECE_UNDERLINE <ide> def test_full_tokenizer(self): <ide> ".", <ide> ], <ide> ) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_transfo_xl.py <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <ide> import os <del>import unittest <ide> from io import open <ide> <ide> from transformers import is_torch_available <ide> def test_full_tokenizer_no_lower(self): <ide> self.assertListEqual( <ide> tokenizer.tokenize(" \tHeLLo ! how \n Are yoU ? "), ["HeLLo", "!", "how", "Are", "yoU", "?"] <ide> ) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_utils.py <ide> def check_tokenizer_from_pretrained(self, tokenizer_class): <ide> @slow <ide> def test_pretrained_tokenizers(self): <ide> self.check_tokenizer_from_pretrained(GPT2Tokenizer) <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_xlm.py <ide> <ide> import json <ide> import os <del>import unittest <ide> <ide> from transformers.tokenization_xlm import VOCAB_FILES_NAMES, XLMTokenizer <ide> <ide> def test_sequence_builders(self): <ide> <ide> assert encoded_sentence == [1] + text + [1] <ide> assert encoded_pair == [1] + text + [1] + text_2 + [1] <del> <del> <del>if __name__ == "__main__": <del> unittest.main() <ide><path>tests/test_tokenization_xlnet.py <ide> from __future__ import absolute_import, division, print_function, unicode_literals <ide> <ide> import os <del>import unittest <ide> <ide> from transformers.tokenization_xlnet import SPIECE_UNDERLINE, XLNetTokenizer <ide> <ide> def test_sequence_builders(self): <ide> <ide> assert encoded_sentence == text + [4, 3] <ide> assert encoded_pair == text + [4] + text_2 + [4, 3] <del> <del> <del>if __name__ == "__main__": <del> unittest.main()
51
PHP
PHP
remove removecookie() method
c4833ec82bfb58eaf83680a7ee1cc64406ed1b04
<ide><path>src/Http/Client.php <ide> public function addCookie(CookieInterface $cookie) <ide> return $this; <ide> } <ide> <del> /** <del> * Removes a cookie from the Client collection. <del> * <del> * @param string $name Cookie name. <del> * @return $this <del> */ <del> public function removeCookie($name) <del> { <del> $this->_cookies = $this->_cookies->remove($name); <del> <del> return $this; <del> } <del> <ide> /** <ide> * Do a GET request. <ide> * <ide><path>tests/TestCase/Http/ClientTest.php <ide> public function testAddCookie() <ide> $this->assertTrue($client->cookies()->has('foo')); <ide> } <ide> <del> /** <del> * Test removeCookie() method. <del> * <del> * @return void <del> */ <del> public function testRemoveCookie() <del> { <del> $cookie = new Cookie('foo'); <del> $jar = new CookieCollection([$cookie]); <del> $client = new Client([ <del> 'cookieJar' => $jar <del> ]); <del> <del> $this->assertTrue($client->cookies()->has('foo')); <del> <del> $client->removeCookie('foo'); <del> $this->assertFalse($client->cookies()->has('foo')); <del> } <del> <ide> /** <ide> * test head request with querystring data <ide> *
2
PHP
PHP
remove old constraints
939264f91edc5d33da5ce6cf95a271a6f4a2e1f2
<ide><path>src/Illuminate/Foundation/Testing/Constraints/FormFieldConstraint.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use Symfony\Component\DomCrawler\Crawler; <del> <del>abstract class FormFieldConstraint extends PageConstraint <del>{ <del> /** <del> * The name or ID of the element. <del> * <del> * @var string <del> */ <del> protected $selector; <del> <del> /** <del> * The expected value. <del> * <del> * @var string <del> */ <del> protected $value; <del> <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $selector <del> * @param mixed $value <del> * @return void <del> */ <del> public function __construct($selector, $value) <del> { <del> $this->selector = $selector; <del> $this->value = (string) $value; <del> } <del> <del> /** <del> * Get the valid elements. <del> * <del> * Multiple elements should be separated by commas without spaces. <del> * <del> * @return string <del> */ <del> abstract protected function validElements(); <del> <del> /** <del> * Get the form field. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $crawler <del> * @return \Symfony\Component\DomCrawler\Crawler <del> * <del> * @throws \PHPUnit_Framework_ExpectationFailedException <del> */ <del> protected function field(Crawler $crawler) <del> { <del> $field = $crawler->filter(implode(', ', $this->getElements())); <del> <del> if ($field->count() > 0) { <del> return $field; <del> } <del> <del> $this->fail($crawler, sprintf( <del> 'There is no %s with the name or ID [%s]', <del> $this->validElements(), $this->selector <del> )); <del> } <del> <del> /** <del> * Get the elements relevant to the selector. <del> * <del> * @return array <del> */ <del> protected function getElements() <del> { <del> $name = str_replace('#', '', $this->selector); <del> <del> $id = str_replace(['[', ']'], ['\\[', '\\]'], $name); <del> <del> return collect(explode(',', $this->validElements()))->map(function ($element) use ($name, $id) { <del> return "{$element}#{$id}, {$element}[name='{$name}']"; <del> })->all(); <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasElement.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use Symfony\Component\DomCrawler\Crawler; <del> <del>class HasElement extends PageConstraint <del>{ <del> /** <del> * The name or ID of the element. <del> * <del> * @var string <del> */ <del> protected $selector; <del> <del> /** <del> * The attributes the element should have. <del> * <del> * @var array <del> */ <del> protected $attributes; <del> <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $selector <del> * @param array $attributes <del> * @return void <del> */ <del> public function __construct($selector, array $attributes = []) <del> { <del> $this->selector = $selector; <del> $this->attributes = $attributes; <del> } <del> <del> /** <del> * Check if the element is found in the given crawler. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> public function matches($crawler) <del> { <del> $elements = $this->crawler($crawler)->filter($this->selector); <del> <del> if ($elements->count() == 0) { <del> return false; <del> } <del> <del> if (empty($this->attributes)) { <del> return true; <del> } <del> <del> $elements = $elements->reduce(function ($element) { <del> return $this->hasAttributes($element); <del> }); <del> <del> return $elements->count() > 0; <del> } <del> <del> /** <del> * Determines if the given element has the attributes. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $element <del> * @return bool <del> */ <del> protected function hasAttributes(Crawler $element) <del> { <del> foreach ($this->attributes as $name => $value) { <del> if (is_numeric($name)) { <del> if (is_null($element->attr($value))) { <del> return false; <del> } <del> } else { <del> if ($element->attr($name) != $value) { <del> return false; <del> } <del> } <del> } <del> <del> return true; <del> } <del> <del> /** <del> * Returns a string representation of the object. <del> * <del> * @return string <del> */ <del> public function toString() <del> { <del> $message = "the element [{$this->selector}]"; <del> <del> if (! empty($this->attributes)) { <del> $message .= ' with the attributes '.json_encode($this->attributes); <del> } <del> <del> return $message; <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasInElement.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use Symfony\Component\DomCrawler\Crawler; <del> <del>class HasInElement extends PageConstraint <del>{ <del> /** <del> * The name or ID of the element. <del> * <del> * @var string <del> */ <del> protected $element; <del> <del> /** <del> * The text expected to be found. <del> * <del> * @var string <del> */ <del> protected $text; <del> <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $element <del> * @param string $text <del> * @return void <del> */ <del> public function __construct($element, $text) <del> { <del> $this->text = $text; <del> $this->element = $element; <del> } <del> <del> /** <del> * Check if the source or text is found within the element in the given crawler. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> public function matches($crawler) <del> { <del> $elements = $this->crawler($crawler)->filter($this->element); <del> <del> $pattern = $this->getEscapedPattern($this->text); <del> <del> foreach ($elements as $element) { <del> $element = new Crawler($element); <del> <del> if (preg_match("/$pattern/i", $element->html())) { <del> return true; <del> } <del> } <del> <del> return false; <del> } <del> <del> /** <del> * Returns the description of the failure. <del> * <del> * @return string <del> */ <del> protected function getFailureDescription() <del> { <del> return sprintf('[%s] contains %s', $this->element, $this->text); <del> } <del> <del> /** <del> * Returns the reversed description of the failure. <del> * <del> * @return string <del> */ <del> protected function getReverseFailureDescription() <del> { <del> return sprintf('[%s] does not contain %s', $this->element, $this->text); <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasLink.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use Illuminate\Support\Str; <del>use Illuminate\Support\Facades\URL; <del> <del>class HasLink extends PageConstraint <del>{ <del> /** <del> * The text expected to be found. <del> * <del> * @var string <del> */ <del> protected $text; <del> <del> /** <del> * The URL expected to be linked in the <a> tag. <del> * <del> * @var string|null <del> */ <del> protected $url; <del> <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $text <del> * @param string|null $url <del> * @return void <del> */ <del> public function __construct($text, $url = null) <del> { <del> $this->url = $url; <del> $this->text = $text; <del> } <del> <del> /** <del> * Check if the link is found in the given crawler. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> public function matches($crawler) <del> { <del> $links = $this->crawler($crawler)->selectLink($this->text); <del> <del> if ($links->count() == 0) { <del> return false; <del> } <del> <del> // If the URL is null we assume the developer only wants to find a link <del> // with the given text regardless of the URL. So if we find the link <del> // we will return true. Otherwise, we will look for the given URL. <del> if ($this->url == null) { <del> return true; <del> } <del> <del> $absoluteUrl = $this->absoluteUrl(); <del> <del> foreach ($links as $link) { <del> $linkHref = $link->getAttribute('href'); <del> <del> if ($linkHref == $this->url || $linkHref == $absoluteUrl) { <del> return true; <del> } <del> } <del> <del> return false; <del> } <del> <del> /** <del> * Add a root if the URL is relative (helper method of the hasLink function). <del> * <del> * @return string <del> */ <del> protected function absoluteUrl() <del> { <del> if (! Str::startsWith($this->url, ['http', 'https'])) { <del> return URL::to($this->url); <del> } <del> <del> return $this->url; <del> } <del> <del> /** <del> * Returns the description of the failure. <del> * <del> * @return string <del> */ <del> public function getFailureDescription() <del> { <del> $description = "has a link with the text [{$this->text}]"; <del> <del> if ($this->url) { <del> $description .= " and the URL [{$this->url}]"; <del> } <del> <del> return $description; <del> } <del> <del> /** <del> * Returns the reversed description of the failure. <del> * <del> * @return string <del> */ <del> protected function getReverseFailureDescription() <del> { <del> $description = "does not have a link with the text [{$this->text}]"; <del> <del> if ($this->url) { <del> $description .= " and the URL [{$this->url}]"; <del> } <del> <del> return $description; <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasSource.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>class HasSource extends PageConstraint <del>{ <del> /** <del> * The expected HTML source. <del> * <del> * @var string <del> */ <del> protected $source; <del> <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $source <del> * @return void <del> */ <del> public function __construct($source) <del> { <del> $this->source = $source; <del> } <del> <del> /** <del> * Check if the source is found in the given crawler. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> protected function matches($crawler) <del> { <del> $pattern = $this->getEscapedPattern($this->source); <del> <del> return preg_match("/{$pattern}/i", $this->html($crawler)); <del> } <del> <del> /** <del> * Returns a string representation of the object. <del> * <del> * @return string <del> */ <del> public function toString() <del> { <del> return "the HTML [{$this->source}]"; <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasText.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>class HasText extends PageConstraint <del>{ <del> /** <del> * The expected text. <del> * <del> * @var string <del> */ <del> protected $text; <del> <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $text <del> * @return void <del> */ <del> public function __construct($text) <del> { <del> $this->text = $text; <del> } <del> <del> /** <del> * Check if the plain text is found in the given crawler. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> protected function matches($crawler) <del> { <del> $pattern = $this->getEscapedPattern($this->text); <del> <del> return preg_match("/{$pattern}/i", $this->text($crawler)); <del> } <del> <del> /** <del> * Returns a string representation of the object. <del> * <del> * @return string <del> */ <del> public function toString() <del> { <del> return "the text [{$this->text}]"; <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/HasValue.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use Symfony\Component\DomCrawler\Crawler; <del> <del>class HasValue extends FormFieldConstraint <del>{ <del> /** <del> * Get the valid elements. <del> * <del> * @return string <del> */ <del> protected function validElements() <del> { <del> return 'input,textarea'; <del> } <del> <del> /** <del> * Check if the input contains the expected value. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> public function matches($crawler) <del> { <del> $crawler = $this->crawler($crawler); <del> <del> return $this->getInputOrTextAreaValue($crawler) == $this->value; <del> } <del> <del> /** <del> * Get the value of an input or textarea. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $crawler <del> * @return string <del> * <del> * @throws \PHPUnit_Framework_ExpectationFailedException <del> */ <del> public function getInputOrTextAreaValue(Crawler $crawler) <del> { <del> $field = $this->field($crawler); <del> <del> return $field->nodeName() == 'input' <del> ? $field->attr('value') <del> : $field->text(); <del> } <del> <del> /** <del> * Return the description of the failure. <del> * <del> * @return string <del> */ <del> protected function getFailureDescription() <del> { <del> return sprintf( <del> 'the field [%s] contains the expected value [%s]', <del> $this->selector, $this->value <del> ); <del> } <del> <del> /** <del> * Returns the reversed description of the failure. <del> * <del> * @return string <del> */ <del> protected function getReverseFailureDescription() <del> { <del> return sprintf( <del> 'the field [%s] does not contain the expected value [%s]', <del> $this->selector, $this->value <del> ); <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/IsChecked.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>class IsChecked extends FormFieldConstraint <del>{ <del> /** <del> * Create a new constraint instance. <del> * <del> * @param string $selector <del> * @return void <del> */ <del> public function __construct($selector) <del> { <del> $this->selector = $selector; <del> } <del> <del> /** <del> * Get the valid elements. <del> * <del> * @return string <del> */ <del> protected function validElements() <del> { <del> return "input[type='checkbox']"; <del> } <del> <del> /** <del> * Determine if the checkbox is checked. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> public function matches($crawler) <del> { <del> $crawler = $this->crawler($crawler); <del> <del> return ! is_null($this->field($crawler)->attr('checked')); <del> } <del> <del> /** <del> * Return the description of the failure. <del> * <del> * @return string <del> */ <del> protected function getFailureDescription() <del> { <del> return "the checkbox [{$this->selector}] is checked"; <del> } <del> <del> /** <del> * Returns the reversed description of the failure. <del> * <del> * @return string <del> */ <del> protected function getReverseFailureDescription() <del> { <del> return "the checkbox [{$this->selector}] is not checked"; <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/IsSelected.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use DOMElement; <del>use Symfony\Component\DomCrawler\Crawler; <del> <del>class IsSelected extends FormFieldConstraint <del>{ <del> /** <del> * Get the valid elements. <del> * <del> * @return string <del> */ <del> protected function validElements() <del> { <del> return 'select,input[type="radio"]'; <del> } <del> <del> /** <del> * Determine if the select or radio element is selected. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return bool <del> */ <del> protected function matches($crawler) <del> { <del> $crawler = $this->crawler($crawler); <del> <del> return in_array($this->value, $this->getSelectedValue($crawler)); <del> } <del> <del> /** <del> * Get the selected value of a select field or radio group. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $crawler <del> * @return array <del> * <del> * @throws \PHPUnit_Framework_ExpectationFailedException <del> */ <del> public function getSelectedValue(Crawler $crawler) <del> { <del> $field = $this->field($crawler); <del> <del> return $field->nodeName() == 'select' <del> ? $this->getSelectedValueFromSelect($field) <del> : [$this->getCheckedValueFromRadioGroup($field)]; <del> } <del> <del> /** <del> * Get the selected value from a select field. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $select <del> * @return array <del> */ <del> protected function getSelectedValueFromSelect(Crawler $select) <del> { <del> $selected = []; <del> <del> foreach ($select->children() as $option) { <del> if ($option->nodeName === 'optgroup') { <del> foreach ($option->childNodes as $child) { <del> if ($child->hasAttribute('selected')) { <del> $selected[] = $this->getOptionValue($child); <del> } <del> } <del> } elseif ($option->hasAttribute('selected')) { <del> $selected[] = $this->getOptionValue($option); <del> } <del> } <del> <del> return $selected; <del> } <del> <del> /** <del> * Get the selected value from an option element. <del> * <del> * @param \DOMElement $option <del> * @return string <del> */ <del> protected function getOptionValue(DOMElement $option) <del> { <del> if ($option->hasAttribute('value')) { <del> return $option->getAttribute('value'); <del> } <del> <del> return $option->textContent; <del> } <del> <del> /** <del> * Get the checked value from a radio group. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $radioGroup <del> * @return string|null <del> */ <del> protected function getCheckedValueFromRadioGroup(Crawler $radioGroup) <del> { <del> foreach ($radioGroup as $radio) { <del> if ($radio->hasAttribute('checked')) { <del> return $radio->getAttribute('value'); <del> } <del> } <del> } <del> <del> /** <del> * Returns the description of the failure. <del> * <del> * @return string <del> */ <del> protected function getFailureDescription() <del> { <del> return sprintf( <del> 'the element [%s] has the selected value [%s]', <del> $this->selector, $this->value <del> ); <del> } <del> <del> /** <del> * Returns the reversed description of the failure. <del> * <del> * @return string <del> */ <del> protected function getReverseFailureDescription() <del> { <del> return sprintf( <del> 'the element [%s] does not have the selected value [%s]', <del> $this->selector, $this->value <del> ); <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/PageConstraint.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>use PHPUnit_Framework_Constraint; <del>use Symfony\Component\DomCrawler\Crawler; <del>use SebastianBergmann\Comparator\ComparisonFailure; <del>use PHPUnit_Framework_ExpectationFailedException as FailedExpection; <del> <del>abstract class PageConstraint extends PHPUnit_Framework_Constraint <del>{ <del> /** <del> * Make sure we obtain the HTML from the crawler or the response. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return string <del> */ <del> protected function html($crawler) <del> { <del> return is_object($crawler) ? $crawler->html() : $crawler; <del> } <del> <del> /** <del> * Make sure we obtain the HTML from the crawler or the response. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return string <del> */ <del> protected function text($crawler) <del> { <del> return is_object($crawler) ? $crawler->text() : strip_tags($crawler); <del> } <del> <del> /** <del> * Create a crawler instance if the given value is not already a Crawler. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @return \Symfony\Component\DomCrawler\Crawler <del> */ <del> protected function crawler($crawler) <del> { <del> return is_object($crawler) ? $crawler : new Crawler($crawler); <del> } <del> <del> /** <del> * Get the escaped text pattern for the constraint. <del> * <del> * @param string $text <del> * @return string <del> */ <del> protected function getEscapedPattern($text) <del> { <del> $rawPattern = preg_quote($text, '/'); <del> <del> $escapedPattern = preg_quote(e($text), '/'); <del> <del> return $rawPattern == $escapedPattern <del> ? $rawPattern : "({$rawPattern}|{$escapedPattern})"; <del> } <del> <del> /** <del> * Throw an exception for the given comparison and test description. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler|string $crawler <del> * @param string $description <del> * @param \SebastianBergmann\Comparator\ComparisonFailure|null $comparisonFailure <del> * @return void <del> * <del> * @throws \PHPUnit_Framework_ExpectationFailedException <del> */ <del> protected function fail($crawler, $description, ComparisonFailure $comparisonFailure = null) <del> { <del> $html = $this->html($crawler); <del> <del> $failureDescription = sprintf( <del> "%s\n\n\nFailed asserting that %s", <del> $html, $this->getFailureDescription() <del> ); <del> <del> if (! empty($description)) { <del> $failureDescription .= ": {$description}"; <del> } <del> <del> if (trim($html) != '') { <del> $failureDescription .= '. Please check the content above.'; <del> } else { <del> $failureDescription .= '. The response is empty.'; <del> } <del> <del> throw new FailedExpection($failureDescription, $comparisonFailure); <del> } <del> <del> /** <del> * Get the description of the failure. <del> * <del> * @return string <del> */ <del> protected function getFailureDescription() <del> { <del> return 'the page contains '.$this->toString(); <del> } <del> <del> /** <del> * Returns the reversed description of the failure. <del> * <del> * @return string <del> */ <del> protected function getReverseFailureDescription() <del> { <del> return 'the page does not contain '.$this->toString(); <del> } <del> <del> /** <del> * Get a string representation of the object. <del> * <del> * Placeholder method to avoid forcing definition of this method. <del> * <del> * @return string <del> */ <del> public function toString() <del> { <del> return ''; <del> } <del>} <ide><path>src/Illuminate/Foundation/Testing/Constraints/ReversePageConstraint.php <del><?php <del> <del>namespace Illuminate\Foundation\Testing\Constraints; <del> <del>class ReversePageConstraint extends PageConstraint <del>{ <del> /** <del> * The page constraint instance. <del> * <del> * @var \Illuminate\Foundation\Testing\Constraints\PageConstraint <del> */ <del> protected $pageConstraint; <del> <del> /** <del> * Create a new reverse page constraint instance. <del> * <del> * @param \Illuminate\Foundation\Testing\Constraints\PageConstraint $pageConstraint <del> * @return void <del> */ <del> public function __construct(PageConstraint $pageConstraint) <del> { <del> $this->pageConstraint = $pageConstraint; <del> } <del> <del> /** <del> * Reverse the original page constraint result. <del> * <del> * @param \Symfony\Component\DomCrawler\Crawler $crawler <del> * @return bool <del> */ <del> public function matches($crawler) <del> { <del> return ! $this->pageConstraint->matches($crawler); <del> } <del> <del> /** <del> * Get the description of the failure. <del> * <del> * This method will attempt to negate the original description. <del> * <del> * @return string <del> */ <del> protected function getFailureDescription() <del> { <del> return $this->pageConstraint->getReverseFailureDescription(); <del> } <del> <del> /** <del> * Get a string representation of the object. <del> * <del> * @return string <del> */ <del> public function toString() <del> { <del> return $this->pageConstraint->toString(); <del> } <del>}
11
Ruby
Ruby
use relation#delete_all for model.delete_all
13989ff8c690b9b9e5282bd4098666c909ea64d3
<ide><path>activerecord/lib/active_record/base.rb <ide> def destroy_all(conditions = nil) <ide> # Both calls delete the affected posts all at once with a single DELETE statement. If you need to destroy dependent <ide> # associations or call your <tt>before_*</tt> or +after_destroy+ callbacks, use the +destroy_all+ method instead. <ide> def delete_all(conditions = nil) <del> if conditions <del> arel_table.where(Arel::SqlLiteral.new(construct_conditions(conditions, scope(:find)))).delete <del> else <del> arel_table.delete <del> end <add> arel_table.where(construct_conditions(conditions, scope(:find))).delete_all <ide> end <ide> <ide> # Returns the result of an SQL statement that should only include a COUNT(*) in the SELECT part. <ide><path>activerecord/lib/active_record/relation.rb <ide> def destroy_all <ide> end <ide> <ide> def delete_all <del> @relation.delete <del> reset <add> @relation.delete.tap { reset } <ide> end <ide> <ide> def loaded?
2
PHP
PHP
apply fixes from styleci
72c92621d946ef01e1b4258f0f4b4769f4d58ddd
<ide><path>tests/Auth/AuthAccessGateTest.php <ide> namespace Illuminate\Tests\Auth; <ide> <ide> use stdClass; <del>use InvalidArgumentException; <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Auth\Access\Gate; <ide> use Illuminate\Container\Container; <ide><path>tests/Container/ContainerTest.php <ide> namespace Illuminate\Tests\Container; <ide> <ide> use stdClass; <del>use ReflectionException; <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Container\Container; <ide> <ide><path>tests/Database/DatabaseConnectionFactoryTest.php <ide> <ide> use Mockery as m; <ide> use ReflectionProperty; <del>use InvalidArgumentException; <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Database\Capsule\Manager as DB; <ide> use Illuminate\Database\Connectors\ConnectionFactory; <ide><path>tests/Database/DatabaseEloquentModelTest.php <ide> use stdClass; <ide> use Exception; <ide> use Mockery as m; <del>use LogicException; <ide> use ReflectionClass; <ide> use DateTimeImmutable; <ide> use DateTimeInterface; <ide><path>tests/Http/HttpRedirectResponseTest.php <ide> namespace Illuminate\Tests\Http; <ide> <ide> use Mockery as m; <del>use BadMethodCallException; <ide> use Illuminate\Http\Request; <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Http\RedirectResponse; <ide><path>tests/Routing/RoutingRouteTest.php <ide> use Illuminate\Support\Str; <ide> use Illuminate\Http\Request; <ide> use Illuminate\Routing\Route; <del>use UnexpectedValueException; <ide> use Illuminate\Routing\Router; <ide> use PHPUnit\Framework\TestCase; <ide> use Illuminate\Events\Dispatcher; <ide><path>tests/View/ViewEngineResolverTest.php <ide> namespace Illuminate\Tests\View; <ide> <ide> use stdClass; <del>use InvalidArgumentException; <ide> use PHPUnit\Framework\TestCase; <ide> <ide> class ViewEngineResolverTest extends TestCase
7
Python
Python
enhance code coverage for blueprint.endpoint
954b7ef7bbc261ac455feb122b56e897653de826
<ide><path>tests/test_blueprints.py <ide> def foo_foo_foo(): <ide> rv = c.get('/py/bar/123') <ide> assert rv.status_code == 404 <ide> <add> <add>def test_endpoint_decorator(): <add> from werkzeug.routing import Rule <add> app = flask.Flask(__name__) <add> app.url_map.add(Rule('/foo', endpoint='bar')) <add> <add> bp = flask.Blueprint('bp', __name__) <add> <add> @bp.endpoint('bar') <add> def foobar(): <add> return flask.request.endpoint <add> <add> app.register_blueprint(bp, url_prefix='/bp_prefix') <add> <add> c = app.test_client() <add> assert c.get('/foo').data == b'bar' <add> assert c.get('/bp_prefix/bar').status_code == 404 <add> <add> <ide> def test_template_filter(): <ide> bp = flask.Blueprint('bp', __name__) <ide> @bp.app_template_filter()
1
Ruby
Ruby
initialize our instance variables
8662722f4fea34259da4d37abd6c55ec717f9d2a
<ide><path>railties/lib/rails/engine.rb <ide> class Engine < Railtie <ide> autoload :Configuration, "rails/engine/configuration" <ide> autoload :Railties, "rails/engine/railties" <ide> <add> def initialize <add> @_all_autoload_paths = nil <add> @_all_load_paths = nil <add> @app = nil <add> @config = nil <add> @env_config = nil <add> @helpers = nil <add> @railties = nil <add> @routes = nil <add> super <add> end <add> <ide> def load_generators(app=self) <ide> initialize_generators <ide> railties.all { |r| r.load_generators(app) } <ide> def load_seed <ide> end <ide> end <ide> <del> protected <add> protected <ide> <ide> def initialize_generators <ide> require "rails/generators" <ide> end <ide> <ide> def routes? <del> defined?(@routes) && @routes <add> @routes <ide> end <ide> <ide> def has_migrations?
1
Javascript
Javascript
add tests for repositoryfordirectorysync
16b8c293a19f2d39166ecfd6e9bd76070a600754
<ide><path>spec/git-repository-provider-spec.js <ide> describe('GitRepositoryProvider', () => { <ide> }) <ide> }) <ide> <del> describe('when specified a Directory without existsSync()', () => { <add> describe('when specified a Directory without exists()', () => { <ide> let directory <ide> <ide> beforeEach(() => { <ide> describe('GitRepositoryProvider', () => { <ide> spyOn(directory, 'getSubdirectory').andReturn(subdirectory) <ide> }) <ide> <del> it('returns null', () => { <del> const repo = provider.repositoryForDirectorySync(directory) <add> it('returns a Promise that resolves to null', async () => { <add> const repo = await provider.repositoryForDirectory(directory) <ide> expect(repo).toBe(null) <ide> expect(directory.getSubdirectory).toHaveBeenCalledWith('.git') <ide> }) <add> }) <add> }) <ide> <del> it('returns a Promise that resolves to null for the async implementation', async () => { <del> const repo = await provider.repositoryForDirectory(directory) <add> describe('.repositoryForDirectorySync(directory)', () => { <add> describe('when specified a Directory with a Git repository', () => { <add> it('resolves with a GitRepository', async () => { <add> const directory = new Directory(path.join(__dirname, 'fixtures', 'git', 'master.git')) <add> const result = provider.repositoryForDirectorySync(directory) <add> expect(result).toBeInstanceOf(GitRepository) <add> expect(provider.pathToRepository[result.getPath()]).toBeTruthy() <add> expect(result.getType()).toBe('git') <add> <add> // Refresh should be started <add> await new Promise(resolve => result.onDidChangeStatuses(resolve)) <add> }) <add> <add> it('resolves with the same GitRepository for different Directory objects in the same repo', () => { <add> const firstRepo = provider.repositoryForDirectorySync( <add> new Directory(path.join(__dirname, 'fixtures', 'git', 'master.git')) <add> ) <add> const secondRepo = provider.repositoryForDirectorySync( <add> new Directory(path.join(__dirname, 'fixtures', 'git', 'master.git', 'objects')) <add> ) <add> <add> expect(firstRepo).toBeInstanceOf(GitRepository) <add> expect(firstRepo).toBe(secondRepo) <add> }) <add> }) <add> <add> describe('when specified a Directory without a Git repository', () => { <add> it('resolves with null', () => { <add> const directory = new Directory(temp.mkdirSync('dir')) <add> const repo = provider.repositoryForDirectorySync(directory) <add> expect(repo).toBe(null) <add> }) <add> }) <add> <add> describe('when specified a Directory with an invalid Git repository', () => { <add> it('resolves with null', () => { <add> const dirPath = temp.mkdirSync('dir') <add> fs.writeFileSync(path.join(dirPath, '.git', 'objects'), '') <add> fs.writeFileSync(path.join(dirPath, '.git', 'HEAD'), '') <add> fs.writeFileSync(path.join(dirPath, '.git', 'refs'), '') <add> <add> const directory = new Directory(dirPath) <add> const repo = provider.repositoryForDirectorySync(directory) <add> expect(repo).toBe(null) <add> }) <add> }) <add> <add> describe('when specified a Directory with a valid gitfile-linked repository', () => { <add> it('returns a Promise that resolves to a GitRepository', () => { <add> const gitDirPath = path.join(__dirname, 'fixtures', 'git', 'master.git') <add> const workDirPath = temp.mkdirSync('git-workdir') <add> fs.writeFileSync(path.join(workDirPath, '.git'), `gitdir: ${gitDirPath}\n`) <add> <add> const directory = new Directory(workDirPath) <add> const result = provider.repositoryForDirectorySync(directory) <add> expect(result).toBeInstanceOf(GitRepository) <add> expect(provider.pathToRepository[result.getPath()]).toBeTruthy() <add> expect(result.getType()).toBe('git') <add> }) <add> }) <add> <add> describe('when specified a Directory without existsSync()', () => { <add> let directory <add> <add> beforeEach(() => { <add> // An implementation of Directory that does not implement existsSync(). <add> const subdirectory = {} <add> directory = { <add> getSubdirectory () {}, <add> isRoot () { return true } <add> } <add> spyOn(directory, 'getSubdirectory').andReturn(subdirectory) <add> }) <add> <add> it('returns null', () => { <add> const repo = provider.repositoryForDirectorySync(directory) <ide> expect(repo).toBe(null) <ide> expect(directory.getSubdirectory).toHaveBeenCalledWith('.git') <ide> })
1
Python
Python
fix wrong merge for manifest version
cb7133004d86bec7686d625a6f898913ca5f4380
<ide><path>numpy/distutils/mingw32ccompiler.py <ide> def rc_name(config): <ide> def generate_manifest(config): <ide> msver = get_build_msvc_version() <ide> if msver is not None: <del> if msver >= 9: <add> if msver >= 8: <ide> check_embedded_msvcr_match_linked(msver) <ide> ma = int(msver) <ide> mi = int((msver - ma) * 10)
1
PHP
PHP
add throws back in
b82101fb977798d695de03e1513653a893814584
<ide><path>src/Illuminate/Container/Container.php <ide> public function singletonIf($abstract, $concrete = null) <ide> * @param string $abstract <ide> * @param \Closure $closure <ide> * @return void <add> * <add> * @throws \InvalidArgumentException <ide> */ <ide> public function extend($abstract, Closure $closure) <ide> {
1
Python
Python
add test for empty subspace
2c37d3b6ec81ee6a86e4ae8f5713d48b6405cfb3
<ide><path>numpy/core/tests/test_ufunc.py <ide> def test_inplace_fancy_indexing(self): <ide> np.invert.at(a, [2, 5, 2]) <ide> assert_equal(a, [0, 1, 2, 3, 4, 5 ^ 0xffffffff, 6, 7, 8, 9]) <ide> <add> # Test empty subspace <add> orig = np.arange(4) <add> a = orig[:,None][:,0:0] <add> np.add.at(a, [0,1], 3) <add> assert_array_equal(orig, np.arange(4)) <ide> <ide> if __name__ == "__main__": <ide> run_module_suite()
1
Javascript
Javascript
implement action helper for htmlbars
18e41644485785ef05b953149e28ba9db1cfa526
<ide><path>packages/ember-routing-handlebars/lib/helpers/action.js <ide> ActionHelper.registerAction = function(actionNameOrStream, options, allowedKeys) <ide> if (actionNameOrStream.isStream) { <ide> actionName = actionNameOrStream.value(); <ide> <del> if (typeof actionName === 'undefined' || typeof actionName === 'function') { <del> actionName = actionNameOrStream._originalPath; <del> Ember.deprecate("You specified a quoteless path to the {{action}} helper '" + <del> actionName + "' which did not resolve to an actionName." + <del> " Perhaps you meant to use a quoted actionName? (e.g. {{action '" + actionName + "'}})."); <del> } <del> } <del> <del> if (!actionName) { <add> Ember.assert("You specified a quoteless path to the {{action}} helper " + <add> "which did not resolve to an action name (a string). " + <add> "Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", <add> typeof actionName === 'string'); <add> } else { <ide> actionName = actionNameOrStream; <ide> } <ide> <ide><path>packages/ember-routing-htmlbars/lib/helpers/action.js <add>/** <add>@module ember <add>@submodule ember-routing-htmlbars <add>*/ <add> <add>import Ember from "ember-metal/core"; // Handlebars, uuid, FEATURES, assert, deprecate <add>import { uuid } from "ember-metal/utils"; <add>import run from "ember-metal/run_loop"; <add>import { readUnwrappedModel } from "ember-views/streams/read"; <add>import { isSimpleClick } from "ember-views/system/utils"; <add>import ActionManager from "ember-views/system/action_manager"; <add>import { indexOf } from "ember-metal/array"; <add> <add>function actionArgs(parameters, actionName) { <add> var ret, i, l; <add> <add> if (actionName === undefined) { <add> ret = new Array(parameters.length); <add> for (i=0, l=parameters.length;i<l;i++) { <add> ret[i] = readUnwrappedModel(parameters[i]); <add> } <add> } else { <add> ret = new Array(parameters.length + 1); <add> ret[0] = actionName; <add> for (i=0, l=parameters.length;i<l; i++) { <add> ret[i + 1] = readUnwrappedModel(parameters[i]); <add> } <add> } <add> <add> return ret; <add>} <add> <add>var ActionHelper = {}; <add> <add>// registeredActions is re-exported for compatibility with older plugins <add>// that were using this undocumented API. <add>ActionHelper.registeredActions = ActionManager.registeredActions; <add> <add>export { ActionHelper }; <add> <add>var keys = ["alt", "shift", "meta", "ctrl"]; <add> <add>var POINTER_EVENT_TYPE_REGEX = /^click|mouse|touch/; <add> <add>var isAllowedEvent = function(event, allowedKeys) { <add> if (typeof allowedKeys === "undefined") { <add> if (POINTER_EVENT_TYPE_REGEX.test(event.type)) { <add> return isSimpleClick(event); <add> } else { <add> allowedKeys = ''; <add> } <add> } <add> <add> if (allowedKeys.indexOf("any") >= 0) { <add> return true; <add> } <add> <add> for (var i=0, l=keys.length;i<l;i++) { <add> if (event[keys[i] + "Key"] && allowedKeys.indexOf(keys[i]) === -1) { <add> return false; <add> } <add> } <add> <add> return true; <add>}; <add> <add>var keyEvents = ['keyUp', 'keyPress', 'keyDown']; <add> <add>function ignoreKeyEvent(eventName, event, keyCode) { <add> var any = 'any'; <add> keyCode = keyCode || any; <add> return indexOf.call(keyEvents, eventName) !== -1 && keyCode !== any && keyCode !== event.which.toString(); <add>} <add> <add>ActionHelper.registerAction = function(actionNameOrStream, options, allowedKeys) { <add> var actionId = uuid(); <add> var eventName = options.eventName; <add> var parameters = options.parameters; <add> <add> ActionManager.registeredActions[actionId] = { <add> eventName: eventName, <add> handler: function handleRegisteredAction(event) { <add> if (!isAllowedEvent(event, allowedKeys)) { return true; } <add> <add> if (options.preventDefault !== false) { <add> event.preventDefault(); <add> } <add> <add> if (options.bubbles === false) { <add> event.stopPropagation(); <add> } <add> <add> var target = options.target.value(); <add> <add> if (Ember.FEATURES.isEnabled("ember-routing-handlebars-action-with-key-code")) { <add> if (ignoreKeyEvent(eventName, event, options.withKeyCode)) { <add> return; <add> } <add> } <add> <add> var actionName; <add> <add> if (actionNameOrStream.isStream) { <add> actionName = actionNameOrStream.value(); <add> <add> Ember.assert("You specified a quoteless path to the {{action}} helper " + <add> "which did not resolve to an action name (a string). " + <add> "Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", <add> typeof actionName === 'string'); <add> } else { <add> actionName = actionNameOrStream; <add> } <add> <add> run(function runRegisteredAction() { <add> if (target.send) { <add> target.send.apply(target, actionArgs(parameters, actionName)); <add> } else { <add> Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function'); <add> target[actionName].apply(target, actionArgs(parameters)); <add> } <add> }); <add> } <add> }; <add> <add> options.view.on('willClearRender', function() { <add> delete ActionManager.registeredActions[actionId]; <add> }); <add> <add> return actionId; <add>}; <add> <add>/** <add> The `{{action}}` helper provides a useful shortcut for registering an HTML <add> element within a template for a single DOM event and forwarding that <add> interaction to the template's controller or specified `target` option. <add> <add> If the controller does not implement the specified action, the event is sent <add> to the current route, and it bubbles up the route hierarchy from there. <add> <add> For more advanced event handling see [Ember.Component](/api/classes/Ember.Component.html) <add> <add> <add> ### Use <add> Given the following application Handlebars template on the page <add> <add> ```handlebars <add> <div {{action 'anActionName'}}> <add> click me <add> </div> <add> ``` <add> <add> And application code <add> <add> ```javascript <add> App.ApplicationController = Ember.Controller.extend({ <add> actions: { <add> anActionName: function() { <add> } <add> } <add> }); <add> ``` <add> <add> Will result in the following rendered HTML <add> <add> ```html <add> <div class="ember-view"> <add> <div data-ember-action="1"> <add> click me <add> </div> <add> </div> <add> ``` <add> <add> Clicking "click me" will trigger the `anActionName` action of the <add> `App.ApplicationController`. In this case, no additional parameters will be passed. <add> <add> If you provide additional parameters to the helper: <add> <add> ```handlebars <add> <button {{action 'edit' post}}>Edit</button> <add> ``` <add> <add> Those parameters will be passed along as arguments to the JavaScript <add> function implementing the action. <add> <add> ### Event Propagation <add> <add> Events triggered through the action helper will automatically have <add> `.preventDefault()` called on them. You do not need to do so in your event <add> handlers. If you need to allow event propagation (to handle file inputs for <add> example) you can supply the `preventDefault=false` option to the `{{action}}` helper: <add> <add> ```handlebars <add> <div {{action "sayHello" preventDefault=false}}> <add> <input type="file" /> <add> <input type="checkbox" /> <add> </div> <add> ``` <add> <add> To disable bubbling, pass `bubbles=false` to the helper: <add> <add> ```handlebars <add> <button {{action 'edit' post bubbles=false}}>Edit</button> <add> ``` <add> <add> If you need the default handler to trigger you should either register your <add> own event handler, or use event methods on your view class. See [Ember.View](/api/classes/Ember.View.html) <add> 'Responding to Browser Events' for more information. <add> <add> ### Specifying DOM event type <add> <add> By default the `{{action}}` helper registers for DOM `click` events. You can <add> supply an `on` option to the helper to specify a different DOM event name: <add> <add> ```handlebars <add> <div {{action "anActionName" on="doubleClick"}}> <add> click me <add> </div> <add> ``` <add> <add> See `Ember.View` 'Responding to Browser Events' for a list of <add> acceptable DOM event names. <add> <add> ### Specifying whitelisted modifier keys <add> <add> By default the `{{action}}` helper will ignore click event with pressed modifier <add> keys. You can supply an `allowedKeys` option to specify which keys should not be ignored. <add> <add> ```handlebars <add> <div {{action "anActionName" allowedKeys="alt"}}> <add> click me <add> </div> <add> ``` <add> <add> This way the `{{action}}` will fire when clicking with the alt key pressed down. <add> <add> Alternatively, supply "any" to the `allowedKeys` option to accept any combination of modifier keys. <add> <add> ```handlebars <add> <div {{action "anActionName" allowedKeys="any"}}> <add> click me with any key pressed <add> </div> <add> ``` <add> <add> ### Specifying a Target <add> <add> There are several possible target objects for `{{action}}` helpers: <add> <add> In a typical Ember application, where templates are managed through use of the <add> `{{outlet}}` helper, actions will bubble to the current controller, then <add> to the current route, and then up the route hierarchy. <add> <add> Alternatively, a `target` option can be provided to the helper to change <add> which object will receive the method call. This option must be a path <add> to an object, accessible in the current context: <add> <add> ```handlebars <add> {{! the application template }} <add> <div {{action "anActionName" target=view}}> <add> click me <add> </div> <add> ``` <add> <add> ```javascript <add> App.ApplicationView = Ember.View.extend({ <add> actions: { <add> anActionName: function(){} <add> } <add> }); <add> <add> ``` <add> <add> ### Additional Parameters <add> <add> You may specify additional parameters to the `{{action}}` helper. These <add> parameters are passed along as the arguments to the JavaScript function <add> implementing the action. <add> <add> ```handlebars <add> {{#each person in people}} <add> <div {{action "edit" person}}> <add> click me <add> </div> <add> {{/each}} <add> ``` <add> <add> Clicking "click me" will trigger the `edit` method on the current controller <add> with the value of `person` as a parameter. <add> <add> @method action <add> @for Ember.Handlebars.helpers <add> @param {String} actionName <add> @param {Object} [context]* <add> @param {Hash} options <add>*/ <add>export function actionHelper(params, hash, options, env) { <add> <add> var target; <add> if (!hash.target) { <add> target = this.getStream('controller'); <add> } else if (hash.target.isStream) { <add> target = hash.target; <add> } else { <add> target = this.getStream(hash.target); <add> } <add> <add> // Ember.assert("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", !params[0].isStream); <add> // Ember.deprecate("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).", params[0].isStream); <add> <add> var actionOptions = { <add> eventName: hash.on || "click", <add> parameters: params.slice(1), <add> view: this, <add> bubbles: hash.bubbles, <add> preventDefault: hash.preventDefault, <add> target: target, <add> withKeyCode: hash.withKeyCode <add> }; <add> <add> var actionId = ActionHelper.registerAction(params[0], actionOptions, hash.allowedKeys); <add> env.dom.setAttribute(options.element, 'data-ember-action', actionId); <add>} <ide><path>packages/ember-routing-htmlbars/lib/main.js <ide> import { <ide> linkToHelper, <ide> deprecatedLinkToHelper <ide> } from "ember-routing-htmlbars/helpers/link-to"; <add>import { actionHelper } from "ember-routing-htmlbars/helpers/action"; <ide> <ide> registerHelper('outlet', outletHelper); <ide> registerHelper('link-to', linkToHelper); <ide> registerHelper('linkTo', deprecatedLinkToHelper); <add>registerHelper('action', actionHelper); <ide> <ide> export default Ember; <add><path>packages/ember-routing-htmlbars/tests/helpers/action_test.js <del><path>packages/ember-routing-handlebars/tests/helpers/action_test.js <ide> import EmberObjectController from "ember-runtime/controllers/object_controller"; <ide> import EmberArrayController from "ember-runtime/controllers/array_controller"; <ide> <ide> import EmberHandlebars from "ember-handlebars"; <add>import htmlbarsCompile from "ember-htmlbars/system/compile"; <ide> import EmberView from "ember-views/views/view"; <ide> import EmberComponent from "ember-views/views/component"; <ide> import jQuery from "ember-views/system/jquery"; <ide> <ide> import { <del> ActionHelper, <del> actionHelper <add> registerHelper as htmlbarsRegisterHelper, <add> default as htmlbarsHelpers <add>} from "ember-htmlbars/helpers"; <add> <add>import { <add> ActionHelper as HandlebarsActionHelper, <add> actionHelper as handlebarsActionHelper <ide> } from "ember-routing-handlebars/helpers/action"; <ide> <add>import { <add> ActionHelper as HTMLBarsActionHelper, <add> actionHelper as htmlbarsActionHelper <add>} from "ember-routing-htmlbars/helpers/action"; <add> <add>var compile, helpers, registerHelper, ActionHelper, actionHelper; <add>if (Ember.FEATURES.isEnabled('ember-htmlbars')) { <add> helpers = htmlbarsHelpers; <add> compile = htmlbarsCompile; <add> registerHelper = htmlbarsRegisterHelper; <add> actionHelper = htmlbarsActionHelper; <add> ActionHelper = HTMLBarsActionHelper; <add>} else { <add> helpers = EmberHandlebars.helpers; <add> compile = EmberHandlebars.compile; <add> registerHelper = function(name, fn) { <add> return EmberHandlebars.registerHelper(name, fn); <add> }; <add> actionHelper = handlebarsActionHelper; <add> ActionHelper = HandlebarsActionHelper; <add>} <add> <ide> var dispatcher, view, originalActionHelper; <ide> var originalRegisterAction = ActionHelper.registerAction; <ide> <ide> var appendView = function() { <ide> run(function() { view.appendTo('#qunit-fixture'); }); <ide> }; <ide> <del>QUnit.module("Ember.Handlebars - action helper", { <add>QUnit.module("ember-routing-htmlbars: action helper", { <ide> setup: function() { <del> originalActionHelper = EmberHandlebars.helpers['action']; <del> EmberHandlebars.registerHelper('action', actionHelper); <add> originalActionHelper = helpers['action']; <add> registerHelper('action', actionHelper); <ide> <ide> dispatcher = EventDispatcher.create(); <ide> dispatcher.setup(); <ide> QUnit.module("Ember.Handlebars - action helper", { <ide> if (view) { view.destroy(); } <ide> }); <ide> <del> delete EmberHandlebars.helpers['action']; <del> EmberHandlebars.helpers['action'] = originalActionHelper; <add> delete helpers['action']; <add> helpers['action'] = originalActionHelper; <ide> } <ide> }); <ide> <ide> test("should output a data attribute with a guid", function() { <ide> view = EmberView.create({ <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>edit</a>') <add> template: compile('<a href="#" {{action "edit"}}>edit</a>') <ide> }); <ide> <ide> appendView(); <ide> test("should by default register a click event", function() { <ide> }; <ide> <ide> view = EmberView.create({ <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>edit</a>') <add> template: compile('<a href="#" {{action "edit"}}>edit</a>') <ide> }); <ide> <ide> appendView(); <ide> test("should allow alternative events to be handled", function() { <ide> }; <ide> <ide> view = EmberView.create({ <del> template: EmberHandlebars.compile('<a href="#" {{action "edit" on="mouseUp"}}>edit</a>') <add> template: compile('<a href="#" {{action "edit" on="mouseUp"}}>edit</a>') <ide> }); <ide> <ide> appendView(); <ide> test("should by default target the view's controller", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>edit</a>') <add> template: compile('<a href="#" {{action "edit"}}>edit</a>') <ide> }); <ide> <ide> appendView(); <ide> test("Inside a yield, the target points at the original target", function() { <ide> boundText: "inner", <ide> truthy: true, <ide> obj: {}, <del> layout: EmberHandlebars.compile("<div>{{boundText}}</div><div>{{#if truthy}}{{yield}}{{/if}}</div>") <add> layout: compile("<div>{{boundText}}</div><div>{{#if truthy}}{{yield}}{{/if}}</div>") <ide> }); <ide> <ide> view = EmberView.create({ <ide> test("Inside a yield, the target points at the original target", function() { <ide> }, <ide> component: component <ide> }, <del> template: EmberHandlebars.compile('{{#if truthy}}{{#view component}}{{#if truthy}}<div {{action "wat"}} class="wat">{{boundText}}</div>{{/if}}{{/view}}{{/if}}') <add> template: compile('{{#if truthy}}{{#view component}}{{#if truthy}}<div {{action "wat"}} class="wat">{{boundText}}</div>{{/if}}{{/view}}{{/if}}') <ide> }); <ide> <ide> appendView(); <ide> test("Inside a yield, the target points at the original target", function() { <ide> equal(watted, true, "The action was called on the right context"); <ide> }); <ide> <add>if (!Ember.FEATURES.isEnabled('ember-htmlbars')) { <ide> test("should target the current controller inside an {{each}} loop [DEPRECATED]", function() { <ide> var registeredTarget; <ide> <ide> test("should target the current controller inside an {{each}} loop [DEPRECATED]" <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('{{#each controller}}{{action "editTodo"}}{{/each}}') <add> template: compile('{{#each controller}}{{action "editTodo"}}{{/each}}') <ide> }); <ide> <ide> expectDeprecation(function() { <ide> test("should target the current controller inside an {{each}} loop [DEPRECATED]" <ide> <ide> ActionHelper.registerAction = originalRegisterAction; <ide> }); <add>} <ide> <ide> test("should target the with-controller inside an {{#with controller='person'}} [DEPRECATED]", function() { <ide> var registeredTarget; <ide> test("should target the with-controller inside an {{#with controller='person'}} <ide> <ide> view = EmberView.create({ <ide> container: container, <del> template: EmberHandlebars.compile('{{#with view.person controller="person"}}{{action "editTodo"}}{{/with}}'), <add> template: compile('{{#with view.person controller="person"}}<div {{action "editTodo"}}></div>{{/with}}'), <ide> person: EmberObject.create(), <ide> controller: parentController <ide> }); <ide> test("should target the with-controller inside an {{each}} in a {{#with controll <ide> <ide> view = EmberView.create({ <ide> container: container, <del> template: EmberHandlebars.compile('{{#with people controller="people"}}{{#each}}<a href="#" {{action name}}>{{name}}</a>{{/each}}{{/with}}'), <add> template: compile('{{#with people controller="people"}}{{#each}}<a href="#" {{action name}}>{{name}}</a>{{/each}}{{/with}}'), <ide> controller: parentController <ide> }); <ide> <ide> test("should allow a target to be specified", function() { <ide> <ide> view = EmberView.create({ <ide> controller: {}, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit" target="view.anotherTarget"}}>edit</a>'), <add> template: compile('<a href="#" {{action "edit" target=view.anotherTarget}}>edit</a>'), <ide> anotherTarget: anotherTarget <ide> }); <ide> <ide> test("should lazily evaluate the target", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit" target="theTarget"}}>edit</a>') <add> template: compile('<a href="#" {{action "edit" target=theTarget}}>edit</a>') <ide> }); <ide> <ide> appendView(); <ide> test("should register an event handler", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>click me</a>') <add> template: compile('<a href="#" {{action "edit"}}>click me</a>') <ide> }); <ide> <ide> appendView(); <ide> test("handles whitelisted modifier keys", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit" allowedKeys="alt"}}>click me</a> <div {{action "shortcut" allowedKeys="any"}}>click me too</div>') <add> template: compile('<a href="#" {{action "edit" allowedKeys="alt"}}>click me</a> <div {{action "shortcut" allowedKeys="any"}}>click me too</div>') <ide> }); <ide> <ide> appendView(); <ide> test("should be able to use action more than once for the same event within a vi <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile( <add> template: compile( <ide> '<a id="edit" href="#" {{action "edit"}}>edit</a><a id="delete" href="#" {{action "delete"}}>delete</a>' <ide> ), <ide> click: function() { originalEventHandlerWasCalled = true; } <ide> test("the event should not bubble if `bubbles=false` is passed", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile( <add> template: compile( <ide> '<a id="edit" href="#" {{action "edit" bubbles=false}}>edit</a><a id="delete" href="#" {{action "delete" bubbles=false}}>delete</a>' <ide> ), <ide> click: function() { originalEventHandlerWasCalled = true; } <ide> test("should work properly in an #each block", function() { <ide> view = EmberView.create({ <ide> controller: controller, <ide> items: Ember.A([1, 2, 3, 4]), <del> template: EmberHandlebars.compile('{{#each item in view.items}}<a href="#" {{action "edit"}}>click me</a>{{/each}}') <add> template: compile('{{#each item in view.items}}<a href="#" {{action "edit"}}>click me</a>{{/each}}') <ide> }); <ide> <ide> appendView(); <ide> test("should work properly in a {{#with foo as bar}} block", function() { <ide> view = EmberView.create({ <ide> controller: controller, <ide> something: {ohai: 'there'}, <del> template: EmberHandlebars.compile('{{#with view.something as somethingElse}}<a href="#" {{action "edit"}}>click me</a>{{/with}}') <add> template: compile('{{#with view.something as somethingElse}}<a href="#" {{action "edit"}}>click me</a>{{/with}}') <ide> }); <ide> <ide> appendView(); <ide> test("should work properly in a #with block [DEPRECATED]", function() { <ide> view = EmberView.create({ <ide> controller: controller, <ide> something: {ohai: 'there'}, <del> template: EmberHandlebars.compile('{{#with view.something}}<a href="#" {{action "edit"}}>click me</a>{{/with}}') <add> template: compile('{{#with view.something}}<a href="#" {{action "edit"}}>click me</a>{{/with}}') <ide> }); <ide> <ide> expectDeprecation(function() { <ide> test("should unregister event handlers on rerender", function() { <ide> var eventHandlerWasCalled = false; <ide> <ide> view = EmberView.extend({ <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>click me</a>'), <add> template: compile('<a href="#" {{action "edit"}}>click me</a>'), <ide> actions: { edit: function() { eventHandlerWasCalled = true; } } <ide> }).create(); <ide> <ide> test("should unregister event handlers on inside virtual views", function() { <ide> } <ide> ]); <ide> view = EmberView.create({ <del> template: EmberHandlebars.compile('{{#each thing in view.things}}<a href="#" {{action "edit"}}>click me</a>{{/each}}'), <add> template: compile('{{#each thing in view.things}}<a href="#" {{action "edit"}}>click me</a>{{/each}}'), <ide> things: things <ide> }); <ide> <ide> test("should properly capture events on child elements of a container with an ac <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<div {{action "edit"}}><button>click me</button></div>') <add> template: compile('<div {{action "edit"}}><button>click me</button></div>') <ide> }); <ide> <ide> appendView(); <ide> test("should allow bubbling of events from action helper to original parent even <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>click me</a>'), <add> template: compile('<a href="#" {{action "edit"}}>click me</a>'), <ide> click: function() { originalEventHandlerWasCalled = true; } <ide> }); <ide> <ide> test("should not bubble an event from action helper to original parent event if <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "edit" bubbles=false}}>click me</a>'), <add> template: compile('<a href="#" {{action "edit" bubbles=false}}>click me</a>'), <ide> click: function() { originalEventHandlerWasCalled = true; } <ide> }); <ide> <ide> test("should allow 'send' as action name (#594)", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<a href="#" {{action "send" }}>send</a>') <add> template: compile('<a href="#" {{action "send" }}>send</a>') <ide> }); <ide> <ide> appendView(); <ide> test("should allow 'send' as action name (#594)", function() { <ide> }); <ide> <ide> <del>test("should send the view, event and current Handlebars context to the action", function() { <add>test("should send the view, event and current context to the action", function() { <ide> var passedTarget; <ide> var passedContext; <ide> <ide> test("should send the view, event and current Handlebars context to the action", <ide> <ide> view = EmberView.create({ <ide> context: aContext, <del> template: EmberHandlebars.compile('<a id="edit" href="#" {{action "edit" this target="aTarget"}}>edit</a>') <add> template: compile('<a id="edit" href="#" {{action "edit" this target=aTarget}}>edit</a>') <ide> }); <ide> <ide> appendView(); <ide> test("should only trigger actions for the event they were registered on", functi <ide> var editWasCalled = false; <ide> <ide> view = EmberView.extend({ <del> template: EmberHandlebars.compile('<a href="#" {{action "edit"}}>edit</a>'), <add> template: compile('<a href="#" {{action "edit"}}>edit</a>'), <ide> actions: { edit: function() { editWasCalled = true; } } <ide> }).create(); <ide> <ide> test("should unwrap controllers passed as a context", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<button {{action "edit" this}}>edit</button>') <add> template: compile('<button {{action "edit" this}}>edit</button>') <ide> }); <ide> <ide> appendView(); <ide> test("should not unwrap controllers passed as `controller`", function() { <ide> <ide> view = EmberView.create({ <ide> controller: controller, <del> template: EmberHandlebars.compile('<button {{action "edit" controller}}>edit</button>') <add> template: compile('<button {{action "edit" controller}}>edit</button>') <ide> }); <ide> <ide> appendView(); <ide> test("should allow multiple contexts to be specified", function() { <ide> controller: controller, <ide> modelA: models[0], <ide> modelB: models[1], <del> template: EmberHandlebars.compile('<button {{action "edit" view.modelA view.modelB}}>edit</button>') <add> template: compile('<button {{action "edit" view.modelA view.modelB}}>edit</button>') <ide> }); <ide> <ide> appendView(); <ide> test("should allow multiple contexts to be specified mixed with string args", fu <ide> view = EmberView.create({ <ide> controller: controller, <ide> modelA: model, <del> template: EmberHandlebars.compile('<button {{action "edit" "herp" view.modelA}}>edit</button>') <add> template: compile('<button {{action "edit" "herp" view.modelA}}>edit</button>') <ide> }); <ide> <ide> appendView(); <ide> test("should allow multiple contexts to be specified mixed with string args", fu <ide> deepEqual(passedParams, ["herp", model], "the action was called with the passed contexts"); <ide> }); <ide> <del>var compile = function(string) { <del> return EmberHandlebars.compile(string); <del>}; <del> <ide> test("it does not trigger action with special clicks", function() { <ide> var showCalled = false; <ide> <ide> test("a quoteless parameter should allow dynamic lookup of the actionName", func <ide> var actionOrder = []; <ide> <ide> view = EmberView.create({ <del> template: compile("<a id='woot-bound-param'' {{action hookMeUp}}>Hi</a>") <add> template: compile("<a id='woot-bound-param' {{action hookMeUp}}>Hi</a>") <ide> }); <ide> <ide> var controller = EmberController.extend({ <ide> test("a quoteless parameter should resolve actionName, including path", function <ide> deepEqual(actionOrder, ['whompWhomp', 'sloopyDookie', 'biggityBoom'], 'action name was looked up properly'); <ide> }); <ide> <del>test("a quoteless parameter that also exists as an action name functions properly", function(){ <del> expectDeprecation('You specified a quoteless path to the {{action}} helper \'ohNoeNotValid\' which did not resolve to an actionName. Perhaps you meant to use a quoted actionName? (e.g. {{action \'ohNoeNotValid\'}}).'); <del> var triggeredAction; <del> <del> view = EmberView.create({ <del> template: compile("<a id='oops-bound-param'' {{action ohNoeNotValid}}>Hi</a>") <del> }); <del> <del> var controller = EmberController.extend({ <del> actions: { <del> ohNoeNotValid: function() { <del> triggeredAction = true; <del> } <del> } <del> }).create(); <del> <del> run(function() { <del> view.set('controller', controller); <del> view.appendTo('#qunit-fixture'); <del> }); <del> <del> run(function(){ <del> view.$("#oops-bound-param").click(); <del> }); <del> <del> ok(triggeredAction, 'the action was triggered'); <del>}); <del> <del>test("a quoteless parameter that also exists as an action name results in a deprecation", function(){ <del> expectDeprecation('You specified a quoteless path to the {{action}} helper \'ohNoeNotValid\' which did not resolve to an actionName. Perhaps you meant to use a quoted actionName? (e.g. {{action \'ohNoeNotValid\'}}).'); <del> <add>test("a quoteless parameter that does not resolve to a value asserts", function(){ <ide> var triggeredAction; <ide> <ide> view = EmberView.create({ <ide> test("a quoteless parameter that also exists as an action name results in a depr <ide> view.appendTo('#qunit-fixture'); <ide> }); <ide> <del> run(function(){ <del> view.$("#oops-bound-param").click(); <del> }); <del> <del> ok(triggeredAction, 'the action was triggered'); <add> expectAssertion(function(){ <add> run(function(){ <add> view.$("#oops-bound-param").click(); <add> }); <add> }, "You specified a quoteless path to the {{action}} helper " + <add> "which did not resolve to an action name (a string). " + <add> "Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}})."); <ide> }); <ide> <del>QUnit.module("Ember.Handlebars - action helper - deprecated invoking directly on target", { <add>QUnit.module("ember-routing-htmlbars: action helper - deprecated invoking directly on target", { <ide> setup: function() { <del> originalActionHelper = EmberHandlebars.helpers['action']; <del> EmberHandlebars.registerHelper('action', actionHelper); <add> originalActionHelper = helpers['action']; <add> registerHelper('action', actionHelper); <ide> <ide> dispatcher = EventDispatcher.create(); <ide> dispatcher.setup(); <ide> }, <ide> <ide> teardown: function() { <del> delete EmberHandlebars.helpers['action']; <del> EmberHandlebars.helpers['action'] = originalActionHelper; <add> delete helpers['action']; <add> helpers['action'] = originalActionHelper; <ide> <ide> run(function() { <ide> dispatcher.destroy();
4
Javascript
Javascript
use document instead of $document
0a3ec5f8bbc1b51c9188f661df1697cc6a32c6a5
<ide><path>src/ng/urlUtils.js <ide> 'use strict'; <ide> <ide> function $$UrlUtilsProvider() { <del> this.$get = ['$document', function($document) { <del> var urlParsingNode = $document[0].createElement("a"), <del> // NOTE: The usage of window instead of $window here is deliberate. When the browser <del> // resolves a URL for XHR, it doesn't know about any mocked $window. $$urlUtils <del> // resolves URLs just as the browser would. Using $window here would confuse the <del> // isSameOrigin check causing unexpected failures. We avoid that by using the real window <del> // object. <add> this.$get = [function() { <add> var urlParsingNode = document.createElement("a"), <add> // NOTE: The usage of window and document instead of $window and $document here is <add> // deliberate. This service depends on the specific behavior of anchor nodes created by the <add> // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and <add> // cause us to break tests. In addition, when the browser resolves a URL for XHR, it <add> // doesn't know about mocked locations and resolves URLs to the real document - which is <add> // exactly the behavior needed here. There is little value is mocking these our for this <add> // service. <ide> originUrl = resolve(window.location.href, true); <ide> <ide> /**
1
Java
Java
introduce alias for 'value' attribute in @payload
250787a35a2422c0bc12b43232d89df75ca8b4a3
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Payload.java <ide> /* <del> * Copyright 2002-2014 the original author or authors. <add> * Copyright 2002-2015 the original author or authors. <ide> * <ide> * Licensed under the Apache License, Version 2.0 (the "License"); <ide> * you may not use this file except in compliance with the License. <ide> import java.lang.annotation.RetentionPolicy; <ide> import java.lang.annotation.Target; <ide> <add>import org.springframework.core.annotation.AliasFor; <ide> import org.springframework.messaging.converter.MessageConverter; <ide> <ide> /** <ide> * specific MIME type to an Object matching the target method parameter. <ide> * <ide> * @author Rossen Stoyanchev <add> * @author Sam Brannen <ide> * @since 4.0 <ide> */ <ide> @Target({ElementType.PARAMETER, ElementType.METHOD}) <ide> @Retention(RetentionPolicy.RUNTIME) <ide> @Documented <ide> public @interface Payload { <ide> <add> /** <add> * Alias for {@link #expression}. <add> */ <add> @AliasFor(attribute="expression") <add> String value() default ""; <add> <ide> /** <ide> * A SpEL expression to be evaluated against the payload object as the root context. <add> * <p> <ide> * This attribute may or may not be supported depending on whether the message being <del> * handled contains a non-primitive Object as its payload or is in serialized form <del> * and requires message conversion. <del> * <p>When processing STOMP over WebSocket messages this attribute is not supported. <add> * handled contains a non-primitive Object as its payload or is in serialized form and <add> * requires message conversion. <add> * <p> <add> * When processing STOMP over WebSocket messages this attribute is not supported. <ide> */ <del> String value() default ""; <add> @AliasFor(attribute="value") <add> String expression() default ""; <ide> <ide> /** <ide> * Whether payload content is required. <ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/PayloadArgumentResolver.java <ide> public boolean supportsParameter(MethodParameter parameter) { <ide> @Override <ide> public Object resolveArgument(MethodParameter param, Message<?> message) throws Exception { <ide> Payload ann = param.getParameterAnnotation(Payload.class); <del> if (ann != null && StringUtils.hasText(ann.value())) { <add> if (ann != null && StringUtils.hasText(ann.expression())) { <ide> throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver"); <ide> } <ide>
2
Java
Java
adjust logging of resource locations
76c9306dda572ab1be9b888feeb7b56ceb989d85
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/resource/ResourceWebHandler.java <ide> public void setUseLastModified(boolean useLastModified) { <ide> public void afterPropertiesSet() throws Exception { <ide> resolveResourceLocations(); <ide> <del> if (logger.isWarnEnabled() && CollectionUtils.isEmpty(getLocations())) { <del> logger.warn("Locations list is empty. No resources will be served unless a " + <del> "custom ResourceResolver is configured as an alternative to PathResourceResolver."); <del> } <del> <ide> if (this.resourceResolvers.isEmpty()) { <ide> this.resourceResolvers.add(new PathResourceResolver()); <ide> } <ide> private void resolveResourceLocations() { <ide> <ide> this.locationsToUse.clear(); <ide> this.locationsToUse.addAll(result); <add> <add> if (logger.isInfoEnabled()) { <add> logger.info(!this.locationsToUse.isEmpty() ? <add> "Locations in use: " + locationToString(this.locationsToUse) : <add> "0 locations in use."); <add> } <ide> } <ide> <ide> /** <ide> private void resolveResourceLocations() { <ide> */ <ide> protected void initAllowedLocations() { <ide> if (CollectionUtils.isEmpty(getLocations())) { <del> if (logger.isInfoEnabled()) { <del> logger.info("Locations list is empty. No resources will be served unless a " + <del> "custom ResourceResolver is configured as an alternative to PathResourceResolver."); <del> } <ide> return; <ide> } <ide> for (int i = getResourceResolvers().size() - 1; i >= 0; i--) { <ide> protected void setHeaders(ServerWebExchange exchange, Resource resource, @Nullab <ide> <ide> @Override <ide> public String toString() { <del> return "ResourceWebHandler " + formatLocations(); <add> return "ResourceWebHandler " + locationToString(getLocations()); <ide> } <ide> <del> private Object formatLocations() { <del> if (!this.locationValues.isEmpty()) { <del> return this.locationValues.stream().collect(Collectors.joining("\", \"", "[\"", "\"]")); <del> } <del> if (!getLocations().isEmpty()) { <del> return "[" + getLocations().toString() <del> .replaceAll("class path resource", "Classpath") <del> .replaceAll("ServletContext resource", "ServletContext") + "]"; <del> } <del> return Collections.emptyList(); <add> private String locationToString(List<Resource> locations) { <add> return locations.toString() <add> .replaceAll("class path resource", "classpath") <add> .replaceAll("ServletContext resource", "ServletContext"); <ide> } <add> <ide> } <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/resource/ResourceHttpRequestHandler.java <ide> public void setUseLastModified(boolean useLastModified) { <ide> public void afterPropertiesSet() throws Exception { <ide> resolveResourceLocations(); <ide> <del> if (logger.isWarnEnabled() && CollectionUtils.isEmpty(getLocations())) { <del> logger.warn("Locations list is empty. No resources will be served unless a " + <del> "custom ResourceResolver is configured as an alternative to PathResourceResolver."); <del> } <del> <ide> if (this.resourceResolvers.isEmpty()) { <ide> this.resourceResolvers.add(new PathResourceResolver()); <ide> } <ide> private void resolveResourceLocations() { <ide> <ide> this.locationsToUse.clear(); <ide> this.locationsToUse.addAll(result); <add> <add> if (logger.isInfoEnabled()) { <add> logger.info(!this.locationsToUse.isEmpty() ? <add> "Locations in use: " + locationToString(this.locationsToUse) : <add> "0 locations in use."); <add> } <ide> } <ide> <ide> /** <ide> protected void setHeaders(HttpServletResponse response, Resource resource, @Null <ide> <ide> @Override <ide> public String toString() { <del> return "ResourceHttpRequestHandler " + <del> getLocations().toString() <del> .replaceAll("class path resource", "Classpath") <del> .replaceAll("ServletContext resource", "ServletContext"); <add> return "ResourceHttpRequestHandler " + locationToString(getLocations()); <add> } <add> <add> private String locationToString(List<Resource> locations) { <add> return locations.toString() <add> .replaceAll("class path resource", "classpath") <add> .replaceAll("ServletContext resource", "ServletContext"); <ide> } <ide> <ide> }
2
Ruby
Ruby
remove duplicated logic from fromurlloader
633f29af5d3c96efb79c513375a8914ee0a0c163
<ide><path>Library/Homebrew/formulary.rb <ide> def initialize url <ide> super formula, HOMEBREW_CACHE_FORMULA/File.basename(uri.path) <ide> end <ide> <del> # Downloads the formula's .rb file <del> def fetch <del> begin <del> have_klass = Formulary.formula_class_defined? class_name <del> rescue NameError <del> raise FormulaUnavailableError.new(name) <del> end <del> <del> unless have_klass <del> HOMEBREW_CACHE_FORMULA.mkpath <del> FileUtils.rm path.to_s, :force => true <del> curl url, '-o', path.to_s <del> end <del> end <del> <del> def get_formula(spec) <del> fetch <add> def load_file <add> HOMEBREW_CACHE_FORMULA.mkpath <add> FileUtils.rm_f(path) <add> curl url, "-o", path <ide> super <ide> end <ide> end
1
PHP
PHP
change the default value of empty to false
c90008344884522cae43d2d386dea44683e24132
<ide><path>src/View/Helper/FormHelper.php <ide> public function select($fieldName, $options = [], $attributes = []) { <ide> 'hiddenField' => true, <ide> 'multiple' => null, <ide> 'secure' => true, <del> 'empty' => isset($attributes['multiple']) ? false : true <add> 'empty' => false, <ide> ]; <ide> <ide> if ($attributes['multiple'] === 'checkbox') { <ide><path>tests/TestCase/View/Helper/FormHelperTest.php <ide> public function testSelect() { <ide> $result = $this->Form->select('Model.field', array()); <ide> $expected = array( <ide> 'select' => array('name' => 'Model[field]'), <del> array('option' => array('value' => '')), <del> '/option', <ide> '/select' <ide> ); <ide> $this->assertTags($result, $expected); <ide> public function testSelect() { <ide> $result = $this->Form->select('Model.field', array('value' => 'good', 'other' => 'bad')); <ide> $expected = array( <ide> 'select' => array('name' => 'Model[field]'), <del> array('option' => array('value' => '')), <del> '/option', <ide> array('option' => array('value' => 'value', 'selected' => 'selected')), <ide> 'good', <ide> '/option', <ide> public function testSelect() { <ide> $result = $this->Form->select('Model.field', array('value' => 'good', 'other' => 'bad')); <ide> $expected = array( <ide> 'select' => array('name' => 'Model[field]'), <del> array('option' => array('value' => '')), <del> '/option', <ide> array('option' => array('value' => 'value')), <ide> 'good', <ide> '/option', <ide> public function testSelect() { <ide> $result = $this->Form->select('Model.field', array('0' => 'No', '1' => 'Yes')); <ide> $expected = array( <ide> 'select' => array('name' => 'Model[field]'), <del> array('option' => array('value' => '')), '/option', <ide> array('option' => array('value' => '0', 'selected' => 'selected')), 'No', '/option', <ide> array('option' => array('value' => '1')), 'Yes', '/option', <ide> '/select' <ide> public function testSelectRequired() { <ide> 'name' => 'user_id', <ide> 'required' => 'required' <ide> ), <del> array('option' => array('value' => '')), '/option', <ide> array('option' => array('value' => '0')), 'option A', '/option', <ide> '/select' <ide> ); <ide> public function testSelectRequired() { <ide> 'name' => 'user_id', <ide> 'disabled' => 'disabled' <ide> ), <del> array('option' => array('value' => '')), '/option', <ide> array('option' => array('value' => '0')), 'option A', '/option', <ide> '/select' <ide> ); <ide> public function testSelectMultipleCheckboxRequestData() { <ide> * @return void <ide> */ <ide> public function testSelectMultipleCheckboxSecurity() { <del> $this->Form->request->params['_Token'] = 'foo'; <add> $this->Form->request->params['_Token'] = 'testKey'; <ide> $this->assertEquals(array(), $this->Form->fields); <ide> <ide> $result = $this->Form->select( <ide> public function testSelectMultipleCheckboxSecurity() { <ide> * @return void <ide> */ <ide> public function testSelectMultipleSecureWithNoOptions() { <del> $this->Form->request->params['_Token'] = 'testkey'; <ide> $this->assertEquals(array(), $this->Form->fields); <ide> <ide> $this->Form->select( <ide> public function testSelectMultipleSecureWithNoOptions() { <ide> ); <ide> $this->assertEquals(array('Model.select'), $this->Form->fields); <ide> } <add> <ide> /** <ide> * When a select box has no options it should not be added to the fields list <ide> * as it always fail post validation. <ide> * <ide> * @return void <ide> */ <ide> public function testSelectNoSecureWithNoOptions() { <del> $this->markTestIncomplete('Need to revisit once models work again.'); <del> $this->Form->request->params['_csrfToken'] = 'testkey'; <del> $this->assertEquals(array(), $this->Form->fields); <add> $this->Form->request->params['_Token'] = 'testkey'; <add> $this->assertEquals([], $this->Form->fields); <ide> <ide> $this->Form->select( <ide> 'Model.select', <del> array() <add> [] <ide> ); <del> $this->assertEquals(array(), $this->Form->fields); <add> $this->assertEquals([], $this->Form->fields); <ide> <ide> $this->Form->select( <del> 'Model.select', <del> array(), <del> array('empty' => true) <add> 'Model.user_id', <add> [], <add> ['empty' => true] <ide> ); <del> $this->assertEquals(array('Model.select'), $this->Form->fields); <add> $this->assertEquals(array('Model.user_id'), $this->Form->fields); <ide> } <ide> <ide> /**
2
Javascript
Javascript
fix broken download button
4fc64ceb76162d01d9ec38a869a7a96f9b13a4f2
<ide><path>web/compatibility.js <ide> var isAndroidPre3 = /Android\s[0-2][^\d]/.test(userAgent); <ide> var isAndroidPre5 = /Android\s[0-4][^\d]/.test(userAgent); <ide> var isChrome = userAgent.indexOf('Chrom') >= 0; <ide> var isChromeWithRangeBug = /Chrome\/(39|40)\./.test(userAgent); <add>var isIOSChrome = userAgent.indexOf('CriOS') >= 0; <ide> var isIE = userAgent.indexOf('Trident') >= 0; <ide> var isIOS = /\b(iPad|iPhone|iPod)(?=;)/.test(userAgent); <ide> var isOpera = userAgent.indexOf('Opera') >= 0; <ide> if (typeof PDFJS === 'undefined') { <ide> })(); <ide> <ide> // Checks if possible to use URL.createObjectURL() <del>// Support: IE <add>// Support: IE, Chrome on iOS <ide> (function checkOnBlobSupport() { <del> // sometimes IE loosing the data created with createObjectURL(), see #3977 <del> if (isIE) { <add> // sometimes IE and Chrome on iOS loosing the data created with <add> // createObjectURL(), see #3977 and #8081 <add> if (isIE || isIOSChrome) { <ide> PDFJS.disableCreateObjectURL = true; <ide> } <ide> })(); <ide><path>web/download_manager.js <ide> if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC || CHROME')) { <ide> }, <ide> <ide> download: function DownloadManager_download(blob, url, filename) { <del> if (!URL) { <del> // URL.createObjectURL is not supported <del> this.downloadUrl(url, filename); <del> return; <del> } <del> <ide> if (navigator.msSaveBlob) { <ide> // IE10 / IE11 <ide> if (!navigator.msSaveBlob(blob, filename)) { <ide> if (typeof PDFJSDev === 'undefined' || PDFJSDev.test('GENERIC || CHROME')) { <ide> return; <ide> } <ide> <add> if (pdfjsLib.PDFJS.disableCreateObjectURL) { <add> // URL.createObjectURL is not supported <add> this.downloadUrl(url, filename); <add> return; <add> } <add> <ide> var blobUrl = URL.createObjectURL(blob); <ide> download(blobUrl, filename); <ide> }
2
Javascript
Javascript
fix regex to include .jsx
5fbc2253c493d0feb7b5d23b8492e2b0d56bfeb6
<ide><path>examples/todomvc/webpack.config.js <ide> module.exports = { <ide> }, <ide> module: { <ide> loaders: [{ <del> test: /\.js?$/, <add> test: /\.jsx?$/, <ide> loaders: ['react-hot', 'babel'], <ide> exclude: /node_modules/ <ide> }, {
1
Ruby
Ruby
fix rubocop warnings
17a7c2388193de0c7aed556df92ca955ffec2753
<ide><path>Library/Homebrew/extend/ARGV.rb <ide> def kegs <ide> <ide> dirs = rack.directory? ? rack.subdirs : [] <ide> <del> raise NoSuchKegError.new(rack.basename) if dirs.empty? <add> raise NoSuchKegError, rack.basename if dirs.empty? <ide> <ide> linked_keg_ref = HOMEBREW_LIBRARY.join("LinkedKegs", rack.basename) <ide> opt_prefix = HOMEBREW_PREFIX.join("opt", rack.basename) <ide> def kegs <ide> if (prefix = f.installed_prefix).directory? <ide> Keg.new(prefix) <ide> else <del> raise MultipleVersionsInstalledError.new(rack.basename) <add> raise MultipleVersionsInstalledError, rack.basename <ide> end <ide> end <ide> rescue FormulaUnavailableError <ide> def build_all_from_source? <ide> # installation run. <ide> def build_formula_from_source?(f) <ide> return true if build_all_from_source? <del> return false unless (build_from_source? || build_bottle?) <add> return false unless build_from_source? || build_bottle? <ide> formulae.any? { |argv_f| argv_f.full_name == f.full_name } <ide> end <ide>
1
Text
Text
add explanation for returning payload
ef87f059131ec607305c3cfe963c37359b601e0e
<ide><path>docs/tutorials/essentials/part-5-async-logic.md <ide> const usersSlice = createSlice({ <ide> export default usersSlice.reducer <ide> ``` <ide> <add>You may noticed that our reducer is not using the `state` variable at all. <add>Instead, we are returning the action payload directly. <add>This has the effect that the existing state is completely replaced with whatever we are returning. <add>In our case, we are replacing the initial state that was empty and therefore `state.push(...action.payload)` would have the same result. <add>But, this could introduce subtle bug is we are not sure that the client state is empty and we want to synchronize the client with the server state. <add>To learn more about how state updates with Immer work, see the ["Writing Reducers with Immer" section in the RTK docs](https://redux-toolkit.js.org/usage/immer-reducers#immer-usage-patterns). <add> <ide> We only need to fetch the list of users once, and we want to do it right when the application starts. We can do that in our `index.js` file, and directly dispatch the `fetchUsers` thunk because we have the `store` right there: <ide> <ide> ```js title="index.js"
1
Ruby
Ruby
move no insecure redirect check to _fetch
75ab94c8ea8940f1609e62d23d45d8729dd4a83f
<ide><path>Library/Homebrew/download_strategy.rb <ide> def fetch <ide> ohai "Downloading #{@url}" <ide> <ide> unless cached_location.exist? <del> urls = actual_urls <del> unless urls.empty? <del> ohai "Downloading from #{urls.last}" <del> if !ENV["HOMEBREW_NO_INSECURE_REDIRECT"].nil? && @url.start_with?("https://") && <del> urls.any? { |u| !u.start_with? "https://" } <del> puts "HTTPS to HTTP redirect detected & HOMEBREW_NO_INSECURE_REDIRECT is set." <del> raise CurlDownloadStrategyError.new(@url) <del> end <del> @url = urls.last <del> end <del> <ide> had_incomplete_download = temporary_path.exist? <ide> begin <ide> _fetch <ide> def clear_cache <ide> <ide> # Private method, can be overridden if needed. <ide> def _fetch <add> urls = actual_urls <add> unless urls.empty? <add> ohai "Downloading from #{urls.last}" <add> if !ENV["HOMEBREW_NO_INSECURE_REDIRECT"].nil? && @url.start_with?("https://") && <add> urls.any? { |u| !u.start_with? "https://" } <add> puts "HTTPS to HTTP redirect detected & HOMEBREW_NO_INSECURE_REDIRECT is set." <add> raise CurlDownloadStrategyError.new(@url) <add> end <add> @url = urls.last <add> end <add> <ide> curl @url, "-C", downloaded_size, "-o", temporary_path <ide> end <ide>
1
Text
Text
add documentation about templating support on…
4571ad05dba48eda9d138c4db20bd2a63022ff63
<ide><path>docs/reference/commandline/service_create.md <ide> accessible at the target port on every node regardless if there is a task for <ide> the service running on the node. For more information refer to <ide> [Use swarm mode routing mesh](https://docs.docker.com/engine/swarm/ingress/). <ide> <add>### Create services using templates <add> <add>You can use templates for some flags of `service create`, using the syntax <add>provided by the Go's [text/template](http://golange.org/pkg/text/template/) package. <add> <add>The supported flags are the following : <add> <add>- `--hostname` <add>- `--mount` <add>- `--env` <add> <add>Valid placeholders for the Go template are listed below: <add> <add>Placeholder | Description <add>----------------- | -------------------------------------------- <add>`.Service.ID` | Service ID <add>`.Service.Name` | Service name <add>`.Service.Labels` | Service labels <add>`.Node.ID` | Node ID <add>`.Task.ID` | Task ID <add>`.Task.Name` | Task name <add>`.Task.Slot` | Task slot <add> <add>#### Template example <add> <add>In this example, we are going to set the template of the created containers based on the <add>service's name and the node's ID where it sits. <add> <add>```bash <add>$ docker service create --name hosttempl --hostname={% raw %}"{{.Node.ID}}-{{.Service.Name}}"{% endraw %} busybox top <add>va8ew30grofhjoychbr6iot8c <add>$ docker service ps va8ew30grofhjoychbr6iot8c <add>NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS <add>hosttempl.1.wo41w8hg8qan busybox:latest@sha256:29f5d56d12684887bdfa50dcd29fc31eea4aaf4ad3bec43daf19026a7ce69912 2e7a8a9c4da2 Running Running about a minute ago <add>$ docker inspect --format={% raw %}"{{.Config.Hostname}}"{% endraw %} hosttempl.1.wo41w8hg8qanxwjwsg4kxpprj <add>x3ti0erg11rjpg64m75kej2mz-hosttempl <add>``` <add> <ide> ## Related information <ide> <ide> * [service inspect](service_inspect.md) <ide><path>docs/reference/commandline/service_update.md <ide> $ docker service update \ <ide> myservice <ide> ``` <ide> <add>### Update services using templates <add> <add>Some flags of `service update` support the use of templating. <add>See [`service create`](./service_create.md#templating) for the reference. <add> <ide> ## Related information <ide> <ide> * [service create](service_create.md)
2
Javascript
Javascript
unify constructor inspection in `util.inspect`
370ddefc14a0bae1027749e0b75b65d0b6b786e9
<ide><path>lib/internal/util/inspect.js <ide> function getKeys(value, showHidden) { <ide> return keys; <ide> } <ide> <del>function getCtxStyle(constructor, tag) { <del> return constructor || tag || 'Object'; <add>function getCtxStyle(value, constructor, tag) { <add> let fallback = ''; <add> if (constructor === null) { <add> fallback = internalGetConstructorName(value); <add> if (fallback === tag) { <add> fallback = 'Object'; <add> } <add> } <add> return getPrefix(constructor, tag, fallback); <ide> } <ide> <ide> function formatProxy(ctx, proxy, recurseTimes) { <ide> function formatRaw(ctx, value, recurseTimes, typedArray) { <ide> formatter = formatIterator; <ide> // Handle other regular objects again. <ide> } else { <del> let fallback = ''; <del> if (constructor === null) { <del> fallback = internalGetConstructorName(value); <del> if (fallback === tag) { <del> fallback = 'Object'; <del> } <del> } <ide> if (keys.length === 0) { <ide> if (isExternal(value)) <ide> return ctx.stylize('[External]', 'special'); <del> return `${getPrefix(constructor, tag, fallback)}{}`; <add> return `${getCtxStyle(value, constructor, tag)}{}`; <ide> } <del> braces[0] = `${getPrefix(constructor, tag, fallback)}{`; <add> braces[0] = `${getCtxStyle(value, constructor, tag)}{`; <ide> } <ide> } <ide> } <ide> <ide> if (recurseTimes > ctx.depth && ctx.depth !== null) { <del> return ctx.stylize(`[${getCtxStyle(constructor, tag)}]`, 'special'); <add> let constructorName = getCtxStyle(value, constructor, tag).slice(0, -1); <add> if (constructor !== null) <add> constructorName = `[${constructorName}]`; <add> return ctx.stylize(constructorName, 'special'); <ide> } <ide> recurseTimes += 1; <ide> <ide> function formatRaw(ctx, value, recurseTimes, typedArray) { <ide> formatProperty(ctx, value, recurseTimes, keys[i], extrasType)); <ide> } <ide> } catch (err) { <del> return handleMaxCallStackSize(ctx, err, constructor, tag, indentationLvl); <add> const constructorName = getCtxStyle(value, constructor, tag).slice(0, -1); <add> return handleMaxCallStackSize(ctx, err, constructorName, indentationLvl); <ide> } <ide> ctx.seen.pop(); <ide> <ide> function groupArrayElements(ctx, output) { <ide> return output; <ide> } <ide> <del>function handleMaxCallStackSize(ctx, err, constructor, tag, indentationLvl) { <add>function handleMaxCallStackSize(ctx, err, constructorName, indentationLvl) { <ide> if (isStackOverflowError(err)) { <ide> ctx.seen.pop(); <ide> ctx.indentationLvl = indentationLvl; <ide> return ctx.stylize( <del> `[${getCtxStyle(constructor, tag)}: Inspection interrupted ` + <add> `[${constructorName}: Inspection interrupted ` + <ide> 'prematurely. Maximum call stack size exceeded.]', <ide> 'special' <ide> ); <ide><path>test/parallel/test-util-inspect.js <ide> if (typeof Symbol !== 'undefined') { <ide> '[Set Iterator] { 1, ... 1 more item, extra: true }'); <ide> } <ide> <add>// Minimal inspection should still return as much information as possible about <add>// the constructor and Symbol.toStringTag. <add>{ <add> class Foo { <add> get [Symbol.toStringTag]() { <add> return 'ABC'; <add> } <add> } <add> const a = new Foo(); <add> assert.strictEqual(inspect(a, { depth: -1 }), 'Foo [ABC] {}'); <add> a.foo = true; <add> assert.strictEqual(inspect(a, { depth: -1 }), '[Foo [ABC]]'); <add> Object.defineProperty(a, Symbol.toStringTag, { <add> value: 'Foo', <add> configurable: true, <add> writable: true <add> }); <add> assert.strictEqual(inspect(a, { depth: -1 }), '[Foo]'); <add> delete a[Symbol.toStringTag]; <add> Object.setPrototypeOf(a, null); <add> assert.strictEqual(inspect(a, { depth: -1 }), '[Foo: null prototype]'); <add> delete a.foo; <add> assert.strictEqual(inspect(a, { depth: -1 }), '[Foo: null prototype] {}'); <add> Object.defineProperty(a, Symbol.toStringTag, { <add> value: 'ABC', <add> configurable: true <add> }); <add> assert.strictEqual( <add> inspect(a, { depth: -1 }), <add> '[Foo: null prototype] [ABC] {}' <add> ); <add> Object.defineProperty(a, Symbol.toStringTag, { <add> value: 'Foo', <add> configurable: true <add> }); <add> assert.strictEqual( <add> inspect(a, { depth: -1 }), <add> '[Object: null prototype] [Foo] {}' <add> ); <add>} <add> <ide> // Test alignment of items in container. <ide> // Assumes that the first numeric character is the start of an item. <ide> {
2
Javascript
Javascript
fix global leaks
a0159b4b295f69e5653ef96d88de579746dcfdc8
<ide><path>lib/http.js <ide> OutgoingMessage.prototype._storeHeader = function(firstLine, headers) { <ide> if (headers) { <ide> var keys = Object.keys(headers); <ide> var isArray = (Array.isArray(headers)); <add> var field, value; <ide> <ide> for (var i = 0, l = keys.length; i < l; i++) { <ide> var key = keys[i]; <ide> OutgoingMessage.prototype.addTrailers = function(headers) { <ide> this._trailer = ''; <ide> var keys = Object.keys(headers); <ide> var isArray = (Array.isArray(headers)); <add> var field, value; <ide> for (var i = 0, l = keys.length; i < l; i++) { <ide> var key = keys[i]; <ide> if (isArray) { <ide><path>lib/string_decoder.js <ide> StringDecoder.prototype.write = function(buffer) { <ide> // Figure out if one of the last i bytes of our buffer announces an <ide> // incomplete char. <ide> for (; i > 0; i--) { <del> c = buffer[buffer.length - i]; <add> var c = buffer[buffer.length - i]; <ide> <ide> // See http://en.wikipedia.org/wiki/UTF-8#Description <ide> <ide><path>test/disabled/test-dns.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var dns = require("dns"), <ide> child_process = require("child_process"); <ide><path>test/disabled/test-eio-race3.js <ide> /* XXX Can this test be modified to not call the now-removed wait()? */ <ide> <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> <ide> console.log('first stat ...'); <ide><path>test/disabled/test-fs-sendfile.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> tcp = require("tcp"); <ide> util = require("util"); <ide><path>test/disabled/test-http-big-proxy-responses.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var util = require("util"), <ide> fs = require("fs"), <ide> http = require("http"), <ide><path>test/disabled/test-http-head-request.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var assert = require("assert"); <ide> var http = require("http"); <ide><path>test/disabled/test-http-stress.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> http = require("http"); <ide> <ide><path>test/disabled/test-http-tls.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> net = require("net"); <ide> http = require("http"); <ide> url = require("url"); <ide><path>test/disabled/test-idle-watcher.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var complete = false; <ide> var idle = new process.IdleWatcher(); <ide><path>test/disabled/test-net-tls-pummel.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> net = require("net"); <ide> fs=require("fs"); <ide> <ide><path>test/disabled/test-net-tls.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var fs = require('fs'); <ide> var net = require('net'); <ide> <ide><path>test/disabled/test-readline.js <ide> // Can't test this when 'make test' doesn't assign a tty to the stdout. <ide> // Yet another use-case for require('tty').spawn ? <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var readline = require("readline"); <ide> <ide> var key = { <ide><path>test/disabled/test-remote-module-loading.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var http = require('http'); <ide> var util = require('util'); <ide><path>test/disabled/test-setuidgid.js <ide> // Requires special privlages <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var assert = require('assert'); <ide> <ide> var oldgid = process.getgid(); <ide><path>test/disabled/tls_client.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var util=require('util'); <ide> var net=require('net'); <ide> var fs=require('fs'); <ide><path>test/disabled/tls_server.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var util=require('util'); <ide> var net=require('net'); <ide><path>test/fixtures/a.js <ide> var c = require('./b/c'); <ide> <del>common.debug('load fixtures/a.js'); <add>console.error('load fixtures/a.js'); <ide> <ide> var string = 'A'; <ide> <ide><path>test/fixtures/b/c.js <ide> var package = require('./package'); <ide> <ide> assert.equal('world', package.hello); <ide> <del>common.debug('load fixtures/b/c.js'); <add>console.error('load fixtures/b/c.js'); <ide> <ide> var string = 'C'; <ide> <ide><path>test/fixtures/b/d.js <del>common.debug('load fixtures/b/d.js'); <add>console.error('load fixtures/b/d.js'); <ide> <ide> var string = 'D'; <ide> <ide><path>test/fixtures/b/package/index.js <ide> exports.hello = 'world'; <del>common.debug('load package/index.js'); <add>console.error('load package/index.js'); <ide><path>test/fixtures/echo.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> common.print('hello world\r\n'); <ide> <ide><path>test/fixtures/print-chars-from-buffer.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> Buffer = require('buffer').Buffer; <ide> <ide> var n = parseInt(process.argv[2]); <ide><path>test/fixtures/print-chars.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var n = parseInt(process.argv[2]); <ide> <ide><path>test/pummel/test-child-process-spawn-loop.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var spawn = require('child_process').spawn; <ide> <ide><path>test/pummel/test-http-client-reconnect-bug.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var net = require('net'), <ide> util = require('util'), <ide><path>test/pummel/test-keep-alive.js <ide> // This test requires the program 'ab' <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> http = require('http'); <ide> exec = require('child_process').exec; <ide> <ide><path>test/pummel/test-net-many-clients.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> net = require('net'); <ide> // settings <ide> var bytes = 1024 * 40; <ide><path>test/pummel/test-net-pingpong-delay.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> net = require('net'); <ide> <ide> <ide><path>test/pummel/test-net-pingpong.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> net = require('net'); <ide> <ide> var tests_run = 0; <ide><path>test/pummel/test-net-throttle.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> net = require('net'); <ide> N = 160 * 1024; // 30kb <ide> <ide><path>test/pummel/test-net-timeout.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> net = require('net'); <ide> exchanges = 0; <ide> starttime = null; <ide><path>test/pummel/test-timers.js <del>common = require('../common'); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> assert = require('assert'); <ide> <ide><path>test/pummel/test-watch-file.js <del>common = require('../common'); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var fs = require('fs'); <ide> var path = require('path'); <ide><path>test/simple/test-assert.js <del>common = require("../common"); <del>assert = common.assert <del> <add>var common = require("../common"); <add>var assert = require('assert'); <ide> var a = require('assert'); <ide> <ide> function makeBlock (f) { <ide> assert.throws(makeBlock(a.deepEqual, 'a', {}), a.AssertionError); <ide> function thrower (errorConstructor){ <ide> throw new errorConstructor('test'); <ide> } <del>aethrow = makeBlock(thrower, a.AssertionError); <add>var aethrow = makeBlock(thrower, a.AssertionError); <ide> aethrow = makeBlock(thrower, a.AssertionError); <ide> <ide> // the basic calls work <ide><path>test/simple/test-c-ares.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var dns = require("dns"); <ide> <ide><path>test/simple/test-chdir.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> assert.equal(true, process.cwd() !== __dirname); <ide> <ide><path>test/simple/test-child-process-buffering.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var spawn = require('child_process').spawn; <ide> <ide><path>test/simple/test-child-process-custom-fds.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require("../common"); <add>var assert = require('assert'); <ide> <ide> var assert = require('assert'); <ide> var spawn = require('child_process').spawn; <ide><path>test/simple/test-child-process-cwd.js <del>common = require("../common"); <del>assert = common.assert <del>spawn = require('child_process').spawn, <del>path = require('path'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var spawn = require('child_process').spawn; <add>var path = require('path'); <ide> <ide> var returns = 0; <ide> <ide><path>test/simple/test-child-process-deprecated-api.js <ide> var exits = 0; <ide> // Check if all child processes exited <ide> process.addListener('exit', function () { <ide> assert.equal(2, exits); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/simple/test-child-process-env.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require("../common"); <add>var assert = require('assert'); <ide> <ide> var spawn = require('child_process').spawn; <del>child = spawn('/usr/bin/env', [], {env: {'HELLO' : 'WORLD'}}); <add>var child = spawn('/usr/bin/env', [], {env: {'HELLO' : 'WORLD'}}); <ide> <del>response = ""; <add>var response = ""; <ide> <ide> child.stdout.setEncoding('utf8'); <ide> <ide><path>test/simple/test-child-process-exec-cwd.js <ide> var exec = require('child_process').exec; <ide> var success_count = 0; <ide> var error_count = 0; <ide> <del>child = exec('pwd', {cwd: "/dev"}, function (err, stdout, stderr) { <add>var child = exec('pwd', {cwd: "/dev"}, function (err, stdout, stderr) { <ide> if (err) { <ide> error_count++; <ide> console.log('error!: ' + err.code); <ide> child = exec('pwd', {cwd: "/dev"}, function (err, stdout, stderr) { <ide> process.addListener('exit', function () { <ide> assert.equal(1, success_count); <ide> assert.equal(0, error_count); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/simple/test-child-process-exec-env.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var exec = require('child_process').exec; <del>success_count = 0; <del>error_count = 0; <del>response = ""; <add>var success_count = 0; <add>var error_count = 0; <add>var response = ""; <ide> <del>child = exec('/usr/bin/env', { env: {'HELLO' : 'WORLD'}}, function (err, stdout, stderr) { <add>var child = exec('/usr/bin/env', { env: {'HELLO' : 'WORLD'}}, function (err, stdout, stderr) { <ide> if (err) { <ide> error_count++; <ide> console.log('error!: ' + err.code); <ide><path>test/simple/test-child-process-exit-code.js <del>common = require("../common"); <del>assert = common.assert <del>spawn = require('child_process').spawn, <del>path = require('path'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var spawn = require('child_process').spawn; <add>var path = require('path'); <ide> <del>exits = 0; <add>var exits = 0; <ide> <del>exitScript = path.join(common.fixturesDir, 'exit.js') <del>exitChild = spawn(process.argv[0], [exitScript, 23]); <add>var exitScript = path.join(common.fixturesDir, 'exit.js') <add>var exitChild = spawn(process.argv[0], [exitScript, 23]); <ide> exitChild.addListener('exit', function(code, signal) { <ide> assert.strictEqual(code, 23); <ide> assert.strictEqual(signal, null); <ide> exitChild.addListener('exit', function(code, signal) { <ide> <ide> <ide> <del>errorScript = path.join(common.fixturesDir, 'child_process_should_emit_error.js') <del>errorChild = spawn(process.argv[0], [errorScript]); <add>var errorScript = path.join(common.fixturesDir, 'child_process_should_emit_error.js') <add>var errorChild = spawn(process.argv[0], [errorScript]); <ide> errorChild.addListener('exit', function(code, signal) { <ide> assert.ok(code !== 0); <ide> assert.strictEqual(signal, null); <ide><path>test/simple/test-child-process-ipc.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var spawn = require('child_process').spawn; <ide> <ide><path>test/simple/test-child-process-kill.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var spawn = require('child_process').spawn; <ide> <ide><path>test/simple/test-child-process-stdin.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var spawn = require('child_process').spawn; <ide> <ide><path>test/simple/test-child-process-stdout-flush.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'); <ide> var spawn = require('child_process').spawn; <ide> var sub = path.join(common.fixturesDir, 'print-chars.js'); <ide> <del>n = 500000; <add>var n = 500000; <ide> <ide> var child = spawn(process.argv[0], [sub, n]); <ide> <ide><path>test/simple/test-console.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var stdout_write = global.process.stdout.write; <ide> var strings = []; <ide><path>test/simple/test-crypto.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> try { <ide> var crypto = require('crypto'); <ide> var h2 = crypto.createHash("sha1").update("Test").update("123").digest("hex"); <ide> assert.equal(h1, h2, "multipled updates"); <ide> <ide> // Test hashing for binary files <del>fn = path.join(common.fixturesDir, 'sample.png'); <add>var fn = path.join(common.fixturesDir, 'sample.png'); <ide> var sha1Hash = crypto.createHash('sha1'); <ide> var fileStream = fs.createReadStream(fn); <ide> fileStream.addListener('data', function(data){ <ide><path>test/simple/test-delayed-require.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <add>var a; <ide> setTimeout(function () { <ide> a = require("../fixtures/a"); <ide> }, 50); <ide><path>test/simple/test-dgram-multicast.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var dgram = require("dgram"), <ide> util = require('util'), <ide> sendSocket.sendNext = function () { <ide> }); <ide> }; <ide> <del>listener_count = 0; <add>var listener_count = 0; <ide> <ide> function mkListener() { <ide> var receivedMessages = []; <ide><path>test/simple/test-dgram-pingpong.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var Buffer = require('buffer').Buffer; <ide> var dgram = require("dgram"); <ide> <ide><path>test/simple/test-dgram-udp4.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var Buffer = require("buffer").Buffer, <ide> fs = require("fs"), <ide><path>test/simple/test-dgram-unix-anon.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var Buffer = require("buffer").Buffer, <ide> fs = require("fs"), <ide><path>test/simple/test-dgram-unix.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <del>fs = require("fs"); <del>dgram = require("dgram"); <add>var fs = require("fs"); <add>var dgram = require("dgram"); <ide> <del>serverPath = "/tmp/dgram_server_sock"; <del>clientPath = "/tmp/dgram_client_sock"; <del>msgToSend = new Buffer("A message to send"); <add>// TODO use common.tmpDir here <add>var serverPath = "/tmp/dgram_server_sock"; <add>var clientPath = "/tmp/dgram_client_sock"; <ide> <del>server = dgram.createSocket("unix_dgram"); <add>var msgToSend = new Buffer("A message to send"); <add> <add>var server = dgram.createSocket("unix_dgram"); <ide> server.on("message", function (msg, rinfo) { <ide> console.log("server got: " + msg + " from " + rinfo.address); <ide> assert.strictEqual(rinfo.address, clientPath); <ide> server.on("message", function (msg, rinfo) { <ide> server.on("listening", function () { <ide> console.log("server is listening"); <ide> <del> client = dgram.createSocket("unix_dgram"); <add> var client = dgram.createSocket("unix_dgram"); <ide> <ide> client.on("message", function (msg, rinfo) { <ide> console.log("client got: " + msg + " from " + rinfo.address); <ide><path>test/simple/test-eio-race.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var count = 100; <ide> var fs = require('fs'); <ide><path>test/simple/test-eio-race2.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'); <ide> var testTxt = path.join(common.fixturesDir, "x.txt"); <ide> var fs = require('fs'); <ide> <ide> setTimeout(function () { <ide> // put this in a timeout, just so it doesn't get bunched up with the <ide> // require() calls.. <del> N = 30; <add> var N = 30; <ide> for (var i=0; i < N; i++) { <ide> console.log("start " + i); <ide> fs.readFile(testTxt, function(err, data) { <ide><path>test/simple/test-eio-race4.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var fs = require('fs'); <ide> var N = 100; <ide> var j = 0; <ide><path>test/simple/test-error-reporting.js <del>common = require("../common"); <del>assert = common.assert <del>exec = require('child_process').exec, <del>path = require('path'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var exec = require('child_process').exec; <add>var path = require('path'); <ide> <del>exits = 0; <add>var exits = 0; <ide> <ide> function errExec (script, callback) { <ide> var cmd = process.argv[0] + ' ' + path.join(common.fixturesDir, script); <ide><path>test/simple/test-event-emitter-add-listeners.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var events = require('events'); <ide> <ide> var e = new events.EventEmitter(); <ide><path>test/simple/test-event-emitter-modify-in-emit.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var events = require('events'); <ide> <ide> var callbacks_called = [ ]; <ide><path>test/simple/test-event-emitter-num-args.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var events = require('events'); <ide> <ide> var e = new events.EventEmitter(), <ide><path>test/simple/test-event-emitter-once.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var events = require('events'); <ide> <ide> var e = new events.EventEmitter(); <ide><path>test/simple/test-event-emitter-remove-listeners.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var events = require('events'); <ide> <ide> <del>count = 0; <add>var count = 0; <ide> <ide> function listener1 () { <ide> console.log('listener1'); <ide> function listener3 () { <ide> count++; <ide> } <ide> <del>e1 = new events.EventEmitter(); <add>var e1 = new events.EventEmitter(); <ide> e1.addListener("hello", listener1); <ide> e1.removeListener("hello", listener1); <ide> assert.deepEqual([], e1.listeners('hello')); <ide> <del>e2 = new events.EventEmitter(); <add>var e2 = new events.EventEmitter(); <ide> e2.addListener("hello", listener1); <ide> e2.removeListener("hello", listener2); <ide> assert.deepEqual([listener1], e2.listeners('hello')); <ide> <del>e3 = new events.EventEmitter(); <add>var e3 = new events.EventEmitter(); <ide> e3.addListener("hello", listener1); <ide> e3.addListener("hello", listener2); <ide> e3.removeListener("hello", listener1); <ide><path>test/simple/test-exception-handler.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var MESSAGE = 'catch me if you can'; <ide> var caughtException = false; <ide><path>test/simple/test-exception-handler2.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> process.on('uncaughtException', function (err) { <ide> console.log('Caught exception: ' + err); <ide><path>test/simple/test-exec.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var exec = require('child_process').exec; <del>success_count = 0; <del>error_count = 0; <add>var success_count = 0; <add>var error_count = 0; <ide> <ide> exec("ls /", function (err, stdout, stderr) { <ide> if (err) { <ide><path>test/simple/test-executable-path.js <del>common = require("../common"); <del>assert = common.assert; <del>path = require("path"); <add>var common = require('../common'); <add>var assert = require('assert');; <add>var path = require("path"); <ide> <del>isDebug = (process.version.indexOf('debug') >= 0); <add>var isDebug = (process.version.indexOf('debug') >= 0); <ide> <del>debugPath = path.normalize(path.join(__dirname, '..', '..', 'build', 'debug', 'node_g')); <del>defaultPath = path.normalize(path.join(__dirname, '..', '..', 'build', 'default', 'node')); <add>var debugPath = path.normalize(path.join(__dirname, '..', '..', 'build', 'debug', 'node_g')); <add>var defaultPath = path.normalize(path.join(__dirname, '..', '..', 'build', 'default', 'node')); <ide> <ide> console.log('debugPath: ' + debugPath); <ide> console.log('defaultPath: ' + defaultPath); <ide><path>test/simple/test-file-read-noexist.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> var got_error = false; <ide><path>test/simple/test-file-write-stream.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var <ide> path = require('path'), <ide><path>test/simple/test-fs-chmod.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> var got_error = false; <ide><path>test/simple/test-fs-error-messages.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var path = require('path'), <ide> fs = require('fs'), <ide><path>test/simple/test-fs-fsync.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var path = require('path'); <ide> var fs = require('fs'); <ide><path>test/simple/test-fs-read-buffer.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'), <ide> Buffer = require('buffer').Buffer, <ide> fs = require('fs'), <ide><path>test/simple/test-fs-read-file-sync-hostname.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var fs = require('fs'); <ide> <ide> // test reading from hostname <ide><path>test/simple/test-fs-read-file-sync.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <add>var path = require('path'); <add>var fs = require('fs'); <ide> <del>path = require('path'); <del>fs = require('fs'); <del>fn = path.join(common.fixturesDir, 'elipses.txt'); <add>var fn = path.join(common.fixturesDir, 'elipses.txt'); <ide> <ide> var s = fs.readFileSync(fn, 'utf8'); <ide> for (var i = 0; i < s.length; i++) { <ide><path>test/simple/test-fs-read-stream.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> // TODO Improved this test. test_ca.pem is too small. A proper test would <ide> // great a large utf8 (with multibyte chars) file and stream it in, <ide> // performing sanity checks throughout. <ide> <del>Buffer = require('buffer').Buffer; <del>path = require('path'); <del>fs = require('fs'); <del>fn = path.join(common.fixturesDir, 'elipses.txt'); <del>rangeFile = path.join(common.fixturesDir, 'x.txt'); <add>var path = require('path'); <add>var fs = require('fs'); <add>var fn = path.join(common.fixturesDir, 'elipses.txt'); <add>var rangeFile = path.join(common.fixturesDir, 'x.txt'); <ide> <del>callbacks = { open: 0, end: 0, close: 0, destroy: 0 }; <add>var callbacks = { open: 0, end: 0, close: 0, destroy: 0 }; <ide> <del>paused = false; <add>var paused = false; <ide> <del>file = fs.ReadStream(fn); <add>var file = fs.ReadStream(fn); <ide> <ide> file.addListener('open', function(fd) { <ide> file.length = 0; <ide><path>test/simple/test-fs-read.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'), <ide> fs = require('fs'), <ide> filepath = path.join(common.fixturesDir, 'x.txt'), <ide><path>test/simple/test-fs-readfile-empty.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var <ide> path = require('path'), <ide><path>test/simple/test-fs-realpath.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var fs = require('fs'); <ide> var path = require('path'); <ide> var exec = require('child_process').exec; <ide><path>test/simple/test-fs-stat.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var fs = require('fs'); <ide> var got_error = false; <ide> var success_count = 0; <ide><path>test/simple/test-fs-symlink.js <del>common = require("../common"); <add>var common = require('../common'); <ide> var assert = common.assert; <ide> var path = require('path'); <ide> var fs = require('fs'); <ide><path>test/simple/test-fs-write-buffer.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'), <ide> Buffer = require('buffer').Buffer, <ide> fs = require('fs'), <ide><path>test/simple/test-fs-write-file.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <add>var fs = require('fs'); <add>var join = require('path').join; <ide> <del>join = require('path').join; <del>fs = require('fs'); <del>Buffer = require('buffer').Buffer; <del> <del>filename = join(common.fixturesDir, 'test.txt'); <add>var filename = join(common.fixturesDir, 'test.txt'); <ide> <ide> common.error('writing to ' + filename); <ide> <del>s = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"; <add>var s = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n"; <ide> <del>ncallbacks = 0; <add>var ncallbacks = 0; <ide> <ide> fs.writeFile(filename, s, function (e) { <ide> if (e) throw e; <ide> fs.writeFile(filename, s, function (e) { <ide> }); <ide> <ide> // test that writeFile accepts buffers <del>filename2 = join(common.fixturesDir, 'test2.txt'); <del>buf = new Buffer(s, 'utf8'); <add>var filename2 = join(common.fixturesDir, 'test2.txt'); <add>var buf = new Buffer(s, 'utf8'); <ide> common.error('writing to ' + filename2); <ide> <ide> fs.writeFile(filename2, buf, function (e) { <ide><path>test/simple/test-fs-write-stream.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var path = require('path'), <ide> fs = require('fs'); <ide><path>test/simple/test-fs-write-sync.js <del>common = require("../common"); <del>assert = common.assert <del>path = require('path'), <del>Buffer = require('buffer').Buffer <del>fs = require('fs') <del>fn = path.join(common.tmpDir, 'write.txt'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var path = require('path'); <add>var fs = require('fs'); <add>var fn = path.join(common.tmpDir, 'write.txt'); <ide> <ide> <del>foo = 'foo' <add>var foo = 'foo' <ide> var fd = fs.openSync(fn, 'w'); <ide> <del>written = fs.writeSync(fd, ''); <add>var written = fs.writeSync(fd, ''); <ide> assert.strictEqual(0, written); <ide> <ide> fs.writeSync(fd, foo); <ide> <del>bar = 'bár' <add>var bar = 'bár' <ide> written = fs.writeSync(fd, new Buffer(bar), 0, Buffer.byteLength(bar)); <ide> assert.ok(written > 3); <ide> fs.closeSync(fd); <ide><path>test/simple/test-global.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> baseFoo = "foo"; <ide> global.baseBar = "bar"; <ide><path>test/simple/test-http-1.0.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require("net"); <add>var http = require("http"); <ide> <ide> var body = "hello world\n"; <ide> var server_response = ""; <ide><path>test/simple/test-http-304.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <del>http = require('http'); <del>childProcess = require('child_process'); <add>var http = require('http'); <add>var childProcess = require('child_process'); <ide> <del>s = http.createServer(function (request, response) { <add>var s = http.createServer(function (request, response) { <ide> response.writeHead(304); <ide> response.end(); <ide> }); <ide><path>test/simple/test-http-blank-header.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var net = require('net'); <ide> <del>http = require('http'); <del>net = require('net'); <add>var gotReq = false; <ide> <del>gotReq = false; <del> <del>server = http.createServer(function (req, res) { <add>var server = http.createServer(function (req, res) { <ide> common.error('got req'); <ide> gotReq = true; <ide> assert.equal('GET', req.method); <ide><path>test/simple/test-http-buffer-sanity.js <ide> var web = http.Server(function (req, res) { <ide> }); <ide> }); <ide> <add>var gotThanks = false; <add> <ide> web.listen(common.PORT, function () { <ide> console.log("Making request"); <ide> <ide> web.listen(common.PORT, function () { <ide> <ide> process.on('exit', function () { <ide> assert.equal(bufferSize, measuredSize); <add> assert.ok(gotThanks); <ide> }); <ide><path>test/simple/test-http-cat.js <del>common = require("../common"); <del>assert = common.assert <del>http = require("http"); <add>var common = require("../common"); <add>var assert = require('assert'); <add>var http = require("http"); <ide> <ide> var body = "exports.A = function() { return 'A';}"; <ide> var server = http.createServer(function (req, res) { <ide><path>test/simple/test-http-chunked.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var http = require("http"); <ide> <ide> var UTF8_STRING = "南越国是前203年至前111年存在于岭南地区的一个国家,国都位于番禺,疆域包括今天中国的广东、广西两省区的大部份地区,福建省、湖南、贵州、云南的一小部份地区和越南的北部。南越国是秦朝灭亡后,由南海郡尉赵佗于前203年起兵兼并桂林郡和象郡后建立。前196年和前179年,南越国曾先后两次名义上臣属于西汉,成为西汉的“外臣”。前112年,南越国末代君主赵建德与西汉发生战争,被汉武帝于前111年所灭。南越国共存在93年,历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、经济现状。"; <ide> server.addListener("listening", function() { <ide> console.log(data); <ide> server.close(); <ide> }); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/simple/test-http-client-race-2.js <del>common = require("../common"); <del>assert = common.assert <del>http = require("http"); <del>url = require("url"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var url = require("url"); <ide> <ide> // <ide> // Slight variation on test-http-client-race to test for another race <ide><path>test/simple/test-http-client-race.js <del>common = require("../common"); <del>assert = common.assert <del>http = require("http"); <del>url = require("url"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var url = require("url"); <ide> <ide> var body1_s = "1111111111111111"; <ide> var body2_s = "22222"; <ide><path>test/simple/test-http-client-upload.js <del>common = require("../common"); <del>assert = common.assert <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <ide> <ide> var sent_body = ""; <ide> var server_req_complete = false; <ide><path>test/simple/test-http-eof-on-connect.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var http = require('http'); <ide> <ide> // This is a regression test for http://github.com/ry/node/issues/#issue/44 <ide> // It is separate from test-http-malformed-request.js because it is only <ide><path>test/simple/test-http-exceptions.js <del>common = require("../common"); <del>assert = common.assert; <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert');; <add>var http = require('http'); <ide> <ide> server = http.createServer(function (req, res) { <ide> intentionally_not_defined(); <ide><path>test/simple/test-http-full-response.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> // This test requires the program "ab" <del>http = require("http"); <del>exec = require("child_process").exec; <add>var http = require('http'); <add>var exec = require("child_process").exec; <ide> <del>bodyLength = 12345; <add>var bodyLength = 12345; <ide> <del>body = ""; <del>for (var i = 0; i < bodyLength; i++) body += 'c'; <add>var body = ""; <add>for (var i = 0; i < bodyLength; i++) { <add> body += 'c'; <add>} <ide> <del>server = http.createServer(function (req, res) { <add>var server = http.createServer(function (req, res) { <ide> res.writeHead(200, { <ide> "Content-Length": bodyLength, <ide> "Content-Type": "text/plain" <ide> }); <ide> res.end(body); <ide> }); <ide> <del>runs = 0; <add>var runs = 0; <ide> <ide> function runAb(opts, callback) { <ide> var command = "ab " + opts + " http://127.0.0.1:" + common.PORT + "/"; <ide><path>test/simple/test-http-head-request.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var util = require('util'); <ide> <del>assert = require("assert"); <del>http = require("http"); <del>util = require("util"); <ide> <add>var body = "hello world\n"; <ide> <del>body = "hello world\n"; <del> <del>server = http.createServer(function (req, res) { <add>var server = http.createServer(function (req, res) { <ide> common.error('req: ' + req.method); <ide> res.writeHead(200, {"Content-Length": body.length}); <ide> res.end(); <ide><path>test/simple/test-http-head-response-has-no-body.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> <ide><path>test/simple/test-http-keep-alive-close-on-header.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> assert = require("assert"); <del>http = require("http"); <del>util = require("util"); <add>var http = require('http'); <add>var util = require('util'); <ide> <ide> body = "hello world\n"; <ide> headers = {'connection':'keep-alive'} <ide><path>test/simple/test-http-keep-alive.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> assert = require("assert"); <del>http = require("http"); <del>util = require("util"); <add>var http = require('http'); <add>var util = require('util'); <ide> <ide> body = "hello world\n"; <ide> headers = {'connection':'keep-alive'} <ide><path>test/simple/test-http-malformed-request.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>http = require("http"); <del>url = require("url"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var http = require('http'); <add>var url = require("url"); <ide> <ide> // Make sure no exceptions are thrown when receiving malformed HTTP <ide> // requests. <ide> <del>nrequests_completed = 0; <del>nrequests_expected = 1; <add>var nrequests_completed = 0; <add>var nrequests_expected = 1; <ide> <ide> var server = http.createServer(function (req, res) { <ide> console.log("req: " + JSON.stringify(url.parse(req.url))); <ide><path>test/simple/test-http-parser.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> // The purpose of this test is not to check HTTP compliance but to test the <ide> // binding. Tests for pathological http messages should be submitted <ide><path>test/simple/test-http-proxy.js <del>common = require("../common"); <del>assert = common.assert <del>http = require("http"); <del>url = require("url"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var url = require("url"); <ide> <ide> var PROXY_PORT = common.PORT; <ide> var BACKEND_PORT = common.PORT+1; <ide> var proxy = http.createServer(function (req, res) { <ide> <ide> var body = ""; <ide> <del>nlistening = 0; <add>var nlistening = 0; <ide> function startReq () { <ide> nlistening++; <ide> if (nlistening < 2) return; <ide><path>test/simple/test-http-server-multiheaders.js <ide> // of the same header as per RFC2616: joining the handful of fields by ', ' <ide> // that support it, and dropping duplicates for other fields. <ide> <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var http = require('http'); <ide> <ide> var srv = http.createServer(function(req, res) { <ide><path>test/simple/test-http-server.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var http = require('http'); <ide> url = require("url"); <ide> qs = require("querystring"); <ide> <ide><path>test/simple/test-http-set-cookies.js <del>common = require("../common"); <del>assert = common.assert; <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert');; <add>var http = require('http'); <ide> <del>nresponses = 0; <add>var nresponses = 0; <ide> <ide> var server = http.createServer(function(req, res) { <ide> if (req.url == '/one') { <ide><path>test/simple/test-http-set-timeout.js <del>common = require("../common"); <del>assert = common.assert; <del>http = require('http'); <add>var common = require('../common'); <add>var assert = require('assert');; <add>var http = require('http'); <ide> <del>server = http.createServer(function (req, res) { <add>var server = http.createServer(function (req, res) { <ide> console.log('got request. setting 1 second timeout'); <ide> req.connection.setTimeout(500); <ide> <ide> server = http.createServer(function (req, res) { <ide> server.listen(common.PORT, function () { <ide> console.log('Server running at http://127.0.0.1:'+common.PORT+'/'); <ide> <del> errorTimer = setTimeout(function () { <add> var errorTimer = setTimeout(function () { <ide> throw new Error('Timeout was not sucessful'); <ide> }, 2000); <ide> <ide><path>test/simple/test-http-set-trailers.js <del>common = require("../common"); <del>assert = common.assert; <del>http = require("http"); <del>net = require("net"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <add>var net = require('net'); <ide> <del>outstanding_reqs = 0; <add>var outstanding_reqs = 0; <ide> <ide> var server = http.createServer(function(req, res) { <ide> res.writeHead(200, [ ['content-type', 'text/plain'] ]); <ide><path>test/simple/test-http-upgrade-client.js <ide> // the HTTP client. This test uses a raw TCP server to better control server <ide> // behavior. <ide> <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var http = require('http'); <ide> var net = require('net'); <ide><path>test/simple/test-http-upgrade-client2.js <ide> var common = require("../common"); <del>var assert = common.assert <del>var http = require('http'), <del> CRLF = '\r\n'; <add>var assert = require('assert'); <add>var http = require('http'); <add> <add>var CRLF = '\r\n'; <ide> <ide> var server = http.createServer(); <ide> server.on('upgrade', function(req, socket, head) { <ide> server.on('upgrade', function(req, socket, head) { <ide> }); <ide> }); <ide> <add>var successCount = 0; <ide> <ide> server.listen(common.PORT, function () { <ide> <ide> server.listen(common.PORT, function () { <ide> <ide> } <ide> <del> successCount = 0; <ide> upgradeRequest(function() { <ide> successCount++; <ide> upgradeRequest(function() { <ide><path>test/simple/test-http-upgrade-server.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var util = require("util"); <ide> var net = require("net"); <ide><path>test/simple/test-http-upgrade-server2.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <del>http = require('http'); <del>net = require('net'); <add>var http = require('http'); <add>var net = require('net'); <ide> <ide> server = http.createServer(function (req, res) { <ide> common.error('got req'); <ide><path>test/simple/test-http-wget.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var http = require('http'); <ide> <ide> // wget sends an HTTP/1.0 request with Connection: Keep-Alive <ide> // <ide><path>test/simple/test-http-write-empty-string.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <del>http = require('http'); <add>var http = require('http'); <ide> assert = require('assert'); <ide> <ide> server = http.createServer(function (request, response) { <ide><path>test/simple/test-http.js <del>common = require("../common"); <del>assert = common.assert <del>http = require("http"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <ide> url = require("url"); <ide> <ide> function p (x) { <ide><path>test/simple/test-listen-fd.js <ide> // Verify that net.Server.listenFD() can be used to accept connections on an <ide> // already-bound, already-listening socket. <ide> <del>common = require("../common"); <del>assert = common.assert <del>http = require('http'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var http = require('http'); <ide> netBinding = process.binding('net'); <ide> <ide> // Create an server and set it listening on a socket bound to common.PORT <ide><path>test/simple/test-memory-usage.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var r = process.memoryUsage(); <ide> console.log(common.inspect(r)); <ide><path>test/simple/test-mkdir-rmdir.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> <ide><path>test/simple/test-module-loading.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'), <ide> fs = require('fs'); <ide> <ide><path>test/simple/test-net-binary.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <ide> <ide> binaryString = ""; <ide> for (var i = 255; i >= 0; i--) { <ide><path>test/simple/test-net-eaddrinuse.js <del>common = require('../common'); <del>assert = common.assert <del>net = require('net'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <ide> <ide> var server1 = net.createServer(function (socket) { <ide> }); <ide><path>test/simple/test-net-isip.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <ide> <ide> assert.equal(net.isIP("127.0.0.1"), 4); <ide> assert.equal(net.isIP("x127.0.0.1"), 0); <ide><path>test/simple/test-net-keepalive.js <del>common = require("../common"); <del>assert = common.assert <del>net = require('net'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <ide> <ide> var serverConnection; <ide> var echoServer = net.createServer(function (connection) { <ide> echoServer.addListener("listening", function() { <ide> clientConnection.end(); <ide> echoServer.close(); <ide> }, 1200); <del>}); <ide>\ No newline at end of file <add>}); <ide><path>test/simple/test-net-pingpong.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <del>net = require("net"); <add>var net = require('net'); <ide> <ide> var tests_run = 0; <ide> <ide><path>test/simple/test-net-reconnect.js <del>common = require("../common"); <del>assert = common.assert <del>net = require('net'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <ide> var N = 50; <ide> <ide> var c = 0; <ide><path>test/simple/test-net-server-max-connections.js <del>common = require("../common"); <del>assert = common.assert; <del>net = require('net'); <add>var common = require('../common'); <add>var assert = require('assert');; <add>var net = require('net'); <ide> <ide> // This test creates 200 connections to a server and sets the server's <ide> // maxConnections property to 100. The first 100 connections make it through <ide><path>test/simple/test-next-tick-errors.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var order = [], <ide> exceptionHandled = false; <ide><path>test/simple/test-next-tick-ordering.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var i; <ide> <ide> var N = 30; <ide><path>test/simple/test-next-tick-ordering2.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var order = []; <ide> process.nextTick(function() { <ide><path>test/simple/test-next-tick.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var complete = 0; <ide> <ide><path>test/simple/test-path.js <ide> var path = require("path"); <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var f = __filename; <ide> <ide><path>test/simple/test-pipe-head.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> exec = require('child_process').exec; <ide> join = require('path').join; <ide><path>test/simple/test-pump-file2tcp-noexist.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>fs = require("fs"); <del>util = require("util"); <del>path = require("path"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var fs = require('fs'); <add>var util = require('util'); <add>var path = require('path'); <ide> fn = path.join(common.fixturesDir, 'does_not_exist.txt'); <ide> <ide> var got_error = false; <ide><path>test/simple/test-pump-file2tcp.js <del>common = require("../common"); <del>assert = common.assert <del>net = require("net"); <del>fs = require("fs"); <del>util = require("util"); <del>path = require("path"); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var net = require('net'); <add>var fs = require('fs'); <add>var util = require('util'); <add>var path = require('path'); <ide> fn = path.join(common.fixturesDir, 'elipses.txt'); <ide> <ide> expected = fs.readFileSync(fn, 'utf8'); <ide><path>test/simple/test-querystring.js <del>common = require("../common"); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> // test using assert <ide> var qs = require("querystring"); <ide><path>test/simple/test-readdir.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> <ide><path>test/simple/test-repl.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var net = require("net"), <ide> repl = require("repl"), <ide><path>test/simple/test-script-context.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var Script = require('vm').Script; <ide> var script = new Script('"passed";'); <ide><path>test/simple/test-script-new.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var Script = require('vm').Script; <ide> common.debug('run a string'); <ide><path>test/simple/test-script-static-context.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var Script = require('vm').Script; <ide> <ide><path>test/simple/test-script-static-new.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var Script = require('vm').Script; <ide> <ide><path>test/simple/test-script-static-this.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var Script = require('vm').Script; <ide> <ide><path>test/simple/test-script-this.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var Script = require('vm').Script; <ide> <ide><path>test/simple/test-sendfd.js <ide> // seen in a response yet. This is intended to ensure that all blobs <ide> // sent out have been relayed back to us. <ide> <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var buffer = require('buffer'); <ide> var child_process = require('child_process'); <ide><path>test/simple/test-signal-handler.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> console.log("process.pid: " + process.pid); <ide> <ide><path>test/simple/test-signal-unregister.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var childKilled = false, done = false, <ide> spawn = require('child_process').spawn, <ide><path>test/simple/test-stdin-from-file.js <del>common = require("../common"); <del>assert = common.assert <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> join = require('path').join; <ide> childProccess = require('child_process'); <del>fs = require('fs'); <add>var fs = require('fs'); <ide> <ide> stdoutScript = join(common.fixturesDir, 'echo.js'); <ide> tmpFile = join(common.fixturesDir, 'stdin.txt'); <ide><path>test/simple/test-stdout-to-file.js <del>common = require("../common"); <del>assert = common.assert <del>path = require('path'); <add>var common = require('../common'); <add>var assert = require('assert'); <add>var path = require('path'); <ide> childProccess = require('child_process'); <del>fs = require('fs'); <add>var fs = require('fs'); <ide> scriptString = path.join(common.fixturesDir, 'print-chars.js'); <ide> scriptBuffer = path.join(common.fixturesDir, 'print-chars-from-buffer.js'); <ide> tmpFile = path.join(common.fixturesDir, 'stdout.txt'); <ide><path>test/simple/test-string-decoder.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> Buffer = require('buffer').Buffer; <ide> StringDecoder = require('string_decoder').StringDecoder; <ide><path>test/simple/test-sync-fileread.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> var path = require('path'); <ide> var fs = require('fs'); <ide> <ide><path>test/simple/test-sys.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> assert.equal('0', common.inspect(0)); <ide> assert.equal('1', common.inspect(1)); <ide><path>test/simple/test-umask.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> var mask = 0664; <ide> var old = process.umask(mask); <ide><path>test/simple/test-url.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert'); <ide> <ide> var url = require('url'), <ide> util = require('util'); <ide><path>test/simple/test-utf8-scripts.js <del>common = require('../common'); <del>assert = common.assert; <add>var common = require('../common'); <add>var assert = require('assert');; <ide> <ide> // üäö <ide>
159
Text
Text
fix doc styles
1d60fc3aa5b7a6032665595c29bdb382bd526e43
<ide><path>BUILDING.md <ide> and not a newer version. <ide> <ide> To run the tests: <ide> <del>``` <add>```console <ide> $ make test <ide> ``` <ide> <ide> Prerequisites: <ide> including the Community edition (remember to select <ide> "Common Tools for Visual C++ 2015" feature during installation). <ide> * [Visual Studio 2017](https://www.visualstudio.com/downloads/), any edition (including the Build Tools SKU). <del> __Required Components:__ "MSbuild", "VC++ 2017 v141 toolset" and one of the Windows SDKs (10 or 8.1). <add> **Required Components:** "MSbuild", "VC++ 2017 v141 toolset" and one of the Windows SDKs (10 or 8.1). <ide> * Basic Unix tools required for some tests, <ide> [Git for Windows](http://git-scm.com/download/win) includes Git Bash <ide> and tools which can be included in the global `PATH`. <ide><path>doc/changelogs/CHANGELOG_V6.md <ide> This is also a security release. All Node.js users should consult the security r <ide> * [[`86b9db601d`](https://github.com/nodejs/node/commit/86b9db601d)] - **src**: add missing length argument to send comment (Daniel Bevenius) [#8816](https://github.com/nodejs/node/pull/8816) <ide> * [[`aa11205f71`](https://github.com/nodejs/node/commit/aa11205f71)] - **src**: rename CHECK_NOT_OOB() macro (Ben Noordhuis) [#8784](https://github.com/nodejs/node/pull/8784) <ide> * [[`8be818eb07`](https://github.com/nodejs/node/commit/8be818eb07)] - **src**: fix minor typo in comments (Daniel Bevenius) [#8736](https://github.com/nodejs/node/pull/8736) <del>* [[`41ad6e3965`](https://github.com/nodejs/node/commit/41ad6e3965)] - **src**: rename handle__ to handle_ in HandleWrap (Daniel Bevenius) [#8712](https://github.com/nodejs/node/pull/8712) <add>* [[`41ad6e3965`](https://github.com/nodejs/node/commit/41ad6e3965)] - **src**: rename `handle__` to `handle_` in HandleWrap (Daniel Bevenius) [#8712](https://github.com/nodejs/node/pull/8712) <ide> * [[`9205edc35c`](https://github.com/nodejs/node/commit/9205edc35c)] - **src**: don't abort when c-ares initialization fails (Ben Noordhuis) [#8710](https://github.com/nodejs/node/pull/8710) <ide> * [[`6ddfe89fdf`](https://github.com/nodejs/node/commit/6ddfe89fdf)] - **src**: remove VS 2013 compatibility hacks (Ben Noordhuis) [#8067](https://github.com/nodejs/node/pull/8067) <ide> * [[`a9491f1604`](https://github.com/nodejs/node/commit/a9491f1604)] - **src**: make ReqWrap req_ member private (Daniel Bevenius) [#8532](https://github.com/nodejs/node/pull/8532) <ide><path>doc/guides/maintaining-V8.md <ide> # Maintaining V8 in Node.js <ide> <del># Background <add>## Background <ide> <ide> V8 follows the Chromium release schedule. The support horizon for Chromium is <ide> very different from the support horizon that Node.js needs to provide to its <ide> This document attempts to document the current processes and proposes a workflow <ide> for maintaining the V8 branches in Node.js LTS and Current releases and how the <ide> Node.js and V8 teams at Google can help. <ide> <del># V8 Release Schedule <add>## V8 Release Schedule <ide> <ide> V8 and Chromium follow a [roughly 6-week release cadence](https://www.chromium.org/developers/calendar). At any given time there are three V8 branches that are **active**. <ide> <ide> For example, at the time of this writing: <ide> All older branches are considered **abandoned**, and are not maintained by the <ide> V8 team. <ide> <del>## V8 merge process overview <add>### V8 merge process overview <ide> <ide> The process for backporting bug fixes to active branches is officially documented [on the V8 wiki](https://github.com/v8/v8/wiki/Merging%20&%20Patching). The summary of the process is: <ide> <ide> The process for backporting bug fixes to active branches is officially documente <ide> * Merge requests to an abandoned branch will be rejected. <ide> * Only bug fixes are accepted for backporting. <ide> <del># Node.js Support Requirements <add>## Node.js Support Requirements <ide> <ide> At any given time Node.js needs to be maintaining a few different V8 branches <ide> for the various Current, LTS, and nightly releases. At present this list <ide> The versions of V8 used in Node.js v4.x and v6.x have already been abandoned by <ide> upstream V8. However, Node.js needs to continue supporting these branches for <ide> many months (Current branches) or several years (LTS branches). <ide> <del># Maintenance Process <add>## Maintenance Process <ide> <ide> Once a bug in Node.js has been identified to be caused by V8, the first step is <ide> to identify the versions of Node.js and V8 affected. The bug may be present in <ide> process. <ide> * Backporting to abandoned branches. <ide> * Backports identified by the V8 team. Bugs identified by upstream V8 that we haven't encountered in Node.js yet. <ide> <del>## Unfixed Upstream Bugs <add>### Unfixed Upstream Bugs <ide> <ide> If the bug can be reproduced on the [`vee-eight-lkgr` branch](https://github.com/v8/node/tree/vee-eight-lkgr), Chromium canary, or V8 tip-of-tree, and the test case is valid, then the bug needs to be fixed upstream first. <ide> <ide> If the bug can be reproduced on the [`vee-eight-lkgr` branch](https://github.com <ide> * V8's build waterfall tests your change. <ide> * Once the bug is fixed it may still need backporting, if it exists in other V8 branches that are still active or are branches that Node.js cares about. Follow the process for backporting below. <ide> <del>## Backporting to Active Branches <add>### Backporting to Active Branches <ide> <ide> If the bug exists in any of the active V8 branches, we may need to get the fix backported. At any given time there are [two active branches](https://build.chromium.org/p/client.v8.branches/console) (beta and stable) in addition to master. The following steps are needed to backport the fix: <ide> <ide> If the bug exists in any of the active V8 branches, we may need to get the fix b <ide> * It is possible that the merge request may not get approved, for example if it is considered to be a feature or otherwise too risky for V8 stable. In such cases we float the patch on the Node.js side. See the process on 'Backporting to Abandoned branches'. <ide> * Once the fix has been merged upstream, it can be picked up during an update of the V8 branch, (see below). <ide> <del>## Backporting to Abandoned Branches <add>### Backporting to Abandoned Branches <ide> <ide> Abandoned V8 branches are supported in the Node.js V8 repository. The fix needs <ide> to be cherry-picked in the Node.js repository and V8-CI must test the change. <ide> example workflow: <ide> <ide> * Download and apply the commit linked-to in the issue (in this case a51f429). `curl -L https://github.com/v8/v8/commit/a51f429.patch | git am -3 --directory=deps/v8`. If the branches have diverged significantly, this may not apply cleanly. It may help to try to cherry-pick the merge to the oldest branch that was done upstream in V8. In this example, this would be the patch from the merge to 5.2. The hope is that this would be closer to the V8 5.1, and has a better chance of applying cleanly. If you're stuck, feel free to ping @ofrobots for help. <ide> * Modify the commit message to match the format we use for V8 backports and replace yourself as the author. `git commit --amend --reset-author`. You may want to add extra description if necessary to indicate the impact of the fix on Node.js. In this case the original issue was descriptive enough. Example: <del>``` <add>```console <ide> deps: cherry-pick a51f429 from V8 upstream <ide> <ide> Original commit message: <ide> PR-URL: <pr link> <ide> ``` <ide> * Open a PR against the `v6.x-staging` branch in the Node.js repo. Launch the normal and [V8-CI](https://ci.nodejs.org/job/node-test-commit-v8-linux/) using the Node.js CI system. We only needed to backport to `v6.x` as the other LTS branches weren't affected by this bug. <ide> <del>## Backports Identified by the V8 team <add>### Backports Identified by the V8 team <ide> <ide> For bugs found through the browser or other channels, the V8 team marks bugs <ide> that might be applicable to the abandoned branches in use by Node.js. This is <ide> to shepherd through the backport process. External contributors are welcome to <ide> collaborate on the backport process as well. Note that some of the bugs may be <ide> security issues and will not be visible to external collaborators. <ide> <del># Updating V8 <add>## Updating V8 <ide> <ide> Node.js keeps a vendored copy of V8 inside of deps/ directory. In addition <ide> Node.js may need to float patches that do not exist upstream. This means that <ide> some care may need to be taken to update the vendored copy of V8. <ide> <del>## Minor updates (patch level) <add>### Minor updates (patch level) <ide> <ide> Because there may be floating patches on the version of V8 in Node.js, it is <ide> safest to apply the patch level updates as a patch. For example, imagine that <ide> V8 also keeps tags of the form *5.4-lkgr* which point to the *Last Known Good <ide> Revision* from the 5.4 branch that can be useful in the update process above. <ide> <ide> <del>## Major Updates <add>### Major Updates <ide> <ide> We upgrade the version of V8 in Node.js master whenever a V8 release goes stable <ide> upstream, that is, whenever a new release of Chrome comes out. <ide> them once you have reviewed them. <ide> <ide> This should be followed up with manual refloating of all relevant patches. <ide> <del># Proposal: Using a fork repo to track upstream V8 <add>## Proposal: Using a fork repo to track upstream V8 <ide> <ide> The fact that Node.js keeps a vendored, potentially edited copy of V8 in deps/ <ide> makes the above processes a bit complicated. An alternative proposal would be to <ide> This would require some tooling to: <ide> * We need a script to bump V8 version numbers when a new version of V8 is promoted from nodejs/v8 to nodejs/node. <ide> * Enabled the V8-CI build in Jenkins to build from the nodejs/v8 fork. <ide> <del># Proposal: Dealing with the need to float patches to a stable/beta <add>## Proposal: Dealing with the need to float patches to a stable/beta <ide> <ide> Sometimes upstream V8 may not want to merge a fix to their stable branches, but <ide> we might. An example of this would be a fix for a performance regression that <ide> We are trying this out in https://github.com/nodejs/node/pull/9754. If this ends <ide> up working, we will investigate making this change upstream. <ide> <ide> <!-- Footnotes themselves at the bottom. --> <del>## Notes <add>### Notes <ide> <ide> <sup>1</sup>Node.js 0.12 and older are intentionally omitted from this document as their support is ending soon. <ide> <ide><path>doc/guides/writing-tests.md <ide> static void at_exit_callback(void* arg) { <ide> ``` <ide> <ide> Next add the test to the `sources` in the `cctest` target in node.gyp: <del>``` <add>```console <ide> 'sources': [ <ide> 'test/cctest/test_env.cc', <ide> ... <ide> ], <ide> ``` <ide> The test can be executed by running the `cctest` target: <del>``` <add>```console <ide> $ make cctest <ide> ``` <ide> <ide><path>doc/releases.md <ide> Create a new blog post by running the [nodejs.org release-post.js script](https: <ide> * The links to the download files won't be complete unless you waited for the ARMv6 builds. Any downloads that are missing will have `*Coming soon*` next to them. It's your responsibility to manually update these later when you have the outstanding builds. <ide> * The SHASUMS256.txt.asc content is at the bottom of the post. When you update the list of tarballs you'll need to copy/paste the new contents of this file to reflect those changes. <ide> * Always use pull-requests on the nodejs.org repo. Be respectful of that working group, but you shouldn't have to wait for PR sign-off. Opening a PR and merging it immediately _should_ be fine. However, please follow the following commit message format: <del>``` <add>```console <ide> Blog: vX.Y.Z release post <ide> <ide> Refs: <full URL to your release proposal PR>
5
Python
Python
remove debug print in scons command
7134947e9d1aeff12cd2a74aa8c7af2111db5d88
<ide><path>numpy/distutils/command/scons.py <ide> def run(self): <ide> # nothing to do, just leave it here. <ide> return <ide> <del> print "is bootstrapping ? %s" % is_bootstrapping() <ide> # XXX: when a scons script is missing, scons only prints warnings, and <ide> # does not return a failure (status is 0). We have to detect this from <ide> # distutils (this cannot work for recursive scons builds...)
1
Ruby
Ruby
use #inspect instead of wrapping symbols
de7ef64f6150806957161fd4b28e6486fd866a88
<ide><path>Library/Homebrew/rubocops/lines.rb <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> shell_parameter_format = if shell_parameter_stripped.empty? <ide> nil <ide> elsif shell_parameter_stripped == "--" <del> ":flag" <add> :flag <ide> elsif shell_parameter_stripped == "--shell=" <del> ":arg" <add> :arg <ide> else <ide> "\"#{shell_parameter_stripped}\"" <ide> end <ide> def audit_formula(_node, _class_node, _parent_class_node, body_node) <ide> replacement_args << "executable: #{executable}" <ide> end <ide> replacement_args << "cmd: \"#{cmd}\"" unless cmd == "completion" <del> replacement_args << "shell_parameter_format: #{shell_parameter_format}" unless shell_parameter_format.nil? <add> replacement_args << "shell_parameter_format: #{shell_parameter_format.inspect}" unless shell_parameter_format.nil? <ide> <ide> offending_node(node) <ide> replacement = "generate_completions_from_executable(#{replacement_args.join(", ")})"
1
Javascript
Javascript
remove unused map util
8f239cb3e5fb887ef8f4a43dc4ce02e5e30f4bbd
<ide><path>api-server/server/utils/map.js <del>import _ from 'lodash'; <del>import { Observable } from 'rx'; <del> <del>import { unDasherize, nameify } from '../../../utils/slugs'; <del>import { <del> addNameIdMap as _addNameIdToMap, <del> checkMapData, <del> getFirstChallenge as _getFirstChallenge <del>} from '../../common/utils/map.js'; <del> <del>const isDev = process.env.FREECODECAMP_NODE_ENV !== 'production'; <del>const isBeta = !!process.env.BETA; <del>const challengesRegex = /^(bonfire|waypoint|zipline|basejump|checkpoint)/i; <del>const addNameIdMap = _.once(_addNameIdToMap); <del>const getFirstChallenge = _.once(_getFirstChallenge); <del>/* <del> * interface ChallengeMap { <del> * result: { <del> * superBlocks: [ ...superBlockDashedName: String ] <del> * }, <del> * entities: { <del> * superBlock: { <del> * [ ...superBlockDashedName ]: SuperBlock <del> * }, <del> * block: { <del> * [ ...blockDashedNameg ]: Block, <del> * challenge: { <del> * [ ...challengeDashedNameg ]: Challenge <del> * } <del> * } <del> * } <del> */ <del>export function _cachedMap({ Block, Challenge }) { <del> const challenges = Challenge.find$({ <del> order: ['order ASC', 'suborder ASC'], <del> where: { isPrivate: false } <del> }); <del> const challengeMap = challenges.map(challenges => <del> challenges <del> .map(challenge => challenge.toJSON()) <del> .reduce((hash, challenge) => { <del> hash[challenge.dashedName] = challenge; <del> return hash; <del> }, {}) <del> ); <del> const blocks = Block.find$({ <del> order: ['superOrder ASC', 'order ASC'], <del> where: { isPrivate: false } <del> }); <del> const blockMap = Observable.combineLatest( <del> blocks.map(blocks => <del> blocks <del> .map(block => block.toJSON()) <del> .reduce((hash, block) => { <del> hash[block.dashedName] = block; <del> return hash; <del> }, {}) <del> ), <del> challenges <del> ).map(([blocksMap, challenges]) => { <del> return challenges.reduce((blocksMap, challenge) => { <del> if (blocksMap[challenge.block].challenges) { <del> blocksMap[challenge.block].challenges.push(challenge.dashedName); <del> } else { <del> blocksMap[challenge.block] = { <del> ...blocksMap[challenge.block], <del> challenges: [challenge.dashedName] <del> }; <del> } <del> return blocksMap; <del> }, blocksMap); <del> }); <del> const superBlockMap = blocks.map(blocks => <del> blocks.reduce((map, block) => { <del> if (map[block.superBlock] && map[block.superBlock].blocks) { <del> map[block.superBlock].blocks.push(block.dashedName); <del> } else { <del> map[block.superBlock] = { <del> title: _.startCase(block.superBlock), <del> order: block.superOrder, <del> name: nameify(_.startCase(block.superBlock)), <del> dashedName: block.superBlock, <del> blocks: [block.dashedName], <del> message: block.superBlockMessage <del> }; <del> } <del> return map; <del> }, {}) <del> ); <del> const superBlocks = superBlockMap.map(superBlockMap => { <del> return Object.keys(superBlockMap) <del> .map(key => superBlockMap[key]) <del> .map(({ dashedName }) => dashedName); <del> }); <del> return Observable.combineLatest( <del> superBlockMap, <del> blockMap, <del> challengeMap, <del> superBlocks, <del> (superBlock, block, challenge, superBlocks) => ({ <del> entities: { <del> superBlock, <del> block, <del> challenge <del> }, <del> result: { <del> superBlocks <del> } <del> }) <del> ) <del> .do(checkMapData) <del> .shareReplay(); <del>} <del> <del>export const cachedMap = _.once(_cachedMap); <del> <del>// type ObjectId: String; <del>// getChallengeById( <del>// map: Observable[map], <del>// id: ObjectId <del>// ) => Observable[Challenge] | Void; <del>export function getChallengeById(map, id) { <del> return Observable.if( <del> () => !id, <del> map.map(getFirstChallenge), <del> map.map(addNameIdMap).map(map => { <del> const { <del> entities: { challenge: challengeMap, challengeIdToName } <del> } = map; <del> let finalChallenge; <del> const dashedName = challengeIdToName[id]; <del> finalChallenge = challengeMap[dashedName]; <del> if (!finalChallenge) { <del> finalChallenge = getFirstChallenge(map); <del> } <del> return finalChallenge; <del> }) <del> ); <del>} <del> <del>export function getChallengeInfo(map) { <del> return map <del> .map(addNameIdMap) <del> .map(({ entities: { challenge: challengeMap, challengeIdToName } }) => ({ <del> challengeMap, <del> challengeIdToName <del> })); <del>} <del> <del>// if challenge is not isComingSoon or isBeta => load <del>// if challenge is ComingSoon we are in beta||dev => load <del>// if challenge is beta and we are in beta||dev => load <del>// else hide <del>function loadComingSoonOrBetaChallenge({ <del> isComingSoon, <del> isBeta: challengeIsBeta <del>}) { <del> return !(isComingSoon || challengeIsBeta) || isDev || isBeta; <del>} <del> <del>// this is a hard search <del>// falls back to soft search <del>export function getChallenge(challengeDashedName, blockDashedName, map) { <del> return map.flatMap(({ entities, result: { superBlocks } }) => { <del> const superBlock = entities.superBlock; <del> const block = entities.block[blockDashedName]; <del> const challenge = entities.challenge[challengeDashedName]; <del> return Observable.if( <del> () => <del> !blockDashedName || <del> !block || <del> !challenge || <del> !loadComingSoonOrBetaChallenge(challenge), <del> getChallengeByDashedName(challengeDashedName, map), <del> Observable.just({ block, challenge }) <del> ).map(({ challenge, block }) => ({ <del> redirect: <del> challenge.block !== blockDashedName <del> ? `/challenges/${block.dashedName}/${challenge.dashedName}` <del> : false, <del> entities: { <del> superBlock, <del> challenge: { <del> [challenge.dashedName]: challenge <del> } <del> }, <del> result: { <del> block: block.dashedName, <del> challenge: challenge.dashedName, <del> superBlocks <del> } <del> })); <del> }); <del>} <del> <del>export function getBlockForChallenge(map, challenge) { <del> return map.map(({ entities: { block } }) => block[challenge.block]); <del>} <del> <del>export function getChallengeByDashedName(dashedName, map) { <del> const challengeName = unDasherize(dashedName).replace(challengesRegex, ''); <del> const testChallengeName = new RegExp(challengeName, 'i'); <del> <del> return map <del> .map(({ entities }) => entities.challenge) <del> .flatMap(challengeMap => { <del> return Observable.from(Object.keys(challengeMap)).map( <del> key => challengeMap[key] <del> ); <del> }) <del> .filter(challenge => { <del> return ( <del> loadComingSoonOrBetaChallenge(challenge) && <del> testChallengeName.test(challenge.name) <del> ); <del> }) <del> .last({ defaultValue: null }) <del> .flatMap(challengeOrNull => { <del> return Observable.if( <del> () => !!challengeOrNull, <del> Observable.just(challengeOrNull), <del> map.map(getFirstChallenge) <del> ); <del> }) <del> .flatMap(challenge => { <del> return getBlockForChallenge(map, challenge).map(block => ({ <del> challenge, <del> block <del> })); <del> }); <del>}
1
Javascript
Javascript
fix $location to handle updates to empty hash well
c648fee5c2c46cbd2ea8b5bd4cec8005f182db1c
<ide><path>src/services.js <ide> angularServiceInject("$location", function($browser) { <ide> extend(location, parseHref(href)); <ide> } else { <ide> if (isDefined(href.hash)) { <del> extend(href, parseHash(href.hash)); <add> extend(href, isString(href.hash) ? parseHash(href.hash) : href.hash); <ide> } <ide> <ide> extend(location, href); <ide> angularServiceInject("$location", function($browser) { <ide> } else <ide> hash.hashSearch = path; <ide> <del> update(hash); <add> hash.hash = composeHash(hash); <add> <add> update({hash: hash}); <ide> } <ide> <ide> <ide> angularServiceInject("$location", function($browser) { <ide> } <ide> if (location.hash != lastLocation.hash) { <ide> var hash = parseHash(location.hash); <del> updateHash(hash.path, hash.search); <add> updateHash(hash.hashPath, hash.hashSearch); <ide> } else { <ide> location.hash = composeHash(location); <ide> location.href = composeHref(location); <ide><path>test/servicesSpec.js <ide> describe("service", function(){ <ide> $location.update('http://www.angularjs.org/index.php#'); <ide> expect($location.href).toEqual('http://www.angularjs.org/index.php'); <ide> }); <add> <add> it('should clear hash when updating to hash-less URL', function() { <add> $location.update('http://server'); <add> expect($location.href).toBe('http://server'); <add> expect($location.hash).toBe(''); <add> }); <ide> }); <ide> <ide> <ide> describe("service", function(){ <ide> expect($location.hashSearch).toEqual({a: 'b'}); <ide> expect($location.hashPath).toEqual('path'); <ide> }); <add> <add> it('should update href and hash when updating to empty string', function() { <add> $location.updateHash(''); <add> expect($location.href).toBe('http://server'); <add> expect($location.hash).toBe(''); <add> <add> scope.$eval(); <add> <add> expect($location.href).toBe('http://server'); <add> expect($location.hash).toBe(''); <add> }); <ide> }); <ide> }); <ide>
2
Javascript
Javascript
fix redeclared vars in test-url
680fb1ea0374ce8a7bf20f7afc7b22726e43763c
<ide><path>test/parallel/test-url.js <ide> var parseTests = { <ide> <ide> }; <ide> <del>for (var u in parseTests) { <del> var actual = url.parse(u); <del> var spaced = url.parse(' \t ' + u + '\n\t'); <del> var expected = parseTests[u]; <add>for (const u in parseTests) { <add> let actual = url.parse(u); <add> const spaced = url.parse(` \t ${u}\n\t`); <add> let expected = parseTests[u]; <ide> <ide> Object.keys(actual).forEach(function(i) { <ide> if (expected[i] === undefined && actual[i] === null) { <ide> var parseTestsWithQueryString = { <ide> href: '/example?query=value' <ide> } <ide> }; <del>for (var u in parseTestsWithQueryString) { <del> var actual = url.parse(u, true); <del> var expected = parseTestsWithQueryString[u]; <del> for (var i in actual) { <add>for (const u in parseTestsWithQueryString) { <add> const actual = url.parse(u, true); <add> const expected = parseTestsWithQueryString[u]; <add> for (const i in actual) { <ide> if (actual[i] === null && expected[i] === undefined) { <ide> expected[i] = null; <ide> } <ide> var formatTests = { <ide> pathname: '/fooA100%mBr', <ide> } <ide> }; <del>for (var u in formatTests) { <del> var expect = formatTests[u].href; <add>for (const u in formatTests) { <add> const expect = formatTests[u].href; <ide> delete formatTests[u].href; <del> var actual = url.format(u); <del> var actualObj = url.format(formatTests[u]); <add> const actual = url.format(u); <add> const actualObj = url.format(formatTests[u]); <ide> assert.equal(actual, expect, <ide> 'wonky format(' + u + ') == ' + expect + <ide> '\nactual:' + actual); <ide> var throws = [ <ide> 0, <ide> function() {} <ide> ]; <del>for (var i = 0; i < throws.length; i++) { <add>for (let i = 0; i < throws.length; i++) { <ide> assert.throws(function() { url.format(throws[i]); }, TypeError); <ide> } <ide> assert(url.format('') === '');
1
Text
Text
normalize react as a product name
0fd3fe3fc6deb41113c19bbb9285205f22e2ce6b
<ide><path>guide/portuguese/react/index.md <ide> const Component2 = () => { <ide> 2. React é declarativo para a maior parte em que estamos mais preocupados com o que fazer, em vez de como fazer uma tarefa específica. A programação declarativa é um paradigma de programação que expressa a lógica de uma computação sem descrever seu fluxo de controle. A programação declarativa vem com certas vantagens, como redução de efeitos colaterais (ocorre quando modificamos qualquer estado ou transformamos algo ou fazemos uma requisição de API), minimizando a mutabilidade (muito abstraído), melhor legibilidade, menores erros. <ide> <ide> 3. Fluxo de dados unidirecional. A interface do usuário no React é, na verdade, a função do estado que significa que, à medida que o estado é atualizado, ele também atualiza a interface do usuário. Portanto, nossa interface do usuário progride conforme o estado muda. <del> <del>## Vantagens do React <add> <add> <add>## Vantagens de React <ide> <ide> Algumas razões para usar o React são: <ide> <ide> Você está livre para usar versões mais atualizadas dessas bibliotecas à medi <ide> <ide> o que você está fazendo aqui? O elemento HTML `<script>` é usado para incorporar ou referenciar um script executável. O atributo "src" aponta para os arquivos de script externos da biblioteca React, da biblioteca ReactDOM e da biblioteca Babel. É como se você tivesse um barbeador elétrico. Literalmente não é bom para você, não importa o quão sofisticado o barbeador elétrico, a menos que você possa conectá-lo à parede e obter acesso à eletricidade. Nosso código React que escreveremos não será bom para nós se nosso navegador não puder se conectar a essas bibliotecas para entender e interpretar o que estamos fazendo. É assim que nossa aplicação vai ganhar o poder do React, será como inserimos o React no Dom. A razão pela qual temos React e ReactDOM como duas bibliotecas diferentes é porque há casos de uso como o React Native, onde a renderização para o DOM não é necessária para o desenvolvimento móvel, então a biblioteca foi dividida para que as pessoas decidissem pelo que precisavam no projeto em que estão trabalhando. Como precisaremos do nosso React para chegar ao DOM, usaremos os dois scripts. O Babel é como aproveitamos o script ECMA além do ES5 e lidamos com algo chamado JSX (JavaScript como XML) que usaremos no React. Vamos dar uma olhada mais profunda na magia de Babel em uma próxima lição :) Certo, concluímos as etapas 1 e 2. Configuramos nosso código de placa de caldeira e configuramos nosso ambiente de desenvolvedor. <ide> <del>### 3 - Renderizador React ao DOM <add> <add>### 3 - Render React ao DOM <add> <ide> <ide> Nossos próximos dois passos serão escolher nosso local no DOM para o qual queremos renderizar nosso conteúdo React. E usar outra tag de script para nosso conteúdo React dentro do corpo. Geralmente, como uma boa separação de interesses, isso seria em seu próprio arquivo, em seguida, vinculado a este documento html. Faremos isso mais tarde nas próximas lições. Por enquanto, vamos deixar isso acontecer dentro do corpo do documento html em que estamos atualmente. Agora vamos ver como é simples escolher um local no DOM para renderizar nosso conteúdo React. Nós vamos dentro do corpo. E a melhor prática não é apenas lançar o React na tag body a ser exibida, mas criar um elemento separado, geralmente um div, que você pode tratar como um elemento raiz para inserir o conteúdo do React. <ide> <ide> Nossos próximos dois passos serão escolher nosso local no DOM para o qual quer <ide> </body> <ide> ``` <ide> <add> <ide> Vamos criar um simples elemento `<div>` e dar a ele um id de "app". Seremos capazes de segmentar esse local para inserir nosso conteúdo React da mesma forma que você pode usar CSS para segmentar um ID para o estilo de sua escolha. Qualquer conteúdo reagente será renderizado nas tags div com o ID do aplicativo. Enquanto isso, deixaremos um texto dizendo que "O React ainda não foi renderizado" Se vemos isso quando visualizamos nossa página, isso significa que em algum lugar perdemos a renderização React. Agora, vamos em frente e criar uma tag de script dentro do nosso corpo, onde vamos criar com React pela primeira vez. A sintaxe que vamos precisar para a nossa tag de script é adicionar um atributo de “type”. Isso especifica o tipo de mídia do script. Acima de nós, usamos um atributo src que apontava para os arquivos de script externos da biblioteca React, da biblioteca ReactDOM e da biblioteca Babel. <ide> <add> <ide> ```javascript <ide> <body> <ide> <div id="app">React has not rendered yet</div> <ide> Então, vamos fazer uma rápida recapitulação. Na nossa tag head pegamos as ta <ide> <ide> ### Mais Informações: <ide> <del>* [Página de Reação](https://reactjs.org/) <add>* [Página do React](https://reactjs.org/) <ide> * [Twitter de Dan Abramov](https://twitter.com/dan_abramov) <del>* [Tutoriais de React em Egghead.io](https://egghead.io/browse/frameworks/react) <ide> <ide> ### Fontes <ide>
1
Javascript
Javascript
add utilities for bundle creation
eda09f89c9f2daa2125409beb8d9d8cce15dde82
<ide><path>packager/react-packager/src/ModuleGraph/output/__tests__/util-test.js <add>/** <add> * Copyright (c) 2016-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> */ <add>'use strict'; <add> <add>jest.disableAutomock(); <add> <add>const {match} = require('sinon'); <add>const {fn} = require('../../test-helpers'); <add>const { <add> addModuleIdsToModuleWrapper, <add> createIdForPathFn, <add>} = require('../util'); <add> <add>const {any} = jasmine; <add> <add>describe('`addModuleIdsToModuleWrapper`:', () => { <add> const path = 'path/to/file'; <add> const createModule = (dependencies = []) => ({ <add> dependencies, <add> file: {code: '__d(function(){});', isModule: true, path}, <add> }); <add> <add> it('completes the module wrapped with module ID, and an array of dependency IDs', () => { <add> const dependencies = [ <add> {id: 'a', path: 'path/to/a.js'}, <add> {id: 'b', path: 'location/of/b.js'}, <add> ]; <add> const module = createModule(dependencies); <add> <add> const idForPath = fn(); <add> idForPath.stub <add> .withArgs(match({path})).returns(12) <add> .withArgs(match({path: dependencies[0].path})).returns(345) <add> .withArgs(match({path: dependencies[1].path})).returns(6); <add> <add> expect(addModuleIdsToModuleWrapper(module, idForPath)) <add> .toEqual('__d(function(){}, 12, [345, 6]);'); <add> }); <add> <add> it('omits the array of dependency IDs if it is empty', () => { <add> const module = createModule(); <add> expect(addModuleIdsToModuleWrapper(module, () => 98)) <add> .toEqual(`__d(function(){}, ${98});`); <add> }); <add>}); <add> <add>describe('`createIdForPathFn`', () => { <add> let idForPath; <add> beforeEach(() => { <add> idForPath = createIdForPathFn(); <add> }); <add> <add> it('returns a number for a string', () => { <add> expect(idForPath({path: 'arbitrary'})).toEqual(any(Number)); <add> }); <add> <add> it('returns consecutive numbers', () => { <add> const strings = [ <add> 'arbitrary string', <add> 'looking/like/a/path', <add> '/absolute/path/to/file.js', <add> '/more files/are here', <add> ]; <add> <add> strings.forEach((string, i) => { <add> expect(idForPath({path: string})).toEqual(i); <add> }); <add> }); <add> <add> it('returns the same id if the same string is passed in again', () => { <add> const path = 'this/is/an/arbitrary/path.js'; <add> const id = idForPath({path}); <add> idForPath({path: '/other/file'}); <add> idForPath({path: 'and/another/file'}); <add> expect(idForPath({path})).toEqual(id); <add> }); <add>}); <ide><path>packager/react-packager/src/ModuleGraph/output/util.js <add>/** <add> * Copyright (c) 2016-present, Facebook, Inc. <add> * All rights reserved. <add> * <add> * This source code is licensed under the BSD-style license found in the <add> * LICENSE file in the root directory of this source tree. An additional grant <add> * of patent rights can be found in the PATENTS file in the same directory. <add> * <add> * @flow <add> */ <add>'use strict'; <add> <add>import type {Module} from '../types.flow'; <add> <add>// Transformed modules have the form <add>// __d(function(require, module, global, exports, dependencyMap) { <add>// /* code */ <add>// }); <add>// <add>// This function adds the numeric module ID, and an array with dependencies of <add>// the dependencies of the module before the closing parenthesis. <add>exports.addModuleIdsToModuleWrapper = ( <add> module: Module, <add> idForPath: {path: string} => number, <add>): string => { <add> const {dependencies, file} = module; <add> const {code} = file; <add> const index = code.lastIndexOf(')'); <add> const depencyIds = <add> dependencies.length ? `, [${dependencies.map(idForPath).join(', ')}]` : ''; <add> return ( <add> code.slice(0, index) + <add> `, ${idForPath(file)}` + <add> depencyIds + <add> code.slice(index) <add> ); <add>}; <add> <add>// Creates an idempotent function that returns numeric IDs for objects based <add>// on their `path` property. <add>exports.createIdForPathFn = (): ({path: string} => number) => { <add> const seen = new Map(); <add> let next = 0; <add> return ({path}) => { <add> let id = seen.get(path); <add> if (id == null) { <add> id = next++; <add> seen.set(path, id); <add> } <add> return id; <add> }; <add>};
2
Text
Text
remove unused line from log readme.md
23c9e2f218b2d24ac672edc8d8f32a9f5cf204f5
<ide><path>src/Log/README.md <ide> You can define as many or as few loggers as your application needs. Loggers <ide> should be configured using `Cake\Core\Log.` An example would be: <ide> <ide> ```php <del>use Cake\Cache\Cache; <del> <ide> use Cake\Log\Log; <ide> <ide> // Short classname
1
Javascript
Javascript
fix documentation for {{each}} helper
82fd051b09b2814fa098f21a493eec73bd8e6074
<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"; <ide> import normalizeSelf from "ember-htmlbars/utils/normalize-self"; <ide> <add>/** <add> The `{{#each}}` helper loops over elements in a collection. It is an extension <add> of the base Handlebars `{{#each}}` helper. <add> <add> The default behavior of `{{#each}}` is to yield its inner block once for every <add> item in an array. <add> <add> ```javascript <add> var developers = [{name: 'Yehuda'},{name: 'Tom'}, {name: 'Paul'}]; <add> ``` <add> <add> ```handlebars <add> {{#each developers as |person|}} <add> {{person.name}} <add> {{! `this` is whatever it was outside the #each }} <add> {{/each}} <add> ``` <add> <add> The same rules apply to arrays of primitives. <add> <add> ```javascript <add> var developerNames = ['Yehuda', 'Tom', 'Paul'] <add> ``` <add> <add> ```handlebars <add> {{#each developerNames as |name|}} <add> {{name}} <add> {{/each}} <add> ``` <add> <add> ### {{else}} condition <add> <add> `{{#each}}` can have a matching `{{else}}`. The contents of this block will render <add> if the collection is empty. <add> <add> ```handlebars <add> {{#each developers as |person|}} <add> {{person.name}} <add> {{else}} <add> <p>Sorry, nobody is available for this task.</p> <add> {{/each}} <add> ``` <add> <add> ### Specifying an alternative view for each item <add> <add> `itemViewClass` can control which view will be used during the render of each <add> item's template. The following template: <add> <add> ```handlebars <add> <ul> <add> {{#each developers itemViewClass="person" as |developer|}} <add> {{developer.name}} <add> {{/each}} <add> </ul> <add> ``` <add> <add> Will use the following view for each item: <add> <add> ```javascript <add> App.PersonView = Ember.View.extend({ <add> tagName: 'li' <add> }); <add> ``` <add> <add> Resulting in HTML output that looks like the following: <add> <add> ```html <add> <ul> <add> <li class="ember-view">Yehuda</li> <add> <li class="ember-view">Tom</li> <add> <li class="ember-view">Paul</li> <add> </ul> <add> ``` <add> <add> `itemViewClass` also enables a non-block form of `{{each}}`. The view <add> must [provide its own template](/api/classes/Ember.View.html#toc_templates) <add> and then the block should be dropped. An example that outputs the same HTML <add> as the previous one: <add> <add> ```javascript <add> App.PersonView = Ember.View.extend({ <add> tagName: 'li', <add> template: '{{developer.name}}' <add> }); <add> ``` <add> <add> ```handlebars <add> <ul> <add> {{each developers itemViewClass="person" as |developer|}} <add> </ul> <add> ``` <add> <add> ### Specifying an alternative view for no items (else) <add> <add> The `emptyViewClass` option provides the same flexibility to the `{{else}}` <add> case of the each helper. <add> <add> ```javascript <add> App.NoPeopleView = Ember.View.extend({ <add> tagName: 'li', <add> template: 'No person is available, sorry' <add> }); <add> ``` <add> <add> ```handlebars <add> <ul> <add> {{#each developers emptyViewClass="no-people" as |developer|}} <add> <li>{{developer.name}}</li> <add> {{/each}} <add> </ul> <add> ``` <add> <add> ### Wrapping each item in a controller <add> <add> Controllers in Ember manage state and decorate data. In many cases, <add> providing a controller for each item in a list can be useful. <add> An item that is passed to an item controller will be set as the `model` property <add> on the controller. <add> <add> This allows state and decoration to be added to the controller <add> while any other property lookups can be delegated to the model. An example: <add> <add> ```javascript <add> App.RecruitController = Ember.Controller.extend({ <add> isAvailableForHire: function() { <add> return !this.get('model.isEmployed') && this.get('model.isSeekingWork'); <add> }.property('model.isEmployed', 'model.isSeekingWork') <add> }) <add> ``` <add> <add> ```handlebars <add> {{#each developers itemController="recruit" as |person|}} <add> {{person.model.name}} {{#if person.isAvailableForHire}}Hire me!{{/if}} <add> {{/each}} <add> ``` <add> <add> @method each <add> @for Ember.Handlebars.helpers <add> @param [name] {String} name for item (used with `as`) <add> @param [path] {String} path <add> @param [options] {Object} Handlebars key/value pairs of options <add> @param [options.itemViewClass] {String} a path to a view class used for each item <add> @param [options.emptyViewClass] {String} a path to a view class used for each item <add> @param [options.itemController] {String} name of a controller to be created for each item <add>*/ <ide> export default function eachHelper(params, hash, blocks) { <ide> var list = params[0]; <ide> var keyPath = hash.key;
1
Go
Go
add new adjectives to the names generator
88ce14ca1a382ddd39f981200e9f562cf35ff035
<ide><path>pkg/namesgenerator/names-generator.go <ide> var ( <ide> "amazing", <ide> "angry", <ide> "awesome", <add> "beautiful", <ide> "blissful", <ide> "bold", <ide> "boring", <ide> "brave", <add> "busy", <ide> "charming", <ide> "clever", <ide> "cocky", <ide> var ( <ide> "elegant", <ide> "eloquent", <ide> "epic", <add> "exciting", <ide> "fervent", <ide> "festive", <ide> "flamboyant", <ide> "focused", <ide> "friendly", <ide> "frosty", <add> "funny", <ide> "gallant", <ide> "gifted", <ide> "goofy", <ide> "gracious", <add> "great", <ide> "happy", <ide> "hardcore", <ide> "heuristic", <ide> "hopeful", <ide> "hungry", <ide> "infallible", <ide> "inspiring", <add> "interesting", <add> "intelligent", <ide> "jolly", <ide> "jovial", <ide> "keen", <ide> var ( <ide> "musing", <ide> "naughty", <ide> "nervous", <add> "nice", <ide> "nifty", <ide> "nostalgic", <ide> "objective", <ide> var ( <ide> "silly", <ide> "sleepy", <ide> "stoic", <add> "strange", <ide> "stupefied", <ide> "suspicious", <ide> "sweet",
1
PHP
PHP
remove unneeded variable assignment
8f25dfe3cd86e0bc9edd9bc892e1f4573c25cee9
<ide><path>src/Core/functions.php <ide> function env(string $key, $default = null) <ide> */ <ide> function triggerWarning(string $message): void <ide> { <del> $stackFrame = 1; <ide> $trace = debug_backtrace(); <del> if (isset($trace[$stackFrame])) { <del> $frame = $trace[$stackFrame]; <add> if (isset($trace[1])) { <add> $frame = $trace[1]; <ide> $frame += ['file' => '[internal]', 'line' => '??']; <ide> $message = sprintf( <ide> '%s - %s, line: %s',
1
Javascript
Javascript
remove some useless boilerplate
9d992a91f2b1bf8977ae63c9a044a5500b3e94a0
<ide><path>examples/async/server.js <ide> var port = 3000; <ide> <ide> var compiler = webpack(config); <ide> app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000 })); <add>app.use(webpackHotMiddleware(compiler)); <ide> <ide> app.get("/", function(req, res) { <ide> res.sendFile(__dirname + '/index.html'); <ide><path>examples/async/webpack.config.js <ide> var webpack = require('webpack'); <ide> module.exports = { <ide> devtool: 'cheap-module-eval-source-map', <ide> entry: [ <del> 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', <add> 'webpack-hot-middleware/client', <ide> './index' <ide> ], <ide> output: { <ide><path>examples/counter/server.js <ide> var port = 3000; <ide> <ide> var compiler = webpack(config); <ide> app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000 })); <add>app.use(webpackHotMiddleware(compiler)); <ide> <ide> app.get("/", function(req, res) { <ide> res.sendFile(__dirname + '/index.html'); <ide><path>examples/counter/webpack.config.js <ide> var webpack = require('webpack'); <ide> module.exports = { <ide> devtool: 'cheap-module-eval-source-map', <ide> entry: [ <del> 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', <add> 'webpack-hot-middleware/client', <ide> './index' <ide> ], <ide> output: { <ide><path>examples/real-world/server.js <ide> var port = 3000; <ide> <ide> var compiler = webpack(config); <ide> app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000 })); <add>app.use(webpackHotMiddleware(compiler)); <ide> <ide> app.get("/", function(req, res) { <ide> res.sendFile(__dirname + '/index.html'); <ide><path>examples/real-world/webpack.config.js <ide> var webpack = require('webpack'); <ide> module.exports = { <ide> devtool: 'cheap-module-eval-source-map', <ide> entry: [ <del> 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', <add> 'webpack-hot-middleware/client', <ide> './index' <ide> ], <ide> output: { <ide><path>examples/todomvc/server.js <ide> var port = 3000; <ide> <ide> var compiler = webpack(config); <ide> app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: config.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000 })); <add>app.use(webpackHotMiddleware(compiler)); <ide> <ide> app.get("/", function(req, res) { <ide> res.sendFile(__dirname + '/index.html'); <ide><path>examples/todomvc/webpack.config.js <ide> var webpack = require('webpack'); <ide> module.exports = { <ide> devtool: 'cheap-module-eval-source-map', <ide> entry: [ <del> 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', <add> 'webpack-hot-middleware/client', <ide> './index' <ide> ], <ide> output: { <ide><path>examples/universal/server/server.js <ide> const port = 3000; <ide> // Use this middleware to set up hot module reloading via webpack. <ide> const compiler = webpack(webpackConfig); <ide> app.use(webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath })); <del>app.use(webpackHotMiddleware(compiler, { log: console.log, path: '/__webpack_hmr', heartbeat: 10 * 1000 })); <add>app.use(webpackHotMiddleware(compiler)); <ide> <ide> // This is fired every time the server side receives a request <ide> app.use(handleRender); <ide><path>examples/universal/webpack.config.js <ide> var webpack = require('webpack'); <ide> module.exports = { <ide> devtool: 'inline-source-map', <ide> entry: [ <del> 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', <add> 'webpack-hot-middleware/client', <ide> './client/index.js' <ide> ], <ide> output: {
10
Text
Text
add ternary example
c2de333137b149e30d0997570f563e56cbee2ff0
<ide><path>guide/english/php/if-else-statement/index.md <ide> For instance: <ide> <ide> ## Ternary Operators <ide> <del>Another important option to consider when using short If/Else statements is the ternary operator. <add>Another option to consider when using short If/Else statements is the ternary operator. <ide> <del>Also there is an alternative syntax for control structures <add>For instance: <add> <add>``` <add><?php <add> <add>$var = (condition) ? (value if true) : (value if false); <add>``` <add> <add>## Alternative If/Else Syntax <add> <add>There is also an alternative syntax for control structures <ide> ~~~~ <ide> if (condition1): <ide> statement1;
1
Ruby
Ruby
add a deprecation for helpers_dir
49be3316c21ae1b779fc26a5eb51890deff56915
<ide><path>actionpack/lib/action_controller/metal/helpers.rb <ide> module Helpers <ide> end <ide> <ide> module ClassMethods <add> def helpers_dir <add> ActiveSupport::Deprecation.warn "ActionController::Base.helpers_dir is deprecated. " << <add> "Please use ActionController::Base.helpers_path (which returns an array)" <add> self.helpers_path <add> end <add> <add> def helpers_dir=(value) <add> ActiveSupport::Deprecation.warn "ActionController::Base.helpers_dir= is deprecated. " << <add> "Please use ActionController::Base.helpers_path= (which is an array)" <add> self.helpers_path = Array(value) <add> end <add> <ide> def inherited(klass) <ide> klass.class_eval { default_helper_module! unless name.blank? } <ide> super <ide><path>actionpack/test/controller/helper_test.rb <ide> def b() end <ide> def c() end <ide> end <ide> <del>class HelperTest < Test::Unit::TestCase <add>class HelperTest < ActiveSupport::TestCase <ide> class TestController < ActionController::Base <ide> attr_accessor :delegate_attr <ide> def delegate_method() end <ide> def test_helper_proxy <ide> assert methods.include?('foobar') <ide> end <ide> <add> def test_deprecation <add> assert_deprecated do <add> ActionController::Base.helpers_dir = "some/foo/bar" <add> end <add> assert_deprecated do <add> assert_equal ["some/foo/bar"], ActionController::Base.helpers_dir <add> end <add> ensure <add> ActionController::Base.helpers_path = [File.dirname(__FILE__) + '/../fixtures/helpers'] <add> end <add> <ide> private <ide> def expected_helper_methods <ide> TestHelper.instance_methods.map {|m| m.to_s } <ide> def test_helper=(helper_module) <ide> end <ide> <ide> <del>class IsolatedHelpersTest < Test::Unit::TestCase <add>class IsolatedHelpersTest < ActiveSupport::TestCase <ide> class A < ActionController::Base <ide> def index <ide> render :inline => '<%= shout %>'
2
Javascript
Javascript
fix lint error
75435b9b08cd7eebb25394ae45b3f888dd001027
<ide><path>src/renderers/webgl/WebGLLights.js <ide> function WebGLLights() { <ide> hash.hemiLength = hemiLength; <ide> hash.shadowsLength = shadows.length; <ide> <del> hash.value++; <add> hash.value ++; <ide> <ide> } <ide>
1
Mixed
Ruby
stringify keys in session.merge!
2bdd29a6e48fe04c6fb6b7c73471a03ecae0ab7c
<ide><path>actionpack/CHANGELOG.md <add>* Make `Session#merge!` stringify keys. <ide> <add> Previously `Session#update` would, but `merge!` wouldn't. <add> <add> *Drew Bragg* <ide> <ide> Please check [7-0-stable](https://github.com/rails/rails/blob/7-0-stable/actionpack/CHANGELOG.md) for previous changes. <ide><path>actionpack/lib/action_dispatch/request/session.rb <ide> def to_hash <ide> # session.to_hash <ide> # # => {"session_id"=>"e29b9ea315edf98aad94cc78c34cc9b2", "foo" => "bar"} <ide> def update(hash) <add> unless hash.respond_to?(:to_hash) <add> raise TypeError, "no implicit conversion of #{hash.class.name} into Hash" <add> end <add> <ide> load_for_write! <del> @delegate.update hash.stringify_keys <add> @delegate.update hash.to_hash.stringify_keys <ide> end <add> alias :merge! :update <ide> <ide> # Deletes given key from the session. <ide> def delete(key) <ide> def empty? <ide> @delegate.empty? <ide> end <ide> <del> def merge!(other) <del> load_for_write! <del> @delegate.merge!(other) <del> end <del> <ide> def each(&block) <ide> to_hash.each(&block) <ide> end <ide><path>actionpack/test/dispatch/session/abstract_store_test.rb <ide> def test_new_session_object_is_merged_with_old <ide> assert_equal session.to_hash, session1.to_hash <ide> end <ide> <add> def test_update_raises_an_exception_if_arg_not_hashable <add> env = {} <add> as = MemoryStore.new app <add> as.call(env) <add> session = Request::Session.find ActionDispatch::Request.new env <add> <add> assert_raise TypeError do <add> session.update("Not hashable") <add> end <add> end <add> <ide> private <ide> def app(&block) <ide> @env = nil <ide><path>actionpack/test/dispatch/session/test_session_test.rb <ide> def test_session_id <ide> assert_instance_of String, session.id.public_id <ide> assert_equal(session.id.public_id, session["session_id"]) <ide> end <add> <add> def test_merge! <add> session = ActionController::TestSession.new <add> session.merge!({ key: "value" }) <add> assert_equal("value", session["key"]) <add> end <ide> end
4
Text
Text
fix the example (for realz)
9af5f33a1629f16c56137e2b9903bc977455075f
<ide><path>actionpack/CHANGELOG.md <ide> <ide> class ApplicationController < ActionController::Base <ide> before_action :authenticate <del> protect_from_forgery prepend: true, unless: -> { @authenticated_by.oauth? } <add> protect_from_forgery prepend: false, unless: -> { @authenticated_by.oauth? } <ide> <ide> private <ide> def authenticate
1
PHP
PHP
restore only error handler
e39b2f50fe5cc5aba9975d47810f3abd6293f683
<ide><path>tests/TestCase/Error/ErrorHandlerTest.php <ide> public function testHandleErrorDebugOn() <ide> */ <ide> public function testHandleErrorTraceOffset() <ide> { <del> $this->_restoreError = true; <del> <ide> set_error_handler(function ($code, $message, $file, $line, $context = null) { <ide> $errorHandler = new ErrorHandler(); <ide> $context['_trace_frame_offset'] = 3; <ide> public function testHandleErrorTraceOffset() <ide> $wrong = $wrong + 1; <ide> $result = ob_get_clean(); <ide> <add> restore_error_handler(); <add> <ide> $this->assertStringNotContainsString( <ide> 'ErrorHandlerTest.php, line ' . (__LINE__ - 4), <ide> $result,
1
Java
Java
enrich websockethandler context
a11d1c8510c34cdb0889a13af969c3cf424464f3
<ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/adapter/ContextWebSocketHandler.java <add>/* <add> * Copyright 2002-2020 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>package org.springframework.web.reactive.socket.adapter; <add> <add>import java.util.List; <add> <add>import reactor.core.publisher.Mono; <add>import reactor.util.context.ContextView; <add> <add>import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.WebSocketSession; <add> <add>/** <add> * {@link WebSocketHandler} decorator that enriches the context of the target handler. <add> * <add> * @author Rossen Stoyanchev <add> * @since 5.3.3 <add> */ <add>public final class ContextWebSocketHandler implements WebSocketHandler { <add> <add> private final WebSocketHandler delegate; <add> <add> private final ContextView contextView; <add> <add> <add> private ContextWebSocketHandler(WebSocketHandler delegate, ContextView contextView) { <add> this.delegate = delegate; <add> this.contextView = contextView; <add> } <add> <add> <add> @Override <add> public List<String> getSubProtocols() { <add> return this.delegate.getSubProtocols(); <add> } <add> <add> @Override <add> public Mono<Void> handle(WebSocketSession session) { <add> return this.delegate.handle(session).contextWrite(this.contextView); <add> } <add> <add> <add> /** <add> * Return the given handler, decorated to insert the given context, or the <add> * same handler instance when the context is empty. <add> */ <add> public static WebSocketHandler decorate(WebSocketHandler handler, ContextView contextView) { <add> return (!contextView.isEmpty() ? new ContextWebSocketHandler(handler, contextView) : handler); <add> } <add> <add>} <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/JettyWebSocketClient.java <ide> <ide> package org.springframework.web.reactive.socket.client; <ide> <add>import java.io.IOException; <ide> import java.net.URI; <ide> <ide> import org.apache.commons.logging.Log; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler; <ide> import org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.adapter.JettyWebSocketSession; <ide> <ide> public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler <ide> <ide> private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) { <ide> Sinks.Empty<Void> completionSink = Sinks.empty(); <del> return Mono.fromCallable( <del> () -> { <del> if (logger.isDebugEnabled()) { <del> logger.debug("Connecting to " + url); <del> } <del> Object jettyHandler = createHandler(url, handler, completionSink); <del> ClientUpgradeRequest request = new ClientUpgradeRequest(); <del> request.setSubProtocols(handler.getSubProtocols()); <del> UpgradeListener upgradeListener = new DefaultUpgradeListener(headers); <del> return this.jettyClient.connect(jettyHandler, url, request, upgradeListener); <del> }) <del> .then(completionSink.asMono()); <add> return Mono.deferContextual(contextView -> { <add> if (logger.isDebugEnabled()) { <add> logger.debug("Connecting to " + url); <add> } <add> Object jettyHandler = createHandler( <add> url, ContextWebSocketHandler.decorate(handler, contextView), completionSink); <add> ClientUpgradeRequest request = new ClientUpgradeRequest(); <add> request.setSubProtocols(handler.getSubProtocols()); <add> UpgradeListener upgradeListener = new DefaultUpgradeListener(headers); <add> try { <add> this.jettyClient.connect(jettyHandler, url, request, upgradeListener); <add> return completionSink.asMono(); <add> } <add> catch (IOException ex) { <add> return Mono.error(ex); <add> } <add> }); <ide> } <ide> <ide> private Object createHandler(URI url, WebSocketHandler handler, Sinks.Empty<Void> completion) { <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/StandardWebSocketClient.java <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler; <ide> import org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.adapter.StandardWebSocketSession; <ide> <ide> public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler <ide> } <ide> <ide> private Mono<Void> executeInternal(URI url, HttpHeaders requestHeaders, WebSocketHandler handler) { <del> Sinks.Empty<Void> completionSink = Sinks.empty(); <del> return Mono.fromCallable( <del> () -> { <add> Sinks.Empty<Void> completion = Sinks.empty(); <add> return Mono.deferContextual( <add> contextView -> { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Connecting to " + url); <ide> } <ide> List<String> protocols = handler.getSubProtocols(); <ide> DefaultConfigurator configurator = new DefaultConfigurator(requestHeaders); <del> Endpoint endpoint = createEndpoint(url, handler, completionSink, configurator); <add> Endpoint endpoint = createEndpoint( <add> url, ContextWebSocketHandler.decorate(handler, contextView), completion, configurator); <ide> ClientEndpointConfig config = createEndpointConfig(configurator, protocols); <del> return this.webSocketContainer.connectToServer(endpoint, config, url); <add> try { <add> this.webSocketContainer.connectToServer(endpoint, config, url); <add> return completion.asMono(); <add> } <add> catch (Exception ex) { <add> return Mono.error(ex); <add> } <ide> }) <del> .subscribeOn(Schedulers.boundedElastic()) // connectToServer is blocking <del> .then(completionSink.asMono()); <add> .subscribeOn(Schedulers.boundedElastic()); // connectToServer is blocking <ide> } <ide> <ide> private StandardWebSocketHandlerAdapter createEndpoint(URI url, WebSocketHandler handler, <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/client/UndertowWebSocketClient.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler; <ide> import org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.adapter.UndertowWebSocketSession; <ide> <ide> public Mono<Void> execute(URI url, HttpHeaders headers, WebSocketHandler handler <ide> } <ide> <ide> private Mono<Void> executeInternal(URI url, HttpHeaders headers, WebSocketHandler handler) { <del> Sinks.Empty<Void> completionSink = Sinks.empty(); <del> return Mono.fromCallable( <del> () -> { <add> Sinks.Empty<Void> completion = Sinks.empty(); <add> return Mono.deferContextual( <add> contextView -> { <ide> if (logger.isDebugEnabled()) { <ide> logger.debug("Connecting to " + url); <ide> } <ide> List<String> protocols = handler.getSubProtocols(); <ide> ConnectionBuilder builder = createConnectionBuilder(url); <ide> DefaultNegotiation negotiation = new DefaultNegotiation(protocols, headers, builder); <ide> builder.setClientNegotiation(negotiation); <del> return builder.connect().addNotifier( <add> builder.connect().addNotifier( <ide> new IoFuture.HandlingNotifier<WebSocketChannel, Object>() { <ide> @Override <ide> public void handleDone(WebSocketChannel channel, Object attachment) { <del> handleChannel(url, handler, completionSink, negotiation, channel); <add> handleChannel(url, ContextWebSocketHandler.decorate(handler, contextView), <add> completion, negotiation, channel); <ide> } <ide> @Override <ide> public void handleFailed(IOException ex, Object attachment) { <ide> // Ignore result: can't overflow, ok if not first or no one listens <del> completionSink.tryEmitError( <add> completion.tryEmitError( <ide> new IllegalStateException("Failed to connect to " + url, ex)); <ide> } <ide> }, null); <del> }) <del> .then(completionSink.asMono()); <add> return completion.asMono(); <add> }); <ide> } <ide> <ide> /** <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/JettyRequestUpgradeStrategy.java <ide> <ide> package org.springframework.web.reactive.socket.server.upgrade; <ide> <add>import java.io.IOException; <ide> import java.util.function.Supplier; <ide> <ide> import javax.servlet.ServletContext; <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler; <ide> import org.springframework.web.reactive.socket.adapter.JettyWebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.adapter.JettyWebSocketSession; <ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; <ide> public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, <ide> HandshakeInfo handshakeInfo = handshakeInfoFactory.get(); <ide> DataBufferFactory factory = response.bufferFactory(); <ide> <del> JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter( <del> handler, session -> new JettyWebSocketSession(session, handshakeInfo, factory)); <del> <ide> startLazily(servletRequest); <ide> <ide> Assert.state(this.factory != null, "No WebSocketServerFactory available"); <ide> public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, <ide> <ide> // Trigger WebFlux preCommit actions and upgrade <ide> return exchange.getResponse().setComplete() <del> .then(Mono.fromCallable(() -> { <add> .then(Mono.deferContextual(contextView -> { <add> JettyWebSocketHandlerAdapter adapter = new JettyWebSocketHandlerAdapter( <add> ContextWebSocketHandler.decorate(handler, contextView), <add> session -> new JettyWebSocketSession(session, handshakeInfo, factory)); <add> <ide> try { <ide> adapterHolder.set(new WebSocketHandlerContainer(adapter, subProtocol)); <ide> this.factory.acceptWebSocket(servletRequest, servletResponse); <ide> } <add> catch (IOException ex) { <add> return Mono.error(ex); <add> } <ide> finally { <ide> adapterHolder.remove(); <ide> } <del> return null; <add> return Mono.empty(); <ide> })); <ide> } <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/TomcatRequestUpgradeStrategy.java <ide> import org.springframework.util.Assert; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler; <ide> import org.springframework.web.reactive.socket.adapter.StandardWebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.adapter.TomcatWebSocketSession; <ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; <ide> public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, <ide> HandshakeInfo handshakeInfo = handshakeInfoFactory.get(); <ide> DataBufferFactory bufferFactory = response.bufferFactory(); <ide> <del> Endpoint endpoint = new StandardWebSocketHandlerAdapter( <del> handler, session -> new TomcatWebSocketSession(session, handshakeInfo, bufferFactory)); <del> <del> String requestURI = servletRequest.getRequestURI(); <del> DefaultServerEndpointConfig config = new DefaultServerEndpointConfig(requestURI, endpoint); <del> config.setSubprotocols(subProtocol != null ? <del> Collections.singletonList(subProtocol) : Collections.emptyList()); <del> <ide> // Trigger WebFlux preCommit actions and upgrade <ide> return exchange.getResponse().setComplete() <del> .then(Mono.fromCallable(() -> { <add> .then(Mono.deferContextual(contextView -> { <add> Endpoint endpoint = new StandardWebSocketHandlerAdapter( <add> ContextWebSocketHandler.decorate(handler, contextView), <add> session -> new TomcatWebSocketSession(session, handshakeInfo, bufferFactory)); <add> <add> String requestURI = servletRequest.getRequestURI(); <add> DefaultServerEndpointConfig config = new DefaultServerEndpointConfig(requestURI, endpoint); <add> config.setSubprotocols(subProtocol != null ? <add> Collections.singletonList(subProtocol) : Collections.emptyList()); <add> <ide> WsServerContainer container = getContainer(servletRequest); <del> container.doUpgrade(servletRequest, servletResponse, config, Collections.emptyMap()); <del> return null; <add> try { <add> container.doUpgrade(servletRequest, servletResponse, config, Collections.emptyMap()); <add> } <add> catch (Exception ex) { <add> return Mono.error(ex); <add> } <add> return Mono.empty(); <ide> })); <ide> } <ide> <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/socket/server/upgrade/UndertowRequestUpgradeStrategy.java <ide> import org.springframework.lang.Nullable; <ide> import org.springframework.web.reactive.socket.HandshakeInfo; <ide> import org.springframework.web.reactive.socket.WebSocketHandler; <add>import org.springframework.web.reactive.socket.adapter.ContextWebSocketHandler; <ide> import org.springframework.web.reactive.socket.adapter.UndertowWebSocketHandlerAdapter; <ide> import org.springframework.web.reactive.socket.adapter.UndertowWebSocketSession; <ide> import org.springframework.web.reactive.socket.server.RequestUpgradeStrategy; <ide> public Mono<Void> upgrade(ServerWebExchange exchange, WebSocketHandler handler, <ide> <ide> // Trigger WebFlux preCommit actions and upgrade <ide> return exchange.getResponse().setComplete() <del> .then(Mono.fromCallable(() -> { <del> DefaultCallback callback = new DefaultCallback(handshakeInfo, handler, bufferFactory); <del> new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange); <del> return null; <add> .then(Mono.deferContextual(contextView -> { <add> DefaultCallback callback = new DefaultCallback( <add> handshakeInfo, <add> ContextWebSocketHandler.decorate(handler, contextView), <add> bufferFactory); <add> try { <add> new WebSocketProtocolHandshakeHandler(handshakes, callback).handleRequest(httpExchange); <add> } <add> catch (Exception ex) { <add> return Mono.error(ex); <add> } <add> return Mono.empty(); <ide> })); <ide> } <ide> <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/AbstractWebSocketIntegrationTests.java <ide> import org.springframework.context.annotation.Bean; <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.http.server.reactive.HttpHandler; <add>import org.springframework.web.filter.reactive.ServerWebExchangeContextFilter; <ide> import org.springframework.web.reactive.DispatcherHandler; <ide> import org.springframework.web.reactive.socket.client.JettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.client.ReactorNettyWebSocketClient; <ide> import org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy; <ide> import org.springframework.web.reactive.socket.server.upgrade.TomcatRequestUpgradeStrategy; <ide> import org.springframework.web.reactive.socket.server.upgrade.UndertowRequestUpgradeStrategy; <add>import org.springframework.web.server.WebFilter; <ide> import org.springframework.web.server.adapter.WebHttpHandlerBuilder; <ide> import org.springframework.web.testfixture.http.server.reactive.bootstrap.HttpServer; <ide> import org.springframework.web.testfixture.http.server.reactive.bootstrap.JettyHttpServer; <ide> protected URI getUrl(String path) { <ide> @Configuration <ide> static class DispatcherConfig { <ide> <add> @Bean <add> public WebFilter contextFilter() { <add> return new ServerWebExchangeContextFilter(); <add> } <add> <ide> @Bean <ide> public DispatcherHandler webHandler() { <ide> return new DispatcherHandler(); <ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/socket/WebSocketIntegrationTests.java <ide> import org.springframework.context.annotation.Configuration; <ide> import org.springframework.http.HttpHeaders; <ide> import org.springframework.http.ResponseCookie; <add>import org.springframework.web.filter.reactive.ServerWebExchangeContextFilter; <ide> import org.springframework.web.reactive.HandlerMapping; <ide> import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping; <ide> import org.springframework.web.reactive.socket.client.WebSocketClient; <ide> private static class EchoWebSocketHandler implements WebSocketHandler { <ide> <ide> @Override <ide> public Mono<Void> handle(WebSocketSession session) { <del> // Use retain() for Reactor Netty <del> return session.send(session.receive().doOnNext(WebSocketMessage::retain)); <add> return Mono.deferContextual(contextView -> { <add> String key = ServerWebExchangeContextFilter.EXCHANGE_CONTEXT_ATTRIBUTE; <add> assertThat(contextView.getOrEmpty(key).orElse(null)).isNotNull(); <add> return session.send(session.receive().doOnNext(WebSocketMessage::retain)); <add> }); <ide> } <ide> } <ide>
9
Go
Go
remove defaultstopsignal const
e53f65a9168aaf4289a490bd56d9e05b46c08bec
<ide><path>container/container.go <ide> func (container *Container) StopSignal() int { <ide> } <ide> <ide> if int(stopSignal) == 0 { <del> stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal) <add> stopSignal, _ = signal.ParseSignal(defaultStopSignal) <ide> } <ide> return int(stopSignal) <ide> } <ide><path>container/container_unit_test.go <ide> func TestContainerStopSignal(t *testing.T) { <ide> Config: &container.Config{}, <ide> } <ide> <del> def, err := signal.ParseSignal(signal.DefaultStopSignal) <add> def, err := signal.ParseSignal(defaultStopSignal) <ide> if err != nil { <ide> t.Fatal(err) <ide> } <ide><path>container/container_unix.go <ide> import ( <ide> ) <ide> <ide> const ( <add> // defaultStopSignal is the default syscall signal used to stop a container. <add> defaultStopSignal = "SIGTERM" <add> <ide> // defaultStopTimeout sets the default time, in seconds, to wait <ide> // for the graceful container stop before forcefully terminating it. <ide> defaultStopTimeout = 10 <ide><path>container/container_windows.go <ide> const ( <ide> containerInternalSecretMountPath = `C:\ProgramData\Docker\internal\secrets` <ide> containerInternalConfigsDirPath = `C:\ProgramData\Docker\internal\configs` <ide> <add> // defaultStopSignal is the default syscall signal used to stop a container. <add> defaultStopSignal = "SIGTERM" <add> <ide> // defaultStopTimeout is the timeout (in seconds) for the shutdown call on a container <ide> defaultStopTimeout = 30 <ide> ) <ide><path>pkg/signal/signal_deprecated.go <ide> const ( <ide> // SIGPIPE is a signal sent to a process when a pipe is written to before the other end is open for reading <ide> // Deprecated: use github.com/moby/sys/signal.SIGPIPE instead <ide> SIGPIPE = msignal.SIGPIPE <del> // DefaultStopSignal is the syscall signal used to stop a container in unix systems. <del> // Deprecated: use github.com/moby/sys/signal.DefaultStopSignal instead <del> DefaultStopSignal = msignal.DefaultStopSignal <add> <add> // DefaultStopSignal has been deprecated and removed. The default value is <add> // now defined in github.com/docker/docker/container. Clients should omit <add> // the container's stop-signal field if the default should be used. <ide> )
5
Javascript
Javascript
add example to file list
3434106cef5a8c0770d68b3b3b0e782ab60655a7
<ide><path>examples/files.js <ide> var files = { <ide> "webgl_postprocessing_sobel", <ide> "webgl_postprocessing_ssao", <ide> "webgl_postprocessing_taa", <del> "webgl_postprocessing_unreal_bloom" <add> "webgl_postprocessing_unreal_bloom", <add> "webgl_postprocessing_unreal_bloom_selective" <ide> ], <ide> "webgl / advanced": [ <ide> "webgl_buffergeometry",
1
Javascript
Javascript
fix parse errors on older android webviews
1cc9c9ca9d9698356ea541517b3d06ce6556c01d
<ide><path>src/ng/animateCss.js <ide> var $CoreAnimateCssProvider = function() { <ide> return this.getPromise().then(f1,f2); <ide> }, <ide> 'catch': function(f1) { <del> return this.getPromise().catch(f1); <add> return this.getPromise()['catch'](f1); <ide> }, <ide> 'finally': function(f1) { <del> return this.getPromise().finally(f1); <add> return this.getPromise()['finally'](f1); <ide> } <ide> }; <ide>
1
PHP
PHP
use correct template name
8c8ed0f2b285f493e527b6d509ba2c446bdb339e
<ide><path>src/View/Cell.php <ide> public function render($template = null) <ide> if (!$builder->getTemplatePath()) { <ide> $builder->setTemplatePath('Cell' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $name)); <ide> } <add> $template = $builder->getTemplate(); <ide> <ide> $this->View = $this->createView(); <ide> try {
1
Text
Text
fix nits in esm.md
b4b7ac6ae811b2b5a3082468115dfb5a5246fe3f
<ide><path>doc/api/esm.md <ide> <ide> <!--name=esm--> <ide> <del>Node contains support for ES Modules based upon the [the Node EP for ES Modules][]. <add>Node.js contains support for ES Modules based upon the <add>[Node.js EP for ES Modules][]. <ide> <del>Not all features of the EP are complete and will be landing as both VM support and implementation is ready. Error messages are still being polished. <add>Not all features of the EP are complete and will be landing as both VM support <add>and implementation is ready. Error messages are still being polished. <ide> <ide> ## Enabling <ide> <ide> <!-- type=misc --> <ide> <del>The `--experimental-modules` flag can be used to enable features for loading ESM modules. <add>The `--experimental-modules` flag can be used to enable features for loading <add>ESM modules. <ide> <del>Once this has been set, files ending with `.mjs` will be able to be loaded as ES Modules. <add>Once this has been set, files ending with `.mjs` will be able to be loaded <add>as ES Modules. <ide> <ide> ```sh <ide> node --experimental-modules my-app.mjs <ide> node --experimental-modules my-app.mjs <ide> <ide> ### Supported <ide> <del>Only the CLI argument for the main entry point to the program can be an entry point into an ESM graph. In the future `import()` can be used to create entry points into ESM graphs at run time. <add>Only the CLI argument for the main entry point to the program can be an entry <add>point into an ESM graph. In the future `import()` can be used to create entry <add>points into ESM graphs at run time. <ide> <ide> ### Unsupported <ide> <ide> Only the CLI argument for the main entry point to the program can be an entry po <ide> <ide> ### No NODE_PATH <ide> <del>`NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks if this behavior is desired. <add>`NODE_PATH` is not part of resolving `import` specifiers. Please use symlinks <add>if this behavior is desired. <ide> <ide> ### No `require.extensions` <ide> <del>`require.extensions` is not used by `import`. The expectation is that loader hooks can provide this workflow in the future. <add>`require.extensions` is not used by `import`. The expectation is that loader <add>hooks can provide this workflow in the future. <ide> <ide> ### No `require.cache` <ide> <ide> `require.cache` is not used by `import`. It has a separate cache. <ide> <ide> ### URL based paths <ide> <del>ESM are resolved and cached based upon [URL](url.spec.whatwg.org) semantics. This means that files containing special characters such as `#` and `?` need to be escaped. <add>ESM are resolved and cached based upon [URL](https://url.spec.whatwg.org/) <add>semantics. This means that files containing special characters such as `#` and <add>`?` need to be escaped. <ide> <del>Modules will be loaded multiple times if the `import` specifier used to resolve them have a different query or fragment. <add>Modules will be loaded multiple times if the `import` specifier used to resolve <add>them have a different query or fragment. <ide> <ide> ```js <ide> import './foo?query=1'; // loads ./foo with query of "?query=1" <ide> For now, only modules using the `file:` protocol can be loaded. <ide> <ide> All CommonJS, JSON, and C++ modules can be used with `import`. <ide> <del>Modules loaded this way will only be loaded once, even if their query or fragment string differs between `import` statements. <add>Modules loaded this way will only be loaded once, even if their query <add>or fragment string differs between `import` statements. <ide> <del>When loaded via `import` these modules will provide a single `default` export representing the value of `module.exports` at the time they finished evaluating. <add>When loaded via `import` these modules will provide a single `default` export <add>representing the value of `module.exports` at the time they finished evaluating. <ide> <ide> ```js <ide> import fs from 'fs'; <ide> fs.readFile('./foo.txt', (err, body) => { <ide> }); <ide> ``` <ide> <del>[the Node EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md <add>[Node.js EP for ES Modules]: https://github.com/nodejs/node-eps/blob/master/002-es-modules.md
1
Javascript
Javascript
update support comments related to ie
693f1b537b0a19cda8b7e8f5379bffa5351b8a6e
<ide><path>src/ajax.js <ide> jQuery.extend( { <ide> if ( s.crossDomain == null ) { <ide> urlAnchor = document.createElement( "a" ); <ide> <del> // Support: IE8-11+ <del> // IE throws exception if url is malformed, e.g. http://example.com:80x/ <add> // Support: IE <=8 - 11, Edge 12 - 13 <add> // IE throws exception on accessing the href property if url is malformed, <add> // e.g. http://example.com:80x/ <ide> try { <ide> urlAnchor.href = s.url; <ide> <del> // Support: IE8-11+ <add> // Support: IE <=8 - 11 only <ide> // Anchor's host property isn't correctly set when s.url is relative <ide> urlAnchor.href = urlAnchor.href; <ide> s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== <ide><path>src/attributes/support.js <ide> define( [ <ide> // Default value for a checkbox should be "on" <ide> support.checkOn = input.value !== ""; <ide> <del> // Support: IE<=11+ <add> // Support: IE <=11 only <ide> // Must access selectedIndex to make default options select <ide> support.optSelected = opt.selected; <ide> <del> // Support: IE<=11+ <add> // Support: IE <=11 only <ide> // An input loses its value after becoming a radio <ide> input = document.createElement( "input" ); <ide> input.value = "t"; <ide><path>src/attributes/val.js <ide> jQuery.extend( { <ide> return val != null ? <ide> val : <ide> <del> // Support: IE10-11+ <add> // Support: IE <=10 - 11 only <ide> // option.text throws exceptions (#14686, #14858) <ide> // Strip and collapse whitespace <ide> // https://html.spec.whatwg.org/#strip-and-collapse-whitespace <ide><path>src/core.js <ide> jQuery.extend( { <ide> }, <ide> <ide> // Convert dashed to camelCase; used by the css and data modules <del> // Support: IE9-11+ <add> // Support: IE <=9 - 11, Edge 12 - 13 <ide> // Microsoft forgot to hump their vendor prefix (#9572) <ide> camelCase: function( string ) { <ide> return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); <ide><path>src/data.js <ide> jQuery.fn.extend( { <ide> i = attrs.length; <ide> while ( i-- ) { <ide> <del> // Support: IE11+ <add> // Support: IE 11 only <ide> // The attrs elements can be null (#14894) <ide> if ( attrs[ i ] ) { <ide> name = attrs[ i ].name; <ide><path>src/effects.js <ide> function defaultPrefilter( elem, props, opts ) { <ide> // Restrict "overflow" and "display" styles during box animations <ide> if ( isBox && elem.nodeType === 1 ) { <ide> <del> // Support: IE 9 - 11 <add> // Support: IE <=9 - 11, Edge 12 - 13 <ide> // Record all 3 overflow attributes because IE does not infer the shorthand <ide> // from identically-valued overflowX and overflowY <ide> opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; <ide><path>src/manipulation.js <ide> define( [ <ide> var <ide> rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, <ide> <del> // Support: IE 10-11, Edge 10240+ <add> // Support: IE <=10 - 11, Edge 12 - 13 <ide> // In IE/Edge using regex groups here causes severe slowdowns. <ide> // See https://connect.microsoft.com/IE/feedback/details/1736512/ <ide> rnoInnerhtml = /<script|<style|<link/i, <ide><path>src/offset.js <ide> jQuery.fn.extend( { <ide> return; <ide> } <ide> <del> // Support: IE<=11+ <add> // Support: IE <=11 only <ide> // Running getBoundingClientRect on a <ide> // disconnected node in IE throws an error <ide> if ( !elem.getClientRects().length ) {
8
Text
Text
fix unnatural spaces in readme
1930d7364deeb3bc745026f81e0c1688f5c2f250
<ide><path>packages/next/README.md <ide> Every `import` you declare gets bundled and served with each page. That means pa <ide> import cowsay from 'cowsay-browser' <ide> <ide> function CowsayHi() { <del> return ( <del> <pre> <del> {cowsay.say({ text: 'hi there!' })} <del> </pre> <del> ) <add> return <pre>{cowsay.say({ text: 'hi there!' })}</pre> <ide> } <ide> <ide> export default CowsayHi <ide> function IndexPage() { <ide> <div> <ide> <Head> <ide> <title>My page title</title> <del> <meta name="viewport" content="initial-scale=1.0, width=device-width" key="viewport" /> <add> <meta <add> name="viewport" <add> content="initial-scale=1.0, width=device-width" <add> key="viewport" <add> /> <ide> </Head> <ide> <Head> <del> <meta name="viewport" content="initial-scale=1.2, width=device-width" key="viewport" /> <add> <meta <add> name="viewport" <add> content="initial-scale=1.2, width=device-width" <add> key="viewport" <add> /> <ide> </Head> <ide> <p>Hello world!</p> <ide> </div> <ide> class HelloUA extends React.Component { <ide> } <ide> <ide> render() { <del> return ( <del> <div> <del> Hello World {this.props.userAgent} <del> </div> <del> ) <add> return <div>Hello World {this.props.userAgent}</div> <ide> } <ide> } <ide> <ide> export default About <ide> <ide> **Custom routes (using props from URL)** <ide> <del> `<Link>` component has two main props: <add>`<Link>` component has two main props: <ide> <del>* `href`: the path inside `pages` directory + query string. <del>* `as`: the path that will be rendered in the browser URL bar. <add>- `href`: the path inside `pages` directory + query string. <add>- `as`: the path that will be rendered in the browser URL bar. <ide> <ide> Example: <ide> <ide> 1. Consider you have the URL `/post/:slug`. <ide> <ide> 2. You created the `pages/post.js` <ide> <del> ```jsx <del> class Post extends React.Component { <del> static async getInitialProps({query}) { <del> console.log('SLUG', query.slug) <del> return {} <del> } <del> render() { <del> return <h1>My blog post</h1> <del> } <del> } <add> ```jsx <add> class Post extends React.Component { <add> static async getInitialProps({ query }) { <add> console.log('SLUG', query.slug) <add> return {} <add> } <add> render() { <add> return <h1>My blog post</h1> <add> } <add> } <add> <add> export default Post <add> ``` <ide> <del> export default Post <del> ``` <ide> 3. You add the route to `express` (or any other server) on `server.js` file (this is only for SSR). This will route the url `/post/:slug` to `pages/post.js` and provide `slug` as part of query in getInitialProps. <ide> <del> ```jsx <del> server.get("/post/:slug", (req, res) => { <del> return app.render(req, res, "/post", { slug: req.params.slug }) <del> }) <del> ``` <add> ```jsx <add> server.get('/post/:slug', (req, res) => { <add> return app.render(req, res, '/post', { slug: req.params.slug }) <add> }) <add> ``` <add> <ide> 4. For client side routing, use `next/link`: <del> ```jsx <del> <Link href="/post?slug=something" as="/post/something"> <del> ``` <add> ```jsx <add> <Link href="/post?slug=something" as="/post/something"> <add> ``` <ide> <del>__Note: use [`<Link prefetch>`](#prefetching-pages) for maximum performance, to link and prefetch in the background at the same time__ <add>**Note: use [`<Link prefetch>`](#prefetching-pages) for maximum performance, to link and prefetch in the background at the same time** <ide> <ide> Client-side routing behaves exactly like the browser: <ide> <ide> export default Home <ide> <ide> ##### Forcing the Link to expose `href` to its child <ide> <del>If child is an `<a>` tag and doesn't have a href attribute we specify it so that the repetition is not needed by the user. However, sometimes, you’ll want to pass an `<a>` tag inside of a wrapper and the `Link` won’t recognize it as a *hyperlink*, and, consequently, won’t transfer its `href` to the child. In cases like that, you should define a boolean `passHref` property to the `Link`, forcing it to expose its `href` property to the child. <add>If child is an `<a>` tag and doesn't have a href attribute we specify it so that the repetition is not needed by the user. However, sometimes, you’ll want to pass an `<a>` tag inside of a wrapper and the `Link` won’t recognize it as a _hyperlink_, and, consequently, won’t transfer its `href` to the child. In cases like that, you should define a boolean `passHref` property to the `Link`, forcing it to expose its `href` property to the child. <ide> <ide> **Please note**: using a tag other than `a` and failing to pass `passHref` may result in links that appear to navigate correctly, but, when being crawled by search engines, will not be recognized as links (owing to the lack of `href` attribute). This may result in negative effects on your sites SEO. <ide> <ide> import Unexpected_A from 'third-library' <ide> function NavLink({ href, name }) { <ide> return ( <ide> <Link href={href} passHref> <del> <Unexpected_A> <del> {name} <del> </Unexpected_A> <add> <Unexpected_A>{name}</Unexpected_A> <ide> </Link> <ide> ) <ide> } <ide> import Router from 'next/router' <ide> <ide> Router.beforePopState(({ url, as, options }) => { <ide> // I only want to allow these two routes! <del> if (as !== "/" || as !== "/other") { <add> if (as !== '/' || as !== '/other') { <ide> // Have SSR render bad routes as a 404. <ide> window.location.href = as <ide> return false <ide> } <ide> <ide> return true <del>}); <add>}) <ide> ``` <ide> <ide> If the function you pass into `beforePopState` returns `false`, `Router` will not handle `popstate`; <ide> Above `Router` object comes with the following API: <ide> The second `as` parameter for `push` and `replace` is an optional _decoration_ of the URL. Useful if you configured custom routes on the server. <ide> <ide> ##### With URL object <add> <ide> You can use a URL object the same way you use it in a `<Link>` component to `push` and `replace` a URL. <ide> <ide> ```jsx <ide> const handler = () => { <ide> } <ide> <ide> function ReadMore() { <del> return ( <add> return ( <ide> <div> <ide> Click <span onClick={handler}>here</span> to read more <ide> </div> <ide> componentDidUpdate(prevProps) { <ide> > NOTES: <ide> > <ide> > Shallow routing works **only** for same page URL changes. For an example, let's assume we have another page called `about`, and you run this: <add>> <ide> > ```js <ide> > Router.push('/?counter=10', '/about?counter=10', { shallow: true }) <ide> > ``` <add>> <ide> > Since that's a new page, it'll unload the current page, load the new one and call `getInitialProps` even though we asked to do shallow routing. <ide> <ide> #### Using a Higher Order Component <ide> function 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> class MyLink extends React.Component { <ide> const { router } = this.props <ide> <ide> return ( <del> <div> <add> <div> <ide> <a onClick={() => setTimeout(() => router.push('/dynamic'), 100)}> <ide> A route transition will happen after 100ms <ide> </a> <ide> app.prepare().then(() => { <ide> ``` <ide> <ide> The `next` API is as follows: <add> <ide> - `next(opts: object)` <ide> <ide> Supported options: <add> <ide> - `dev` (`bool`) whether to launch Next.js in dev mode - default `false` <ide> - `dir` (`string`) where the Next project is located - default `'.'` <ide> - `quiet` (`bool`) Hide error messages containing server information - default `false` <ide> Supported options: <ide> Then, change your `start` script to `NODE_ENV=production node server.js`. <ide> <ide> #### Disabling file-system routing <add> <ide> By default, `Next` will serve each file in `/pages` under a pathname matching the filename (eg, `/pages/some-file.js` is served at `site.com/some-file`. <ide> <ide> If your project uses custom routing, this behavior may result in the same content being served from multiple paths, which can present problems with SEO and UX. <ide> app.prepare().then(() => { <ide> handleNextRequests(req, res) <ide> }) <ide> <del> server.listen(port, (err) => { <add> server.listen(port, err => { <ide> if (err) { <ide> throw err <ide> } <ide> <ide> console.log(`> Ready on http://localhost:${port}`) <ide> }) <ide> }) <del> <ide> ``` <ide> <ide> ### Dynamic Import <ide> export default Home <ide> ```jsx <ide> // components/hello.js <ide> export function Hello() { <del> return ( <del> <p>Hello!</p> <del> ) <add> return <p>Hello!</p> <ide> } <ide> ``` <ide> <ide> ```jsx <ide> import dynamic from 'next/dynamic' <ide> <del>const DynamicComponent = dynamic(() => import('../components/hello').then((mod) => mod.Hello)) <add>const DynamicComponent = dynamic(() => <add> import('../components/hello').then(mod => mod.Hello) <add>) <ide> <ide> function Home() { <ide> return ( <ide> export default Home <ide> ```jsx <ide> import dynamic from 'next/dynamic' <ide> <del>const DynamicComponentWithCustomLoading = dynamic(() => import('../components/hello2'), { <del> loading: () => <p>...</p> <del>}) <add>const DynamicComponentWithCustomLoading = dynamic( <add> () => import('../components/hello2'), <add> { <add> loading: () => <p>...</p> <add> } <add>) <ide> <ide> function Home() { <ide> return ( <ide> export default Home <ide> ```jsx <ide> import dynamic from 'next/dynamic' <ide> <del>const DynamicComponentWithNoSSR = dynamic(() => import('../components/hello3'), { <del> ssr: false <del>}) <add>const DynamicComponentWithNoSSR = dynamic( <add> () => import('../components/hello3'), <add> { <add> ssr: false <add> } <add>) <ide> <ide> function Home() { <ide> return ( <ide> const HelloBundle = dynamic({ <ide> <ide> return components <ide> }, <del> render: (props, { Hello1, Hello2 }) => <add> render: (props, { Hello1, Hello2 }) => ( <ide> <div> <del> <h1> <del> {props.title} <del> </h1> <add> <h1>{props.title}</h1> <ide> <Hello1 /> <ide> <Hello2 /> <ide> </div> <add> ) <ide> }) <ide> <ide> function DynamicBundle() { <ide> class MyApp extends App { <ide> return { pageProps } <ide> } <ide> <del> render () { <add> render() { <ide> const { Component, pageProps } = this.props <ide> <ide> return ( <ide> export default MyDocument <ide> <ide> All of `<Head />`, `<Main />` and `<NextScript />` are required for page to be properly rendered. <ide> <del>__Note: React-components outside of `<Main />` will not be initialised by the browser. Do _not_ add application logic here. If you need shared components in all your pages (like a menu or a toolbar), take a look at the `App` component instead.__ <add>**Note: React-components outside of `<Main />` will not be initialised by the browser. Do _not_ add application logic here. If you need shared components in all your pages (like a menu or a toolbar), take a look at the `App` component instead.** <ide> <ide> The `ctx` object is equivalent to the one received in all [`getInitialProps`](#fetching-data-and-component-lifecycle) hooks, with one addition: <ide> <ide> - `renderPage` (`Function`) a callback that executes the actual React rendering logic (synchronously). It's useful to decorate this function in order to support server-rendering wrappers like Aphrodite's [`renderStatic`](https://github.com/Khan/aphrodite#server-side-rendering) <ide> <ide> #### Customizing `renderPage` <add> <ide> 🚧 It should be noted that the only reason you should be customizing `renderPage` is for usage with css-in-js libraries <ide> that need to wrap the application to properly work with server-rendering. 🚧 <ide> <ide> class MyDocument extends Document { <ide> static async getInitialProps(ctx) { <ide> const originalRenderPage = ctx.renderPage <ide> <del> ctx.renderPage = () => originalRenderPage({ <del> // useful for wrapping the whole react tree <del> enhanceApp: App => App, <del> // useful for wrapping in a per-page basis <del> enhanceComponent: Component => Component <del> }) <add> ctx.renderPage = () => <add> originalRenderPage({ <add> // useful for wrapping the whole react tree <add> enhanceApp: App => App, <add> // useful for wrapping in a per-page basis <add> enhanceComponent: Component => Component <add> }) <ide> <ide> // Run the parent `getInitialProps` using `ctx` that now includes our custom `renderPage` <ide> const initialProps = await Document.getInitialProps(ctx) <ide> import React from 'react' <ide> <ide> class Error extends React.Component { <ide> static getInitialProps({ res, err }) { <del> const statusCode = res ? res.statusCode : err ? err.statusCode : null; <add> const statusCode = res ? res.statusCode : err ? err.statusCode : null <ide> return { statusCode } <ide> } <ide> <ide> class Page extends React.Component { <ide> return <Error statusCode={this.props.errorCode} /> <ide> } <ide> <del> return ( <del> <div> <del> Next stars: {this.props.stars} <del> </div> <del> ) <add> return <div>Next stars: {this.props.stars}</div> <ide> } <ide> } <ide> <ide> module.exports = { <ide> Or use a function: <ide> <ide> ```js <del>module.exports = (phase, {defaultConfig}) => { <add>module.exports = (phase, { defaultConfig }) => { <ide> return { <ide> /* config options here */ <ide> } <ide> module.exports = (phase, {defaultConfig}) => { <ide> Phases can be imported from `next/constants`: <ide> <ide> ```js <del>const {PHASE_DEVELOPMENT_SERVER} = require('next/constants') <del>module.exports = (phase, {defaultConfig}) => { <del> if(phase === PHASE_DEVELOPMENT_SERVER) { <add>const { PHASE_DEVELOPMENT_SERVER } = require('next/constants') <add>module.exports = (phase, { defaultConfig }) => { <add> if (phase === PHASE_DEVELOPMENT_SERVER) { <ide> return { <ide> /* development only config options here */ <ide> } <ide> module.exports = { <ide> maxInactiveAge: 25 * 1000, <ide> // number of pages that should be kept simultaneously without being disposed <ide> pagesBufferLength: 2 <del> }, <add> } <ide> } <ide> ``` <ide> <ide> To fall back to the default of generating a unique id return `null` from the fun <ide> module.exports = { <ide> generateBuildId: async () => { <ide> // When process.env.YOUR_BUILD_ID is undefined we fall back to the default <del> if(process.env.YOUR_BUILD_ID) { <add> if (process.env.YOUR_BUILD_ID) { <ide> return process.env.YOUR_BUILD_ID <ide> } <ide> <ide> Some commonly asked for features are available as modules: <ide> - [@zeit/next-preact](https://github.com/zeit/next-plugins/tree/master/packages/next-preact) <ide> - [@zeit/next-typescript](https://github.com/zeit/next-plugins/tree/master/packages/next-typescript) <ide> <del>*Warning: The `webpack` function is executed twice, once for the server and once for the client. This allows you to distinguish between client and server configuration using the `isServer` property* <add>_Warning: The `webpack` function is executed twice, once for the server and once for the client. This allows you to distinguish between client and server configuration using the `isServer` property_ <ide> <ide> Multiple configurations can be combined together with function composition. For example: <ide> <ide> ```js <ide> const withTypescript = require('@zeit/next-typescript') <ide> const withSass = require('@zeit/next-sass') <ide> <del>module.exports = withTypescript(withSass({ <del> webpack(config, options) { <del> // Further custom configuration here <del> return config <del> } <del>})) <add>module.exports = withTypescript( <add> withSass({ <add> webpack(config, options) { <add> // Further custom configuration here <add> return config <add> } <add> }) <add>) <ide> ``` <ide> <ide> In order to extend our usage of `webpack`, you can define a function that extends its config via `next.config.js`. <ide> module.exports = { <ide> <ide> In order to extend our usage of `babel`, you can simply define a `.babelrc` file at the root of your app. This file is optional. <ide> <del>If found, we're going to consider it the *source of truth*, therefore it needs to define what next needs as well, which is the `next/babel` preset. <add>If found, we're going to consider it the _source of truth_, therefore it needs to define what next needs as well, which is the `next/babel` preset. <ide> <ide> This is designed so that you are not surprised by modifications we could make to the babel configurations. <ide> <ide> These presets / plugins **should not** be added to your custom `.babelrc`. Inste <ide> ```json <ide> { <ide> "presets": [ <del> ["next/babel", { <del> "preset-env": {}, <del> "transform-runtime": {}, <del> "styled-jsx": {}, <del> "class-properties": {} <del> }] <add> [ <add> "next/babel", <add> { <add> "preset-env": {}, <add> "transform-runtime": {}, <add> "styled-jsx": {}, <add> "class-properties": {} <add> } <add> ] <ide> ], <ide> "plugins": [] <ide> } <ide> export default Index <ide> > :warning: Note that this option is not available when using `target: 'serverless'` <ide> <ide> > :warning: Generally you want to use build-time configuration to provide your configuration. <del>The reason for this is that runtime configuration adds a small rendering / initialization overhead. <add>> The reason for this is that runtime configuration adds a small rendering / initialization overhead. <ide> <ide> The `next/config` module gives your app access to the `publicRuntimeConfig` and `serverRuntimeConfig` stored in your `next.config.js`. <ide> <ide> Anything accessible to both client and server-side code should be under `publicR <ide> ```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> secondSecret: process.env.SECOND_SECRET // Pass through env variables <ide> }, <del> publicRuntimeConfig: { // Will be available on both server and client <del> staticFolder: '/static', <add> publicRuntimeConfig: { <add> // Will be available on both server and client <add> staticFolder: '/static' <ide> } <ide> } <ide> ``` <ide> module.exports = { <ide> // pages/index.js <ide> import getConfig from 'next/config' <ide> // Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else. <del>const {serverRuntimeConfig, publicRuntimeConfig} = getConfig() <add>const { serverRuntimeConfig, publicRuntimeConfig } = getConfig() <ide> <ide> console.log(serverRuntimeConfig.mySecret) // Will only be available on the server side <ide> console.log(publicRuntimeConfig.staticFolder) // Will be available on both server and client <ide> module.exports = { <ide> crossOrigin: 'anonymous' <ide> } <ide> ``` <add> <ide> ## Production deployment <ide> <ide> To deploy, instead of running `next`, you want to build for production usage ahead of time. Therefore, building and starting are separate commands: <ide> To enable **serverless mode** in Next.js, add the `serverless` build `target` in <ide> ```js <ide> // next.config.js <ide> module.exports = { <del> target: "serverless", <del>}; <add> target: 'serverless' <add>} <ide> ``` <ide> <ide> The `serverless` target will output a single lambda per page. This file is completely standalone and doesn't require any dependencies to run: <ide> Next.js provides low-level APIs for serverless deployments as hosting platforms <ide> For example if the platform supports the Node.js [`http.Server`](https://nodejs.org/api/http.html#http_class_http_server) class: <ide> <ide> ```js <del>const http = require("http"); <del>const page = require("./.next/serverless/pages/about.js"); <del>const server = new http.Server((req, res) => page.render(req, res)); <del>server.listen(3000, () => console.log("Listening on http://localhost:3000")); <add>const http = require('http') <add>const page = require('./.next/serverless/pages/about.js') <add>const server = new http.Server((req, res) => page.render(req, res)) <add>server.listen(3000, () => console.log('Listening on http://localhost:3000')) <ide> ``` <ide> <ide> For specific platform examples see [the examples section above](#serverless-deployment). <ide> The page object has 2 values: <ide> - `page` - `String` the page inside the `pages` directory to render <ide> - `query` - `Object` the `query` object passed to `getInitialProps` when pre-rendering. Defaults to `{}` <ide> <del> <ide> ### Usage <ide> <ide> Simply develop your app as you normally do with Next.js. Then run: <ide> This function is asynchronous and gets the default `exportPathMap` as a paramete <ide> ```js <ide> // next.config.js <ide> module.exports = { <del> exportPathMap: async function (defaultPathMap) { <add> exportPathMap: async function(defaultPathMap) { <ide> return { <ide> '/': { page: '/' }, <ide> '/about': { page: '/about' }, <ide> const { promisify } = require('util') <ide> const copyFile = promisify(fs.copyFile) <ide> <ide> module.exports = { <del> exportPathMap: async function (defaultPathMap, {dev, dir, outDir, distDir, buildId}) { <add> exportPathMap: async function( <add> defaultPathMap, <add> { dev, dir, outDir, distDir, buildId } <add> ) { <ide> if (dev) { <ide> return defaultPathMap <ide> } <ide> A zone is a single deployment of a Next.js app. Just like that, you can have mul <ide> <ide> For an example, you can have two zones like this: <ide> <del>* https://docs.my-app.com for serving `/docs/**` <del>* https://ui.my-app.com for serving all other pages <add>- https://docs.my-app.com for serving `/docs/**` <add>- https://ui.my-app.com for serving all other pages <ide> <ide> With multi zones support, you can merge both these apps into a single one. Which allows your customers to browse it using a single URL. But you can develop and deploy both apps independently. <ide> <ide> With multi zones support, you can merge both these apps into a single one. Which <ide> <ide> There are no special zones related APIs. You only need to do following things: <ide> <del>* Make sure to keep only the pages you need in your app. (For an example, https://ui.my-app.com should not contain pages for `/docs/**`) <del>* Make sure your app has an [assetPrefix](https://github.com/zeit/next.js#cdn-support-with-asset-prefix). (You can also define the assetPrefix [dynamically](https://github.com/zeit/next.js#dynamic-assetprefix).) <add>- Make sure to keep only the pages you need in your app. (For an example, https://ui.my-app.com should not contain pages for `/docs/**`) <add>- Make sure your app has an [assetPrefix](https://github.com/zeit/next.js#cdn-support-with-asset-prefix). (You can also define the assetPrefix [dynamically](https://github.com/zeit/next.js#dynamic-assetprefix).) <ide> <ide> ### How to merge them <ide> <ide> You can use [micro proxy](https://github.com/zeit/micro-proxy) as your local pro <ide> ```json <ide> { <ide> "rules": [ <del> {"pathname": "/docs**", "method":["GET", "POST", "OPTIONS"], "dest": "https://docs.my-app.com"}, <del> {"pathname": "/**", "dest": "https://ui.my-app.com"} <add> { <add> "pathname": "/docs**", <add> "method": ["GET", "POST", "OPTIONS"], <add> "dest": "https://docs.my-app.com" <add> }, <add> { "pathname": "/**", "dest": "https://ui.my-app.com" } <ide> ] <ide> } <ide> ``` <ide> For the production deployment, you can use the [path alias](https://zeit.co/docs <ide> <summary>Is this production ready?</summary> <ide> Next.js has been powering https://zeit.co since its inception. <ide> <del> We’re ecstatic about both the developer experience and end-user performance, so we decided to share it with the community. <add>We’re ecstatic about both the developer experience and end-user performance, so we decided to share it with the community. <add> <ide> </details> <ide> <ide> <p></p> <ide> Yes and No. <ide> Yes in that both make your life easier. <ide> <ide> No in that it enforces a _structure_ so that we can do more advanced things like: <add> <ide> - Server side rendering <ide> - Automatic code splitting <ide> <ide> In addition, Next.js provides two built-in features that are critical for every single website: <add> <ide> - Routing with lazy component loading: `<Link>` (by importing `next/link`) <ide> - A way for components to alter `<head>`: `<Head>` (by importing `next/head`) <ide> <ide> If you want to create re-usable React components that you can embed in your Next <ide> <summary>How do I use CSS-in-JS solutions?</summary> <ide> <ide> Next.js bundles [styled-jsx](https://github.com/zeit/styled-jsx) supporting scoped css. However you can use any CSS-in-JS solution in your Next app by just including your favorite library [as mentioned before](#css-in-js) in the document. <add> <ide> </details> <ide> <ide> <p></p> <ide> Next.js bundles [styled-jsx](https://github.com/zeit/styled-jsx) supporting scop <ide> <ide> We track V8. Since V8 has wide support for ES6 and `async` and `await`, we transpile those. Since V8 doesn’t support class decorators, we don’t transpile those. <ide> <del>See the documentation about [customizing the babel config](#customizing-babel-config) and [next/preset](/packages/next/build/babel/preset.js) for more information. <add>See the documentation about [customizing the babel config](#customizing-babel-config) and [next/preset](/packages/next/build/babel/preset.js) for more information. <ide> <ide> </details> <ide> <ide> We tested the flexibility of the routing with some interesting scenarios. For an <ide> We [added](#custom-server-and-routing) the ability to map between an arbitrary URL and any component by supplying a request handler. <ide> <ide> On the client side, we have a parameter call `as` on `<Link>` that _decorates_ the URL differently from the URL it _fetches_. <add> <ide> </details> <ide> <ide> <p></p> <ide> On the client side, we have a parameter call `as` on `<Link>` that _decorates_ t <ide> <summary>How do I fetch data?</summary> <ide> <ide> It’s up to you. `getInitialProps` is an `async` function (or a regular function that returns a `Promise`). It can retrieve data from anywhere. <add> <ide> </details> <ide> <ide> <p></p> <ide> Yes! Here's an example with [Apollo](/examples/with-apollo). <ide> <summary>Can I use it with Redux?</summary> <ide> <ide> Yes! Here's an [example](/examples/with-redux) <add> <ide> </details> <ide> <ide> <p></p> <ide> Yes! Here's an [example](/examples/with-redux) <ide> <summary>Can I use Next with my favorite Javascript library or toolkit?</summary> <ide> <ide> Since our first release we've had **many** example contributions, you can check them out in the [examples](/examples) directory <add> <ide> </details> <ide> <ide> <p></p>
1
Javascript
Javascript
remove unused callback argument
179f6611d59a23df086fc34dc72cc40fc9fdf074
<ide><path>test/sequential/test-http-max-http-headers.js <ide> function test1() { <ide> headers = fillHeaders(headers, currentSize); <ide> <ide> const server = net.createServer((sock) => { <del> sock.once('data', (chunk) => { <add> sock.once('data', () => { <ide> writeHeaders(sock, headers); <ide> sock.resume(); <ide> });
1
Javascript
Javascript
add touch support to force layout
07e64e94fc195ec08ae15d84f8419e4298aaed1c
<ide><path>d3.js <ide> if (!Object.create) Object.create = function(o) { <ide> f.prototype = o; <ide> return new f(); <ide> }; <del>var d3_array = d3_arraySlice; // conversion for NodeLists <add>d3.array = d3_arraySlice; // conversion for NodeLists <ide> <ide> function d3_arrayCopy(psuedoarray) { <ide> var i = -1, n = psuedoarray.length, array = []; <ide> function d3_arraySlice(psuedoarray) { <ide> } <ide> <ide> try { <del> d3_array(document.documentElement.childNodes)[0].nodeType; <add> d3.array(document.documentElement.childNodes)[0].nodeType; <ide> } catch(e) { <del> d3_array = d3_arrayCopy; <add> d3.array = d3_arrayCopy; <ide> } <ide> d3.functor = function(v) { <ide> return typeof v === "function" ? v : function() { return v; }; <ide> function d3_hsl_rgb(h, s, l) { <ide> return d3_rgb(vv(h + 120), vv(h), vv(h - 120)); <ide> } <ide> var d3_select = function(s, n) { return n.querySelector(s); }, <del> d3_selectAll = function(s, n) { return d3_array(n.querySelectorAll(s)); }; <add> d3_selectAll = function(s, n) { return d3.array(n.querySelectorAll(s)); }; <ide> <ide> // Use Sizzle, if available. <ide> if (typeof Sizzle === "function") { <ide> d3.select = function(selector) { <ide> d3.selectAll = function(selector) { <ide> return typeof selector === "string" <ide> ? d3_root.selectAll(selector) <del> : d3_selection([d3_array(selector)]); // assume node[] <add> : d3_selection([d3.array(selector)]); // assume node[] <ide> }; <ide> <ide> function d3_selection(groups) { <ide> function d3_svg_mousePoint(container, e) { <ide> }; <ide> d3.svg.touches = function(container) { <ide> var touches = d3.event.touches; <del> return touches ? d3_array(touches).map(function(touch) { <add> return touches ? d3.array(touches).map(function(touch) { <ide> var point = d3_svg_mousePoint(container, touch); <ide> point.identifier = touch.identifier; <ide> return point; <ide><path>d3.layout.js <ide> d3.layout.force = function() { <ide> this <ide> .on("mouseover.force", d3_layout_forceDragOver) <ide> .on("mouseout.force", d3_layout_forceDragOut) <del> .on("mousedown.force", d3_layout_forceDragDown); <add> .on("mousedown.force", d3_layout_forceDragDown) <add> .on("touchstart.force", d3_layout_forceDragDown); <ide> <ide> d3.select(window) <ide> .on("mousemove.force", dragmove) <add> .on("touchmove.force", dragmove) <ide> .on("mouseup.force", dragup, true) <add> .on("touchend.force", dragup, true) <ide> .on("click.force", d3_layout_forceDragClick, true); <ide> <ide> return force; <ide> }; <ide> <ide> function dragmove() { <del> if (!d3_layout_forceDragNode) return; <del> var parent = d3_layout_forceDragElement.parentNode; <del> <del> // O NOES! The drag element was removed from the DOM. <del> if (!parent) { <del> d3_layout_forceDragNode.fixed = false; <del> d3_layout_forceDragNode = d3_layout_forceDragElement = null; <del> return; <del> } <add> if (!d3.keys(d3_layout_forceDragNodes).length) return; <add> (d3.event.touches <add> ? d3.array(d3.event.touches).map(function(t) { return t.identifier; }) <add> : [null]).forEach(function(id) { <add> var parent = d3_layout_forceDragElements[id].parentNode; <add> <add> // O NOES! The drag element was removed from the DOM. <add> if (!parent) { <add> d3_layout_forceDragNodes[id].fixed = false; <add> delete d3_layout_forceDragNodes[id]; <add> delete d3_layout_forceDragElements[id]; <add> return; <add> } <add> <add> var m = id === null <add> ? d3.svg.mouse(parent) <add> : d3.svg.touches(parent) <add> .filter(function(t) { return t.identifier === id; })[0]; <ide> <del> var m = d3.svg.mouse(parent); <del> d3_layout_forceDragMoved = true; <del> d3_layout_forceDragNode.px = m[0]; <del> d3_layout_forceDragNode.py = m[1]; <add> d3_layout_forceDragMoved[id] = true; <add> d3_layout_forceDragNodes[id].px = m[0]; <add> d3_layout_forceDragNodes[id].py = m[1]; <add> }); <ide> force.resume(); // restart annealing <ide> } <ide> <ide> function dragup() { <del> if (!d3_layout_forceDragNode) return; <del> <del> // If the node was moved, prevent the mouseup from propagating. <del> // Also prevent the subsequent click from propagating (e.g., for anchors). <del> if (d3_layout_forceDragMoved) { <del> d3_layout_forceStopClick = true; <del> d3_layout_forceCancel(); <del> } <del> <del> dragmove(); <del> d3_layout_forceDragNode.fixed = false; <del> d3_layout_forceDragNode = d3_layout_forceDragElement = null; <add> if (!d3.keys(d3_layout_forceDragNodes).length) return; <add> var touches = d3.event.changedTouches || d3.event.touches; <add> (touches ? d3.array(touches).map(function(t) { return t.identifier; }) <add> : [null]).forEach(function(id) { <add> // If the node was moved, prevent the mouseup from propagating. <add> // Also prevent the subsequent click from propagating (e.g., for anchors). <add> if (d3_layout_forceDragMoved[id]) { <add> d3_layout_forceStopClick = true; <add> d3_layout_forceCancel(); <add> } <add> dragmove(); <add> d3_layout_forceDragNodes[id].fixed = false; <add> delete d3_layout_forceDragNodes[id]; <add> delete d3_layout_forceDragElements[id]; <add> }); <ide> } <ide> <ide> return force; <ide> }; <ide> <del>var d3_layout_forceDragNode, <del> d3_layout_forceDragMoved, <del> d3_layout_forceStopClick, <del> d3_layout_forceDragElement; <add>var d3_layout_forceDragNodes = {}, <add> d3_layout_forceDragMoved = {}, <add> d3_layout_forceStopClick = false, <add> d3_layout_forceDragElements = {}; <ide> <ide> function d3_layout_forceDragOver(d) { <ide> d.fixed = true; <ide> } <ide> <ide> function d3_layout_forceDragOut(d) { <del> if (d !== d3_layout_forceDragNode) { <add> if (d !== d3_layout_forceDragNodes[id]) { <ide> d.fixed = false; <ide> } <ide> } <ide> <ide> function d3_layout_forceDragDown(d, i) { <del> (d3_layout_forceDragNode = d).fixed = true; <del> d3_layout_forceDragMoved = false; <del> d3_layout_forceDragElement = this; <add> var id = d3.event.touches ? d3.event.touches[0].identifier : null; <add> d.fixed = true; <add> d3_layout_forceDragNodes[id] = d; <add> if (id in d3_layout_forceDragMoved) delete d3_layout_forceDragMoved[id]; <add> d3_layout_forceDragElements[id] = this; <ide> d3_layout_forceCancel(); <ide> } <ide> <ide><path>d3.layout.min.js <del>(function(){function V(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function U(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function T(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function S(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function R(a,b){return a.depth-b.depth}function Q(a,b){return b.x-a.x}function P(a,b){return a.x-b.x}function O(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=O(c[f],b),a)>0&&(a=d)}return a}function N(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function M(a){return a.children?a.children[0]:a._tree.thread}function L(a,b){return a.parent==b.parent?1:2}function K(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function J(a){var b=a.children;return b?J(b[b.length-1]):a}function I(a){var b=a.children;return b?I(b[0]):a}function H(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function G(a){return 1+d3.max(a,function(a){return a.y})}function F(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function E(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)E(e[f],b,c,d)}}function D(a){var b=a.children;b?(b.forEach(D),a.r=A(b)):a.r=Math.sqrt(a.value)}function C(a){delete a._pack_next,delete a._pack_prev}function B(a){a._pack_next=a._pack_prev=a}function A(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(B),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],F(g,h,i),l(i),x(g,i),g._pack_prev=i,x(i,h),h=g._pack_next;for(var m=3;m<f;m++){F(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(z(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(z(k,i)){p<o&&(n=-1,j=k);break}n==0?(x(g,i),h=i,l(i)):n>0?(y(g,j),h=j,m--):(y(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(C);return s}function z(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function y(a,b){a._pack_next=b,b._pack_prev=a}function x(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function w(a,b){return a.value-b.value}function v(a,b){return b.value-a.value}function u(a){return a.value}function t(a){return a.children}function s(a,b){return a+b[1]}function r(a){return a.reduce(s,0)}function q(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function n(a,b,c){a.y0=b,a.y=c}function m(a){return a.y}function l(a){return a.x}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){(a=c).fixed=!0,b=!1,e=this,j()}function g(b){b!==a&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){!a||(b&&(c=!0,j()),z(),a.fixed=!1,a=e=null)}function z(){if(!!a){var c=e.parentNode;if(!c){a.fixed=!1,a=e=null;return}var f=d3.svg.mouse(c);b=!0,a.px=f[0],a.py=f[1],d.resume()}}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h),d3.select(window).on("mousemove.force",z).on("mouseup.force",A,!0).on("click.force",i,!0);return d};return d};var a,b,c,e;d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=o["default"],c=p.zero,d=n,e=l,f=m;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:o[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:p[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var o={"inside-out":function(a){var b=a.length,c,d,e=a.map(q),f=a.map(r),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},p={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=v,b=t,c=u;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,D(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);E(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(w)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;S(g,function(a){a.children?(a.x=H(a.children),a.y=G(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=I(g),m=J(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=N(g),e=M(e),g&&e)h=M(h),f=N(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(U(V(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!N(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!M(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;T(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];S(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=O(g,Q),l=O(g,P),m=O(g,R),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})() <ide>\ No newline at end of file <add>(function(){function V(a,b,c){return a._tree.ancestor.parent==b.parent?a._tree.ancestor:c}function U(a,b,c){a=a._tree,b=b._tree;var d=c/(b.number-a.number);a.change+=d,b.change-=d,b.shift+=c,b.prelim+=c,b.mod+=c}function T(a){var b=0,c=0,d=a.children,e=d.length,f;while(--e>=0)f=d[e]._tree,f.prelim+=b,f.mod+=b,b+=f.shift+(c+=f.change)}function S(a,b){function c(a,d){var e=a.children;if(e){var f,g=null,h=-1,i=e.length;while(++h<i)f=e[h],c(f,g),g=f}b(a,d)}c(a,null)}function R(a,b){return a.depth-b.depth}function Q(a,b){return b.x-a.x}function P(a,b){return a.x-b.x}function O(a,b){var c=a.children;if(c){var d,e=c.length,f=-1;while(++f<e)b(d=O(c[f],b),a)>0&&(a=d)}return a}function N(a){return a.children?a.children[a.children.length-1]:a._tree.thread}function M(a){return a.children?a.children[0]:a._tree.thread}function L(a,b){return a.parent==b.parent?1:2}function K(a){return d3.merge(a.map(function(a){return(a.children||[]).map(function(b){return{source:a,target:b}})}))}function J(a){var b=a.children;return b?J(b[b.length-1]):a}function I(a){var b=a.children;return b?I(b[0]):a}function H(a){return a.reduce(function(a,b){return a+b.x},0)/a.length}function G(a){return 1+d3.max(a,function(a){return a.y})}function F(a,b,c){var d=b.r+c.r,e=a.r+c.r,f=b.x-a.x,g=b.y-a.y,h=Math.sqrt(f*f+g*g),i=(e*e+h*h-d*d)/(2*e*h),j=Math.acos(i),k=i*e,l=Math.sin(j)*e;f/=h,g/=h,c.x=a.x+k*f+l*g,c.y=a.y+k*g-l*f}function E(a,b,c,d){var e=a.children;a.x=b+=d*a.x,a.y=c+=d*a.y,a.r*=d;if(e){var f=-1,g=e.length;while(++f<g)E(e[f],b,c,d)}}function D(a){var b=a.children;b?(b.forEach(D),a.r=A(b)):a.r=Math.sqrt(a.value)}function C(a){delete a._pack_next,delete a._pack_prev}function B(a){a._pack_next=a._pack_prev=a}function A(a){function l(a){b=Math.min(a.x-a.r,b),c=Math.max(a.x+a.r,c),d=Math.min(a.y-a.r,d),e=Math.max(a.y+a.r,e)}var b=Infinity,c=-Infinity,d=Infinity,e=-Infinity,f=a.length,g,h,i,j,k;a.forEach(B),g=a[0],g.x=-g.r,g.y=0,l(g);if(f>1){h=a[1],h.x=h.r,h.y=0,l(h);if(f>2){i=a[2],F(g,h,i),l(i),x(g,i),g._pack_prev=i,x(i,h),h=g._pack_next;for(var m=3;m<f;m++){F(g,h,i=a[m]);var n=0,o=1,p=1;for(j=h._pack_next;j!==h;j=j._pack_next,o++)if(z(j,i)){n=1;break}if(n==1)for(k=g._pack_prev;k!==j._pack_prev;k=k._pack_prev,p++)if(z(k,i)){p<o&&(n=-1,j=k);break}n==0?(x(g,i),h=i,l(i)):n>0?(y(g,j),h=j,m--):(y(j,h),g=j,m--)}}}var q=(b+c)/2,r=(d+e)/2,s=0;for(var m=0;m<f;m++){var t=a[m];t.x-=q,t.y-=r,s=Math.max(s,t.r+Math.sqrt(t.x*t.x+t.y*t.y))}a.forEach(C);return s}function z(a,b){var c=b.x-a.x,d=b.y-a.y,e=a.r+b.r;return e*e-c*c-d*d>.001}function y(a,b){a._pack_next=b,b._pack_prev=a}function x(a,b){var c=a._pack_next;a._pack_next=b,b._pack_prev=a,b._pack_next=c,c._pack_prev=b}function w(a,b){return a.value-b.value}function v(a,b){return b.value-a.value}function u(a){return a.value}function t(a){return a.children}function s(a,b){return a+b[1]}function r(a){return a.reduce(s,0)}function q(a){var b=1,c=0,d=a[0][1],e,f=a.length;for(;b<f;++b)(e=a[b][1])>d&&(c=b,d=e);return c}function n(a,b,c){a.y0=b,a.y=c}function m(a){return a.y}function l(a){return a.x}function k(a){var b=0,c=0;a.count=0,a.leaf||a.nodes.forEach(function(d){k(d),a.count+=d.count,b+=d.count*d.cx,c+=d.count*d.cy}),a.point&&(a.leaf||(a.point.x+=Math.random()-.5,a.point.y+=Math.random()-.5),a.count++,b+=a.point.x,c+=a.point.y),a.cx=b/a.count,a.cy=c/a.count}function j(){d3.event.stopPropagation(),d3.event.preventDefault()}function i(){c&&(j(),c=!1)}function h(c,d){var f=d3.event.touches?d3.event.touches[0].identifier:null;c.fixed=!0,a[f]=c,f in b&&delete b[f],e[f]=this,j()}function g(b){b!==a[id]&&(b.fixed=!1)}function f(a){a.fixed=!0}d3.layout={},d3.layout.chord=function(){function k(){b.sort(function(a,b){a=Math.min(a.source.value,a.target.value),b=Math.min(b.source.value,b.target.value);return i(a,b)})}function j(){var a={},j=[],l=d3.range(e),m=[],n,o,p,q,r;b=[],c=[],n=0,q=-1;while(++q<e){o=0,r=-1;while(++r<e)o+=d[q][r];j.push(o),m.push(d3.range(e)),n+=o}g&&l.sort(function(a,b){return g(j[a],j[b])}),h&&m.forEach(function(a,b){a.sort(function(a,c){return h(d[b][a],d[b][c])})}),n=(2*Math.PI-f*e)/n,o=0,q=-1;while(++q<e){p=o,r=-1;while(++r<e){var s=l[q],t=m[q][r],u=d[s][t];a[s+"-"+t]={index:s,subindex:t,startAngle:o,endAngle:o+=u*n,value:u}}c.push({index:s,startAngle:p,endAngle:o,value:(o-p)/n}),o+=f}q=-1;while(++q<e){r=q-1;while(++r<e){var v=a[q+"-"+r],w=a[r+"-"+q];(v.value||w.value)&&b.push({source:v,target:w})}}i&&k()}var a={},b,c,d,e,f=0,g,h,i;a.matrix=function(f){if(!arguments.length)return d;e=(d=f)&&d.length,b=c=null;return a},a.padding=function(d){if(!arguments.length)return f;f=d,b=c=null;return a},a.sortGroups=function(d){if(!arguments.length)return g;g=d,b=c=null;return a},a.sortSubgroups=function(c){if(!arguments.length)return h;h=c,b=null;return a},a.sortChords=function(c){if(!arguments.length)return i;i=c,b&&k();return a},a.chords=function(){b||j();return b},a.groups=function(){c||j();return c};return a},d3.layout.force=function(){function A(){if(!!d3.keys(a).length){var d=d3.event.changedTouches||d3.event.touches;(d?d3.array(d).map(function(a){return a.identifier}):[null]).forEach(function(d){b[d]&&(c=!0,j()),z(),a[d].fixed=!1,delete a[d],delete e[d]})}}function z(){!d3.keys(a).length||((d3.event.touches?d3.array(d3.event.touches).map(function(a){return a.identifier}):[null]).forEach(function(c){var d=e[c].parentNode;if(!d)a[c].fixed=!1,delete a[c],delete e[c];else{var f=c===null?d3.svg.mouse(d):d3.svg.touches(d).filter(function(a){return a.identifier===c})[0];b[c]=!0,a[c].px=f[0],a[c].py=f[1]}}),d.resume())}function y(){var a=u.length,b=v.length,c=d3.geom.quadtree(u),d,e,f,g,h,i,j;for(d=0;d<b;++d){e=v[d],f=e.source,g=e.target,i=g.x-f.x,j=g.y-f.y;if(h=i*i+j*j)h=n*((h=Math.sqrt(h))-p)/h,i*=h,j*=h,g.x-=i,g.y-=j,f.x+=i,f.y+=j}var s=n*r;i=m[0]/2,j=m[1]/2,d=-1;while(++d<a)e=u[d],e.x+=(i-e.x)*s,e.y+=(j-e.y)*s;k(c);var t=n*q;d=-1;while(++d<a)c.visit(x(u[d],t));d=-1;while(++d<a)e=u[d],e.fixed?(e.x=e.px,e.y=e.py):(e.x-=(e.px-(e.px=e.x))*o,e.y-=(e.py-(e.py=e.y))*o);l.tick.dispatch({type:"tick",alpha:n});return(n*=.99)<.005}function x(a,b){return function(c,d,e,f,g){if(c.point!==a){var h=c.cx-a.x,i=c.cy-a.y,j=1/Math.sqrt(h*h+i*i);if((f-d)*j<s){var k=b*c.count*j*j;a.x+=h*k,a.y+=i*k;return!0}if(c.point&&isFinite(j)){var k=b*j*j;a.x+=h*k,a.y+=i*k}}}}var d={},l=d3.dispatch("tick"),m=[1,1],n,o=.9,p=20,q=-30,r=.1,s=.8,t,u,v,w;d.on=function(a,b){l[a].add(b);return d},d.nodes=function(a){if(!arguments.length)return u;u=a;return d},d.links=function(a){if(!arguments.length)return v;v=a;return d},d.size=function(a){if(!arguments.length)return m;m=a;return d},d.distance=function(a){if(!arguments.length)return p;p=a;return d},d.drag=function(a){if(!arguments.length)return o;o=a;return d},d.charge=function(a){if(!arguments.length)return q;q=a;return d},d.gravity=function(a){if(!arguments.length)return r;r=a;return d},d.theta=function(a){if(!arguments.length)return s;s=a;return d},d.start=function(){function k(){if(!h){h=[];for(b=0;b<c;++b)h[b]=[];for(b=0;b<e;++b){var d=v[b];h[d.source.index].push(d.target),h[d.target.index].push(d.source)}}return h[a]}function j(b,c){var d=k(a),e=-1,f=d.length,g;while(++e<f)if(!isNaN(g=d[e][b]))return g;return Math.random()*c}var a,b,c=u.length,e=v.length,f=m[0],g=m[1],h,i;for(a=0;a<c;++a)(i=u[a]).index=a;for(a=0;a<e;++a)i=v[a],typeof i.source=="number"&&(i.source=u[i.source]),typeof i.target=="number"&&(i.target=u[i.target]);for(a=0;a<c;++a)i=u[a],isNaN(i.x)&&(i.x=j("x",f)),isNaN(i.y)&&(i.y=j("y",g)),isNaN(i.px)&&(i.px=i.x),isNaN(i.py)&&(i.py=i.y);return d.resume()},d.resume=function(){n=.1,d3.timer(y);return d},d.stop=function(){n=0;return d},d.drag=function(){this.on("mouseover.force",f).on("mouseout.force",g).on("mousedown.force",h).on("touchstart.force",h),d3.select(window).on("mousemove.force",z).on("touchmove.force",z).on("mouseup.force",A,!0).on("touchend.force",A,!0).on("click.force",i,!0);return d};return d};var a={},b={},c=!1,e={};d3.layout.partition=function(){function e(e,f){var g=a.call(this,e,f);c(g[0],0,b[0],b[1]/d(g[0]));return g}function d(a){var b=a.children,c=0;if(b){var e=-1,f=b.length;while(++e<f)c=Math.max(c,d(b[e]))}return 1+c}function c(a,b,d,e){var f=a.children;a.x=b,a.y=a.depth*e,a.dx=d,a.dy=e;if(f){var g=-1,h=f.length,i,j;d/=a.value;while(++g<h)c(i=f[g],b,j=i.value*d,e),b+=j}}var a=d3.layout.hierarchy(),b=[1,1];e.sort=d3.rebind(e,a.sort),e.children=d3.rebind(e,a.children),e.value=d3.rebind(e,a.value),e.size=function(a){if(!arguments.length)return b;b=a;return e};return e},d3.layout.pie=function(){function f(f,g){var h=+(typeof c=="function"?c.apply(this,arguments):c),i=(typeof e=="function"?e.apply(this,arguments):e)-c,j=d3.range(f.length);b!=null&&j.sort(function(a,c){return b(f[a],f[c])});var k=f.map(a);i/=k.reduce(function(a,b){return a+b},0);var l=j.map(function(a){return{value:d=k[a],startAngle:h,endAngle:h+=d*i}});return f.map(function(a,b){return l[j[b]]})}var a=Number,b=null,c=0,e=2*Math.PI;f.value=function(b){if(!arguments.length)return a;a=b;return f},f.sort=function(a){if(!arguments.length)return b;b=a;return f},f.startAngle=function(a){if(!arguments.length)return c;c=a;return f},f.endAngle=function(a){if(!arguments.length)return e;e=a;return f};return f},d3.layout.stack=function(){function g(h,i){var j=h.map(function(b,c){return a.call(g,b,c)}),k=j.map(function(a,b){return a.map(function(a,b){return[e.call(g,a,b),f.call(g,a,b)]})}),l=b.call(g,k,i);j=d3.permute(j,l),k=d3.permute(k,l);var m=c.call(g,k,i),n=j.length,o=j[0].length,p,q,r;for(q=0;q<o;++q){d.call(g,j[0][q],r=m[q],k[0][q][1]);for(p=1;p<n;++p)d.call(g,j[p][q],r+=k[p-1][q][1],k[p][q][1])}return h}var a=Object,b=o["default"],c=p.zero,d=n,e=l,f=m;g.values=function(b){if(!arguments.length)return a;a=b;return g},g.order=function(a){if(!arguments.length)return b;b=typeof a=="function"?a:o[a];return g},g.offset=function(a){if(!arguments.length)return c;c=typeof a=="function"?a:p[a];return g},g.x=function(a){if(!arguments.length)return e;e=a;return g},g.y=function(a){if(!arguments.length)return f;f=a;return g},g.out=function(a){if(!arguments.length)return d;d=a;return g};return g};var o={"inside-out":function(a){var b=a.length,c,d,e=a.map(q),f=a.map(r),g=d3.range(b).sort(function(a,b){return e[a]-e[b]}),h=0,i=0,j=[],k=[];for(c=0;c<b;++c)d=g[c],h<i?(h+=f[d],j.push(d)):(i+=f[d],k.push(d));return k.reverse().concat(j)},reverse:function(a){return d3.range(a.length).reverse()},"default":function(a){return d3.range(a.length)}},p={silhouette:function(a){var b=a.length,c=a[0].length,d=[],e=0,f,g,h,i=[];for(g=0;g<c;++g){for(f=0,h=0;f<b;f++)h+=a[f][g][1];h>e&&(e=h),d.push(h)}for(g=0;g<c;++g)i[g]=(e-d[g])/2;return i},wiggle:function(a){var b=a.length,c=a[0],d=c.length,e=0,f,g,h,i,j,k,l,m,n,o=[];o[0]=m=n=0;for(g=1;g<d;++g){for(f=0,i=0;f<b;++f)i+=a[f][g][1];for(f=0,j=0,l=c[g][0]-c[g-1][0];f<b;++f){for(h=0,k=(a[f][g][1]-a[f][g-1][1])/(2*l);h<f;++h)k+=(a[h][g][1]-a[h][g-1][1])/l;j+=k*a[f][g][1]}o[g]=m-=i?j/i*l:0,m<n&&(n=m)}for(g=0;g<d;++g)o[g]-=n;return o},expand:function(a){var b=a.length,c=a[0].length,d=1/b,e,f,g,h=[];for(f=0;f<c;++f){for(e=0,g=0;e<b;e++)g+=a[e][f][1];if(g)for(e=0;e<b;e++)a[e][f][1]/=g;else for(e=0;e<b;e++)a[e][f][1]=d}for(f=0;f<c;++f)h[f]=0;return h},zero:function(a){var b=-1,c=a[0].length,d=[];while(++b<c)d[b]=0;return d}};d3.layout.hierarchy=function(){function g(a){var b=[];e(a,0,b);return b}function f(a,b){var d=a.children,e=0;if(d){var h=-1,i=d.length,j=b+1;while(++h<i)e+=f(d[h],j)}else c&&(e=c.call(g,a.data,b));c&&(a.value=e);return e}function e(f,h,i){var j=b.call(g,f,h),k={depth:h,data:f};i.push(k);if(j){var l=-1,m=j.length,n=k.children=[],o=0,p=h+1;while(++l<m)d=e(j[l],p,i),d.parent=k,n.push(d),o+=d.value;a&&n.sort(a),c&&(k.value=o)}else c&&(k.value=c.call(g,f,h));return k}var a=v,b=t,c=u;g.sort=function(b){if(!arguments.length)return a;a=b;return g},g.children=function(a){if(!arguments.length)return b;b=a;return g},g.value=function(a){if(!arguments.length)return c;c=a;return g},g.revalue=function(a){f(a,0);return a};return g},d3.layout.pack=function(){function c(c,d){var e=a.call(this,c,d),f=e[0];f.x=0,f.y=0,D(f);var g=b[0],h=b[1],i=1/Math.max(2*f.r/g,2*f.r/h);E(f,g/2,h/2,i);return e}var a=d3.layout.hierarchy(),b=[1,1];c.sort=d3.rebind(c,a.sort),c.children=d3.rebind(c,a.children),c.value=d3.rebind(c,a.value),c.size=function(a){if(!arguments.length)return b;b=a;return c};return c.sort(w)},d3.layout.cluster=function(){function d(d,e){var f=a.call(this,d,e),g=f[0],h,i=0,j,k;S(g,function(a){a.children?(a.x=H(a.children),a.y=G(a.children)):(a.x=h?i+=b(a,h):0,a.y=0,h=a)});var l=I(g),m=J(g),n=l.x-b(l,m)/2,o=m.x+b(m,l)/2;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=(1-a.y/g.y)*c[1]});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.tree=function(){function d(d,e){function j(a,c,d){if(c){var e=a,f=a,g=c,h=a.parent.children[0],i=e._tree.mod,j=f._tree.mod,k=g._tree.mod,l=h._tree.mod,m;while(g=N(g),e=M(e),g&&e)h=M(h),f=N(f),f._tree.ancestor=a,m=g._tree.prelim+k-e._tree.prelim-i+b(g,e),m>0&&(U(V(g,a,d),a,m),i+=m,j+=m),k+=g._tree.mod,i+=e._tree.mod,l+=h._tree.mod,j+=f._tree.mod;g&&!N(f)&&(f._tree.thread=g,f._tree.mod+=k-j),e&&!M(h)&&(h._tree.thread=e,h._tree.mod+=i-l,d=a)}return d}function i(a,b){a.x=a._tree.prelim+b;var c=a.children;if(c){var d=-1,e=c.length;b+=a._tree.mod;while(++d<e)i(c[d],b)}}function h(a,c){var d=a.children,e=a._tree;if(d){var f=d.length,g=d[0],i,k=g,l,m=-1;while(++m<f)l=d[m],h(l,i),k=j(l,i,k),i=l;T(a);var n=.5*(g._tree.prelim+l._tree.prelim);c?(e.prelim=c._tree.prelim+b(a,c),e.mod=e.prelim-n):e.prelim=n}else c&&(e.prelim=c._tree.prelim+b(a,c))}var f=a.call(this,d,e),g=f[0];S(g,function(a,b){a._tree={ancestor:a,prelim:0,mod:0,change:0,shift:0,number:b?b._tree.number+1:0}}),h(g),i(g,-g._tree.prelim);var k=O(g,Q),l=O(g,P),m=O(g,R),n=k.x-b(k,l)/2,o=l.x+b(l,k)/2,p=m.depth;S(g,function(a){a.x=(a.x-n)/(o-n)*c[0],a.y=a.depth/p*c[1],delete a._tree});return f}var a=d3.layout.hierarchy().sort(null).value(null),b=L,c=[1,1];d.sort=d3.rebind(d,a.sort),d.children=d3.rebind(d,a.children),d.links=K,d.separation=function(a){if(!arguments.length)return b;b=a;return d},d.size=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.layout.treemap=function(){function k(b){var i=e||a(b),j=i[0];j.x=0,j.y=0,j.dx=c[0],j.dy=c[1],e&&a.revalue(j),f(j,c[0]*c[1]/j.value),(e?h:g)(j),d&&(e=i);return i}function j(a,c,d,e){var f=-1,g=a.length,h=d.x,i=d.y,j=c?b(a.area/c):0,k;if(c==d.dx){if(e||j>d.dy)j=d.dy;while(++f<g)k=a[f],k.x=h,k.y=i,k.dy=j,h+=k.dx=b(k.area/j);k.z=!0,k.dx+=d.x+d.dx-h,d.y+=j,d.dy-=j}else{if(e||j>d.dx)j=d.dx;while(++f<g)k=a[f],k.x=h,k.y=i,k.dx=j,i+=k.dy=b(k.area/j);k.z=!1,k.dy+=d.y+d.dy-i,d.x+=j,d.dx-=j}}function i(a,b){var c=a.area,d,e=0,f=Infinity,g=-1,h=a.length;while(++g<h)d=a[g].area,d<f&&(f=d),d>e&&(e=d);c*=c,b*=b;return Math.max(b*e/c,c/(b*f))}function h(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=a.children.slice(),d,e=[];e.area=0;while(d=c.pop())e.push(d),e.area+=d.area,d.z!=null&&(j(e,d.z?b.dx:b.dy,b,!c.length),e.length=e.area=0);a.children.forEach(h)}}function g(a){if(!!a.children){var b={x:a.x,y:a.y,dx:a.dx,dy:a.dy},c=[],d=a.children.slice(),e,f=Infinity,h,k=Math.min(b.dx,b.dy),l;c.area=0;while((l=d.length)>0)c.push(e=d[l-1]),c.area+=e.area,(h=i(c,k))<=f?(d.pop(),f=h):(c.area-=c.pop().area,j(c,k,b,!1),k=Math.min(b.dx,b.dy),c.length=c.area=0,f=Infinity);c.length&&(j(c,k,b,!0),c.length=c.area=0),a.children.forEach(g)}}function f(a,b){var c=a.children;a.area=a.value*b;if(c){var d=-1,e=c.length;while(++d<e)f(c[d],b)}}var a=d3.layout.hierarchy(),b=Math.round,c=[1,1],d=!1,e;k.sort=d3.rebind(k,a.sort),k.children=d3.rebind(k,a.children),k.value=d3.rebind(k,a.value),k.size=function(a){if(!arguments.length)return c;c=a;return k},k.round=function(a){if(!arguments.length)return b!=Number;b=a?Math.round:Number;return k},k.sticky=function(a){if(!arguments.length)return d;d=a,e=null;return k};return k}})() <ide>\ No newline at end of file <ide><path>d3.min.js <del>(function(){function cb(){return"circle"}function ca(){return 64}function b_(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(b$<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();b$=!e.f&&!e.e,d.remove()}b$?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]}function bZ(a){return[a.x,a.y]}function bY(a){return a.endAngle}function bX(a){return a.startAngle}function bW(a){return a.radius}function bV(a){return a.target}function bU(a){return a.source}function bT(){return 0}function bS(a){return a.length<3?bz(a):a[0]+bF(a,bR(a))}function bR(a){var b=[],c,d,e,f,g=bQ(a),h=-1,i=a.length-1;while(++h<i)c=bP(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function bQ(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=bP(e,f);while(++b<c)d[b]=g+(g=bP(e=f,f=a[b+1]));d[b]=g;return d}function bP(a,b){return(b[1]-a[1])/(b[0]-a[0])}function bO(a,b,c){a.push("C",bK(bL,b),",",bK(bL,c),",",bK(bM,b),",",bK(bM,c),",",bK(bN,b),",",bK(bN,c))}function bK(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bJ(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bK(bN,g),",",bK(bN,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bO(b,g,h);return b.join("")}function bI(a){if(a.length<4)return bz(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(bK(bN,f)+","+bK(bN,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),bO(b,f,g);return b.join("")}function bH(a){if(a.length<3)return bz(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bO(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bO(b,h,i);return b.join("")}function bG(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bF(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return bz(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bE(a,b,c){return a.length<3?bz(a):a[0]+bF(a,bG(a,b))}function bD(a,b){return a.length<3?bz(a):a[0]+bF((a.push(a[0]),a),bG([a[a.length-2]].concat(a,[a[1]]),b))}function bC(a,b){return a.length<4?bz(a):a[1]+bF(a.slice(1,a.length-1),bG(a,b))}function bB(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bA(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function bz(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bx(a){return a[1]}function bw(a){return a[0]}function bv(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bu(a){return a.endAngle}function bt(a){return a.startAngle}function bs(a){return a.outerRadius}function br(a){return a.innerRadius}function bk(a){return function(b){return-Math.pow(-b,a)}}function bj(a){return function(b){return Math.pow(b,a)}}function bi(a){return-Math.log(-a)/Math.LN10}function bh(a){return Math.log(a)/Math.LN10}function bg(a,b,c,d){function i(b){var c=1,d=a.length-2;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return c-1}var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(a){var b=i(a);return f[b](e[b](a))}}function bf(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bd(){var a=null,b=$,c=Infinity;while(b)b.flush?b=a?a.next=b.next:$=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bc(){var a,b=Date.now(),c=$;while(c)a=b-c.then,a>c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bd()-b;d>24?(isFinite(d)&&(clearTimeout(ba),ba=setTimeout(bc,d)),_=0):(_=1,be(bc))}function bb(a,b){var c=Date.now(),d=!1,e,f=$;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||($={callback:a,then:c,delay:b,next:$}),_||(ba=clearTimeout(ba),_=1,be(bc))}}function Z(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function Y(a){function n(b){var g=!0,l=-1;a.each(function(){if(i[++l]!==2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){g=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!==c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a===1){i[l]=2;if(n.active===c){var r=n.owner;r===c&&(delete this.__transition__,f&&this.parentNode.removeChild(this)),X=c,h.end.dispatch.apply(this,arguments),X=0,n.owner=r}}}});return g}var b={},c=X||++W,d={},e=[],f=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),bb(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,Z(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,Z(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=Y(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=Y(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){f=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=g;return b.delay(0).duration(250)}function V(a){return{__data__:a}}function U(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function T(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return S(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function S(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return S(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return S(c)}a.select=function(a){return b(function(b){return P(a,b)})},a.selectAll=function(a){return c(function(b){return Q(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return S(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=V(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=V(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=S(e);k.enter=function(){return T(d)},k.exit=function(){return S(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){if(a=this.classList)return a.remove(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;d=f(d.replace(e," ")),c?a.baseVal=d:this.className=d}function g(){if(a=this.classList)return a.add(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;e.lastIndex=0,e.test(d)||(d=f(d+" "+b),c?a.baseVal=d:this.className=d)}var e=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){if(a=this.classList)return a.contains(b);var a=this.className;e.lastIndex=0;return e.test(a.baseVal!=null?a.baseVal:a)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),P(c,b))}function d(b){return b.insertBefore(document.createElement(a),P(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=U.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e===-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function h(a){var d=d3.event;d3.event=a;try{c.call(this,e.__data__,b)}finally{d3.event=d}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=h,d);var e=this})},a.transition=function(){return Y(a)},a.call=g;return a}function O(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return E(g(a+120),g(a),g(a-120))}function N(a,b,c){this.h=a,this.s=b,this.l=c}function M(a,b,c){return new N(a,b,c)}function J(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function I(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return M(g,h,i)}function H(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(J(h[0]),J(h[1]),J(h[2]))}}if(i=K[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function G(a){return a<16?"0"+a.toString(16):a.toString(16)}function F(a,b,c){this.r=a,this.g=b,this.b=c}function E(a,b,c){return new F(a,b,c)}function D(a,b){b=1/(b-(a=+a));return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function C(a,b){b=1/(b-(a=+a));return function(c){return(c-a)*b}}function B(a){return a in A||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function y(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function x(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function w(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function v(a){return 1-Math.sqrt(1-a*a)}function u(a){return a?Math.pow(2,10*(a-1))-.001:0}function t(a){return 1-Math.cos(a*Math.PI/2)}function s(a){return function(b){return Math.pow(b,a)}}function r(a){return a}function q(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function p(a){return function(b){return 1-a(1-b)}}function k(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function i(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function g(a){a.apply(this,(arguments[0]=this,arguments));return this}function f(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function e(a){return a==null}function c(a){return Array.prototype.slice.call(a)}function b(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.16.0"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b});var a=c;try{a(document.documentElement.childNodes)[0].nodeType}catch(d){a=b}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.permute=function(a,b){var c=[],d=-1,e=b.length;while(++d<e)c[d]=a[b[d]];return c},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],d=[],f,g=-1,h=a.length;arguments.length<2&&(b=e);while(++g<h)b.call(d,f=a[g],g)?d=[]:(d.length||c.push(d),d.push(f));return c},d3.range=function(a,b,c){arguments.length===1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(h,"\\$&")};var h=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=i(c);return b},d3.format=function(a){var b=j.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],i=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),i==="d"&&(h="0");return function(a){var b=+a,j=b<0&&(b=-b)?"−":d;if(i==="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+j.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=k(a)),a=j+a}else{g&&(a=k(a)),a=j+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var j=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,l=s(2),m=s(3),n={linear:function(){return r},poly:s,quad:function(){return l},cubic:function(){return m},sin:function(){return t},exp:function(){return u},circle:function(){return v},elastic:w,back:x,bounce:function(){return y}},o={"in":function(a){return a},out:p,"in-out":q,"out-in":function(a){return q(p(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return o[d](n[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in K||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;z.lastIndex=0;for(d=0;c=z.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=z.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=z.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length===1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return O(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=B(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var z=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,A={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length===1?H(""+a,E,O):E(~~a,~~b,~~c)},F.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return E(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return E(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},F.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return E(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},F.prototype.hsl=function(){return I(this.r,this.g,this.b)},F.prototype.toString=function(){return"#"+G(this.r)+G(this.g)+G(this.b)};var K={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var L in K)K[L]=H(K[L],E,O);d3.hsl=function(a,b,c){return arguments.length===1?H(""+a,I,M):M(+a,+b,+c)},N.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,this.l/a)},N.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return M(this.h,this.s,a*this.l)},N.prototype.rgb=function(){return O(this.h,this.s,this.l)},N.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var P=function(a,b){return b.querySelector(a)},Q=function(b,c){return a(c.querySelectorAll(b))};typeof Sizzle=="function"&&(P=function(a,b){return Sizzle(a,b)[0]},Q=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var R=S([[document]]);R[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?R.select(a):S([[a]])},d3.selectAll=function(b){return typeof b=="string"?R.selectAll(b):S([a(b)])},d3.transition=R.transition;var W=0,X=0,$=null,_,ba;d3.timer=function(a){bb(a,0)},d3.timer.flush=function(){var a,b=Date.now(),c=$;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bd()};var be=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function i(b){var c=d3.min(a),d=d3.max(a),e=d-c,f=Math.pow(10,Math.floor(Math.log(e/b)/Math.LN10)),g=b/(e/f);g<=.15?f*=10:g<=.35?f*=5:g<=.75&&(f*=2);return{start:Math.ceil(c/f)*f,stop:Math.floor(d/f)*f+f*.5,step:f}}function h(a){return e(a)}function g(){var g=a.length==2?bf:bg,i=d?D:C;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var a=[0,1],b=[0,1],c=d3.interpolate,d=!1,e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(a){var b=i(a);return d3.range(b.start,b.stop,b.step)},h.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(i(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return g()},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bh,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?bi:bh,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bi){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bh.pow=function(a){return Math.pow(10,a)},bi.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bk:bj;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bl)},d3.scale.category20=function(){return d3.scale.ordinal().range(bm)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bn)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bo)};var bl=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bm=["#1f77b4","#aec7e8","#ff7f0e" <del>,"#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bn=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bo=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bp,h=d.apply(this,arguments)+bp,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bq?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=br,b=bs,c=bt,d=bu;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bp;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bp=-Math.PI/2,bq=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bv(this,c,a,b),e)}var a=bw,b=bx,c="linear",d=by[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=by[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var by={linear:bz,"step-before":bA,"step-after":bB,basis:bH,"basis-open":bI,"basis-closed":bJ,cardinal:bE,"cardinal-open":bC,"cardinal-closed":bD,monotone:bS},bL=[0,2/3,1/3,0],bM=[0,1/3,2/3,0],bN=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bv(this,d,a,c),f)+"L"+e(bv(this,d,a,b).reverse(),f)+"Z"}var a=bw,b=bT,c=bx,d="linear",e=by[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=by[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bp,k=e.call(a,h,g)+bp;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bU,b=bV,c=bW,d=bt,e=bu;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bU,b=bV,c=bZ;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){return b_(a,d3.event)};var b$=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(b){var c=d3.event.touches;return c?a(c).map(function(a){var c=b_(b,a);c.identifier=a.identifier;return c}):[]},d3.svg.symbol=function(){function c(c,d){return(cc[a.call(this,c,d)]||cc.circle)(b.call(this,c,d))}var a=cb,b=ca;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var cc={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*ce)),c=b*ce;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cd),c=b*cd/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cd),c=b*cd/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},cd=Math.sqrt(3),ce=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <add>(function(){function ca(){return"circle"}function b_(){return 64}function b$(a,b){var c=(a.ownerSVGElement||a).createSVGPoint();if(bZ<0&&(window.scrollX||window.scrollY)){var d=d3.select(document.body).append("svg:svg").style("position","absolute").style("top",0).style("left",0),e=d[0][0].getScreenCTM();bZ=!e.f&&!e.e,d.remove()}bZ?(c.x=b.pageX,c.y=b.pageY):(c.x=b.clientX,c.y=b.clientY),c=c.matrixTransform(a.getScreenCTM().inverse());return[c.x,c.y]}function bY(a){return[a.x,a.y]}function bX(a){return a.endAngle}function bW(a){return a.startAngle}function bV(a){return a.radius}function bU(a){return a.target}function bT(a){return a.source}function bS(){return 0}function bR(a){return a.length<3?by(a):a[0]+bE(a,bQ(a))}function bQ(a){var b=[],c,d,e,f,g=bP(a),h=-1,i=a.length-1;while(++h<i)c=bO(a[h],a[h+1]),Math.abs(c)<1e-6?g[h]=g[h+1]=0:(d=g[h]/c,e=g[h+1]/c,f=d*d+e*e,f>9&&(f=c*3/Math.sqrt(f),g[h]=f*d,g[h+1]=f*e));h=-1;while(++h<=i)f=(a[Math.min(i,h+1)][0]-a[Math.max(0,h-1)][0])/(6*(1+g[h]*g[h])),b.push([f||0,g[h]*f||0]);return b}function bP(a){var b=0,c=a.length-1,d=[],e=a[0],f=a[1],g=d[0]=bO(e,f);while(++b<c)d[b]=g+(g=bO(e=f,f=a[b+1]));d[b]=g;return d}function bO(a,b){return(b[1]-a[1])/(b[0]-a[0])}function bN(a,b,c){a.push("C",bJ(bK,b),",",bJ(bK,c),",",bJ(bL,b),",",bJ(bL,c),",",bJ(bM,b),",",bJ(bM,c))}function bJ(a,b){return a[0]*b[0]+a[1]*b[1]+a[2]*b[2]+a[3]*b[3]}function bI(a){var b,c=-1,d=a.length,e=d+4,f,g=[],h=[];while(++c<4)f=a[c%d],g.push(f[0]),h.push(f[1]);b=[bJ(bM,g),",",bJ(bM,h)],--c;while(++c<e)f=a[c%d],g.shift(),g.push(f[0]),h.shift(),h.push(f[1]),bN(b,g,h);return b.join("")}function bH(a){if(a.length<4)return by(a);var b=[],c=-1,d=a.length,e,f=[0],g=[0];while(++c<3)e=a[c],f.push(e[0]),g.push(e[1]);b.push(bJ(bM,f)+","+bJ(bM,g)),--c;while(++c<d)e=a[c],f.shift(),f.push(e[0]),g.shift(),g.push(e[1]),bN(b,f,g);return b.join("")}function bG(a){if(a.length<3)return by(a);var b=[],c=1,d=a.length,e=a[0],f=e[0],g=e[1],h=[f,f,f,(e=a[1])[0]],i=[g,g,g,e[1]];b.push(f,",",g),bN(b,h,i);while(++c<d)e=a[c],h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bN(b,h,i);c=-1;while(++c<2)h.shift(),h.push(e[0]),i.shift(),i.push(e[1]),bN(b,h,i);return b.join("")}function bF(a,b){var c=[],d=(1-b)/2,e,f=a[0],g=a[1],h=1,i=a.length;while(++h<i)e=f,f=g,g=a[h],c.push([d*(g[0]-e[0]),d*(g[1]-e[1])]);return c}function bE(a,b){if(b.length<1||a.length!=b.length&&a.length!=b.length+2)return by(a);var c=a.length!=b.length,d="",e=a[0],f=a[1],g=b[0],h=g,i=1;c&&(d+="Q"+(f[0]-g[0]*2/3)+","+(f[1]-g[1]*2/3)+","+f[0]+","+f[1],e=a[1],i=2);if(b.length>1){h=b[1],f=a[i],i++,d+="C"+(e[0]+g[0])+","+(e[1]+g[1])+","+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1];for(var j=2;j<b.length;j++,i++)f=a[i],h=b[j],d+="S"+(f[0]-h[0])+","+(f[1]-h[1])+","+f[0]+","+f[1]}if(c){var k=a[i];d+="Q"+(f[0]+h[0]*2/3)+","+(f[1]+h[1]*2/3)+","+k[0]+","+k[1]}return d}function bD(a,b,c){return a.length<3?by(a):a[0]+bE(a,bF(a,b))}function bC(a,b){return a.length<3?by(a):a[0]+bE((a.push(a[0]),a),bF([a[a.length-2]].concat(a,[a[1]]),b))}function bB(a,b){return a.length<4?by(a):a[1]+bE(a.slice(1,a.length-1),bF(a,b))}function bA(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("H",(e=a[c])[0],"V",e[1]);return b.join("")}function bz(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("V",(e=a[c])[1],"H",e[0]);return b.join("")}function by(a){var b=[],c=0,d=a.length,e=a[0];b.push(e[0],",",e[1]);while(++c<d)b.push("L",(e=a[c])[0],",",e[1]);return b.join("")}function bw(a){return a[1]}function bv(a){return a[0]}function bu(a,b,c,d){var e=[],f=-1,g=b.length,h=typeof c=="function",i=typeof d=="function",j;if(h&&i)while(++f<g)e.push([c.call(a,j=b[f],f),d.call(a,j,f)]);else if(h)while(++f<g)e.push([c.call(a,b[f],f),d]);else if(i)while(++f<g)e.push([c,d.call(a,b[f],f)]);else while(++f<g)e.push([c,d]);return e}function bt(a){return a.endAngle}function bs(a){return a.startAngle}function br(a){return a.outerRadius}function bq(a){return a.innerRadius}function bj(a){return function(b){return-Math.pow(-b,a)}}function bi(a){return function(b){return Math.pow(b,a)}}function bh(a){return-Math.log(-a)/Math.LN10}function bg(a){return Math.log(a)/Math.LN10}function bf(a,b,c,d){function i(b){var c=1,d=a.length-2;while(c<=d){var e=c+d>>1,f=a[e];if(f<b)c=e+1;else if(f>b)d=e-1;else return e}return c-1}var e=[],f=[],g=0,h=a.length;while(++g<h)e.push(c(a[g-1],a[g])),f.push(d(b[g-1],b[g]));return function(a){var b=i(a);return f[b](e[b](a))}}function be(a,b,c,d){var e=c(a[0],a[1]),f=d(b[0],b[1]);return function(a){return f(e(a))}}function bc(){var a=null,b=Z,c=Infinity;while(b)b.flush?b=a?a.next=b.next:Z=b.next:(c=Math.min(c,b.then+b.delay),b=(a=b).next);return c}function bb(){var a,b=Date.now(),c=Z;while(c)a=b-c.then,a>c.delay&&(c.flush=c.callback(a)),c=c.next;var d=bc()-b;d>24?(isFinite(d)&&(clearTimeout(_),_=setTimeout(bb,d)),$=0):($=1,bd(bb))}function ba(a,b){var c=Date.now(),d=!1,e,f=Z;if(!!isFinite(b)){while(f){if(f.callback===a){f.then=c,f.delay=b,d=!0;break}e=f,f=f.next}d||(Z={callback:a,then:c,delay:b,next:Z}),$||(_=clearTimeout(_),$=1,bd(bb))}}function Y(a){return typeof a=="function"?function(b,c,d){return d3.interpolate(d,String(a.call(this,b,c)))}:(a=String(a),function(b,c,d){return d3.interpolate(d,a)})}function X(a){function n(b){var f=!0,l=-1;a.each(function(){if(i[++l]!==2){var a=(b-j[l])/k[l],n=this.__transition__,o,p,q=e[l];if(a<1){f=!1;if(a<0)return}else a=1;if(i[l]){if(!n||n.active!==c){i[l]=2;return}}else{if(!n||n.active>c){i[l]=2;return}i[l]=1,h.start.dispatch.apply(this,arguments),q=e[l]={},n.active=c;for(p in d)if(o=d[p].apply(this,arguments))q[p]=o}o=m(a);for(p in q)q[p].call(this,o);if(a===1){i[l]=2;if(n.active===c){var r=n.owner;r===c&&(delete this.__transition__,g&&this.parentNode.removeChild(this)),W=c,h.end.dispatch.apply(this,arguments),W=0,n.owner=r}}}});return f}var b={},c=W||++V,d={},e=[],g=!1,h=d3.dispatch("start","end"),i=[],j=[],k=[],l,m=d3.ease("cubic-in-out");a.each(function(){(this.__transition__||(this.__transition__={})).owner=c}),b.delay=function(c){var d=Infinity,e=-1;typeof c=="function"?a.each(function(a,b){var f=j[++e]=+c.apply(this,arguments);f<d&&(d=f)}):(d=+c,a.each(function(a,b){j[++e]=d})),ba(n,d);return b},b.duration=function(c){var d=-1;typeof c=="function"?(l=0,a.each(function(a,b){var e=k[++d]=+c.apply(this,arguments);e>l&&(l=e)})):(l=+c,a.each(function(a,b){k[++d]=l}));return b},b.ease=function(a){m=typeof a=="function"?a:d3.ease.apply(d3,arguments);return b},b.attrTween=function(a,c){function f(b,d){var e=c.call(this,b,d,this.getAttributeNS(a.space,a.local));return function(b){this.setAttributeNS(a.space,a.local,e(b))}}function e(b,d){var e=c.call(this,b,d,this.getAttribute(a));return function(b){this.setAttribute(a,e(b))}}d["attr."+a]=a.local?f:e;return b},b.attr=function(a,c){return b.attrTween(a,Y(c))},b.styleTween=function(a,c,e){function f(b,d){var f=c.call(this,b,d,window.getComputedStyle(this,null).getPropertyValue(a));return function(b){this.style.setProperty(a,f(b),e)}}arguments.length<3&&(e=null),d["style."+a]=f;return b},b.style=function(a,c,d){arguments.length<3&&(d=null);return b.styleTween(a,Y(c),d)},b.text=function(a){d.text=function(b,c){this.textContent=typeof a=="function"?a.call(this,b,c):a};return b},b.select=function(b){var c,d=X(a.select(b)).ease(m);c=-1,d.delay(function(a,b){return j[++c]}),c=-1,d.duration(function(a,b){return k[++c]});return d},b.selectAll=function(b){var c,d=X(a.selectAll(b)).ease(m);c=-1,d.delay(function(a,b){return j[b?c:++c]}),c=-1,d.duration(function(a,b){return k[b?c:++c]});return d},b.remove=function(){g=!0;return b},b.each=function(a,c){h[a].add(c);return b},b.call=f;return b.delay(0).duration(250)}function U(a){return{__data__:a}}function T(a){arguments.length||(a=d3.ascending);return function(b,c){return a(b&&b.__data__,c&&c.__data__)}}function S(a){function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(f.parentNode)),e.__data__=g.__data__):d.push(null)}return R(c)}a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),O(c,b))}function d(b){return b.insertBefore(document.createElement(a),O(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)};return a}function R(a){function d(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];if(h)return b.call(h,h.__data__,f)}}return null}function c(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g];for(var i=0,j=e.length;i<j;i++)if(f=e[i])c.push(d=b(f)),d.parentNode=f}return R(c)}function b(b){var c=[],d,e,f,g;for(var h=0,i=a.length;h<i;h++){f=a[h],c.push(d=[]),d.parentNode=f.parentNode;for(var j=0,k=f.length;j<k;j++)(g=f[j])?(d.push(e=b(g)),e&&"__data__"in g&&(e.__data__=g.__data__)):d.push(null)}return R(c)}a.select=function(a){return b(function(b){return O(a,b)})},a.selectAll=function(a){return c(function(b){return P(a,b)})},a.filter=function(b){var c=[],d,e,f;for(var g=0,h=a.length;g<h;g++){e=a[g],c.push(d=[]),d.parentNode=e.parentNode;for(var i=0,j=e.length;i<j;i++)(f=e[i])&&b.call(f,f.__data__,i)&&d.push(f)}return R(c)},a.map=function(b){var c,d;for(var e=0,f=a.length;e<f;e++){c=a[e];for(var g=0,h=c.length;g<h;g++)if(d=c[g])d.__data__=b.call(d,d.__data__,g)}return a},a.data=function(b,c){function g(a,b){var g=0,h=a.length,i=b.length,j=Math.min(h,i),k=Math.max(h,i),l=[],m=[],n=[],o,p;if(c){var q={},r=[],s,t=b.length;for(g=0;g<h;g++)s=c.call(o=a[g],o.__data__,g),s in q?n[t++]=a[g]:q[s]=o,r.push(s);for(g=0;g<i;g++)o=q[s=c.call(b,p=b[g],g)],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=U(p),l[g]=n[g]=null),delete q[s];for(g=0;g<h;g++)r[g]in q&&(n[g]=a[g])}else{for(;g<j;g++)o=a[g],p=b[g],o?(o.__data__=p,l[g]=o,m[g]=n[g]=null):(m[g]=U(p),l[g]=n[g]=null);for(;g<i;g++)m[g]=U(b[g]),l[g]=n[g]=null;for(;g<k;g++)n[g]=a[g],m[g]=l[g]=null}m.parentNode=l.parentNode=n.parentNode=a.parentNode,d.push(m),e.push(l),f.push(n)}var d=[],e=[],f=[],h=-1,i=a.length,j;if(typeof b=="function")while(++h<i)g(j=a[h],b.call(j,j.parentNode.__data__,h));else while(++h<i)g(j=a[h],b);var k=R(e);k.enter=function(){return S(d)},k.exit=function(){return R(f)};return k},a.each=function(b){for(var c=0,d=a.length;c<d;c++){var e=a[c];for(var f=0,g=e.length;f<g;f++){var h=e[f];h&&b.call(h,h.__data__,f)}}return a},a.empty=function(){return!d(function(){return!0})},a.node=function(){return d(function(){return this})},a.attr=function(b,c){function j(){var a=c.apply(this,arguments);a==null?this.removeAttributeNS(b.space,b.local):this.setAttributeNS(b.space,b.local,a)}function i(){var a=c.apply(this,arguments);a==null?this.removeAttribute(b):this.setAttribute(b,a)}function h(){this.setAttributeNS(b.space,b.local,c)}function g(){this.setAttribute(b,c)}function f(){this.removeAttributeNS(b.space,b.local)}function e(){this.removeAttribute(b)}b=d3.ns.qualify(b);if(arguments.length<2)return d(b.local?function(){return this.getAttributeNS(b.space,b.local)}:function(){return this.getAttribute(b)});return a.each(c==null?b.local?f:e:typeof c=="function"?b.local?j:i:b.local?h:g)},a.classed=function(b,c){function i(){(c.apply(this,arguments)?g:h).call(this)}function h(){if(a=this.classList)return a.remove(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;d=e(d.replace(f," ")),c?a.baseVal=d:this.className=d}function g(){if(a=this.classList)return a.add(b);var a=this.className,c=a.baseVal!=null,d=c?a.baseVal:a;f.lastIndex=0,f.test(d)||(d=e(d+" "+b),c?a.baseVal=d:this.className=d)}var f=new RegExp("(^|\\s+)"+d3.requote(b)+"(\\s+|$)","g");if(arguments.length<2)return d(function(){if(a=this.classList)return a.contains(b);var a=this.className;f.lastIndex=0;return f.test(a.baseVal!=null?a.baseVal:a)});return a.each(typeof c=="function"?i:c?g:h)},a.style=function(b,c,e){function h(){var a=c.apply(this,arguments);a==null?this.style.removeProperty(b):this.style.setProperty(b,a,e)}function g(){this.style.setProperty(b,c,e)}function f(){this.style.removeProperty(b)}arguments.length<3&&(e="");if(arguments.length<2)return d(function(){return window.getComputedStyle(this,null).getPropertyValue(b)});return a.each(c==null?f:typeof c=="function"?h:g)},a.property=function(b,c){function g(){var a=c.apply(this,arguments);a==null?delete this[b]:this[b]=a}function f(){this[b]=c}function e(){delete this[b]}b=d3.ns.qualify(b);if(arguments.length<2)return d(function(){return this[b]});return a.each(c==null?e:typeof c=="function"?g:f)},a.text=function(b){function e(){this.textContent=b.apply(this,arguments)}function c(){this.textContent=b}if(arguments.length<1)return d(function(){return this.textContent});return a.each(typeof b=="function"?e:c)},a.html=function(b){function e(){this.innerHTML=b.apply(this,arguments)}function c(){this.innerHTML=b}if(arguments.length<1)return d(function(){return this.innerHTML});return a.each(typeof b=="function"?e:c)},a.append=function(a){function d(b){return b.appendChild(document.createElementNS(a.space,a.local))}function c(b){return b.appendChild(document.createElement(a))}a=d3.ns.qualify(a);return b(a.local?d:c)},a.insert=function(a,c){function e(b){return b.insertBefore(document.createElementNS(a.space,a.local),O(c,b))}function d(b){return b.insertBefore(document.createElement(a),O(c,b))}a=d3.ns.qualify(a);return b(a.local?e:d)},a.remove=function(){return a.each(function(){var a=this.parentNode;a&&a.removeChild(this)})},a.sort=function(b){b=T.apply(this,arguments);for(var c=0,d=a.length;c<d;c++){var e=a[c];e.sort(b);for(var f=1,g=e.length,h=e[0];f<g;f++){var i=e[f];i&&(h&&h.parentNode.insertBefore(i,h.nextSibling),h=i)}}return a},a.on=function(b,c,d){arguments.length<3&&(d=!1);var e=b.indexOf("."),f=e===-1?b:b.substring(0,e),g="__on"+b;return a.each(function(a,b){function h(a){var d=d3.event;d3.event=a;try{c.call(this,e.__data__,b)}finally{d3.event=d}}this[g]&&this.removeEventListener(f,this[g],d),c&&this.addEventListener(f,this[g]=h,d);var e=this})},a.transition=function(){return X(a)},a.call=f;return a}function N(a,b,c){function g(a){return Math.round(f(a)*255)}function f(a){a>360?a-=360:a<0&&(a+=360);if(a<60)return d+(e-d)*a/60;if(a<180)return e;if(a<240)return d+(e-d)*(240-a)/60;return d}var d,e;a=a%360,a<0&&(a+=360),b=b<0?0:b>1?1:b,c=c<0?0:c>1?1:c,e=c<=.5?c*(1+b):c+b-c*b,d=2*c-e;return D(g(a+120),g(a),g(a-120))}function M(a,b,c){this.h=a,this.s=b,this.l=c}function L(a,b,c){return new M(a,b,c)}function I(a){var b=parseFloat(a);return a.charAt(a.length-1)==="%"?Math.round(b*2.55):b}function H(a,b,c){var d=Math.min(a/=255,b/=255,c/=255),e=Math.max(a,b,c),f=e-d,g,h,i=(e+d)/2;f?(h=i<.5?f/(e+d):f/(2-e-d),a==e?g=(b-c)/f+(b<c?6:0):b==e?g=(c-a)/f+2:g=(a-b)/f+4,g*=60):h=g=0;return L(g,h,i)}function G(a,b,c){var d=0,e=0,f=0,g,h,i;g=/([a-z]+)\((.*)\)/i.exec(a);if(g){h=g[2].split(",");switch(g[1]){case"hsl":return c(parseFloat(h[0]),parseFloat(h[1])/100,parseFloat(h[2])/100);case"rgb":return b(I(h[0]),I(h[1]),I(h[2]))}}if(i=J[a])return b(i.r,i.g,i.b);a!=null&&a.charAt(0)==="#"&&(a.length===4?(d=a.charAt(1),d+=d,e=a.charAt(2),e+=e,f=a.charAt(3),f+=f):a.length===7&&(d=a.substring(1,3),e=a.substring(3,5),f=a.substring(5,7)),d=parseInt(d,16),e=parseInt(e,16),f=parseInt(f,16));return b(d,e,f)}function F(a){return a<16?"0"+a.toString(16):a.toString(16)}function E(a,b,c){this.r=a,this.g=b,this.b=c}function D(a,b,c){return new E(a,b,c)}function C(a,b){b=1/(b-(a=+a));return function(c){return Math.max(0,Math.min(1,(c-a)*b))}}function B(a,b){b=1/(b-(a=+a));return function(c){return(c-a)*b}}function A(a){return a in z||/\bcolor\b/.test(a)?d3.interpolateRgb:d3.interpolate}function x(a){return a<1/2.75?7.5625*a*a:a<2/2.75?7.5625*(a-=1.5/2.75)*a+.75:a<2.5/2.75?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}function w(a){a||(a=1.70158);return function(b){return b*b*((a+1)*b-a)}}function v(a,b){var c;arguments.length<2&&(b=.45),arguments.length<1?(a=1,c=b/4):c=b/(2*Math.PI)*Math.asin(1/a);return function(d){return 1+a*Math.pow(2,10*-d)*Math.sin((d-c)*2*Math.PI/b)}}function u(a){return 1-Math.sqrt(1-a*a)}function t(a){return a?Math.pow(2,10*(a-1))-.001:0}function s(a){return 1-Math.cos(a*Math.PI/2)}function r(a){return function(b){return Math.pow(b,a)}}function q(a){return a}function p(a){return function(b){return.5*(b<.5?a(2*b):2-a(2-2*b))}}function o(a){return function(b){return 1-a(1-b)}}function j(a){var b=a.lastIndexOf("."),c=b>=0?a.substring(b):(b=a.length,""),d=[];while(b>0)d.push(a.substring(b-=3,b+3));return d.reverse().join(",")+c}function h(a){var b={},c=[];b.add=function(a){for(var d=0;d<c.length;d++)if(c[d].listener==a)return b;c.push({listener:a,on:!0});return b},b.remove=function(a){for(var d=0;d<c.length;d++){var e=c[d];if(e.listener==a){e.on=!1,c=c.slice(0,d).concat(c.slice(d+1));break}}return b},b.dispatch=function(){var a=c;for(var b=0,d=a.length;b<d;b++){var e=a[b];e.on&&e.listener.apply(this,arguments)}};return b}function f(a){a.apply(this,(arguments[0]=this,arguments));return this}function e(a){return a.replace(/(^\s+)|(\s+$)/g,"").replace(/\s+/g," ")}function d(a){return a==null}function b(a){return Array.prototype.slice.call(a)}function a(a){var b=-1,c=a.length,d=[];while(++b<c)d.push(a[b]);return d}d3={version:"1.16.0"},Date.now||(Date.now=function(){return+(new Date)}),Object.create||(Object.create=function(a){function b(){}b.prototype=a;return new b}),d3.array=b;try{d3.array(document.documentElement.childNodes)[0].nodeType}catch(c){d3.array=a}d3.functor=function(a){return typeof a=="function"?a:function(){return a}},d3.rebind=function(a,b){return function(){var c=b.apply(a,arguments);return arguments.length?a:c}},d3.ascending=function(a,b){return a<b?-1:a>b?1:0},d3.descending=function(a,b){return b<a?-1:b>a?1:0},d3.min=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e>(f=a[c])&&(e=f);else{e=b(a[0]);while(++c<d)e>(f=b(a[c]))&&(e=f)}return e},d3.max=function(a,b){var c=0,d=a.length,e=a[0],f;if(arguments.length===1)while(++c<d)e<(f=a[c])&&(e=f);else{e=b(e);while(++c<d)e<(f=b(a[c]))&&(e=f)}return e},d3.nest=function(){function g(a,d){if(d>=b.length)return a;var e=[],f=c[d++],h;for(h in a)e.push({key:h,values:g(a[h],d)});f&&e.sort(function(a,b){return f(a.key,b.key)});return e}function f(c,g){if(g>=b.length)return e?e.call(a,c):d?c.sort(d):c;var h=-1,i=c.length,j=b[g++],k,l,m={};while(++h<i)(k=j(l=c[h]))in m?m[k].push(l):m[k]=[l];for(k in m)m[k]=f(m[k],g);return m}var a={},b=[],c=[],d,e;a.map=function(a){return f(a,0)},a.entries=function(a){return g(f(a,0),0)},a.key=function(c){b.push(c);return a},a.sortKeys=function(d){c[b.length-1]=d;return a},a.sortValues=function(b){d=b;return a},a.rollup=function(b){e=b;return a};return a},d3.keys=function(a){var b=[];for(var c in a)b.push(c);return b},d3.values=function(a){var b=[];for(var c in a)b.push(a[c]);return b},d3.entries=function(a){var b=[];for(var c in a)b.push({key:c,value:a[c]});return b},d3.permute=function(a,b){var c=[],d=-1,e=b.length;while(++d<e)c[d]=a[b[d]];return c},d3.merge=function(a){return Array.prototype.concat.apply([],a)},d3.split=function(a,b){var c=[],e=[],f,g=-1,h=a.length;arguments.length<2&&(b=d);while(++g<h)b.call(e,f=a[g],g)?e=[]:(e.length||c.push(e),e.push(f));return c},d3.range=function(a,b,c){arguments.length===1&&(b=a,a=0),c==null&&(c=1);if((b-a)/c==Infinity)throw new Error("infinite range");var d=[],e=-1,f;if(c<0)while((f=a+c*++e)>b)d.push(f);else while((f=a+c*++e)<b)d.push(f);return d},d3.requote=function(a){return a.replace(g,"\\$&")};var g=/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g;d3.xhr=function(a,b,c){var d=new XMLHttpRequest;arguments.length<3?c=b:b&&d.overrideMimeType&&d.overrideMimeType(b),d.open("GET",a,!0),d.onreadystatechange=function(){d.readyState===4&&c(d.status<300?d:null)},d.send(null)},d3.text=function(a,b,c){function d(a){c(a&&a.responseText)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.json=function(a,b){d3.text(a,"application/json",function(a){b(a?JSON.parse(a):null)})},d3.html=function(a,b){d3.text(a,"text/html",function(a){if(a!=null){var c=document.createRange();c.selectNode(document.body),a=c.createContextualFragment(a)}b(a)})},d3.xml=function(a,b,c){function d(a){c(a&&a.responseXML)}arguments.length<3&&(c=b,b=null),d3.xhr(a,b,d)},d3.ns={prefix:{svg:"http://www.w3.org/2000/svg",xhtml:"http://www.w3.org/1999/xhtml",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"},qualify:function(a){var b=a.indexOf(":");return b<0?a:{space:d3.ns.prefix[a.substring(0,b)],local:a.substring(b+1)}}},d3.dispatch=function(a){var b={},c;for(var d=0,e=arguments.length;d<e;d++)c=arguments[d],b[c]=h(c);return b},d3.format=function(a){var b=i.exec(a),c=b[1]||" ",d=b[3]||"",e=b[5],f=+b[6],g=b[7],h=b[8],k=b[9];h&&(h=h.substring(1)),e&&(c="0",g&&(f-=Math.floor((f-1)/4))),k==="d"&&(h="0");return function(a){var b=+a,i=b<0&&(b=-b)?"−":d;if(k==="d"&&b%1)return"";h?a=b.toFixed(h):a=""+b;if(e){var l=a.length+i.length;l<f&&(a=Array(f-l+1).join(c)+a),g&&(a=j(a)),a=i+a}else{g&&(a=j(a)),a=i+a;var l=a.length;l<f&&(a=Array(f-l+1).join(c)+a)}return a}};var i=/(?:([^{])?([<>=^]))?([+\- ])?(#)?(0)?([0-9]+)?(,)?(\.[0-9]+)?([a-zA-Z%])?/,k=r(2),l=r(3),m={linear:function(){return q},poly:r,quad:function(){return k},cubic:function(){return l},sin:function(){return s},exp:function(){return t},circle:function(){return u},elastic:v,back:w,bounce:function(){return x}},n={"in":function(a){return a},out:o,"in-out":p,"out-in":function(a){return p(o(a))}};d3.ease=function(a){var b=a.indexOf("-"),c=b>=0?a.substring(0,b):a,d=b>=0?a.substring(b+1):"in";return n[d](m[c].apply(null,Array.prototype.slice.call(arguments,1)))},d3.event=null,d3.interpolate=function(a,b){if(typeof b=="number")return d3.interpolateNumber(+a,b);if(typeof b=="string")return b in J||/^(#|rgb\(|hsl\()/.test(b)?d3.interpolateRgb(String(a),b):d3.interpolateString(String(a),b);if(b instanceof Array)return d3.interpolateArray(a,b);return d3.interpolateObject(a,b)},d3.interpolateNumber=function(a,b){b-=a;return function(c){return a+b*c}},d3.interpolateRound=function(a,b){b-=a;return function(c){return Math.round(a+b*c)}},d3.interpolateString=function(a,b){var c,d,e,f=0,g=0,h=[],i=[],j,k;y.lastIndex=0;for(d=0;c=y.exec(b);++d)c.index&&h.push(b.substring(f,g=c.index)),i.push({i:h.length,x:c[0]}),h.push(null),f=y.lastIndex;f<b.length&&h.push(b.substring(f));for(d=0,j=i.length;(c=y.exec(a))&&d<j;++d){k=i[d];if(k.x==c[0]){if(k.i)if(h[k.i+1]==null){h[k.i-1]+=k.x,h.splice(k.i,1);for(e=d+1;e<j;++e)i[e].i--}else{h[k.i-1]+=k.x+h[k.i+1],h.splice(k.i,2);for(e=d+1;e<j;++e)i[e].i-=2}else if(h[k.i+1]==null)h[k.i]=k.x;else{h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1);for(e=d+1;e<j;++e)i[e].i--}i.splice(d,1),j--,d--}else k.x=d3.interpolateNumber(parseFloat(c[0]),parseFloat(k.x))}while(d<j)k=i.pop(),h[k.i+1]==null?h[k.i]=k.x:(h[k.i]=k.x+h[k.i+1],h.splice(k.i+1,1)),j--;if(h.length===1)return h[0]==null?i[0].x:function(){return b};return function(a){for(d=0;d<j;++d)h[(k=i[d]).i]=k.x(a);return h.join("")}},d3.interpolateRgb=function(a,b){a=d3.rgb(a),b=d3.rgb(b);var c=a.r,d=a.g,e=a.b,f=b.r-c,g=b.g-d,h=b.b-e;return function(a){return"rgb("+Math.round(c+f*a)+","+Math.round(d+g*a)+","+Math.round(e+h*a)+")"}},d3.interpolateHsl=function(a,b){a=d3.hsl(a),b=d3.hsl(b);var c=a.h,d=a.s,e=a.l,f=b.h-c,g=b.s-d,h=b.l-e;return function(a){return N(c+f*a,d+g*a,e+h*a).toString()}},d3.interpolateArray=function(a,b){var c=[],d=[],e=a.length,f=b.length,g=Math.min(a.length,b.length),h;for(h=0;h<g;++h)c.push(d3.interpolate(a[h],b[h]));for(;h<e;++h)d[h]=a[h];for(;h<f;++h)d[h]=b[h];return function(a){for(h=0;h<g;++h)d[h]=c[h](a);return d}},d3.interpolateObject=function(a,b){var c={},d={},e;for(e in a)e in b?c[e]=A(e)(a[e],b[e]):d[e]=a[e];for(e in b)e in a||(d[e]=b[e]);return function(a){for(e in c)d[e]=c[e](a);return d}};var y=/[-+]?(?:\d+\.\d+|\d+\.|\.\d+|\d+)(?:[eE][-]?\d+)?/g,z={background:1,fill:1,stroke:1};d3.rgb=function(a,b,c){return arguments.length===1?G(""+a,D,N):D(~~a,~~b,~~c)},E.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);var b=this.r,c=this.g,d=this.b,e=30;if(!b&&!c&&!d)return D(e,e,e);b&&b<e&&(b=e),c&&c<e&&(c=e),d&&d<e&&(d=e);return D(Math.min(255,Math.floor(b/a)),Math.min(255,Math.floor(c/a)),Math.min(255,Math.floor(d/a)))},E.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return D(Math.max(0,Math.floor(a*this.r)),Math.max(0,Math.floor(a*this.g)),Math.max(0,Math.floor(a*this.b)))},E.prototype.hsl=function(){return H(this.r,this.g,this.b)},E.prototype.toString=function(){return"#"+F(this.r)+F(this.g)+F(this.b)};var J={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"};for(var K in J)J[K]=G(J[K],D,N);d3.hsl=function(a,b,c){return arguments.length===1?G(""+a,H,L):L(+a,+b,+c)},M.prototype.brighter=function(a){a=Math.pow(.7,arguments.length?a:1);return L(this.h,this.s,this.l/a)},M.prototype.darker=function(a){a=Math.pow(.7,arguments.length?a:1);return L(this.h,this.s,a*this.l)},M.prototype.rgb=function(){return N(this.h,this.s,this.l)},M.prototype.toString=function(){return"hsl("+this.h+","+this.s*100+"%,"+this.l*100+"%)"};var O=function(a,b){return b.querySelector(a)},P=function(a,b){return d3.array(b.querySelectorAll(a))};typeof Sizzle=="function"&&(O=function(a,b){return Sizzle(a,b)[0]},P=function(a,b){return Sizzle.uniqueSort(Sizzle(a,b))});var Q=R([[document]]);Q[0].parentNode=document.documentElement,d3.select=function(a){return typeof a=="string"?Q.select(a):R([[a]])},d3.selectAll=function(a){return typeof a=="string"?Q.selectAll(a):R([d3.array(a)])},d3.transition=Q.transition;var V=0,W=0,Z=null,$,_;d3.timer=function(a){ba(a,0)},d3.timer.flush=function(){var a,b=Date.now(),c=Z;while(c)a=b-c.then,c.delay||(c.flush=c.callback(a)),c=c.next;bc()};var bd=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,17)};d3.scale={},d3.scale.linear=function(){function i(b){var c=d3.min(a),d=d3.max(a),e=d-c,f=Math.pow(10,Math.floor(Math.log(e/b)/Math.LN10)),g=b/(e/f);g<=.15?f*=10:g<=.35?f*=5:g<=.75&&(f*=2);return{start:Math.ceil(c/f)*f,stop:Math.floor(d/f)*f+f*.5,step:f}}function h(a){return e(a)}function g(){var g=a.length==2?be:bf,i=d?C:B;e=g(a,b,i,c),f=g(b,a,i,d3.interpolate);return h}var a=[0,1],b=[0,1],c=d3.interpolate,d=!1,e,f;h.invert=function(a){return f(a)},h.domain=function(b){if(!arguments.length)return a;a=b.map(Number);return g()},h.range=function(a){if(!arguments.length)return b;b=a;return g()},h.rangeRound=function(a){return h.range(a).interpolate(d3.interpolateRound)},h.clamp=function(a){if(!arguments.length)return d;d=a;return g()},h.interpolate=function(a){if(!arguments.length)return c;c=a;return g()},h.ticks=function(a){var b=i(a);return d3.range(b.start,b.stop,b.step)},h.tickFormat=function(a){var b=Math.max(0,-Math.floor(Math.log(i(a).step)/Math.LN10+.01));return d3.format(",."+b+"f")};return g()},d3.scale.log=function(){function d(c){return a(b(c))}var a=d3.scale.linear(),b=bg,c=b.pow;d.invert=function(b){return c(a.invert(b))},d.domain=function(e){if(!arguments.length)return a.domain().map(c);b=(e[0]||e[1])<0?bh:bg,c=b.pow,a.domain(e.map(b));return d},d.range=d3.rebind(d,a.range),d.rangeRound=d3.rebind(d,a.rangeRound),d.interpolate=d3.rebind(d,a.interpolate),d.clamp=d3.rebind(d,a.clamp),d.ticks=function(){var d=a.domain(),e=[];if(d.every(isFinite)){var f=Math.floor(d[0]),g=Math.ceil(d[1]),h=c(d[0]),i=c(d[1]);if(b===bh){e.push(c(f));for(;f++<g;)for(var j=9;j>0;j--)e.push(c(f)*j)}else{for(;f<g;f++)for(var j=1;j<10;j++)e.push(c(f)*j);e.push(c(f))}for(f=0;e[f]<h;f++);for(g=e.length;e[g-1]>i;g--);e=e.slice(f,g)}return e},d.tickFormat=function(){return function(a){return a.toPrecision(1)}};return d},bg.pow=function(a){return Math.pow(10,a)},bh.pow=function(a){return-Math.pow(10,-a)},d3.scale.pow=function(){function f(b){return a(d(b))}var a=d3.scale.linear(),b=d3.scale.linear(),c=1,d=Number,e=d;f.invert=function(b){return e(a.invert(b))},f.domain=function(g){if(!arguments.length)return a.domain().map(e);var h=(g[0]||g[1])<0?bj:bi;d=h(c),e=h(1/c),a.domain(g.map(d)),b.domain(g);return f},f.range=d3.rebind(f,a.range),f.rangeRound=d3.rebind(f,a.rangeRound),f.interpolate=d3.rebind(f,a.interpolate),f.clamp=d3.rebind(f,a.clamp),f.ticks=b.ticks,f.tickFormat=b.tickFormat,f.exponent=function(a){if(!arguments.length)return c;var b=f.domain();c=a;return f.domain(b)};return f},d3.scale.sqrt=function(){return d3.scale.pow().exponent(.5)},d3.scale.ordinal=function(){function e(d){var e=d in b?b[d]:b[d]=a.push(d)-1;return c[e%c.length]}var a=[],b={},c=[],d=0;e.domain=function(c){if(!arguments.length)return a;a=c,b={};var d=-1,f=-1,g=a.length;while(++d<g)c=a[d],c in b||(b[c]=++f);return e},e.range=function(a){if(!arguments.length)return c;c=a;return e},e.rangePoints=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length-1+f);c=a.length==1?[(g+h)/2]:d3.range(g+i*f/2,h+i/2,i),d=0;return e},e.rangeBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=(h-g)/(a.length+f);c=d3.range(g+i*f,h,i),d=i*(1-f);return e},e.rangeRoundBands=function(b,f){arguments.length<2&&(f=0);var g=b[0],h=b[1],i=h-g,j=Math.floor(i/(a.length+f)),k=i-(a.length-f)*j;c=d3.range(g+Math.round(k/2),h,j),d=Math.round(j*(1-f));return e},e.rangeBand=function(){return d};return e},d3.scale.category10=function(){return d3.scale.ordinal().range(bk)},d3.scale.category20=function(){return d3.scale.ordinal().range(bl)},d3.scale.category20b=function(){return d3.scale.ordinal().range(bm)},d3.scale.category20c=function(){return d3.scale.ordinal().range(bn)};var bk=["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],bl= <add>["#1f77b4","#aec7e8","#ff7f0e","#ffbb78","#2ca02c","#98df8a","#d62728","#ff9896","#9467bd","#c5b0d5","#8c564b","#c49c94","#e377c2","#f7b6d2","#7f7f7f","#c7c7c7","#bcbd22","#dbdb8d","#17becf","#9edae5"],bm=["#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6"],bn=["#3182bd","#6baed6","#9ecae1","#c6dbef","#e6550d","#fd8d3c","#fdae6b","#fdd0a2","#31a354","#74c476","#a1d99b","#c7e9c0","#756bb1","#9e9ac8","#bcbddc","#dadaeb","#636363","#969696","#bdbdbd","#d9d9d9"];d3.scale.quantile=function(){function f(a){return b[e(a)]}function e(a){if(isNaN(a=+a))return NaN;var b=0,d=c.length-1;while(b<=d){var e=b+d>>1,f=c[e];if(f<a)b=e+1;else if(f>a)d=e-1;else return e}return d<0?0:d}function d(){var d=-1,e=c.length=b.length,f=a.length/e;while(++d<e)c[d]=a[~~(d*f)]}var a=[],b=[],c=[];f.domain=function(b){if(!arguments.length)return a;a=b.filter(function(a){return!isNaN(a)}).sort(d3.ascending),d();return f},f.range=function(a){if(!arguments.length)return b;b=a,d();return f},f.quantiles=function(){return c};return f},d3.scale.quantize=function(){function f(b){return e[Math.max(0,Math.min(d,Math.floor(c*(b-a))))]}var a=0,b=1,c=2,d=1,e=[0,1];f.domain=function(d){if(!arguments.length)return[a,b];a=d[0],b=d[1],c=e.length/(b-a);return f},f.range=function(g){if(!arguments.length)return e;e=g,c=e.length/(b-a),d=e.length-1;return f};return f},d3.svg={},d3.svg.arc=function(){function e(){var e=a.apply(this,arguments),f=b.apply(this,arguments),g=c.apply(this,arguments)+bo,h=d.apply(this,arguments)+bo,i=h-g,j=i<Math.PI?"0":"1",k=Math.cos(g),l=Math.sin(g),m=Math.cos(h),n=Math.sin(h);return i>=bp?e?"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"M0,"+e+"A"+e+","+e+" 0 1,1 0,"+ -e+"A"+e+","+e+" 0 1,1 0,"+e+"Z":"M0,"+f+"A"+f+","+f+" 0 1,1 0,"+ -f+"A"+f+","+f+" 0 1,1 0,"+f+"Z":e?"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L"+e*m+","+e*n+"A"+e+","+e+" 0 "+j+",0 "+e*k+","+e*l+"Z":"M"+f*k+","+f*l+"A"+f+","+f+" 0 "+j+",1 "+f*m+","+f*n+"L0,0"+"Z"}var a=bq,b=br,c=bs,d=bt;e.innerRadius=function(b){if(!arguments.length)return a;a=d3.functor(b);return e},e.outerRadius=function(a){if(!arguments.length)return b;b=d3.functor(a);return e},e.startAngle=function(a){if(!arguments.length)return c;c=d3.functor(a);return e},e.endAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return e},e.centroid=function(){var e=(a.apply(this,arguments)+b.apply(this,arguments))/2,f=(c.apply(this,arguments)+d.apply(this,arguments))/2+bo;return[Math.cos(f)*e,Math.sin(f)*e]};return e};var bo=-Math.PI/2,bp=2*Math.PI-1e-6;d3.svg.line=function(){function f(c){return c.length<1?null:"M"+d(bu(this,c,a,b),e)}var a=bv,b=bw,c="linear",d=bx[c],e=.7;f.x=function(b){if(!arguments.length)return a;a=b;return f},f.y=function(a){if(!arguments.length)return b;b=a;return f},f.interpolate=function(a){if(!arguments.length)return c;d=bx[c=a];return f},f.tension=function(a){if(!arguments.length)return e;e=a;return f};return f};var bx={linear:by,"step-before":bz,"step-after":bA,basis:bG,"basis-open":bH,"basis-closed":bI,cardinal:bD,"cardinal-open":bB,"cardinal-closed":bC,monotone:bR},bK=[0,2/3,1/3,0],bL=[0,1/3,2/3,0],bM=[0,1/6,2/3,1/6];d3.svg.area=function(){function g(d){return d.length<1?null:"M"+e(bu(this,d,a,c),f)+"L"+e(bu(this,d,a,b).reverse(),f)+"Z"}var a=bv,b=bS,c=bw,d="linear",e=bx[d],f=.7;g.x=function(b){if(!arguments.length)return a;a=b;return g},g.y0=function(a){if(!arguments.length)return b;b=a;return g},g.y1=function(a){if(!arguments.length)return c;c=a;return g},g.interpolate=function(a){if(!arguments.length)return d;e=bx[d=a];return g},g.tension=function(a){if(!arguments.length)return f;f=a;return g};return g},d3.svg.chord=function(){function j(a,b,c,d){return"Q 0,0 "+d}function i(a,b){return"A"+a+","+a+" 0 0,1 "+b}function h(a,b){return a.a0==b.a0&&a.a1==b.a1}function g(a,b,f,g){var h=b.call(a,f,g),i=c.call(a,h,g),j=d.call(a,h,g)+bo,k=e.call(a,h,g)+bo;return{r:i,a0:j,a1:k,p0:[i*Math.cos(j),i*Math.sin(j)],p1:[i*Math.cos(k),i*Math.sin(k)]}}function f(c,d){var e=g(this,a,c,d),f=g(this,b,c,d);return"M"+e.p0+i(e.r,e.p1)+(h(e,f)?j(e.r,e.p1,e.r,e.p0):j(e.r,e.p1,f.r,f.p0)+i(f.r,f.p1)+j(f.r,f.p1,e.r,e.p0))+"Z"}var a=bT,b=bU,c=bV,d=bs,e=bt;f.radius=function(a){if(!arguments.length)return c;c=d3.functor(a);return f},f.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return f},f.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return f},f.startAngle=function(a){if(!arguments.length)return d;d=d3.functor(a);return f},f.endAngle=function(a){if(!arguments.length)return e;e=d3.functor(a);return f};return f},d3.svg.diagonal=function(){function d(d,e){var f=a.call(this,d,e),g=b.call(this,d,e),h=(f.y+g.y)/2,i=[f,{x:f.x,y:h},{x:g.x,y:h},g];i=i.map(c);return"M"+i[0]+"C"+i[1]+" "+i[2]+" "+i[3]}var a=bT,b=bU,c=bY;d.source=function(b){if(!arguments.length)return a;a=d3.functor(b);return d},d.target=function(a){if(!arguments.length)return b;b=d3.functor(a);return d},d.projection=function(a){if(!arguments.length)return c;c=a;return d};return d},d3.svg.mouse=function(a){return b$(a,d3.event)};var bZ=/WebKit/.test(navigator.userAgent)?-1:0;d3.svg.touches=function(a){var b=d3.event.touches;return b?d3.array(b).map(function(b){var c=b$(a,b);c.identifier=b.identifier;return c}):[]},d3.svg.symbol=function(){function c(c,d){return(cb[a.call(this,c,d)]||cb.circle)(b.call(this,c,d))}var a=ca,b=b_;c.type=function(b){if(!arguments.length)return a;a=d3.functor(b);return c},c.size=function(a){if(!arguments.length)return b;b=d3.functor(a);return c};return c},d3.svg.symbolTypes=["circle","cross","diamond","square","triangle-down","triangle-up"];var cb={circle:function(a){var b=Math.sqrt(a/Math.PI);return"M0,"+b+"A"+b+","+b+" 0 1,1 0,"+ -b+"A"+b+","+b+" 0 1,1 0,"+b+"Z"},cross:function(a){var b=Math.sqrt(a/5)/2;return"M"+ -3*b+","+ -b+"H"+ -b+"V"+ -3*b+"H"+b+"V"+ -b+"H"+3*b+"V"+b+"H"+b+"V"+3*b+"H"+ -b+"V"+b+"H"+ -3*b+"Z"},diamond:function(a){var b=Math.sqrt(a/(2*cd)),c=b*cd;return"M0,"+ -b+"L"+c+",0"+" 0,"+b+" "+ -c+",0"+"Z"},square:function(a){var b=Math.sqrt(a)/2;return"M"+ -b+","+ -b+"L"+b+","+ -b+" "+b+","+b+" "+ -b+","+b+"Z"},"triangle-down":function(a){var b=Math.sqrt(a/cc),c=b*cc/2;return"M0,"+c+"L"+b+","+ -c+" "+ -b+","+ -c+"Z"},"triangle-up":function(a){var b=Math.sqrt(a/cc),c=b*cc/2;return"M0,"+ -c+"L"+b+","+c+" "+ -b+","+c+"Z"}},cc=Math.sqrt(3),cd=Math.tan(30*Math.PI/180)})() <ide>\ No newline at end of file <ide><path>src/core/array.js <del>var d3_array = d3_arraySlice; // conversion for NodeLists <add>d3.array = d3_arraySlice; // conversion for NodeLists <ide> <ide> function d3_arrayCopy(psuedoarray) { <ide> var i = -1, n = psuedoarray.length, array = []; <ide> function d3_arraySlice(psuedoarray) { <ide> } <ide> <ide> try { <del> d3_array(document.documentElement.childNodes)[0].nodeType; <add> d3.array(document.documentElement.childNodes)[0].nodeType; <ide> } catch(e) { <del> d3_array = d3_arrayCopy; <add> d3.array = d3_arrayCopy; <ide> } <ide><path>src/core/selection.js <ide> var d3_select = function(s, n) { return n.querySelector(s); }, <del> d3_selectAll = function(s, n) { return d3_array(n.querySelectorAll(s)); }; <add> d3_selectAll = function(s, n) { return d3.array(n.querySelectorAll(s)); }; <ide> <ide> // Use Sizzle, if available. <ide> if (typeof Sizzle === "function") { <ide> d3.select = function(selector) { <ide> d3.selectAll = function(selector) { <ide> return typeof selector === "string" <ide> ? d3_root.selectAll(selector) <del> : d3_selection([d3_array(selector)]); // assume node[] <add> : d3_selection([d3.array(selector)]); // assume node[] <ide> }; <ide> <ide> function d3_selection(groups) { <ide><path>src/layout/force.js <ide> d3.layout.force = function() { <ide> this <ide> .on("mouseover.force", d3_layout_forceDragOver) <ide> .on("mouseout.force", d3_layout_forceDragOut) <del> .on("mousedown.force", d3_layout_forceDragDown); <add> .on("mousedown.force", d3_layout_forceDragDown) <add> .on("touchstart.force", d3_layout_forceDragDown); <ide> <ide> d3.select(window) <ide> .on("mousemove.force", dragmove) <add> .on("touchmove.force", dragmove) <ide> .on("mouseup.force", dragup, true) <add> .on("touchend.force", dragup, true) <ide> .on("click.force", d3_layout_forceDragClick, true); <ide> <ide> return force; <ide> }; <ide> <ide> function dragmove() { <del> if (!d3_layout_forceDragNode) return; <del> var parent = d3_layout_forceDragElement.parentNode; <del> <del> // O NOES! The drag element was removed from the DOM. <del> if (!parent) { <del> d3_layout_forceDragNode.fixed = false; <del> d3_layout_forceDragNode = d3_layout_forceDragElement = null; <del> return; <del> } <add> if (!d3.keys(d3_layout_forceDragNodes).length) return; <add> (d3.event.touches <add> ? d3.array(d3.event.touches).map(function(t) { return t.identifier; }) <add> : [null]).forEach(function(id) { <add> var parent = d3_layout_forceDragElements[id].parentNode; <add> <add> // O NOES! The drag element was removed from the DOM. <add> if (!parent) { <add> d3_layout_forceDragNodes[id].fixed = false; <add> delete d3_layout_forceDragNodes[id]; <add> delete d3_layout_forceDragElements[id]; <add> return; <add> } <add> <add> var m = id === null <add> ? d3.svg.mouse(parent) <add> : d3.svg.touches(parent) <add> .filter(function(t) { return t.identifier === id; })[0]; <ide> <del> var m = d3.svg.mouse(parent); <del> d3_layout_forceDragMoved = true; <del> d3_layout_forceDragNode.px = m[0]; <del> d3_layout_forceDragNode.py = m[1]; <add> d3_layout_forceDragMoved[id] = true; <add> d3_layout_forceDragNodes[id].px = m[0]; <add> d3_layout_forceDragNodes[id].py = m[1]; <add> }); <ide> force.resume(); // restart annealing <ide> } <ide> <ide> function dragup() { <del> if (!d3_layout_forceDragNode) return; <del> <del> // If the node was moved, prevent the mouseup from propagating. <del> // Also prevent the subsequent click from propagating (e.g., for anchors). <del> if (d3_layout_forceDragMoved) { <del> d3_layout_forceStopClick = true; <del> d3_layout_forceCancel(); <del> } <del> <del> dragmove(); <del> d3_layout_forceDragNode.fixed = false; <del> d3_layout_forceDragNode = d3_layout_forceDragElement = null; <add> if (!d3.keys(d3_layout_forceDragNodes).length) return; <add> var touches = d3.event.changedTouches || d3.event.touches; <add> (touches ? d3.array(touches).map(function(t) { return t.identifier; }) <add> : [null]).forEach(function(id) { <add> // If the node was moved, prevent the mouseup from propagating. <add> // Also prevent the subsequent click from propagating (e.g., for anchors). <add> if (d3_layout_forceDragMoved[id]) { <add> d3_layout_forceStopClick = true; <add> d3_layout_forceCancel(); <add> } <add> dragmove(); <add> d3_layout_forceDragNodes[id].fixed = false; <add> delete d3_layout_forceDragNodes[id]; <add> delete d3_layout_forceDragElements[id]; <add> }); <ide> } <ide> <ide> return force; <ide> }; <ide> <del>var d3_layout_forceDragNode, <del> d3_layout_forceDragMoved, <del> d3_layout_forceStopClick, <del> d3_layout_forceDragElement; <add>var d3_layout_forceDragNodes = {}, <add> d3_layout_forceDragMoved = {}, <add> d3_layout_forceStopClick = false, <add> d3_layout_forceDragElements = {}; <ide> <ide> function d3_layout_forceDragOver(d) { <ide> d.fixed = true; <ide> } <ide> <ide> function d3_layout_forceDragOut(d) { <del> if (d !== d3_layout_forceDragNode) { <add> if (d !== d3_layout_forceDragNodes[id]) { <ide> d.fixed = false; <ide> } <ide> } <ide> <ide> function d3_layout_forceDragDown(d, i) { <del> (d3_layout_forceDragNode = d).fixed = true; <del> d3_layout_forceDragMoved = false; <del> d3_layout_forceDragElement = this; <add> var id = d3.event.touches ? d3.event.touches[0].identifier : null; <add> d.fixed = true; <add> d3_layout_forceDragNodes[id] = d; <add> if (id in d3_layout_forceDragMoved) delete d3_layout_forceDragMoved[id]; <add> d3_layout_forceDragElements[id] = this; <ide> d3_layout_forceCancel(); <ide> } <ide> <ide><path>src/svg/touches.js <ide> d3.svg.touches = function(container) { <ide> var touches = d3.event.touches; <del> return touches ? d3_array(touches).map(function(touch) { <add> return touches ? d3.array(touches).map(function(touch) { <ide> var point = d3_svg_mousePoint(container, touch); <ide> point.identifier = touch.identifier; <ide> return point;
8
PHP
PHP
collect garbage for cycles
2439b05189292c4b9e0ae907caa4c1f9d2e5d2de
<ide><path>tests/Database/DatabaseQueryBuilderMemoryLeakTest.php <ide> protected function runMemoryTest(\Closure $callback) <ide> <ide> $last = null; <ide> <add> gc_collect_cycles(); <add> <ide> while($i--) <ide> { <ide> $callback();
1
Text
Text
add missing quotes [skip ci]
58e6e5c8989a5387c94badf333e9329705c92b44
<ide><path>guides/source/security.md <ide> Here is the most straightforward test to check for XSS: <ide> This JavaScript code will simply display an alert box. The next examples do exactly the same, only in very uncommon places: <ide> <ide> ```html <del><img src=javascript:alert('Hello')> <add><img src="javascript:alert('Hello')"> <ide> <table background="javascript:alert('Hello')"> <ide> ``` <ide>
1
Text
Text
add ubuntu arch note
b2f1f7ee00070aa5ae0265296baee2a268aa3cbc
<ide><path>docs/installation/linux/ubuntulinux.md <ide> packages from the new repository: <ide> <ide> deb https://apt.dockerproject.org/repo ubuntu-wily main <ide> <del> > **Note**: Docker does not provide packages for all architectures. To install docker on <add> > **Note**: Docker does not provide packages for all architectures. You can find <add> > nightly built binaries in https://master.dockerproject.org. To install docker on <ide> > a multi-architecture system, add an `[arch=...]` clause to the entry. Refer to the <ide> > [Debian Multiarch wiki](https://wiki.debian.org/Multiarch/HOWTO#Setting_up_apt_sources) <ide> > for details.
1
Text
Text
fix napi version for node_api_symbol_for
0818b525ad966db1e859b94dafd7ab113447f053
<ide><path>doc/api/n-api.md <ide> of the ECMAScript Language Specification. <ide> added: <ide> - v17.5.0 <ide> - v16.15.0 <del>napiVersion: <del> - v17.5.0 <del> - v16.15.0 <ide> --> <ide> <ide> > Stability: 1 - Experimental
1
Javascript
Javascript
remove feature test from invokeguardedcallbackdev
6c66d38d2549d14a3775a6a0687be6375967d009
<ide><path>scripts/jest/fiber.setup.js <ide> jest.mock('ReactFeatureFlags', () => { <ide> const flags = require.requireActual('ReactFeatureFlags'); <ide> return Object.assign({}, flags, { <ide> disableNewFiberFeatures: true, <del> forceInvokeGuardedCallbackDev: true, <ide> }); <ide> }); <ide> jest.mock('ReactNativeFeatureFlags', () => { <ide><path>src/renderers/shared/utils/ReactErrorUtils.js <ide> const ReactErrorUtils = { <ide> /** <ide> * Call a function while guarding against errors that happens within it. <ide> * Returns an error if it throws, otherwise null. <add> * <add> * In production, this is implemented using a try-catch. The reason we don't <add> * use a try-catch directly is so that we can swap out a different <add> * implementation in DEV mode. <ide> * <ide> * @param {String} name of the guard to use for logging or debugging <ide> * @param {Function} func The function to invoke <ide> const ReactErrorUtils = { <ide> /** <ide> * Same as invokeGuardedCallback, but instead of returning an error, it stores <ide> * it in a global so it can be rethrown by `rethrowCaughtError` later. <add> * TODO: See if _caughtError and _rethrowError can be unified. <ide> * <ide> * @param {String} name of the guard to use for logging or debugging <ide> * @param {Function} func The function to invoke <ide> let invokeGuardedCallback = function(name, func, context, a, b, c, d, e, f) { <ide> }; <ide> <ide> if (__DEV__) { <del> const ReactFeatureFlags = require('ReactFeatureFlags'); <add> // In DEV mode, we swap out invokeGuardedCallback for a special version <add> // that plays more nicely with the browser's DevTools. The idea is to preserve <add> // "Pause on exceptions" behavior. Because React wraps all user-provided <add> // functions in invokeGuardedCallback, and the production version of <add> // invokeGuardedCallback uses a try-catch, all user exceptions are treated <add> // like caught exceptions, and the DevTools won't pause unless the developer <add> // takes the extra step of enabling pause on caught exceptions. This is <add> // untintuitive, though, because even though React has caught the error, from <add> // the developer's perspective, the error is uncaught. <add> // <add> // To preserve the expected "Pause on exceptions" behavior, we don't use a <add> // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake <add> // DOM node, and call the user-provided callback from inside an event handler <add> // for that fake event. If the callback throws, the error is "captured" using <add> // a global event handler. But because the error happens in a different <add> // event loop context, it does not interrupt the normal program flow. <add> // Effectively, this gives us try-catch behavior without actually using <add> // try-catch. Neat! <ide> <add> // Check that the browser supports the APIs we need to implement our special <add> // DEV version of invokeGuardedCallback <ide> if ( <ide> typeof window !== 'undefined' && <ide> typeof window.dispatchEvent === 'function' && <ide> typeof document !== 'undefined' && <ide> typeof document.createEvent === 'function' <ide> ) { <del> let preventDefault = true; <del> <del> /** <del> * To help development we can get better devtools integration by simulating a <del> * real browser event. <del> */ <ide> const fakeNode = document.createElement('react'); <ide> let depth = 0; <ide> <ide> if (__DEV__) { <ide> e, <ide> f, <ide> ) { <del> depth++; <del> <del> let error; <add> // Keeps track of whether the user-provided callback threw an error. We <add> // set this to true at the beginning, then set it to false right after <add> // calling the function. If the function errors, `didError` will never be <add> // set to false. This strategy works even if the browser is flaky and <add> // fails to call our global error handler, because it doesn't rely on <add> // the error event at all. <ide> let didError = true; <add> <add> // Create an event handler for our fake event. We will synchronously <add> // dispatch our fake event using `dispatchEvent`. Inside the handler, we <add> // call the user-provided callback. <ide> const funcArgs = Array.prototype.slice.call(arguments, 3); <del> const boundFunc = function() { <add> function callCallback() { <ide> func.apply(context, funcArgs); <ide> didError = false; <del> }; <del> const onFakeEventError = function(event) { <add> } <add> <add> // Create a global error event handler. We use this to capture the value <add> // that was thrown. It's possible that this error handler will fire more <add> // than once; for example, if non-React code also calls `dispatchEvent` <add> // and a handler for that event throws. We should be resilient to most of <add> // those cases. Even if our error event handler fires more than once, the <add> // last error event is always used. If the callback actually does error, <add> // we know that the last error event is the correct one, because it's not <add> // possible for anything else to have happened in between our callback <add> // erroring and the code that follows the `dispatchEvent` call below. If <add> // the callback doesn't error, but the error event was fired, we know to <add> // ignore it because `didError` will be false, as described above. <add> let error; <add> // Use this to track whether the error event is ever called. <add> let didSetError = false; <add> <add> function onError(event) { <ide> error = event.error; <del> if (preventDefault) { <del> event.preventDefault(); <del> } <del> }; <add> didSetError = true; <add> } <ide> <add> // Create a fake event type. We add `depth` to the event name so that <add> // nested `invokeGuardedCallback` calls do not clash. Otherwise, a nested <add> // call would trigger the fake event handlers of any call higher in <add> // the stack. <add> depth++; <ide> const evtType = `react-${name ? name : 'invokeguardedcallback'}-${depth}`; <del> window.addEventListener('error', onFakeEventError); <del> fakeNode.addEventListener(evtType, boundFunc, false); <del> const evt = document.createEvent('Event'); <ide> <add> // Attach our event handlers <add> window.addEventListener('error', onError); <add> fakeNode.addEventListener(evtType, callCallback, false); <add> <add> // Synchronously dispatch our fake event. If the user-provided function <add> // errors, it will trigger our global error handler. <add> const evt = document.createEvent('Event'); <ide> evt.initEvent(evtType, false, false); <ide> fakeNode.dispatchEvent(evt); <add> <ide> if (didError) { <add> if (!didSetError) { <add> // The callback errored, but the error event never fired. <add> error = new Error( <add> 'An error was thrown inside one of your components, but React ' + <add> "doesn't know what it was. This is likely due to browser " + <add> 'flakiness. React does its best to preserve the "Pause on ' + <add> 'exceptions" behavior of the DevTools, which requires some ' + <add> "DEV-mode only tricks. It's possible that these don't work in " + <add> 'your browser. Try triggering the error in production mode, ' + <add> 'or switching to a modern browser. If you suspect that this is ' + <add> 'actually an issue with React, please file an issue.', <add> ); <add> } <ide> ReactErrorUtils._hasCaughtError = true; <ide> ReactErrorUtils._caughtError = error; <ide> } else { <ide> ReactErrorUtils._hasCaughtError = false; <ide> ReactErrorUtils._caughtError = null; <ide> } <ide> <del> fakeNode.removeEventListener(evtType, boundFunc, false); <del> window.removeEventListener('error', onFakeEventError); <add> // Remove our event listeners <add> fakeNode.removeEventListener(evtType, callCallback, false); <add> window.removeEventListener('error', onError); <ide> <add> // Decrement the depth. This isn't strictly necessary, because we could <add> // just keep incrementing the number; the only requirement is that no two <add> // calls to `invokeGuardedCallback` use the same event type at the same <add> // time. But this does prevent `depth` from increasing boundlessly. <ide> depth--; <ide> }; <ide> <del> // Feature test the development version of invokeGuardedCallback <del> // before enabling. <del> let useInvokeGuardedCallbackDev; <del> if (ReactFeatureFlags.forceInvokeGuardedCallbackDev) { <del> // jsdom doesn't handle throwing null correctly (it fails when attempting <del> // to access the 'message' property) but we need the ability to test it. <del> // We use a feature flag to override the default feature test. <del> useInvokeGuardedCallbackDev = true; <del> } else { <del> try { <del> const err = new Error('test'); <del> invokeGuardedCallbackDev( <del> null, <del> () => { <del> throw err; <del> }, <del> null, <del> ); <del> const A = ReactErrorUtils.clearCaughtError(); <del> <del> invokeGuardedCallbackDev( <del> null, <del> () => { <del> throw null; <del> }, <del> null, <del> ); <del> const B = ReactErrorUtils.clearCaughtError(); <del> <del> if (A === err && B === null) { <del> useInvokeGuardedCallbackDev = true; <del> } <del> } catch (e) { <del> useInvokeGuardedCallbackDev = false; <del> } <del> } <del> <del> if (useInvokeGuardedCallbackDev) { <del> invokeGuardedCallback = invokeGuardedCallbackDev; <del> preventDefault = false; <del> } <add> invokeGuardedCallback = invokeGuardedCallbackDev; <ide> } <ide> } <ide> <ide><path>src/renderers/shared/utils/ReactFeatureFlags.js <ide> var ReactFeatureFlags = { <ide> disableNewFiberFeatures: false, <ide> enableAsyncSubtreeAPI: false, <del> // We set this to true when running unit tests <del> forceInvokeGuardedCallbackDev: false, <ide> }; <ide> <ide> module.exports = ReactFeatureFlags;
3