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
Go
Go
remove unnecessary hardcoded version
accf28a7dbdd46203c661d30b80326df4d447cea
<ide><path>api/server/middleware.go <ide> import ( <ide> "github.com/docker/docker/api" <ide> "github.com/docker/docker/api/server/httputils" <ide> "github.com/docker/docker/api/server/middleware" <del> "github.com/docker/docker/dockerversion" <ide> "github.com/docker/docker/pkg/authorization" <ide> ) <ide> <ide> import ( <ide> func (s *Server) handleWithGlobalMiddlewares(handler httputils.APIFunc) httputils.APIFunc { <ide> next := handler <ide> <del> handleVersion := middleware.NewVersionMiddleware(dockerversion.Version, api.DefaultVersion, api.MinVersion) <add> handleVersion := middleware.NewVersionMiddleware(s.cfg.Version, api.DefaultVersion, api.MinVersion) <ide> next = handleVersion(next) <ide> <ide> if s.cfg.EnableCors { <ide><path>api/server/server_test.go <ide> package server <ide> import ( <ide> "net/http" <ide> "net/http/httptest" <add> "strings" <ide> "testing" <ide> <ide> "github.com/docker/docker/api/server/httputils" <ide> import ( <ide> ) <ide> <ide> func TestMiddlewares(t *testing.T) { <del> cfg := &Config{} <add> cfg := &Config{ <add> Version: "0.1omega2", <add> } <ide> srv := &Server{ <ide> cfg: cfg, <ide> } <ide> func TestMiddlewares(t *testing.T) { <ide> if httputils.VersionFromContext(ctx) == "" { <ide> t.Fatalf("Expected version, got empty string") <ide> } <add> <add> if sv := w.Header().Get("Server"); !strings.Contains(sv, "Docker/0.1omega2") { <add> t.Fatalf("Expected server version in the header `Docker/0.1omega2`, got %s", sv) <add> } <add> <ide> return nil <ide> } <ide>
2
Python
Python
extract clientinfo to module level
1b568d73e1dfb838a3a0446e3a6063b9f27f04b8
<ide><path>airflow/providers/google/cloud/_internal_client/secret_manager_client.py <ide> <ide> import google <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <add> <ide> if sys.version_info >= (3, 8): <ide> from functools import cached_property <ide> else: <ide> from cached_property import cached_property <ide> <ide> from google.api_core.exceptions import InvalidArgument, NotFound, PermissionDenied <del>from google.api_core.gapic_v1.client_info import ClientInfo <ide> from google.cloud.secretmanager_v1 import SecretManagerServiceClient <ide> <ide> from airflow.utils.log.logging_mixin import LoggingMixin <del>from airflow.version import version <ide> <ide> SECRET_ID_PATTERN = r"^[a-zA-Z0-9-_]*$" <ide> <ide> def is_valid_secret_name(secret_name: str) -> bool: <ide> @cached_property <ide> def client(self) -> SecretManagerServiceClient: <ide> """Create an authenticated KMS client""" <del> _client = SecretManagerServiceClient( <del> credentials=self.credentials, client_info=ClientInfo(client_library_version='airflow_v' + version) <del> ) <add> _client = SecretManagerServiceClient(credentials=self.credentials, client_info=CLIENT_INFO) <ide> return _client <ide> <ide> def get_secret(self, secret_id: str, project_id: str, secret_version: str = 'latest') -> Optional[str]: <ide><path>airflow/providers/google/cloud/hooks/automl.py <ide> ListTableSpecsPager, <ide> ) <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <add> <ide> if sys.version_info >= (3, 8): <ide> from functools import cached_property <ide> else: <ide> def get_conn(self) -> AutoMlClient: <ide> :rtype: google.cloud.automl_v1beta1.AutoMlClient <ide> """ <ide> if self._client is None: <del> self._client = AutoMlClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = AutoMlClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @cached_property <ide> def prediction_client(self) -> PredictionServiceClient: <ide> :return: Google Cloud AutoML PredictionServiceClient client object. <ide> :rtype: google.cloud.automl_v1beta1.PredictionServiceClient <ide> """ <del> return PredictionServiceClient(credentials=self._get_credentials(), client_info=self.client_info) <add> return PredictionServiceClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide> def create_model( <ide><path>airflow/providers/google/cloud/hooks/bigquery.py <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.hooks.dbapi import DbApiHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> from airflow.utils.helpers import convert_camel_to_snake <ide> from airflow.utils.log.logging_mixin import LoggingMixin <ide> def get_client(self, project_id: Optional[str] = None, location: Optional[str] = <ide> :return: <ide> """ <ide> return Client( <del> client_info=self.client_info, <add> client_info=CLIENT_INFO, <ide> project=project_id, <ide> location=location, <ide> credentials=self._get_credentials(), <ide><path>airflow/providers/google/cloud/hooks/bigquery_dts.py <ide> ) <ide> from googleapiclient.discovery import Resource <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> DataTransferServiceClient: <ide> """ <ide> if not self._conn: <ide> self._conn = DataTransferServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info <add> credentials=self._get_credentials(), client_info=CLIENT_INFO <ide> ) <ide> return self._conn <ide> <ide><path>airflow/providers/google/cloud/hooks/bigtable.py <ide> from google.cloud.bigtable.table import ClusterState, Table <ide> from google.cloud.bigtable_admin_v2 import enums <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def _get_client(self, project_id: str): <ide> self._client = Client( <ide> project=project_id, <ide> credentials=self._get_credentials(), <del> client_info=self.client_info, <add> client_info=CLIENT_INFO, <ide> admin=True, <ide> ) <ide> return self._client <ide><path>airflow/providers/google/cloud/hooks/cloud_build.py <ide> from google.cloud.devtools.cloudbuild_v1.types import Build, BuildTrigger, RepoSource <ide> <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> # Time to sleep between active checks of the operation results <ide> def get_conn(self) -> CloudBuildClient: <ide> :rtype: `google.cloud.devtools.cloudbuild_v1.CloudBuildClient` <ide> """ <ide> if not self._client: <del> self._client = CloudBuildClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = CloudBuildClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide><path>airflow/providers/google/cloud/hooks/cloud_composer.py <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_environment_client(self) -> EnvironmentsClient: <ide> """Retrieves client library object that allow access Environments service.""" <ide> return EnvironmentsClient( <ide> credentials=self._get_credentials(), <del> client_info=self.client_info, <add> client_info=CLIENT_INFO, <ide> client_options=self.client_options, <ide> ) <ide> <ide> def get_image_versions_client( <ide> """Retrieves client library object that allow access Image Versions service.""" <ide> return ImageVersionsClient( <ide> credentials=self._get_credentials(), <del> client_info=self.client_info, <add> client_info=CLIENT_INFO, <ide> client_options=self.client_options, <ide> ) <ide> <ide><path>airflow/providers/google/cloud/hooks/datacatalog.py <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> <ide> def __init__( <ide> def get_conn(self) -> DataCatalogClient: <ide> """Retrieves client library object that allow access to Cloud Data Catalog service.""" <ide> if not self._client: <del> self._client = DataCatalogClient( <del> credentials=self._get_credentials(), client_info=self.client_info <del> ) <add> self._client = DataCatalogClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide><path>airflow/providers/google/cloud/hooks/dataproc.py <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> from airflow.version import version as airflow_version <ide> <ide> def get_cluster_client( <ide> client_options = {'api_endpoint': f'{region}-dataproc.googleapis.com:443'} <ide> <ide> return ClusterControllerClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def get_template_client( <ide> def get_template_client( <ide> client_options = {'api_endpoint': f'{region}-dataproc.googleapis.com:443'} <ide> <ide> return WorkflowTemplateServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def get_job_client( <ide> def get_job_client( <ide> client_options = {'api_endpoint': f'{region}-dataproc.googleapis.com:443'} <ide> <ide> return JobControllerClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def get_batch_client( <ide> def get_batch_client( <ide> client_options = {'api_endpoint': f'{region}-dataproc.googleapis.com:443'} <ide> <ide> return BatchControllerClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def wait_for_operation(self, operation: Operation, timeout: Optional[float] = None): <ide><path>airflow/providers/google/cloud/hooks/dataproc_metastore.py <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_dataproc_metastore_client(self) -> DataprocMetastoreClient: <ide> client_options = {'api_endpoint': 'metastore.googleapis.com:443'} <ide> <ide> return DataprocMetastoreClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def wait_for_operation(self, timeout: Optional[float], operation: Operation): <ide><path>airflow/providers/google/cloud/hooks/dlp.py <ide> ) <ide> <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> DLP_JOB_PATH_PATTERN = "^projects/[^/]+/dlpJobs/(?P<job>.*?)$" <ide> def get_conn(self) -> DlpServiceClient: <ide> :rtype: google.cloud.dlp_v2.DlpServiceClient <ide> """ <ide> if not self._client: <del> self._client = DlpServiceClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = DlpServiceClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide><path>airflow/providers/google/cloud/hooks/gcs.py <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.utils.helpers import normalize_directory_path <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> from airflow.utils import timezone <ide> from airflow.version import version <ide> def get_conn(self) -> storage.Client: <ide> """Returns a Google Cloud Storage service object.""" <ide> if not self._conn: <ide> self._conn = storage.Client( <del> credentials=self._get_credentials(), client_info=self.client_info, project=self.project_id <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, project=self.project_id <ide> ) <ide> <ide> return self._conn <ide><path>airflow/providers/google/cloud/hooks/kms.py <ide> from google.api_core.retry import Retry <ide> from google.cloud.kms_v1 import KeyManagementServiceClient <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> KeyManagementServiceClient: <ide> """ <ide> if not self._conn: <ide> self._conn = KeyManagementServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info <add> credentials=self._get_credentials(), client_info=CLIENT_INFO <ide> ) <ide> return self._conn <ide> <ide><path>airflow/providers/google/cloud/hooks/kubernetes_engine.py <ide> <ide> from airflow import version <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> OPERATIONAL_POLL_INTERVAL = 15 <ide> def get_conn(self) -> container_v1.ClusterManagerClient: <ide> """ <ide> if self._client is None: <ide> credentials = self._get_credentials() <del> self._client = container_v1.ClusterManagerClient( <del> credentials=credentials, client_info=self.client_info <del> ) <add> self._client = container_v1.ClusterManagerClient(credentials=credentials, client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> # To preserve backward compatibility <ide><path>airflow/providers/google/cloud/hooks/natural_language.py <ide> Document, <ide> ) <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> LanguageServiceClient: <ide> :rtype: google.cloud.language_v1.LanguageServiceClient <ide> """ <ide> if not self._conn: <del> self._conn = LanguageServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info <del> ) <add> self._conn = LanguageServiceClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._conn <ide> <ide> @GoogleBaseHook.quota_retry() <ide><path>airflow/providers/google/cloud/hooks/os_login.py <ide> from google.api_core.retry import Retry <ide> from google.cloud.oslogin_v1 import ImportSshPublicKeyResponse, OsLoginServiceClient <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> OsLoginServiceClient: <ide> if self._conn: <ide> return self._conn <ide> <del> self._conn = OsLoginServiceClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._conn = OsLoginServiceClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._conn <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide><path>airflow/providers/google/cloud/hooks/pubsub.py <ide> from typing import Dict, List, Optional, Sequence, Tuple, Union <ide> from uuid import uuid4 <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <add> <ide> if sys.version_info >= (3, 8): <ide> from functools import cached_property <ide> else: <ide> def get_conn(self) -> PublisherClient: <ide> :rtype: google.cloud.pubsub_v1.PublisherClient <ide> """ <ide> if not self._client: <del> self._client = PublisherClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = PublisherClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @cached_property <ide> def subscriber_client(self) -> SubscriberClient: <ide> :return: Google Cloud Pub/Sub client object. <ide> :rtype: google.cloud.pubsub_v1.SubscriberClient <ide> """ <del> return SubscriberClient(credentials=self._get_credentials(), client_info=self.client_info) <add> return SubscriberClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide> def publish( <ide><path>airflow/providers/google/cloud/hooks/spanner.py <ide> from google.longrunning.operations_grpc_pb2 import Operation <ide> <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def _get_client(self, project_id: str) -> Client: <ide> """ <ide> if not self._client: <ide> self._client = Client( <del> project=project_id, credentials=self._get_credentials(), client_info=self.client_info <add> project=project_id, credentials=self._get_credentials(), client_info=CLIENT_INFO <ide> ) <ide> return self._client <ide> <ide><path>airflow/providers/google/cloud/hooks/speech_to_text.py <ide> from google.cloud.speech_v1 import SpeechClient <ide> from google.cloud.speech_v1.types import RecognitionAudio, RecognitionConfig <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> SpeechClient: <ide> :rtype: google.cloud.speech_v1.SpeechClient <ide> """ <ide> if not self._client: <del> self._client = SpeechClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = SpeechClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @GoogleBaseHook.quota_retry() <ide><path>airflow/providers/google/cloud/hooks/tasks.py <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow.exceptions import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> CloudTasksClient: <ide> :rtype: google.cloud.tasks_v2.CloudTasksClient <ide> """ <ide> if self._client is None: <del> self._client = CloudTasksClient(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = CloudTasksClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide><path>airflow/providers/google/cloud/hooks/text_to_speech.py <ide> VoiceSelectionParams, <ide> ) <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> TextToSpeechClient: <ide> """ <ide> if not self._client: <ide> <del> self._client = TextToSpeechClient( <del> credentials=self._get_credentials(), client_info=self.client_info <del> ) <add> self._client = TextToSpeechClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> <ide> return self._client <ide> <ide><path>airflow/providers/google/cloud/hooks/translate.py <ide> <ide> from google.cloud.translate_v2 import Client <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> Client: <ide> :rtype: google.cloud.translate_v2.Client <ide> """ <ide> if not self._client: <del> self._client = Client(credentials=self._get_credentials(), client_info=self.client_info) <add> self._client = Client(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @GoogleBaseHook.quota_retry() <ide><path>airflow/providers/google/cloud/hooks/vertex_ai/custom_job.py <ide> from google.cloud.aiplatform_v1.types import CustomJob, PipelineJob, TrainingPipeline <ide> <ide> from airflow import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_pipeline_service_client( <ide> client_options = {'api_endpoint': f'{region}-aiplatform.googleapis.com:443'} <ide> <ide> return PipelineServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def get_job_service_client( <ide> def get_job_service_client( <ide> client_options = {'api_endpoint': f'{region}-aiplatform.googleapis.com:443'} <ide> <ide> return JobServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def get_custom_container_training_job( <ide><path>airflow/providers/google/cloud/hooks/vertex_ai/dataset.py <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <ide> from airflow import AirflowException <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_dataset_service_client(self, region: Optional[str] = None) -> DatasetSer <ide> client_options = {'api_endpoint': f'{region}-aiplatform.googleapis.com:443'} <ide> <ide> return DatasetServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info, client_options=client_options <add> credentials=self._get_credentials(), client_info=CLIENT_INFO, client_options=client_options <ide> ) <ide> <ide> def wait_for_operation(self, operation: Operation, timeout: Optional[float] = None): <ide><path>airflow/providers/google/cloud/hooks/video_intelligence.py <ide> from google.cloud.videointelligence_v1 import VideoIntelligenceServiceClient <ide> from google.cloud.videointelligence_v1.types import VideoContext <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import GoogleBaseHook <ide> <ide> <ide> def get_conn(self) -> VideoIntelligenceServiceClient: <ide> """ <ide> if not self._conn: <ide> self._conn = VideoIntelligenceServiceClient( <del> credentials=self._get_credentials(), client_info=self.client_info <add> credentials=self._get_credentials(), client_info=CLIENT_INFO <ide> ) <ide> return self._conn <ide> <ide><path>airflow/providers/google/cloud/hooks/vision.py <ide> from copy import deepcopy <ide> from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <add> <ide> if sys.version_info >= (3, 8): <ide> from functools import cached_property <ide> else: <ide> def get_conn(self) -> ProductSearchClient: <ide> :rtype: google.cloud.vision_v1.ProductSearchClient <ide> """ <ide> if not self._client: <del> self._client = ProductSearchClient( <del> credentials=self._get_credentials(), client_info=self.client_info <del> ) <add> self._client = ProductSearchClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> return self._client <ide> <ide> @cached_property <ide><path>airflow/providers/google/cloud/hooks/workflows.py <ide> from google.cloud.workflows_v1beta.services.workflows.pagers import ListWorkflowsPager <ide> from google.protobuf.field_mask_pb2 import FieldMask <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.providers.google.common.hooks.base_google import PROVIDE_PROJECT_ID, GoogleBaseHook <ide> <ide> <ide> class WorkflowsHook(GoogleBaseHook): <ide> <ide> def get_workflows_client(self) -> WorkflowsClient: <ide> """Returns WorkflowsClient.""" <del> return WorkflowsClient(credentials=self._get_credentials(), client_info=self.client_info) <add> return WorkflowsClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> <ide> def get_executions_client(self) -> ExecutionsClient: <ide> """Returns ExecutionsClient.""" <del> return ExecutionsClient(credentials=self._get_credentials(), client_info=self.client_info) <add> return ExecutionsClient(credentials=self._get_credentials(), client_info=CLIENT_INFO) <ide> <ide> @GoogleBaseHook.fallback_to_default_project_id <ide> def create_workflow( <ide><path>airflow/providers/google/cloud/log/gcs_task_handler.py <ide> import sys <ide> from typing import Collection, Optional <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <add> <ide> if sys.version_info >= (3, 8): <ide> from functools import cached_property <ide> else: <ide> from cached_property import cached_property <ide> <del>from google.api_core.client_info import ClientInfo <del> <ide> # not sure why but mypy complains on missing `storage` but it is clearly there and is importable <ide> from google.cloud import storage # type: ignore[attr-defined] <ide> <del>from airflow import version <ide> from airflow.providers.google.cloud.utils.credentials_provider import get_credentials_and_project_id <ide> from airflow.utils.log.file_task_handler import FileTaskHandler <ide> from airflow.utils.log.logging_mixin import LoggingMixin <ide> def client(self) -> storage.Client: <ide> ) <ide> return storage.Client( <ide> credentials=credentials, <del> client_info=ClientInfo(client_library_version='airflow_v' + version.version), <add> client_info=CLIENT_INFO, <ide> project=self.project_id if self.project_id else project_id, <ide> ) <ide> <ide><path>airflow/providers/google/cloud/log/stackdriver_task_handler.py <ide> from typing import Collection, Dict, List, Optional, Tuple, Type, Union <ide> from urllib.parse import urlencode <ide> <add>from airflow.providers.google.common.consts import CLIENT_INFO <add> <ide> if sys.version_info >= (3, 8): <ide> from functools import cached_property <ide> else: <ide> from cached_property import cached_property <ide> <del>from google.api_core.gapic_v1.client_info import ClientInfo <ide> from google.auth.credentials import Credentials <ide> from google.cloud import logging as gcp_logging <ide> from google.cloud.logging import Resource <ide> from google.cloud.logging.handlers.transports import BackgroundThreadTransport, Transport <ide> from google.cloud.logging_v2.services.logging_service_v2 import LoggingServiceV2Client <ide> from google.cloud.logging_v2.types import ListLogEntriesRequest, ListLogEntriesResponse <ide> <del>from airflow import version <ide> from airflow.models import TaskInstance <ide> from airflow.providers.google.cloud.utils.credentials_provider import get_credentials_and_project_id <ide> <ide> def _client(self) -> gcp_logging.Client: <ide> client = gcp_logging.Client( <ide> credentials=credentials, <ide> project=project, <del> client_info=ClientInfo(client_library_version='airflow_v' + version.version), <add> client_info=CLIENT_INFO, <ide> ) <ide> return client <ide> <ide> def _logging_service_client(self) -> LoggingServiceV2Client: <ide> credentials, _ = self._credentials_and_project <ide> client = LoggingServiceV2Client( <ide> credentials=credentials, <del> client_info=ClientInfo(client_library_version='airflow_v' + version.version), <add> client_info=CLIENT_INFO, <ide> ) <ide> return client <ide> <ide><path>airflow/providers/google/common/consts.py <ide> # KIND, either express or implied. See the License for the <ide> # specific language governing permissions and limitations <ide> # under the License. <add>from google.api_core.gapic_v1.client_info import ClientInfo <add> <add>from airflow import version <ide> <ide> GOOGLE_DEFAULT_DEFERRABLE_METHOD_NAME = 'execute_complete' <add> <add>CLIENT_INFO = ClientInfo(client_library_version='airflow_v' + version.version) <ide><path>airflow/providers/google/common/hooks/base_google.py <ide> import logging <ide> import os <ide> import tempfile <add>import warnings <ide> from contextlib import ExitStack, contextmanager <ide> from subprocess import check_output <ide> from typing import Any, Callable, Dict, Optional, Sequence, Tuple, TypeVar, Union, cast <ide> _get_target_principal_and_delegates, <ide> get_credentials_and_project_id, <ide> ) <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.utils.process_utils import patch_environ <ide> <ide> log = logging.getLogger(__name__) <ide> def client_info(self) -> ClientInfo: <ide> the Google Cloud. It is not supported by The Google APIs Python Client that use Discovery <ide> based APIs. <ide> """ <del> client_info = ClientInfo(client_library_version='airflow_v' + version.version) <del> return client_info <add> warnings.warn( <add> "This method is deprecated, please use `airflow.providers.google.common.consts.CLIENT_INFO`.", <add> DeprecationWarning, <add> stacklevel=2, <add> ) <add> return CLIENT_INFO <ide> <ide> @property <ide> def scopes(self) -> Sequence[str]: <ide><path>tests/providers/google/cloud/_internal_client/test_secret_manager_client.py <ide> from google.cloud.secretmanager_v1.types import AccessSecretVersionResponse <ide> <ide> from airflow.providers.google.cloud._internal_client.secret_manager_client import _SecretManagerClient <del>from airflow.version import version <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> <ide> INTERNAL_CLIENT_MODULE = "airflow.providers.google.cloud._internal_client.secret_manager_client" <add>INTERNAL_COMMON_MODULE = "airflow.providers.google.common.consts" <ide> <ide> <ide> class TestSecretManagerClient(TestCase): <ide> @mock.patch(INTERNAL_CLIENT_MODULE + ".SecretManagerServiceClient") <del> @mock.patch(INTERNAL_CLIENT_MODULE + ".ClientInfo") <del> def test_auth(self, mock_client_info, mock_secrets_client): <del> mock_client_info_mock = mock.MagicMock() <del> mock_client_info.return_value = mock_client_info_mock <add> def test_auth(self, mock_secrets_client): <ide> mock_secrets_client.return_value = mock.MagicMock() <ide> secrets_client = _SecretManagerClient(credentials="credentials") <ide> _ = secrets_client.client <del> mock_client_info.assert_called_with(client_library_version='airflow_v' + version) <del> mock_secrets_client.assert_called_with(credentials='credentials', client_info=mock_client_info_mock) <add> mock_secrets_client.assert_called_with(credentials='credentials', client_info=CLIENT_INFO) <ide> <ide> @mock.patch(INTERNAL_CLIENT_MODULE + ".SecretManagerServiceClient") <del> @mock.patch(INTERNAL_CLIENT_MODULE + ".ClientInfo") <del> def test_get_non_existing_key(self, mock_client_info, mock_secrets_client): <add> def test_get_non_existing_key(self, mock_secrets_client): <ide> mock_client = mock.MagicMock() <del> mock_client_info.return_value = mock.MagicMock() <ide> mock_secrets_client.return_value = mock_client <ide> mock_client.secret_version_path.return_value = "full-path" <ide> # The requested secret id or secret version does not exist <ide> def test_get_non_existing_key(self, mock_client_info, mock_secrets_client): <ide> mock_client.access_secret_version.assert_called_once_with('full-path') <ide> <ide> @mock.patch(INTERNAL_CLIENT_MODULE + ".SecretManagerServiceClient") <del> @mock.patch(INTERNAL_CLIENT_MODULE + ".ClientInfo") <del> def test_get_no_permissions(self, mock_client_info, mock_secrets_client): <add> def test_get_no_permissions(self, mock_secrets_client): <ide> mock_client = mock.MagicMock() <del> mock_client_info.return_value = mock.MagicMock() <ide> mock_secrets_client.return_value = mock_client <ide> mock_client.secret_version_path.return_value = "full-path" <ide> # No permissions for requested secret id <ide> def test_get_no_permissions(self, mock_client_info, mock_secrets_client): <ide> mock_client.access_secret_version.assert_called_once_with('full-path') <ide> <ide> @mock.patch(INTERNAL_CLIENT_MODULE + ".SecretManagerServiceClient") <del> @mock.patch(INTERNAL_CLIENT_MODULE + ".ClientInfo") <del> def test_get_invalid_id(self, mock_client_info, mock_secrets_client): <add> def test_get_invalid_id(self, mock_secrets_client): <ide> mock_client = mock.MagicMock() <del> mock_client_info.return_value = mock.MagicMock() <ide> mock_secrets_client.return_value = mock_client <ide> mock_client.secret_version_path.return_value = "full-path" <ide> # The requested secret id is using invalid character <ide> def test_get_invalid_id(self, mock_client_info, mock_secrets_client): <ide> mock_client.access_secret_version.assert_called_once_with('full-path') <ide> <ide> @mock.patch(INTERNAL_CLIENT_MODULE + ".SecretManagerServiceClient") <del> @mock.patch(INTERNAL_CLIENT_MODULE + ".ClientInfo") <del> def test_get_existing_key(self, mock_client_info, mock_secrets_client): <add> def test_get_existing_key(self, mock_secrets_client): <ide> mock_client = mock.MagicMock() <del> mock_client_info.return_value = mock.MagicMock() <ide> mock_secrets_client.return_value = mock_client <ide> mock_client.secret_version_path.return_value = "full-path" <ide> test_response = AccessSecretVersionResponse() <ide> def test_get_existing_key(self, mock_client_info, mock_secrets_client): <ide> mock_client.access_secret_version.assert_called_once_with('full-path') <ide> <ide> @mock.patch(INTERNAL_CLIENT_MODULE + ".SecretManagerServiceClient") <del> @mock.patch(INTERNAL_CLIENT_MODULE + ".ClientInfo") <del> def test_get_existing_key_with_version(self, mock_client_info, mock_secrets_client): <add> def test_get_existing_key_with_version(self, mock_secrets_client): <ide> mock_client = mock.MagicMock() <del> mock_client_info.return_value = mock.MagicMock() <ide> mock_secrets_client.return_value = mock_client <ide> mock_client.secret_version_path.return_value = "full-path" <ide> test_response = AccessSecretVersionResponse() <ide><path>tests/providers/google/cloud/hooks/test_automl.py <ide> from google.cloud.automl_v1beta1 import AutoMlClient <ide> <ide> from airflow.providers.google.cloud.hooks.automl import CloudAutoMLHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id <ide> <ide> CREDENTIALS = "test-creds" <del>CLIENT_INFO = "client-info" <ide> TASK_ID = "test-automl-hook" <ide> GCP_PROJECT_ID = "test-project" <ide> GCP_LOCATION = "test-location" <ide> def setUp(self) -> None: <ide> self.hook = CloudAutoMLHook() <ide> self.hook._get_credentials = mock.MagicMock(return_value=CREDENTIALS) # type: ignore <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.automl.GoogleBaseHook.client_info", <del> new_callable=lambda: CLIENT_INFO, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.automl.AutoMlClient") <del> def test_get_conn(self, mock_automl_client, mock_client_info): <add> def test_get_conn(self, mock_automl_client): <ide> self.hook.get_conn() <ide> mock_automl_client.assert_called_once_with(credentials=CREDENTIALS, client_info=CLIENT_INFO) <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.automl.GoogleBaseHook.client_info", <del> new_callable=lambda: CLIENT_INFO, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.automl.PredictionServiceClient") <del> def test_prediction_client(self, mock_prediction_client, mock_client_info): <add> def test_prediction_client(self, mock_prediction_client): <ide> client = self.hook.prediction_client # noqa <ide> mock_prediction_client.assert_called_once_with(credentials=CREDENTIALS, client_info=CLIENT_INFO) <ide> <ide><path>tests/providers/google/cloud/hooks/test_bigquery_dts.py <ide> from google.cloud.bigquery_datatransfer_v1.types import TransferConfig <ide> <ide> from airflow.providers.google.cloud.hooks.bigquery_dts import BiqQueryDataTransferServiceHook <del>from airflow.version import version <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id <ide> <ide> CREDENTIALS = "test-creds" <ide> def setUp(self) -> None: <ide> self.hook = BiqQueryDataTransferServiceHook() <ide> self.hook._get_credentials = mock.MagicMock(return_value=CREDENTIALS) # type: ignore <ide> <del> def test_version_information(self): <del> expected_version = "airflow_v" + version <del> assert expected_version == self.hook.client_info.client_library_version <del> <ide> def test_disable_auto_scheduling(self): <ide> expected = deepcopy(TRANSFER_CONFIG) <ide> expected.schedule_options.disable_auto_scheduling = True <ide><path>tests/providers/google/cloud/hooks/test_bigtable.py <ide> from google.cloud.bigtable_admin_v2 import enums <ide> <ide> from airflow.providers.google.cloud.hooks.bigtable import BigtableHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import ( <ide> GCP_PROJECT_ID_HOOK_UNIT_TEST, <ide> mock_base_gcp_hook_default_project_id, <ide> def setUp(self): <ide> ): <ide> self.bigtable_hook_no_default_project_id = BigtableHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.bigtable.BigtableHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.bigtable.BigtableHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.bigtable.Client") <del> def test_bigtable_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_bigtable_client_creation(self, mock_client, mock_get_creds): <ide> result = self.bigtable_hook_no_default_project_id._get_client(GCP_PROJECT_ID_HOOK_UNIT_TEST) <ide> mock_client.assert_called_once_with( <ide> project=GCP_PROJECT_ID_HOOK_UNIT_TEST, <ide> credentials=mock_get_creds.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> admin=True, <ide> ) <ide> assert mock_client.return_value == result <ide> def setUp(self): <ide> ): <ide> self.bigtable_hook_default_project_id = BigtableHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.bigtable.BigtableHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.bigtable.BigtableHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.bigtable.Client") <del> def test_bigtable_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_bigtable_client_creation(self, mock_client, mock_get_creds): <ide> result = self.bigtable_hook_default_project_id._get_client(GCP_PROJECT_ID_HOOK_UNIT_TEST) <ide> mock_client.assert_called_once_with( <ide> project=GCP_PROJECT_ID_HOOK_UNIT_TEST, <ide> credentials=mock_get_creds.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> admin=True, <ide> ) <ide> assert mock_client.return_value == result <ide><path>tests/providers/google/cloud/hooks/test_cloud_build.py <ide> <ide> <ide> import unittest <del>from unittest.mock import MagicMock, PropertyMock, patch <add>from unittest.mock import MagicMock, patch <ide> <ide> from airflow.providers.google.cloud.hooks.cloud_build import CloudBuildHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id <ide> <ide> PROJECT_ID = "cloud-build-project" <ide> def setUp(self): <ide> ): <ide> self.hook = CloudBuildHook(gcp_conn_id="test") <ide> <del> @patch( <del> "airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook.client_info", <del> new_callable=PropertyMock, <del> ) <ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildHook._get_credentials") <ide> @patch("airflow.providers.google.cloud.hooks.cloud_build.CloudBuildClient") <del> def test_cloud_build_service_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_cloud_build_service_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_dataproc.py <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks.dataproc import DataprocHook, DataProcJobBuilder <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.version import version <ide> <ide> AIRFLOW_VERSION = "v" + version.replace(".", "-").replace("+", "-") <ide> def setUp(self): <ide> self.hook = DataprocHook(gcp_conn_id="test") <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("ClusterControllerClient")) <del> def test_get_cluster_client(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_cluster_client(self, mock_client, mock_get_credentials): <ide> self.hook.get_cluster_client(region=GCP_LOCATION) <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options=None, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("ClusterControllerClient")) <del> def test_get_cluster_client_region(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_cluster_client_region(self, mock_client, mock_get_credentials): <ide> self.hook.get_cluster_client(region='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("ClusterControllerClient")) <del> def test_get_cluster_client_region_deprecation_warning( <del> self, mock_client, mock_client_info, mock_get_credentials <del> ): <add> def test_get_cluster_client_region_deprecation_warning(self, mock_client, mock_get_credentials): <ide> warning_message = ( <ide> "Parameter `location` will be deprecated. " <ide> "Please provide value through `region` parameter instead." <ide> def test_get_cluster_client_region_deprecation_warning( <ide> self.hook.get_cluster_client(location='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> assert warning_message == str(warnings[0].message) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("WorkflowTemplateServiceClient")) <del> def test_get_template_client_global(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_template_client_global(self, mock_client, mock_get_credentials): <ide> _ = self.hook.get_template_client() <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options=None, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("WorkflowTemplateServiceClient")) <del> def test_get_template_client_region(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_template_client_region(self, mock_client, mock_get_credentials): <ide> _ = self.hook.get_template_client(region='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("WorkflowTemplateServiceClient")) <del> def test_get_template_client_region_deprecation_warning( <del> self, mock_client, mock_client_info, mock_get_credentials <del> ): <add> def test_get_template_client_region_deprecation_warning(self, mock_client, mock_get_credentials): <ide> warning_message = ( <ide> "Parameter `location` will be deprecated. " <ide> "Please provide value through `region` parameter instead." <ide> def test_get_template_client_region_deprecation_warning( <ide> _ = self.hook.get_template_client(location='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> assert warning_message == str(warnings[0].message) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("JobControllerClient")) <del> def test_get_job_client(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_job_client(self, mock_client, mock_get_credentials): <ide> self.hook.get_job_client(region=GCP_LOCATION) <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options=None, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("JobControllerClient")) <del> def test_get_job_client_region(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_job_client_region(self, mock_client, mock_get_credentials): <ide> self.hook.get_job_client(region='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("JobControllerClient")) <del> def test_get_job_client_region_deprecation_warning( <del> self, mock_client, mock_client_info, mock_get_credentials <del> ): <add> def test_get_job_client_region_deprecation_warning(self, mock_client, mock_get_credentials): <ide> warning_message = ( <ide> "Parameter `location` will be deprecated. " <ide> "Please provide value through `region` parameter instead." <ide> def test_get_job_client_region_deprecation_warning( <ide> self.hook.get_job_client(location='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> assert warning_message == str(warnings[0].message) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("BatchControllerClient")) <del> def test_get_batch_client(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_batch_client(self, mock_client, mock_get_credentials): <ide> self.hook.get_batch_client(region=GCP_LOCATION) <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options=None, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("BatchControllerClient")) <del> def test_get_batch_client_region(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_batch_client_region(self, mock_client, mock_get_credentials): <ide> self.hook.get_batch_client(region='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> <ide> @mock.patch(DATAPROC_STRING.format("DataprocHook._get_credentials")) <del> @mock.patch(DATAPROC_STRING.format("DataprocHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(DATAPROC_STRING.format("BatchControllerClient")) <del> def test_get_batch_client_region_deprecation_warning( <del> self, mock_client, mock_client_info, mock_get_credentials <del> ): <add> def test_get_batch_client_region_deprecation_warning(self, mock_client, mock_get_credentials): <ide> warning_message = ( <ide> "Parameter `location` will be deprecated. " <ide> "Please provide value through `region` parameter instead." <ide> def test_get_batch_client_region_deprecation_warning( <ide> self.hook.get_batch_client(location='region1') <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> client_options={'api_endpoint': 'region1-dataproc.googleapis.com:443'}, <ide> ) <ide> assert warning_message == str(warnings[0].message) <ide><path>tests/providers/google/cloud/hooks/test_dlp.py <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks.dlp import CloudDLPHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id <ide> <ide> API_RESPONSE = {} # type: Dict[Any, Any] <ide> def setUp(self): <ide> ): <ide> self.hook = CloudDLPHook(gcp_conn_id="test") <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.dlp.CloudDLPHook.client_info", new_callable=mock.PropertyMock <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.dlp.CloudDLPHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.dlp.DlpServiceClient") <del> def test_dlp_service_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_dlp_service_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_gcs.py <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks import gcs <ide> from airflow.providers.google.cloud.hooks.gcs import _fallback_object_url_to_object_name_and_bucket_name <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.utils import timezone <ide> from airflow.version import version <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id <ide> def setUp(self): <ide> ): <ide> self.gcs_hook = gcs.GCSHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> 'airflow.providers.google.common.hooks.base_google.GoogleBaseHook.client_info', <del> new_callable=mock.PropertyMock, <del> return_value="CLIENT_INFO", <del> ) <ide> @mock.patch( <ide> BASE_STRING.format("GoogleBaseHook._get_credentials_and_project_id"), <ide> return_value=("CREDENTIALS", "PROJECT_ID"), <ide> ) <ide> @mock.patch(GCS_STRING.format('GoogleBaseHook.get_connection')) <ide> @mock.patch('google.cloud.storage.Client') <del> def test_storage_client_creation( <del> self, mock_client, mock_get_connection, mock_get_creds_and_project_id, mock_client_info <del> ): <add> def test_storage_client_creation(self, mock_client, mock_get_connection, mock_get_creds_and_project_id): <ide> hook = gcs.GCSHook() <ide> result = hook.get_conn() <ide> # test that Storage Client is called with required arguments <ide> mock_client.assert_called_once_with( <del> client_info="CLIENT_INFO", credentials="CREDENTIALS", project="PROJECT_ID" <add> client_info=CLIENT_INFO, credentials="CREDENTIALS", project="PROJECT_ID" <ide> ) <ide> assert mock_client.return_value == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_kms.py <ide> from unittest import mock <ide> <ide> from airflow.providers.google.cloud.hooks.kms import CloudKMSHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> <ide> Response = namedtuple("Response", ["plaintext", "ciphertext"]) <ide> <ide> def setUp(self): <ide> ): <ide> self.kms_hook = CloudKMSHook(gcp_conn_id="test") <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.kms.CloudKMSHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.kms.CloudKMSHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.kms.KeyManagementServiceClient") <del> def test_kms_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_kms_client_creation(self, mock_client, mock_get_creds): <ide> result = self.kms_hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, <del> client_info=mock_client_info.return_value, <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.kms_hook._conn == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_kubernetes_engine.py <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks.kubernetes_engine import GKEHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> <ide> TASK_ID = 'test-gke-cluster-operator' <ide> CLUSTER_NAME = 'test-cluster' <ide> class TestGKEHookClient(unittest.TestCase): <ide> def setUp(self): <ide> self.gke_hook = GKEHook(location=GKE_ZONE) <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.kubernetes_engine.GKEHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.kubernetes_engine.GKEHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.kubernetes_engine.container_v1.ClusterManagerClient") <del> def test_gke_cluster_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_gke_cluster_client_creation(self, mock_client, mock_get_creds): <ide> <ide> result = self.gke_hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.gke_hook._client == result <ide> <ide> def setUp(self): <ide> self.gke_hook._client = mock.Mock() <ide> <ide> @mock.patch('airflow.providers.google.cloud.hooks.kubernetes_engine.container_v1.ClusterManagerClient') <del> @mock.patch('airflow.providers.google.common.hooks.base_google.ClientInfo') <ide> @mock.patch('airflow.providers.google.cloud.hooks.kubernetes_engine.GKEHook._get_credentials') <del> def test_get_client(self, mock_get_credentials, mock_client_info, mock_client): <add> def test_get_client(self, mock_get_credentials, mock_client): <ide> self.gke_hook._client = None <ide> self.gke_hook.get_conn() <ide> assert mock_get_credentials.called <ide> mock_client.assert_called_once_with( <del> credentials=mock_get_credentials.return_value, client_info=mock_client_info.return_value <add> credentials=mock_get_credentials.return_value, client_info=CLIENT_INFO <ide> ) <ide> <ide> def test_get_operation(self): <ide><path>tests/providers/google/cloud/hooks/test_natural_language.py <ide> from google.cloud.language_v1.proto.language_service_pb2 import Document <ide> <ide> from airflow.providers.google.cloud.hooks.natural_language import CloudNaturalLanguageHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id <ide> <ide> API_RESPONSE = {} # type: Dict[Any, Any] <ide> def setUp(self): <ide> ): <ide> self.hook = CloudNaturalLanguageHook(gcp_conn_id="test") <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.natural_language.CloudNaturalLanguageHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch( <ide> "airflow.providers.google.cloud.hooks.natural_language.CloudNaturalLanguageHook._get_credentials" <ide> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.natural_language.LanguageServiceClient") <del> def test_language_service_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_language_service_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._conn == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_pubsub.py <ide> from parameterized import parameterized <ide> <ide> from airflow.providers.google.cloud.hooks.pubsub import PubSubException, PubSubHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from airflow.version import version <ide> <ide> BASE_STRING = 'airflow.providers.google.common.hooks.base_google.{}' <ide> def _generate_messages(self, count) -> List[ReceivedMessage]: <ide> for i in range(1, count + 1) <ide> ] <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.pubsub.PubSubHook.client_info", new_callable=mock.PropertyMock <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.pubsub.PubSubHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.pubsub.PublisherClient") <del> def test_publisher_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_publisher_client_creation(self, mock_client, mock_get_creds): <ide> assert self.pubsub_hook._client is None <ide> result = self.pubsub_hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.pubsub_hook._client == result <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.pubsub.PubSubHook.client_info", new_callable=mock.PropertyMock <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.pubsub.PubSubHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.pubsub.SubscriberClient") <del> def test_subscriber_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_subscriber_client_creation(self, mock_client, mock_get_creds): <ide> assert self.pubsub_hook._client is None <ide> result = self.pubsub_hook.subscriber_client <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> <ide> @mock.patch(PUBSUB_STRING.format('PubSubHook.get_conn')) <ide><path>tests/providers/google/cloud/hooks/test_spanner.py <ide> from unittest.mock import PropertyMock <ide> <ide> from airflow.providers.google.cloud.hooks.spanner import SpannerHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import ( <ide> GCP_PROJECT_ID_HOOK_UNIT_TEST, <ide> mock_base_gcp_hook_default_project_id, <ide> def setUp(self): <ide> ): <ide> self.spanner_hook_default_project_id = SpannerHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.spanner.SpannerHook.client_info", new_callable=mock.PropertyMock <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.spanner.SpannerHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.spanner.Client") <del> def test_spanner_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_spanner_client_creation(self, mock_client, mock_get_creds): <ide> result = self.spanner_hook_default_project_id._get_client(GCP_PROJECT_ID_HOOK_UNIT_TEST) <ide> mock_client.assert_called_once_with( <ide> project=GCP_PROJECT_ID_HOOK_UNIT_TEST, <ide> credentials=mock_get_creds.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> ) <ide> assert mock_client.return_value == result <ide> assert self.spanner_hook_default_project_id._client == result <ide> def setUp(self): <ide> ): <ide> self.spanner_hook_no_default_project_id = SpannerHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.spanner.SpannerHook.client_info", new_callable=mock.PropertyMock <del> ) <ide> @mock.patch( <ide> "airflow.providers.google.cloud.hooks.spanner.SpannerHook._get_credentials", <ide> return_value="CREDENTIALS", <ide> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.spanner.Client") <del> def test_spanner_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_spanner_client_creation(self, mock_client, mock_get_creds): <ide> result = self.spanner_hook_no_default_project_id._get_client(GCP_PROJECT_ID_HOOK_UNIT_TEST) <ide> mock_client.assert_called_once_with( <ide> project=GCP_PROJECT_ID_HOOK_UNIT_TEST, <ide> credentials=mock_get_creds.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> ) <ide> assert mock_client.return_value == result <ide> assert self.spanner_hook_no_default_project_id._client == result <ide><path>tests/providers/google/cloud/hooks/test_speech_to_text.py <ide> # <ide> <ide> import unittest <del>from unittest.mock import PropertyMock, patch <add>from unittest.mock import patch <ide> <ide> from airflow.providers.google.cloud.hooks.speech_to_text import CloudSpeechToTextHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id <ide> <ide> PROJECT_ID = "project-id" <ide> def setUp(self): <ide> ): <ide> self.gcp_speech_to_text_hook = CloudSpeechToTextHook(gcp_conn_id="test") <ide> <del> @patch( <del> "airflow.providers.google.cloud.hooks.speech_to_text.CloudSpeechToTextHook.client_info", <del> new_callable=PropertyMock, <del> ) <ide> @patch("airflow.providers.google.cloud.hooks.speech_to_text.CloudSpeechToTextHook._get_credentials") <ide> @patch("airflow.providers.google.cloud.hooks.speech_to_text.SpeechClient") <del> def test_speech_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_speech_client_creation(self, mock_client, mock_get_creds): <ide> result = self.gcp_speech_to_text_hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.gcp_speech_to_text_hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_tasks.py <ide> from google.cloud.tasks_v2.types import Queue, Task <ide> <ide> from airflow.providers.google.cloud.hooks.tasks import CloudTasksHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_no_default_project_id <ide> <ide> API_RESPONSE = {} # type: Dict[Any, Any] <ide> def setUp(self): <ide> ): <ide> self.hook = CloudTasksHook(gcp_conn_id="test") <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.tasks.CloudTasksHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.tasks.CloudTasksHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.tasks.CloudTasksClient") <del> def test_cloud_tasks_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_cloud_tasks_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_text_to_speech.py <ide> # <ide> <ide> import unittest <del>from unittest.mock import PropertyMock, patch <add>from unittest.mock import patch <ide> <ide> from airflow.providers.google.cloud.hooks.text_to_speech import CloudTextToSpeechHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id <ide> <ide> INPUT = {"text": "test text"} <ide> def setUp(self): <ide> ): <ide> self.gcp_text_to_speech_hook = CloudTextToSpeechHook(gcp_conn_id="test") <ide> <del> @patch( <del> "airflow.providers.google.cloud.hooks.text_to_speech.CloudTextToSpeechHook.client_info", <del> new_callable=PropertyMock, <del> ) <ide> @patch("airflow.providers.google.cloud.hooks.text_to_speech.CloudTextToSpeechHook._get_credentials") <ide> @patch("airflow.providers.google.cloud.hooks.text_to_speech.TextToSpeechClient") <del> def test_text_to_speech_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_text_to_speech_client_creation(self, mock_client, mock_get_creds): <ide> result = self.gcp_text_to_speech_hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.gcp_text_to_speech_hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_translate.py <ide> from unittest import mock <ide> <ide> from airflow.providers.google.cloud.hooks.translate import CloudTranslateHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id <ide> <ide> PROJECT_ID_TEST = 'project-id' <ide> def setUp(self): <ide> ): <ide> self.hook = CloudTranslateHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.translate.CloudTranslateHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.translate.CloudTranslateHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.translate.Client") <del> def test_translate_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_translate_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_video_intelligence.py <ide> from google.cloud.videointelligence_v1 import enums <ide> <ide> from airflow.providers.google.cloud.hooks.video_intelligence import CloudVideoIntelligenceHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id <ide> <ide> INPUT_URI = "gs://bucket-name/input-file" <ide> def setUp(self): <ide> ): <ide> self.hook = CloudVideoIntelligenceHook(gcp_conn_id="test") <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.video_intelligence.CloudVideoIntelligenceHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch( <ide> "airflow.providers.google.cloud.hooks.video_intelligence.CloudVideoIntelligenceHook._get_credentials" <ide> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.video_intelligence.VideoIntelligenceServiceClient") <del> def test_video_intelligence_service_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_video_intelligence_service_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._conn == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_vision.py <ide> <ide> from airflow.exceptions import AirflowException <ide> from airflow.providers.google.cloud.hooks.vision import ERR_DIFF_NAMES, ERR_UNABLE_TO_CREATE, CloudVisionHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> from tests.providers.google.cloud.utils.base_gcp_mock import mock_base_gcp_hook_default_project_id <ide> <ide> PROJECT_ID_TEST = 'project-id' <ide> def setUp(self): <ide> ): <ide> self.hook = CloudVisionHook(gcp_conn_id='test') <ide> <del> @mock.patch( <del> "airflow.providers.google.cloud.hooks.vision.CloudVisionHook.client_info", <del> new_callable=mock.PropertyMock, <del> ) <ide> @mock.patch("airflow.providers.google.cloud.hooks.vision.CloudVisionHook._get_credentials") <ide> @mock.patch("airflow.providers.google.cloud.hooks.vision.ProductSearchClient") <del> def test_product_search_client_creation(self, mock_client, mock_get_creds, mock_client_info): <add> def test_product_search_client_creation(self, mock_client, mock_get_creds): <ide> result = self.hook.get_conn() <del> mock_client.assert_called_once_with( <del> credentials=mock_get_creds.return_value, client_info=mock_client_info.return_value <del> ) <add> mock_client.assert_called_once_with(credentials=mock_get_creds.return_value, client_info=CLIENT_INFO) <ide> assert mock_client.return_value == result <ide> assert self.hook._client == result <ide> <ide><path>tests/providers/google/cloud/hooks/test_workflows.py <ide> from unittest import mock <ide> <ide> from airflow.providers.google.cloud.hooks.workflows import WorkflowsHook <add>from airflow.providers.google.common.consts import CLIENT_INFO <ide> <ide> BASE_PATH = "airflow.providers.google.cloud.hooks.workflows.{}" <ide> LOCATION = "europe-west1" <ide> def setup_method(self, _): <ide> self.hook = WorkflowsHook(gcp_conn_id="test") <ide> <ide> @mock.patch(BASE_PATH.format("WorkflowsHook._get_credentials")) <del> @mock.patch(BASE_PATH.format("WorkflowsHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(BASE_PATH.format("WorkflowsClient")) <del> def test_get_workflows_client(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_workflows_client(self, mock_client, mock_get_credentials): <ide> self.hook.get_workflows_client() <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> ) <ide> <ide> @mock.patch(BASE_PATH.format("WorkflowsHook._get_credentials")) <del> @mock.patch(BASE_PATH.format("WorkflowsHook.client_info"), new_callable=mock.PropertyMock) <ide> @mock.patch(BASE_PATH.format("ExecutionsClient")) <del> def test_get_executions_client(self, mock_client, mock_client_info, mock_get_credentials): <add> def test_get_executions_client(self, mock_client, mock_get_credentials): <ide> self.hook.get_executions_client() <ide> mock_client.assert_called_once_with( <ide> credentials=mock_get_credentials.return_value, <del> client_info=mock_client_info.return_value, <add> client_info=CLIENT_INFO, <ide> ) <ide> <ide> @mock.patch(BASE_PATH.format("WorkflowsHook.get_workflows_client"))
51
Javascript
Javascript
fix typo in core.helpers.js
ef1c4fb0cbd7c35f0affaa27bf589b6f3302fd8c
<ide><path>src/core/core.helpers.js <ide> <ide> //Declare root variable - window in the browser, global on the server <ide> var root = this, <del> previous = root.Chart; <add> Chart = root.Chart; <ide> <ide> //Global Chart helpers object for utility methods and classes <ide> var helpers = Chart.helpers = {};
1
Javascript
Javascript
prevent infinite loop in cffparser_parseheader
5f021b067c1228f3c74b26373415d3f31ce1643c
<ide><path>src/core/fonts.js <ide> var CFFParser = (function CFFParserClosure() { <ide> }, <ide> parseHeader: function CFFParser_parseHeader() { <ide> var bytes = this.bytes; <add> var bytesLength = bytes.length; <ide> var offset = 0; <ide> <del> while (bytes[offset] != 1) <add> // Prevent an infinite loop, by checking that the offset is within the <add> // bounds of the bytes array. Necessary in empty, or invalid, font files. <add> while (offset < bytesLength && bytes[offset] !== 1) { <ide> ++offset; <del> <del> if (offset !== 0) { <add> } <add> if (offset >= bytesLength) { <add> error('Invalid CFF header'); <add> } else if (offset !== 0) { <ide> info('cff data is shifted'); <ide> bytes = bytes.subarray(offset); <ide> this.bytes = bytes;
1
Text
Text
update description for docker plugin inspect
fdedc38f0c398a81360a90b627493872ef3c8a56
<ide><path>docs/reference/commandline/plugin_inspect.md <ide> parent = "smn_cli" <ide> # plugin inspect (experimental) <ide> <ide> ```markdown <del>Usage: docker plugin inspect PLUGIN <add>Usage: docker plugin inspect [OPTIONS] PLUGIN [PLUGIN...] <ide> <del>Inspect a plugin <add>Display detailed information on one or more plugins <ide> <ide> Options: <ide> -f, --format string Format the output using the given go template
1
Javascript
Javascript
use native promises
b12db7645e624e65b5af2fc23be64b66c2ca1a5d
<ide><path>local-cli/dependencies/dependencies.js <ide> * LICENSE file in the root directory of this source tree. An additional grant <ide> * of patent rights can be found in the PATENTS file in the same directory. <ide> */ <add>'use strict'; <ide> <add>const ReactPackager = require('../../packager/react-packager'); <add> <add>const denodeify = require('denodeify'); <ide> const fs = require('fs'); <ide> const path = require('path'); <del>const Promise = require('promise'); <del>const ReactPackager = require('../../packager/react-packager'); <ide> <ide> function dependencies(argv, config, args, packagerInstance) { <ide> const rootModuleAbsolutePath = args.entryFile; <ide> function dependencies(argv, config, args, packagerInstance) { <ide> } <ide> }); <ide> return writeToFile <del> ? Promise.denodeify(outStream.end).bind(outStream)() <add> ? denodeify(outStream.end).bind(outStream)() <ide> : Promise.resolve(); <ide> } <ide> )); <ide><path>packager/react-packager/src/AssetServer/__tests__/AssetServer-test.js <ide> jest.disableAutomock(); <ide> <ide> jest.mock('fs'); <ide> <del>const Promise = require('promise'); <del> <ide> const AssetServer = require('../'); <ide> const crypto = require('crypto'); <ide> const {EventEmitter} = require('events'); <ide><path>packager/react-packager/src/AssetServer/index.js <ide> */ <ide> 'use strict'; <ide> <del>const Promise = require('promise'); <del> <ide> const crypto = require('crypto'); <ide> const declareOpts = require('../lib/declareOpts'); <add>const denodeify = require('denodeify'); <ide> const fs = require('fs'); <ide> const getAssetDataFromName = require('../node-haste').getAssetDataFromName; <ide> const path = require('path'); <ide> function timeoutableDenodeify(fsFunc, timeout) { <ide> return function raceWrapper(...args) { <ide> return Promise.race([ <ide> createTimeoutPromise(timeout), <del> Promise.denodeify(fsFunc).apply(this, args) <add> denodeify(fsFunc).apply(this, args) <ide> ]); <ide> }; <ide> } <ide><path>packager/react-packager/src/Bundler/__tests__/Bundle-test.js <ide> jest.disableAutomock(); <ide> <ide> const Bundle = require('../Bundle'); <ide> const ModuleTransport = require('../../lib/ModuleTransport'); <del>const Promise = require('Promise'); <ide> const SourceMapGenerator = require('source-map').SourceMapGenerator; <ide> const crypto = require('crypto'); <ide> <ide><path>packager/react-packager/src/Bundler/index.js <ide> <ide> 'use strict'; <ide> <del>const Promise = require('promise'); <del> <ide> const assert = require('assert'); <ide> const fs = require('fs'); <ide> const path = require('path'); <ide> const ModuleTransport = require('../lib/ModuleTransport'); <ide> const declareOpts = require('../lib/declareOpts'); <ide> const imageSize = require('image-size'); <ide> const version = require('../../../../package.json').version; <add>const denodeify = require('denodeify'); <ide> <ide> import AssetServer from '../AssetServer'; <ide> import Module from '../node-haste/Module'; <ide> import ResolutionResponse from '../node-haste/DependencyGraph/ResolutionResponse'; <ide> <del>const sizeOf = Promise.denodeify(imageSize); <add>const sizeOf = denodeify(imageSize); <ide> <ide> const noop = () => {}; <ide> <ide><path>packager/react-packager/src/JSTransformer/index.js <ide> 'use strict'; <ide> <ide> const Logger = require('../Logger'); <del>const Promise = require('promise'); <ide> <ide> const declareOpts = require('../lib/declareOpts'); <add>const denodeify = require('denodeify'); <ide> const os = require('os'); <ide> const util = require('util'); <ide> const workerFarm = require('worker-farm'); <ide> class Transformer { <ide> ['minify', 'transformAndExtractDependencies'], <ide> opts.transformTimeoutInterval, <ide> ); <del> this._transform = Promise.denodeify(this._workers.transformAndExtractDependencies); <del> this.minify = Promise.denodeify(this._workers.minify); <add> this._transform = denodeify(this._workers.transformAndExtractDependencies); <add> this.minify = denodeify(this._workers.minify); <ide> } <ide> } <ide> <ide><path>packager/react-packager/src/Server/index.js <ide> const getPlatformExtension = require('../node-haste').getPlatformExtension; <ide> const Bundler = require('../Bundler'); <ide> const MultipartResponse = require('./MultipartResponse'); <ide> const ProgressBar = require('progress'); <del>const Promise = require('promise'); <ide> const SourceMapConsumer = require('source-map').SourceMapConsumer; <ide> <ide> const declareOpts = require('../lib/declareOpts'); <ide> class Server { <ide> // This is safe as the asset url contains a hash of the asset. <ide> res.setHeader('Cache-Control', 'max-age=31536000'); <ide> res.end(this._rangeRequestMiddleware(req, res, data, assetPath)); <add> print(log(createActionEndEntry(processingAssetRequestLogEntry)), ['asset']); <ide> }, <ide> error => { <ide> console.error(error.stack); <ide> res.writeHead('404'); <ide> res.end('Asset not found'); <ide> } <del> ).done(() => { <del> print(log(createActionEndEntry(processingAssetRequestLogEntry)), ['asset']); <del> }); <add> ); <ide> } <ide> <ide> optionsHash(options) { <ide> class Server { <ide> }); <ide> }); <ide> }).then( <del> stack => res.end(JSON.stringify({stack: stack})), <add> stack => { <add> res.end(JSON.stringify({stack: stack})); <add> print(log(createActionEndEntry(symbolicatingLogEntry))); <add> }, <ide> error => { <ide> console.error(error.stack || error); <ide> res.statusCode = 500; <ide> res.end(JSON.stringify({error: error.message})); <ide> } <del> ).done(() => { <del> print(log(createActionEndEntry(symbolicatingLogEntry))); <del> }); <add> ); <ide> } <ide> <ide> _sourceMapForURL(reqUrl) {
7
Mixed
Javascript
add runtime deprecate for file stream open()
773769df60ac4f2448fa88b2ece035de2512928f
<ide><path>doc/api/deprecations.md <ide> Type: Documentation-only (supports [`--pending-deprecation`][]) <ide> The `process._tickCallback` property was never documented as <ide> an officially supported API. <ide> <add><a id="DEP0XXX"></a> <add>### DEP0XXX: `WriteStream.open()` and `ReadStream.open()` are internal <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/29061 <add> description: Runtime deprecation. <add>--> <add> <add>Type: Runtime <add> <add>[`WriteStream.open()`][] and [`ReadStream.open()`][] are undocumented internal <add>APIs that do not make sense to use in userland. File streams should always be <add>opened through their corresponding factory methods [`fs.createWriteStream()`][] <add>and [`fs.createReadStream()`][]) or by passing a file descriptor in options. <add> <ide> [`--pending-deprecation`]: cli.html#cli_pending_deprecation <ide> [`--throw-deprecation`]: cli.html#cli_throw_deprecation <ide> [`Buffer.allocUnsafeSlow(size)`]: buffer.html#buffer_class_method_buffer_allocunsafeslow_size <ide> an officially supported API. <ide> [`Decipher`]: crypto.html#crypto_class_decipher <ide> [`EventEmitter.listenerCount(emitter, eventName)`]: events.html#events_eventemitter_listenercount_emitter_eventname <ide> [`REPLServer.clearBufferedCommand()`]: repl.html#repl_replserver_clearbufferedcommand <add>[`ReadStream.open()`]: fs.html#fs_class_fs_readstream <ide> [`Server.connections`]: net.html#net_server_connections <ide> [`Server.getConnections()`]: net.html#net_server_getconnections_callback <ide> [`Server.listen({fd: <number>})`]: net.html#net_server_listen_handle_backlog_callback <ide> [`SlowBuffer`]: buffer.html#buffer_class_slowbuffer <add>[`WriteStream.open()`]: fs.html#fs_class_fs_writestream <ide> [`assert`]: assert.html <ide> [`asyncResource.runInAsyncScope()`]: async_hooks.html#async_hooks_asyncresource_runinasyncscope_fn_thisarg_args <ide> [`child_process`]: child_process.html <ide> an officially supported API. <ide> [`ecdh.setPublicKey()`]: crypto.html#crypto_ecdh_setpublickey_publickey_encoding <ide> [`emitter.listenerCount(eventName)`]: events.html#events_emitter_listenercount_eventname <ide> [`fs.access()`]: fs.html#fs_fs_access_path_mode_callback <add>[`fs.createReadStream()`]: fs.html#fs_fs_createreadstream_path_options <add>[`fs.createWriteStream()`]: fs.html#fs_fs_createwritestream_path_options <ide> [`fs.exists(path, callback)`]: fs.html#fs_fs_exists_path_callback <ide> [`fs.lchmod(path, mode, callback)`]: fs.html#fs_fs_lchmod_path_mode_callback <ide> [`fs.lchmodSync(path, mode)`]: fs.html#fs_fs_lchmodsync_path_mode <ide><path>lib/internal/fs/streams.js <ide> const { Math, Object } = primordials; <ide> const { <ide> ERR_OUT_OF_RANGE <ide> } = require('internal/errors').codes; <add>const internalUtil = require('internal/util'); <ide> const { validateNumber } = require('internal/validators'); <ide> const fs = require('fs'); <ide> const { Buffer } = require('buffer'); <ide> function ReadStream(path, options) { <ide> } <ide> <ide> if (typeof this.fd !== 'number') <del> this.open(); <add> _openReadFs(this); <ide> <ide> this.on('end', function() { <ide> if (this.autoClose) { <ide> function ReadStream(path, options) { <ide> Object.setPrototypeOf(ReadStream.prototype, Readable.prototype); <ide> Object.setPrototypeOf(ReadStream, Readable); <ide> <del>ReadStream.prototype.open = function() { <del> fs.open(this.path, this.flags, this.mode, (er, fd) => { <add>const openReadFs = internalUtil.deprecate(function() { <add> _openReadFs(this); <add>}, 'ReadStream.prototype.open() is deprecated', 'DEP0XXX'); <add>ReadStream.prototype.open = openReadFs; <add> <add>function _openReadFs(stream) { <add> // Backwards compat for overriden open. <add> if (stream.open !== openReadFs) { <add> stream.open(); <add> return; <add> } <add> <add> fs.open(stream.path, stream.flags, stream.mode, (er, fd) => { <ide> if (er) { <del> if (this.autoClose) { <del> this.destroy(); <add> if (stream.autoClose) { <add> stream.destroy(); <ide> } <del> this.emit('error', er); <add> stream.emit('error', er); <ide> return; <ide> } <ide> <del> this.fd = fd; <del> this.emit('open', fd); <del> this.emit('ready'); <add> stream.fd = fd; <add> stream.emit('open', fd); <add> stream.emit('ready'); <ide> // Start the flow of data. <del> this.read(); <add> stream.read(); <ide> }); <del>}; <add>} <ide> <ide> ReadStream.prototype._read = function(n) { <ide> if (typeof this.fd !== 'number') { <ide> function WriteStream(path, options) { <ide> this.setDefaultEncoding(options.encoding); <ide> <ide> if (typeof this.fd !== 'number') <del> this.open(); <add> _openWriteFs(this); <ide> } <ide> Object.setPrototypeOf(WriteStream.prototype, Writable.prototype); <ide> Object.setPrototypeOf(WriteStream, Writable); <ide> WriteStream.prototype._final = function(callback) { <ide> callback(); <ide> }; <ide> <del>WriteStream.prototype.open = function() { <del> fs.open(this.path, this.flags, this.mode, (er, fd) => { <add>const openWriteFs = internalUtil.deprecate(function() { <add> _openWriteFs(this); <add>}, 'WriteStream.prototype.open() is deprecated', 'DEP0XXX'); <add>WriteStream.prototype.open = openWriteFs; <add> <add>function _openWriteFs(stream) { <add> // Backwards compat for overriden open. <add> if (stream.open !== openWriteFs) { <add> stream.open(); <add> return; <add> } <add> <add> fs.open(stream.path, stream.flags, stream.mode, (er, fd) => { <ide> if (er) { <del> if (this.autoClose) { <del> this.destroy(); <add> if (stream.autoClose) { <add> stream.destroy(); <ide> } <del> this.emit('error', er); <add> stream.emit('error', er); <ide> return; <ide> } <ide> <del> this.fd = fd; <del> this.emit('open', fd); <del> this.emit('ready'); <add> stream.fd = fd; <add> stream.emit('open', fd); <add> stream.emit('ready'); <ide> }); <del>}; <add>} <ide> <ide> <ide> WriteStream.prototype._write = function(data, encoding, cb) { <ide><path>test/parallel/test-fs-read-stream-patch-open.js <add>'use strict'; <add>const common = require('../common'); <add>const fs = require('fs'); <add> <add>common.expectWarning( <add> 'DeprecationWarning', <add> 'ReadStream.prototype.open() is deprecated', 'DEP0XXX'); <add>const s = fs.createReadStream('asd') <add> // We don't care about errors in this test. <add> .on('error', () => {}); <add>s.open(); <add> <add>// Allow overriding open(). <add>fs.ReadStream.prototype.open = common.mustCall(); <add>fs.createReadStream('asd'); <ide><path>test/parallel/test-fs-write-stream-patch-open.js <add>'use strict'; <add>const common = require('../common'); <add>const fs = require('fs'); <add> <add>const tmpdir = require('../common/tmpdir'); <add> <add>// Run in a child process because 'out' is opened twice, blocking the tmpdir <add>// and preventing cleanup. <add>if (process.argv[2] !== 'child') { <add> // Parent <add> const assert = require('assert'); <add> const { fork } = require('child_process'); <add> tmpdir.refresh(); <add> <add> // Run test <add> const child = fork(__filename, ['child'], { stdio: 'inherit' }); <add> child.on('exit', common.mustCall(function(code) { <add> assert.strictEqual(code, 0); <add> })); <add> <add> return; <add>} <add> <add>// Child <add> <add>common.expectWarning( <add> 'DeprecationWarning', <add> 'WriteStream.prototype.open() is deprecated', 'DEP0XXX'); <add>const s = fs.createWriteStream(`${tmpdir.path}/out`); <add>s.open(); <add> <add>// Allow overriding open(). <add>fs.WriteStream.prototype.open = common.mustCall(); <add>fs.createWriteStream('asd');
4
Python
Python
fix build breakage
827bc405c59d98251055ea93e0a6392925d713a6
<ide><path>numpy/distutils/fcompiler/__init__.py <ide> def get_library_dirs(self): <ide> <ide> def get_version(self, force=False, ok_status=[0]): <ide> assert self._is_customised <del> return CCompiler.get_version(force=force, ok_status=ok_status) <add> return CCompiler.get_version(self, force=force, ok_status=ok_status) <ide> <ide> ############################################################ <ide>
1
Python
Python
improve error message when loading models from hub
46efc5802458e91a702528332d76d464061d201f
<ide><path>src/transformers/configuration_utils.py <ide> def get_config_dict( <ide> logger.error(err) <ide> msg = ( <ide> f"Can't load config for '{pretrained_model_name_or_path}'. Make sure that:\n\n" <del> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n\n" <add> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n" <add> f" (make sure '{pretrained_model_name_or_path}' is not a path to a local directory with something else, in that case)\n\n" <ide> f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing a {CONFIG_NAME} file\n\n" <ide> ) <ide> <ide><path>src/transformers/feature_extraction_utils.py <ide> def get_feature_extractor_dict( <ide> logger.error(err) <ide> msg = ( <ide> f"Can't load feature extractor for '{pretrained_model_name_or_path}'. Make sure that:\n\n" <del> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n\n" <add> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n" <add> f" (make sure '{pretrained_model_name_or_path}' is not a path to a local directory with something else, in that case)\n\n" <ide> f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing a {FEATURE_EXTRACTOR_NAME} file\n\n" <ide> ) <ide> raise EnvironmentError(msg) <ide><path>src/transformers/modeling_flax_utils.py <ide> def from_pretrained( <ide> logger.error(err) <ide> msg = ( <ide> f"Can't load weights for '{pretrained_model_name_or_path}'. Make sure that:\n\n" <del> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n\n" <add> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n" <add> f" (make sure '{pretrained_model_name_or_path}' is not a path to a local directory with something else, in that case)\n\n" <ide> f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing a file named {WEIGHTS_NAME}.\n\n" <ide> ) <ide> raise EnvironmentError(msg) <ide><path>src/transformers/modeling_tf_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs): <ide> logger.error(err) <ide> msg = ( <ide> f"Can't load weights for '{pretrained_model_name_or_path}'. Make sure that:\n\n" <del> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n\n" <add> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n" <add> f" (make sure '{pretrained_model_name_or_path}' is not a path to a local directory with something else, in that case)\n\n" <ide> f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing a file named one of {TF2_WEIGHTS_NAME}, {WEIGHTS_NAME}.\n\n" <ide> ) <ide> raise EnvironmentError(msg) <ide><path>src/transformers/modeling_utils.py <ide> def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P <ide> logger.error(err) <ide> msg = ( <ide> f"Can't load weights for '{pretrained_model_name_or_path}'. Make sure that:\n\n" <del> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n\n" <add> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n" <add> f" (make sure '{pretrained_model_name_or_path}' is not a path to a local directory with something else, in that case)\n\n" <ide> f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing a file named one of {WEIGHTS_NAME}, {TF2_WEIGHTS_NAME}, {TF_WEIGHTS_NAME}\n\n" <ide> ) <ide> <ide><path>src/transformers/tokenization_utils_base.py <ide> def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], <ide> if all(full_file_name is None for full_file_name in resolved_vocab_files.values()): <ide> msg = ( <ide> f"Can't load tokenizer for '{pretrained_model_name_or_path}'. Make sure that:\n\n" <del> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n\n" <add> f"- '{pretrained_model_name_or_path}' is a correct model identifier listed on 'https://huggingface.co/models'\n" <add> f" (make sure '{pretrained_model_name_or_path}' is not a path to a local directory with something else, in that case)\n\n" <ide> f"- or '{pretrained_model_name_or_path}' is the correct path to a directory containing relevant tokenizer files\n\n" <ide> ) <ide>
6
Text
Text
register zsc for the inference api
e7aa64838cc604abf7a49e69ca0ffe7af683d8ca
<ide><path>model_cards/facebook/bart-large-mnli/README.md <ide> --- <ide> license: mit <ide> thumbnail: https://huggingface.co/front/thumbnails/facebook.png <add>pipeline_tag: zero-shot-classification <ide> ---
1
Ruby
Ruby
fix whitespace and unsupported method args
d4cc1e33b80a546a58bcd2eaa49ea4c5e9682cbc
<ide><path>lib/arel/visitors/to_sql.rb <ide> def quoted o, a <ide> quote(o, column_for(a)) <ide> end <ide> <del> def unsupported o, a <add> def unsupported o <ide> raise "unsupported: #{o.class.name}" <ide> end <ide> <ide><path>lib/arel/visitors/visitor.rb <ide> def dispatch <ide> end <ide> <ide> def visit object <del> send dispatch[object.class], object <add> send dispatch[object.class], object <ide> rescue NoMethodError => e <ide> raise e if respond_to?(dispatch[object.class], true) <ide> superklass = object.class.ancestors.find { |klass|
2
Text
Text
fix docs for next/image unconfigured hosts
5e6b008b561caf2710ab7be63320a3d549474a5b
<ide><path>errors/next-image-unconfigured-host.md <ide> <ide> #### Why This Error Occurred <ide> <del>On one of your pages that leverages the `next/image` component, you passed a `src` value that uses a hostname in the URL that isn't defined in the `images.domains` config in `next.config.js`. <add>One of your pages that leverages the `next/image` component, passed a `src` value that uses a hostname in the URL that isn't defined in the `images.remotePatterns` or `images.domains` in `next.config.js`. <ide> <ide> #### Possible Ways to Fix It <ide> <del>Add the hostname of your URL to the `images.domains` config in `next.config.js`: <add>Add the protocol, hostname, port, and pathname to the `images.remotePatterns` config in `next.config.js`: <add> <add>```js <add>// next.config.js <add>module.exports = { <add> images: { <add> remotePatterns: [ <add> { <add> protocol: 'https', <add> hostname: 'example.com', <add> port: '', <add> pathname: '/account123/**', <add> }, <add> ], <add> }, <add>} <add>``` <add> <add>If you are using an older version of Next.js prior to 12.3.0, you can use `images.domains` instead: <ide> <ide> ```js <ide> // next.config.js
1
Text
Text
add v3.5.0-beta.3 to changelog
a835354b5f91454403caa21fc8b9fc267b3483be
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.5.0-beta.3 (September 24, 2018) <add> <add>- [#16978](https://github.com/emberjs/ember.js/pull/16978) [BUGFIX] Properly teardown alias <add>- [#16999](https://github.com/emberjs/ember.js/pull/16999) [BUGFIX] Fix mouseEnter/Leave event delegation w/o jQuery <add> <ide> ### v3.5.0-beta.2 (September 10, 2018) <ide> <ide> - [#16933](https://github.com/emberjs/ember.js/pull/16933) [BUGFIX] Update glimmer-vm packages to 0.38.8
1
Mixed
Python
update cache_dir in readme and examples
05053d163cbd6021e47487699e4e2de36c3b7720
<ide><path>README.md <ide> Here is a detailed documentation of the classes in the package and how to use th <ide> To load one of Google AI's pre-trained models or a PyTorch saved model (an instance of `BertForPreTraining` saved with `torch.save()`), the PyTorch model classes and the tokenizer can be instantiated as <ide> <ide> ```python <del>model = BERT_CLASS.from_pretrain(PRE_TRAINED_MODEL_NAME_OR_PATH) <add>model = BERT_CLASS.from_pretrain(PRE_TRAINED_MODEL_NAME_OR_PATH, cache_dir=None) <ide> ``` <ide> <ide> where <ide> <ide> - `BERT_CLASS` is either the `BertTokenizer` class (to load the vocabulary) or one of the six PyTorch model classes (to load the pre-trained weights): `BertModel`, `BertForMaskedLM`, `BertForNextSentencePrediction`, `BertForPreTraining`, `BertForSequenceClassification` or `BertForQuestionAnswering`, and <del> <ide> - `PRE_TRAINED_MODEL_NAME_OR_PATH` is either: <ide> <ide> - the shortcut name of a Google AI's pre-trained model selected in the list: <ide> where <ide> - `bert_config.json` a configuration file for the model, and <ide> - `pytorch_model.bin` a PyTorch dump of a pre-trained instance `BertForPreTraining` (saved with the usual `torch.save()`) <ide> <del>If `PRE_TRAINED_MODEL_NAME_OR_PATH` is a shortcut name, the pre-trained weights will be downloaded from AWS S3 (see the links [here](pytorch_pretrained_bert/modeling.py)) and stored in a cache folder to avoid future download (the cache folder can be found at `~/.pytorch_pretrained_bert/`). <add> If `PRE_TRAINED_MODEL_NAME_OR_PATH` is a shortcut name, the pre-trained weights will be downloaded from AWS S3 (see the links [here](pytorch_pretrained_bert/modeling.py)) and stored in a cache folder to avoid future download (the cache folder can be found at `~/.pytorch_pretrained_bert/`). <add>- `cache_dir` can be an optional path to a specific directory to download and cache the pre-trained model weights. This option is useful in particular when you are using distributed training: to avoid concurrent access to the same weights you can set for example `cache_dir='./pretrained_model_{}'.format(args.local_rank)` (see the section on distributed training for more information) <ide> <ide> Example: <ide> ```python <ide><path>examples/run_classifier.py <ide> def main(): <ide> len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs) <ide> <ide> # Prepare model <del> model = BertForSequenceClassification.from_pretrained(args.bert_model, len(label_list)) <add> model = BertForSequenceClassification.from_pretrained(args.bert_model, len(label_list), <add> cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank)) <ide> if args.fp16: <ide> model.half() <ide> model.to(device) <ide><path>examples/run_squad.py <ide> def main(): <ide> len(train_examples) / args.train_batch_size / args.gradient_accumulation_steps * args.num_train_epochs) <ide> <ide> # Prepare model <del> model = BertForQuestionAnswering.from_pretrained(args.bert_model) <add> model = BertForQuestionAnswering.from_pretrained(args.bert_model, <add> cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank)) <ide> if args.fp16: <ide> model.half() <ide> model.to(device) <ide><path>pytorch_pretrained_bert/__init__.py <ide> BertForMaskedLM, BertForNextSentencePrediction, <ide> BertForSequenceClassification, BertForQuestionAnswering) <ide> from .optimization import BertAdam <add>from .file_utils import PYTORCH_PRETRAINED_BERT_CACHE
4
Javascript
Javascript
initialize data object when replaced
9e06f90d14365e7a313acfa57042daf000989853
<ide><path>src/core/core.config.js <ide> function initOptions(config) { <ide> options.scales = mergeScaleConfig(config, options); <ide> } <ide> <del>function initConfig(config) { <del> config = config || {}; <del> <del> const data = config.data = config.data || {datasets: [], labels: []}; <add>function initData(data) { <add> data = data || {}; <ide> data.datasets = data.datasets || []; <ide> data.labels = data.labels || []; <add> return data; <add>} <add> <add>function initConfig(config) { <add> config = config || {}; <add> config.data = initData(config.data); <ide> <ide> initOptions(config); <ide> <ide> export default class Config { <ide> } <ide> <ide> set data(data) { <del> this._config.data = data; <add> this._config.data = initData(data); <ide> } <ide> <ide> get options() { <ide><path>test/specs/core.controller.tests.js <ide> describe('Chart', function() { <ide> expect(createChart).toThrow(new Error('"area" is not a registered controller.')); <ide> }); <ide> <add> it('should initialize the data object', function() { <add> const chart = acquireChart({type: 'bar'}); <add> expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []})); <add> chart.data = {}; <add> expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []})); <add> chart.data = null; <add> expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []})); <add> chart.data = undefined; <add> expect(chart.data).toEqual(jasmine.objectContaining({labels: [], datasets: []})); <add> }); <add> <ide> describe('should disable hover', function() { <ide> it('when options.hover=false', function() { <ide> var chart = acquireChart({
2
PHP
PHP
implement random fix from 5.0 in 5.1
08fc7fa9350032582ad4e775416e9642d8cde2a2
<ide><path>src/Illuminate/Support/Str.php <ide> public static function random($length = 16) <ide> if (function_exists('random_bytes')) { <ide> $bytes = random_bytes($length * 2); <ide> } elseif (function_exists('openssl_random_pseudo_bytes')) { <del> $bytes = openssl_random_pseudo_bytes($length * 2); <add> $bytes = openssl_random_pseudo_bytes($length * 2, $strong); <add> if ($bytes === false || $strong === false) { <add> throw new RuntimeException('Unable to generate random string.'); <add> } <ide> } else { <ide> throw new RuntimeException('OpenSSL extension is required for PHP 5 users.'); <ide> } <ide> <del> if ($bytes === false) { <del> throw new RuntimeException('Unable to generate random string.'); <del> } <del> <ide> return substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $length); <ide> } <ide>
1
Python
Python
add a test case for it
1657e6b6ff04e17025c5946915585d95992283ae
<ide><path>libcloud/test/dns/test_cloudflare.py <ide> def test_create_record(self): <ide> self.assertEqual(record.type, 'A') <ide> self.assertEqual(record.data, '127.0.0.3') <ide> <add> def test_create_record_error_with_error_chain(self): <add> zone = self.driver.list_zones()[0] <add> <add> CloudFlareMockHttp.type = 'error_chain_error' <add> <add> expected_msg = r'.*1004: DNS Validation Error \(error chain: 9011: Length of content is invalid\)' <add> <add> self.assertRaisesRegex(LibcloudError, expected_msg, <add> self.driver.create_record, <add> name='test5', zone=zone, <add> type=RecordType.CAA, <add> data='caa.foo.com') <add> <ide> def test_create_record_with_property_that_cant_be_set(self): <ide> zone = self.driver.list_zones()[0] <ide> <ide> def _client_v4_zones(self, method, url, body, headers): <ide> <ide> body = self.fixtures.load('zones_{}.json'.format(method)) <ide> <del> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <add> return (httplib.BAD_REQUEST, body, {}, httplib.responses[httplib.BAD_REQUEST]) <ide> <ide> def _client_v4_zones_1234(self, method, url, body, headers): <ide> if method not in {'GET', 'PATCH', 'DELETE'}: <ide> def _client_v4_zones_1234_dns_records(self, method, url, body, headers): <ide> <ide> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <ide> <add> def _client_v4_zones_1234_dns_records_error_chain_error(self, method, url, body, headers): <add> if method not in ['POST']: <add> raise AssertionError('Unsupported method: %s' % (method)) <add> <add> body = self.fixtures.load('error_with_error_chain.json') <add> <add> return (httplib.OK, body, {}, httplib.responses[httplib.OK]) <add> <ide> def _client_v4_zones_1234_dns_records_0000(self, method, url, body, headers): <ide> if method not in {'GET'}: <ide> raise AssertionError('Unsupported method')
1
Javascript
Javascript
add missing field definition in contextdependency
5649b9c9a347f6642baef99adddcedf69eba1082
<ide><path>lib/dependencies/ContextDependency.js <ide> class ContextDependency extends Dependency { <ide> super(); <ide> this.options = options; <ide> this.userRequest = this.options.request; <add> this.critical = false; <ide> this.hadGlobalOrStickyRegExp = false; <ide> if (this.options.regExp.global || this.options.regExp.sticky) { <ide> this.options.regExp = null; <ide> class ContextDependency extends Dependency { <ide> } <ide> } <ide> <add>// TODO remove in webpack 5 <ide> Object.defineProperty(ContextDependency.prototype, "async", { <ide> configurable: false, <ide> get() {
1
Ruby
Ruby
fix the truffleruby branch
ff5e909b635bdc6ec0f915e101a44281dfd30b97
<ide><path>activesupport/lib/active_support/descendants_tracker.rb <ide> def direct_descendants(klass) <ide> # <ide> # JRuby for now doesn't have Class#descendant, but when it will, it will likely <ide> # have the same WeakMap semantic than Truffle so we future proof this as much as possible. <del> class WeakSet <add> class WeakSet # :nodoc: <ide> def initialize <ide> @map = ObjectSpace::WeakMap.new <ide> end <ide> def []=(object, _present) <ide> @map[object_id] = object <ide> end <ide> end <add> WeakSet.new <ide> end <ide> <ide> class << self
1
Python
Python
take advantage of symmetry in leggauss
49427504787e46bc394305901997d629f039fd19
<ide><path>numpy/polynomial/legendre.py <ide> def leggauss(deg): <ide> # matrix is symmetric in this case in order to obtain better zeros. <ide> c = np.array([0]*deg + [1]) <ide> m = legcompanion(c) <del> x = la.eigvals(m) <add> x = la.eigvalsh(m) <ide> x.sort() <ide> <ide> # improve roots by one application of Newton
1
Javascript
Javascript
handle blank shells in test-os.js
b5569dbe8dee7f259644ef6b73b756d9ea2ba090
<ide><path>test/parallel/test-os.js <ide> if (common.isWindows) { <ide> } else { <ide> is.number(pwd.uid); <ide> is.number(pwd.gid); <del> assert.ok(pwd.shell.includes(path.sep)); <add> assert.strictEqual(typeof pwd.shell, 'string'); <add> // It's possible for /etc/passwd to leave the user's shell blank. <add> if (pwd.shell.length > 0) { <add> assert(pwd.shell.includes(path.sep)); <add> } <ide> assert.strictEqual(pwd.uid, pwdBuf.uid); <ide> assert.strictEqual(pwd.gid, pwdBuf.gid); <ide> assert.strictEqual(pwd.shell, pwdBuf.shell.toString('utf8'));
1
Text
Text
fix typo in .github/issue_template/bug_report.md
d82a127961a1e1db3d7afaa0c2ffa80f1332c547
<ide><path>.github/ISSUE_TEMPLATE/bug_report.md <ide> If you are using kubernetes, please attempt to recreate the issue using minikube <ide> <ide> If this is a UI bug, please provide a screenshot of the bug or a link to a youtube video of the bug in action <ide> <del>You can include images using the .md sytle of <add>You can include images using the .md style of <ide> ![alt text](http://url/to/img.png) <ide> <ide> To record a screencast, mac users can use QuickTime and then create an unlisted youtube video with the resulting .mov file.
1
Text
Text
add generics section
ddb81086a93b42ac724751675512387865dd52c2
<ide><path>guide/english/swift/generics/index.md <add>--- <add>title: Generics <add>--- <add> <add># Generics <add> <add>Write a name inside angle brackets to make a generic function or type. <add>```Swift <add>func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] { <add> var result = [Item]() <add> for _ in 0..<numberOfTimes { <add> result.append(item) <add> } <add> return result <add>} <add>makeArray(repeating: "knock", numberOfTimes: 4) <add>``` <add> <add>***You can make generic forms of functions and methods, as well as classes, enumerations, and structures.*** <add> <add>```Swift <add>// Reimplement the Swift standard library's optional type <add> enum OptionalValue<Wrapped> { <add> case none <add> case some(Wrapped) <add> } <add> var possibleInteger: OptionalValue<Int> = .none <add> possibleInteger = .some(100) <add>``` <add> <add>Use `where` right before the body to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass. <add> <add>```swift <add>func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool <add>where T.Element: Equatable, T.Element == U.Element <add>{ <add> for lhsItem in lhs { <add> for rhsItem in rhs { <add> if lhsItem == rhsItem { <add> return true <add> } <add> } <add> } <add>return false <add>} <add>anyCommonElements([1, 2, 3], [3])
1
Python
Python
update imdb_cnn.py to use globalmaxpooling1d
4cd83631ee003fb2847b78838880392101542517
<ide><path>examples/imdb_cnn.py <ide> <ide> from keras.preprocessing import sequence <ide> from keras.models import Sequential <del>from keras.layers import Dense, Dropout, Activation, Flatten <add>from keras.layers import Dense, Dropout, Activation <ide> from keras.layers import Embedding <del>from keras.layers import Convolution1D, MaxPooling1D <add>from keras.layers import Convolution1D, GlobalMaxPooling1D <ide> from keras.datasets import imdb <ide> from keras import backend as K <ide> <ide> activation='relu', <ide> subsample_length=1)) <ide> # we use max pooling: <del>model.add(MaxPooling1D(pool_length=model.output_shape[1])) <del> <del># We flatten the output of the conv layer, <del># so that we can add a vanilla dense layer: <del>model.add(Flatten()) <add>model.add(GlobalMaxPooling1D()) <ide> <ide> # We add a vanilla hidden layer: <ide> model.add(Dense(hidden_dims))
1
Python
Python
improve asset fetching
126050f259c3bfbef43129bc156c0a6ac381d1f5
<ide><path>spacy/cli/project.py <ide> def project_assets(project_dir: Path) -> None: <ide> msg.warn(f"No assets specified in {CONFIG_FILE}", exits=0) <ide> msg.info(f"Fetching {len(assets)} asset(s)") <ide> variables = config.get("variables", {}) <add> fetched_assets = [] <ide> for asset in assets: <ide> url = asset["url"].format(**variables) <ide> dest = asset["dest"].format(**variables) <del> fetch_asset(project_path, url, dest, asset.get("checksum")) <add> fetched_path = fetch_asset(project_path, url, dest, asset.get("checksum")) <add> if fetched_path: <add> fetched_assets.append(str(fetched_path)) <add> if fetched_assets: <add> with working_dir(project_path): <add> run_command(["dvc", "add", *fetched_assets, "--external"]) <ide> <ide> <ide> def fetch_asset( <ide> project_path: Path, url: str, dest: Path, checksum: Optional[str] = None <del>) -> None: <add>) -> Optional[Path]: <ide> """Fetch an asset from a given URL or path. Will try to import the file <ide> using DVC's import-url if possible (fully tracked and versioned) and falls <ide> back to get-url (versioned) and a non-DVC download if necessary. If a <ide> def fetch_asset( <ide> project_path (Path): Path to project directory. <ide> url (str): URL or path to asset. <ide> checksum (Optional[str]): Optional expected checksum of local file. <add> RETURNS (Optional[Path]): The path to the fetched asset or None if fetching <add> the asset failed. <ide> """ <ide> url = convert_asset_url(url) <ide> dest_path = (project_path / dest).resolve() <ide> def fetch_asset( <ide> # TODO: add support for caches (dvc import-url with local path) <ide> if checksum == get_checksum(dest_path): <ide> msg.good(f"Skipping download with matching checksum: {dest}") <del> return <del> dvc_add_cmd = ["dvc", "add", str(dest_path), "--external"] <add> return dest_path <ide> with working_dir(project_path): <ide> try: <ide> # If these fail, we don't want to output an error or info message. <ide> def fetch_asset( <ide> except subprocess.CalledProcessError: <ide> dvc_cmd = ["dvc", "get-url", url, str(dest_path)] <ide> print(subprocess.check_output(dvc_cmd, stderr=subprocess.DEVNULL)) <del> run_command(dvc_add_cmd) <ide> except subprocess.CalledProcessError: <ide> try: <ide> download_file(url, dest_path) <ide> except requests.exceptions.HTTPError as e: <ide> msg.fail(f"Download failed: {dest}", e) <del> run_command(dvc_add_cmd) <add> return None <ide> if checksum and checksum != get_checksum(dest_path): <ide> msg.warn(f"Checksum doesn't match value defined in {CONFIG_FILE}: {dest}") <ide> msg.good(f"Fetched asset {dest}") <add> return dest_path <ide> <ide> <ide> def project_run_all(project_dir: Path, *dvc_args) -> None:
1
PHP
PHP
add "remember" to ignore list
ff525b995b21998aeba4d87ff97a54b0cb6c6df3
<ide><path>laravel/auth/drivers/eloquent.php <ide> public function retrieve($id) <ide> */ <ide> public function attempt($arguments = array()) <ide> { <del> $user = $this->model()->where(function($query) use($arguments) { <add> $user = $this->model()->where(function($query) use($arguments) <add> { <ide> $username = Config::get('auth.username'); <ide> <ide> $query->where($username, '=', $arguments['username']); <ide> <del> foreach( array_except($arguments, array('username', 'password')) as $column => $val ) <add> foreach(array_except($arguments, array('username', 'password', 'remember')) as $column => $val) <ide> { <ide> $query->where($column, '=', $val); <ide> } <del> })->first(); <add> })->first(); <ide> <del> // If the credentials match what is in the database we will just <del> // log the user into the application and remember them if asked. <del> $password = $arguments['password']; <add> // If the credentials match what is in the database we will just <add> // log the user into the application and remember them if asked. <add> $password = $arguments['password']; <ide> <del> $password_field = Config::get('auth.password', 'password'); <add> $password_field = Config::get('auth.password', 'password'); <ide> <del> if ( ! is_null($user) and Hash::check($password, $user->get_attribute($password_field))) <del> { <del> return $this->login($user->id, array_get($arguments, 'remember')); <del> } <add> if ( ! is_null($user) and Hash::check($password, $user->get_attribute($password_field))) <add> { <add> return $this->login($user->id, array_get($arguments, 'remember')); <add> } <ide> <ide> return false; <ide> } <ide><path>laravel/auth/drivers/fluent.php <ide> protected function get_user($arguments) <ide> { <ide> $table = Config::get('auth.table'); <ide> <del> return DB::table($table)->where(function($query) use($arguments) { <add> return DB::table($table)->where(function($query) use($arguments) <add> { <ide> $username = Config::get('auth.username'); <ide> <ide> $query->where($username, '=', $arguments['username']); <ide> <del> foreach( array_except($arguments, array('username', 'password')) as $column => $val ) <add> foreach(array_except($arguments, array('username', 'password', 'remember')) as $column => $val) <ide> { <ide> $query->where($column, '=', $val); <ide> }
2
Javascript
Javascript
replace console.log/error with debuglog
41b1e87356ec73810d57c37c7058d186f8d574bd
<ide><path>test/parallel/test-cluster-setup-master-multiple.js <ide> require('../common'); <ide> const assert = require('assert'); <ide> const cluster = require('cluster'); <add>const debug = require('util').debuglog('test'); <ide> <ide> assert(cluster.isMaster); <ide> <ide> const configs = []; <ide> <ide> // Capture changes <ide> cluster.on('setup', () => { <del> console.log('"setup" emitted', cluster.settings); <add> debug(`"setup" emitted ${JSON.stringify(cluster.settings)}`); <ide> configs.push(cheapClone(cluster.settings)); <ide> }); <ide> <ide> execs.forEach((v, i) => { <ide> // Cluster emits 'setup' asynchronously, so we must stay alive long <ide> // enough for that to happen <ide> setTimeout(() => { <del> console.log('cluster setup complete'); <add> debug('cluster setup complete'); <ide> }, (execs.length + 1) * 100);
1
PHP
PHP
add a test for nulls
aa6fd355152276b7fee22e7503023b42c6d29c93
<ide><path>tests/TestCase/Shell/Helper/TableHelperTest.php <ide> public function testEmptyStrings() <ide> $this->assertEquals($expected, $this->stub->messages()); <ide> } <ide> <add> /** <add> * Test that output works when data contains just empty strings. <add> */ <add> public function testNullValues() <add> { <add> $data = [ <add> ['Header 1', 'Header', 'Empty'], <add> ['short', 'Longish thing', null], <add> ['Longer thing', 'short', null], <add> ]; <add> $this->helper->output($data); <add> $expected = [ <add> '+--------------+---------------+-------+', <add> '| <info>Header 1</info> | <info>Header</info> | <info>Empty</info> |', <add> '+--------------+---------------+-------+', <add> '| short | Longish thing | |', <add> '| Longer thing | short | |', <add> '+--------------+---------------+-------+', <add> ]; <add> $this->assertEquals($expected, $this->stub->messages()); <add> } <add> <ide> /** <ide> * Test output with multi-byte characters <ide> *
1
Text
Text
fix typo in docs/manpage.md
05b4d264f06b5c2e4a336181646a58c0115281b8
<ide><path>docs/Manpage.md <ide> The search for *`text`* is extended online to `homebrew/core` and `homebrew/cask <ide> Print export statements. When run in a shell, this installation of Homebrew will be added to your `PATH`, `MANPATH`, and `INFOPATH`. <ide> <ide> The variables `HOMEBREW_PREFIX`, `HOMEBREW_CELLAR` and `HOMEBREW_REPOSITORY` are also exported to avoid querying them multiple times. <del>To help guarantee idempotence, this command produces no output when Homebrew's `bin` and `sbin` directores are first and second <add>To help guarantee idempotence, this command produces no output when Homebrew's `bin` and `sbin` directories are first and second <ide> respectively in your `PATH`. Consider adding evaluation of this command's output to your dotfiles (e.g. `~/.profile`, <ide> `~/.bash_profile`, or `~/.zprofile`) with: `eval "$(brew shellenv)"` <ide>
1
Python
Python
update quick_sort.py (#928)
34889fc6d8d3ac1cf5af11039cc1ec40185f778e
<ide><path>sorts/quick_sort.py <ide> def quick_sort(collection): <ide> if length <= 1: <ide> return collection <ide> else: <del> pivot = collection[0] <del> # Modify the list comprehensions to reduce the number of judgments, the speed has increased by more than 50%. <del> greater = [] <del> lesser = [] <del> for element in collection[1:]: <add> # Use the last element as the first pivot <add> pivot = collection.pop() <add> # Put elements greater than pivot in greater list <add> # Put elements lesser than pivot in lesser list <add> greater, lesser = [], [] <add> for element in collection: <ide> if element > pivot: <ide> greater.append(element) <ide> else: <ide> lesser.append(element) <del> # greater = [element for element in collection[1:] if element > pivot] <del> # lesser = [element for element in collection[1:] if element <= pivot] <ide> return quick_sort(lesser) + [pivot] + quick_sort(greater) <ide> <ide>
1
PHP
PHP
update firstorfail logic
f409e0433fd1d9186dc6dfb32e277adb74e96fdc
<ide><path>src/Illuminate/Collections/Collection.php <ide> public function firstOrFail($key = null, $operator = null, $value = null) <ide> ? $this->operatorForWhere(...func_get_args()) <ide> : $key; <ide> <del> $items = $this->when($filter)->filter($filter); <add> $items = $this->unless($filter == null)->filter($filter); <ide> <ide> if ($items->isEmpty()) { <ide> throw new ItemNotFoundException; <ide><path>src/Illuminate/Collections/LazyCollection.php <ide> public function firstOrFail($key = null, $operator = null, $value = null) <ide> : $key; <ide> <ide> return $this <del> ->when($filter) <add> ->unless($filter == null) <ide> ->filter($filter) <ide> ->take(1) <ide> ->collect()
2
Ruby
Ruby
store the singleton_class in a local variable
17cb1266c7b91c934dcef2afe38ea4dab677ef91
<ide><path>activesupport/lib/active_support/testing/time_helpers.rb <ide> def unstub_all! <ide> private <ide> <ide> def unstub_object(stub) <del> stub.object.singleton_class.send :undef_method, stub.method_name <del> stub.object.singleton_class.send :alias_method, stub.method_name, stub.original_method <del> stub.object.singleton_class.send :undef_method, stub.original_method <add> singleton_class = stub.object.singleton_class <add> singleton_class.send :undef_method, stub.method_name <add> singleton_class.send :alias_method, stub.method_name, stub.original_method <add> singleton_class.send :undef_method, stub.original_method <ide> end <ide> end <ide>
1
Python
Python
use openblas 0.3.10
22ac0da7f24787d274c36062507239402b5e0f09
<ide><path>tools/openblas_support.py <ide> <ide> from tempfile import mkstemp, gettempdir <ide> from urllib.request import urlopen, Request <add>from urllib.error import HTTPError <ide> <del>OPENBLAS_V = '0.3.9' <add>OPENBLAS_V = '0.3.10' <ide> # Temporary build of OpenBLAS to test a fix for dynamic detection of CPU <del>OPENBLAS_LONG = 'v0.3.7-527-g79fd006c' # the 0.3.7 is misleading <add>OPENBLAS_LONG = 'v0.3.10' <ide> BASE_LOC = 'https://anaconda.org/multibuild-wheels-staging/openblas-libs' <ide> BASEURL = f'{BASE_LOC}/{OPENBLAS_LONG}/download' <ide> ARCHITECTURES = ['', 'windows', 'darwin', 'aarch64', 'x86_64', 'i686', 'ppc64le', 's390x'] <ide> "openblas64_-v0.3.7-527-g79fd006c-manylinux2014_s390x.tar.gz": "9fddbebf5301518fc4a5d2022a61886544a0566868c8c014359a1ee6b17f2814", <ide> "openblas-v0.3.7-527-g79fd006c-manylinux1_i686.tar.gz": "24fb92684ec4676185fff5c9340f50c3db6075948bcef760e9c715a8974e4680", <ide> "openblas-v0.3.7-527-g79fd006c-manylinux1_x86_64.tar.gz": "ebb8236b57a1b4075fd5cdc3e9246d2900c133a42482e5e714d1e67af5d00e62", <del>"openblas-v0.3.7-527-g79fd006c-manylinux1_i686.tar.gz": "24fb92684ec4676185fff5c9340f50c3db6075948bcef760e9c715a8974e4680", <del>"openblas-v0.3.7-527-g79fd006c-manylinux1_x86_64.tar.gz": "ebb8236b57a1b4075fd5cdc3e9246d2900c133a42482e5e714d1e67af5d00e62", <del>"openblas-v0.3.7-527-g79fd006c-manylinux1_i686.tar.gz": "24fb92684ec4676185fff5c9340f50c3db6075948bcef760e9c715a8974e4680", <del>"openblas-v0.3.7-527-g79fd006c-manylinux1_x86_64.tar.gz": "ebb8236b57a1b4075fd5cdc3e9246d2900c133a42482e5e714d1e67af5d00e62", <ide> } <ide> <ide> <ide> def get_manylinux(arch): <ide> return ret <ide> <ide> <del>def download_openblas(target, arch, ilp64): <add>def download_openblas(target, arch, ilp64, is_32bit): <ide> ml_ver = get_manylinux(arch) <ide> fnsuffix = {None: "", "64_": "64_"}[ilp64] <ide> filename = '' <ide> def download_openblas(target, arch, ilp64): <ide> filename = f'{BASEURL}/openblas{fnsuffix}-{OPENBLAS_LONG}-{suffix}' <ide> typ = 'tar.gz' <ide> elif arch == 'windows': <del> if IS_32BIT: <add> if is_32bit: <ide> suffix = 'win32-gcc_7_1_0.zip' <ide> else: <ide> suffix = 'win_amd64-gcc_7_1_0.zip' <ide> def download_openblas(target, arch, ilp64): <ide> if not filename: <ide> return None <ide> req = Request(url=filename, headers=headers) <del> response = urlopen(req) <add> try: <add> response = urlopen(req) <add> except HTTPError as e: <add> print(f'Could not download "{filename}"', file=sys.stderr) <add> raise <ide> length = response.getheader('content-length') <ide> if response.status != 200: <ide> print(f'Could not download "{filename}"', file=sys.stderr) <ide> def download_openblas(target, arch, ilp64): <ide> fid.write(data) <ide> return typ <ide> <del>def setup_openblas(arch=get_arch(), ilp64=get_ilp64()): <add>def setup_openblas(arch=get_arch(), ilp64=get_ilp64(), is_32bit=IS_32BIT): <ide> ''' <ide> Download and setup an openblas library for building. If successful, <ide> the configuration script will find it automatically. <ide> def setup_openblas(arch=get_arch(), ilp64=get_ilp64()): <ide> _, tmp = mkstemp() <ide> if not arch: <ide> raise ValueError('unknown architecture') <del> typ = download_openblas(tmp, arch, ilp64) <add> typ = download_openblas(tmp, arch, ilp64, is_32bit) <ide> if not typ: <ide> return '' <ide> if arch == 'windows': <ide> def test_setup(arches): <ide> ''' <ide> def items(): <ide> for arch in arches: <del> yield arch, None <del> if arch not in ('i686'): <del> yield arch, '64_' <add> yield arch, None, False <add> if arch not in ('i686',): <add> yield arch, '64_', False <add> if arch in ('windows',): <add> yield arch, None, False <add> <ide> <ide> errs = [] <del> for arch, ilp64 in items(): <add> for arch, ilp64, is_32bit in items(): <ide> if arch == '': <ide> continue <ide> <ide> target = None <ide> try: <ide> try: <del> target = setup_openblas(arch, ilp64) <add> target = setup_openblas(arch, ilp64, is_32bit) <ide> except Exception as e: <del> print(f'Could not setup {arch}:') <del> print(str(e)) <add> print(f'Could not setup {arch} with ilp64 {ilp64}, 32bit {is_32bit}:') <add> print(e) <ide> errs.append(e) <ide> continue <ide> if not target:
1
Java
Java
fix warnings in headermethodargumentresolver
6bb6b6e6b5620af0f82cd80fb8c65684097f22e5
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolver.java <ide> <ide> package org.springframework.messaging.handler.annotation.support; <ide> <add>import java.util.List; <add>import java.util.Map; <add> <ide> import org.apache.commons.logging.Log; <ide> import org.apache.commons.logging.LogFactory; <ide> import org.springframework.beans.factory.config.ConfigurableBeanFactory; <ide> import org.springframework.messaging.MessageHandlingException; <ide> import org.springframework.messaging.handler.annotation.Header; <ide> import org.springframework.messaging.support.NativeMessageHeaderAccessor; <del>import org.springframework.util.MultiValueMap; <del> <del>import java.util.List; <del>import java.util.Map; <ide> <ide> /** <ide> * Resolves method parameters annotated with {@link Header @Header}. <ide> protected Object resolveArgumentInternal(MethodParameter parameter, Message<?> m <ide> <ide> private Object getNativeHeaderValue(Message<?> message, String name) { <ide> <del> Map<String, List<String>> nativeHeaders = <del> (Map<String, List<String>>) message.getHeaders().get(NativeMessageHeaderAccessor.NATIVE_HEADERS); <add> Map<String, List<String>> nativeHeaders = getNativeHeaders(message); <ide> <ide> if (name.startsWith("nativeHeaders.")) { <ide> name = name.substring("nativeHeaders.".length()); <ide> private Object getNativeHeaderValue(Message<?> message, String name) { <ide> return (nativeHeaderValues.size() == 1) ? nativeHeaderValues.get(0) : nativeHeaderValues; <ide> } <ide> <add> @SuppressWarnings("unchecked") <add> private Map<String, List<String>> getNativeHeaders(Message<?> message) { <add> return (Map<String, List<String>>) message.getHeaders().get( <add> NativeMessageHeaderAccessor.NATIVE_HEADERS); <add> } <add> <ide> @Override <ide> protected void handleMissingValue(String headerName, MethodParameter parameter, Message<?> message) { <ide> throw new MessageHandlingException(message, "Missing header '" + headerName +
1
Text
Text
add better explanation of monad laws
bbbaca63c124f68e999bd34a72355ae051bb10fa
<ide><path>client/src/pages/guide/english/haskell/monad/index.md <ide> title: Monad <ide> # Monad Laws <ide> There are 3 laws which must be satisfied by a data type to be considered as monad <ide> <add>## Left Identity <add>`return a >>= f` must equal `f a` <ide> <add>This states that if we take a value and use `return` to put it in default context, <add>then use `>>=` to feed it into a function, it's the same as applying the <add>function to the original value. <add> <add>## Right Identity <add>`m >>= return` must equal `m` <add>This states that if we use `>>=` to feed a monadic value into return, we <add>get back our original monadic value. <add> <add>## Associativity <add>`(m >>= f) >>= g` must equal `m >>= (\x -> f x >>= g)` <add>This allows us to chain together monadic function applications, regardless of <add>how they are nested. <add> <add>This may seem obvious, and you may assume that it should work by default, but the <add>associative law is required for this behavior <add> <add># But what about `>>=` and `return`? <add>Simple: <add> <add>`>>=`, or 'bind' takes a monad and a function that takes a value and returns a <add>monad, and applies the function to a monad. This essentially allows us to <add>manipulate data within monads, which can't be accessed by non-monadic functions. <add> <add>`return`, on the other hand, takes a value and returns a monad containing <add>that value. Everything you could ever want to know about `return` is right <add>there in the type signature: <add>```haskell <add>return :: a -> m a <add>``` <ide> <ide> # Maybe Monad <ide>
1
Ruby
Ruby
use the $stderr global variable
22a98624d2d249add58c31833e1b4e452c242d03
<ide><path>Library/Homebrew/utils.rb <ide> def oh1 title <ide> end <ide> <ide> def opoo warning <del> STDERR.puts "#{Tty.red}Warning#{Tty.reset}: #{warning}" <add> $stderr.puts "#{Tty.red}Warning#{Tty.reset}: #{warning}" <ide> end <ide> <ide> def onoe error <del> STDERR.puts "#{Tty.red}Error#{Tty.reset}: #{error}" <add> $stderr.puts "#{Tty.red}Error#{Tty.reset}: #{error}" <ide> end <ide> <ide> def ofail error
1
Text
Text
replace stub with guide
f1ef10aeb0b68804f7653c05d9daebfb6fa2a9fe
<ide><path>guide/english/certifications/javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability/index.md <ide> title: Understand String Immutability <ide> --- <ide> ## Understand String Immutability <ide> <del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/basic-javascript/understand-string-immutability/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>. <add>## Problem Explanation <add>Correct the assignment to ```myStr``` so it contains the string value of ```Hello World``` using the approach shown in the example above. <ide> <del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>. <add>## Hint <add>Instead of ```Jello World ```, ```myStr``` should be assigned ```Hello World```. <ide> <del><!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds --> <add> ## Spoiler Alert! Solution ahead. <add>**Solution** <add>```javascript <add>// Setup <add>var myStr = "Jello World"; <add> // Only change code below this line <add> myStr = "Hello World"; <add>``` <add> ## Code Explanation <add>String literals such as ```"Jello World"``` cannot be changed by the individual letter (hence being *immutable*), so the variable containing the incorrect string must be replaced with the desired string using the assignment operator ```=```
1
Ruby
Ruby
move mysql2 test for when adapter will be loaded
8e2c0803f5e114f74ce0e8acc44ae43da97175e3
<ide><path>activerecord/test/cases/adapters/mysql/mysql_adapter_test.rb <ide> def test_bad_connection_mysql <ide> end <ide> end <ide> <del> def test_bad_connection_mysql2 <del> assert_raise ActiveRecord::NoDatabaseError do <del> connection = ActiveRecord::Base.mysql2_connection(adapter: "mysql2", database: "should_not_exist-cinco-dog-db") <del> connection.exec_query('drop table if exists ex') <del> end <del> end <del> <ide> def test_valid_column <ide> column = @conn.columns('ex').find { |col| col.name == 'id' } <ide> assert @conn.valid_type?(column.type) <ide><path>activerecord/test/cases/adapters/mysql2/connection_test.rb <ide> def teardown <ide> super <ide> end <ide> <add> def test_bad_connection <add> assert_raise ActiveRecord::NoDatabaseError do <add> connection = ActiveRecord::Base.mysql2_connection(adapter: "mysql2", database: "should_not_exist-cinco-dog-db") <add> connection.exec_query('drop table if exists ex') <add> end <add> end <add> <ide> def test_no_automatic_reconnection_after_timeout <ide> assert @connection.active? <ide> @connection.update('set @@wait_timeout=1')
2
Javascript
Javascript
add empty publicruntimeconfig to serverless tests
e7440858db5d23fe162549df762d93b0b543b04c
<ide><path>test/integration/serverless/next.config.js <ide> module.exports = { <ide> }, <ide> experimental: { <ide> publicDirectory: true <del> } <add> }, <add> // make sure error isn't thrown from empty publicRuntimeConfig <add> publicRuntimeConfig: {} <ide> }
1
Python
Python
add missing import
b1b8cf8b3a7789530a94def061de14c948c5c373
<ide><path>libcloud/py3.py <ide> def dictvalues(d): <ide> else: <ide> import httplib <ide> from StringIO import StringIO <add> import urllib <ide> import urllib2 <ide> import urlparse <ide>
1
Ruby
Ruby
set `m4` on linux when `bison` is a dependency
22db7aa516ef385949582cac1f12d8984e441f8b
<ide><path>Library/Homebrew/extend/os/linux/extend/ENV/super.rb <ide> def setup_build_environment(formula: nil, cc: nil, build_bottle: false, bottle_a <ide> self["HOMEBREW_OPTIMIZATION_LEVEL"] = "O2" <ide> self["HOMEBREW_DYNAMIC_LINKER"] = determine_dynamic_linker_path <ide> self["HOMEBREW_RPATH_PATHS"] = determine_rpath_paths(@formula) <add> self["M4"] = "#{HOMEBREW_PREFIX}/opt/m4/bin/m4" if deps.any? { |d| d.name == "libtool" || d.name == "bison" } <ide> end <ide> <ide> def homebrew_extra_paths
1
Java
Java
fix measureinwindow for view-backed nodes
520f70bd57e8211a375990a9e0d805a0a738b176
<ide><path>ReactAndroid/src/main/java/com/facebook/react/flat/FlatUIImplementation.java <ide> private void measureHelper(int reactTag, boolean relativeToWindow, Callback call <ide> FlatShadowNode node = (FlatShadowNode) resolveShadowNode(reactTag); <ide> if (node.mountsToView()) { <ide> mStateBuilder.ensureBackingViewIsCreated(node); <del> super.measure(reactTag, callback); <add> if (relativeToWindow) { <add> super.measureInWindow(reactTag, callback); <add> } else { <add> super.measure(reactTag, callback); <add> } <ide> return; <ide> } <ide>
1
Text
Text
fix translation in spanish readme.md
be74e5be01dc5c7243815c0e308bf02f98cb7666
<ide><path>docs/spanish/README.md <ide> </tr> <ide> </table> <ide> <del># Documentation Quick Reference <add># Documentación de referencia rápida <ide> <ide> ¡Hola 👋 ! <ide>
1
Mixed
Text
improve string#squish whitespaces matching
b5245da94a7c7667b57bb2184fa9aa7beb998da6
<ide><path>activesupport/CHANGELOG.md <ide> <ide> * Optimize log subscribers to check log level before doing any processing. *Brian Durand* <ide> <add>* Improve String#squish to handle Unicode whitespace. *Antoine Lyset* <add> <ide> Please check [3-2-stable](https://github.com/rails/rails/blob/3-2-stable/activesupport/CHANGELOG.md) for previous changes. <ide><path>activesupport/lib/active_support/core_ext/string/filters.rb <ide> class String <ide> # the string, and then changing remaining consecutive whitespace <ide> # groups into one space each. <ide> # <add> # Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E). <add> # <ide> # %{ Multi-line <ide> # string }.squish # => "Multi-line string" <ide> # " foo bar \n \t boo".squish # => "foo bar boo" <ide> def squish <ide> <ide> # Performs a destructive squish. See String#squish. <ide> def squish! <del> strip! <del> gsub!(/\s+/, ' ') <add> gsub!(/\A[[:space:]]+/, '') <add> gsub!(/[[:space:]]+\Z/, '') <add> gsub!(/[[:space:]]+/, ' ') <ide> self <ide> end <ide> <ide><path>activesupport/test/core_ext/string_ext_test.rb <ide> def test_starts_ends_with_alias <ide> end <ide> <ide> def test_string_squish <del> original = %{ A string with tabs(\t\t), newlines(\n\n), and <del> many spaces( ). } <add> original = %{\u180E\u180E A string surrounded by unicode mongolian vowel separators, <add> with tabs(\t\t), newlines(\n\n), unicode nextlines(\u0085\u0085) and many spaces( ). \u180E\u180E} <ide> <del> expected = "A string with tabs( ), newlines( ), and many spaces( )." <add> expected = "A string surrounded by unicode mongolian vowel separators, " + <add> "with tabs( ), newlines( ), unicode nextlines( ) and many spaces( )." <ide> <ide> # Make sure squish returns what we expect: <ide> assert_equal original.squish, expected <ide><path>guides/source/active_support_core_extensions.md <ide> The method `squish` strips leading and trailing whitespace, and substitutes runs <ide> <ide> There's also the destructive version `String#squish!`. <ide> <add>Note that it handles both ASCII and Unicode whitespace like mongolian vowel separator (U+180E). <add> <ide> NOTE: Defined in `active_support/core_ext/string/filters.rb`. <ide> <ide> ### `truncate`
4
Text
Text
add arquivei to companies list
c6824a34a9779675e42d9b8bc7025f3dbc942c3d
<ide><path>README.md <ide> Currently **officially** using Airflow: <ide> 1. [AltX](https://www.getaltx.com/about) [[@pedromduarte](https://github.com/pedromduarte)] <ide> 1. [Apigee](https://apigee.com) [[@btallman](https://github.com/btallman)] <ide> 1. [ARGO Labs](http://www.argolabs.org) [[California Data Collaborative](https://github.com/California-Data-Collaborative)] <add>1. [Arquivei](https://www.arquivei.com.br/) [[@arquivei](https://github.com/arquivei)] <ide> 1. [Astronomer](http://www.astronomer.io) [[@schnie](https://github.com/schnie), [@andscoop](https://github.com/andscoop), [@tedmiston](https://github.com/tedmiston), [@benjamingregory](https://github.com/benjamingregory)] <ide> 1. [Auth0](https://auth0.com) [[@sicarul](https://github.com/sicarul)] <ide> 1. [Away](https://awaytravel.com) [[@trunsky](https://github.com/trunsky)]
1
Mixed
Javascript
update apollo links in examples
b990b29d2d64a7c12152752264fbd79e5371681b
<ide><path>examples/with-apollo-and-redux-saga/lib/withApollo.js <ide> export default ComposedComponent => { <ide> } catch (error) { <ide> // Prevent Apollo Client GraphQL errors from crashing SSR. <ide> // Handle them in components via the data.error prop: <del> // http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error <add> // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error <ide> } <ide> // getDataFromTree does not call componentWillUnmount <ide> // head side effect therefore need to be cleared manually <ide><path>examples/with-apollo-and-redux-saga/pages/about.js <ide> export default () => ( <ide> <article> <ide> <h1>The Idea Behind This Example</h1> <ide> <p> <del> <a href='http://dev.apollodata.com'>Apollo</a> is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <add> <a href='https://www.apollographql.com/client/'>Apollo</a> is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <ide> </p> <ide> <p> <ide> In this simple example, we integrate Apollo seamlessly with <a href='https://github.com/zeit/next.js'>Next</a> by wrapping our pages inside a <a href='https://facebook.github.io/react/docs/higher-order-components.html'>higher-order component (HOC)</a>. Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application. <ide> </p> <ide> <p> <del> On initial page load, while on the server and inside getInitialProps, we invoke the Apollo method, <a href='http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree'>getDataFromTree</a>. This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. <add> On initial page load, while on the server and inside getInitialProps, we invoke the Apollo method, <a href='https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree'>getDataFromTree</a>. This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. <ide> </p> <ide> <p> <ide> This example relies on <a href='http://graph.cool'>graph.cool</a> for its GraphQL backend. <ide><path>examples/with-apollo-and-redux/lib/withApollo.js <ide> export default ComposedComponent => { <ide> } catch (error) { <ide> // Prevent Apollo Client GraphQL errors from crashing SSR. <ide> // Handle them in components via the data.error prop: <del> // http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error <add> // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error <ide> } <ide> // getDataFromTree does not call componentWillUnmount <ide> // head side effect therefore need to be cleared manually <ide> export default ComposedComponent => { <ide> ) <ide> } <ide> } <del>} <ide>\ No newline at end of file <add>} <ide><path>examples/with-apollo-auth/README.md <ide> now <ide> <ide> This is an extention of the _[with Apollo](https://github.com/zeit/next.js/tree/master/examples/with-apollo#the-idea-behind-the-example)_ example: <ide> <del>> [Apollo](http://dev.apollodata.com) is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <add>> [Apollo](https://www.apollographql.com/client/) is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <ide> > <ide> > In this simple example, we integrate Apollo seamlessly with Next by wrapping our *pages* inside a [higher-order component (HOC)](https://facebook.github.io/react/docs/higher-order-components.html). Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application. <ide> > <del>> On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. <add>> On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. <ide> > <ide> > This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend. <ide> > <ide><path>examples/with-apollo-auth/lib/withApollo.js <ide> export default App => { <ide> } catch (error) { <ide> // Prevent Apollo Client GraphQL errors from crashing SSR. <ide> // Handle them in components via the data.error prop: <del> // http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error <add> // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error <ide> console.error('Error while running `getDataFromTree`', error) <ide> } <ide> <ide><path>examples/with-apollo/README.md <ide> now <ide> <ide> ## The idea behind the example <ide> <del>[Apollo](http://dev.apollodata.com) is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <add>[Apollo](https://www.apollographql.com/client/) is a GraphQL client that allows you to easily query the exact data you need from a GraphQL server. In addition to fetching and mutating data, Apollo analyzes your queries and their results to construct a client-side cache of your data, which is kept up to date as further queries and mutations are run, fetching more results from the server. <ide> <ide> In this simple example, we integrate Apollo seamlessly with Next by wrapping our *pages/_app.js* inside a [higher-order component (HOC)](https://facebook.github.io/react/docs/higher-order-components.html). Using the HOC pattern we're able to pass down a central store of query result data created by Apollo into our React component hierarchy defined inside each page of our Next application. <ide> <del>On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. <add>On initial page load, while on the server and inside `getInitialProps`, we invoke the Apollo method, [`getDataFromTree`](https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree). This method returns a promise; at the point in which the promise resolves, our Apollo Client store is completely initialized. <ide> <ide> This example relies on [graph.cool](https://www.graph.cool) for its GraphQL backend. <ide><path>examples/with-apollo/lib/with-apollo-client.js <ide> export default (App) => { <ide> } catch (error) { <ide> // Prevent Apollo Client GraphQL errors from crashing SSR. <ide> // Handle them in components via the data.error prop: <del> // http://dev.apollodata.com/react/api-queries.html#graphql-query-data-error <add> // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error <ide> console.error('Error while running `getDataFromTree`', error) <ide> } <ide> <ide><path>examples/with-apollo/pages/about.js <ide> export default () => ( <ide> <article> <ide> <h1>The Idea Behind This Example</h1> <ide> <p> <del> <a href='http://dev.apollodata.com'>Apollo</a> is a GraphQL client that <add> <a href='https://www.apollographql.com/client/'>Apollo</a> is a GraphQL client that <ide> allows you to easily query the exact data you need from a GraphQL <ide> server. In addition to fetching and mutating data, Apollo analyzes your <ide> queries and their results to construct a client-side cache of your data, <ide> export default () => ( <ide> <p> <ide> On initial page load, while on the server and inside getInitialProps, we <ide> invoke the Apollo method,{' '} <del> <a href='http://dev.apollodata.com/react/server-side-rendering.html#getDataFromTree'> <add> <a href='https://www.apollographql.com/docs/react/features/server-side-rendering.html#getDataFromTree'> <ide> getDataFromTree <ide> </a>. This method returns a promise; at the point in which the promise <ide> resolves, our Apollo Client store is completely initialized.
8
PHP
PHP
onceusingid()
a6ddacb568c1d4fa2d4b6e9f739830692c055973
<ide><path>tests/Auth/AuthGuardTest.php <ide> public function testLoginUsingIdFailure() <ide> $this->assertFalse($guard->loginUsingId(11)); <ide> } <ide> <add> public function testOnceUsingIdSetsUser() <add> { <add> list($session, $provider, $request, $cookie) = $this->getMocks(); <add> $guard = m::mock('Illuminate\Auth\SessionGuard', ['default', $provider, $session])->makePartial(); <add> <add> $user = m::mock('Illuminate\Contracts\Auth\Authenticatable'); <add> $guard->getProvider()->shouldReceive('retrieveById')->once()->with(10)->andReturn($user); <add> $guard->shouldReceive('setUser')->once()->with($user); <add> <add> $this->assertTrue($guard->onceUsingId(10)); <add> } <add> <ide> public function testOnceUsingIdFailure() <ide> { <ide> list($session, $provider, $request, $cookie) = $this->getMocks();
1
Text
Text
note functional equivalence in reset task
d4863f30de023d0f6817afcddc114889493e6d3c
<ide><path>guides/source/migrations.md <ide> version to migrate to. <ide> <ide> ### Resetting the Database <ide> <del>The `rake db:reset` task will drop the database, recreate it and load the <del>current schema into it. <add>The `rake db:reset` task will drop the database and set it up again. This is <add>functionally eqivalent to `rake db:drop db:setup` <ide> <ide> NOTE: This is not the same as running all the migrations. It will only use the <ide> contents of the current schema.rb file. If a migration can't be rolled back,
1
Ruby
Ruby
create homebrew_cache when needed
512073ad388953152ab88802237dd469c799983c
<ide><path>Library/Homebrew/cache_store.rb <ide> def created? <ide> # @return [DBM] db <ide> def db <ide> # DBM::WRCREAT: Creates the database if it does not already exist <del> @db ||= DBM.open(dbm_file_path, DATABASE_MODE, DBM::WRCREAT) <add> @db ||= begin <add> HOMEBREW_CACHE.mkpath <add> DBM.open(dbm_file_path, DATABASE_MODE, DBM::WRCREAT) <add> end <ide> end <ide> <ide> # Creates a CacheStoreDatabase
1
Javascript
Javascript
remove an unnecessary warning
7443f63ae995a01f0b97675a17ca3b0d81bd0ad2
<ide><path>src/renderers/shared/reconciler/ReactUpdateQueue.js <ide> function enqueueUpdate(internalInstance) { <ide> } <ide> <ide> function getInternalInstanceReadyForUpdate(publicInstance, callerName) { <del> warning( <del> ReactCurrentOwner.current == null, <del> '%s(...): Cannot update during an existing state transition ' + <del> '(such as within `render`). Render methods should be a pure function ' + <del> 'of props and state.', <del> callerName <del> ); <add> if (__DEV__) { <add> warning( <add> ReactCurrentOwner.current == null, <add> '%s(...): Cannot update during an existing state transition ' + <add> '(such as within `render`). Render methods should be a pure function ' + <add> 'of props and state.', <add> callerName <add> ); <add> } <ide> <ide> var internalInstance = ReactInstanceMap.get(publicInstance); <ide> if (!internalInstance) { <ide><path>src/renderers/shared/reconciler/ReactUpdates.js <ide> <ide> var CallbackQueue = require('CallbackQueue'); <ide> var PooledClass = require('PooledClass'); <del>var ReactCurrentOwner = require('ReactCurrentOwner'); <ide> var ReactPerf = require('ReactPerf'); <ide> var ReactReconciler = require('ReactReconciler'); <ide> var Transaction = require('Transaction'); <ide> function enqueueUpdate(component) { <ide> // verify that that's the case. (This is called by each top-level update <ide> // function, like setProps, setState, forceUpdate, etc.; creation and <ide> // destruction of top-level components is guarded in ReactMount.) <del> warning( <del> ReactCurrentOwner.current == null, <del> 'enqueueUpdate(): Render methods should be a pure function of props ' + <del> 'and state; triggering nested component updates from render is not ' + <del> 'allowed. If necessary, trigger nested updates in ' + <del> 'componentDidUpdate.' <del> ); <ide> <ide> if (!batchingStrategy.isBatchingUpdates) { <ide> batchingStrategy.batchedUpdates(enqueueUpdate, component);
2
Text
Text
deprecate thenable support
1cea3918af6c8d5c0e4ab6b1604ccbbcc6442548
<ide><path>doc/api/deprecations.md <ide> should have the same effect. The receiving end should also check the <ide> [`readable.readableEnded`][] value on [`http.IncomingMessage`][] to get whether <ide> it was an aborted or graceful destroy. <ide> <add>### DEP0157: Thenable support in streams <add> <add><!-- YAML <add>changes: <add> - version: REPLACEME <add> pr-url: https://github.com/nodejs/node/pull/40860 <add> description: Documentation-only deprecation. <add>--> <add> <add>Type: Documentation-only <add> <add>An undocumented feature of Node.js streams was to support thenables in <add>implementation methods. This is now deprecated, use callbacks instead and avoid <add>use of async function for streams implementation methods. <add> <add>This feature caused users to encounter unexpected problems where the user <add>implements the function in callback style but uses e.g. an async method which <add>would cause an error since mixing promise and callback semantics is not valid. <add> <add>```js <add>const w = new Writable({ <add> async final(callback) { <add> await someOp(); <add> callback(); <add> } <add>}); <add>``` <add> <ide> [Legacy URL API]: url.md#legacy-url-api <ide> [NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf <ide> [RFC 6066]: https://tools.ietf.org/html/rfc6066#section-3
1
Ruby
Ruby
routeset#rewrite => url_for
4d2470f7daad8cebd0a69f5ea0509a41af0596b8
<ide><path>actionpack/lib/action_controller/test_case.rb <ide> def build_request_uri(action, parameters) <ide> :relative_url_root => nil, <ide> :_path_segments => @request.symbolized_path_parameters) <ide> <del> url, query_string = @router.rewrite(options).split("?", 2) <add> url, query_string = @router.url_for(options).split("?", 2) <ide> <ide> @request.env["SCRIPT_NAME"] = @controller.config.relative_url_root <ide> @request.env["PATH_INFO"] = url <ide><path>actionpack/lib/action_dispatch/routing/route_set.rb <ide> def generate(options, recall = {}, extras = false) <ide> <ide> RESERVED_OPTIONS = [:anchor, :params, :only_path, :host, :protocol, :port, :trailing_slash, :skip_relative_url_root] <ide> <del> # TODO: Terrible method name <del> def rewrite(options) <add> def url_for(options) <ide> handle_positional_args(options) <ide> <ide> rewritten_url = "" <ide><path>actionpack/lib/action_dispatch/routing/url_for.rb <ide> def url_for(options = nil) <ide> when String <ide> options <ide> when nil, Hash <del> _router.rewrite(url_options.merge(options || {})) <add> _router.url_for(url_options.merge(options || {})) <ide> else <ide> polymorphic_url(options) <ide> end <ide><path>actionpack/test/controller/caching_test.rb <ide> def test_page_caching_resources_saves_to_correct_path_with_extension_even_if_def <ide> match '/', :to => 'posts#index', :as => :main <ide> end <ide> @params[:format] = 'rss' <del> assert_equal '/posts.rss', @router.rewrite(@params) <add> assert_equal '/posts.rss', @router.url_for(@params) <ide> @params[:format] = nil <del> assert_equal '/', @router.rewrite(@params) <add> assert_equal '/', @router.url_for(@params) <ide> end <ide> end <ide> <ide><path>actionpack/test/controller/url_rewriter_test.rb <ide> def initialize(request) <ide> end <ide> <ide> def rewrite(router, options) <del> router.rewrite(@options.merge(options)) <add> router.url_for(@options.merge(options)) <ide> end <ide> end <ide>
5
Python
Python
fix tapas issue
70f88eecccb54e344bd8ada1698b4e62ca7d79ff
<ide><path>src/transformers/models/tapas/modeling_tapas.py <ide> def _segment_reduce(values, index, segment_reduce_fn, name): <ide> <ide> segment_means = scatter( <ide> src=flat_values, <del> index=flat_index.indices.type(torch.long), <add> index=flat_index.indices.long(), <ide> dim=0, <del> dim_size=flat_index.num_segments, <add> dim_size=int(flat_index.num_segments), <ide> reduce=segment_reduce_fn, <ide> ) <ide> <ide><path>tests/test_modeling_tapas.py <ide> def test_reduce_max(self): <ide> # We use np.testing.assert_array_equal rather than Tensorflow's assertAllEqual <ide> np.testing.assert_array_equal(maximum.numpy(), [2, 3]) <ide> <del> @unittest.skip("Fix me I'm failing on CI") <ide> def test_reduce_sum_vectorized(self): <ide> values = torch.as_tensor([[1.0, 2.0, 3.0], [2.0, 3.0, 4.0], [3.0, 4.0, 5.0]]) <ide> index = IndexMap(indices=torch.as_tensor([0, 0, 1]), num_segments=2, batch_dims=0)
2
Javascript
Javascript
improve docs for event names
5079d4efc5eb694354c3afb89f5af30aafb2fb54
<ide><path>packages/ember-views/lib/views/view.js <ide> class: <ide> <ide> ### Event Names <ide> <del> Possible events names for any of the responding approaches described above <del> are: <add> All of the event handling approaches described above respond to the same set <add> of events. The names of the built-in events are listed below. (The hash of <add> built-in events exists in `Ember.EventDispatcher`.) Additional, custom events <add> can be registered by using `Ember.Application.customEvents`. <ide> <ide> Touch events: <ide>
1
Python
Python
fix gru activation
d04cac6526171af608baf38f68f9767af62b0555
<ide><path>keras/layers/recurrent.py <ide> def step(self, x, states): <ide> z = self.inner_activation(x_z + K.dot(h_tm1, self.U_z)) <ide> r = self.inner_activation(x_r + K.dot(h_tm1, self.U_r)) <ide> <del> hh = self.inner_activation(x_h + K.dot(r * h_tm1, self.U_h)) <add> hh = self.activation(x_h + K.dot(r * h_tm1, self.U_h)) <ide> h = z * h_tm1 + (1 - z) * hh <ide> return h, [h] <ide>
1
Text
Text
add v3.18.0-beta.1 to changelog
0e47aa17097bc515f16e93157aff4e965d89d994
<ide><path>CHANGELOG.md <ide> # Ember Changelog <ide> <add>### v3.18.0-beta.1 (March 5, 2020) <add> <add>- [#18774](https://github.com/emberjs/ember.js/pull/18774) [BUGFIX] Suspend observer deactivation during property changes <add>- [#18785](https://github.com/emberjs/ember.js/pull/18785) Drop Node 8 support. <add> <ide> ### v3.17.0 (March 4, 2020) <ide> <ide> - [#18688](https://github.com/emberjs/ember.js/pull/18688) / [#18621](https://github.com/emberjs/ember.js/pull/18621) / [#18714](https://github.com/emberjs/ember.js/pull/18714) / [#18743](https://github.com/emberjs/ember.js/pull/18743) / [#18762](https://github.com/emberjs/ember.js/pull/18762) Upgrades Glimmer VM to 0.47.9, fixes ignored `checked` attribute on `input`, fixes using `array` and `hash` helper together
1
Ruby
Ruby
remove ogx mime type from tests
e3d658e319bd0ab179fc0e12329ed4dc18bce584
<ide><path>actionpack/test/dispatch/mime_type_test.rb <ide> class MimeTypeTest < ActiveSupport::TestCase <ide> <ide> test "parse application with trailing star" do <ide> accept = "application/*" <del> expect = [Mime[:html], Mime[:js], Mime[:xml], Mime[:rss], Mime[:atom], Mime[:yaml], Mime[:url_encoded_form], Mime[:json], Mime[:pdf], Mime[:zip], Mime[:gzip], Mime[:ogx]] <add> expect = [Mime[:html], Mime[:js], Mime[:xml], Mime[:rss], Mime[:atom], Mime[:yaml], Mime[:url_encoded_form], Mime[:json], Mime[:pdf], Mime[:zip], Mime[:gzip]] <ide> parsed = Mime::Type.parse(accept) <ide> assert_equal expect.map(&:to_s).sort!, parsed.map(&:to_s).sort! <ide> end
1
Javascript
Javascript
use safeset to filter known special protocols
0d2311820d50e29b83eb9f885d961f9b43dfd165
<ide><path>lib/url.js <ide> const { toASCII } = process.binding('config').hasIntl ? <ide> <ide> const { hexTable } = require('internal/querystring'); <ide> <add>const { SafeSet } = require('internal/safe_globals'); <add> <ide> const { <ide> ERR_INVALID_ARG_TYPE <ide> } = require('internal/errors').codes; <ide> const simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/; <ide> <ide> const hostnameMaxLen = 255; <ide> // protocols that can allow "unsafe" and "unwise" chars. <del>const unsafeProtocol = { <del> 'javascript': true, <del> 'javascript:': true <del>}; <add>const unsafeProtocol = new SafeSet([ <add> 'javascript', <add> 'javascript:' <add>]); <ide> // protocols that never have a hostname. <del>const hostlessProtocol = { <del> 'javascript': true, <del> 'javascript:': true <del>}; <add>const hostlessProtocol = new SafeSet([ <add> 'javascript', <add> 'javascript:' <add>]); <ide> // protocols that always contain a // bit. <del>const slashedProtocol = { <del> 'http': true, <del> 'http:': true, <del> 'https': true, <del> 'https:': true, <del> 'ftp': true, <del> 'ftp:': true, <del> 'gopher': true, <del> 'gopher:': true, <del> 'file': true, <del> 'file:': true <del>}; <add>const slashedProtocol = new SafeSet([ <add> 'http', <add> 'http:', <add> 'https', <add> 'https:', <add> 'ftp', <add> 'ftp:', <add> 'gopher', <add> 'gopher:', <add> 'file', <add> 'file:' <add>]); <ide> const { <ide> CHAR_SPACE, <ide> CHAR_TAB, <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> if (slashesDenoteHost || proto || hostPattern.test(rest)) { <ide> var slashes = rest.charCodeAt(0) === CHAR_FORWARD_SLASH && <ide> rest.charCodeAt(1) === CHAR_FORWARD_SLASH; <del> if (slashes && !(proto && hostlessProtocol[lowerProto])) { <add> if (slashes && !(proto && hostlessProtocol.has(lowerProto))) { <ide> rest = rest.slice(2); <ide> this.slashes = true; <ide> } <ide> } <ide> <del> if (!hostlessProtocol[lowerProto] && <del> (slashes || (proto && !slashedProtocol[proto]))) { <add> if (!hostlessProtocol.has(lowerProto) && <add> (slashes || (proto && !slashedProtocol.has(proto)))) { <ide> <ide> // there's a hostname. <ide> // the first instance of /, ?, ;, or # ends the host. <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> <ide> // now rest is set to the post-host stuff. <ide> // chop off any delim chars. <del> if (!unsafeProtocol[lowerProto]) { <add> if (!unsafeProtocol.has(lowerProto)) { <ide> // First, make 100% sure that any "autoEscape" chars get <ide> // escaped, even if encodeURIComponent doesn't think they <ide> // need to be. <ide> Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { <ide> } else if (firstIdx > 0) { <ide> this.pathname = rest.slice(0, firstIdx); <ide> } <del> if (slashedProtocol[lowerProto] && <add> if (slashedProtocol.has(lowerProto) && <ide> this.hostname && !this.pathname) { <ide> this.pathname = '/'; <ide> } <ide> Url.prototype.format = function format() { <ide> <ide> // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. <ide> // unless they had them to begin with. <del> if (this.slashes || slashedProtocol[protocol]) { <add> if (this.slashes || slashedProtocol.has(protocol)) { <ide> if (this.slashes || host) { <ide> if (pathname && pathname.charCodeAt(0) !== CHAR_FORWARD_SLASH) <ide> pathname = '/' + pathname; <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> } <ide> <ide> // urlParse appends trailing / to urls like http://www.example.com <del> if (slashedProtocol[result.protocol] && <add> if (slashedProtocol.has(result.protocol) && <ide> result.hostname && !result.pathname) { <ide> result.path = result.pathname = '/'; <ide> } <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> // if it is file:, then the host is dropped, <ide> // because that's known to be hostless. <ide> // anything else is assumed to be absolute. <del> if (!slashedProtocol[relative.protocol]) { <add> if (!slashedProtocol.has(relative.protocol)) { <ide> var keys = Object.keys(relative); <ide> for (var v = 0; v < keys.length; v++) { <ide> var k = keys[v]; <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> result.protocol = relative.protocol; <ide> if (!relative.host && <ide> !/^file:?$/.test(relative.protocol) && <del> !hostlessProtocol[relative.protocol]) { <add> !hostlessProtocol.has(relative.protocol)) { <ide> const relPath = (relative.pathname || '').split('/'); <ide> while (relPath.length && !(relative.host = relPath.shift())); <ide> if (!relative.host) relative.host = ''; <ide> Url.prototype.resolveObject = function resolveObject(relative) { <ide> var removeAllDots = mustEndAbs; <ide> var srcPath = result.pathname && result.pathname.split('/') || []; <ide> var relPath = relative.pathname && relative.pathname.split('/') || []; <del> var noLeadingSlashes = result.protocol && !slashedProtocol[result.protocol]; <add> var noLeadingSlashes = result.protocol && <add> !slashedProtocol.has(result.protocol); <ide> <ide> // if the url is a non-slashed url, then relative <ide> // links like ../.. should be able
1
Ruby
Ruby
separate the brew info for multiple formulae
4303817ec78bbd7a36b919062f6fada64a337028
<ide><path>Library/Homebrew/cmd/info.rb <ide> def print_info <ide> puts "#{HOMEBREW_CELLAR.children.length} kegs, #{HOMEBREW_CELLAR.abv}" <ide> end <ide> else <del> ARGV.named.each do |f| <add> ARGV.named.each_with_index do |f,i| <add> puts unless i == 0 <ide> begin <ide> info_formula Formula.factory(f) <ide> rescue FormulaUnavailableError
1
PHP
PHP
fix cs error
61f77ff1c89d3fba1de8959c00844432903d9d3d
<ide><path>tests/TestCase/Cache/SimpleCacheEngineTest.php <ide> <ide> namespace Cake\Test\TestCase\Cache; <ide> <del>use Cake\Cache\CacheEngine; <ide> use Cake\Cache\Engine\FileEngine; <ide> use Cake\Cache\SimpleCacheEngine; <ide> use Cake\TestSuite\TestCase;
1
PHP
PHP
update component.php
dae4e17286aa9d482f548c2883caa01e9435dd75
<ide><path>src/Illuminate/View/Component.php <ide> abstract class Component <ide> /** <ide> * Get the view / view contents that represent the component. <ide> * <del> * @return \Illuminate\View\View|string <add> * @return \Illuminate\View\View|\Closure|string <ide> */ <ide> abstract public function render(); <ide> <ide> /** <ide> * Resolve the Blade view or view file that should be used when rendering the component. <ide> * <del> * @return \Illuminate\View\View|string <add> * @return \Illuminate\View\View|\Closure|string <ide> */ <ide> public function resolveView() <ide> {
1
Text
Text
add missing entries for v1.6.0-rc.0/v1.6.0
baa30695f3378554a23c6796ff6444d25d9bb0de
<ide><path>CHANGELOG.md <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> - **ngModelOptions:** allow options to be inherited from ancestor `ngModelOptions` <ide> ([296cfc](https://github.com/angular/angular.js/commit/296cfce40c25e9438bfa46a0eb27240707a10ffa), <ide> [#10922](https://github.com/angular/angular.js/issues/10922)) <del>- **$compile:** set `preAssignBindingsEnabled` to false by default <del> ([bcd0d4](https://github.com/angular/angular.js/commit/bcd0d4d896d0dfdd988ff4f849c1d40366125858), <del> [#15352](https://github.com/angular/angular.js/issues/15352)) <add>- **$compile:** <add> - add `preAssignBindingsEnabled` option <add> ([dfb8cf](https://github.com/angular/angular.js/commit/dfb8cf6402678206132e5bc603764d21e0f986ef)) <add> - set `preAssignBindingsEnabled` to false by default <add> ([bcd0d4](https://github.com/angular/angular.js/commit/bcd0d4d896d0dfdd988ff4f849c1d40366125858), <add> [#15352](https://github.com/angular/angular.js/issues/15352)) <add> - throw error when directive name or factory function is invalid <add> ([53a3bf](https://github.com/angular/angular.js/commit/53a3bf6634600c3aeff092eacc35edf399b27aec) <add> [#15056](https://github.com/angular/angular.js/issues/15056)) <ide> - **jqLite:** <ide> - implement `jqLite(f)` as an alias to `jqLite(document).ready(f)` <ide> ([369fb7](https://github.com/angular/angular.js/commit/369fb7f4f73664bcdab0350701552d8bef6f605e)) <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> - JSONP requests now require a trusted resource URL <ide> ([6476af](https://github.com/angular/angular.js/commit/6476af83cd0418c84e034a955b12a842794385c4), <ide> [#11352](https://github.com/angular/angular.js/issues/11352)) <add>- **$anchorScroll:** convert numeric hash targets to string <add> ([9062ba](https://github.com/angular/angular.js/commit/9062bae05c002934fe7bfd76043dcc3de9acfde6) <add> [#14680](https://github.com/angular/angular.js/issues/14680)) <ide> - **select:** support values of any type added with `ngValue` <ide> ([f02b70](https://github.com/angular/angular.js/commit/f02b707b5e4a5ffd1e1a20d910754cfabfc19622), <ide> [#9842](https://github.com/angular/angular.js/issues/9842)) <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> [#10597](https://github.com/angular/angular.js/issues/10597)) <ide> - allow `ngTrim` to work for `input[type=radio]` <ide> ([47724b](https://github.com/angular/angular.js/commit/47724baffe050269385b3481e9a9cf4ab3944b4b)) <add>- **ngSwitch:** allow multiple case matches via optional attribute `ngSwitchWhenSeparator` <add> ([0b221](https://github.com/angular/angular.js/commit/0b22173000596bf4b78f6a90083b994d46164d79) <add> [#3410](https://github.com/angular/angular.js/issues/3410) <add> [#3516](https://github.com/angular/angular.js/issues/3516)) <ide> - **$interpolate:** use custom `toString()` function if present <ide> ([a5fd2e](https://github.com/angular/angular.js/commit/a5fd2e4c0376676fa317e09a8d8be4966b82cbfe), <ide> [#7317](https://github.com/angular/angular.js/issues/7317), <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> ([c9dffd](https://github.com/angular/angular.js/commit/c9dffde1cb167660120753181cb6d01dc1d1b3d0), <ide> [#13653](https://github.com/angular/angular.js/issues/13653), <ide> [#7992](https://github.com/angular/angular.js/issues/7992)) <del>- **$location:** default hashPrefix to `'!'` <del> ([aa077e](https://github.com/angular/angular.js/commit/aa077e81129c740041438688dff2e8d20c3d7b52), <del> [#13812](https://github.com/angular/angular.js/issues/13812)) <add>- **$resource:** pass `status`/`statusText` to success callbacks <add> ([e3a378](https://github.com/angular/angular.js/commit/e3a378e7a329f60f6b48517f83a4f4c9efecb056) <add> [#8341](https://github.com/angular/angular.js/issues/8841) <add> [#8841](https://github.com/angular/angular.js/issues/8841)) <add>- **$location:** <add> - default hashPrefix to `'!'` <add> ([aa077e](https://github.com/angular/angular.js/commit/aa077e81129c740041438688dff2e8d20c3d7b52) <add> [#13812](https://github.com/angular/angular.js/issues/13812)) <add> - add support for selectively rewriting links based on attribute <add> ([3d686a](https://github.com/angular/angular.js/commit/3d686a988dc4373da094cff6905e5b0d8da6afa4)) <add>- **$controller:** throw when requested controller is not registered <add> ([eacfe4](https://github.com/angular/angular.js/commit/eacfe4148eb97e550117ed7fd3c37b58537a9f64) <add> [#14980](https://github.com/angular/angular.js/issues/14980)) <ide> <ide> <ide> <ide> ## Security Related <ide> - Please read the [Sandbox Removal Blog Post](http://angularjs.blogspot.com/2016/09/angular-16-expression-sandbox-removal.html). <del>- **bootstrap:** explicitly whitelist URL schemes for bootstrap. (#15427) <del> ([7f1b8b](https://github.com/angular/angular.js/commit/7f1b8bdfe1043871c5ead2ec602efc41e0de5e53)) <add>- **bootstrap:** <add> - explicitly whitelist URL schemes for bootstrap. <add> ([7f1b8b](https://github.com/angular/angular.js/commit/7f1b8bdfe1043871c5ead2ec602efc41e0de5e53)) <ide> - do not bootstrap from unknown schemes with a different origin <del> ([465d17](https://github.com/angular/angular.js/commit/465d1734559ca4a7f4aa24387060f88fcc53ecb1)) <add> ([465d17](https://github.com/angular/angular.js/commit/465d1734559ca4a7f4aa24387060f88fcc53ecb1) <add> [#15428](https://github.com/angular/angular.js/issues/15428)) <ide> - **$compile:** <ide> - secure `link[href]` as a `RESOURCE_URL`s in `$sce` <ide> ([04cad4](https://github.com/angular/angular.js/commit/04cad41d26ebaf44b5ee0c29a152d61f235f3efa), <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> <ide> <ide> ## Bug Fixes <del>- **$sce:** fix `adjustMatcher` to replace multiple '*' and '**' (#7897) <add>- **$sce:** fix `adjustMatcher` to replace multiple `*` and `**` <ide> ([991a2b](https://github.com/angular/angular.js/commit/991a2b30e00aed1d312e29555e356a795f9e3d62)) <ide> - **ngModelOptions:** handle debounce of `updateOn` triggers that are not in debounce list <ide> ([789790](https://github.com/angular/angular.js/commit/789790feee4d6c5b1f5d5b18ecb0ccf6edd36fb3)) <ide> - **ngMock/$controller:** respect `$compileProvider.preAssignBindingsEnabled()` <ide> ([7d9a79](https://github.com/angular/angular.js/commit/7d9a791c6a8c80d29d6c84afa287c81f2a307439)) <del>- **$location:** throw if the path starts with double (back)slashes <del> ([4aa953](https://github.com/angular/angular.js/commit/4aa9534b0fea732d6492a2863c3ee7e077c8d004)) <add>- **$location:** <add> - prevent infinite digest with IDN URLs in Edge <add> ([705afc](https://github.com/angular/angular.js/commit/705afcd160c8428133b36f2cd63db305dc52f2d7) <add> [#15217](https://github.com/angular/angular.js/issues/15217)) <add> - throw if the path starts with double (back)slashes <add> ([4aa953](https://github.com/angular/angular.js/commit/4aa9534b0fea732d6492a2863c3ee7e077c8d004)) <ide> - **core:** do not auto-bootstrap when loaded from an extension. <ide> ([0ff10e](https://github.com/angular/angular.js/commit/0ff10e1b56c6b7c4ac465e35c96a5886e294bac5)) <ide> - **input[radio]:** use strict comparison when evaluating checked-ness <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> - don't throw tplrt error when there is a whitespace around a top-level comment <ide> ([76d3da](https://github.com/angular/angular.js/commit/76d3dafdeaf2f343d094b5a34ffb74adf64bb284), <ide> [#15108](https://github.com/angular/angular.js/issues/15108)) <add> - clean up `@`-binding observers when re-assigning bindings <add> ([586e2a](https://github.com/angular/angular.js/commit/586e2acb269016a0fee66ac33f4a385f631afad0) <add> [#15268](https://github.com/angular/angular.js/issues/15268)) <add> - set attribute value even if `ngAttr*` contains no interpolation <add> ([3fe3da](https://github.com/angular/angular.js/commit/3fe3da8794571a1479d884be26a621f06cdb7842) <add> [#15133](https://github.com/angular/angular.js/issues/15133)) <add> - `bindToController` should work without `controllerAs` <add> ([16dcce](https://github.com/angular/angular.js/commit/16dccea8873b06285d4ec6eb3bb8e96ccbd3b64e) <add> [#15088](https://github.com/angular/angular.js/issues/15088)) <add> - do not overwrite values set in `$onInit()` for `<`-bound literals <add> ([a1bdff](https://github.com/angular/angular.js/commit/a1bdffa12f82e838dee5492956b380df7e54cdf9) <add> [#15118](https://github.com/angular/angular.js/issues/15118)) <add> - avoid calling `$onChanges()` twice for `NaN` initial values <add> ([7d7efb](https://github.com/angular/angular.js/commit/7d7efbf545c8c07713eb45301660dcfca4121445)) <ide> - disallow linking the same element more than once <ide> ([1e1fbc](https://github.com/angular/angular.js/commit/1e1fbc75f5e20e8541f517a5cf6f30f8f2eed53f)) <ide> - correctly merge consecutive text nodes on IE11 <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> [#5513](https://github.com/angular/angular.js/issues/5513), <ide> [#5597](https://github.com/angular/angular.js/issues/5597)) <ide> - move check for interpolation of on-event attributes to compile time <del> ([b89c21](https://github.com/angular/angular.js/commit/b89c2181a9a165e06c027390164e08635ec449f4), <del> [#13267](https://github.com/angular/angular.js/issues/13267)) <add> ([b89c21](https://github.com/angular/angular.js/commit/b89c2181a9a165e06c027390164e08635ec449f4), <add> [#13267](https://github.com/angular/angular.js/issues/13267)) <ide> - **select, ngOptions, ngValue:** <ide> - don't add comment nodes as empty options <ide> ([245b27](https://github.com/angular/angular.js/commit/245b27101aad129061585252b73652054319ca82), <ide> [#15454](https://github.com/angular/angular.js/issues/15454)) <ide> - do not throw when removing the element (e.g. via `ngIf`) <del> ([7a667c](https://github.com/angular/angular.js/commit/7a667c77e36f2b1738425a9cfb52d48bb9d8220f)) <add> ([7a667c](https://github.com/angular/angular.js/commit/7a667c77e36f2b1738425a9cfb52d48bb9d8220f)) <ide> - add/remove selected attribute for selected/unselected options <ide> ([c75698](https://github.com/angular/angular.js/commit/c75698df55f5a026bcd7fcecbb9d4ff0bc3ebc3e)) <ide> - don't register options when select has no ngModel <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> ([e6afca](https://github.com/angular/angular.js/commit/e6afca00c9061a3e13b570796ca3ab428c1723a1), <ide> [#14031](https://github.com/angular/angular.js/issues/14031)) <ide> - **$resource:** <del> - **$resource:** allow params in `hostname` (except for IPv6 addresses) <add> - allow params in `hostname` (except for IPv6 addresses) <ide> ([752b1e](https://github.com/angular/angular.js/commit/752b1e69b7a8e9c0b908f1980e9c738888f3647c), <ide> [#14542](https://github.com/angular/angular.js/issues/14542)) <ide> - fulfill promise with the correct value on error <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> - **loader:** `module.decorator` order of operations is now irrelevant <ide> ([6a2ebd](https://github.com/angular/angular.js/commit/6a2ebdba5df27e789e3cb10f11eedf90f7b9b97e), <ide> [#12382](https://github.com/angular/angular.js/issues/12382)) <add>- **$sanitize:** reduce stack height in IE <= 11 <add> ([45129c](https://github.com/angular/angular.js/commit/45129cfd06104bd89f469dded9ccbaf20894bd76) <add> [#14928](https://github.com/angular/angular.js/issues/14928)) <ide> - **ngAnimate:** make svg elements work with `classNameFilter` <ide> ([81bf7e](https://github.com/angular/angular.js/commit/81bf7ed73ee67f9eb997da869c52839449ca02b3)) <ide> <ide> consolidating all the changes shown in the previous 1.6.0 release candidates.** <ide> ([d71dc2](https://github.com/angular/angular.js/commit/d71dc2f5afec230711351e9f160873a41eb60597)) <ide> - **injector:** cache the results of the native class detection check <ide> ([5ceb5d](https://github.com/angular/angular.js/commit/5ceb5dbfa6d9b6d15232a1f5c767b2f431325948)) <del>- **$compile:** use strict comparison for `controller === '@'` <del> ([bbd3db](https://github.com/angular/angular.js/commit/bbd3db14f857aab996ad129f2f15ca6348e9fd9f)) <add>- **$compile:** <add> - use strict comparison for `controller === '@'` <add> ([bbd3db](https://github.com/angular/angular.js/commit/bbd3db14f857aab996ad129f2f15ca6348e9fd9f)) <add> - validate `directive.restrict` property on directive init <add> ([11f273](https://github.com/angular/angular.js/commit/11f2731f72e932615e8ce15e6a73f4ac808cc7e7)) <ide> - **$parse:** <ide> - Inline constants <ide> ([bd7d5f](https://github.com/angular/angular.js/commit/bd7d5f6345439aa2d1da708ffee20b4c565131d4)) <ide> Please read the [Sandbox Removal Blog Post](http://angularjs.blogspot.com/2016/0 <ide> - **ngModel:** treat synchronous validators as boolean always ([7bc71a](https://github.com/angular/angular.js/commit/7bc71adc63bb6bb609b44dd2d3ea8fb0cd3f300b) [#14734](https://github.com/angular/angular.js/issues/14734)) <ide> - **$q:** treat thrown errors as regular rejections ([e13eea](https://github.com/angular/angular.js/commit/e13eeabd7e34a78becec06cfbe72c23f2dcb85f9) [#3174](https://github.com/angular/angular.js/issues/3174) [#15213](https://github.com/angular/angular.js/issues/15213)) <ide> - **ngTransclude:** use fallback content if only whitespace is provided ([32aa7e](https://github.com/angular/angular.js/commit/32aa7e7395527624119e3917c54ee43b4d219301) [#15077](https://github.com/angular/angular.js/issues/15077)) <add>- **$location:** prevent infinite digest with IDN URLs in Edge ([705afc](https://github.com/angular/angular.js/commit/705afcd160c8428133b36f2cd63db305dc52f2d7) [#15217](https://github.com/angular/angular.js/issues/15217)) <ide> - **$compile:** <ide> - don't throw tplrt error when there is a whitespace around a top-level comment ([76d3da](https://github.com/angular/angular.js/commit/76d3dafdeaf2f343d094b5a34ffb74adf64bb284) [#15108](https://github.com/angular/angular.js/issues/15108)) <ide> - disallow linking the same element more than once ([1e1fbc](https://github.com/angular/angular.js/commit/1e1fbc75f5e20e8541f517a5cf6f30f8f2eed53f)) <ide> Please read the [Sandbox Removal Blog Post](http://angularjs.blogspot.com/2016/0 <ide> - don't add leading white-space in attributes for a specific merge case ([305ba1](https://github.com/angular/angular.js/commit/305ba1a3fb3529cb3fdf04c12ac03fbb4f634456)) <ide> - don't trim white-space in attributes ([97bbf8](https://github.com/angular/angular.js/commit/97bbf86a1979d099802f0d631c17c54b87563b40) [#5513](https://github.com/angular/angular.js/issues/5513) [#5597](https://github.com/angular/angular.js/issues/5597)) <ide> - move check for interpolation of on-event attributes to compile time ([b89c21](https://github.com/angular/angular.js/commit/b89c2181a9a165e06c027390164e08635ec449f4) [#13267](https://github.com/angular/angular.js/issues/13267)) <add> - clean up `@`-binding observers when re-assigning bindings <add> ([586e2a](https://github.com/angular/angular.js/commit/586e2acb269016a0fee66ac33f4a385f631afad0) <add> [#15268](https://github.com/angular/angular.js/issues/15268)) <add> - set attribute value even if `ngAttr*` contains no interpolation <add> ([3fe3da](https://github.com/angular/angular.js/commit/3fe3da8794571a1479d884be26a621f06cdb7842) <add> [#15133](https://github.com/angular/angular.js/issues/15133)) <add> - `bindToController` should work without `controllerAs` <add> ([16dcce](https://github.com/angular/angular.js/commit/16dccea8873b06285d4ec6eb3bb8e96ccbd3b64e) <add> [#15088](https://github.com/angular/angular.js/issues/15088)) <add> - do not overwrite values set in `$onInit()` for `<`-bound literals <add> ([a1bdff](https://github.com/angular/angular.js/commit/a1bdffa12f82e838dee5492956b380df7e54cdf9) <add> [#15118](https://github.com/angular/angular.js/issues/15118)) <add> - avoid calling `$onChanges()` twice for `NaN` initial values <add> ([7d7efb](https://github.com/angular/angular.js/commit/7d7efbf545c8c07713eb45301660dcfca4121445)) <ide> - **select:** <ide> - add/remove selected attribute for selected/unselected options ([c75698](https://github.com/angular/angular.js/commit/c75698df55f5a026bcd7fcecbb9d4ff0bc3ebc3e)) <ide> - don't register options when select has no ngModel ([e8c2e1](https://github.com/angular/angular.js/commit/e8c2e119758e58e18fe43932d09a8ff9f506aa9d)) <ide> Please read the [Sandbox Removal Blog Post](http://angularjs.blogspot.com/2016/0 <ide> - **ngMock/$httpBackend:** fail if a url is provided but is `undefined` ([7551b8](https://github.com/angular/angular.js/commit/7551b8975a91ee286cc2cf4af5e78f924533575e) [#8442](https://github.com/angular/angular.js/issues/8442) [#10934](https://github.com/angular/angular.js/issues/10934)) <ide> - **$route:** don't process route change controllers and templates for `redirectTo` routes ([7f4b35](https://github.com/angular/angular.js/commit/7f4b356c2bebb87f0c26b57a20415b004b20bcd1) [#3332](https://github.com/angular/angular.js/issues/3332)) <ide> - **loader:** `module.decorator` order of operations is now irrelevant ([6a2ebd](https://github.com/angular/angular.js/commit/6a2ebdba5df27e789e3cb10f11eedf90f7b9b97e) [#12382](https://github.com/angular/angular.js/issues/12382)) <add>- **$sanitize:** reduce stack height in IE <= 11 <add> ([45129c](https://github.com/angular/angular.js/commit/45129cfd06104bd89f469dded9ccbaf20894bd76) <add> [#14928](https://github.com/angular/angular.js/issues/14928)) <ide> - **ngAnimate:** make svg elements work with `classNameFilter` ([81bf7e](https://github.com/angular/angular.js/commit/81bf7ed73ee67f9eb997da869c52839449ca02b3)) <ide> <ide> <ide> Please read the [Sandbox Removal Blog Post](http://angularjs.blogspot.com/2016/0 <ide> - don't remove a boolean attribute for `.attr(attrName, '')` ([3faf45](https://github.com/angular/angular.js/commit/3faf4505732758165083c9d21de71fa9b6983f4a)) <ide> - remove the attribute for `.attr(attribute, null)` ([4e3624](https://github.com/angular/angular.js/commit/4e3624552284d0e725bf6262b2e468cd2c7682fa)) <ide> - return `[]` for `.val()` on `<select multiple>` with no selection ([d882fd](https://github.com/angular/angular.js/commit/d882fde2e532216e7cf424495db1ccb5be1789f8)) <add>- **$compile:** <add> - add `preAssignBindingsEnabled` option <add> ([dfb8cf](https://github.com/angular/angular.js/commit/dfb8cf6402678206132e5bc603764d21e0f986ef)) <add> - throw error when directive name or factory function is invalid <add> ([53a3bf](https://github.com/angular/angular.js/commit/53a3bf6634600c3aeff092eacc35edf399b27aec) <add> [#15056](https://github.com/angular/angular.js/issues/15056)) <ide> - **$http:** <ide> - remove deprecated callback methods: `success()/error()` ([b54a39](https://github.com/angular/angular.js/commit/b54a39e2029005e0572fbd2ac0e8f6a4e5d69014)) <ide> - JSONP callback must be specified by `jsonpCallbackParam` config ([fb6634](https://github.com/angular/angular.js/commit/fb663418710736161a6b5da49c345e92edf58dcb) [#15161](https://github.com/angular/angular.js/issues/15161) [#11352](https://github.com/angular/angular.js/issues/11352)) <ide> - JSONP requests now require a trusted resource URL ([6476af](https://github.com/angular/angular.js/commit/6476af83cd0418c84e034a955b12a842794385c4) [#11352](https://github.com/angular/angular.js/issues/11352)) <add>- **$anchorScroll:** convert numeric hash targets to string <add> ([9062ba](https://github.com/angular/angular.js/commit/9062bae05c002934fe7bfd76043dcc3de9acfde6) <add> [#14680](https://github.com/angular/angular.js/issues/14680)) <ide> - **ngModelOptions:** allow options to be inherited from ancestor `ngModelOptions` ([87a2ff](https://github.com/angular/angular.js/commit/87a2ff76af5d0a9268d8eb84db5755077d27c84c) [#10922](https://github.com/angular/angular.js/issues/10922)) <ide> - **input:** <ide> - add support for binding to `input[type=range]` ([913016](https://github.com/angular/angular.js/commit/9130166767c4792c5d32d08a918fc7becf32c9a6) [#5892](https://github.com/angular/angular.js/issues/5892) [#14870](https://github.com/angular/angular.js/issues/14870)) <ide> - add support for `step` to `input[type=number]` ([e1da4be](https://github.com/angular/angular.js/commit/e1da4bed8e291003d485a8ad346ab80bed8ae2e3) [#10597](https://github.com/angular/angular.js/issues/10597)) <ide> - allow `ngTrim` to work for `input[type=radio]` ([47724b](https://github.com/angular/angular.js/commit/47724baffe050269385b3481e9a9cf4ab3944b4b)) <add>- **ngSwitch:** allow multiple case matches via optional attribute `ngSwitchWhenSeparator` <add> ([0b221](https://github.com/angular/angular.js/commit/0b22173000596bf4b78f6a90083b994d46164d79) <add> [#3410](https://github.com/angular/angular.js/issues/3410) <add> [#3516](https://github.com/angular/angular.js/issues/3516)) <ide> - **ngRoute:** allow `ngView` to be included in an asynchronously loaded template ([c13c66](https://github.com/angular/angular.js/commit/c13c666728c1a1485ef18e92d7cb35118ce39609) [#1213](https://github.com/angular/angular.js/issues/1213)) <ide> - **select:** support values of any type added with `ngValue` ([f02b70](https://github.com/angular/angular.js/commit/f02b707b5e4a5ffd1e1a20d910754cfabfc19622) [#9842](https://github.com/angular/angular.js/issues/9842)) <ide> - **$interpolate:** use custom `toString()` function if present ([a5fd2e](https://github.com/angular/angular.js/commit/a5fd2e4c0376676fa317e09a8d8be4966b82cbfe) [#7317](https://github.com/angular/angular.js/issues/7317) [#11406](https://github.com/angular/angular.js/issues/11406)) <ide> - **$route:** implement `resolveRedirectTo` ([e98656](https://github.com/angular/angular.js/commit/e9865654b39c71be71034c38581a8c7bd16bc716) [#5150](https://github.com/angular/angular.js/issues/5150)) <ide> - **$q:** report promises with non rejection callback ([c9dffd](https://github.com/angular/angular.js/commit/c9dffde1cb167660120753181cb6d01dc1d1b3d0) [#13653](https://github.com/angular/angular.js/issues/13653) [#7992](https://github.com/angular/angular.js/issues/7992)) <del>- **$location:** default hashPrefix to `'!'` ([aa077e](https://github.com/angular/angular.js/commit/aa077e81129c740041438688dff2e8d20c3d7b52) [#13812](https://github.com/angular/angular.js/issues/13812)) <add>- **$resource:** pass `status`/`statusText` to success callbacks <add> ([e3a378](https://github.com/angular/angular.js/commit/e3a378e7a329f60f6b48517f83a4f4c9efecb056) <add> [#8341](https://github.com/angular/angular.js/issues/8841) <add> [#8841](https://github.com/angular/angular.js/issues/8841)) <add>- **$location:** <add> - default hashPrefix to `'!'` <add> ([aa077e](https://github.com/angular/angular.js/commit/aa077e81129c740041438688dff2e8d20c3d7b52) <add> [#13812](https://github.com/angular/angular.js/issues/13812)) <add> - add support for selectively rewriting links based on attribute <add> ([3d686a](https://github.com/angular/angular.js/commit/3d686a988dc4373da094cff6905e5b0d8da6afa4)) <add>- **$controller:** throw when requested controller is not registered <add> ([eacfe4](https://github.com/angular/angular.js/commit/eacfe4148eb97e550117ed7fd3c37b58537a9f64) <add> [#14980](https://github.com/angular/angular.js/issues/14980)) <ide> <ide> <ide> ## Performance Improvements <ide> Please read the [Sandbox Removal Blog Post](http://angularjs.blogspot.com/2016/0 <ide> - **$animate:** listen for document visibility changes ([d71dc2](https://github.com/angular/angular.js/commit/d71dc2f5afec230711351e9f160873a41eb60597)) <ide> - **injector:** cache the results of the native class detection check ([5ceb5d](https://github.com/angular/angular.js/commit/5ceb5dbfa6d9b6d15232a1f5c767b2f431325948)) <ide> - **$parse:** Inline constants ([bd7d5f](https://github.com/angular/angular.js/commit/bd7d5f6345439aa2d1da708ffee20b4c565131d4)) <del>- **$compile:** use strict comparison for `controller === '@'` ([bbd3db](https://github.com/angular/angular.js/commit/bbd3db14f857aab996ad129f2f15ca6348e9fd9f)) <add>- **$compile:** <add> - use strict comparison for `controller === '@'` <add> ([bbd3db](https://github.com/angular/angular.js/commit/bbd3db14f857aab996ad129f2f15ca6348e9fd9f)) <add> - validate `directive.restrict` property on directive init <add> ([11f273](https://github.com/angular/angular.js/commit/11f2731f72e932615e8ce15e6a73f4ac808cc7e7)) <ide> - **$parse:** remove Angular expression sandbox ([1547c7](https://github.com/angular/angular.js/commit/1547c751aa48efe7dbefef701c3df5983b04aa2e) [#15094](https://github.com/angular/angular.js/issues/15094)) <ide> <ide>
1
Javascript
Javascript
fix breaking of pickerandroid when child is null.
cd18527e7768b3f1a29442094f10c65f823c1bf1
<ide><path>Libraries/Components/Picker/PickerAndroid.android.js <ide> class PickerAndroid extends React.Component< <ide> ): PickerAndroidState { <ide> let selectedIndex = 0; <ide> const items = React.Children.map(props.children, (child, index) => { <add> if (child === null) { <add> return; <add> } <ide> if (child.props.value === props.selectedValue) { <ide> selectedIndex = index; <ide> }
1
Python
Python
fix typo in test_views.py
05586d66572a990a802c4186933bfe41624e4947
<ide><path>tests/www/test_views.py <ide> def test_dt_nr_dr_form_default_parameters(self): <ide> def test_dt_nr_dr_form_with_execution_date_parameter_only(self): <ide> self.tester.test_with_execution_date_parameter_only() <ide> <del> def test_dt_nr_dr_form_with_base_date_and_num_runs_parmeters_only(self): <add> def test_dt_nr_dr_form_with_base_date_and_num_runs_parameters_only(self): <ide> self.tester.test_with_base_date_and_num_runs_parameters_only() <ide> <ide> def test_dt_nr_dr_form_with_base_date_and_num_runs_and_execution_date_outside(self): <ide> def test_dt_nr_dr_form_default_parameters(self): <ide> def test_dt_nr_dr_form_with_execution_date_parameter_only(self): <ide> self.tester.test_with_execution_date_parameter_only() <ide> <del> def test_dt_nr_dr_form_with_base_date_and_num_runs_parmeters_only(self): <add> def test_dt_nr_dr_form_with_base_date_and_num_runs_parameters_only(self): <ide> self.tester.test_with_base_date_and_num_runs_parameters_only() <ide> <ide> def test_dt_nr_dr_form_with_base_date_and_num_runs_and_execution_date_outside(self):
1
Javascript
Javascript
fix a typo
725028b07dbd60d0f40b94be3fe191d4e8c93cc9
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> * $resource} service. <ide> * <ide> * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by <del> * the $q service. While for simple usage patters this doesn't matter much, for advanced usage, <add> * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage, <ide> * it is important to familiarize yourself with these apis and guarantees they provide. <ide> * <ide> *
1
Go
Go
drop queries in root doamin when ndots is set
db9a7021ac961169a1890cc5c3f7487f97d47684
<ide><path>libnetwork/resolver.go <ide> func (r *resolver) ServeDNS(w dns.ResponseWriter, query *dns.Msg) { <ide> return <ide> } <ide> <add> // If the user sets ndots > 0 explicitly and the query is <add> // in the root domain don't forward it out. We will return <add> // failure and let the client retry with the search domain <add> // attached <add> if resp == nil { <add> switch query.Question[0].Qtype { <add> case dns.TypeA: <add> fallthrough <add> case dns.TypeAAAA: <add> if r.sb.ndotsSet && !strings.Contains(strings.TrimSuffix(name, "."), ".") { <add> resp = createRespMsg(query) <add> } <add> } <add> } <add> <ide> proto := w.LocalAddr().Network() <ide> maxSize := 0 <ide> if proto == "tcp" { <ide><path>libnetwork/sandbox.go <ide> type sandbox struct { <ide> isStub bool <ide> inDelete bool <ide> ingress bool <add> ndotsSet bool <ide> sync.Mutex <ide> } <ide> <ide><path>libnetwork/sandbox_dns_unix.go <ide> import ( <ide> "os" <ide> "path" <ide> "path/filepath" <add> "strconv" <add> "strings" <ide> <ide> log "github.com/Sirupsen/logrus" <ide> "github.com/docker/libnetwork/etchosts" <ide> func (sb *sandbox) rebuildDNS() error { <ide> // external v6 DNS servers has to be listed in resolv.conf <ide> dnsList = append(dnsList, resolvconf.GetNameservers(currRC.Content, types.IPv6)...) <ide> <del> // Resolver returns the options in the format resolv.conf expects <del> dnsOptionsList = append(dnsOptionsList, sb.resolver.ResolverOptions()...) <add> // If the user config and embedded DNS server both have ndots option set, <add> // remember the user's config so that unqualified names not in the docker <add> // domain can be dropped. <add> resOptions := sb.resolver.ResolverOptions() <add> <add>dnsOpt: <add> for _, resOpt := range resOptions { <add> if strings.Contains(resOpt, "ndots") { <add> for _, option := range dnsOptionsList { <add> if strings.Contains(option, "ndots") { <add> parts := strings.Split(option, ":") <add> if len(parts) != 2 { <add> return fmt.Errorf("invalid ndots option %v", option) <add> } <add> if num, err := strconv.Atoi(parts[1]); err != nil { <add> return fmt.Errorf("invalid number for ndots option %v", option) <add> } else if num > 0 { <add> sb.ndotsSet = true <add> break dnsOpt <add> } <add> } <add> } <add> } <add> } <add> <add> dnsOptionsList = append(dnsOptionsList, resOptions...) <ide> <ide> _, err = resolvconf.Build(sb.config.resolvConfPath, dnsList, dnsSearchList, dnsOptionsList) <ide> return err
3
Javascript
Javascript
check non-existent attribute as well to be sure
e93ca40aa7ec4337a57fcdbc699d900e01b4c67e
<ide><path>test/unit/traversing.js <ide> test("filter(jQuery)", function() { <ide> }) <ide> <ide> test("closest()", function() { <del> expect(12); <add> expect(13); <ide> same( jQuery("body").closest("body").get(), q("body"), "closest(body)" ); <ide> same( jQuery("body").closest("html").get(), q("html"), "closest(html)" ); <ide> same( jQuery("body").closest("div").get(), [], "closest(div)" ); <ide> test("closest()", function() { <ide> equals( jQuery("<div><p></p></div>").find("p").closest("table").length, 0, "Make sure disconnected closest work." ); <ide> // Bug #7369 <ide> equals( jQuery('<div foo="bar"></div>').closest('[foo]').length, 1, "Disconnected nodes with attribute selector" ); <add> equals( jQuery('<div></div>').closest('[lang]').length, 0, "Disconnected nodes with non-existent attribute selector" ); <ide> }); <ide> <ide> test("closest(Array)", function() {
1
Python
Python
fix flaky templatized call
ca030b93bdd531cbf2ad57c5d082ddfd0b96c0db
<ide><path>tests/sensors/test_python.py <ide> def test_python_callable_arguments_are_templatized(self): <ide> task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) <ide> <ide> ds_templated = DEFAULT_DATE.date().isoformat() <del> # 2 calls: first: at start, second: before timeout <del> assert 2 == len(recorded_calls) <ide> self._assert_calls_equal( <ide> recorded_calls[0], <ide> Call( <ide> def test_python_callable_keyword_arguments_are_templatized(self): <ide> with pytest.raises(AirflowSensorTimeout): <ide> task.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) <ide> <del> # 2 calls: first: at start, second: before timeout <del> # But sometimes 1 is also OK if the system is "busy" - we anyhow only check the first one which <del> # will always be there <del> assert len(recorded_calls) >= 1 <ide> self._assert_calls_equal( <ide> recorded_calls[0], <ide> Call(
1
Text
Text
fix typo in rails 4.2 release notes
1154879e2f88f2c1e1523f413161c9fd175ff398
<ide><path>guides/source/4_2_release_notes.md <ide> method that sends the email asynchronously via a job in a queue, so it doesn't <ide> block the controller or model. <ide> <ide> The new [Global ID](https://github.com/rails/globalid) library makes it easy <del>to pass Active Record objects to jobs. The library stores a glogal URI that <add>to pass Active Record objects to jobs. The library stores a global URI that <ide> uniquely represents the model without serializing its state. This means you no <ide> longer have to manually pack and unpack your Active Records by passing ids. <ide> Just give the job the Active Record object, its global ID will be stored, and
1
PHP
PHP
fix errors with recursion in debug()
dca050fbd6a14db29f9748cef7a9fcef185c5a51
<ide><path>lib/Cake/Test/Case/Utility/DebuggerTest.php <ide> public function testNoDbCredentials() { <ide> $this->assertEquals($expected, $output); <ide> } <ide> <add>/** <add> * Test that exportVar() doesn't loop through recursive structures. <add> * <add> * @return void <add> */ <add> public function testExportVarRecursion() { <add> $output = Debugger::exportVar($GLOBALS); <add> $this->assertContains("'GLOBALS' => [recursion]", $output); <add> } <add> <ide> /** <ide> * test trace exclude <ide> * <ide><path>lib/Cake/Utility/Debugger.php <ide> protected static function _array(array $var, $depth, $indent) { <ide> <ide> if ($depth >= 0) { <ide> foreach ($var as $key => $val) { <add> if ($val !== $var) { <add> $val = self::_export($val, $depth, $indent); <add> } else { <add> $val = '[recursion]'; <add> } <ide> $vars[] = $break . self::exportVar($key) . <ide> ' => ' . <del> self::_export($val, $depth, $indent); <add> $val; <ide> } <ide> } else { <ide> $vars[] = $break . '[maximum depth reached]';
2
Javascript
Javascript
adjust virtical alignment of tooptip items
d81914ea29aa8fd26a6aef286b37922a267b2252
<ide><path>src/core/core.tooltip.js <ide> var exports = Element.extend({ <ide> <ide> drawTitle: function(pt, vm, ctx) { <ide> var title = vm.title; <add> var length = title.length; <add> var titleFontSize, titleSpacing, i; <ide> <del> if (title.length) { <add> if (length) { <ide> pt.x = getAlignedX(vm, vm._titleAlign); <ide> <ide> ctx.textAlign = vm._titleAlign; <del> ctx.textBaseline = 'top'; <add> ctx.textBaseline = 'middle'; <ide> <del> var titleFontSize = vm.titleFontSize; <del> var titleSpacing = vm.titleSpacing; <add> titleFontSize = vm.titleFontSize; <add> titleSpacing = vm.titleSpacing; <ide> <ide> ctx.fillStyle = vm.titleFontColor; <ide> ctx.font = helpers.fontString(titleFontSize, vm._titleFontStyle, vm._titleFontFamily); <ide> <del> var i, len; <del> for (i = 0, len = title.length; i < len; ++i) { <del> ctx.fillText(title[i], pt.x, pt.y); <add> for (i = 0; i < length; ++i) { <add> ctx.fillText(title[i], pt.x, pt.y + titleFontSize / 2); <ide> pt.y += titleFontSize + titleSpacing; // Line Height and spacing <ide> <del> if (i + 1 === title.length) { <add> if (i + 1 === length) { <ide> pt.y += vm.titleMarginBottom - titleSpacing; // If Last, add margin, remove spacing <ide> } <ide> } <ide> var exports = Element.extend({ <ide> var bodyAlign = vm._bodyAlign; <ide> var body = vm.body; <ide> var drawColorBoxes = vm.displayColors; <del> var labelColors = vm.labelColors; <ide> var xLinePadding = 0; <ide> var colorX = drawColorBoxes ? getAlignedX(vm, 'left') : 0; <del> var textColor; <add> <add> var fillLineOfText = function(line) { <add> ctx.fillText(line, pt.x + xLinePadding, pt.y + bodyFontSize / 2); <add> pt.y += bodyFontSize + bodySpacing; <add> }; <add> <add> var bodyItem, textColor, labelColors, lines, i, j, ilen, jlen; <ide> <ide> ctx.textAlign = bodyAlign; <del> ctx.textBaseline = 'top'; <add> ctx.textBaseline = 'middle'; <ide> ctx.font = helpers.fontString(bodyFontSize, vm._bodyFontStyle, vm._bodyFontFamily); <ide> <ide> pt.x = getAlignedX(vm, bodyAlign); <ide> <del> // Before Body <del> var fillLineOfText = function(line) { <del> ctx.fillText(line, pt.x + xLinePadding, pt.y); <del> pt.y += bodyFontSize + bodySpacing; <del> }; <del> <ide> // Before body lines <ide> ctx.fillStyle = vm.bodyFontColor; <ide> helpers.each(vm.beforeBody, fillLineOfText); <ide> var exports = Element.extend({ <ide> : 0; <ide> <ide> // Draw body lines now <del> helpers.each(body, function(bodyItem, i) { <add> for (i = 0, ilen = body.length; i < ilen; ++i) { <add> bodyItem = body[i]; <ide> textColor = vm.labelTextColors[i]; <add> labelColors = vm.labelColors[i]; <add> <ide> ctx.fillStyle = textColor; <ide> helpers.each(bodyItem.before, fillLineOfText); <ide> <del> helpers.each(bodyItem.lines, function(line) { <add> lines = bodyItem.lines; <add> for (j = 0, jlen = lines.length; j < jlen; ++j) { <ide> // Draw Legend-like boxes if needed <ide> if (drawColorBoxes) { <ide> // Fill a white rect so that colours merge nicely if the opacity is < 1 <ide> var exports = Element.extend({ <ide> <ide> // Border <ide> ctx.lineWidth = 1; <del> ctx.strokeStyle = labelColors[i].borderColor; <add> ctx.strokeStyle = labelColors.borderColor; <ide> ctx.strokeRect(colorX, pt.y, bodyFontSize, bodyFontSize); <ide> <ide> // Inner square <del> ctx.fillStyle = labelColors[i].backgroundColor; <add> ctx.fillStyle = labelColors.backgroundColor; <ide> ctx.fillRect(colorX + 1, pt.y + 1, bodyFontSize - 2, bodyFontSize - 2); <ide> ctx.fillStyle = textColor; <ide> } <ide> <del> fillLineOfText(line); <del> }); <add> fillLineOfText(lines[j]); <add> } <ide> <ide> helpers.each(bodyItem.after, fillLineOfText); <del> }); <add> } <ide> <ide> // Reset back to 0 for after body <ide> xLinePadding = 0; <ide> var exports = Element.extend({ <ide> <ide> drawFooter: function(pt, vm, ctx) { <ide> var footer = vm.footer; <add> var length = footer.length; <add> var footerFontSize, i; <ide> <del> if (footer.length) { <add> if (length) { <ide> pt.x = getAlignedX(vm, vm._footerAlign); <ide> pt.y += vm.footerMarginTop; <ide> <ide> ctx.textAlign = vm._footerAlign; <del> ctx.textBaseline = 'top'; <add> ctx.textBaseline = 'middle'; <add> <add> footerFontSize = vm.footerFontSize; <ide> <ide> ctx.fillStyle = vm.footerFontColor; <del> ctx.font = helpers.fontString(vm.footerFontSize, vm._footerFontStyle, vm._footerFontFamily); <add> ctx.font = helpers.fontString(footerFontSize, vm._footerFontStyle, vm._footerFontFamily); <ide> <del> helpers.each(footer, function(line) { <del> ctx.fillText(line, pt.x, pt.y); <del> pt.y += vm.footerFontSize + vm.footerSpacing; <del> }); <add> for (i = 0; i < length; ++i) { <add> ctx.fillText(footer[i], pt.x, pt.y + footerFontSize / 2); <add> pt.y += footerFontSize + vm.footerSpacing; <add> } <ide> } <ide> }, <ide> <ide><path>src/plugins/plugin.legend.js <ide> var Legend = Element.extend({ <ide> var totalHeight = 0; <ide> <ide> ctx.textAlign = 'left'; <del> ctx.textBaseline = 'top'; <add> ctx.textBaseline = 'middle'; <ide> <ide> helpers.each(me.legendItems, function(legendItem, i) { <ide> var boxWidth = getBoxWidth(labelOpts, fontSize); <ide><path>test/specs/core.tooltip.tests.js <ide> describe('Core.Tooltip', function() { <ide> expect(mockContext.getCalls()).toEqual(Array.prototype.concat(drawBody, [ <ide> {name: 'setTextAlign', args: ['left']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['title', 105, 105]}, <add> {name: 'fillText', args: ['title', 105, 111]}, <ide> {name: 'setTextAlign', args: ['left']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['label', 105, 123]}, <add> {name: 'fillText', args: ['label', 105, 129]}, <ide> {name: 'setTextAlign', args: ['left']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['footer', 105, 141]}, <add> {name: 'fillText', args: ['footer', 105, 147]}, <ide> {name: 'restore', args: []} <ide> ])); <ide> }); <ide> describe('Core.Tooltip', function() { <ide> expect(mockContext.getCalls()).toEqual(Array.prototype.concat(drawBody, [ <ide> {name: 'setTextAlign', args: ['right']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['title', 195, 105]}, <add> {name: 'fillText', args: ['title', 195, 111]}, <ide> {name: 'setTextAlign', args: ['right']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['label', 195, 123]}, <add> {name: 'fillText', args: ['label', 195, 129]}, <ide> {name: 'setTextAlign', args: ['right']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['footer', 195, 141]}, <add> {name: 'fillText', args: ['footer', 195, 147]}, <ide> {name: 'restore', args: []} <ide> ])); <ide> }); <ide> describe('Core.Tooltip', function() { <ide> expect(mockContext.getCalls()).toEqual(Array.prototype.concat(drawBody, [ <ide> {name: 'setTextAlign', args: ['center']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['title', 150, 105]}, <add> {name: 'fillText', args: ['title', 150, 111]}, <ide> {name: 'setTextAlign', args: ['center']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['label', 150, 123]}, <add> {name: 'fillText', args: ['label', 150, 129]}, <ide> {name: 'setTextAlign', args: ['center']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['footer', 150, 141]}, <add> {name: 'fillText', args: ['footer', 150, 147]}, <ide> {name: 'restore', args: []} <ide> ])); <ide> }); <ide> describe('Core.Tooltip', function() { <ide> expect(mockContext.getCalls()).toEqual(Array.prototype.concat(drawBody, [ <ide> {name: 'setTextAlign', args: ['right']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['title', 195, 105]}, <add> {name: 'fillText', args: ['title', 195, 111]}, <ide> {name: 'setTextAlign', args: ['center']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['label', 150, 123]}, <add> {name: 'fillText', args: ['label', 150, 129]}, <ide> {name: 'setTextAlign', args: ['left']}, <ide> {name: 'setFillStyle', args: ['#fff']}, <del> {name: 'fillText', args: ['footer', 105, 141]}, <add> {name: 'fillText', args: ['footer', 105, 147]}, <ide> {name: 'restore', args: []} <ide> ])); <ide> });
3
Java
Java
refine use of substring operations
ab859fcc963195d612c2341986f2e7cda7e1dc0c
<ide><path>spring-aop/src/main/java/org/springframework/aop/aspectj/AspectJAdviceParameterNameDiscoverer.java <ide> private PointcutBody getPointcutBody(String[] tokens, int startIndex) { <ide> } <ide> <ide> if (tokens[currentIndex].endsWith(")")) { <del> sb.append(tokens[currentIndex].substring(0, tokens[currentIndex].length() - 1)); <add> sb.append(tokens[currentIndex], 0, tokens[currentIndex].length() - 1); <ide> return new PointcutBody(numTokensConsumed, sb.toString().trim()); <ide> } <ide> <ide><path>spring-beans/src/main/java/org/springframework/beans/PropertyEditorRegistrySupport.java <ide> private void addStrippedPropertyPaths(List<String> strippedPaths, String nestedP <ide> if (endIndex != -1) { <ide> String prefix = propertyPath.substring(0, startIndex); <ide> String key = propertyPath.substring(startIndex, endIndex + 1); <del> String suffix = propertyPath.substring(endIndex + 1, propertyPath.length()); <add> String suffix = propertyPath.substring(endIndex + 1); <ide> // Strip the first key. <ide> strippedPaths.add(nestedPath + prefix + suffix); <ide> // Search for further keys to strip, with the first key stripped. <ide><path>spring-context/src/main/java/org/springframework/scheduling/config/TaskExecutorFactoryBean.java <ide> private void determinePoolSizeRange(ThreadPoolTaskExecutor executor) { <ide> int separatorIndex = this.poolSize.indexOf('-'); <ide> if (separatorIndex != -1) { <ide> corePoolSize = Integer.parseInt(this.poolSize.substring(0, separatorIndex)); <del> maxPoolSize = Integer.parseInt(this.poolSize.substring(separatorIndex + 1, this.poolSize.length())); <add> maxPoolSize = Integer.parseInt(this.poolSize.substring(separatorIndex + 1)); <ide> if (corePoolSize > maxPoolSize) { <ide> throw new IllegalArgumentException( <ide> "Lower bound of pool-size range must not exceed the upper bound"); <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/DefaultMessageListenerContainer.java <ide> public void setConcurrency(String concurrency) { <ide> int separatorIndex = concurrency.indexOf('-'); <ide> if (separatorIndex != -1) { <ide> setConcurrentConsumers(Integer.parseInt(concurrency.substring(0, separatorIndex))); <del> setMaxConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1, concurrency.length()))); <add> setMaxConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1))); <ide> } <ide> else { <ide> setConcurrentConsumers(1); <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/SimpleMessageListenerContainer.java <ide> public void setConcurrency(String concurrency) { <ide> try { <ide> int separatorIndex = concurrency.indexOf('-'); <ide> if (separatorIndex != -1) { <del> setConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1, concurrency.length()))); <add> setConcurrentConsumers(Integer.parseInt(concurrency.substring(separatorIndex + 1))); <ide> } <ide> else { <ide> setConcurrentConsumers(Integer.parseInt(concurrency)); <ide><path>spring-jms/src/main/java/org/springframework/jms/listener/endpoint/JmsActivationSpecConfig.java <ide> public void setConcurrency(String concurrency) { <ide> try { <ide> int separatorIndex = concurrency.indexOf('-'); <ide> if (separatorIndex != -1) { <del> setMaxConcurrency(Integer.parseInt(concurrency.substring(separatorIndex + 1, concurrency.length()))); <add> setMaxConcurrency(Integer.parseInt(concurrency.substring(separatorIndex + 1))); <ide> } <ide> else { <ide> setMaxConcurrency(Integer.parseInt(concurrency)); <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompDecoder.java <ide> private String unescape(String inString) { <ide> int index = inString.indexOf('\\'); <ide> <ide> while (index >= 0) { <del> sb.append(inString.substring(pos, index)); <add> sb.append(inString, pos, index); <ide> if (index + 1 >= inString.length()) { <ide> throw new StompConversionException("Illegal escape sequence at index " + index + ": " + inString); <ide> } <ide><path>spring-messaging/src/main/java/org/springframework/messaging/simp/stomp/StompEncoder.java <ide> else if (sb != null){ <ide> private StringBuilder getStringBuilder(@Nullable StringBuilder sb, String inString, int i) { <ide> if (sb == null) { <ide> sb = new StringBuilder(inString.length()); <del> sb.append(inString.substring(0, i)); <add> sb.append(inString, 0, i); <ide> } <ide> return sb; <ide> } <ide><path>spring-test/src/main/java/org/springframework/test/web/servlet/setup/PatternMappingFilterProxy.java <ide> public PatternMappingFilterProxy(Filter delegate, String... urlPatterns) { <ide> private void addUrlPattern(String urlPattern) { <ide> Assert.notNull(urlPattern, "Found null URL Pattern"); <ide> if (urlPattern.startsWith(EXTENSION_MAPPING_PATTERN)) { <del> this.endsWithMatches.add(urlPattern.substring(1, urlPattern.length())); <add> this.endsWithMatches.add(urlPattern.substring(1)); <ide> } <ide> else if (urlPattern.equals(PATH_MAPPING_PATTERN)) { <ide> this.startsWithMatches.add(""); <ide><path>spring-web/src/main/java/org/springframework/web/util/UriTemplate.java <ide> else if (c == '}') { <ide> throw new IllegalArgumentException( <ide> "No custom regular expression specified after ':' in \"" + variable + "\""); <ide> } <del> String regex = variable.substring(idx + 1, variable.length()); <add> String regex = variable.substring(idx + 1); <ide> pattern.append('('); <ide> pattern.append(regex); <ide> pattern.append(')'); <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/view/RedirectView.java <ide> protected StringBuilder expandTargetUrlTemplate(String targetUrl, <ide> String name = matcher.group(1); <ide> Object value = (model.containsKey(name) ? model.get(name) : uriVariables.get(name)); <ide> Assert.notNull(value, () -> "No value for URI variable '" + name + "'"); <del> result.append(targetUrl.substring(endLastMatch, matcher.start())); <add> result.append(targetUrl, endLastMatch, matcher.start()); <ide> result.append(encodeUriVariable(value.toString())); <ide> endLastMatch = matcher.end(); <ide> found = matcher.find(); <ide> } <del> result.append(targetUrl.substring(endLastMatch, targetUrl.length())); <add> result.append(targetUrl.substring(endLastMatch)); <ide> return result; <ide> } <ide> <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/tags/UrlTag.java <ide> String createUrl() throws JspException { <ide> } <ide> else { <ide> if (this.context.endsWith("/")) { <del> url.append(this.context.substring(0, this.context.length() - 1)); <add> url.append(this.context, 0, this.context.length() - 1); <ide> } <ide> else { <ide> url.append(this.context); <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/view/RedirectView.java <ide> protected StringBuilder replaceUriTemplateVariables( <ide> if (value == null) { <ide> throw new IllegalArgumentException("Model has no value for key '" + name + "'"); <ide> } <del> result.append(targetUrl.substring(endLastMatch, matcher.start())); <add> result.append(targetUrl, endLastMatch, matcher.start()); <ide> result.append(UriUtils.encodePathSegment(value.toString(), encodingScheme)); <ide> endLastMatch = matcher.end(); <ide> } <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/WebSocketExtension.java <ide> private static WebSocketExtension parseExtension(String extension) { <ide> int eqIndex = parameter.indexOf('='); <ide> if (eqIndex != -1) { <ide> String attribute = parameter.substring(0, eqIndex); <del> String value = parameter.substring(eqIndex + 1, parameter.length()); <add> String value = parameter.substring(eqIndex + 1); <ide> parameters.put(attribute, value); <ide> } <ide> }
14
Text
Text
add readme files in nlp/modeling folder
ab6d40ca85a9d98f25347d2c059de44497e853c8
<ide><path>official/nlp/README.md <del># TensorFlow Natural Language Processing Models <add># TensorFlow Natural Language Processing Modelling Toolkit <ide> <del>tensorflow/models/official/nlp is a library of state-of-the-art models for <del>Natural Language Processing (NLP). <add>tensorflow/models/official/nlp provides a [modeling library](modeling) for constructing <add>NLP model achitectures, as well as TF2 reference implementations for <add>state-of-the-art models. <ide> <del>The library currently contains TensorFlow 2.x implementations, pre-trained <del>model weights, usage scripts and conversion utilities for the following models: <add>The repository contains the following models, with implementations, pre-trained <add>model weights, usage scripts and conversion utilities: <ide> <ide> * [Bert](bert) <del> <ide> * [Albert](albert) <del> <ide> * [XLNet](xlnet) <del> <ide> * [Transformer for translation](transformer) <add> <add>Addtional features: <add> <add>* Distributed trainable on both multi-GPU and TPU <add>* e2e training for custom models, including both pretraining and finetuning. <add> <add> <add> <ide><path>official/nlp/modeling/README.md <add># NLP Modeling Library <add> <add>This libary provides a set of Keras primitives (Layers, Networks, and Models) <add>that can be assembled into transformer-based models. They are <add>flexible, validated, interoperable, and both TF1 and TF2 compatible. <add> <add>* [`layers`](layers) are the fundamental building blocks for NLP models. <add>They can be used to assemble new layers, networks, or models. <add> <add>* [`networks`](networks) are combinations of layers (and possibly other networks). They are sub-units of models that would not be trained alone. They <add>encapsulate common network structures like a classification head <add>or a transformer encoder into an easily handled object with a <add>standardized configuration. <add> <add>* [`models`](models) are combinations of layers and networks that would be trained. Pre-built canned models are provided as both convenience functions and canonical examples. <add> <add>* [`losses`](losses) contains common loss computation used in NLP tasks. <add> <add>Besides the pre-defined primitives, it also provides scaffold classes to allow <add>easy experimentation with noval achitectures, e.g., you don’t need to fork a whole Transformer object to try a different kind of attention primitive, for instance. <add> <add>* [`TransformerScaffold`](layers/transformer_scaffold.py) implements the <add>Transformer from ["Attention Is All You Need"] <add>(https://arxiv.org/abs/1706.03762), with a customizable attention layer <add>option. Users can pass a class to `attention_cls` and associated config to <add>`attention_cfg`, in which case the scaffold will instantiate the class with <add>the config, or pass a class instance to `attention_cls`. <add> <add>* [`EncoderScaffold`](networks/encoder_scaffold.py) implements the transformer <add>encoder from ["BERT: Pre-training of Deep Bidirectional Transformers for <add>Language Understanding"](https://arxiv.org/abs/1810.04805), with customizable <add>embedding subnetwork (which will replace the standard embedding logic) and/or a <add>custom hidden layer (which will replace the Transformer instantiation in the <add>encoder). <add> <add>BERT and ALBERT models in this repo are implemented using this library. Code examples can be found in the corresponding model folder. <add> <add> <add> <add> <add> <add> <add> <ide><path>official/nlp/modeling/layers/README.md <add># Layers <add>Layers are the fundamental building blocks for NLP models. They can be used to <add>assemble new layers, networks, or models. <add> <add>* [DenseEinsum](dense_einsum.py) implements a feedforward network using tf.einsum. This layer contains the einsum op, the associated weight, and the <add>logic required to generate the einsum expression for the given initialization <add>parameters. <add> <add>* [Attention](attention.py) implements an optionally masked attention between two tensors, from_tensor and to_tensor, as described in ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762). If `from_tensor` and `to_tensor` are the same, then this is self-attention. <add> <add>* [CachedAttention](attention.py) implements an attention layer with cache used <add>for auto-agressive decoding. <add> <add>* [Transformer](transformer.py) implements an optionally masked transformer as <add>described in ["Attention Is All You Need"](https://arxiv.org/abs/1706.03762). <add> <add>* [OnDeviceEmbedding](on_device_embedding.py) implements efficient embedding lookups designed for TPU-based models. <add> <add>* [PositionalEmbedding](position_embedding.py) creates a positional embedding <add> as described in ["BERT: Pre-training <add> of Deep Bidirectional Transformers for Language Understanding"] <add> (https://arxiv.org/abs/1810.04805). <add> <add>* [SelfAttentionMask](self_attention_mask.py) creates a 3D attention mask from a 2D tensor mask. <add> <add>* [MaskedSoftmax](masked_softmax.py) implements a softmax with an optional masking input. If no mask is provided to this layer, it performs a standard softmax; however, if a mask tensor is applied (which should be 1 in positions where the data should be allowed through, and 0 where the data should be masked), the output will have masked positions set to approximately zero. <ide><path>official/nlp/modeling/losses/README.md <add># Losses <add> <add>Losses contains common loss computation used in NLP tasks. <add> <add>* `weighted_sparse_categorical_crossentropy_loss` computes per-batch sparse <add>categorical crossentropy loss. <add> <add>* `weighted_sparse_categorical_crossentropy_per_example_loss` computes <add>per-example sparse categorical crossentropy loss. <ide><path>official/nlp/modeling/models/README.md <add># Models <add> <add>Models are combinations of layers and networks that would be trained. <add> <add>Several pre-built canned models are provided to train encoder networks. These <add>models are intended as both convenience functions and canonical examples. <add> <add>* [`BertClassifier`](bert_classifier.py) implements a simple classification <add>model containing a single classification head using the Classification network. <add> <add>* [`BertSpanLabeler`](bert_span_labeler.py) implementats a simple single-span <add>start-end predictor (that is, a model that predicts two values: a start token <add>index and an end token index), suitable for SQuAD-style tasks. <add> <add>* [`BertPretrainer`](bert_pretrainer.py) implements a masked LM and a <add>classification head using the Masked LM and Classification networks, <add>respectively. <ide><path>official/nlp/modeling/networks/README.md <add># Networks <add> <add>Networks are combinations of layers (and possibly other networks). They are sub-units of models that would not be trained alone. It <add>encapsulates common network structures like a classification head <add>or a transformer encoder into an easily handled object with a <add>standardized configuration. <add> <add>* [`TransformerEncoder`](transformer_encoder.py) implements a bi-directional <add>Transformer-based encoder as described in ["BERT: Pre-training of Deep <add>Bidirectional Transformers for Language Understanding"](https://arxiv.org/abs/1810.04805). It includes the embedding lookups, <add>transformer layers and pooling layer. <add> <add>* [`AlbertTransformerEncoder`](albert_transformer_encoder.py) implements a <add>Transformer-encoder described in the paper ["ALBERT: A Lite BERT for <add>Self-supervised Learning of Language Representations] <add>(https://arxiv.org/abs/1909.11942). Compared with [BERT](https://arxiv.org/abs/1810.04805), ALBERT refactorizes embedding parameters <add>into two smaller matrices and shares parameters across layers. <add> <add>* [`MaskedLM`](masked_lm.py) implements a masked language model for BERT pretraining. It assumes that the network being passed has a `get_embedding_table()` method. <add> <add>* [`Classification`](classification.py) contains a single hidden layer, and is intended for use as a classification head. <add> <add>* [`SpanLabeling`](span_labeling.py) implements a single-span labeler (that is, a prediction head that can predict one start and end index per batch item) based on a single dense hidden layer. It can be used in the SQuAD task. <add>
6
Mixed
Text
allow pre-parsed data (to scale id's)
53c6c618c6fc8b30efdb1e7e75a1c4673fe179d2
<ide><path>docs/SUMMARY.md <ide> * [Usage](getting-started/usage.md) <ide> * [Migration Guide](getting-started/v3-migration.md) <ide> * [General](general/README.md) <add> * [Data structures](general/data-structures.md) <ide> * [Accessibility](general/accessibility.md) <ide> * [Responsive](general/responsive.md) <ide> * [Pixel Ratio](general/device-pixel-ratio.md) <ide> * [Options](general/options.md) <ide> * [Colors](general/colors.md) <ide> * [Fonts](general/fonts.md) <del> * [Performance](general/performance.md) <add> * [Performance](general/performance.md) <ide> * [Configuration](configuration/README.md) <ide> * [Animations](configuration/animations.md) <ide> * [Layout](configuration/layout.md) <ide><path>docs/axes/cartesian/category.md <ide> let chart = new Chart(ctx, { <ide> } <ide> }); <ide> ``` <add> <ide> As part of axis definition: <ide> <ide> ```javascript <ide> The category scale provides the following options for configuring tick marks. Th <ide> | Name | Type | Default | Description <ide> | ---- | ---- | ------- | ----------- <ide> | `labels` | `string[]` | - | An array of labels to display. <del>| `min` | `string` | | The minimum item to display. [more...](#min-max-configuration) <del>| `max` | `string` | | The maximum item to display. [more...](#min-max-configuration) <add>| `min` | <code>string&#124;number</code> | | The minimum item to display. [more...](#min-max-configuration) <add>| `max` | <code>string&#124;number</code> | | The maximum item to display. [more...](#min-max-configuration) <ide> <ide> ## Min Max Configuration <del>For both the `min` and `max` properties, the value must be in the `labels` array. In the example below, the x axis would only display "March" through "June". <add> <add>For both the `min` and `max` properties, the value must be `string` in the `labels` array or `numeric` value as an index of a label in that array. In the example below, the x axis would only display "March" through "June". <ide> <ide> ```javascript <ide> let chart = new Chart(ctx, { <ide> let chart = new Chart(ctx, { <ide> } <ide> }); <ide> ``` <add> <add>## Internal data format <add> <add>Internally category scale uses label indices <ide><path>docs/axes/cartesian/linear.md <ide> let options = { <ide> } <ide> }; <ide> ``` <add> <add>## Internal data format <add> <add>Internally, linear scale uses numeric data <ide><path>docs/axes/cartesian/logarithmic.md <ide> The logarithmic scale is use to chart numerical data. It can be placed on either <ide> ## Tick Configuration Options <ide> <ide> The logarithmic scale options extend the [common tick configuration](README.md#tick-configuration). This scale does not define any options that are unique to it. <add> <add>## Internal data format <add> <add>Internally logarithmic scale uses numeric data <ide><path>docs/axes/cartesian/time.md <ide> The `ticks.source` property controls the ticks generation. <ide> * `'labels'`: generates ticks from user given `labels` ONLY <ide> <ide> ### Parser <add> <ide> If this property is defined as a string, it is interpreted as a custom format to be used by Moment.js to parse the date. <ide> <ide> If this is a function, it must return a Moment.js object given the appropriate data value. <add> <add>### Internal data format <add> <add>Internally time scale uses milliseconds since epoch <ide><path>docs/axes/radial/linear.md <ide> let chart = new Chart(ctx, { <ide> In contrast to the `suggested*` settings, the `min` and `max` settings set explicit ends to the axes. When these are set, some data points may not be visible. <ide> <ide> ## Step Size <add> <ide> If set, the scale ticks will be enumerated by multiple of `stepSize`, having one tick per increment. If not set, the ticks are labeled automatically using the nice numbers algorithm. <ide> <ide> This example sets up a chart with a y axis that creates ticks at `0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5`. <ide> The following options are used to configure the point labels that are shown on t <ide> | `fontSize` | `number` | `10` | font size in pixels. <ide> | `fontStyle` | `string` | `'normal'` | Font style to use when rendering point labels. <ide> | `lineHeight` | <code>number&#124;string</code> | `1.2` | Height of an individual line of text (see [MDN](https://developer.mozilla.org/en-US/docs/Web/CSS/line-height)). <add> <add>## Internal data format <add> <add>Internally linear radial scale uses numeric data <ide><path>docs/charts/bar.md <ide> # Bar <add> <ide> A bar chart provides a way of showing data values represented as vertical bars. It is sometimes used to show trend data, and the comparison of multiple data sets side by side. <ide> <ide> {% chartjs %} <ide> that derive from a bar chart. <ide> **Note:** for negative bars in vertical chart, `top` and `bottom` are flipped. Same goes for `left` and `right` in horizontal chart. <ide> <ide> Options are: <add> <ide> * `'bottom'` <ide> * `'left'` <ide> * `'top'` <ide> The interaction with each bar can be controlled with the following properties: <ide> All these values, if `undefined`, fallback to the associated [`elements.rectangle.*`](../configuration/elements.md#rectangle-configuration) options. <ide> <ide> ## Dataset Configuration <add> <ide> The bar chart accepts the following configuration from the associated dataset options: <ide> <ide> | Name | Type | Default | Description <ide> Sample: |==============| <ide> <ide> ## Data Structure <ide> <del>The `data` property of a dataset for a bar chart is specified as an array of numbers. Each point in the data array corresponds to the label at the same index on the x axis. <del> <del>```javascript <del>data: [20, 10] <del>``` <del> <del>You can also specify the dataset as x/y coordinates when using the [time scale](../axes/cartesian/time.md#time-cartesian-axis). <del> <del>```javascript <del>data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}] <del>``` <del> <del>You can also specify the dataset for a bar chart as arrays of two numbers. This will force rendering of bars with gaps between them (floating-bars). First and second numbers in array will correspond the start and the end point of a bar respectively. <del>```javascript <del>data: [[5,6], [-3,-6]] <del>``` <add>All of the supported [data structures](../general/data-structures.md) can be used with bar charts. <ide> <ide> ## Stacked Bar Chart <ide> <ide> var myBarChart = new Chart(ctx, { <ide> The configuration options for the horizontal bar chart are the same as for the [bar chart](#scale-configuration). However, any options specified on the x axis in a bar chart, are applied to the y axis in a horizontal bar chart. <ide> <ide> The default horizontal bar configuration is specified in `Chart.defaults.horizontalBar`. <add> <add>## Internal data format <add> <add>`{x, y, _custom}` where `_custom` is optional object defining stacked bar properties: `{start, end, barStart, barEnd, min, max}`. `start` and `end` are the input values. Those two are repeated in `barStart` (closer to origin), `barEnd` (further from origin), `min` and `max`. <ide><path>docs/charts/bubble.md <ide> Bubble chart datasets need to contain a `data` array of points, each points repr <ide> ``` <ide> <ide> **Important:** the radius property, `r` is **not** scaled by the chart, it is the raw radius in pixels of the bubble that is drawn on the canvas. <add> <add>## Internal data format <add> <add>`{x, y, _custom}` where `_custom` is the radius. <ide><path>docs/charts/line.md <ide> # Line <add> <ide> A line chart is a way of plotting data points on a line. Often, it is used to show trend data, or the comparison of two data sets. <ide> <ide> {% chartjs %} <ide> A line chart is a way of plotting data points on a line. Often, it is used to sh <ide> {% endchartjs %} <ide> <ide> ## Example Usage <add> <ide> ```javascript <ide> var myLineChart = new Chart(ctx, { <ide> type: 'line', <ide> The interaction with each point can be controlled with the following properties: <ide> | `pointHoverRadius` | The radius of the point when hovered. <ide> <ide> ### cubicInterpolationMode <add> <ide> The following interpolation modes are supported. <add> <ide> * `'default'` <ide> * `'monotone'` <ide> <ide> The `'monotone'` algorithm is more suited to `y = f(x)` datasets : it preserves <ide> If left untouched (`undefined`), the global `options.elements.line.cubicInterpolationMode` property is used. <ide> <ide> ### Stepped Line <add> <ide> The following values are supported for `steppedLine`. <add> <ide> * `false`: No Step Interpolation (default) <ide> * `true`: Step-before Interpolation (eq. `'before'`) <ide> * `'before'`: Step-before Interpolation <ide> The line chart defines the following configuration options. These options are me <ide> It is common to want to apply a configuration setting to all created line charts. The global line chart settings are stored in `Chart.defaults.line`. Changing the global options only affects charts created after the change. Existing charts are not changed. <ide> <ide> For example, to configure all line charts with `spanGaps = true` you would do: <add> <ide> ```javascript <ide> Chart.defaults.line.spanGaps = true; <ide> ``` <ide> <ide> ## Data Structure <ide> <del>The `data` property of a dataset for a line chart can be passed in two formats. <del> <del>### number[] <del>```javascript <del>data: [20, 10] <del>``` <del> <del>When the `data` array is an array of numbers, the x axis is generally a [category](../axes/cartesian/category.md#category-cartesian-axis). The points are placed onto the axis using their position in the array. When a line chart is created with a category axis, the `labels` property of the data object must be specified. <del> <del>### Point[] <del> <del>```javascript <del>data: [{ <del> x: 10, <del> y: 20 <del>}, { <del> x: 15, <del> y: 10 <del>}] <del>``` <del> <del>This alternate is used for sparse datasets, such as those in [scatter charts](./scatter.md#scatter-chart). Each data point is specified using an object containing `x` and `y` properties. <add>See [`Data structures`](../general/data-structures.md) <ide> <ide> ## Stacked Area Chart <ide> <ide> var stackedLine = new Chart(ctx, { <ide> } <ide> }); <ide> ``` <add> <add>## Internal data format <add> <add>`{x, y}` <ide><path>docs/charts/radar.md <ide> data: { <ide> }] <ide> } <ide> ``` <add> <add>## Internal data format <add> <add>`{x, y}` <ide><path>docs/charts/scatter.md <ide> data: [{ <ide> y: 10 <ide> }] <ide> ``` <add> <add>## Internal data format <add> <add>`{x, y}` <ide><path>docs/general/data-structures.md <add># Data structures <add> <add>The `data` property of a dataset can be passed in various formats. By default, that `data` is parsed using the associated chart type and scales. <add> <add>## Primitive[] <add> <add>```javascript <add>data: [20, 10], <add>labels: ['a', 'b'] <add>``` <add> <add>When the `data` is an array of numbers, values from `labels` array at the same index are used for the index axis (`x` for vertical, `y` for horizontal charts). <add> <add>## Object[] <add> <add>```javascript <add>data: [{x: 10, y: 20}, {x: 15, y: 10}] <add>``` <add> <add>```javascript <add>data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}] <add>``` <add> <add>```javascript <add>data: [{x:'Sales', y:20}, {x:'Revenue', y:10}] <add>``` <add> <add>This is also the internal format used for parsed data. Property names are matched to scale-id. In this mode, parsing can be disabled by specifying `parsing: false` at chart options or dataset. If parsing is disabled, data must be in the formats the associated chart type and scales use internally. <add> <add>## Object <add> <add>```javascript <add>data: { <add> January: 10, <add> February: 20 <add>} <add>``` <add> <add>In this mode, property name is used for `index` scale and value for `value` scale. For vertical charts, index scale is `x` and value scale is `y`. <ide><path>docs/general/performance.md <ide> new Chart(ctx, { <ide> }); <ide> ``` <ide> <add>## Data structure and format <add> <add>Provide prepared data in the internal format accepted by the dataset and scales and set `parsing: false`. See [Data structures](data-structures.md) for more information. <add> <ide> ## Data Decimation <ide> <ide> Decimating your data will achieve the best results. When there is a lot of data to display on the graph, it doesn't make sense to show tens of thousands of data points on a graph that is only a few hundred pixels wide. <ide><path>src/core/core.datasetController.js <ide> helpers.extend(DatasetController.prototype, { <ide> const me = this; <ide> const {_cachedMeta: meta, _data: data} = me; <ide> const {iScale, vScale, _stacked} = meta; <del> let i, ilen, parsed; <del> <del> if (helpers.isArray(data[start])) { <add> const parsing = resolve([me.getDataset().parsing, me.chart.options.parsing, true]); <add> let offset = 0; <add> let i, parsed; <add> <add> if (parsing === false) { <add> parsed = data; <add> offset = start; <add> } else if (helpers.isArray(data[start])) { <ide> parsed = me._parseArrayData(meta, data, start, count); <ide> } else if (helpers.isObject(data[start])) { <ide> parsed = me._parseObjectData(meta, data, start, count); <ide> } else { <ide> parsed = me._parsePrimitiveData(meta, data, start, count); <ide> } <ide> <del> for (i = 0, ilen = parsed.length; i < ilen; ++i) { <del> meta.data[start + i]._parsed = parsed[i]; <add> for (i = 0; i < count; ++i) { <add> meta.data[i + start]._parsed = parsed[i + offset]; <ide> } <ide> <ide> if (_stacked) {
14
PHP
PHP
fix blank line before return statement
4ae2eda53ab99339e14842dc8be5b64a9cffb1e8
<ide><path>src/Routing/Router.php <ide> public static function routeExists($url = null, $full = false) <ide> { <ide> try { <ide> $route = static::url($url, $full); <add> <ide> return true; <ide> } catch (MissingRouteException $e) { <add> <ide> return false; <ide> } <ide> }
1
Javascript
Javascript
implement ssr=false support
b5a03a38964fba0e5f203c33941424b377c6ccd3
<ide><path>examples/with-dynamic-import/components/hello3.js <add>export default () => ( <add> <p>Hello World 3 (imported dynamiclly) </p> <add>) <ide><path>examples/with-dynamic-import/pages/index.js <ide> const DynamicComponentWithCustomLoading = dynamic( <ide> loading: () => (<p>...</p>) <ide> } <ide> ) <add>const DynamicComponentWithNoSSR = dynamic( <add> import('../components/hello3'), <add> { ssr: false } <add>) <ide> <ide> export default () => ( <ide> <div> <ide> <Header /> <ide> <DynamicComponent /> <ide> <DynamicComponentWithCustomLoading /> <add> <DynamicComponentWithNoSSR /> <ide> <p>HOME PAGE is here!</p> <ide> <Counter /> <ide> </div> <ide><path>lib/dynamic.js <ide> export default function dynamicComponent (promise, options = {}) { <ide> return class Comp extends React.Component { <ide> constructor (...args) { <ide> super(...args) <add> <ide> this.LoadingComponent = options.loading ? options.loading : () => (<p>loading...</p>) <add> this.ssr = options.ssr === false ? options.ssr : true <add> <ide> this.state = { AsyncComponent: null } <ide> this.isServer = typeof window === 'undefined' <del> this.loadComponent() <add> <add> if (this.ssr) { <add> this.loadComponent() <add> } <ide> } <ide> <ide> loadComponent () { <ide> export default function dynamicComponent (promise, options = {}) { <ide> <ide> componentDidMount () { <ide> this.mounted = true <add> if (!this.ssr) { <add> this.loadComponent() <add> } <ide> } <ide> <ide> render () {
3
Javascript
Javascript
add response interceptors
188bdf7768c9594a01a18abae3fa9a3114802508
<ide><path>src/service/http.js <ide> function $HttpProvider() { <ide> } <ide> }; <ide> <add> var responseInterceptors = this.responseInterceptors = []; <add> <ide> this.$get = ['$httpBackend', '$browser', '$exceptionHandler', '$cacheFactory', '$rootScope', '$q', <ide> function($httpBackend, $browser, $exceptionHandler, $cacheFactory, $rootScope, $q) { <ide> <ide> function $HttpProvider() { <ide> deferredResp = $q.defer(), <ide> promise = deferredResp.promise; <ide> <add> forEach(responseInterceptors, function(interceptor) { <add> promise = interceptor(promise); <add> }); <add> <ide> promise.success = function(fn) { <ide> promise.then(function(response) { <ide> fn(response.data, response.status, response.headers, config); <ide><path>test/service/httpSpec.js <ide> describe('$http', function() { <ide> })); <ide> <ide> <add> describe('$httpProvider', function() { <add> <add> describe('interceptors', function() { <add> <add> it('should default to an empty array', inject(function($httpProvider) { <add> expect($httpProvider.responseInterceptors).toEqual([]); <add> })); <add> <add> <add> it('should pass the responses through interceptors', inject(function($httpProvider, $q) { <add> // just change the response data and pass the response object along <add> $httpProvider.responseInterceptors.push(function(httpPromise) { <add> return httpPromise.then(function(response) { <add> response.data += '!'; <add> return response; <add> }); <add> }); <add> <add> // return a new resolved promise representing modified response object <add> $httpProvider.responseInterceptors.push(function(httpPromise) { <add> return httpPromise.then(function(response) { <add> var deferred = $q.defer(); <add> deferred.resolve({ <add> data: response.data + '?', <add> status: 209, <add> headers: response.headers, <add> config: response.config <add> }); <add> return deferred.promise; <add> }); <add> }); <add> }, function($http, $httpBackend) { <add> $httpBackend.expect('GET', '/foo').respond(201, 'Hello'); <add> $http.get('/foo').success(function(data, status) { <add> expect(data).toBe('Hello!?'); <add> expect(status).toBe(209); <add> callback(); <add> }) <add> $httpBackend.flush(); <add> expect(callback).toHaveBeenCalledOnce(); <add> })); <add> }); <add> }); <add> <add> <ide> it('should do basic request', function() { <ide> $httpBackend.expect('GET', '/url').respond(''); <ide> $http({url: '/url', method: 'GET'});
2
Javascript
Javascript
streamify template bindings
f839dcd89ad5ecc50d5403a06f507449380557b0
<ide><path>packages/ember-handlebars/lib/controls.js <ide> import Ember from "ember-metal/core"; // Ember.assert <ide> // var emberAssert = Ember.assert; <ide> <ide> import EmberHandlebars from "ember-handlebars-compiler"; <del>import { handlebarsGet } from "ember-handlebars/ext"; <add> <ide> /** <ide> @module ember <ide> @submodule ember-handlebars-compiler <ide> */ <ide> <del>function _resolveOption(context, options, key) { <del> if (options.hashTypes[key] === "ID") { <del> return handlebarsGet(context, options.hash[key], options); <del> } else { <del> return options.hash[key]; <del> } <del>} <del> <ide> /** <ide> <ide> The `{{input}}` helper inserts an HTML `<input>` tag into the template, <ide> function _resolveOption(context, options, key) { <ide> export function inputHelper(options) { <ide> Ember.assert('You can only pass attributes to the `input` helper, not arguments', arguments.length < 2); <ide> <add> var view = options.data.view; <ide> var hash = options.hash; <ide> var types = options.hashTypes; <del> var inputType = _resolveOption(this, options, 'type'); <ide> var onEvent = hash.on; <add> var inputType; <add> <add> if (types.type === 'ID') { <add> inputType = view.getStream(hash.type).value(); <add> } else { <add> inputType = hash.type; <add> } <ide> <ide> if (inputType === 'checkbox') { <ide> delete hash.type; <ide><path>packages/ember-handlebars/lib/ext.js <ide> import { <ide> // late bound via requireModule because of circular dependencies. <ide> var resolveHelper, SimpleHandlebarsView; <ide> <del>import isEmpty from 'ember-metal/is_empty'; <add>import Stream from "ember-metal/streams/stream"; <add>import KeyStream from "ember-views/streams/key_stream"; <add>import { <add> readArray, <add> readHash <add>} from "ember-metal/streams/read"; <ide> <ide> var slice = [].slice; <ide> var originalTemplate = EmberHandlebars.template; <ide> <del>/** <del> If a path starts with a reserved keyword, returns the root <del> that should be used. <del> <del> @private <del> @method normalizePath <del> @for Ember <del> @param root {Object} <del> @param path {String} <del> @param data {Hash} <del>*/ <del> <del>import Cache from 'ember-metal/cache'; <del> <del>var FIRST_SEGMENT_CACHE = new Cache(1000, function(path){ <del> return path.split('.', 1)[0]; <del>}); <del> <del>function normalizePath(root, path, data) { <del> var keywords = (data && data.keywords) || {}; <del> var keyword, isKeyword; <del> <del> // Get the first segment of the path. For example, if the <del> // path is "foo.bar.baz", returns "foo". <del> keyword = FIRST_SEGMENT_CACHE.get(path); <del> <del> // Test to see if the first path is a keyword that has been <del> // passed along in the view's data hash. If so, we will treat <del> // that object as the new root. <del> if (keywords.hasOwnProperty(keyword)) { <del> // Look up the value in the template's data hash. <del> root = keywords[keyword]; <del> isKeyword = true; <del> <del> // Handle cases where the entire path is the reserved <del> // word. In that case, return the object itself. <del> if (path === keyword) { <del> path = ''; <del> } else { <del> // Strip the keyword from the path and look up <del> // the remainder from the newly found root. <del> path = path.substr(keyword.length+1); <del> } <del> } <del> <del> return { <del> root: root, <del> path: path, <del> isKeyword: isKeyword <del> }; <del>} <del> <del> <del>/** <del> Lookup both on root and on window. If the path starts with <del> a keyword, the corresponding object will be looked up in the <del> template's data hash and used to resolve the path. <del> <del> @method get <del> @for Ember.Handlebars <del> @param {Object} root The object to look up the property on <del> @param {String} path The path to be lookedup <del> @param {Object} options The template's option hash <del>*/ <del>function handlebarsGet(root, path, options) { <del> var data = options && options.data; <del> var normalizedPath = normalizePath(root, path, data); <del> var value; <del> <del> // In cases where the path begins with a keyword, change the <del> // root to the value represented by that keyword, and ensure <del> // the path is relative to it. <del> root = normalizedPath.root; <del> path = normalizedPath.path; <del> <del> // Ember.get with a null root and GlobalPath will fall back to <del> // Ember.lookup, which is no longer allowed in templates. <del> // <del> // But when outputting a primitive, root will be the primitive <del> // and path a blank string. These primitives should pass through <del> // to `get`. <del> if (root || path === '') { <del> value = get(root, path); <del> } <del> <del> if (detectIsGlobal(path)) { <del> if (value === undefined && root !== Ember.lookup) { <del> root = Ember.lookup; <del> value = get(root, path); <del> } <del> if (root === Ember.lookup || root === null) { <del> Ember.deprecate("Global lookup of "+path+" from a Handlebars template is deprecated."); <del> } <del> } <del> <del> return value; <del>} <del> <ide> /** <ide> handlebarsGetView resolves a view based on strings passed into a template. <ide> For example: <ide> function handlebarsGet(root, path, options) { <ide> function handlebarsGetView(context, path, container, data) { <ide> var viewClass; <ide> if ('string' === typeof path) { <del> if (data) { <del> var normalizedPath = normalizePath(context, path, data); <del> context = normalizedPath.root; <del> path = normalizedPath.path; <add> if (!data) { <add> throw new Error("handlebarsGetView: must pass data"); <ide> } <ide> <ide> // Only lookup view class on context if there is a context. If not, <ide> // the global lookup path on get may kick in. <del> viewClass = context && get(context, path); <add> var lazyValue = data.view.getStream(path); <add> viewClass = lazyValue.value(); <ide> var isGlobal = detectIsGlobal(path); <ide> <ide> if (!viewClass && !isGlobal) { <ide> function handlebarsGetView(context, path, container, data) { <ide> return viewClass; <ide> } <ide> <del>/** <del> This method uses `Ember.Handlebars.get` to lookup a value, then ensures <del> that the value is escaped properly. <del> <del> If `unescaped` is a truthy value then the escaping will not be performed. <del> <del> @method getEscaped <del> @for Ember.Handlebars <del> @param {Object} root The object to look up the property on <del> @param {String} path The path to be lookedup <del> @param {Object} options The template's option hash <del> @since 1.4.0 <del>*/ <del>export function getEscaped(root, path, options) { <del> var result = handlebarsGet(root, path, options); <del> <del> if (result === null || result === undefined) { <del> result = ""; <del> } else if (!(result instanceof Handlebars.SafeString)) { <del> result = String(result); <del> } <del> if (!options.hash.unescaped){ <del> result = Handlebars.Utils.escapeExpression(result); <del> } <del> <del> return result; <del>} <del> <del>export function resolveParams(context, params, options) { <del> var resolvedParams = [], types = options.types, param, type; <del> <del> for (var i=0, l=params.length; i<l; i++) { <del> param = params[i]; <del> type = types[i]; <del> <del> if (type === 'ID') { <del> resolvedParams.push(handlebarsGet(context, param, options)); <del> } else { <del> resolvedParams.push(param); <del> } <add>export function stringifyValue(value, shouldEscape) { <add> if (value === null || value === undefined) { <add> value = ""; <add> } else if (!(value instanceof Handlebars.SafeString)) { <add> value = String(value); <ide> } <ide> <del> return resolvedParams; <del>} <del> <del>export function resolveHash(context, hash, options) { <del> var resolvedHash = {}, types = options.hashTypes, type; <del> <del> for (var key in hash) { <del> if (!hash.hasOwnProperty(key)) { continue; } <del> <del> type = types[key]; <del> <del> if (type === 'ID') { <del> resolvedHash[key] = handlebarsGet(context, hash[key], options); <del> } else { <del> resolvedHash[key] = hash[key]; <del> } <add> if (shouldEscape) { <add> value = Handlebars.Utils.escapeExpression(value); <ide> } <ide> <del> return resolvedHash; <add> return value; <ide> } <ide> <ide> /** <ide> function makeBoundHelper(fn) { <ide> SimpleHandlebarsView = requireModule('ember-handlebars/views/handlebars_bound_view')['SimpleHandlebarsView']; <ide> } // ES6TODO: stupid circular dep <ide> <del> var dependentKeys = slice.call(arguments, 1); <add> var dependentKeys = []; <add> for (var i = 1; i < arguments.length; i++) { <add> dependentKeys.push(arguments[i]); <add> } <ide> <ide> function helper() { <del> var properties = slice.call(arguments, 0, -1); <del> var numProperties = properties.length; <del> var options = arguments[arguments.length - 1]; <del> var normalizedProperties = []; <add> var numParams = arguments.length - 1; <add> var options = arguments[numParams]; <ide> var data = options.data; <del> var types = data.isUnbound ? slice.call(options.types, 1) : options.types; <add> var view = data.view; <add> var types = options.types; <ide> var hash = options.hash; <ide> var hashTypes = options.hashTypes; <del> var view = data.view; <del> var contexts = options.contexts; <del> var currentContext = (contexts && contexts.length) ? contexts[0] : this; <del> var prefixPathForDependentKeys = ''; <del> var loc, len, hashOption; <del> var boundOption, property; <del> var normalizedValue = SimpleHandlebarsView.prototype.normalizedValue; <add> var context = this; <ide> <ide> Ember.assert("registerBoundHelper-generated helpers do not support use with Handlebars blocks.", !options.fn); <ide> <del> // Detect bound options (e.g. countBinding="otherCount") <del> var boundOptions = hash.boundOptions = {}; <del> for (hashOption in hash) { <del> if (IS_BINDING.test(hashOption)) { <del> // Lop off 'Binding' suffix. <del> boundOptions[hashOption.slice(0, -7)] = hash[hashOption]; <del> } else if (hashTypes[hashOption] === 'ID') { <del> boundOptions[hashOption] = hash[hashOption]; <add> var properties = new Array(numParams); <add> var params = new Array(numParams); <add> <add> for (var i = 0; i < numParams; i++) { <add> properties[i] = arguments[i]; <add> if (types[i] === 'ID') { <add> params[i] = view.getStream(arguments[i]); <add> } else { <add> params[i] = arguments[i]; <ide> } <ide> } <ide> <del> // Expose property names on data.properties object. <del> var watchedProperties = []; <del> data.properties = []; <del> for (loc = 0; loc < numProperties; ++loc) { <del> data.properties.push(properties[loc]); <del> if (types[loc] === 'ID') { <del> var normalizedProp = normalizePath(currentContext, properties[loc], data); <del> normalizedProperties.push(normalizedProp); <del> watchedProperties.push(normalizedProp); <del> } else { <del> if (data.isUnbound) { <del> normalizedProperties.push({path: properties[loc]}); <del> }else { <del> normalizedProperties.push(null); <del> } <add> for (var prop in hash) { <add> if (IS_BINDING.test(prop)) { <add> hash[prop.slice(0, -7)] = view.getStream(hash[prop]); <add> hash[prop] = undefined; <add> } else if (hashTypes[prop] === 'ID') { <add> hash[prop] = view.getStream(hash[prop]); <ide> } <ide> } <ide> <del> // Handle case when helper invocation is preceded by `unbound`, e.g. <del> // {{unbound myHelper foo}} <add> var valueFn = function() { <add> var args = readArray(params); <add> args.push({ <add> hash: readHash(hash), <add> data: { properties: properties } <add> }); <add> return fn.apply(context, args); <add> }; <add> <ide> if (data.isUnbound) { <del> return evaluateUnboundHelper(this, fn, normalizedProperties, options); <del> } <add> return valueFn(); <add> } else { <add> var lazyValue = new Stream(valueFn); <add> var bindView = new SimpleHandlebarsView(lazyValue, !options.hash.unescaped); <add> view.appendChild(bindView); <ide> <del> var bindView = new SimpleHandlebarsView(null, null, !options.hash.unescaped, options.data); <add> var scheduledRerender = view._wrapAsScheduled(bindView.rerender); <add> lazyValue.subscribe(scheduledRerender, bindView); <ide> <del> // Override SimpleHandlebarsView's method for generating the view's content. <del> bindView.normalizedValue = function() { <del> var args = []; <del> var boundOption; <add> var param; <ide> <del> // Copy over bound hash options. <del> for (boundOption in boundOptions) { <del> if (!boundOptions.hasOwnProperty(boundOption)) { continue; } <del> property = normalizePath(currentContext, boundOptions[boundOption], data); <del> bindView.path = property.path; <del> bindView.pathRoot = property.root; <del> hash[boundOption] = normalizedValue.call(bindView); <add> for (i = 0; i < numParams; i++) { <add> param = params[i]; <add> if (param && param.isStream) { <add> param.subscribe(lazyValue.notifyAll, lazyValue); <add> } <ide> } <ide> <del> for (loc = 0; loc < numProperties; ++loc) { <del> property = normalizedProperties[loc]; <del> if (property) { <del> bindView.path = property.path; <del> bindView.pathRoot = property.root; <del> args.push(normalizedValue.call(bindView)); <del> } else { <del> args.push(properties[loc]); <add> for (prop in hash) { <add> param = hash[prop]; <add> if (param && param.isStream) { <add> param.subscribe(lazyValue.notifyAll, lazyValue); <ide> } <ide> } <del> args.push(options); <ide> <del> // Run the supplied helper function. <del> return fn.apply(currentContext, args); <del> }; <del> <del> view.appendChild(bindView); <add> if (numParams > 0) { <add> var onDependentKeyNotify = function onDependentKeyNotify(stream) { <add> stream.value(); <add> lazyValue.notify(); <add> }; <ide> <del> // Assemble list of watched properties that'll re-render this helper. <del> for (boundOption in boundOptions) { <del> if (boundOptions.hasOwnProperty(boundOption)) { <del> watchedProperties.push(normalizePath(currentContext, boundOptions[boundOption], data)); <add> for (i = 0; i < dependentKeys.length; i++) { <add> param = new KeyStream(params[0], dependentKeys[i]); <add> param.value(); <add> param.subscribe(onDependentKeyNotify); <add> } <ide> } <ide> } <del> <del> // Observe each property. <del> for (loc = 0, len = watchedProperties.length; loc < len; ++loc) { <del> property = watchedProperties[loc]; <del> view.registerObserver(property.root, property.path, bindView, bindView.rerender); <del> } <del> <del> if (types[0] !== 'ID' || normalizedProperties.length === 0) { <del> return; <del> } <del> <del> // Add dependent key observers to the first param <del> var normalized = normalizedProperties[0]; <del> var pathRoot = normalized.root; <del> var path = normalized.path; <del> <del> if(!isEmpty(path)) { <del> prefixPathForDependentKeys = path + '.'; <del> } <del> for (var i=0, l=dependentKeys.length; i<l; i++) { <del> view.registerObserver(pathRoot, prefixPathForDependentKeys + dependentKeys[i], bindView, bindView.rerender); <del> } <ide> } <ide> <del> helper._rawFunction = fn; <ide> return helper; <ide> } <ide> <del>/** <del> Renders the unbound form of an otherwise bound helper function. <del> <del> @private <del> @method evaluateUnboundHelper <del> @param {Function} fn <del> @param {Object} context <del> @param {Array} normalizedProperties <del> @param {String} options <del>*/ <del>function evaluateUnboundHelper(context, fn, normalizedProperties, options) { <del> var args = []; <del> var hash = options.hash; <del> var boundOptions = hash.boundOptions; <del> var types = slice.call(options.types, 1); <del> var loc, len, property, propertyType, boundOption; <del> <del> for (boundOption in boundOptions) { <del> if (!boundOptions.hasOwnProperty(boundOption)) { continue; } <del> hash[boundOption] = handlebarsGet(context, boundOptions[boundOption], options); <del> } <del> <del> for (loc = 0, len = normalizedProperties.length; loc < len; ++loc) { <del> property = normalizedProperties[loc]; <del> propertyType = types[loc]; <del> if (propertyType === "ID") { <del> args.push(handlebarsGet(property.root, property.path, options)); <del> } else { <del> args.push(property.path); <del> } <del> } <del> args.push(options); <del> return fn.apply(context, args); <del>} <del> <ide> /** <ide> Overrides Handlebars.template so that we can distinguish <ide> user-created, top-level templates from inner contexts. <ide> export function template(spec) { <ide> } <ide> <ide> export { <del> normalizePath, <ide> makeBoundHelper, <del> handlebarsGet, <del> handlebarsGetView, <del> evaluateUnboundHelper <add> handlebarsGetView <ide> }; <ide><path>packages/ember-handlebars/lib/helpers/binding.js <ide> import Ember from "ember-metal/core"; // Ember.assert, Ember.warn, uuid <ide> <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> import { get } from "ember-metal/property_get"; <add>import { set } from "ember-metal/property_set"; <ide> import { <ide> apply, <ide> uuid <ide> } from "ember-metal/utils"; <ide> import { fmt } from "ember-runtime/system/string"; <ide> import { create as o_create } from "ember-metal/platform"; <add>import { typeOf } from "ember-metal/utils"; <ide> import isNone from 'ember-metal/is_none'; <ide> import { forEach } from "ember-metal/array"; <ide> import View from "ember-views/views/view"; <ide> import run from "ember-metal/run_loop"; <del>import { removeObserver } from "ember-metal/observer"; <del>import { isGlobalPath } from "ember-metal/binding"; <del>import { bind as emberBind } from "ember-metal/binding"; <del>import jQuery from "ember-views/system/jquery"; <ide> import { isArray } from "ember-metal/utils"; <ide> import keys from "ember-metal/keys"; <ide> import Cache from "ember-metal/cache"; <add>import SimpleStream from "ember-metal/streams/simple"; <add>import KeyStream from "ember-views/streams/key_stream"; <ide> <ide> import { <ide> _HandlebarsBoundView, <ide> SimpleHandlebarsView <ide> } from "ember-handlebars/views/handlebars_bound_view"; <ide> <del>import { <del> normalizePath, <del> handlebarsGet, <del> getEscaped <del>} from "ember-handlebars/ext"; <del> <del>import { <del> guidFor, <del> typeOf <del>} from "ember-metal/utils"; <del> <ide> var helpers = EmberHandlebars.helpers; <ide> var SafeString = EmberHandlebars.SafeString; <ide> <ide> function exists(value) { <ide> <ide> var WithView = _HandlebarsBoundView.extend({ <ide> init: function() { <del> var controller; <del> <ide> apply(this, this._super, arguments); <ide> <del> var keywords = this.templateData.keywords; <ide> var keywordName = this.templateHash.keywordName; <del> var keywordPath = this.templateHash.keywordPath; <ide> var controllerName = this.templateHash.controller; <del> var preserveContext = this.preserveContext; <ide> <ide> if (controllerName) { <ide> var previousContext = this.previousContext; <del> controller = this.container.lookupFactory('controller:'+controllerName).create({ <add> var controller = this.container.lookupFactory('controller:'+controllerName).create({ <ide> parentController: previousContext, <ide> target: previousContext <ide> }); <ide> <ide> this._generatedController = controller; <ide> <del> if (!preserveContext) { <del> this.set('controller', controller); <del> <add> if (this.preserveContext) { <add> this._keywords[keywordName] = controller; <add> this.lazyValue.subscribe(function(modelStream) { <add> set(controller, 'model', modelStream.value()); <add> }); <add> } else { <add> set(this, 'controller', controller); <ide> this.valueNormalizerFunc = function(result) { <del> controller.set('model', result); <del> return controller; <add> controller.set('model', result); <add> return controller; <ide> }; <del> } else { <del> var controllerPath = jQuery.expando + guidFor(controller); <del> keywords[controllerPath] = controller; <del> emberBind(keywords, controllerPath + '.model', keywordPath); <del> keywordPath = controllerPath; <ide> } <del> } <ide> <del> if (preserveContext) { <del> emberBind(keywords, keywordName, keywordPath); <add> set(controller, 'model', this.lazyValue.value()); <ide> } <del> <ide> }, <add> <ide> willDestroy: function() { <ide> this._super(); <ide> <ide> var WithView = _HandlebarsBoundView.extend({ <ide> // KVO system will look for and update if the property changes. <ide> function bind(property, options, preserveContext, shouldDisplay, valueNormalizer, childProperties) { <ide> var data = options.data; <del> var fn = options.fn; <del> var inverse = options.inverse; <ide> var view = data.view; <del> var normalized, observer, i; <ide> <ide> // we relied on the behavior of calling without <ide> // context to mean this === window, but when running <ide> // "use strict", it's possible for this to === undefined; <ide> var currentContext = this || window; <ide> <del> normalized = normalizePath(currentContext, property, data); <add> var valueStream = view.getStream(property); <add> var lazyValue; <ide> <del> // Set up observers for observable objects <del> if ('object' === typeof this) { <del> if (data.insideGroup) { <del> observer = function() { <del> while (view._contextView) { <del> view = view._contextView; <del> } <del> run.once(view, 'rerender'); <del> }; <add> if (childProperties) { <add> lazyValue = new SimpleStream(valueStream); <ide> <del> var template, context; <del> var result = handlebarsGet(currentContext, property, options); <add> var subscriber = function(childStream) { <add> childStream.value(); <add> lazyValue.notify(); <add> }; <ide> <del> result = valueNormalizer ? valueNormalizer(result) : result; <add> for (var i = 0; i < childProperties.length; i++) { <add> var childStream = new KeyStream(valueStream, childProperties[i]); <add> childStream.value(); <add> childStream.subscribe(subscriber); <add> } <add> } else { <add> lazyValue = valueStream; <add> } <ide> <del> context = preserveContext ? currentContext : result; <del> if (shouldDisplay(result)) { <del> template = fn; <del> } else if (inverse) { <del> template = inverse; <del> } <add> // Set up observers for observable objects <add> var viewClass = _HandlebarsBoundView; <add> var viewOptions = { <add> preserveContext: preserveContext, <add> shouldDisplayFunc: shouldDisplay, <add> valueNormalizerFunc: valueNormalizer, <add> displayTemplate: options.fn, <add> inverseTemplate: options.inverse, <add> lazyValue: lazyValue, <add> previousContext: currentContext, <add> isEscaped: !options.hash.unescaped, <add> templateData: options.data, <add> templateHash: options.hash, <add> helperName: options.helperName <add> }; <ide> <del> template(context, { data: options.data }); <del> } else { <del> var viewClass = _HandlebarsBoundView; <del> var viewOptions = { <del> preserveContext: preserveContext, <del> shouldDisplayFunc: shouldDisplay, <del> valueNormalizerFunc: valueNormalizer, <del> displayTemplate: fn, <del> inverseTemplate: inverse, <del> path: property, <del> pathRoot: currentContext, <del> previousContext: currentContext, <del> isEscaped: !options.hash.unescaped, <del> templateData: options.data, <del> templateHash: options.hash, <del> helperName: options.helperName <del> }; <del> <del> if (options.isWithHelper) { <del> viewClass = WithView; <del> } <add> if (options.keywords) { <add> viewOptions._keywords = options.keywords; <add> } <ide> <del> // Create the view that will wrap the output of this template/property <del> // and add it to the nearest view's childViews array. <del> // See the documentation of Ember._HandlebarsBoundView for more. <del> var bindView = view.createChildView(viewClass, viewOptions); <add> if (options.isWithHelper) { <add> viewClass = WithView; <add> } <ide> <del> view.appendChild(bindView); <add> // Create the view that will wrap the output of this template/property <add> // and add it to the nearest view's childViews array. <add> // See the documentation of Ember._HandlebarsBoundView for more. <add> var bindView = view.createChildView(viewClass, viewOptions); <ide> <del> observer = function() { <del> run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); <del> }; <del> } <add> view.appendChild(bindView); <ide> <del> // Observes the given property on the context and <del> // tells the Ember._HandlebarsBoundView to re-render. If property <del> // is an empty string, we are printing the current context <del> // object ({{this}}) so updating it is not our responsibility. <del> if (normalized.path !== '') { <del> view.registerObserver(normalized.root, normalized.path, observer); <del> if (childProperties) { <del> for (i=0; i<childProperties.length; i++) { <del> view.registerObserver(normalized.root, normalized.path+'.'+childProperties[i], observer); <del> } <del> } <del> } <del> } else { <del> // The object is not observable, so just render it out and <del> // be done with it. <del> data.buffer.push(getEscaped(currentContext, property, options)); <del> } <add> lazyValue.subscribe(view._wrapAsScheduled(function() { <add> run.scheduleOnce('render', bindView, 'rerenderIfNeeded'); <add> })); <ide> } <ide> <del>function simpleBind(currentContext, property, options) { <add>function simpleBind(currentContext, lazyValue, options) { <ide> var data = options.data; <ide> var view = data.view; <del> var normalized, observer, pathRoot, output; <ide> <del> normalized = normalizePath(currentContext, property, data); <del> pathRoot = normalized.root; <add> var bindView = new SimpleHandlebarsView( <add> lazyValue, !options.hash.unescaped <add> ); <ide> <del> // Set up observers for observable objects <del> if (pathRoot && ('object' === typeof pathRoot)) { <del> if (data.insideGroup) { <del> observer = function() { <del> while (view._contextView) { <del> view = view._contextView; <del> } <del> run.once(view, 'rerender'); <del> }; <add> bindView._parentView = view; <add> view.appendChild(bindView); <ide> <del> output = getEscaped(currentContext, property, options); <del> <del> data.buffer.push(output); <del> } else { <del> var bindView = new SimpleHandlebarsView( <del> property, currentContext, !options.hash.unescaped, options.data <del> ); <del> <del> bindView._parentView = view; <del> view.appendChild(bindView); <del> <del> observer = function() { <del> run.scheduleOnce('render', bindView, 'rerender'); <del> }; <del> } <del> <del> // Observes the given property on the context and <del> // tells the Ember._HandlebarsBoundView to re-render. If property <del> // is an empty string, we are printing the current context <del> // object ({{this}}) so updating it is not our responsibility. <del> if (normalized.path !== '') { <del> view.registerObserver(normalized.root, normalized.path, observer); <del> } <del> } else { <del> // The object is not observable, so just render it out and <del> // be done with it. <del> output = getEscaped(currentContext, property, options); <del> data.buffer.push(output); <del> } <add> lazyValue.subscribe(view._wrapAsScheduled(function() { <add> run.scheduleOnce('render', bindView, 'rerender'); <add> })); <ide> } <ide> <ide> function shouldDisplayIfHelperContent(result) { <ide> function bindHelper(property, options) { <ide> var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this; <ide> <ide> if (!options.fn) { <del> return simpleBind(context, property, options); <add> var lazyValue = options.data.view.getStream(property); <add> return simpleBind(context, lazyValue, options); <ide> } <ide> <ide> options.helperName = 'bind'; <ide> function boundIfHelper(property, fn) { <ide> function unboundIfHelper(property, fn) { <ide> var context = (fn.contexts && fn.contexts.length) ? fn.contexts[0] : this; <ide> var data = fn.data; <add> var view = data.view; <ide> var template = fn.fn; <ide> var inverse = fn.inverse; <del> var normalized, propertyValue; <ide> <del> normalized = normalizePath(context, property, data); <del> propertyValue = handlebarsGet(context, property, fn); <add> var propertyValue = view.getStream(property).value(); <ide> <ide> if (!shouldDisplayIfHelperContent(propertyValue)) { <ide> template = inverse; <ide> function unboundIfHelper(property, fn) { <ide> @param {Hash} options <ide> @return {String} HTML string <ide> */ <del>function withHelper(context, options) { <add>function withHelper(contextPath) { <add> var options = arguments[arguments.length - 1]; <add> var view = options.data.view; <ide> var bindContext, preserveContext; <ide> var helperName = 'with'; <ide> <ide> if (arguments.length === 4) { <del> var keywordName, path, rootPath, normalized, contextPath; <del> <ide> Ember.assert("If you pass more than one argument to the with helper," + <ide> " it must be in the form #with foo as bar", arguments[1] === "as"); <del> options = arguments[3]; <del> keywordName = arguments[2]; <del> path = arguments[0]; <ide> <del> if (path) { <del> helperName += ' ' + path + ' as ' + keywordName; <add> var keywordName = arguments[2]; <add> <add> if (contextPath) { <add> helperName += ' ' + contextPath + ' as ' + keywordName; <ide> } <ide> <ide> Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); <ide> <ide> var localizedOptions = o_create(options); <ide> localizedOptions.data = o_create(options.data); <del> localizedOptions.data.keywords = o_create(options.data.keywords || {}); <ide> <del> if (isGlobalPath(path)) { <del> contextPath = path; <del> } else { <del> normalized = normalizePath(this, path, options.data); <del> path = normalized.path; <del> rootPath = normalized.root; <del> <del> // This is a workaround for the fact that you cannot bind separate objects <del> // together. When we implement that functionality, we should use it here. <del> var contextKey = jQuery.expando + guidFor(rootPath); <del> localizedOptions.data.keywords[contextKey] = rootPath; <del> // if the path is '' ("this"), just bind directly to the current context <del> contextPath = path ? contextKey + '.' + path : contextKey; <del> } <add> localizedOptions.keywords = {}; <add> localizedOptions.keywords[keywordName] = view.getStream(contextPath); <ide> <ide> localizedOptions.hash.keywordName = keywordName; <del> localizedOptions.hash.keywordPath = contextPath; <ide> <ide> bindContext = this; <del> context = contextPath; <ide> options = localizedOptions; <ide> preserveContext = true; <ide> } else { <ide> Ember.assert("You must pass exactly one argument to the with helper", arguments.length === 2); <ide> Ember.assert("You must pass a block to the with helper", options.fn && options.fn !== Handlebars.VM.noop); <ide> <del> helperName += ' ' + context; <add> helperName += ' ' + contextPath; <ide> bindContext = options.contexts[0]; <ide> preserveContext = false; <ide> } <ide> <ide> options.helperName = helperName; <ide> options.isWithHelper = true; <ide> <del> return bind.call(bindContext, context, options, preserveContext, exists); <add> return bind.call(bindContext, contextPath, options, preserveContext, exists); <ide> } <ide> /** <ide> See [boundIf](/api/classes/Ember.Handlebars.helpers.html#method_boundIf) <ide> function bindAttrHelper(options) { <ide> // current value of the property as an attribute. <ide> forEach.call(attrKeys, function(attr) { <ide> var path = attrs[attr]; <del> var normalized; <ide> <ide> Ember.assert(fmt("You must provide an expression as the value of bound attribute." + <ide> " You specified: %@=%@", [attr, path]), typeof path === 'string'); <ide> <del> normalized = normalizePath(ctx, path, options.data); <del> <del> var value = (path === 'this') ? normalized.root : handlebarsGet(ctx, path, options); <add> var lazyValue = view.getStream(path); <add> var value = lazyValue.value(); <ide> var type = typeOf(value); <ide> <ide> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [value]), <ide> value === null || value === undefined || type === 'number' || type === 'string' || type === 'boolean'); <ide> <del> var observer; <del> <del> observer = function observer() { <del> var result = handlebarsGet(ctx, path, options); <add> lazyValue.subscribe(view._wrapAsScheduled(function applyAttributeBindings() { <add> var result = lazyValue.value(); <ide> <ide> Ember.assert(fmt("Attributes must be numbers, strings or booleans, not %@", [result]), <ide> result === null || result === undefined || typeof result === 'number' || <ide> typeof result === 'string' || typeof result === 'boolean'); <ide> <ide> var elem = view.$("[data-bindattr-" + dataId + "='" + dataId + "']"); <ide> <del> // If we aren't able to find the element, it means the element <del> // to which we were bound has been removed from the view. <del> // In that case, we can assume the template has been re-rendered <del> // and we need to clean up the observer. <del> if (!elem || elem.length === 0) { <del> removeObserver(normalized.root, normalized.path, observer); <del> return; <del> } <add> Ember.assert("An attribute binding was triggered when the element was not in the DOM", elem && elem.length !== 0); <ide> <ide> View.applyAttributeBindings(elem, attr, result); <del> }; <del> <del> // Add an observer to the view for when the property changes. <del> // When the observer fires, find the element using the <del> // unique data id and update the attribute to the new value. <del> // Note: don't add observer when path is 'this' or path <del> // is whole keyword e.g. {{#each x in list}} ... {{bind-attr attr="x"}} <del> if (path !== 'this' && !(normalized.isKeyword && normalized.path === '' )) { <del> view.registerObserver(normalized.root, normalized.path, observer); <del> } <add> })); <ide> <ide> // if this changes, also change the logic in ember-views/lib/views/view.js <ide> if ((type === 'string' || (type === 'number' && !isNaN(value)))) { <ide> function bindClasses(context, classBindings, view, bindAttrId, options) { <ide> var ret = []; <ide> var newClass, value, elem; <ide> <del> // Helper method to retrieve the property from the context and <del> // determine which class string to return, based on whether it is <del> // a Boolean or not. <del> var classStringForPath = function(root, parsedPath, options) { <del> var val; <del> var path = parsedPath.path; <del> <del> if (path === 'this') { <del> val = root; <del> } else if (path === '') { <del> val = true; <del> } else { <del> val = handlebarsGet(root, path, options); <del> } <del> <del> return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); <del> }; <del> <ide> // For each property passed, loop through and setup <ide> // an observer. <ide> forEach.call(classBindings.split(' '), function(binding) { <ide> function bindClasses(context, classBindings, view, bindAttrId, options) { <ide> // closes over this variable, so it knows which string to remove when <ide> // the property changes. <ide> var oldClass; <del> var observer; <ide> var parsedPath = View._parsePropertyPath(binding); <ide> var path = parsedPath.path; <del> var pathRoot = context; <del> var normalized; <add> var initialValue; <ide> <del> if (path !== '' && path !== 'this') { <del> normalized = normalizePath(context, path, options.data); <add> if (path === '') { <add> initialValue = true; <add> } else { <add> var lazyValue = view.getStream(path); <add> initialValue = lazyValue.value(); <ide> <del> pathRoot = normalized.root; <del> path = normalized.path; <del> } <add> // Set up an observer on the context. If the property changes, toggle the <add> // class name. <add> lazyValue.subscribe(view._wrapAsScheduled(function applyClassNameBindings() { <add> // Get the current value of the property <add> var value = lazyValue.value(); <add> newClass = classStringForParsedPath(parsedPath, value); <add> elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); <add> <add> Ember.assert("A class name binding was triggered when the element was not in the DOM", elem && elem.length !== 0); <ide> <del> // Set up an observer on the context. If the property changes, toggle the <del> // class name. <del> observer = function() { <del> // Get the current value of the property <del> newClass = classStringForPath(context, parsedPath, options); <del> elem = bindAttrId ? view.$("[data-bindattr-" + bindAttrId + "='" + bindAttrId + "']") : view.$(); <del> <del> // If we can't find the element anymore, a parent template has been <del> // re-rendered and we've been nuked. Remove the observer. <del> if (!elem || elem.length === 0) { <del> removeObserver(pathRoot, path, observer); <del> } else { <ide> // If we had previously added a class to the element, remove it. <ide> if (oldClass) { <ide> elem.removeClass(oldClass); <ide> function bindClasses(context, classBindings, view, bindAttrId, options) { <ide> } else { <ide> oldClass = null; <ide> } <del> } <del> }; <del> <del> if (path !== '' && path !== 'this') { <del> view.registerObserver(pathRoot, path, observer); <add> })); <ide> } <ide> <ide> // We've already setup the observer; now we just need to figure out the <ide> // correct behavior right now on the first pass through. <del> value = classStringForPath(context, parsedPath, options); <add> value = classStringForParsedPath(parsedPath, initialValue); <ide> <ide> if (value) { <ide> ret.push(value); <ide> function bindClasses(context, classBindings, view, bindAttrId, options) { <ide> return ret; <ide> } <ide> <add>function classStringForParsedPath(parsedPath, value) { <add> return View._classStringForValue(parsedPath.path, value, parsedPath.className, parsedPath.falsyClassName); <add>} <add> <ide> export { <ide> bind, <ide> _triageMustacheHelper, <ide><path>packages/ember-handlebars/lib/helpers/collection.js <ide> import Ember from "ember-metal/core"; // Ember.assert, Ember.deprecate <ide> <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> <add>import { IS_BINDING } from "ember-metal/mixin"; <ide> import { fmt } from "ember-runtime/system/string"; <ide> import { get } from "ember-metal/property_get"; <add>import SimpleStream from "ember-metal/streams/simple"; <ide> import { handlebarsGetView } from "ember-handlebars/ext"; <ide> import { ViewHelper } from "ember-handlebars/helpers/view"; <ide> import alias from "ember-metal/alias"; <add>import View from "ember-views/views/view"; <ide> import CollectionView from "ember-views/views/collection_view"; <ide> <ide> /** <ide> function collectionHelper(path, options) { <ide> } <ide> <ide> var hash = options.hash; <add> var hashTypes = options.hashTypes; <ide> var itemHash = {}; <ide> var match; <ide> <ide> function collectionHelper(path, options) { <ide> var itemViewClass; <ide> <ide> if (hash.itemView) { <del> itemViewClass = handlebarsGetView(this, hash.itemView, container, options.data); <add> itemViewClass = hash.itemView; <ide> } else if (hash.itemViewClass) { <del> itemViewClass = handlebarsGetView(collectionPrototype, hash.itemViewClass, container, options.data); <add> if (hashTypes.itemViewClass === 'ID') { <add> var itemViewClassStream = view.getStream(hash.itemViewClass); <add> Ember.deprecate('Resolved the view "'+hash.itemViewClass+'" on the global context. Pass a view name to be looked up on the container instead, such as {{view "select"}}. http://emberjs.com/guides/deprecations#toc_global-lookup-of-views-since-1-8', !itemViewClassStream.isGlobal()); <add> itemViewClass = itemViewClassStream.value(); <add> } else { <add> itemViewClass = hash.itemViewClass; <add> } <ide> } else { <del> itemViewClass = handlebarsGetView(collectionPrototype, collectionPrototype.itemViewClass, container, options.data); <add> itemViewClass = collectionPrototype.itemViewClass; <add> } <add> <add> if (typeof itemViewClass === 'string') { <add> itemViewClass = container.lookupFactory('view:'+itemViewClass); <ide> } <ide> <ide> Ember.assert(fmt("%@ #collection: Could not find itemViewClass %@", [data.view, itemViewClass]), !!itemViewClass); <ide> <ide> delete hash.itemViewClass; <ide> delete hash.itemView; <add> delete hashTypes.itemViewClass; <add> delete hashTypes.itemView; <ide> <ide> // Go through options passed to the {{collection}} helper and extract options <ide> // that configure item views instead of the collection itself. <ide> for (var prop in hash) { <add> if (prop === 'itemController' || prop === 'itemClassBinding') { <add> continue; <add> } <ide> if (hash.hasOwnProperty(prop)) { <ide> match = prop.match(/^item(.)(.*)$/); <del> <del> if (match && prop !== 'itemController') { <del> // Convert itemShouldFoo -> shouldFoo <del> itemHash[match[1].toLowerCase() + match[2]] = hash[prop]; <del> // Delete from hash as this will end up getting passed to the <del> // {{view}} helper method. <add> if (match) { <add> var childProp = match[1].toLowerCase() + match[2]; <add> <add> if (hashTypes[prop] === 'ID' || IS_BINDING.test(prop)) { <add> itemHash[childProp] = view._getBindingForStream(hash[prop]); <add> } else { <add> itemHash[childProp] = hash[prop]; <add> } <ide> delete hash[prop]; <ide> } <ide> } <ide> function collectionHelper(path, options) { <ide> } <ide> <ide> var viewOptions = ViewHelper.propertiesFromHTMLOptions({ data: data, hash: itemHash }, this); <add> <add> if (hash.itemClassBinding) { <add> var itemClassBindings = hash.itemClassBinding.split(' '); <add> <add> for (var i = 0; i < itemClassBindings.length; i++) { <add> var parsedPath = View._parsePropertyPath(itemClassBindings[i]); <add> if (parsedPath.path === '') { <add> parsedPath.stream = new SimpleStream(true); <add> } else { <add> parsedPath.stream = view.getStream(parsedPath.path); <add> } <add> itemClassBindings[i] = parsedPath; <add> } <add> <add> viewOptions.classNameBindings = itemClassBindings; <add> } <add> <ide> hash.itemViewClass = itemViewClass.extend(viewOptions); <ide> <ide> options.helperName = options.helperName || 'collection'; <ide><path>packages/ember-handlebars/lib/helpers/debug.js <ide> import Ember from "ember-metal/core"; // Ember.FEATURES, <ide> import { inspect } from "ember-metal/utils"; <ide> import Logger from "ember-metal/logger"; <ide> <del>import { <del> normalizePath, <del> handlebarsGet <del>} from "ember-handlebars/ext"; <del> <ide> var a_slice = [].slice; <ide> <ide> /** <ide> var a_slice = [].slice; <ide> function logHelper() { <ide> var params = a_slice.call(arguments, 0, -1); <ide> var options = arguments[arguments.length - 1]; <add> var view = options.data.view; <ide> var logger = Logger.log; <ide> var values = []; <del> var allowPrimitives = true; <ide> <ide> for (var i = 0; i < params.length; i++) { <del> var type = options.types[i]; <del> <del> if (type === 'ID' || !allowPrimitives) { <del> var context = (options.contexts && options.contexts[i]) || this; <del> var normalized = normalizePath(context, params[i], options.data); <del> <del> if (normalized.path === 'this') { <del> values.push(normalized.root); <del> } else { <del> values.push(handlebarsGet(normalized.root, normalized.path, options)); <del> } <add> if (options.types[i] === 'ID') { <add> var stream = view.getStream(params[i]); <add> values.push(stream.value()); <ide> } else { <ide> values.push(params[i]); <ide> } <ide><path>packages/ember-handlebars/lib/helpers/each.js <ide> @submodule ember-handlebars <ide> */ <ide> import Ember from "ember-metal/core"; // Ember.assert;, Ember.K <del>var K = Ember.K; <ide> <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> <ide> import { Binding } from "ember-metal/binding"; <ide> import ControllerMixin from "ember-runtime/mixins/controller"; <ide> import ArrayController from "ember-runtime/controllers/array_controller"; <ide> import EmberArray from "ember-runtime/mixins/array"; <del>import copy from "ember-runtime/copy"; <del>import run from "ember-metal/run_loop"; <del>import { handlebarsGet } from "ember-handlebars/ext"; <ide> <ide> import { <ide> addObserver, <ide> var EachView = CollectionView.extend(_Metamorph, { <ide> createChildView: function(view, attrs) { <ide> view = this._super(view, attrs); <ide> <del> // At the moment, if a container view subclass wants <del> // to insert keywords, it is responsible for cloning <del> // the keywords hash. This will be fixed momentarily. <del> var keyword = get(this, 'keyword'); <ide> var content = get(view, 'content'); <add> var keyword = get(this, 'keyword'); <ide> <ide> if (keyword) { <del> var data = get(view, 'templateData'); <del> <del> data = copy(data); <del> data.keywords = view.cloneKeywords(); <del> set(view, 'templateData', data); <del> <del> // In this case, we do not bind, because the `content` of <del> // a #each item cannot change. <del> data.keywords[keyword] = content; <add> view._keywords[keyword] = content; <ide> } <ide> <ide> // If {{#each}} is looping over an array of controllers, <ide> var EachView = CollectionView.extend(_Metamorph, { <ide> } <ide> }); <ide> <del>var GroupedEach = EmberHandlebars.GroupedEach = function(context, path, options) { <del> var self = this; <del> var normalized = EmberHandlebars.normalizePath(context, path, options.data); <del> <del> this.context = context; <del> this.path = path; <del> this.options = options; <del> this.template = options.fn; <del> this.containingView = options.data.view; <del> this.normalizedRoot = normalized.root; <del> this.normalizedPath = normalized.path; <del> this.content = this.lookupContent(); <del> <del> this.addContentObservers(); <del> this.addArrayObservers(); <del> <del> this.containingView.on('willClearRender', function() { <del> self.destroy(); <del> }); <del>}; <del> <del>GroupedEach.prototype = { <del> contentWillChange: function() { <del> this.removeArrayObservers(); <del> }, <del> <del> contentDidChange: function() { <del> this.content = this.lookupContent(); <del> this.addArrayObservers(); <del> this.rerenderContainingView(); <del> }, <del> <del> contentArrayWillChange: K, <del> <del> contentArrayDidChange: function() { <del> this.rerenderContainingView(); <del> }, <del> <del> lookupContent: function() { <del> return handlebarsGet(this.normalizedRoot, this.normalizedPath, this.options); <del> }, <del> <del> addArrayObservers: function() { <del> if (!this.content) { return; } <del> <del> this.content.addArrayObserver(this, { <del> willChange: 'contentArrayWillChange', <del> didChange: 'contentArrayDidChange' <del> }); <del> }, <del> <del> removeArrayObservers: function() { <del> if (!this.content) { return; } <del> <del> this.content.removeArrayObserver(this, { <del> willChange: 'contentArrayWillChange', <del> didChange: 'contentArrayDidChange' <del> }); <del> }, <del> <del> addContentObservers: function() { <del> addBeforeObserver(this.normalizedRoot, this.normalizedPath, this, this.contentWillChange); <del> addObserver(this.normalizedRoot, this.normalizedPath, this, this.contentDidChange); <del> }, <del> <del> removeContentObservers: function() { <del> removeBeforeObserver(this.normalizedRoot, this.normalizedPath, this.contentWillChange); <del> removeObserver(this.normalizedRoot, this.normalizedPath, this.contentDidChange); <del> }, <del> <del> render: function() { <del> if (!this.content) { return; } <del> <del> var content = this.content; <del> var contentLength = get(content, 'length'); <del> var options = this.options; <del> var data = options.data; <del> var template = this.template; <del> <del> data.insideEach = true; <del> for (var i = 0; i < contentLength; i++) { <del> var context = content.objectAt(i); <del> options.data.keywords[options.hash.keyword] = context; <del> template(context, { data: data }); <del> } <del> }, <del> <del> rerenderContainingView: function() { <del> var self = this; <del> run.scheduleOnce('render', this, function() { <del> // It's possible it's been destroyed after we enqueued a re-render call. <del> if (!self.destroyed) { <del> self.containingView.rerender(); <del> } <del> }); <del> }, <del> <del> destroy: function() { <del> this.removeContentObservers(); <del> if (this.content) { <del> this.removeArrayObservers(); <del> } <del> this.destroyed = true; <del> } <del>}; <del> <ide> /** <ide> The `{{#each}}` helper loops over elements in a collection. It is an extension <ide> of the base Handlebars `{{#each}}` helper. <ide> GroupedEach.prototype = { <ide> {{/each}} <ide> ``` <ide> <del> ### (Experimental) Grouped Each <del> <del> If a list's membership often changes, but properties of items in that <del> group rarely change, a significant improvement in template rendering <del> time can be achieved by using the experimental [group helper](https://github.com/emberjs/group-helper). <del> <del> ```handlebars <del> {{#group}} <del> {{#each people}} <del> {{firstName}} {{lastName}} <del> {{/each}} <del> {{/group}} <del> ``` <del> <del> When the membership of `people` changes, or when any property changes, the entire <del> `{{#group}}` block will be re-rendered. <del> <del> An `{{#each}}` inside the `{{#group}}` helper can opt-out of the special group <del> behavior by passing the `groupedRows` option. For example: <del> <del> ```handlebars <del> {{#group}} <del> {{#each dealers}} <del> {{! uses group's special behavior }} <del> {{firstName}} {{lastName}} <del> {{/each}} <del> <del> {{#each car in cars groupedRows=true}} <del> {{! does not use group's special behavior }} <del> {{car.make}} {{car.model}} {{car.color}} <del> {{/each}} <del> {{/group}} <del> ``` <del> <del> Any change to the `dealers` collection will cause the entire group to be re-rendered. <del> Changes to the `cars` collection will be re-rendered individually, as they are with <del> normal `{{#each}}` usage. <del> <del> `{{#group}}` is implemented with an `itemViewClass`, so specifying an `itemViewClass` <del> on an `{{#each}}` will also disable the special re-rendering behavior. <del> <ide> @method each <ide> @for Ember.Handlebars.helpers <ide> @param [name] {String} name for item (used with `in`) <ide> GroupedEach.prototype = { <ide> @param [options.itemViewClass] {String} a path to a view class used for each item <ide> @param [options.emptyViewClass] {String} a path to a view class used for each item <ide> @param [options.itemController] {String} name of a controller to be created for each item <del> @param [options.groupedRows] {boolean} enable normal item-by-item rendering when inside a `#group` helper <ide> */ <del>function eachHelper(path, options) { <del> var ctx; <add>function eachHelper(path) { <add> var options = arguments[arguments.length - 1]; <ide> var helperName = 'each'; <ide> <ide> if (arguments.length === 4) { <ide> Ember.assert("If you pass more than one argument to the each helper," + <ide> " it must be in the form #each foo in bar", arguments[1] === "in"); <ide> <ide> var keywordName = arguments[0]; <del> <del> <del> options = arguments[3]; <ide> path = arguments[2]; <ide> <ide> helperName += ' ' + keywordName + ' in ' + path; <ide> <del> if (path === '') { <del> path = "this"; <del> } <del> <ide> options.hash.keyword = keywordName; <del> <ide> } else if (arguments.length === 1) { <del> options = path; <del> path = 'this'; <add> path = ''; <ide> } else { <ide> helperName += ' ' + path; <ide> } <ide> <add> options.hash.emptyViewClass = Ember._MetamorphView; <ide> options.hash.dataSourceBinding = path; <del> // Set up emptyView as a metamorph with no tag <del> //options.hash.emptyViewClass = Ember._MetamorphView; <del> <del> // can't rely on this default behavior when use strict <del> ctx = this || window; <del> <add> options.hashTypes.dataSourceBinding = 'STRING'; <ide> options.helperName = options.helperName || helperName; <ide> <del> if (options.data.insideGroup && !options.hash.groupedRows && !options.hash.itemViewClass) { <del> new GroupedEach(ctx, path, options).render(); <del> } else { <del> return EmberHandlebars.helpers.collection.call(ctx, EmberHandlebars.EachView, options); <del> } <add> return EmberHandlebars.helpers.collection.call(this, EmberHandlebars.EachView, options); <ide> } <ide> <ide> export { <ide> EachView, <del> GroupedEach, <ide> eachHelper <ide> }; <del> <ide><path>packages/ember-handlebars/lib/helpers/partial.js <ide> import Ember from "ember-metal/core"; // Ember.assert <ide> // var emberAssert = Ember.assert; <ide> <ide> import { isNone } from 'ember-metal/is_none'; <del>import { handlebarsGet } from "ember-handlebars/ext"; <ide> import { bind } from "ember-handlebars/helpers/binding"; <ide> <ide> /** <ide> import { bind } from "ember-handlebars/helpers/binding"; <ide> */ <ide> <ide> export default function partialHelper(name, options) { <add> var view = options.data.view; <ide> <ide> var context = (options.contexts && options.contexts.length) ? options.contexts[0] : this; <ide> <ide> options.helperName = options.helperName || 'partial'; <ide> <ide> if (options.types[0] === "ID") { <add> var partialNameStream = view.getStream(name); <ide> // Helper was passed a property path; we need to <ide> // create a binding that will re-render whenever <ide> // this property changes. <ide> options.fn = function(context, fnOptions) { <del> var partialName = handlebarsGet(context, name, fnOptions); <del> renderPartial(context, partialName, fnOptions); <add> renderPartial(context, partialNameStream.value(), fnOptions); <ide> }; <ide> <ide> return bind.call(context, name, options, true, exists); <ide><path>packages/ember-handlebars/lib/helpers/shared.js <del>import { handlebarsGet } from "ember-handlebars/ext"; <del> <del>export default function resolvePaths(options) { <del> var ret = []; <del> var contexts = options.contexts; <del> var roots = options.roots; <del> var data = options.data; <del> <del> for (var i=0, l=contexts.length; i<l; i++) { <del> ret.push(handlebarsGet(roots[i], contexts[i], { data: data })); <del> } <del> <del> return ret; <del>} <ide><path>packages/ember-handlebars/lib/helpers/unbound.js <ide> import EmberHandlebars from "ember-handlebars-compiler"; <ide> <ide> import { resolveHelper } from "ember-handlebars/helpers/binding"; <del>import { handlebarsGet } from "ember-handlebars/ext"; <del> <del>var slice = [].slice; <ide> <ide> /** <ide> `unbound` allows you to output a property without binding. *Important:* The <ide> var slice = [].slice; <ide> @param {String} property <ide> @return {String} HTML string <ide> */ <del>export default function unboundHelper(property, fn) { <del> var options = arguments[arguments.length - 1]; <del> var container = options.data.view.container; <del> var helper, context, out, ctx; <del> <del> ctx = this; <del> if (arguments.length > 2) { <del> // Unbound helper call. <add>export default function unboundHelper(property) { <add> var argsLength = arguments.length; <add> var options = arguments[argsLength - 1]; <add> var view = options.data.view; <add> var container = view.container; <add> <add> if (argsLength <= 2) { <add> return view.getStream(property).value(); <add> } else { <ide> options.data.isUnbound = true; <del> helper = resolveHelper(container, property) || EmberHandlebars.helpers.helperMissing; <del> out = helper.apply(ctx, slice.call(arguments, 1)); <add> options.types.shift(); <add> <add> var args = new Array(argsLength - 1); <add> for (var i = 1; i < argsLength; i++) { <add> args[i - 1] = arguments[i]; <add> } <add> <add> var helper = resolveHelper(container, property) || EmberHandlebars.helpers.helperMissing; <add> var result = helper.apply(this, args); <add> <ide> delete options.data.isUnbound; <del> return out; <add> return result; <ide> } <del> <del> context = (fn.contexts && fn.contexts.length) ? fn.contexts[0] : ctx; <del> return handlebarsGet(context, property, fn); <ide> } <ide><path>packages/ember-handlebars/lib/helpers/view.js <ide> import Ember from "ember-metal/core"; // Ember.warn, Ember.assert <ide> <ide> import EmberObject from "ember-runtime/system/object"; <ide> import { get } from "ember-metal/property_get"; <add>import keys from "ember-metal/keys"; <ide> import { IS_BINDING } from "ember-metal/mixin"; <add>import { readViewFactory } from "ember-views/streams/read"; <ide> import View from "ember-views/views/view"; <del>import { isGlobalPath } from "ember-metal/binding"; <del>import keys from 'ember-metal/keys'; <del>import { <del> normalizePath, <del> handlebarsGet, <del> handlebarsGetView <del>} from "ember-handlebars/ext"; <add>import SimpleStream from "ember-metal/streams/simple"; <ide> <del>var SELF_BINDING = /^_view\./; <del> <del>function makeBindings(thisContext, options) { <add>function makeBindings(options) { <ide> var hash = options.hash; <del> var hashType = options.hashTypes; <add> var hashTypes = options.hashTypes; <add> var view = options.data.view; <ide> <ide> for (var prop in hash) { <del> if (hashType[prop] === 'ID') { <add> var hashType = hashTypes[prop]; <add> var value = hash[prop]; <ide> <del> var value = hash[prop]; <add> if (IS_BINDING.test(prop)) { <add> // classBinding is processed separately <add> if (prop === 'classBinding') { <add> continue; <add> } <ide> <del> if (IS_BINDING.test(prop)) { <add> if (hashType === 'ID') { <ide> Ember.warn("You're attempting to render a view by passing " + <ide> prop + "=" + value + <ide> " to a view helper, but this syntax is ambiguous. You should either surround " + <ide> value + " in quotes or remove `Binding` from " + prop + "."); <del> } else { <del> hash[prop + 'Binding'] = value; <del> hashType[prop + 'Binding'] = 'STRING'; <add> hash[prop] = view._getBindingForStream(value); <add> } else if (typeof value === 'string') { <add> hash[prop] = view._getBindingForStream(value); <add> } <add> } else { <add> if (hashType === 'ID') { <add> hash[prop + 'Binding'] = view._getBindingForStream(value); <ide> delete hash[prop]; <del> delete hashType[prop]; <add> delete hashTypes[prop]; <ide> } <ide> } <ide> } <ide> <del> if (hash.hasOwnProperty('idBinding')) { <add> if (hash.idBinding) { <ide> // id can't be bound, so just perform one-time lookup. <del> hash.id = handlebarsGet(thisContext, hash.idBinding, options); <del> hashType.id = 'STRING'; <add> hash.id = hash.idBinding.value(); <add> hashTypes.id = 'STRING'; <ide> delete hash.idBinding; <del> delete hashType.idBinding; <add> delete hashTypes.idBinding; <ide> } <ide> } <ide> <ide> export var ViewHelper = EmberObject.create({ <ide> propertiesFromHTMLOptions: function(options) { <add> var view = options.data.view; <ide> var hash = options.hash; <del> var data = options.data; <ide> var classes = hash['class']; <ide> <ide> var extensions = { <ide> export var ViewHelper = EmberObject.create({ <ide> // Set the proper context for all bindings passed to the helper. This applies to regular attribute bindings <ide> // as well as class name bindings. If the bindings are local, make them relative to the current context <ide> // instead of the view. <del> var path; <add> <ide> var hashKeys = keys(hash); <ide> <ide> for (var i = 0, l = hashKeys.length; i < l; i++) { <del> var prop = hashKeys[i]; <del> var isBinding = IS_BINDING.test(prop); <add> var prop = hashKeys[i]; <ide> <ide> if (prop !== 'classNameBindings') { <ide> extensions[prop] = hash[prop]; <ide> } <del> <del> // Test if the property ends in "Binding" <del> if (isBinding && typeof extensions[prop] === 'string') { <del> path = this.contextualizeBindingPath(hash[prop], data); <del> if (path) { <del> extensions[prop] = path; <del> } <del> } <ide> } <ide> <del> if (extensions.classNameBindings) { <del> // Evaluate the context of class name bindings: <del> for (var j = 0, k = extensions.classNameBindings.length; j < k; j++) { <del> var full = extensions.classNameBindings[j]; <del> <del> if (typeof full === 'string') { <del> // Contextualize the path of classNameBinding so this: <del> // <del> // classNameBinding="isGreen:green" <del> // <del> // is converted to this: <del> // <del> // classNameBinding="_parentView.context.isGreen:green" <del> var parsedPath = View._parsePropertyPath(full); <del> if (parsedPath.path !== '') { <del> path = this.contextualizeBindingPath(parsedPath.path, data); <del> if (path) { <del> extensions.classNameBindings[j] = path + parsedPath.classNames; <del> } <del> } <add> var classNameBindings = extensions.classNameBindings; <add> if (classNameBindings) { <add> for (var j = 0; j < classNameBindings.length; j++) { <add> var parsedPath = View._parsePropertyPath(classNameBindings[j]); <add> if (parsedPath.path === '') { <add> parsedPath.stream = new SimpleStream(true); <add> } else { <add> parsedPath.stream = view.getStream(parsedPath.path); <ide> } <add> classNameBindings[j] = parsedPath; <ide> } <ide> } <ide> <ide> return extensions; <ide> }, <ide> <del> // Transform bindings from the current context to a context that can be evaluated within the view. <del> // Returns null if the path shouldn't be changed. <del> contextualizeBindingPath: function(path, data) { <del> if (SELF_BINDING.test(path)) { <del> return path.slice(6); // Lop off "_view." <del> } <del> var normalized = normalizePath(null, path, data); <del> if (normalized.isKeyword) { <del> return 'templateData.keywords.' + path; <del> } else if (isGlobalPath(path)) { <del> return null; <del> } else if (path === 'this' || path === '') { <del> return '_parentView.context'; <del> } else { <del> return '_parentView.context.' + path; <del> } <del> }, <del> <del> helper: function(thisContext, path, options) { <add> helper: function(thisContext, newView, options) { <ide> var data = options.data; <ide> var fn = options.fn; <del> var newView; <del> <del> makeBindings(thisContext, options); <ide> <del> var container = this.container || (data && data.view && data.view.container); <del> newView = handlebarsGetView(thisContext, path, container, options.data); <add> makeBindings(options); <ide> <ide> var viewOptions = this.propertiesFromHTMLOptions(options, thisContext); <ide> var currentView = data.view; <ide> export var ViewHelper = EmberObject.create({ <ide> var data = options.data; <ide> var fn = options.fn; <ide> <del> makeBindings(thisContext, options); <add> makeBindings(options); <ide> <ide> Ember.assert( <ide> 'Only a instance of a view may be passed to the ViewHelper.instanceHelper', <ide> export var ViewHelper = EmberObject.create({ <ide> @param {Hash} options <ide> @return {String} HTML string <ide> */ <del>export function viewHelper(path, options) { <add>export function viewHelper(path) { <ide> Ember.assert("The view helper only takes a single argument", arguments.length <= 2); <ide> <add> var options = arguments[arguments.length - 1]; <add> var types = options.types; <add> var view = options.data.view; <add> var container = view.container || view._keywords.view.value().container; <add> var viewClass; <add> <ide> // If no path is provided, treat path param as options <ide> // and get an instance of the registered `view:toplevel` <del> if (path && path.data && path.data.isRenderData) { <del> options = path; <del> if (options.data && options.data.view && options.data.view.container) { <del> path = options.data.view.container.lookupFactory('view:toplevel'); <add> if (arguments.length === 1) { <add> if (container) { <add> viewClass = container.lookupFactory('view:toplevel'); <add> } else { <add> viewClass = View; <add> } <add> } else { <add> var pathStream; <add> if (typeof path === 'string' && types[0] === 'ID') { <add> pathStream = view.getStream(path); <add> Ember.deprecate('Resolved the view "'+path+'" on the global context. Pass a view name to be looked up on the container instead, such as {{view "select"}}. http://emberjs.com/guides/deprecations#toc_global-lookup-of-views-since-1-8', !pathStream.isGlobal()); <ide> } else { <del> path = View; <add> pathStream = path; <ide> } <add> <add> viewClass = readViewFactory(pathStream, container); <ide> } <ide> <ide> options.helperName = options.helperName || 'view'; <ide> <del> return ViewHelper.helper(this, path, options); <add> return ViewHelper.helper(this, viewClass, options); <ide> } <ide><path>packages/ember-handlebars/lib/main.js <ide> import { runLoadHooks } from "ember-runtime/system/lazy_load"; <ide> import bootstrap from "ember-handlebars/loader"; <ide> <ide> import { <del> normalizePath, <ide> template, <ide> makeBoundHelper, <ide> registerBoundHelper, <del> resolveHash, <del> resolveParams, <del> getEscaped, <del> handlebarsGet, <del> evaluateUnboundHelper, <ide> helperMissingHelper, <ide> blockHelperMissingHelper <ide> } from "ember-handlebars/ext"; <ide> import { <ide> // side effect of extending StringUtils of htmlSafe <ide> import "ember-handlebars/string"; <ide> <del>import resolvePaths from "ember-handlebars/helpers/shared"; <ide> import { <ide> bind, <ide> _triageMustacheHelper, <ide> import { <ide> } from "ember-handlebars/helpers/debug"; <ide> import { <ide> EachView, <del> GroupedEach, <ide> eachHelper <ide> } from "ember-handlebars/helpers/each"; <ide> import templateHelper from "ember-handlebars/helpers/template"; <ide> EmberHandlebars.bootstrap = bootstrap; <ide> EmberHandlebars.template = template; <ide> EmberHandlebars.makeBoundHelper = makeBoundHelper; <ide> EmberHandlebars.registerBoundHelper = registerBoundHelper; <del>EmberHandlebars.resolveHash = resolveHash; <del>EmberHandlebars.resolveParams = resolveParams; <ide> EmberHandlebars.resolveHelper = resolveHelper; <del>EmberHandlebars.get = handlebarsGet; <del>EmberHandlebars.getEscaped = getEscaped; <del>EmberHandlebars.evaluateUnboundHelper = evaluateUnboundHelper; <ide> EmberHandlebars.bind = bind; <ide> EmberHandlebars.bindClasses = bindClasses; <ide> EmberHandlebars.EachView = EachView; <del>EmberHandlebars.GroupedEach = GroupedEach; <del>EmberHandlebars.resolvePaths = resolvePaths; <ide> EmberHandlebars.ViewHelper = ViewHelper; <del>EmberHandlebars.normalizePath = normalizePath; <ide> <ide> <ide> // Ember Globals <ide><path>packages/ember-handlebars/lib/views/handlebars_bound_view.js <ide> import { <ide> } from "ember-views/views/states"; <ide> <ide> import _MetamorphView from "ember-handlebars/views/metamorph_view"; <del>import { handlebarsGet } from "ember-handlebars/ext"; <ide> import { uuid } from "ember-metal/utils"; <ide> <del>function SimpleHandlebarsView(path, pathRoot, isEscaped, templateData) { <del> this.path = path; <del> this.pathRoot = pathRoot; <add>function SimpleHandlebarsView(lazyValue, isEscaped) { <add> this.lazyValue = lazyValue; <ide> this.isEscaped = isEscaped; <del> this.templateData = templateData; <ide> this[Ember.GUID_KEY] = uuid(); <ide> this._lastNormalizedValue = undefined; <ide> this.state = 'preRender'; <ide> SimpleHandlebarsView.prototype = { <ide> propertyDidChange: K, <ide> <ide> normalizedValue: function() { <del> var path = this.path; <del> var pathRoot = this.pathRoot; <del> var escape = this.isEscaped; <del> var result, templateData; <del> <del> // Use the pathRoot as the result if no path is provided. This <del> // happens if the path is `this`, which gets normalized into <del> // a `pathRoot` of the current Handlebars context and a path <del> // of `''`. <del> if (path === '') { <del> result = pathRoot; <del> } else { <del> templateData = this.templateData; <del> result = handlebarsGet(pathRoot, path, { data: templateData }); <del> } <add> var result = this.lazyValue.value(); <ide> <ide> if (result === null || result === undefined) { <ide> result = ""; <del> } else if (!escape && !(result instanceof EmberHandlebars.SafeString)) { <add> } else if (!this.isEscaped && !(result instanceof EmberHandlebars.SafeString)) { <ide> result = new EmberHandlebars.SafeString(result); <ide> } <ide> <ide> var _HandlebarsBoundView = _MetamorphView.extend({ <ide> */ <ide> inverseTemplate: null, <ide> <del> <del> /** <del> The path to look up on `pathRoot` that is passed to <del> `shouldDisplayFunc` to determine which template to render. <del> <del> In addition, if `preserveContext` is `false,` the object at this path will <del> be passed to the template when rendering. <del> <del> @property path <del> @type String <del> @default null <del> */ <del> path: null, <del> <del> /** <del> The object from which the `path` will be looked up. Sometimes this is the <del> same as the `previousContext`, but in cases where this view has been <del> generated for paths that start with a keyword such as `view` or <del> `controller`, the path root will be that resolved object. <del> <del> @property pathRoot <del> @type Object <del> */ <del> pathRoot: null, <add> lazyValue: null, <ide> <ide> normalizedValue: function() { <del> var path = get(this, 'path'); <del> var pathRoot = get(this, 'pathRoot'); <add> var value = this.lazyValue.value(); <ide> var valueNormalizer = get(this, 'valueNormalizerFunc'); <del> var result, templateData; <del> <del> // Use the pathRoot as the result if no path is provided. This <del> // happens if the path is `this`, which gets normalized into <del> // a `pathRoot` of the current Handlebars context and a path <del> // of `''`. <del> if (path === '') { <del> result = pathRoot; <del> } else { <del> templateData = get(this, 'templateData'); <del> result = handlebarsGet(pathRoot, path, { data: templateData }); <del> } <del> <del> return valueNormalizer ? valueNormalizer(result) : result; <add> return valueNormalizer ? valueNormalizer(value) : value; <ide> }, <ide> <ide> rerenderIfNeeded: function() { <ide><path>packages/ember-handlebars/tests/handlebars_test.js <ide> test("child views can be inserted using the {{view}} Handlebars helper", functio <ide> ok(view.$().text().match(/Hello world!.*Goodbye cruel world\!/), "parent view should appear before the child view"); <ide> }); <ide> <del>test("should accept relative paths to views", function() { <del> view = EmberView.create({ <del> template: EmberHandlebars.compile('Hey look, at {{view "view.myCool.view"}}'), <del> <del> myCool: EmberObject.create({ <del> view: EmberView.extend({ <del> template: EmberHandlebars.compile("my cool view") <del> }) <del> }) <del> }); <del> <del> appendView(); <del> <del> equal(view.$().text(), "Hey look, at my cool view"); <del>}); <del> <ide> test("child views can be inserted inside a bind block", function() { <ide> container.register('template:nester', EmberHandlebars.compile("<h1 id='hello-world'>Hello {{world}}</h1>{{view view.bqView}}")); <ide> container.register('template:nested', EmberHandlebars.compile("<div id='child-view'>Goodbye {{#with content}}{{blah}} {{view view.otherView}}{{/with}} {{world}}</div>")); <ide> test("child views can be inserted inside a bind block", function() { <ide> ok(view.$().text().match(/Hello world!.*Goodbye.*wot.*cruel.*world\!/), "parent view should appear before the child view"); <ide> }); <ide> <del>test("View should bind properties in the parent context", function() { <del> var context = { <del> content: EmberObject.create({ <del> wham: 'bam' <del> }), <del> <del> blam: "shazam" <del> }; <del> <del> view = EmberView.create({ <del> context: context, <del> template: EmberHandlebars.compile('<h1 id="first">{{#with content}}{{wham}}-{{../blam}}{{/with}}</h1>') <del> }); <del> <del> appendView(); <del> <del> equal(view.$('#first').text(), "bam-shazam", "renders parent properties"); <del>}); <del> <ide> test("using Handlebars helper that doesn't exist should result in an error", function() { <ide> var names = [{ name: 'Alex' }, { name: 'Stef' }]; <ide> var context = { content: A(names) }; <ide> test("using Handlebars helper that doesn't exist should result in an error", fun <ide> }, "Missing helper: 'group'"); <ide> }); <ide> <del>test("View should bind properties in the grandparent context", function() { <del> var context = { <del> content: EmberObject.create({ <del> wham: 'bam', <del> thankYou: EmberObject.create({ <del> value: "ma'am" <del> }) <del> }), <del> <del> blam: "shazam" <del> }; <del> <del> view = EmberView.create({ <del> context: context, <del> template: EmberHandlebars.compile('<h1 id="first">{{#with content}}{{#with thankYou}}{{value}}-{{../wham}}-{{../../blam}}{{/with}}{{/with}}</h1>') <del> }); <del> <del> appendView(); <del> <del> equal(view.$('#first').text(), "ma'am-bam-shazam", "renders grandparent properties"); <del>}); <del> <ide> test("View should update when a property changes and the bind helper is used", function() { <ide> container.register('template:foo', EmberHandlebars.compile('<h1 id="first">{{#with view.content}}{{bind "wham"}}{{/with}}</h1>')); <ide> <ide> test("itemViewClass works in the #collection helper with a global (DEPRECATED)", <ide> exampleController: ArrayProxy.create({ <ide> content: A(['alpha']) <ide> }), <del> template: EmberHandlebars.compile('{{#collection content=view.exampleController itemViewClass="TemplateTests.ExampleItemView"}}beta{{/collection}}') <add> template: EmberHandlebars.compile('{{#collection content=view.exampleController itemViewClass=TemplateTests.ExampleItemView}}beta{{/collection}}') <ide> }); <ide> <ide> expectDeprecation(function(){ <ide> test("itemViewClass works in the #collection helper with a global (DEPRECATED)", <ide> ok(firstGrandchild(view).isAlsoCustom, "uses the example view class specified in the #collection helper"); <ide> }); <ide> <del>test("itemViewClass works in the #collection helper relatively", function() { <add>test("itemViewClass works in the #collection helper with a property", function() { <ide> var ExampleItemView = EmberView.extend({ <ide> isAlsoCustom: true <ide> }); <ide> <del> var ExampleCollectionView = CollectionView.extend({ <del> possibleItemView: ExampleItemView <del> }); <add> var ExampleCollectionView = CollectionView; <ide> <ide> view = EmberView.create({ <add> possibleItemView: ExampleItemView, <ide> exampleCollectionView: ExampleCollectionView, <ide> exampleController: ArrayProxy.create({ <ide> content: A(['alpha']) <ide> }), <del> template: EmberHandlebars.compile('{{#collection view.exampleCollectionView content=view.exampleController itemViewClass="possibleItemView"}}beta{{/collection}}') <add> template: EmberHandlebars.compile('{{#collection view.exampleCollectionView content=view.exampleController itemViewClass=view.possibleItemView}}beta{{/collection}}') <ide> }); <ide> <ide> run(function() { <ide> test("should not update boundIf if truthiness does not change", function() { <ide> equal(view.$('#first').text(), "bam", "renders block when condition is true"); <ide> }); <ide> <del>test("boundIf should support parent access", function() { <del> view = EmberView.create({ <del> template: EmberHandlebars.compile( <del> '<h1 id="first">{{#with view.content}}{{#with thankYou}}'+ <del> '{{#boundIf ../view.show}}parent{{/boundIf}}-{{#boundIf ../../view.show}}grandparent{{/boundIf}}'+ <del> '{{/with}}{{/with}}</h1>' <del> ), <del> <del> content: EmberObject.create({ <del> show: true, <del> thankYou: EmberObject.create() <del> }), <del> <del> show: true <del> }); <del> <del> appendView(); <del> <del> equal(view.$('#first').text(), "parent-grandparent", "renders boundIfs using .."); <del>}); <del> <ide> test("{{view}} id attribute should set id on layer", function() { <ide> container.register('template:foo', EmberHandlebars.compile('{{#view view.idView id="bar"}}baz{{/view}}')); <ide> <ide> test("should be able to bind to globals with {{bind-attr}} (DEPRECATED)", functi <ide> }, /Global lookup of TemplateTests.value from a Handlebars template is deprecated/); <ide> <ide> equal(view.$('img').attr('alt'), "Test", "renders initial value"); <del> <del> expectDeprecation(function(){ <del> run(function() { <del> TemplateTests.set('value', 'Updated'); <del> }); <del> }, /Global lookup of TemplateTests.value from a Handlebars template is deprecated/); <del> <del> equal(view.$('img').attr('alt'), "Updated", "updates value"); <ide> }); <ide> <ide> test("should not allow XSS injection via {{bind-attr}}", function() { <ide> test("should be able to bind classes to globals with {{bind-attr class}} (DEPREC <ide> }, /Global lookup of TemplateTests.isOpen from a Handlebars template is deprecated/); <ide> <ide> ok(view.$('img').hasClass('is-open'), "sets classname to the dasherized value of the global property"); <del> <del> expectDeprecation(function(){ <del> run(function() { <del> TemplateTests.set('isOpen', false); <del> }); <del> }, /Global lookup of TemplateTests.isOpen from a Handlebars template is deprecated/); <del> <del> ok(!view.$('img').hasClass('is-open'), "removes the classname when the global property has changed"); <ide> }); <ide> <ide> test("should be able to bind-attr to 'this' in an {{#each}} block", function() { <ide> test("should be able to output a property without binding", function() { <ide> var context = { <ide> content: EmberObject.create({ <ide> anUnboundString: "No spans here, son." <del> }), <del> <del> anotherUnboundString: "Not here, either." <add> }) <ide> }; <ide> <ide> view = EmberView.create({ <ide> context: context, <ide> template: EmberHandlebars.compile( <del> '<div id="first">{{unbound content.anUnboundString}}</div>'+ <del> '{{#with content}}<div id="second">{{unbound ../anotherUnboundString}}</div>{{/with}}' <add> '<div id="first">{{unbound content.anUnboundString}}</div>' <ide> ) <ide> }); <ide> <ide> appendView(); <ide> <ide> equal(view.$('#first').html(), "No spans here, son."); <del> equal(view.$('#second').html(), "Not here, either."); <ide> }); <ide> <ide> test("should allow standard Handlebars template usage", function() { <ide> QUnit.module("Ember.View - handlebars integration", { <ide> <ide> test("should be able to log a property", function() { <ide> var context = { <del> value: 'one', <del> valueTwo: 'two', <del> <del> content: EmberObject.create({}) <add> value: 'one' <ide> }; <ide> <ide> view = EmberView.create({ <ide> context: context, <del> template: EmberHandlebars.compile('{{log value}}{{#with content}}{{log ../valueTwo}}{{/with}}') <add> template: EmberHandlebars.compile('{{log value}}') <ide> }); <ide> <ide> appendView(); <ide> <ide> equal(view.$().text(), "", "shouldn't render any text"); <ide> equal(logCalls[0], 'one', "should call log with value"); <del> equal(logCalls[1], 'two', "should call log with valueTwo"); <ide> }); <ide> <ide> test("should be able to log a view property", function() { <ide> test("should teardown observers from bind-attr on rerender", function() { <ide> <ide> appendView(); <ide> <del> equal(observersFor(view, 'foo').length, 2); <add> equal(observersFor(view, 'foo').length, 1); <ide> <ide> run(function() { <ide> view.rerender(); <ide> }); <ide> <del> equal(observersFor(view, 'foo').length, 2); <add> equal(observersFor(view, 'foo').length, 1); <ide> }); <ide><path>packages/ember-handlebars/tests/helpers/bound_helper_test.js <ide> test("bound helpers should support options", function() { <ide> <ide> appendView(); <ide> <del> ok(view.$().text() === 'ababab', "helper output is correct"); <add> equal(view.$().text(), 'ababab', "helper output is correct"); <ide> }); <ide> <ide> test("bound helpers should support keywords", function() { <ide> test("bound helpers should support keywords", function() { <ide> <ide> appendView(); <ide> <del> ok(view.$().text() === 'AB', "helper output is correct"); <add> equal(view.$().text(), 'AB', "helper output is correct"); <ide> }); <ide> <ide> test("bound helpers should support global paths [DEPRECATED]", function() { <ide> test("bound helpers should support global paths [DEPRECATED]", function() { <ide> appendView(); <ide> }, /Global lookup of Text from a Handlebars template is deprecated/); <ide> <del> ok(view.$().text() === 'AB', "helper output is correct"); <add> equal(view.$().text(), 'AB', "helper output is correct"); <ide> }); <ide> <ide> test("bound helper should support this keyword", function() { <ide> test("bound helper should support this keyword", function() { <ide> <ide> appendView(); <ide> <del> ok(view.$().text() === 'AB', "helper output is correct"); <add> equal(view.$().text(), 'AB', "helper output is correct"); <ide> }); <ide> <ide> test("bound helpers should support bound options", function() { <ide> test("bound helpers can handle `this` keyword when it's a non-object", function( <ide> run(view.controller.things, 'pushObject', 'wallace'); <ide> equal(view.$().text(), 'wallace!', "helper output is correct"); <ide> }); <del> <del> <ide><path>packages/ember-handlebars/tests/helpers/each_test.js <ide> test("it defers all normalization of itemView names to the resolver", function() <ide> test("it supports {{itemViewClass=}} with global (DEPRECATED)", function() { <ide> run(function() { view.destroy(); }); // destroy existing view <ide> view = EmberView.create({ <del> template: templateFor('{{each view.people itemViewClass="MyView"}}'), <add> template: templateFor('{{each view.people itemViewClass=MyView}}'), <ide> people: people <ide> }); <ide> <ide> test("it supports {{itemViewClass=}} via container", function() { <ide> test("it supports {{itemViewClass=}} with tagName (DEPRECATED)", function() { <ide> run(function() { view.destroy(); }); // destroy existing view <ide> view = EmberView.create({ <del> template: templateFor('{{each view.people itemViewClass="MyView" tagName="ul"}}'), <add> template: templateFor('{{each view.people itemViewClass=MyView tagName="ul"}}'), <ide> people: people <ide> }); <ide> <ide><path>packages/ember-handlebars/tests/helpers/view_test.js <ide> test("View lookup - App.FuView (DEPRECATED)", function() { <ide> equal(jQuery('#fu').text(), 'bro'); <ide> }); <ide> <del>test("View lookup - 'App.FuView' (DEPRECATED)", function() { <del> Ember.lookup = { <del> App: { <del> FuView: viewClass({ <del> elementId: "fu", <del> template: Ember.Handlebars.compile("bro") <del> }) <del> } <del> }; <del> <del> view = viewClass({ <del> template: Ember.Handlebars.compile("{{view 'App.FuView'}}") <del> }).create(); <del> <del> expectDeprecation(function(){ <del> run(view, 'appendTo', '#qunit-fixture'); <del> }, /Resolved the view "App.FuView" on the global context/); <del> <del> equal(jQuery('#fu').text(), 'bro'); <del>}); <del> <ide> test("View lookup - 'fu'", function() { <ide> var FuView = viewClass({ <ide> elementId: "fu", <ide> test("allows you to pass attributes that will be assigned to the class instance, <ide> ok(jQuery('#bar').hasClass('bar')); <ide> equal(jQuery('#bar').text(), 'Bar'); <ide> }); <add> <ide> test("Should apply class without condition always", function() { <ide> view = EmberView.create({ <ide> context: [], <ide> test("Should apply class without condition always", function() { <ide> run(view, 'appendTo', '#qunit-fixture'); <ide> <ide> ok(jQuery('#foo').hasClass('foo'), "Always applies classbinding without condition"); <del> <ide> }); <ide><path>packages/ember-handlebars/tests/helpers/with_test.js <ide> test("nested {{with}} blocks shadow the outer scoped variable properly.", functi <ide> <ide> equal(view.$().text(), "Limbo-Wrath-Treachery-Wrath-Limbo", "should be properly scoped after updating"); <ide> }); <add> <ide> QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", { <ide> setup: function() { <ide> Ember.lookup = lookup = { Ember: Ember }; <ide> QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", { <ide> view = EmberView.create({ <ide> template: EmberHandlebars.compile("{{#with Foo.bar as qux}}{{qux}}{{/with}}") <ide> }); <del> <del> ignoreDeprecation(function() { <del> appendView(view); <del> }); <ide> }, <ide> <ide> teardown: function() { <ide> QUnit.module("Handlebars {{#with}} globals helper [DEPRECATED]", { <ide> }); <ide> <ide> test("it should support #with Foo.bar as qux [DEPRECATED]", function() { <del> equal(view.$().text(), "baz", "should be properly scoped"); <del> <ide> expectDeprecation(function() { <del> run(function() { <del> set(lookup.Foo, 'bar', 'updated'); <del> }); <add> appendView(view); <ide> }, /Global lookup of Foo.bar from a Handlebars template is deprecated/); <ide> <add> equal(view.$().text(), "baz", "should be properly scoped"); <add> <add> run(function() { <add> set(lookup.Foo, 'bar', 'updated'); <add> }); <add> <ide> equal(view.$().text(), "updated", "should update"); <ide> }); <ide> <ide><path>packages/ember-handlebars/tests/lookup_test.js <del>QUnit.module("Ember.Handlebars.resolveParams"); <del> <del>test("Raw string parameters should be returned as Strings", function() { <del> var params = Ember.Handlebars.resolveParams({}, ["foo", "bar", "baz"], { types: ["STRING", "STRING", "STRING"] }); <del> deepEqual(params, ["foo", "bar", "baz"]); <del>}); <del> <del>test("Raw boolean parameters should be returned as Booleans", function() { <del> var params = Ember.Handlebars.resolveParams({}, [true, false], { types: ["BOOLEAN", "BOOLEAN"] }); <del> deepEqual(params, [true, false]); <del>}); <del> <del>test("Raw numeric parameters should be returned as Numbers", function() { <del> var params = Ember.Handlebars.resolveParams({}, [1, 1.0, 1.5, 0.5], { types: ["NUMBER", "NUMBER", "NUMBER", "NUMBER"] }); <del> deepEqual(params, [1, 1, 1.5, 0.5]); <del>}); <del> <del>test("ID parameters should be looked up on the context", function() { <del> var context = { <del> salutation: "Mr", <del> name: { <del> first: "Tom", <del> last: "Dale" <del> } <del> }; <del> <del> var params = Ember.Handlebars.resolveParams(context, ["salutation", "name.first", "name.last"], { types: ["ID", "ID", "ID"] }); <del> deepEqual(params, ["Mr", "Tom", "Dale"]); <del>}); <del> <del>test("ID parameters that start with capital letters fall back to Ember.lookup as their context (DEPRECATED)", function() { <del> Ember.lookup.Global = "I'm going global, what you ain't a local?"; <del> <del> var context = {}, params; <del> <del> expectDeprecation(function(){ <del> params = Ember.Handlebars.resolveParams(context, ["Global"], { types: ["ID"] }); <del> }, /Global lookup of Global from a Handlebars template is deprecated./); <del> deepEqual(params, [Ember.lookup.Global]); <del>}); <del> <del>test("ID parameters that start with capital letters look up on given context first", function() { <del> Ember.lookup.Global = "I'm going global, what you ain't a local?"; <del> <del> var context = { Global: "Steal away from lookup" }; <del> <del> var params = Ember.Handlebars.resolveParams(context, ["Global"], { types: ["ID"] }); <del> deepEqual(params, [context.Global]); <del>}); <del> <del>test("ID parameters can look up keywords", function() { <del> var controller = { <del> salutation: "Mr" <del> }; <del> <del> var view = { <del> name: { first: "Tom", last: "Dale" } <del> }; <del> <del> var context = { <del> yuno: "State Charts" <del> }; <del> <del> var options = { <del> types: ["ID", "ID", "ID", "ID"], <del> data: { <del> keywords: { <del> controller: controller, <del> view: view <del> } <del> } <del> }; <del> <del> var params = Ember.Handlebars.resolveParams(context, ["controller.salutation", "view.name.first", "view.name.last", "yuno"], options); <del> deepEqual(params, ["Mr", "Tom", "Dale", "State Charts"]); <del>}); <del> <del>QUnit.module("Ember.Handlebars.resolveHash"); <del> <del>test("Raw string parameters should be returned as Strings", function() { <del> var hash = Ember.Handlebars.resolveHash({}, { string: "foo" }, { hashTypes: { string: "STRING" } }); <del> deepEqual(hash, { string: "foo" }); <del>}); <del> <del>test("Raw boolean parameters should be returned as Booleans", function() { <del> var hash = Ember.Handlebars.resolveHash({}, { yes: true, no: false }, { hashTypes: { yes: "BOOLEAN", no: "BOOLEAN" } }); <del> deepEqual(hash, { yes: true, no: false }); <del>}); <del> <del>test("Raw numeric parameters should be returned as Numbers", function() { <del> var hash = Ember.Handlebars.resolveHash({}, { one: 1, oneFive: 1.5, ohFive: 0.5 }, { hashTypes: { one: "NUMBER", oneFive: "NUMBER", ohFive: "NUMBER" } }); <del> deepEqual(hash, { one: 1, oneFive: 1.5, ohFive: 0.5 }); <del>}); <del> <del>test("ID parameters should be looked up on the context", function() { <del> var context = { <del> salutation: "Mr", <del> name: { <del> first: "Tom", <del> last: "Dale" <del> } <del> }; <del> <del> var hash = Ember.Handlebars.resolveHash(context, { mr: "salutation", firstName: "name.first", lastName: "name.last" }, { hashTypes: { mr: "ID", firstName: "ID", lastName: "ID" } }); <del> deepEqual(hash, { mr: "Mr", firstName: "Tom", lastName: "Dale" }); <del>}); <del> <del>test("ID parameters can look up keywords", function() { <del> var controller = { <del> salutation: "Mr" <del> }; <del> <del> var view = { <del> name: { first: "Tom", last: "Dale" } <del> }; <del> <del> var context = { <del> yuno: "State Charts" <del> }; <del> <del> var options = { <del> hashTypes: { mr: "ID", firstName: "ID", lastName: "ID", yuno: "ID" }, <del> data: { <del> keywords: { <del> controller: controller, <del> view: view <del> } <del> } <del> }; <del> <del> var hash = Ember.Handlebars.resolveHash(context, { mr: "controller.salutation", firstName: "view.name.first", lastName: "view.name.last", yuno: "yuno" }, options); <del> deepEqual(hash, { mr: "Mr", firstName: "Tom", lastName: "Dale", yuno: "State Charts" }); <del>}); <ide><path>packages/ember-handlebars/tests/views/collection_view_test.js <ide> test("should give its item views the property specified by itemPropertyBinding", <ide> equal(view.$('ul li:first').text(), "yobaz", "change property of sub view"); <ide> }); <ide> <add>test("should unsubscribe stream bindings", function() { <add> view = EmberView.create({ <add> baz: "baz", <add> content: A([EmberObject.create(), EmberObject.create(), EmberObject.create()]), <add> template: EmberHandlebars.compile('{{#collection contentBinding="view.content" itemPropertyBinding="view.baz"}}{{view.property}}{{/collection}}') <add> }); <add> <add> run(function() { <add> view.appendTo('#qunit-fixture'); <add> }); <add> <add> var barStreamBinding = view._streamBindings['view.baz']; <add> <add> equal(barStreamBinding.subscribers.length, 3*2, "adds 3 subscribers"); <add> <add> run(function() { <add> view.get('content').popObject(); <add> }); <add> <add> equal(barStreamBinding.subscribers.length, 2*2, "removes 1 subscriber"); <add>}); <add> <ide> test("should work inside a bound {{#if}}", function() { <ide> var testData = A([EmberObject.create({ isBaz: false }), EmberObject.create({ isBaz: true }), EmberObject.create({ isBaz: true })]); <ide> var IfTestCollectionView = CollectionView.extend({ <ide><path>packages/ember-handlebars/tests/views/handlebars_bound_view_test.js <add>import Stream from "ember-metal/streams/stream"; <ide> import { SimpleHandlebarsView } from 'ember-handlebars/views/handlebars_bound_view'; <ide> <ide> QUnit.module('SimpleHandlebarsView'); <ide> <ide> test('does not render if update is triggured by normalizedValue is the same as the previous normalizedValue', function(){ <ide> var value = null; <del> var path = 'foo'; <del> var pathRoot = { 'foo': 'bar' }; <add> var obj = { 'foo': 'bar' }; <add> var lazyValue = new Stream(function() { <add> return obj.foo; <add> }); <ide> var isEscaped = true; <del> var templateData; <del> var view = new SimpleHandlebarsView(path, pathRoot, isEscaped, templateData); <add> var view = new SimpleHandlebarsView(lazyValue, isEscaped); <ide> view._morph = { <ide> update: function(newValue) { <ide> value = newValue; <ide> test('does not render if update is triggured by normalizedValue is the same as t <ide> <ide> equal(value, null, 'expected no call to morph.update'); <ide> <del> pathRoot.foo = 'baz'; // change property <add> obj.foo = 'baz'; // change property <add> lazyValue.notify(); <ide> <ide> view.update(); <ide> <ide><path>packages/ember-handlebars/tests/views/metamorph_view_test.js <ide> test("a metamorph view calls its childrens' willInsertElement and didInsertEleme <ide> } <ide> }), <ide> <del> template: EmberHandlebars.compile('{{#if view.condition}}{{view "view.ViewWithCallback"}}{{/if}}'), <add> template: EmberHandlebars.compile('{{#if view.condition}}{{view view.ViewWithCallback}}{{/if}}'), <ide> condition: false <ide> }); <ide> <ide><path>packages/ember-metal/lib/mixin.js <ide> import { <ide> import { <ide> create as o_create <ide> } from "ember-metal/platform"; <add>import { get } from "ember-metal/property_get"; <add>import { set, trySet } from "ember-metal/property_set"; <ide> import { <ide> guidFor, <ide> meta as metaFor, <ide> import { <ide> addObserver, <ide> removeObserver, <ide> addBeforeObserver, <del> removeBeforeObserver <add> removeBeforeObserver, <add> _suspendObserver <ide> } from "ember-metal/observer"; <ide> import { <ide> addListener, <ide> function detectBinding(obj, key, value, m) { <ide> } <ide> } <ide> <add>function connectStreamBinding(obj, key, stream) { <add> var onNotify = function(stream) { <add> _suspendObserver(obj, key, null, didChange, function() { <add> trySet(obj, key, stream.value()); <add> }); <add> }; <add> <add> var didChange = function() { <add> stream.setValue(get(obj, key), onNotify); <add> }; <add> <add> // Initialize value <add> set(obj, key, stream.value()); <add> <add> addObserver(obj, key, null, didChange); <add> <add> stream.subscribe(onNotify); <add> <add> if (obj._streamBindingSubscriptions === undefined) { <add> obj._streamBindingSubscriptions = Object.create(null); <add> } <add> <add> obj._streamBindingSubscriptions[key] = onNotify; <add>} <add> <ide> function connectBindings(obj, m) { <ide> // TODO Mixin.apply(instance) should disconnect binding if exists <ide> var bindings = m.bindings; <ide> function connectBindings(obj, m) { <ide> binding = bindings[key]; <ide> if (binding) { <ide> to = key.slice(0, -7); // strip Binding off end <del> if (binding instanceof Binding) { <add> if (binding.isStream) { <add> connectStreamBinding(obj, to, binding); <add> continue; <add> } else if (binding instanceof Binding) { <ide> binding = binding.copy(); // copy prototypes' instance <ide> binding.to(to); <ide> } else { // binding is string path <ide><path>packages/ember-metal/lib/path_cache.js <ide> var IS_GLOBAL = /^([A-Z$]|([0-9][A-Z$]))/; <ide> var IS_GLOBAL_PATH = /^([A-Z$]|([0-9][A-Z$])).*[\.]/; <ide> var HAS_THIS = 'this.'; <ide> <del>var isGlobalCache = new Cache(1000, function(key) { return IS_GLOBAL.test(key); }); <del>var isGlobalPathCache = new Cache(1000, function(key) { return IS_GLOBAL_PATH.test(key); }); <del>var hasThisCache = new Cache(1000, function(key) { return key.indexOf(HAS_THIS) !== -1; }); <del>var isPathCache = new Cache(1000, function(key) { return key.indexOf('.') !== -1; }); <add>var isGlobalCache = new Cache(1000, function(key) { return IS_GLOBAL.test(key); }); <add>var isGlobalPathCache = new Cache(1000, function(key) { return IS_GLOBAL_PATH.test(key); }); <add>var hasThisCache = new Cache(1000, function(key) { return key.indexOf(HAS_THIS) !== -1; }); <add>var firstDotIndexCache = new Cache(1000, function(key) { return key.indexOf('.'); }); <add> <add>var firstKeyCache = new Cache(1000, function(path) { <add> var index = firstDotIndexCache.get(path); <add> if (index === -1) { <add> return path; <add> } else { <add> return path.slice(0, index); <add> } <add>}); <add> <add>var tailPathCache = new Cache(1000, function(path) { <add> var index = firstDotIndexCache.get(path); <add> if (index !== -1) { <add> return path.slice(index + 1); <add> } <add>}); <ide> <ide> export var caches = { <del> isGlobalCache: isGlobalCache, <del> isGlobalPathCache: isGlobalPathCache, <del> hasThisCache: hasThisCache, <del> isPathCache: isPathCache <add> isGlobalCache: isGlobalCache, <add> isGlobalPathCache: isGlobalPathCache, <add> hasThisCache: hasThisCache, <add> firstDotIndexCache: firstDotIndexCache, <add> firstKeyCache: firstKeyCache, <add> tailPathCache: tailPathCache <ide> }; <ide> <ide> export function isGlobal(path) { <ide> export function hasThis(path) { <ide> } <ide> <ide> export function isPath(path) { <del> return isPathCache.get(path); <add> return firstDotIndexCache.get(path) !== -1; <add>} <add> <add>export function getFirstKey(path) { <add> return firstKeyCache.get(path); <add>} <add> <add>export function getTailPath(path) { <add> return tailPathCache.get(path); <ide> } <ide><path>packages/ember-metal/lib/streams/read.js <add>export function read(object) { <add> if (object && object.isStream) { <add> return object.value(); <add> } else { <add> return object; <add> } <add>} <add> <add>export function readArray(array) { <add> var length = array.length; <add> var ret = new Array(length); <add> for (var i = 0; i < length; i++) { <add> ret[i] = read(array[i]); <add> } <add> return ret; <add>} <add> <add>export function readHash(object) { <add> var ret = {}; <add> for (var key in object) { <add> ret[key] = read(object[key]); <add> } <add> return ret; <add>} <ide><path>packages/ember-metal/lib/streams/simple.js <add>import merge from "ember-metal/merge"; <add>import Stream from "ember-metal/streams/stream"; <add>import { create } from "ember-metal/platform"; <add>import { read } from "ember-metal/streams/read"; <add> <add>function SimpleStream(source) { <add> this.source = source; <add> <add> if (source && source.isStream) { <add> source.subscribe(this._didChange, this); <add> } <add>} <add> <add>SimpleStream.prototype = create(Stream.prototype); <add> <add>merge(SimpleStream.prototype, { <add> valueFn: function() { <add> return read(this.source); <add> }, <add> <add> setSource: function(nextSource) { <add> var prevSource = this.source; <add> if (nextSource !== prevSource) { <add> if (prevSource && prevSource.isStream) { <add> prevSource.unsubscribe(this._didChange, this); <add> } <add> <add> if (nextSource && nextSource.isStream) { <add> nextSource.subscribe(this._didChange, this); <add> } <add> <add> this.source = nextSource; <add> this.notify(); <add> } <add> }, <add> <add> _didChange: function() { <add> this.notify(); <add> }, <add> <add> destroy: function() { <add> if (this.source && this.source.isStream) { <add> this.source.unsubscribe(this._didChange, this); <add> } <add> <add> this.source = undefined; <add> Stream.prototype.destroy.call(this); <add> } <add>}); <add> <add>export default SimpleStream; <ide><path>packages/ember-metal/lib/streams/stream.js <add>import { <add> getFirstKey, <add> getTailPath <add>} from "ember-metal/path_cache"; <add> <add>var NIL = function NIL(){}; <add> <add>function Stream(fn) { <add> this.valueFn = fn; <add> this.cache = NIL; <add> this.subscribers = undefined; <add> this.children = undefined; <add> this.destroyed = false; <add>} <add> <add>Stream.prototype = { <add> isStream: true, <add> <add> cache: NIL, <add> <add> get: function(path) { <add> var firstKey = getFirstKey(path); <add> var tailPath = getTailPath(path); <add> <add> if (this.children === undefined) { <add> this.children = Object.create(null); <add> } <add> <add> var keyStream = this.children[firstKey]; <add> <add> if (keyStream === undefined) { <add> keyStream = this._makeChildStream(firstKey, path); <add> this.children[firstKey] = keyStream; <add> } <add> <add> if (tailPath === undefined) { <add> return keyStream; <add> } else { <add> return keyStream.get(tailPath); <add> } <add> }, <add> <add> value: function() { <add> if (this.cache !== NIL) { <add> return this.cache; <add> } else { <add> return this.cache = this.valueFn(); <add> } <add> }, <add> <add> setValue: function() { <add> throw new Error("Stream error: setValue not implemented"); <add> }, <add> <add> notifyAll: function() { <add> this.notify(); <add> }, <add> <add> notify: function(callbackToSkip, contextToSkip) { <add> if (this.cache !== NIL) { <add> this.cache = NIL; <add> this.notifySubscribers(callbackToSkip, contextToSkip); <add> } <add> }, <add> <add> subscribe: function(callback, context) { <add> if (this.subscribers === undefined) { <add> this.subscribers = [callback, context]; <add> } else { <add> this.subscribers.push(callback, context); <add> } <add> }, <add> <add> unsubscribe: function(callback, context) { <add> var subscribers = this.subscribers; <add> <add> if (subscribers !== undefined) { <add> for (var i = 0, l = subscribers.length; i < l; i += 2) { <add> if (subscribers[i] === callback && subscribers[i+1] === context) { <add> subscribers.splice(i, 2); <add> return; <add> } <add> } <add> } <add> }, <add> <add> notifySubscribers: function(callbackToSkip, contextToSkip) { <add> var subscribers = this.subscribers; <add> <add> if (subscribers !== undefined) { <add> for (var i = 0, l = subscribers.length; i < l; i += 2) { <add> var callback = subscribers[i]; <add> var context = subscribers[i+1]; <add> <add> if (callback === callbackToSkip && context === contextToSkip) { <add> continue; <add> } <add> <add> if (context === undefined) { <add> callback(this); <add> } else { <add> callback.call(context, this); <add> } <add> } <add> } <add> }, <add> <add> destroy: function() { <add> if (this.destroyed) return; <add> this.destroyed = true; <add> <add> var children = this.children; <add> for (var key in children) { <add> children[key].destroy(); <add> } <add> }, <add> <add> isGlobal: function() { <add> var stream = this; <add> while (stream !== undefined) { <add> if (stream._isRoot) { <add> return stream._isGlobal; <add> } <add> stream = stream.source; <add> } <add> } <add>}; <add> <add>export default Stream; <ide><path>packages/ember-metal/lib/streams/stream_binding.js <add>import { create } from "ember-metal/platform"; <add>import merge from "ember-metal/merge"; <add>import run from "ember-metal/run_loop"; <add>import Stream from "ember-metal/streams/stream"; <add> <add>function StreamBinding(stream) { <add> Ember.assert("StreamBinding error: tried to bind to object that is not a stream", stream && stream.isStream); <add> <add> this.stream = stream; <add> this.senderCallback = undefined; <add> this.senderContext = undefined; <add> this.senderValue = undefined; <add> this.destroyed = false; <add> <add> stream.subscribe(this._onNotify, this); <add>} <add> <add>StreamBinding.prototype = create(Stream.prototype); <add> <add>merge(StreamBinding.prototype, { <add> valueFn: function() { <add> return this.stream.value(); <add> }, <add> <add> _onNotify: function() { <add> this._scheduleSync(undefined, undefined, this); <add> }, <add> <add> setValue: function(value, callback, context) { <add> this._scheduleSync(value, callback, context); <add> }, <add> <add> _scheduleSync: function(value, callback, context) { <add> if (this.senderCallback === undefined && this.senderContext === undefined) { <add> this.senderCallback = callback; <add> this.senderContext = context; <add> this.senderValue = value; <add> run.schedule('sync', this, this._sync); <add> } else if (this.senderContext !== this) { <add> this.senderCallback = callback; <add> this.senderContext = context; <add> this.senderValue = value; <add> } <add> }, <add> <add> _sync: function() { <add> if (this.destroyed) { <add> return; <add> } <add> <add> if (this.senderContext !== this) { <add> this.stream.setValue(this.senderValue); <add> } <add> <add> var senderCallback = this.senderCallback; <add> var senderContext = this.senderContext; <add> this.senderCallback = undefined; <add> this.senderContext = undefined; <add> this.senderValue = undefined; <add> <add> this.notify(senderCallback, senderContext); <add> }, <add> <add> destroy: function() { <add> if (this.destroyed) { <add> return; <add> } <add> <add> this.destroyed = true; <add> this.stream.unsubscribe(this._onNotify, this); <add> } <add>}); <add> <add>export default StreamBinding; <ide><path>packages/ember-metal/tests/streams/stream_binding_test.js <add>import { get } from "ember-metal/property_get"; <add>import { set } from "ember-metal/property_set"; <add>import { mixin } from "ember-metal/mixin"; <add>import run from 'ember-metal/run_loop'; <add>import Stream from "ember-metal/streams/stream"; <add>import StreamBinding from "ember-metal/streams/stream_binding"; <add> <add>var source, value; <add> <add>QUnit.module('Stream Binding', { <add> setup: function() { <add> value = "zlurp"; <add> <add> source = new Stream(function() { <add> return value; <add> }); <add> <add> source.setValue = function(_value, callback, context) { <add> value = _value; <add> this.notify(callback, context); <add> }; <add> }, <add> teardown: function() { <add> value = undefined; <add> source = undefined; <add> } <add>}); <add> <add>test('basic', function() { <add> var binding = new StreamBinding(source); <add> <add> equal(binding.value(), "zlurp"); <add> <add> run(function() { <add> source.setValue("blorg"); <add> }); <add> <add> equal(binding.value(), "blorg"); <add> <add> binding.destroy(); // destroy should not fail <add>}); <add> <add>test('the source stream can send values to a single subscriber)', function() { <add> var binding = new StreamBinding(source); <add> var obj = mixin({}, { toBinding: binding }); <add> <add> equal(get(obj, 'to'), "zlurp", "immediately syncs value forward on init"); <add> <add> run(function() { <add> source.setValue("blorg"); <add> equal(get(obj, 'to'), "zlurp", "does not immediately sync value on set"); <add> }); <add> <add> equal(get(obj, 'to'), "blorg", "value has synced after run loop"); <add>}); <add> <add>test('the source stream can send values to multiple subscribers', function() { <add> var binding = new StreamBinding(source); <add> var obj1 = mixin({}, { toBinding: binding }); <add> var obj2 = mixin({}, { toBinding: binding }); <add> <add> equal(get(obj1, 'to'), "zlurp", "immediately syncs value forward on init"); <add> equal(get(obj2, 'to'), "zlurp", "immediately syncs value forward on init"); <add> <add> run(function() { <add> source.setValue("blorg"); <add> equal(get(obj1, 'to'), "zlurp", "does not immediately sync value on set"); <add> equal(get(obj2, 'to'), "zlurp", "does not immediately sync value on set"); <add> }); <add> <add> equal(get(obj1, 'to'), "blorg", "value has synced after run loop"); <add> equal(get(obj2, 'to'), "blorg", "value has synced after run loop"); <add>}); <add> <add>test('a subscriber can set the value on the source stream and notify the other subscribers', function() { <add> var binding = new StreamBinding(source); <add> var obj1 = mixin({}, { toBinding: binding }); <add> var obj2 = mixin({}, { toBinding: binding }); <add> <add> run(function() { <add> set(obj1, 'to', "blorg"); <add> equal(get(obj2, 'to'), "zlurp", "does not immediately sync value on set"); <add> equal(source.value(), "zlurp", "does not immediately sync value on set"); <add> }); <add> <add> equal(get(obj2, 'to'), "blorg", "value has synced after run loop"); <add> equal(source.value(), "blorg", "value has synced after run loop"); <add>}); <add> <add>test('if source and subscribers sync value, source wins', function() { <add> var binding = new StreamBinding(source); <add> var obj1 = mixin({}, { toBinding: binding }); <add> var obj2 = mixin({}, { toBinding: binding }); <add> var obj3 = mixin({}, { toBinding: binding }); <add> <add> run(function() { <add> set(obj1, 'to', "blorg"); <add> source.setValue("hoopla"); <add> set(obj2, 'to', "flarp"); <add> equal(get(obj3, 'to'), "zlurp", "does not immediately sync value on set"); <add> }); <add> <add> equal(source.value(), "hoopla", "value has synced after run loop"); <add> equal(get(obj1, 'to'), "hoopla", "value has synced after run loop"); <add> equal(get(obj2, 'to'), "hoopla", "value has synced after run loop"); <add> equal(get(obj3, 'to'), "hoopla", "value has synced after run loop"); <add>}); <add> <add>test('the last value sent by the source wins', function() { <add> var binding = new StreamBinding(source); <add> var obj = mixin({}, { toBinding: binding }); <add> <add> run(function() { <add> source.setValue("blorg"); <add> source.setValue("hoopla"); <add> equal(get(obj, 'to'), "zlurp", "does not immediately sync value on set"); <add> }); <add> <add> equal(source.value(), "hoopla", "value has synced after run loop"); <add> equal(get(obj, 'to'), "hoopla", "value has synced after run loop"); <add>}); <ide><path>packages/ember-routing-handlebars/lib/helpers/action.js <ide> import { forEach } from "ember-metal/array"; <ide> import { uuid } from "ember-metal/utils"; <ide> import run from "ember-metal/run_loop"; <ide> <add>import { readUnwrappedModel } from "ember-views/streams/read"; <ide> import { isSimpleClick } from "ember-views/system/utils"; <ide> import ActionManager from "ember-views/system/action_manager"; <del> <ide> import EmberHandlebars from "ember-handlebars"; <del>import { handlebarsGet } from "ember-handlebars/ext"; <del>import { <del> resolveParams <del>} from "ember-routing-handlebars/helpers/shared"; <ide> <ide> /** <ide> @module ember <ide> @submodule ember-routing <ide> */ <ide> <del>var a_slice = Array.prototype.slice; <del> <del>function args(options, actionName) { <del> var ret = []; <del> if (actionName) { ret.push(actionName); } <add>function actionArgs(parameters, actionName) { <add> var ret, i; <ide> <del> var types = options.options.types.slice(1); <del> var data = options.options.data; <add> if (actionName === undefined) { <add> ret = new Array(parameters.length); <add> for (i = 0; i < parameters.length; 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; i < parameters.length; i++) { <add> ret[i + 1] = readUnwrappedModel(parameters[i]); <add> } <add> } <ide> <del> return ret.concat(resolveParams(options.context, options.params, { types: types, data: data })); <add> return ret; <ide> } <ide> <ide> var ActionHelper = {}; <ide> function ignoreKeyEvent(eventName, event, keyCode) { <ide> return isKeyEvent(eventName) && keyCode !== any && keyCode !== event.which.toString(); <ide> } <ide> <del>ActionHelper.registerAction = function(actionNameOrPath, options, allowedKeys) { <add>ActionHelper.registerAction = function(actionNameOrStream, options, allowedKeys) { <ide> var actionId = uuid(); <add> var eventName = options.eventName; <add> var parameters = options.parameters; <ide> <ide> ActionManager.registeredActions[actionId] = { <del> eventName: options.eventName, <add> eventName: eventName, <ide> handler: function handleRegisteredAction(event) { <ide> if (!isAllowedEvent(event, allowedKeys)) { return true; } <ide> <ide> ActionHelper.registerAction = function(actionNameOrPath, options, allowedKeys) { <ide> event.stopPropagation(); <ide> } <ide> <del> var target = options.target; <del> var parameters = options.parameters; <del> var eventName = options.eventName; <del> var actionName; <add> var target = options.target.value(); <ide> <ide> if (Ember.FEATURES.isEnabled("ember-routing-handlebars-action-with-key-code")) { <ide> if (ignoreKeyEvent(eventName, event, options.withKeyCode)) { <ide> return; <ide> } <ide> } <ide> <del> if (target.target) { <del> target = handlebarsGet(target.root, target.target, target.options); <del> } else { <del> target = target.root; <del> } <add> var actionName; <ide> <del> if (options.boundProperty) { <del> actionName = resolveParams(parameters.context, [actionNameOrPath], { types: ['ID'], data: parameters.options.data })[0]; <add> if (actionNameOrStream.isStream) { <add> actionName = actionNameOrStream.value(); <ide> <ide> if (typeof actionName === 'undefined' || typeof actionName === 'function') { <add> actionName = actionNameOrStream._originalPath; <ide> Ember.deprecate("You specified a quoteless path to the {{action}} helper '" + <del> actionNameOrPath + "' which did not resolve to an actionName." + <del> " Perhaps you meant to use a quoted actionName? (e.g. {{action '" + actionNameOrPath + "'}})."); <del> actionName = actionNameOrPath; <add> actionName + "' which did not resolve to an actionName." + <add> " Perhaps you meant to use a quoted actionName? (e.g. {{action '" + actionName + "'}})."); <ide> } <ide> } <ide> <ide> if (!actionName) { <del> actionName = actionNameOrPath; <add> actionName = actionNameOrStream; <ide> } <ide> <ide> run(function runRegisteredAction() { <ide> if (target.send) { <del> target.send.apply(target, args(parameters, actionName)); <add> target.send.apply(target, actionArgs(parameters, actionName)); <ide> } else { <ide> Ember.assert("The action '" + actionName + "' did not exist on " + target, typeof target[actionName] === 'function'); <del> target[actionName].apply(target, args(parameters)); <add> target[actionName].apply(target, actionArgs(parameters)); <ide> } <ide> }); <ide> } <ide> ActionHelper.registerAction = function(actionNameOrPath, options, allowedKeys) { <ide> @param {Hash} options <ide> */ <ide> export function actionHelper(actionName) { <del> var options = arguments[arguments.length - 1]; <del> var contexts = a_slice.call(arguments, 1, -1); <add> var length = arguments.length; <add> var options = arguments[length - 1]; <add> var view = options.data.view; <ide> var hash = options.hash; <del> var controller = options.data.keywords.controller; <add> var types = options.types; <ide> <ide> // create a hash to pass along to registerAction <del> var action = { <add> var parameters = []; <add> <add> var actionOptions = { <ide> eventName: hash.on || "click", <del> parameters: { <del> context: this, <del> options: options, <del> params: contexts <del> }, <add> parameters: parameters, <ide> view: options.data.view, <ide> bubbles: hash.bubbles, <ide> preventDefault: hash.preventDefault, <del> target: { options: options }, <del> withKeyCode: hash.withKeyCode, <del> boundProperty: options.types[0] === "ID" <add> target: view.getStream(hash.target || 'controller'), <add> withKeyCode: hash.withKeyCode <ide> }; <ide> <del> if (hash.target) { <del> action.target.root = this; <del> action.target.target = hash.target; <del> } else if (controller) { <del> action.target.root = controller; <add> var actionNameStream; <add> <add> if (types[0] === "ID") { <add> actionNameStream = view.getStream(actionName); <add> actionNameStream._originalPath = actionName; <add> } else { <add> actionNameStream = actionName; <add> } <add> <add> for (var i = 1; i < length - 1; i++) { <add> if (types[i] === "ID") { <add> parameters.push(view.getStream(arguments[i])); <add> } else { <add> parameters.push(arguments[i]); <add> } <ide> } <ide> <del> var actionId = ActionHelper.registerAction(actionName, action, hash.allowedKeys); <add> var actionId = ActionHelper.registerAction(actionNameStream, actionOptions, hash.allowedKeys); <ide> return new EmberHandlebars.SafeString('data-ember-action="' + actionId + '"'); <ide> } <ide><path>packages/ember-routing-handlebars/lib/helpers/link_to.js <ide> import { computed } from "ember-metal/computed"; <ide> <ide> import { fmt } from "ember-runtime/system/string"; <ide> import EmberObject from "ember-runtime/system/object"; <add>import ControllerMixin from "ember-runtime/mixins/controller"; <ide> import keys from "ember-metal/keys"; <ide> import { isSimpleClick } from "ember-views/system/utils"; <ide> import EmberComponent from "ember-views/views/component"; <del>import EmberHandlebars from "ember-handlebars"; <ide> import { viewHelper } from "ember-handlebars/helpers/view"; <ide> import { routeArgs } from "ember-routing/utils"; <del>import { <del> resolveParams, <del> resolvePaths <del>} from "ember-routing-handlebars/helpers/shared"; <add>import { stringifyValue } from "ember-handlebars/ext"; <add>import { read } from "ember-metal/streams/read"; <ide> <ide> import 'ember-handlebars'; <ide> <ide> var QueryParams = EmberObject.extend({ <ide> values: null <ide> }); <ide> <del>function getResolvedPaths(options) { <del> <del> var types = options.options.types; <del> var data = options.options.data; <del> <del> return resolvePaths(options.context, options.params, { types: types, data: data }); <del>} <del> <ide> /** <ide> `Ember.LinkView` renders an element whose `click` event triggers a <ide> transition of the application's instance of `Ember.Router` to <ide> var LinkView = Ember.LinkView = EmberComponent.extend({ <ide> @since 1.3.0 <ide> **/ <ide> _setupPathObservers: function(){ <del> var helperParameters = this.parameters; <del> var linkTextPath = helperParameters.options.linkTextPath; <del> var paths = getResolvedPaths(helperParameters); <del> var length = paths.length; <del> var path, i, normalizedPath; <del> <del> if (linkTextPath) { <del> normalizedPath = getNormalizedPath(linkTextPath, helperParameters); <del> this.registerObserver(normalizedPath.root, normalizedPath.path, this, this.rerender); <add> var params = this.params; <add> <add> var scheduledRerender = this._wrapAsScheduled(this.rerender); <add> var scheduledParamsChanged = this._wrapAsScheduled(this._paramsChanged); <add> <add> if (this.linkTitle) { <add> this.linkTitle.subscribe(scheduledRerender, this); <ide> } <ide> <del> for(i=0; i < length; i++) { <del> path = paths[i]; <del> if (null === path) { <del> // A literal value was provided, not a path, so nothing to observe. <del> continue; <add> for (var i = 0; i < params.length; i++) { <add> var param = params[i]; <add> if (param && param.isStream) { <add> param.subscribe(scheduledParamsChanged, this); <ide> } <del> <del> normalizedPath = getNormalizedPath(path, helperParameters); <del> this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); <ide> } <ide> <ide> var queryParamsObject = this.queryParamsObject; <ide> if (queryParamsObject) { <ide> var values = queryParamsObject.values; <del> <del> // Install observers for all of the hash options <del> // provided in the (query-params) subexpression. <ide> for (var k in values) { <del> if (!values.hasOwnProperty(k)) { continue; } <add> if (!values.hasOwnProperty(k)) { <add> continue; <add> } <ide> <del> if (queryParamsObject.types[k] === 'ID') { <del> normalizedPath = getNormalizedPath(values[k], helperParameters); <del> this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); <add> var value = values[k]; <add> if (value && value.isStream) { <add> value.subscribe(scheduledParamsChanged, this); <ide> } <ide> } <ide> } <ide> var LinkView = Ember.LinkView = EmberComponent.extend({ <ide> @return {Array} <ide> */ <ide> resolvedParams: computed('router.url', function() { <del> var parameters = this.parameters; <del> var options = parameters.options; <del> var types = options.types; <del> var data = options.data; <del> var targetRouteName, models; <del> var onlyQueryParamsSupplied = (parameters.params.length === 0); <add> var params = this.params; <add> var targetRouteName; <add> var models = []; <add> var onlyQueryParamsSupplied = (params.length === 0); <ide> <ide> if (onlyQueryParamsSupplied) { <ide> var appController = this.container.lookup('controller:application'); <ide> targetRouteName = get(appController, 'currentRouteName'); <del> models = []; <ide> } else { <del> models = resolveParams(parameters.context, parameters.params, { types: types, data: data }); <del> targetRouteName = models.shift(); <add> targetRouteName = read(params[0]); <add> <add> for (var i = 1; i < params.length; i++) { <add> models.push(read(params[i])); <add> } <ide> } <ide> <ide> var suppliedQueryParams = getResolvedQueryParams(this, targetRouteName); <ide> if (Ember.FEATURES.isEnabled("ember-routing-linkto-target-attribute")) { <ide> function linkToHelper(name) { <ide> var options = slice.call(arguments, -1)[0]; <ide> var params = slice.call(arguments, 0, -1); <add> var view = options.data.view; <ide> var hash = options.hash; <add> var hashTypes = options.hashTypes; <add> var types = options.types; <add> var shouldEscape = !hash.unescaped; <add> var queryParamsObject; <ide> <ide> Ember.assert("You must provide one or more parameters to the link-to helper.", params.length); <ide> <ide> if (params[params.length - 1] instanceof QueryParams) { <del> hash.queryParamsObject = params.pop(); <add> hash.queryParamsObject = queryParamsObject = params.pop(); <ide> } <ide> <del> hash.disabledBinding = hash.disabledWhen; <add> if (hash.disabledWhen) { <add> hash.disabledBinding = hash.disabledWhen; <add> hashTypes.disabledBinding = hashTypes.disabledWhen; <add> delete hash.disabledWhen; <add> delete hashTypes.disabledWhen; <add> } <ide> <ide> if (!options.fn) { <ide> var linkTitle = params.shift(); <del> var linkType = options.types.shift(); <del> var context = this; <del> if (linkType === 'ID') { <del> options.linkTextPath = linkTitle; <add> var linkTitleType = types.shift(); <add> if (linkTitleType === 'ID') { <add> hash.linkTitle = linkTitle = view.getStream(linkTitle); <ide> options.fn = function() { <del> return EmberHandlebars.getEscaped(context, linkTitle, options); <add> return stringifyValue(linkTitle.value(), shouldEscape); <ide> }; <ide> } else { <ide> options.fn = function() { <ide> function linkToHelper(name) { <ide> } <ide> } <ide> <del> hash.parameters = { <del> context: this, <del> options: options, <del> params: params <del> }; <add> // Setup route & param streams <add> for (var i = 0; i < params.length; i++) { <add> var paramPath = params[i]; <add> if (types[i] === 'ID') { <add> var lazyValue = view.getStream(paramPath); <add> <add> // TODO: Consider a better approach to unwrapping controllers. <add> if (paramPath !== 'controller') { <add> while (ControllerMixin.detect(lazyValue.value())) { <add> paramPath = (paramPath === '') ? 'model' : paramPath + '.model'; <add> lazyValue = view.getStream(paramPath); <add> } <add> } <add> params[i] = lazyValue; <add> } <add> } <add> <add> hash.params = params; <ide> <ide> options.helperName = options.helperName || 'link-to'; <ide> <ide> function linkToHelper(name) { <ide> export function queryParamsHelper(options) { <ide> Ember.assert(fmt("The `query-params` helper only accepts hash parameters, e.g. (query-params queryParamPropertyName='%@') as opposed to just (query-params '%@')", [options, options]), arguments.length === 1); <ide> <add> var view = options.data.view; <add> var hash = options.hash; <add> var hashTypes = options.hashTypes; <add> <add> for (var k in hash) { <add> if (hashTypes[k] === 'ID') { <add> hash[k] = view.getStream(hash[k]); <add> } <add> } <add> <ide> return QueryParams.create({ <del> values: options.hash, <del> types: options.hashTypes <add> values: options.hash <ide> }); <ide> } <ide> <ide> function deprecatedLinkToHelper() { <ide> } <ide> <ide> function getResolvedQueryParams(linkView, targetRouteName) { <del> var helperParameters = linkView.parameters; <ide> var queryParamsObject = linkView.queryParamsObject; <ide> var resolvedQueryParams = {}; <ide> <ide> if (!queryParamsObject) { return resolvedQueryParams; } <del> var rawParams = queryParamsObject.values; <del> <del> for (var key in rawParams) { <del> if (!rawParams.hasOwnProperty(key)) { continue; } <ide> <del> var value = rawParams[key]; <del> var type = queryParamsObject.types[key]; <del> <del> if (type === 'ID') { <del> var normalizedPath = getNormalizedPath(value, helperParameters); <del> value = EmberHandlebars.get(normalizedPath.root, normalizedPath.path, helperParameters.options); <del> } <del> resolvedQueryParams[key] = value; <add> var values = queryParamsObject.values; <add> for (var key in values) { <add> if (!values.hasOwnProperty(key)) { continue; } <add> resolvedQueryParams[key] = read(values[key]); <ide> } <del> return resolvedQueryParams; <del>} <ide> <del>function getNormalizedPath(path, helperParameters) { <del> return EmberHandlebars.normalizePath(helperParameters.context, path, helperParameters.options.data); <add> return resolvedQueryParams; <ide> } <ide> <ide> function paramsAreLoaded(params) { <ide><path>packages/ember-routing-handlebars/lib/helpers/outlet.js <ide> import Ember from "ember-metal/core"; // assert <add>import { set } from "ember-metal/property_set"; <ide> import ContainerView from "ember-views/views/container_view"; <ide> import { _Metamorph } from "ember-handlebars/views/metamorph_view"; <ide> import { viewHelper } from "ember-handlebars/helpers/view"; <ide> export { OutletView }; <ide> */ <ide> export function outletHelper(property, options) { <ide> var outletSource; <del> var container; <ide> var viewName; <ide> var viewClass; <ide> var viewFullName; <ide> export function outletHelper(property, options) { <ide> property = 'main'; <ide> } <ide> <del> container = options.data.view.container; <add> var view = options.data.view; <add> var container = view.container; <ide> <del> outletSource = options.data.view; <add> outletSource = view; <ide> while (!outletSource.get('template.isTop')) { <ide> outletSource = outletSource.get('_parentView'); <ide> } <add> set(view, 'outletSource', outletSource); <ide> <ide> // provide controller override <ide> viewName = options.hash.view; <ide> export function outletHelper(property, options) { <ide> } <ide> <ide> viewClass = viewName ? container.lookupFactory(viewFullName) : options.hash.viewClass || OutletView; <add> options.types = [ 'ID' ]; <ide> <del> options.hash.outletSource = outletSource; <ide> options.hash.currentViewBinding = '_view.outletSource._outlets.' + property; <add> options.hashTypes.currentViewBinding = 'STRING'; <ide> <ide> options.helperName = options.helperName || 'outlet'; <ide> <ide><path>packages/ember-routing-handlebars/lib/helpers/render.js <ide> import { <ide> generateControllerFactory, <ide> default as generateController <ide> } from "ember-routing/system/generate_controller"; <del>import { handlebarsGet } from "ember-handlebars/ext"; <ide> import { ViewHelper } from "ember-handlebars/helpers/view"; <ide> <ide> /** <ide> You could render it inside the `post` template using the `render` helper. <ide> */ <ide> export default function renderHelper(name, contextString, options) { <ide> var length = arguments.length; <del> var container, router, controller, view, context; <add> var container, router, controller, view, initialContext; <ide> <del> container = (options || contextString).data.keywords.controller.container; <add> container = (options || contextString).data.view._keywords.controller.value().container; <ide> router = container.lookup('router:main'); <ide> <ide> if (length === 2) { <ide> export default function renderHelper(name, contextString, options) { <ide> " second argument, as in {{render \"post\" post}}.", !router || !router._lookupActiveView(name)); <ide> } else if (length === 3) { <ide> // create a new controller <del> context = handlebarsGet(options.contexts[1], contextString, options); <add> initialContext = options.data.view.getStream(contextString).value(); <ide> } else { <ide> throw new EmberError("You must pass a templateName to render"); <ide> } <ide> export default function renderHelper(name, contextString, options) { <ide> "' did not resolve to a controller.", container.has(controllerFullName)); <ide> } <ide> <del> var parentController = options.data.keywords.controller; <add> var parentController = options.data.view._keywords.controller.value(); <ide> <ide> // choose name <ide> if (length > 2) { <ide> var factory = container.lookupFactory(controllerFullName) || <del> generateControllerFactory(container, controllerName, context); <add> generateControllerFactory(container, controllerName, initialContext); <ide> <ide> controller = factory.create({ <del> model: context, <add> modelBinding: options.data.view._getBindingForStream(contextString), <ide> parentController: parentController, <ide> target: parentController <ide> }); <ide> export default function renderHelper(name, contextString, options) { <ide> }); <ide> } <ide> <del> var root = options.contexts[1]; <del> <del> if (root) { <del> view.registerObserver(root, contextString, function() { <del> controller.set('model', handlebarsGet(root, contextString, options)); <del> }); <del> } <del> <ide> options.hash.viewName = camelize(name); <ide> <ide> var templateName = 'template:' + name; <ide> export default function renderHelper(name, contextString, options) { <ide> <ide> options.hash.controller = controller; <ide> <del> if (router && !context) { <add> if (router && !initialContext) { <ide> router._connectActiveView(name, view); <ide> } <ide> <ide><path>packages/ember-routing-handlebars/lib/helpers/shared.js <del>import { get } from "ember-metal/property_get"; <del>import { map } from "ember-metal/array"; <del>import ControllerMixin from "ember-runtime/mixins/controller"; <del>import { <del> resolveParams as handlebarsResolve, <del> handlebarsGet <del>} from "ember-handlebars/ext"; <del> <del>export function resolveParams(context, params, options) { <del> return map.call(resolvePaths(context, params, options), function(path, i) { <del> if (null === path) { <del> // Param was string/number, not a path, so just return raw string/number. <del> return params[i]; <del> } else { <del> return handlebarsGet(context, path, options); <del> } <del> }); <del>} <del> <del>export function resolvePaths(context, params, options) { <del> var resolved = handlebarsResolve(context, params, options); <del> var types = options.types; <del> <del> return map.call(resolved, function(object, i) { <del> if (types[i] === 'ID') { <del> return unwrap(object, params[i]); <del> } else { <del> return null; <del> } <del> }); <del> <del> function unwrap(object, path) { <del> if (path === 'controller') { return path; } <del> <del> if (ControllerMixin.detect(object)) { <del> return unwrap(get(object, 'model'), path ? path + '.model' : 'model'); <del> } else { <del> return path; <del> } <del> } <del>} <ide><path>packages/ember-routing-handlebars/lib/main.js <ide> Ember Routing Handlebars <ide> <ide> import Ember from "ember-metal/core"; <ide> import EmberHandlebars from "ember-handlebars"; <del>import Router from "ember-routing/system/router"; <del> <del>import { <del> resolvePaths, <del> resolveParams <del>} from "ember-routing-handlebars/helpers/shared"; <ide> <ide> import { <ide> deprecatedLinkToHelper, <ide> import { <ide> actionHelper <ide> } from "ember-routing-handlebars/helpers/action"; <ide> <del>Router.resolveParams = resolveParams; <del>Router.resolvePaths = resolvePaths; <del> <ide> Ember.LinkView = LinkView; <ide> EmberHandlebars.ActionHelper = ActionHelper; <ide> EmberHandlebars.OutletView = OutletView; <ide><path>packages/ember-routing-handlebars/tests/helpers/action_test.js <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> <del>import "ember-routing-handlebars/helpers/shared"; <ide> import { <ide> ActionHelper, <ide> actionHelper <ide> test("should by default target the view's controller", function() { <ide> var controller = {}; <ide> <ide> ActionHelper.registerAction = function(actionName, options) { <del> registeredTarget = options.target; <add> registeredTarget = options.target.value(); <ide> }; <ide> <ide> view = EmberView.create({ <ide> test("should by default target the view's controller", function() { <ide> <ide> appendView(); <ide> <del> equal(registeredTarget.root, controller, "The controller was registered as the target"); <add> equal(registeredTarget, controller, "The controller was registered as the target"); <ide> <ide> ActionHelper.registerAction = originalRegisterAction; <ide> }); <ide> test("should target the current controller inside an {{each}} loop", function() <ide> var registeredTarget; <ide> <ide> ActionHelper.registerAction = function(actionName, options) { <del> registeredTarget = options.target; <add> registeredTarget = options.target.value(); <ide> }; <ide> <ide> var itemController = EmberObjectController.create(); <ide> test("should target the current controller inside an {{each}} loop", function() <ide> <ide> appendView(); <ide> <del> equal(registeredTarget.root, itemController, "the item controller is the target of action"); <add> equal(registeredTarget, itemController, "the item controller is the target of action"); <ide> <ide> ActionHelper.registerAction = originalRegisterAction; <ide> }); <ide> test("should target the with-controller inside an {{#with controller='person'}}" <ide> var registeredTarget; <ide> <ide> ActionHelper.registerAction = function(actionName, options) { <del> registeredTarget = options.target; <add> registeredTarget = options.target.value(); <ide> }; <ide> <ide> var PersonController = EmberObjectController.extend(); <ide> test("should target the with-controller inside an {{#with controller='person'}}" <ide> <ide> appendView(); <ide> <del> ok(registeredTarget.root instanceof PersonController, "the with-controller is the target of action"); <add> ok(registeredTarget instanceof PersonController, "the with-controller is the target of action"); <ide> <ide> ActionHelper.registerAction = originalRegisterAction; <ide> }); <ide> test("should allow a target to be specified", function() { <ide> var registeredTarget; <ide> <ide> ActionHelper.registerAction = function(actionName, options) { <del> registeredTarget = options.target; <add> registeredTarget = options.target.value(); <ide> }; <ide> <ide> var anotherTarget = EmberView.create(); <ide> test("should allow a target to be specified", function() { <ide> <ide> appendView(); <ide> <del> equal(registeredTarget.options.data.keywords.view, view, "The specified target was registered"); <del> equal(registeredTarget.target, 'view.anotherTarget', "The specified target was registered"); <add> equal(registeredTarget, anotherTarget, "The specified target was registered"); <ide> <ide> ActionHelper.registerAction = originalRegisterAction; <ide> <ide> test("should lazily evaluate the target", function() { <ide> <ide> equal(firstEdit, 1); <ide> <del> set(controller, 'theTarget', second); <add> run(function() { <add> set(controller, 'theTarget', second); <add> }); <ide> <ide> run(function() { <ide> jQuery('a').trigger('click'); <ide> test("should unwrap controllers passed as a context", function() { <ide> equal(passedContext, model, "the action was passed the unwrapped model"); <ide> }); <ide> <add>test("should not unwrap controllers passed as `controller`", function() { <add> var passedContext; <add> var model = EmberObject.create(); <add> var controller = EmberObjectController.extend({ <add> model: model, <add> actions: { <add> edit: function(context) { <add> passedContext = context; <add> } <add> } <add> }).create(); <add> <add> view = EmberView.create({ <add> controller: controller, <add> template: EmberHandlebars.compile('<button {{action "edit" controller}}>edit</button>') <add> }); <add> <add> appendView(); <add> <add> view.$('button').trigger('click'); <add> <add> equal(passedContext, controller, "the action was passed the controller"); <add>}); <add> <ide> test("should allow multiple contexts to be specified", function() { <ide> var passedContexts; <ide> var models = [EmberObject.create(), EmberObject.create()]; <ide> test("a quoteless parameter should allow dynamic lookup of the actionName", func <ide> }); <ide> <ide> var testBoundAction = function(propertyValue){ <del> controller.set('hookMeUp', propertyValue); <add> run(function() { <add> controller.set('hookMeUp', propertyValue); <add> }); <ide> <ide> run(function(){ <ide> view.$("#woot-bound-param").click(); <ide><path>packages/ember-views/lib/streams/context_stream.js <add>import Ember from 'ember-metal/core'; <add> <add>import merge from "ember-metal/merge"; <add>import { create } from "ember-metal/platform"; <add>import { isGlobal } from "ember-metal/path_cache"; <add>import Stream from "ember-metal/streams/stream"; <add>import SimpleStream from "ember-metal/streams/simple"; <add> <add>function ContextStream(view) { <add> Ember.assert("ContextStream error: the argument is not a view", view && view.isView); <add> this.view = view; <add>} <add> <add>ContextStream.prototype = create(Stream.prototype); <add> <add>merge(ContextStream.prototype, { <add> value: function() {}, <add> <add> _makeChildStream: function(key, _fullPath) { <add> var stream; <add> <add> if (key === '' || key === 'this') { <add> stream = this.view._baseContext; <add> } else if (isGlobal(key) && Ember.lookup[key]) { <add> Ember.deprecate("Global lookup of " + _fullPath + " from a Handlebars template is deprecated."); <add> stream = new SimpleStream(Ember.lookup[key]); <add> stream._isGlobal = true; <add> } else if (key in this.view._keywords) { <add> stream = new SimpleStream(this.view._keywords[key]); <add> } else { <add> stream = new SimpleStream(this.view._baseContext.get(key)); <add> } <add> <add> stream._isRoot = true; <add> <add> if (key === 'controller') { <add> stream._isController = true; <add> } <add> <add> return stream; <add> } <add>}); <add> <add>export default ContextStream; <ide><path>packages/ember-views/lib/streams/key_stream.js <add>import Ember from 'ember-metal/core'; <add> <add>import merge from "ember-metal/merge"; <add>import { create } from "ember-metal/platform"; <add>import { get } from "ember-metal/property_get"; <add>import { set } from "ember-metal/property_set"; <add>import { <add> addObserver, <add> removeObserver <add>} from "ember-metal/observer"; <add>import Stream from "ember-metal/streams/stream"; <add>import { read } from "ember-metal/streams/read"; <add> <add>function KeyStream(source, key) { <add> Ember.assert("KeyStream error: key must be a non-empty string", typeof key === 'string' && key.length > 0); <add> Ember.assert("KeyStream error: key must not have a '.'", key.indexOf('.') === -1); <add> <add> this.source = source; <add> this.obj = undefined; <add> this.key = key; <add> <add> if (source && source.isStream) { <add> source.subscribe(this._didChange, this); <add> } <add>} <add> <add>KeyStream.prototype = create(Stream.prototype); <add> <add>merge(KeyStream.prototype, { <add> valueFn: function() { <add> var prevObj = this.obj; <add> var nextObj = read(this.source); <add> <add> if (nextObj !== prevObj) { <add> if (prevObj && typeof prevObj === 'object') { <add> removeObserver(prevObj, this.key, this, this._didChange); <add> } <add> <add> if (nextObj && typeof nextObj === 'object') { <add> addObserver(nextObj, this.key, this, this._didChange); <add> } <add> <add> this.obj = nextObj; <add> } <add> <add> if (nextObj) { <add> return get(nextObj, this.key); <add> } <add> }, <add> <add> setValue: function(value) { <add> if (this.obj) { <add> set(this.obj, this.key, value); <add> } <add> }, <add> <add> setSource: function(nextSource) { <add> Ember.assert("KeyStream error: source must be an object", typeof nextSource === 'object'); <add> <add> var prevSource = this.source; <add> <add> if (nextSource !== prevSource) { <add> if (prevSource && prevSource.isStream) { <add> prevSource.unsubscribe(this._didChange, this); <add> } <add> <add> if (nextSource && nextSource.isStream) { <add> nextSource.subscribe(this._didChange, this); <add> } <add> <add> this.source = nextSource; <add> this.notify(); <add> } <add> }, <add> <add> _didChange: function() { <add> this.notify(); <add> }, <add> <add> destroy: function() { <add> if (this.source && this.source.isStream) { <add> this.source.unsubscribe(this._didChange, this); <add> } <add> <add> if (this.obj && typeof this.obj === 'object') { <add> removeObserver(this.obj, this.key, this, this._didChange); <add> } <add> <add> this.source = undefined; <add> this.obj = undefined; <add> <add> Stream.prototype.destroy.call(this); <add> } <add>}); <add> <add>export default KeyStream; <add> <add>// The transpiler does not resolve cycles, so we export <add>// the `_makeChildStream` method onto `Stream` here. <add> <add>Stream.prototype._makeChildStream = function(key) { <add> return new KeyStream(this, key); <add>}; <ide><path>packages/ember-views/lib/streams/read.js <add>import Ember from "ember-metal/core"; <add>import { get } from "ember-metal/property_get"; <add>import { isGlobal } from "ember-metal/path_cache"; <add>import { fmt } from "ember-runtime/system/string"; <add>import { read } from "ember-metal/streams/read"; <add>import View from "ember-views/views/view"; <add>import ControllerMixin from "ember-runtime/mixins/controller"; <add> <add>export function readViewFactory(object, container) { <add> var value = read(object); <add> var viewClass; <add> <add> if (typeof value === 'string') { <add> if (isGlobal(value)) { <add> viewClass = get(null, value); <add> Ember.deprecate('Resolved the view "'+value+'" on the global context. Pass a view name to be looked up on the container instead, such as {{view "select"}}. http://emberjs.com/guides/deprecations#toc_global-lookup-of-views-since-1-8', !viewClass); <add> } else { <add> Ember.assert("View requires a container to resolve views not passed in through the context", !!container); <add> viewClass = container.lookupFactory('view:'+value); <add> } <add> } else { <add> viewClass = value; <add> } <add> <add> Ember.assert(fmt(value+" must be a subclass of Ember.View, not %@", [viewClass]), View.detect(viewClass)); <add> <add> return viewClass; <add>} <add> <add>export function readUnwrappedModel(object) { <add> if (object && object.isStream) { <add> var result = object.value(); <add> <add> // If the path is exactly `controller` then we don't unwrap it. <add> if (!object._isController) { <add> while (ControllerMixin.detect(result)) { <add> result = get(result, 'model'); <add> } <add> } <add> <add> return result; <add> } else { <add> return object; <add> } <add>} <ide><path>packages/ember-views/lib/views/collection_view.js <ide> import { <ide> observer, <ide> beforeObserver <ide> } from "ember-metal/mixin"; <del>import { <del> handlebarsGetView <del>} from "ember-handlebars/ext"; <add>import { readViewFactory } from "ember-views/streams/read"; <ide> import EmberArray from "ember-runtime/mixins/array"; <ide> <ide> /** <ide> var CollectionView = ContainerView.extend({ <ide> <ide> if (len) { <ide> itemViewClass = get(this, 'itemViewClass'); <del> itemViewClass = handlebarsGetView(content, itemViewClass, this.container); <add> itemViewClass = readViewFactory(itemViewClass, this.container); <ide> <ide> for (idx = start; idx < start+added; idx++) { <ide> item = content.objectAt(idx); <ide><path>packages/ember-views/lib/views/component.js <ide> var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, { <ide> <ide> init: function() { <ide> this._super(); <del> set(this, 'origContext', get(this, 'context')); <ide> set(this, 'context', this); <ide> set(this, 'controller', this); <ide> }, <ide> var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, { <ide> */ <ide> templateName: null, <ide> <del> // during render, isolate keywords <del> cloneKeywords: function() { <del> return { <del> view: this, <del> controller: this <del> }; <add> _setupKeywords: function() { <add> this._keywords.view.setSource(this); <ide> }, <ide> <ide> _yield: function(context, options) { <ide> var Component = View.extend(TargetActionSupport, ComponentTemplateDeprecation, { <ide> tagName: '', <ide> _contextView: parentView, <ide> template: template, <del> context: options.data.insideGroup ? get(this, 'origContext') : get(parentView, 'context'), <add> context: get(parentView, 'context'), <ide> controller: get(parentView, 'controller'), <del> templateData: { keywords: parentView.cloneKeywords(), insideGroup: options.data.insideGroup } <add> templateData: { keywords: {} } <ide> }); <ide> } <ide> }, <ide><path>packages/ember-views/lib/views/container_view.js <ide> merge(states.inBuffer, { <ide> merge(states.hasElement, { <ide> childViewsWillChange: function(view, views, start, removed) { <ide> for (var i=start; i<start+removed; i++) { <del> views[i].remove(); <add> var _view = views[i]; <add> _view._unsubscribeFromStreamBindings(); <add> _view.remove(); <ide> } <ide> }, <ide> <ide><path>packages/ember-views/lib/views/view.js <ide> import { set } from "ember-metal/property_set"; <ide> import setProperties from "ember-metal/set_properties"; <ide> import run from "ember-metal/run_loop"; <ide> import { addObserver, removeObserver } from "ember-metal/observer"; <del> <ide> import { defineProperty } from "ember-metal/properties"; <ide> import { guidFor } from "ember-metal/utils"; <ide> import { computed } from "ember-metal/computed"; <ide> import { observer } from "ember-metal/mixin"; <add>import SimpleStream from "ember-metal/streams/simple"; <add>import KeyStream from "ember-views/streams/key_stream"; <add>import StreamBinding from "ember-metal/streams/stream_binding"; <add>import ContextStream from "ember-views/streams/context_stream"; <ide> <ide> import { <ide> typeOf, <ide> import { <ide> } from "ember-metal/enumerable_utils"; <ide> <ide> import { beforeObserver } from "ember-metal/mixin"; <del>import copy from "ember-runtime/copy"; <del>import { isGlobalPath } from "ember-metal/binding"; <ide> <ide> import { <ide> propertyWillChange, <ide> import "ember-views/system/ext"; // for the side effect of extending Ember.run. <ide> <ide> import CoreView from "ember-views/views/core_view"; <ide> <add> <ide> /** <ide> @module ember <ide> @submodule ember-views <ide> var View = CoreView.extend({ <ide> _parentViewDidChange: observer('_parentView', function() { <ide> if (this.isDestroying) { return; } <ide> <add> this._setupKeywords(); <ide> this.trigger('parentViewDidChange'); <ide> <ide> if (get(this, 'parentView.controller') && !get(this, 'controller')) { <ide> var View = CoreView.extend({ <ide> }); <ide> }), <ide> <del> cloneKeywords: function() { <del> var templateData = get(this, 'templateData'); <add> _setupKeywords: function() { <add> var keywords = this._keywords; <add> var contextView = this._contextView || this._parentView; <add> <add> if (contextView) { <add> var parentKeywords = contextView._keywords; <ide> <del> var keywords = templateData ? copy(templateData.keywords) : {}; <del> set(keywords, 'view', this.isVirtual ? keywords.view : this); <del> set(keywords, 'controller', get(this, 'controller')); <add> keywords.view.setSource(this.isVirtual ? parentKeywords.view : this); <ide> <del> return keywords; <add> for (var name in parentKeywords) { <add> if (keywords[name]) continue; <add> keywords[name] = parentKeywords[name]; <add> } <add> } else { <add> keywords.view.setSource(this.isVirtual ? null : this); <add> } <ide> }, <ide> <ide> /** <ide> var View = CoreView.extend({ <ide> <ide> if (template) { <ide> var context = get(this, 'context'); <del> var keywords = this.cloneKeywords(); <ide> var output; <ide> <ide> var data = { <ide> view: this, <ide> buffer: buffer, <del> isRenderData: true, <del> keywords: keywords, <del> insideGroup: get(this, 'templateData.insideGroup') <add> isRenderData: true <ide> }; <ide> <ide> // Invoke the template with the provided template context, which <ide> var View = CoreView.extend({ <ide> // ('content.isUrgent') <ide> forEach(classBindings, function(binding) { <ide> <del> Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1); <add> var parsedPath; <add> <add> if (typeof binding === 'string') { <add> Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1); <add> parsedPath = View._parsePropertyPath(binding); <add> if (parsedPath.path === '') { <add> parsedPath.stream = new SimpleStream(true); <add> } else { <add> parsedPath.stream = this.getStream('_view.' + parsedPath.path); <add> } <add> } else { <add> parsedPath = binding; <add> } <ide> <ide> // Variable in which the old class value is saved. The observer function <ide> // closes over this variable, so it knows which string to remove when <ide> // the property changes. <ide> var oldClass; <del> // Extract just the property name from bindings like 'foo:bar' <del> var parsedPath = View._parsePropertyPath(binding); <ide> <ide> // Set up an observer on the context. If the property changes, toggle the <ide> // class name. <del> var observer = function() { <add> var observer = this._wrapAsScheduled(function() { <ide> // Get the current value of the property <del> newClass = this._classStringForProperty(binding); <add> newClass = this._classStringForProperty(parsedPath); <ide> elem = this.$(); <ide> <ide> // If we had previously added a class to the element, remove it. <ide> var View = CoreView.extend({ <ide> } else { <ide> oldClass = null; <ide> } <del> }; <add> }); <ide> <ide> // Get the class name for the property at its current value <del> dasherizedClass = this._classStringForProperty(binding); <add> dasherizedClass = this._classStringForProperty(parsedPath); <ide> <ide> if (dasherizedClass) { <ide> // Ensure that it gets into the classNames array <ide> var View = CoreView.extend({ <ide> oldClass = dasherizedClass; <ide> } <ide> <del> this.registerObserver(this, parsedPath.path, observer); <add> parsedPath.stream.subscribe(observer, this); <ide> // Remove className so when the view is rerendered, <ide> // the className is added based on binding reevaluation <ide> this.one('willClearRender', function() { <ide> var View = CoreView.extend({ <ide> @param property <ide> @private <ide> */ <del> _classStringForProperty: function(property) { <del> var parsedPath = View._parsePropertyPath(property); <del> var path = parsedPath.path; <del> <del> var val = get(this, path); <del> if (val === undefined && isGlobalPath(path)) { <del> val = get(Ember.lookup, path); <del> } <del> <del> return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); <add> _classStringForProperty: function(parsedPath) { <add> return View._classStringForValue(parsedPath.path, parsedPath.stream.value(), parsedPath.className, parsedPath.falsyClassName); <ide> }, <ide> <ide> // .......................................................... <ide> var View = CoreView.extend({ <ide> <ide> // setup child views. be sure to clone the child views array first <ide> this._childViews = this._childViews.slice(); <add> this._baseContext = undefined; <add> this._contextStream = undefined; <add> this._streamBindings = undefined; <add> <add> if (!this._keywords) { <add> this._keywords = Object.create(null); <add> } <add> this._keywords.view = new SimpleStream(); <add> this._keywords._view = this; <add> this._keywords.controller = new KeyStream(this, 'controller'); <add> this._setupKeywords(); <ide> <ide> Ember.assert("Only arrays are allowed for 'classNameBindings'", typeOf(this.classNameBindings) === 'array'); <ide> this.classNameBindings = emberA(this.classNameBindings.slice()); <ide> var View = CoreView.extend({ <ide> return; <ide> } <ide> <del> var view = this; <del> var stateCheckedObserver = function() { <del> view.currentState.invokeObserver(this, observer); <del> }; <del> var scheduledObserver = function() { <del> run.scheduleOnce('render', this, stateCheckedObserver); <del> }; <add> var scheduledObserver = this._wrapAsScheduled(observer); <ide> <ide> addObserver(root, path, target, scheduledObserver); <ide> <ide> this.one('willClearRender', function() { <ide> removeObserver(root, path, target, scheduledObserver); <ide> }); <del> } <add> }, <add> <add> _wrapAsScheduled: function(fn) { <add> var view = this; <add> var stateCheckedFn = function() { <add> view.currentState.invokeObserver(this, fn); <add> }; <add> var scheduledFn = function() { <add> run.scheduleOnce('render', this, stateCheckedFn); <add> }; <add> return scheduledFn; <add> }, <add> <add> getStream: function(path) { <add> return this._getContextStream().get(path); <add> }, <add> <add> _getBindingForStream: function(path) { <add> if (this._streamBindings === undefined) { <add> this._streamBindings = Object.create(null); <add> this.one('willDestroyElement', this, this._destroyStreamBindings); <add> } <add> <add> if (this._streamBindings[path] !== undefined) { <add> return this._streamBindings[path]; <add> } else { <add> var stream = this._getContextStream().get(path); <add> return this._streamBindings[path] = new StreamBinding(stream); <add> } <add> }, <ide> <add> _destroyStreamBindings: function() { <add> var streamBindings = this._streamBindings; <add> for (var path in streamBindings) { <add> streamBindings[path].destroy(); <add> } <add> this._streamBindings = undefined; <add> }, <add> <add> _getContextStream: function() { <add> if (this._contextStream === undefined) { <add> this._baseContext = new KeyStream(this, 'context'); <add> this._contextStream = new ContextStream(this); <add> this.one('willDestroyElement', this, this._destroyContextStream); <add> } <add> <add> return this._contextStream; <add> }, <add> <add> _destroyContextStream: function() { <add> this._baseContext.destroy(); <add> this._baseContext = undefined; <add> this._contextStream.destroy(); <add> this._contextStream = undefined; <add> }, <add> <add> _unsubscribeFromStreamBindings: function() { <add> for (var key in this._streamBindingSubscriptions) { <add> var streamBinding = this[key + 'Binding']; <add> var callback = this._streamBindingSubscriptions[key]; <add> streamBinding.unsubscribe(callback); <add> } <add> } <ide> }); <add> <ide> deprecateProperty(View.prototype, 'state', '_state'); <ide> deprecateProperty(View.prototype, 'states', '_states'); <ide> <ide> View.reopenClass({ <ide> } <ide> <ide> return { <add> stream: undefined, <ide> path: propertyPath, <ide> classNames: classNames, <ide> className: (className === '') ? undefined : className, <ide><path>packages/ember-views/tests/views/container_view_test.js <ide> test("if a ContainerView starts with a currentView, it is rendered as a child vi <ide> controller: controller <ide> }); <ide> var context = null; <del> var templateData = null; <ide> var mainView = View.create({ <ide> template: function(ctx, opts) { <ide> context = ctx; <del> templateData = opts.data; <ide> return "This is the main view."; <ide> } <ide> }); <ide> test("if a ContainerView starts with a currentView, it is rendered as a child vi <ide> equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); <ide> equal(mainView.get('parentView'), container, "parentView is setup"); <ide> equal(context, container.get('context'), 'context preserved'); <del> equal(templateData.keywords.controller, controller, 'templateData is setup'); <del> equal(templateData.keywords.view, mainView, 'templateData is setup'); <add> equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); <add> equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); <ide> }); <ide> <ide> test("if a ContainerView is created with a currentView, it is rendered as a child view", function() { <ide> var context = null; <del> var templateData = null; <ide> var mainView = View.create({ <ide> template: function(ctx, opts) { <ide> context = ctx; <del> templateData = opts.data; <ide> return "This is the main view."; <ide> } <ide> }); <ide> test("if a ContainerView is created with a currentView, it is rendered as a chil <ide> equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); <ide> equal(mainView.get('parentView'), container, "parentView is setup"); <ide> equal(context, container.get('context'), 'context preserved'); <del> equal(templateData.keywords.controller, controller, 'templateData is setup'); <del> equal(templateData.keywords.view, mainView, 'templateData is setup'); <add> equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); <add> equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); <ide> }); <ide> <ide> test("if a ContainerView starts with no currentView and then one is set, the ContainerView is updated", function() { <ide> var context = null; <del> var templateData = null; <ide> var mainView = View.create({ <ide> template: function(ctx, opts) { <ide> context = ctx; <del> templateData = opts.data; <ide> return "This is the main view."; <ide> } <ide> }); <ide> test("if a ContainerView starts with no currentView and then one is set, the Con <ide> equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); <ide> equal(mainView.get('parentView'), container, "parentView is setup"); <ide> equal(context, container.get('context'), 'context preserved'); <del> equal(templateData.keywords.controller, controller, 'templateData is setup'); <del> equal(templateData.keywords.view, mainView, 'templateData is setup'); <add> equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); <add> equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); <ide> }); <ide> <ide> test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated", function() { <ide> var context = null; <del> var templateData = null; <ide> var mainView = View.create({ <ide> template: function(ctx, opts) { <ide> context = ctx; <del> templateData = opts.data; <ide> return "This is the main view."; <ide> } <ide> }); <ide> test("if a ContainerView starts with a currentView and then is set to null, the <ide> equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); <ide> equal(mainView.get('parentView'), container, "parentView is setup"); <ide> equal(context, container.get('context'), 'context preserved'); <del> equal(templateData.keywords.controller, controller, 'templateData is setup'); <del> equal(templateData.keywords.view, mainView, 'templateData is setup'); <add> equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); <add> equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); <ide> <ide> run(function() { <ide> set(container, 'currentView', null); <ide> test("if a ContainerView starts with a currentView and then is set to null, the <ide> <ide> test("if a ContainerView starts with a currentView and then is set to null, the ContainerView is updated and the previous currentView is destroyed", function() { <ide> var context = null; <del> var templateData = null; <ide> var mainView = View.create({ <ide> template: function(ctx, opts) { <ide> context = ctx; <del> templateData = opts.data; <ide> return "This is the main view."; <ide> } <ide> }); <ide> test("if a ContainerView starts with a currentView and then is set to null, the <ide> equal(container.objectAt(0), mainView, "should have the currentView as the only child view"); <ide> equal(mainView.get('parentView'), container, "parentView is setup"); <ide> equal(context, container.get('context'), 'context preserved'); <del> equal(templateData.keywords.controller, controller, 'templateData is setup'); <del> equal(templateData.keywords.view, mainView, 'templateData is setup'); <add> equal(mainView._keywords.controller.value(), controller, 'controller keyword is setup'); <add> equal(mainView._keywords.view.value(), mainView, 'view keyword is setup'); <ide> <ide> run(function() { <ide> set(container, 'currentView', null); <ide><path>packages/ember-views/tests/views/view/template_test.js <ide> test("should provide a controller to the template if a controller is specified o <ide> controller: controller1, <ide> <ide> template: function(buffer, options) { <del> optionsDataKeywordsControllerForView = options.data.keywords.controller; <add> optionsDataKeywordsControllerForView = options.data.view._keywords.controller.value(); <ide> } <ide> }); <ide> <ide> test("should provide a controller to the template if a controller is specified o <ide> templateData: options.data, <ide> template: function(context, options) { <ide> contextForView = context; <del> optionsDataKeywordsControllerForChildView = options.data.keywords.controller; <add> optionsDataKeywordsControllerForChildView = options.data.view._keywords.controller.value(); <ide> } <ide> })); <del> optionsDataKeywordsControllerForView = options.data.keywords.controller; <add> optionsDataKeywordsControllerForView = options.data.view._keywords.controller.value(); <ide> } <ide> }); <ide> <ide> test("should provide a controller to the template if a controller is specified o <ide> templateData: options.data, <ide> template: function(context, options) { <ide> contextForControllerlessView = context; <del> optionsDataKeywordsControllerForChildView = options.data.keywords.controller; <add> optionsDataKeywordsControllerForChildView = options.data.view._keywords.controller.value(); <ide> } <ide> })); <del> optionsDataKeywordsControllerForView = options.data.keywords.controller; <add> optionsDataKeywordsControllerForView = options.data.view._keywords.controller.value(); <ide> } <ide> }); <ide>
44
Javascript
Javascript
remove unused argument
0f56cfdd13b86c1d98a08a90715850b34bb46fde
<ide><path>src/ng/http.js <ide> function $HttpProvider() { <ide> // strip json vulnerability protection prefix <ide> data = data.replace(PROTECTION_PREFIX, ''); <ide> if (JSON_START.test(data) && JSON_END.test(data)) <del> data = fromJson(data, true); <add> data = fromJson(data); <ide> } <ide> return data; <ide> }],
1
Text
Text
add missing grave accent
e243e33cb4a116a11ddf91916cf38c695da49763
<ide><path>guides/source/upgrading_ruby_on_rails.md <ide> it. <ide> Rails 5 adds the ability to run tasks and tests through `bin/rails` instead of rake. Generally <ide> these changes are in parallel with rake, but some were ported over altogether. As the `rails` <ide> command already looks for and runs `bin/rails`, we recommend you to use the shorter `rails` <del>over `bin/rails. <add>over `bin/rails`. <ide> <ide> To use the new test runner simply type `rails test`. <ide>
1
Ruby
Ruby
increase fail log lines, allow config
9aecb1be2b89843c66852ad11ba6c22ef10d2e64
<ide><path>Library/Homebrew/formula.rb <ide> def system(cmd, *args) <ide> $stdout.flush <ide> <ide> unless $?.success? <add> log_lines = ENV["HOMEBREW_FAIL_LOG_LINES"] <add> log_lines ||= "15" <add> <ide> log.flush <del> Kernel.system "/usr/bin/tail", "-n", "5", logfn unless verbose <add> unless verbose <add> puts "Last #{log_lines} lines from #{logfn}:" <add> Kernel.system "/usr/bin/tail", "-n", log_lines, logfn <add> end <ide> log.puts <ide> <ide> require "cmd/config"
1
Python
Python
add cyme to intersphinx
650c3c419f432498d6e9f9b0681f29bec6d04848
<ide><path>docs/conf.py <ide> "http://docs.python.org/dev": None, <ide> "http://kombu.readthedocs.org/en/latest/": None, <ide> "http://django-celery.readthedocs.org/en/latest": None, <add> "http://cyme.readthedocs.org/en/latest": None, <ide> } <ide> <ide> # The name of the Pygments (syntax highlighting) style to use. <ide> <ide> ### Issuetracker <ide> <del>if True: <add>if False: <ide> issuetracker = "github" <ide> issuetracker_project = "celery/celery" <ide> issuetracker_issue_pattern = r'[Ii]ssue #(\d+)'
1
Ruby
Ruby
add formula check for crufy sourceforge urls
3c47f7918b47377732a26445b27566a226e85831
<ide><path>Library/Homebrew/test/formula_test.rb <ide> def test_for_misquoted_prefix <ide> assert_equal('', result, "--prefix is incorrectly single-quoted in #{f}") <ide> end <ide> end <add> <add> def test_for_crufy_sourceforge_url <add> # Don't specify mirror for SourceForge downloads <add> Formulary.paths.each do |f| <add> result = `grep "\?use_mirror=" "#{f}"`.strip <add> assert_equal('', result, "Remove 'use_mirror' from url for #{f}") <add> end <add> end <ide> end
1
Javascript
Javascript
change modulegraph storage to weakmap
224ed2ac0ce8f1a8dae571fd5efe63b5e3bdca3c
<ide><path>lib/ModuleGraph.js <ide> class ModuleGraphModule { <ide> <ide> class ModuleGraph { <ide> constructor() { <del> /** @type {Map<Dependency, ModuleGraphConnection>} */ <del> this._dependencyMap = new Map(); <add> /** @type {WeakMap<Dependency, ModuleGraphConnection>} */ <add> this._dependencyMap = new WeakMap(); <ide> /** @type {Map<Module, ModuleGraphModule>} */ <ide> this._moduleMap = new Map(); <del> /** @type {Map<Module, Set<ModuleGraphConnection>>} */ <del> this._originMap = new Map(); <del> /** @type {Map<any, Object>} */ <del> this._metaMap = new Map(); <add> /** @type {WeakMap<any, Object>} */ <add> this._metaMap = new WeakMap(); <ide> <ide> // Caching <ide> this._cacheModuleGraphModuleKey1 = undefined;
1
Javascript
Javascript
add hascrypto check to common flags check
2a02b9df6ef35b34b7d93cf8408ce53fb2f66b53
<ide><path>test/common/index.js <ide> const { <ide> <ide> const noop = () => {}; <ide> <add>const hasCrypto = Boolean(process.versions.openssl); <add> <ide> const isMainThread = (() => { <ide> try { <ide> return require('worker_threads').isMainThread; <ide> if (process.argv.length === 2 && <ide> const args = process.execArgv.map((arg) => arg.replace(/_/g, '-')); <ide> for (const flag of flags) { <ide> if (!args.includes(flag) && <add> // If the binary was built without-ssl then the crypto flags are <add> // invalid (bad option). The test itself should handle this case. <add> hasCrypto && <ide> // If the binary is build without `intl` the inspect option is <ide> // invalid. The test itself should handle this case. <ide> (process.config.variables.v8_enable_inspector !== 0 || <ide> const rootDir = isWindows ? 'c:\\' : '/'; <ide> <ide> const buildType = process.config.target_defaults.default_configuration; <ide> <del>const hasCrypto = Boolean(process.versions.openssl); <ide> <ide> // If env var is set then enable async_hook hooks for all tests. <ide> if (process.env.NODE_TEST_WITH_ASYNC_HOOKS) {
1
Python
Python
add tests for oauth authentication
1062d71f8be929f1f7e6910a8d573ac643082bae
<ide><path>rest_framework/tests/authentication.py <ide> from django.contrib.auth.models import User <ide> from django.http import HttpResponse <ide> from django.test import Client, TestCase <del>from rest_framework import HTTP_HEADER_ENCODING <add>import time <add>from rest_framework import HTTP_HEADER_ENCODING, status <ide> from rest_framework import permissions <ide> from rest_framework.authtoken.models import Token <del>from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication <add>from rest_framework.authentication import TokenAuthentication, BasicAuthentication, SessionAuthentication, OAuthAuthentication <ide> from rest_framework.compat import patterns <ide> from rest_framework.views import APIView <ide> import json <ide> import base64 <del> <add>from oauth_provider.models import Consumer, Resource <add>from oauth_provider.models import Token as OAuthToken <add>from oauth_provider import consts as oauth_consts <add>import oauth2 as oauth <ide> <ide> class MockView(APIView): <ide> permission_classes = (permissions.IsAuthenticated,) <ide> def post(self, request): <ide> def put(self, request): <ide> return HttpResponse({'a': 1, 'b': 2, 'c': 3}) <ide> <add> def get(self, request): <add> return HttpResponse({'a': 1, 'b': 2, 'c': 3}) <add> <ide> urlpatterns = patterns('', <ide> (r'^session/$', MockView.as_view(authentication_classes=[SessionAuthentication])), <ide> (r'^basic/$', MockView.as_view(authentication_classes=[BasicAuthentication])), <ide> (r'^token/$', MockView.as_view(authentication_classes=[TokenAuthentication])), <ide> (r'^auth-token/$', 'rest_framework.authtoken.views.obtain_auth_token'), <add> (r'^oauth/$', MockView.as_view(authentication_classes=[OAuthAuthentication])) <ide> ) <ide> <ide> <ide> def test_token_login_form(self): <ide> {'username': self.username, 'password': self.password}) <ide> self.assertEqual(response.status_code, 200) <ide> self.assertEqual(json.loads(response.content.decode('ascii'))['token'], self.key) <add> <add>class OAuthTests(TestCase): <add> """OAuth 1.0a authentication""" <add> urls = 'rest_framework.tests.authentication' <add> <add> def setUp(self): <add> self.csrf_client = Client(enforce_csrf_checks=True) <add> self.username = 'john' <add> self.email = 'lennon@thebeatles.com' <add> self.password = 'password' <add> self.user = User.objects.create_user(self.username, self.email, self.password) <add> <add> self.CONSUMER_KEY = 'consumer_key' <add> self.CONSUMER_SECRET = 'consumer_secret' <add> self.TOKEN_KEY = "token_key" <add> self.TOKEN_SECRET = "token_secret" <add> <add> self.consumer = Consumer.objects.create(key=self.CONSUMER_KEY, secret=self.CONSUMER_SECRET, <add> name='example', user=self.user, status=oauth_consts.ACCEPTED) <add> <add> <add> self.resource = Resource.objects.create(name="resource name", url="api/") <add> self.token = OAuthToken.objects.create(user=self.user, consumer=self.consumer, resource=self.resource, <add> token_type=OAuthToken.ACCESS, key=self.TOKEN_KEY, secret=self.TOKEN_SECRET, is_approved=True <add> ) <add> <add> <add> def _create_authorization_header(self): <add> params = { <add> 'oauth_version': "1.0", <add> 'oauth_nonce': oauth.generate_nonce(), <add> 'oauth_timestamp': int(time.time()), <add> 'oauth_token': self.token.key, <add> 'oauth_consumer_key': self.consumer.key <add> } <add> <add> req = oauth.Request(method="GET", url="http://example.com", parameters=params) <add> <add> signature_method = oauth.SignatureMethod_PLAINTEXT() <add> req.sign_request(signature_method, self.consumer, self.token) <add> <add> return req.to_header()["Authorization"] <add> <add> def _create_authorization_url_parameters(self): <add> params = { <add> 'oauth_version': "1.0", <add> 'oauth_nonce': oauth.generate_nonce(), <add> 'oauth_timestamp': int(time.time()), <add> 'oauth_token': self.token.key, <add> 'oauth_consumer_key': self.consumer.key <add> } <add> <add> req = oauth.Request(method="GET", url="http://example.com", parameters=params) <add> <add> signature_method = oauth.SignatureMethod_PLAINTEXT() <add> req.sign_request(signature_method, self.consumer, self.token) <add> return dict(req) <add> <add> def test_post_form_passing_oauth(self): <add> """Ensure POSTing form over OAuth with correct credentials passes and does not require CSRF""" <add> auth = self._create_authorization_header() <add> response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 200) <add> <add> def test_post_form_repeated_nonce_failing_oauth(self): <add> """Ensure POSTing form over OAuth with repeated auth (same nonces and timestamp) credentials fails""" <add> auth = self._create_authorization_header() <add> response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 200) <add> <add> # simulate reply attack auth header containes already used (nonce, timestamp) pair <add> response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) <add> self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)) <add> <add> def test_post_form_token_removed_failing_oauth(self): <add> """Ensure POSTing when there is no OAuth access token in db fails""" <add> self.token.delete() <add> auth = self._create_authorization_header() <add> response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) <add> self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)) <add> <add> def test_post_form_consumer_status_not_accepted_failing_oauth(self): <add> """Ensure POSTing when consumer status is anything other than ACCEPTED fails""" <add> for consumer_status in (oauth_consts.CANCELED, oauth_consts.PENDING, oauth_consts.REJECTED): <add> self.consumer.status = consumer_status <add> self.consumer.save() <add> <add> auth = self._create_authorization_header() <add> response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) <add> self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)) <add> <add> def test_post_form_with_request_token_failing_oauth(self): <add> """Ensure POSTing with unauthorized request token instead of access token fails""" <add> self.token.token_type = OAuthToken.REQUEST <add> self.token.save() <add> <add> auth = self._create_authorization_header() <add> response = self.csrf_client.post('/oauth/', {'example': 'example'}, HTTP_AUTHORIZATION=auth) <add> self.assertIn(response.status_code, (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN)) <add> <add> def test_post_form_with_urlencoded_parameters(self): <add> """Ensure POSTing with x-www-form-urlencoded auth parameters passes""" <add> params = self._create_authorization_url_parameters() <add> response = self.csrf_client.post('/oauth/', params) <add> self.assertEqual(response.status_code, 200) <add> <add> def test_get_form_with_url_parameters(self): <add> """Ensure GETing with auth in url parameters passes""" <add> params = self._create_authorization_url_parameters() <add> response = self.csrf_client.get('/oauth/', params) <add> self.assertEqual(response.status_code, 200) <add> <add> def test_post_hmac_sha1_signature_passes(self): <add> """Ensure POSTing using HMAC_SHA1 signature method passes""" <add> params = { <add> 'oauth_version': "1.0", <add> 'oauth_nonce': oauth.generate_nonce(), <add> 'oauth_timestamp': int(time.time()), <add> 'oauth_token': self.token.key, <add> 'oauth_consumer_key': self.consumer.key <add> } <add> <add> req = oauth.Request(method="POST", url="http://testserver/oauth/", parameters=params) <add> <add> signature_method = oauth.SignatureMethod_HMAC_SHA1() <add> req.sign_request(signature_method, self.consumer, self.token) <add> auth = req.to_header()["Authorization"] <add> <add> response = self.csrf_client.post('/oauth/', HTTP_AUTHORIZATION=auth) <add> self.assertEqual(response.status_code, 200) <add>
1
Go
Go
fix bug in deleteneighbor
6afe20096d0dc75a6cfac91dd34dc055a95ddcd1
<ide><path>libnetwork/osl/neigh_linux.go <ide> func (n *networkNamespace) DeleteNeighbor(dstIP net.IP, dstMac net.HardwareAddr, <ide> for i, nh := range n.neighbors { <ide> if nh.dstIP.Equal(dstIP) && bytes.Equal(nh.dstMac, dstMac) { <ide> n.neighbors = append(n.neighbors[:i], n.neighbors[i+1:]...) <add> break <ide> } <ide> } <ide> n.Unlock()
1
Python
Python
add missing right parenthesis
2c408050c127c8155b36ac61e0e3d0e095dd1f1e
<ide><path>weave/ext_tools.py <ide> def build_information(self): <ide> info.append(func.customize) <ide> #redundant, but easiest place to make sure compiler is set <ide> for i in info: <del> i.set_compiler(self.compiler <add> i.set_compiler(self.compiler) <ide> return info <ide> <ide> def get_headers(self):
1
Text
Text
fix bug in email with name example code
fd984e850050710bfcba45c641757bce24072e12
<ide><path>guides/source/action_mailer_basics.md <ide> email address in the format `"Full Name <email>"`. <ide> ```ruby <ide> def welcome_email(user) <ide> @user = user <del> email_with_name = "#{@user.name} <#{@user.email}>" <add> email_with_name = %("#{@user.name}" <#{@user.email}>) <ide> mail(to: email_with_name, subject: 'Welcome to My Awesome Site') <ide> end <ide> ```
1
Python
Python
replace assertions with valueerror exceptions
3187228206cce052c5df0a8643fe85d2fd50e6a0
<ide><path>src/transformers/generation_utils.py <ide> def _expand_inputs_for_generation( <ide> model_kwargs["attention_mask"] = attention_mask.index_select(0, expanded_return_idx) <ide> <ide> if is_encoder_decoder: <del> assert encoder_outputs is not None <add> if encoder_outputs is None: <add> raise ValueError("If `is_encoder_decoder` is True, make sure that `encoder_outputs` is defined.") <ide> encoder_outputs["last_hidden_state"] = encoder_outputs.last_hidden_state.index_select( <ide> 0, expanded_return_idx.to(encoder_outputs.last_hidden_state.device) <ide> ) <ide> def greedy_search( <ide> <ide> # finished sentences should have their next token be a padding token <ide> if eos_token_id is not None: <del> assert pad_token_id is not None, "If eos_token_id is defined, make sure that pad_token_id is defined." <add> if pad_token_id is None: <add> raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.") <ide> next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences) <ide> <ide> # update generated ids, model inputs, and length for next step <ide> def sample( <ide> <ide> # finished sentences should have their next token be a padding token <ide> if eos_token_id is not None: <del> assert pad_token_id is not None, "If eos_token_id is defined, make sure that pad_token_id is defined." <add> if pad_token_id is None: <add> raise ValueError("If `eos_token_id` is defined, make sure that `pad_token_id` is defined.") <ide> next_tokens = next_tokens * unfinished_sequences + pad_token_id * (1 - unfinished_sequences) <ide> <ide> # update generated ids, model inputs, and length for next step <ide> def beam_search( <ide> <ide> batch_beam_size, cur_len = input_ids.shape <ide> <del> assert ( <del> num_beams * batch_size == batch_beam_size <del> ), f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}." <add> if num_beams * batch_size != batch_beam_size: <add> raise ValueError( <add> f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}." <add> ) <ide> <ide> beam_scores = torch.zeros((batch_size, num_beams), dtype=torch.float, device=input_ids.device) <ide> beam_scores[:, 1:] = -1e9 <ide> def group_beam_search( <ide> <ide> batch_beam_size, cur_len = input_ids.shape <ide> <del> assert ( <del> num_beams * batch_size == batch_beam_size <del> ), f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}." <add> if num_beams * batch_size != batch_beam_size: <add> raise ValueError( <add> f"Batch dimension of `input_ids` should be {num_beams * batch_size}, but is {batch_beam_size}." <add> ) <ide> <ide> beam_scores = torch.full((batch_size, num_beams), -1e9, dtype=torch.float, device=device) <ide> # initialise score of first beam of each group with 0 and the rest with 1e-9. This ensures that the beams in
1
Python
Python
use entry_points to install the f2py scripts
f22a33b71dc767d81ed60f40c3b84456d2a33f79
<ide><path>numpy/f2py/__main__.py <ide> # See http://cens.ioc.ee/projects/f2py2e/ <ide> from __future__ import division, print_function <ide> <del>import os <del>import sys <del>for mode in ["g3-numpy", "2e-numeric", "2e-numarray", "2e-numpy"]: <del> try: <del> i = sys.argv.index("--" + mode) <del> del sys.argv[i] <del> break <del> except ValueError: <del> pass <del>os.environ["NO_SCIPY_IMPORT"] = "f2py" <del>if mode == "g3-numpy": <del> sys.stderr.write("G3 f2py support is not implemented, yet.\\n") <del> sys.exit(1) <del>elif mode == "2e-numeric": <del> from f2py2e import main <del>elif mode == "2e-numarray": <del> sys.argv.append("-DNUMARRAY") <del> from f2py2e import main <del>elif mode == "2e-numpy": <del> from numpy.f2py import main <del>else: <del> sys.stderr.write("Unknown mode: " + repr(mode) + "\\n") <del> sys.exit(1) <add>from f2py2e import main <add> <ide> main() <ide><path>numpy/f2py/f2py2e.py <ide> def main(): <ide> from numpy.distutils.system_info import show_all <ide> show_all() <ide> return <add> <add> # Probably outdated options that were not working before 1.16 <add> if '--g3-numpy' in sys.argv[1:]: <add> sys.stderr.write("G3 f2py support is not implemented, yet.\\n") <add> sys.exit(1) <add> elif '--2e-numeric' in sys.argv[1:]: <add> sys.argv.remove('--2e-numeric') <add> elif '--2e-numarray' in sys.argv[1:]: <add> # Note that this errors becaust the -DNUMARRAY argument is <add> # not recognized. Just here for back compatibility and the <add> # error message. <add> sys.argv.append("-DNUMARRAY") <add> sys.argv.remove('--2e-numarray') <add> elif '--2e-numpy' in sys.argv[1:]: <add> sys.argv.remove('--2e-numpy') <add> else: <add> pass <add> <ide> if '-c' in sys.argv[1:]: <ide> run_compile() <ide> else: <ide> run_main(sys.argv[1:]) <del> <del># if __name__ == "__main__": <del># main() <del> <del> <del># EOF <ide><path>numpy/f2py/setup.py <ide> """ <ide> from __future__ import division, print_function <ide> <del>__version__ = "$Id: setup.py,v 1.32 2005/01/30 17:22:14 pearu Exp $" <del> <ide> import os <ide> import sys <ide> from distutils.dep_util import newer <ide> from numpy.distutils import log <ide> from numpy.distutils.core import setup <ide> from numpy.distutils.misc_util import Configuration <ide> <del>from __version__ import version <del> <del> <del>def _get_f2py_shebang(): <del> """ Return shebang line for f2py script <ide> <del> If we are building a binary distribution format, then the shebang line <del> should be ``#!python`` rather than ``#!`` followed by the contents of <del> ``sys.executable``. <del> """ <del> if set(('bdist_wheel', 'bdist_egg', 'bdist_wininst', <del> 'bdist_rpm')).intersection(sys.argv): <del> return '#!python' <del> return '#!' + sys.executable <add>from __version__ import version <ide> <ide> <ide> def configuration(parent_package='', top_path=None): <ide> config = Configuration('f2py', parent_package, top_path) <del> <ide> config.add_data_dir('tests') <del> <del> config.add_data_files('src/fortranobject.c', <del> 'src/fortranobject.h', <del> ) <del> <del> config.make_svn_version_py() <del> <del> def generate_f2py_py(build_dir): <del> f2py_exe = 'f2py' + os.path.basename(sys.executable)[6:] <del> if f2py_exe[-4:] == '.exe': <del> f2py_exe = f2py_exe[:-4] + '.py' <del> if 'bdist_wininst' in sys.argv and f2py_exe[-3:] != '.py': <del> f2py_exe = f2py_exe + '.py' <del> target = os.path.join(build_dir, f2py_exe) <del> if newer(__file__, target): <del> log.info('Creating %s', target) <del> f = open(target, 'w') <del> f.write(_get_f2py_shebang() + '\n') <del> mainloc = os.path.join(os.path.dirname(__file__), "__main__.py") <del> with open(mainloc) as mf: <del> f.write(mf.read()) <del> f.close() <del> return target <del> <del> config.add_scripts(generate_f2py_py) <del> <del> log.info('F2PY Version %s', config.get_version()) <del> <add> config.add_data_files( <add> 'src/fortranobject.c', <add> 'src/fortranobject.h') <ide> return config <ide> <add> <ide> if __name__ == "__main__": <ide> <ide> config = configuration(top_path='') <del> print('F2PY Version', version) <ide> config = config.todict() <ide> <ide> config['download_url'] = "http://cens.ioc.ee/projects/f2py2e/2.x"\ <ide><path>numpy/tests/test_scripts.py <ide> def run_command(cmd, check_code=True): <ide> @pytest.mark.skipif(is_inplace, reason="Cannot test f2py command inplace") <ide> def test_f2py(): <ide> # test that we can run f2py script <add> <add> def try_f2py_commands(cmds): <add> success = 0 <add> for f2py_cmd in cmds: <add> try: <add> code, stdout, stderr = run_command([f2py_cmd, '-v']) <add> assert_equal(stdout.strip(), b'2') <add> success += 1 <add> except Exception: <add> pass <add> return success <add> <ide> if sys.platform == 'win32': <add> # Only the single 'f2py' script is installed in windows. <ide> exe_dir = dirname(sys.executable) <del> <ide> if exe_dir.endswith('Scripts'): # virtualenv <del> f2py_cmd = r"%s\f2py.py" % exe_dir <add> f2py_cmds = [os.path.join(exe_dir, 'f2py')] <ide> else: <del> f2py_cmd = r"%s\Scripts\f2py.py" % exe_dir <del> <del> code, stdout, stderr = run_command([sys.executable, f2py_cmd, '-v']) <del> success = stdout.strip() == b'2' <del> assert_(success, "Warning: f2py not found in path") <add> f2py_cmds = [os.path.join(exe_dir, "Scripts", 'f2py')] <add> success = try_f2py_commands(f2py_cmds) <add> msg = "Warning: f2py not found in path" <add> assert_(success == 1, msg) <ide> else: <add> # Three scripts are installed in Unix-like systems: <add> # 'f2py', 'f2py{major}', and 'f2py{major.minor}'. For example, <add> # if installed with python3.7 the scripts would be named <add> # 'f2py', 'f2py3', and 'f2py3.7'. <ide> version = sys.version_info <ide> major = str(version.major) <ide> minor = str(version.minor) <del> <ide> f2py_cmds = ('f2py', 'f2py' + major, 'f2py' + major + '.' + minor) <del> success = False <del> <del> for f2py_cmd in f2py_cmds: <del> try: <del> code, stdout, stderr = run_command([f2py_cmd, '-v']) <del> assert_equal(stdout.strip(), b'2') <del> success = True <del> break <del> except Exception: <del> pass <del> msg = "Warning: neither %s nor %s nor %s found in path" % f2py_cmds <del> assert_(success, msg) <add> success = try_f2py_commands(f2py_cmds) <add> msg = "Warning: not all of %s, %s, and %s are found in path" % f2py_cmds <add> assert_(success == 3, msg) <ide><path>setup.py <ide> def setup_package(): <ide> # Rewrite the version file everytime <ide> write_version_py() <ide> <add> # The f2py scripts that will be installed <add> if sys.platform == 'win32': <add> f2py_cmds = [ <add> 'f2py = numpy.f2py.f2py2e:main', <add> ] <add> else: <add> f2py_cmds = [ <add> 'f2py = numpy.f2py.f2py2e:main', <add> 'f2py%s = numpy.f2py.f2py2e:main' % sys.version_info[:1], <add> 'f2py%s.%s = numpy.f2py.f2py2e:main' % sys.version_info[:2], <add> ] <add> <ide> metadata = dict( <ide> name = 'numpy', <ide> maintainer = "NumPy Developers", <ide> def setup_package(): <ide> cmdclass={"sdist": sdist_checked}, <ide> python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*', <ide> zip_safe=False, <add> entry_points={ <add> 'console_scripts': f2py_cmds <add> }, <ide> ) <ide> <ide> if "--force" in sys.argv:
5
Javascript
Javascript
improve landing page
b5c1775beb489653d06845480fd1f24d744a1c78
<ide><path>website/src/react-native/_index.js <ide> module.exports = React.createClass({ <ide> });`} <ide> </Prism> <ide> <del> <h2>Asynchronous</h2> <add> <h2>Asynchronous Execution</h2> <ide> <p> <del> All operations between the JavaScript application code and the native platform are performed asynchronously, and the native modules can also make use of additional threads as well. This means we can decode images off of the main thread, save to disk in the background, measure text and compute layouts without blocking the UI, and more. As a result, React Native apps are naturally fluid and responsive. The communication is also fully serializable, which allows us to leverage Chrome Developer Tools to debug JS while running the app in the full app environment, in the sim or on a real device. <add> All operations between the JavaScript application code and the native platform are performed asynchronously, and the native modules can also make use of additional threads as well. This means we can decode images off of the main thread, save to disk in the background, measure text and compute layouts without blocking the UI, and more. As a result, React Native apps are naturally fluid and responsive. The communication is also fully serializable, which allows us to leverage Chrome Developer Tools to debug the JavaScript while running the complete app, either in the simulator or on a physical device. <ide> </p> <ide> <img src="/react-native/img/chrome_breakpoint.png" width="800" height="606" /> <del> <h2>Touch Handling</h2> <ide> <add> <h2>Touch Handling</h2> <ide> <p> <del> iOS has a very powerful system called the Responder Chain to negotiate touches in complex view hierarchies which does not have a universal analog on the web. React Native implements a similar responder system and provides high level components such as TouchableHighlight that integrate properly with scroll views and other elements without any additional configutation. <add> iOS has a very powerful system called the Responder Chain to negotiate touches in complex view hierarchies which does not have a universal analog on the web. React Native implements a similar responder system and provides high level components such as TouchableHighlight that integrate properly with scroll views and other elements without any additional configuration. <ide> </p> <ide> <Prism> <ide> {`var React = require('react-native'); <ide> module.exports = React.createClass({ <ide> <ide> <h2>Flexbox and Styling</h2> <ide> <p> <del> Laying out views should be easy, which is why we brought the flexbox layout model from the web to React Native. Flexbox makes it easy to build the most common UI layouts, such as stacked and nested boxes with margin and padding. React Native also supports common web syles, such as fontWeight, and the StyleSheet abstraction makes it easy to declare all your styles and layout right along with the components that use them and used inline. <add> Laying out views should be easy, which is why we brought the flexbox layout model from the web to React Native. Flexbox makes it simple to build the most common UI layouts, such as stacked and nested boxes with margin and padding. React Native also supports common web syles, such as fontWeight, and the StyleSheet abstraction provides an optimized mechanism to declare all your styles and layout right along with the components that use them and apply them inline. <ide> </p> <ide> <Prism> <ide> {`var React = require('react-native'); <ide> var styles = StyleSheet.create({ <ide> <ide> <h2>Polyfills</h2> <ide> <p> <del> React Native is focused on changing the way view code is written. For the rest, we look to the web for universal standards and polyfill those APIs where appropriate. You can use npm to install JavaScript libraries that work on top of the functionality baked into React Native, such as XMLHttpRequest, requestAnimationFrame, and navigator.geolocation. We are working on expanding the available APIs, and are excited for the Open Source community to contribute as well. <add> React Native is focused on changing the way view code is written. For the rest, we look to the web for universal standards and polyfill those APIs where appropriate. You can use npm to install JavaScript libraries that work on top of the functionality baked into React Native, such as XMLHttpRequest, window.requestAnimationFrame, and navigator.geolocation. We are working on expanding the available APIs, and are excited for the Open Source community to contribute as well. <ide> </p> <ide> <Prism> <ide> {`var React = require('react-native'); <ide> var { Text } = React; <ide> module.exports = React.createClass({ <ide> getInitialState: function() { <del> return { <del> position: 'unknown', <del> }; <add> return { position: 'unknown' }; <ide> }, <ide> componentDidMount: function() { <ide> navigator.geolocation.getCurrentPosition( <ide> module.exports = React.createClass({ <ide> });`} <ide> </Prism> <ide> <add> <h2>Extensibility</h2> <add> <p> <add> It is certainly possible to create a great app using React Native without writing a single line of native code, but React Native is also designed to be easily expended with custom native views and modules - that means you can reuse anything you{"'"}ve already built, and can import and use your favorite native libraries. To create a simple module in iOS, create a new class that implements the RCTBridgeModule protocol, and add RCT_EXPORT to the function you want to make available in JavaScript. <add> </p> <add> <Prism> <add>{`// Objective-C <add> <add>#import "RCTBridgeModule.h" <add> <add>@interface MyCustomModule : NSObject <RCTBridgeModule> <add>@end <add> <add>@implementation MyCustomModule <add> <add>- (void)processString:(NSString *)input callback:(RCTResponseSenderBlock)callback <add>{ <add> RCT_EXPORT(); // available as NativeModules.MyCustomModule.processString <add> callback(@[[input stringByReplacingOccurrencesOfString:@"Goodbye" withString:@"Hello"];]]); <add>} <add>@end`} <add> </Prism> <add> <Prism> <add>{`// JavaScript <add> <add>var React = require('react-native'); <add>var { NativeModules, Text } = React; <add> <add>var Message = React.createClass({ <add> render: function() { <add> getInitialState() { <add> return { text: 'Goodbye World.' }; <add> }, <add> componentDidMount() { <add> NativeModules.MyCustomModule.processString(this.state.text, (text) => { <add> this.setState({text}); <add> }); <add> }, <add> return ( <add> <Text>{this.state.text}</Text> <add> ); <add> }, <add>});`} <add> </Prism> <add> <p> <add> Custom iOS views can be exposed by subclassing RCTViewManager, implementing a -(UIView *)view method, and exporting properties with the RCT_EXPORT_VIEW_PROPERTY macro. Then a simple JavaScript file connects the dots. <add> </p> <add> <Prism> <add>{`// Objective-C <add> <add>#import "RCTViewManager.h" <add> <add>@interface MyCustomViewManager : RCTViewManager <add>@end <add> <add>@implementation MyCustomViewManager <add> <add>- (UIView *)view <add>{ <add> return [[MyCustomView alloc] init]; <add>} <add> <add>RCT_EXPORT_VIEW_PROPERTY(myCustomProperty); <add>@end`} <add> </Prism> <add> <Prism> <add>{`// JavaScript <add> <add>module.exports = createReactIOSNativeComponentClass({ <add> validAttributes: { myCustomProperty: true }, <add> uiViewClassName: 'MyCustomView', <add>});`} <add> </Prism> <ide> </div> <ide> <section className="home-bottom-section"> <ide> <div className="buttons-unit">
1
Python
Python
clarify dropout and seed in tok2vec
709fc5e4ade928a779df3db787056e8e80ed4a57
<ide><path>spacy/ml/models/tok2vec.py <ide> def build_Tok2Vec_model( <ide> cols = [ID, NORM, PREFIX, SUFFIX, SHAPE, ORTH] <ide> with Model.define_operators({">>": chain, "|": concatenate, "**": clone}): <ide> norm = HashEmbed( <del> nO=width, nV=embed_size, column=cols.index(NORM), dropout=dropout, <add> nO=width, nV=embed_size, column=cols.index(NORM), dropout=None, <ide> seed=0 <ide> ) <ide> if subword_features: <ide> prefix = HashEmbed( <del> nO=width, nV=embed_size // 2, column=cols.index(PREFIX), dropout=dropout, <add> nO=width, nV=embed_size // 2, column=cols.index(PREFIX), dropout=None, <ide> seed=1 <ide> ) <ide> suffix = HashEmbed( <del> nO=width, nV=embed_size // 2, column=cols.index(SUFFIX), dropout=dropout, <add> nO=width, nV=embed_size // 2, column=cols.index(SUFFIX), dropout=None, <ide> seed=2 <ide> ) <ide> shape = HashEmbed( <del> nO=width, nV=embed_size // 2, column=cols.index(SHAPE), dropout=dropout, <add> nO=width, nV=embed_size // 2, column=cols.index(SHAPE), dropout=None, <ide> seed=3 <ide> ) <ide> else: <ide> def build_Tok2Vec_model( <ide> >> Maxout( <ide> nO=width, <ide> nI=width * columns, <del> nP=maxout_pieces, <add> nP=3, <ide> dropout=0.0, <ide> normalize=True, <ide> ), <ide> def build_Tok2Vec_model( <ide> >> Maxout( <ide> nO=width, <ide> nI=width * columns, <del> nP=maxout_pieces, <add> nP=3, <ide> dropout=0.0, <ide> normalize=True, <ide> ), <ide> def build_Tok2Vec_model( <ide> >> Maxout( <ide> nO=width, <ide> nI=width * columns, <del> nP=maxout_pieces, <add> nP=3, <ide> dropout=0.0, <ide> normalize=True, <ide> ), <ide> def build_Tok2Vec_model( <ide> reduce_dimensions = Maxout( <ide> nO=width, <ide> nI=nM * nC + width, <del> nP=maxout_pieces, <add> nP=3, <ide> dropout=0.0, <ide> normalize=True, <ide> )
1
Javascript
Javascript
add linkedin id field to user model
0ced58c9f557aeb64f8452f39a87b95353a66bdc
<ide><path>models/User.js <ide> var userSchema = new mongoose.Schema({ <ide> twitter: { type: String, unique: true, sparse: true }, <ide> google: { type: String, unique: true, sparse: true }, <ide> github: { type: String, unique: true, sparse: true }, <add> linkedin: { type: String, unique: true, sparse: true }, <ide> tokens: Array, <ide> <ide> profile: {
1
PHP
PHP
add coverage for iteractive path setting
a829aed32d50926c16658f3ff6667eabf993d06a
<ide><path>tests/TestCase/Command/I18nExtractCommandTest.php <ide> public function testExecute() <ide> $this->assertRegExp($pattern, $result); <ide> } <ide> <add> /** <add> * testExecute with no paths <add> * <add> * @return void <add> */ <add> public function testExecuteNoPathOption() <add> { <add> $this->exec( <add> 'i18n extract ' . <add> '--merge=no ' . <add> '--extract-core=no ' . <add> '--output=' . $this->path . DS, <add> [ <add> TEST_APP . 'templates' . DS, <add> 'D' <add> ] <add> ); <add> $this->assertExitSuccess(); <add> $this->assertFileExists($this->path . DS . 'default.pot'); <add> } <add> <ide> /** <ide> * testExecute with merging on method <ide> *
1
Javascript
Javascript
add null check to outputlength logic
92ca2c208bf8c1a8abb21df800619b2890f72461
<ide><path>lib/internal/crypto/hash.js <ide> function Hash(algorithm, options) { <ide> if (!(this instanceof Hash)) <ide> return new Hash(algorithm, options); <ide> validateString(algorithm, 'algorithm'); <del> const xofLen = typeof options === 'object' ? options.outputLength : undefined; <add> const xofLen = typeof options === 'object' && options !== null ? <add> options.outputLength : undefined; <ide> if (xofLen !== undefined) <ide> validateUint32(xofLen, 'options.outputLength'); <ide> this[kHandle] = new _Hash(algorithm, xofLen); <ide><path>test/parallel/test-crypto-hash.js <ide> common.expectsError( <ide> // Default outputLengths. <ide> assert.strictEqual(crypto.createHash('shake128').digest('hex'), <ide> '7f9c2ba4e88f827d616045507605853e'); <add> assert.strictEqual(crypto.createHash('shake128', null).digest('hex'), <add> '7f9c2ba4e88f827d616045507605853e'); <ide> assert.strictEqual(crypto.createHash('shake256').digest('hex'), <ide> '46b9dd2b0ba88d13233b3feb743eeb24' + <ide> '3fcd52ea62b81b82b50c27646ed5762f');
2
PHP
PHP
reset default debugger output format
124248a2f20644c11e589104e03d345753ca52a9
<ide><path>tests/TestCase/Error/DebuggerTest.php <ide> public function testAddFormatCallback() <ide> $result = ob_get_clean(); <ide> $this->assertStringContainsString('Notice: I eated an error', $result); <ide> $this->assertStringContainsString('DebuggerTest.php', $result); <add> <add> Debugger::setOutputFormat('js'); <ide> } <ide> <ide> /**
1
PHP
PHP
use array values
351e3b7694a804e8d6a613288419ccabd22bc012
<ide><path>src/Illuminate/Queue/SerializesModels.php <ide> public function __sleep() <ide> )); <ide> } <ide> <del> return array_filter(array_map(function ($p) { <add> return array_values(array_filter(array_map(function ($p) { <ide> return $p->isStatic() ? null : $p->getName(); <del> }, $properties)); <add> }, $properties))); <ide> } <ide> <ide> /**
1
Ruby
Ruby
accept both regexps and strings for localhost
68b4720fd18796f337000f37bf57af905b0370a7
<ide><path>actionpack/lib/action_dispatch/middleware/show_exceptions.rb <ide> module ActionDispatch <ide> # This middleware rescues any exception returned by the application and renders <ide> # nice exception pages if it's being rescued locally. <ide> class ShowExceptions <del> LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/].freeze <add> LOCALHOST = [/^127\.0\.0\.\d{1,3}$/, "::1", /^0:0:0:0:0:0:0:1(%.*)?$/].freeze <ide> <ide> RESCUES_TEMPLATE_PATH = File.join(File.dirname(__FILE__), 'templates') <ide> <ide> def rescue_action_in_public(exception) <ide> <ide> # True if the request came from localhost, 127.0.0.1. <ide> def local_request?(request) <del> LOCALHOST.any?{ |local_ip| request.remote_addr =~ local_ip && request.remote_ip =~ local_ip } <add> LOCALHOST.any? { |local_ip| local_ip === request.remote_addr && local_ip === request.remote_ip } <ide> end <ide> <ide> def status_code(exception)
1
Ruby
Ruby
use homebrew curl based on root domain
2f0a53c0daf1ee1f3039ab32213916d22ff7e277
<ide><path>Library/Homebrew/livecheck/livecheck.rb <ide> require "livecheck/livecheck_version" <ide> require "livecheck/skip_conditions" <ide> require "livecheck/strategy" <add>require "addressable" <ide> require "ruby-progressbar" <ide> require "uri" <ide> <ide> def preprocess_url(url) <ide> url <ide> end <ide> <del> # Fetch with brewed curl if using the download or homepage URL <del> # and the download URL specifies `using: :homebrew_curl`. <add> # livecheck should fetch a URL using brewed curl if the formula/cask <add> # contains a `stable`/`url` or `head` URL `using: :homebrew_curl` that <add> # shares the same root domain. <ide> sig { params(formula_or_cask: T.any(Formula, Cask::Cask), url: String).returns(T::Boolean) } <ide> def use_homebrew_curl?(formula_or_cask, url) <del> if checkable_urls(formula_or_cask).include?(url) <del> case formula_or_cask <del> when Formula <del> [:stable, :head].any? do |spec_name| <del> next false unless (spec = formula_or_cask.send(spec_name)) <add> url_root_domain = Addressable::URI.parse(url)&.domain <add> return false if url_root_domain.blank? <ide> <del> spec.using == :homebrew_curl <del> end <del> when Cask::Cask <del> formula_or_cask.url.using == :homebrew_curl <del> else <del> T.absurd(formula_or_cask) <add> # Collect root domains of URLs with `using: :homebrew_curl` <add> homebrew_curl_root_domains = [] <add> case formula_or_cask <add> when Formula <add> [:stable, :head].each do |spec_name| <add> next unless (spec = formula_or_cask.send(spec_name)) <add> next unless spec.using == :homebrew_curl <add> <add> domain = Addressable::URI.parse(spec.url)&.domain <add> homebrew_curl_root_domains << domain if domain.present? <ide> end <del> else <del> false <add> when Cask::Cask <add> return false unless formula_or_cask.url.using == :homebrew_curl <add> <add> domain = Addressable::URI.parse(formula_or_cask.url.to_s)&.domain <add> homebrew_curl_root_domains << domain if domain.present? <ide> end <add> <add> homebrew_curl_root_domains.include?(url_root_domain) <ide> end <ide> <ide> # Identifies the latest version of the formula and returns a Hash containing <ide> def latest_version( <ide> when "PageMatch", "HeaderMatch" <ide> use_homebrew_curl?((referenced_formula_or_cask || formula_or_cask), url) <ide> end <add> puts "Homebrew curl?: Yes" if debug && homebrew_curl.present? <ide> <ide> strategy_data = strategy.find_versions( <ide> url: url, <ide> def latest_version( <ide> version_info[:meta][:url][:strategy] = strategy_data[:url] <ide> end <ide> version_info[:meta][:url][:final] = strategy_data[:final_url] if strategy_data[:final_url] <add> version_info[:meta][:url][:homebrew_curl] = homebrew_curl if homebrew_curl.present? <ide> <ide> version_info[:meta][:strategy] = strategy.present? ? strategy_name : nil <ide> version_info[:meta][:strategies] = strategies.map { |s| livecheck_strategy_names[s] } if strategies.present? <ide><path>Library/Homebrew/test/livecheck/livecheck_spec.rb <ide> formula("test") do <ide> desc "Test formula" <ide> homepage "https://brew.sh" <del> url "https://brew.sh/test-0.0.1.tgz", using: :homebrew_curl <add> url "https://brew.sh/test-0.0.1.tgz" <ide> head "https://github.com/Homebrew/brew.git" <ide> <ide> livecheck do <ide> cask "test" do <ide> version "0.0.1,2" <ide> <del> url "https://brew.sh/test-0.0.1.dmg", using: :homebrew_curl <add> url "https://brew.sh/test-0.0.1.dmg" <ide> name "Test" <ide> desc "Test cask" <ide> homepage "https://brew.sh" <ide> end <ide> <ide> describe "::use_homebrew_curl?" do <del> it "uses brewed curl if called for by the download URL" do <add> let(:example_url) { "https://www.example.com/test-0.0.1.tgz" } <add> <add> let(:f_homebrew_curl) do <add> formula("test") do <add> desc "Test formula" <add> homepage "https://brew.sh" <add> url "https://brew.sh/test-0.0.1.tgz", using: :homebrew_curl <add> # head is deliberably omitted to exercise more of the method <add> <add> livecheck do <add> url "https://formulae.brew.sh/api/formula/ruby.json" <add> regex(/"stable":"(\d+(?:\.\d+)+)"/i) <add> end <add> end <add> end <add> <add> let(:c_homebrew_curl) do <add> Cask::CaskLoader.load(+<<-RUBY) <add> cask "test" do <add> version "0.0.1,2" <add> <add> url "https://brew.sh/test-0.0.1.dmg", using: :homebrew_curl <add> name "Test" <add> desc "Test cask" <add> homepage "https://brew.sh" <add> <add> livecheck do <add> url "https://formulae.brew.sh/api/formula/ruby.json" <add> regex(/"stable":"(\d+(?:\.\d+)+)"/i) <add> end <add> end <add> RUBY <add> end <add> <add> it "returns `true` when URL matches a `using: :homebrew_curl` URL" do <add> expect(livecheck.use_homebrew_curl?(f_homebrew_curl, livecheck_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(f_homebrew_curl, homepage_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(f_homebrew_curl, stable_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(c_homebrew_curl, livecheck_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(c_homebrew_curl, homepage_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(c_homebrew_curl, cask_url)).to be(true) <add> end <add> <add> it "returns `false` if URL root domain differs from `using: :homebrew_curl` URLs" do <add> expect(livecheck.use_homebrew_curl?(f_homebrew_curl, example_url)).to be(false) <add> expect(livecheck.use_homebrew_curl?(c_homebrew_curl, example_url)).to be(false) <add> end <add> <add> it "returns `false` if a `using: homebrew_curl` URL is not present" do <ide> expect(livecheck.use_homebrew_curl?(f, livecheck_url)).to be(false) <del> expect(livecheck.use_homebrew_curl?(f, homepage_url)).to be(true) <del> expect(livecheck.use_homebrew_curl?(f, stable_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(f, homepage_url)).to be(false) <add> expect(livecheck.use_homebrew_curl?(f, stable_url)).to be(false) <add> expect(livecheck.use_homebrew_curl?(f, example_url)).to be(false) <ide> expect(livecheck.use_homebrew_curl?(c, livecheck_url)).to be(false) <del> expect(livecheck.use_homebrew_curl?(c, homepage_url)).to be(true) <del> expect(livecheck.use_homebrew_curl?(c, cask_url)).to be(true) <add> expect(livecheck.use_homebrew_curl?(c, homepage_url)).to be(false) <add> expect(livecheck.use_homebrew_curl?(c, cask_url)).to be(false) <add> expect(livecheck.use_homebrew_curl?(c, example_url)).to be(false) <add> end <add> <add> it "returns `false` if URL string does not contain a domain" do <add> expect(livecheck.use_homebrew_curl?(f_homebrew_curl, "test")).to be(false) <ide> end <ide> end <ide>
2